Skip to content

Commit

Permalink
Search categories for candidates in the correct order
Browse files Browse the repository at this point in the history
This prevents a situation when two categories (A and B) have the same
image, category A is (according to sortkey order) more important,
but it gets no recommendation, because this image got assigned to B.

After this change, categories are searched in their sortkey order,
so category A will always get this filename before category B.
  • Loading branch information
edwardspec committed Sep 20, 2024
1 parent 7877172 commit 4a4e8d3
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions includes/Hooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,6 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) {
}

// Randomly choose up to $wgRelatedImagesMaxImagesPerCategory titles (not equal to $title) from $categoryNames.
$filenamesPerCategory = []; # [ 'Category_name' => [ 'filename', ... ], ... ]
$seenFilenames = [];

$res = $dbr->newSelectQueryBuilder()
->select( [
'page_title AS filename',
Expand All @@ -154,6 +151,11 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) {
->caller( __METHOD__ )
->fetchResultSet();

// List of candidates to recommend (in the same order as $categoryNames):
// [ 'Category_name' => [ 'filename', ... ], ... ]
$filenamesPerCategory = array_fill_keys( $categoryNames, [] );
$seenFilenames = [];

foreach ( $res as $row ) {
if ( isset( $seenFilenames[$row->filename] ) ) {
// Already recommended in another category.
Expand All @@ -168,20 +170,15 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) {
continue;
}

if ( !isset( $filenamesPerCategory[$row->category] ) ) {
$filenamesPerCategory[$row->category] = [];
}

if ( count( $filenamesPerCategory[$row->category] ) < $wgRelatedImagesMaxImagesPerCategory ) {
$filenamesPerCategory[$row->category][] = $row->filename;
}
}

$logger = LoggerFactory::getInstance( 'RelatedImages' );
$logger->debug( 'RelatedImages: file={file}, categoryOrder={categoryOrder}, filenamesPerCategory: {candidates}',
$logger->debug( 'RelatedImages: file={file}, filenamesPerCategory: {candidates}',
[
'file' => $title->getFullText(),
'categoryOrder' => implode( '|', $categoryNames ),
'file' => $title->getDBKey(),
'candidates' => FormatJson::encode( $filenamesPerCategory )
]
);
Expand All @@ -195,8 +192,7 @@ public function onImagePageAfterImageLinks( $imagePage, &$html ) {
$thumbsize = $this->getThumbnailSize();

$numCategoriesCount = 0;
foreach ( $categoryNames as $category ) {
$filenames = $filenamesPerCategory[$category] ?? [];
foreach ( $filenamesPerCategory as $category => $filenames ) {
if ( !$filenames ) {
continue;
}
Expand Down

0 comments on commit 4a4e8d3

Please sign in to comment.