fix(igdb): let region_mode decide the localized title (#5785)

* fix(igdb): let region_mode decide the localized title

get_igdb_preferred_locale ignored scan.priority.region_mode, so a rom
tagged (Japan) always got IGDB's ja-JP localized title, even with
prefer_config and us first in scan.priority.region. Under prefer_config
the configured regions now come first and the rom's own tags are the
fallback, matching the ScreenScraper handler since #4413. The default
prefer_rom_tags ordering is unchanged.

Fixes #5784

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(igdb): fold the region_mode note into one docstring sentence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Log a missing IGDB locale at debug: under prefer_config every ROM asks
for the first config locale, so a missing one is routine, not a warning.
Pin SCAN_REGION_MODE in the multi-region locale test instead of relying
on MagicMock's auto attribute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Drop the IGDB-locale filter on the ROM's region codes; the final
lookup loop already skips codes IGDB has no locale for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Spell out the USA region in the prefer_config test docstring so it
does not read as the pronoun, untangle the fallback test docstring, and
finish the clipped Returns line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(metadata): share one region order across IGDB, ScreenScraper and LaunchBox

IGDB now tries every preferred locale in order, up to the first region
that uses the default title, instead of only the first. Under
prefer_config with [eu, jp], a (Japan) ROM whose game has no EU
localization gets the Japanese title again rather than the default.

preferred_region_codes in the filesystem base handler builds the region
order once. ScreenScraper, IGDB and LaunchBox all read it, so LaunchBox
artwork follows region_mode too, and uppercase config codes match the
ROM's tags for every provider.

European country codes map to IGDB's EU locale and ScreenScraper's ss
to the default title, so a (France) ROM no longer falls through to the
next configured region.

An unquoted no (Norway, Norwegian) in scan.priority.region or
scan.priority.language loads as false from YAML and crashed every IGDB
match. The config loader now turns it back into "no" and drops other
non-string entries with a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(igdb): drop _string_codes and spell out the EU region codes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
This commit is contained in:
Matt Kaatman
2026-11-26 19:11:48 -06:00
committed by GitHub
parent 4477c87376
commit d8d9fa7884
8 changed files with 232 additions and 124 deletions

View File

@@ -177,6 +177,35 @@ def region_name_to_provider_shortcode(region_name: str | None) -> str | None:
return _REGION_NAME_TO_PROVIDER_SHORTCODE_CI.get(region_name.lower())
def preferred_region_codes(region_names: Iterable[str] | None) -> list[str]:
"""Provider region shortcodes in the order scan.priority.region_mode prefers.
Args:
region_names: The ROM's region tags; the configured priority ranks them.
Returns:
Deduplicated lowercase shortcodes. "prefer_config" puts the configured
list first, and "prefer_rom_tags" puts the ROM's tags first.
"""
config = cm.get_config()
priority = [code.lower() for code in config.SCAN_REGION_PRIORITY]
rom_codes = list(
dict.fromkeys(
code
for name in region_names or ()
if (code := region_name_to_provider_shortcode(name))
)
)
rom_codes.sort(
key=lambda code: priority.index(code) if code in priority else len(priority)
)
if config.SCAN_REGION_MODE == "prefer_config":
return list(dict.fromkeys(priority + rom_codes))
return list(dict.fromkeys(rom_codes + priority))
# Reverse of REGION_NAME_TO_PROVIDER_SHORTCODE. A list per code because two
# names can claim one code ("nl" for both Holland and Netherlands), and a rom
# tagged with either has to rank the same.

View File

@@ -16,13 +16,13 @@ from adapters.services.igdb import (
)
from adapters.services.igdb_types import (
Game,
GameLocalization,
GameType,
mark_expanded,
mark_list_expanded,
)
from config import IGDB_CLIENT_ID, IGDB_CLIENT_SECRET, IS_PYTEST_RUN
from config.config_manager import config_manager as cm
from handler.filesystem.base_handler import region_name_to_provider_shortcode
from handler.filesystem.base_handler import preferred_region_codes
from handler.redis_handler import async_cache
from logger.logger import log
from models.rom import Rom
@@ -415,7 +415,26 @@ def derive_player_count(
REGION_TO_IGDB_LOCALE: dict[str, str | None] = {
"us": None, # United States - use default (no localization needed)
"wor": None, # World - use default
"ss": None, # ScreenScraper's world region - use default
"eu": "EU", # Europe region
# European countries, which IGDB only localizes as a continent
"bg": "EU",
"cz": "EU",
"de": "EU",
"dk": "EU",
"fi": "EU",
"fr": "EU",
"gr": "EU",
"hu": "EU",
"it": "EU",
"nl": "EU",
"no": "EU",
"pl": "EU",
"pt": "EU",
"se": "EU",
"sk": "EU",
"sp": "EU",
"uk": "EU",
"jp": "ja-JP", # Japan
"kr": "ko-KR", # Korea
"cn": "zh-CN", # China (Simplified Chinese)
@@ -423,53 +442,40 @@ REGION_TO_IGDB_LOCALE: dict[str, str | None] = {
}
def get_igdb_preferred_locale(rom: Rom | None = None) -> str | None:
"""Get IGDB locale from the ROM's prioritized regions when available.
Maps region priority codes to IGDB's game_localizations region identifiers.
Prioritizes the ROM's tagged regions by scan.priority.region, then falls
back to scan.priority.region.
def get_igdb_preferred_locales(rom: Rom | None = None) -> list[str]:
"""Get IGDB locales in preference order, up to the first region using the default.
Returns:
IGDB region identifier (e.g., "ja-JP", "EU") or None for default
IGDB region identifiers (e.g., "ja-JP", "EU"); empty means the default title
"""
config = cm.get_config()
priority = config.SCAN_REGION_PRIORITY
normalized_priority = [region.lower() for region in priority]
rom_regions = (
rom.regions if rom is not None and isinstance(rom.regions, list) else []
)
if rom is not None and isinstance(rom.regions, list):
rom_codes: list[str] = []
for region_name in rom.regions:
code = region_name_to_provider_shortcode(region_name)
if code and code in REGION_TO_IGDB_LOCALE:
rom_codes.append(code)
locales: list[str] = []
for code in preferred_region_codes(rom_regions):
if code not in REGION_TO_IGDB_LOCALE:
continue
locale = REGION_TO_IGDB_LOCALE[code]
if locale is None:
break
if locale not in locales:
locales.append(locale)
rom_codes.sort(
key=lambda code: (
normalized_priority.index(code)
if code in normalized_priority
else len(normalized_priority)
)
)
if rom_codes:
return REGION_TO_IGDB_LOCALE[rom_codes[0]]
for region in priority:
if region.lower() in REGION_TO_IGDB_LOCALE:
return REGION_TO_IGDB_LOCALE[region.lower()]
return None
return locales
def extract_localized_data(rom: Game, preferred_locale: str | None) -> tuple[str, str]:
"""Extract localized name and cover URL based on preferred locale.
def extract_localized_data(
rom: Game, preferred_locales: Sequence[str]
) -> tuple[str, str]:
"""Extract the name and cover URL of the first preferred locale the game has.
Returns (name, cover_url) - falls back to default if locale not found.
Returns (name, cover_url) - falls back to default if no locale is found.
"""
default_name = rom.get("name", "")
default_cover = pydash.get(rom, "cover.url", "")
if not preferred_locale:
if not preferred_locales:
return default_name, default_cover
game_localizations = rom.get("game_localizations", [])
@@ -478,29 +484,36 @@ def extract_localized_data(rom: Game, preferred_locale: str | None) -> tuple[str
assert mark_list_expanded(game_localizations)
# Keyed by region identifier, e.g. "ja-JP", "ko-KR", "EU"
by_locale: dict[str, GameLocalization] = {}
for loc in game_localizations:
region = loc.get("region")
if not region:
continue
assert mark_expanded(region)
identifier = region.get("identifier")
if identifier:
by_locale.setdefault(identifier, loc)
# Match locale by region identifier (e.g., "ja-JP", "ko-KR", "EU")
if region.get("identifier") == preferred_locale:
localized_name = loc.get("name") or default_name
localized_cover = loc.get("cover")
for locale in preferred_locales:
localization = by_locale.get(locale)
if localization is None:
continue
if localized_cover:
assert mark_expanded(localized_cover)
cover_url = localized_cover.get("url", "") or default_cover
else:
cover_url = default_cover
localized_name = localization.get("name") or default_name
localized_cover = localization.get("cover")
return localized_name, cover_url
if localized_cover:
assert mark_expanded(localized_cover)
cover_url = localized_cover.get("url", "") or default_cover
else:
cover_url = default_cover
# Locale not found, fall back to default
log.warning(
f"IGDB locale '{preferred_locale}' not found for '{default_name}', using default"
return localized_name, cover_url
log.debug(
f"IGDB locales {list(preferred_locales)} not found for '{default_name}', using default"
)
return default_name, default_cover
@@ -508,7 +521,7 @@ def extract_localized_data(rom: Game, preferred_locale: str | None) -> tuple[str
def build_igdb_rom(
handler: "IGDBHandler",
rom: Game,
preferred_locale: str | None,
preferred_locales: Sequence[str],
platform_igdb_id: int | None,
) -> "IGDBRom":
"""Build an IGDBRom from IGDB game data with localization support.
@@ -516,7 +529,7 @@ def build_igdb_rom(
Args:
handler: IGDBHandler instance for URL normalization
rom: Game data from IGDB API
preferred_locale: Locale code (e.g., "ja-JP") or None
preferred_locales: Locale codes (e.g., "ja-JP") in preference order
platform_igdb_id: IGDB platform identifier
Returns:
@@ -525,7 +538,7 @@ def build_igdb_rom(
rom_screenshots = rom.get("screenshots", [])
assert mark_list_expanded(rom_screenshots)
localized_name, localized_cover = extract_localized_data(rom, preferred_locale)
localized_name, localized_cover = extract_localized_data(rom, preferred_locales)
return IGDBRom(
igdb_id=rom["id"],
@@ -928,7 +941,7 @@ class IGDBHandler(MetadataHandler):
return fallback_rom
return build_igdb_rom(
self, res, get_igdb_preferred_locale(rom=rom), platform_igdb_id
self, res, get_igdb_preferred_locales(rom=rom), platform_igdb_id
)
async def get_rom_by_id(self, rom: Rom, igdb_id: int) -> IGDBRom:
@@ -943,7 +956,7 @@ class IGDBHandler(MetadataHandler):
if not roms:
return IGDBRom(igdb_id=None)
return build_igdb_rom(self, roms[0], get_igdb_preferred_locale(rom=rom), None)
return build_igdb_rom(self, roms[0], get_igdb_preferred_locales(rom=rom), None)
async def get_matched_rom_by_id(self, rom: Rom, igdb_id: int) -> IGDBRom | None:
if not self.is_enabled():
@@ -1004,9 +1017,9 @@ class IGDBHandler(MetadataHandler):
if rom["id"] not in unique_ids
]
preferred_locale = get_igdb_preferred_locale(rom=rom)
preferred_locales = get_igdb_preferred_locales(rom=rom)
return [
build_igdb_rom(self, rom, preferred_locale, platform_igdb_id)
build_igdb_rom(self, rom, preferred_locales, platform_igdb_id)
for rom in matched_roms
]

View File

@@ -5,7 +5,10 @@ from typing import TYPE_CHECKING, Any, Literal
from config.config_manager import MetadataMediaType
from config.config_manager import config_manager as cm
from handler.filesystem import fs_resource_handler, fs_rom_handler
from handler.filesystem.base_handler import region_name_to_provider_shortcode
from handler.filesystem.base_handler import (
preferred_region_codes,
region_name_to_provider_shortcode,
)
from handler.metadata.ss_handler import get_preferred_media_types
from utils.database import safe_str_to_bool
from utils.html_text import html_to_text
@@ -88,28 +91,16 @@ BOX_ART: tuple[BoxArt, ...] = (
def rom_region_shortcodes(fs_name: str) -> tuple[str, ...]:
"""Provider region shortcodes to prefer for a ROM, most-preferred first.
Combines the regions tagged in the filename (reordered by the user's
SCAN_REGION_PRIORITY) with the configured priority list, so a ROM tagged
"(USA)" prefers its US cover even when another region sorts first.
Under "prefer_rom_tags" a ROM with no known region tag gets none, so the
listing order picks its artwork.
"""
if not fs_name:
region_names = fs_rom_handler.parse_tags(fs_name).regions if fs_name else []
if cm.get_config().SCAN_REGION_MODE != "prefer_config" and not any(
region_name_to_provider_shortcode(name) for name in region_names
):
return ()
priority = cm.get_config().SCAN_REGION_PRIORITY
rom_codes: list[str] = []
for region_name in fs_rom_handler.parse_tags(fs_name).regions:
code = region_name_to_provider_shortcode(region_name)
if code and code not in rom_codes:
rom_codes.append(code)
rom_codes.sort(
key=lambda code: priority.index(code) if code in priority else len(priority)
)
if not rom_codes:
return ()
return tuple(dict.fromkeys(rom_codes + priority))
return tuple(preferred_region_codes(region_names))
# Video container extensions recognized when probing for local LaunchBox media

View File

@@ -35,7 +35,7 @@ from handler.filesystem.base_handler import (
TRANSLATION_TAG,
normalize_provider_languages,
normalize_provider_regions,
region_name_to_provider_shortcode,
preferred_region_codes,
)
from logger.formatter import highlight as hl
from logger.logger import log
@@ -192,38 +192,15 @@ def add_ss_auth_to_url(url: str | None) -> str:
def get_preferred_regions(rom: Rom | None = None) -> list[str]:
"""Get preferred regions, prepending the rom's own region tags when available.
"""Get ScreenScraper regions in preference order, ending with its catch-all regions.
When a rom is tagged with multiple regions (e.g. "(Japan, USA)"), the rom's
own tags are reordered according to the user's SCAN_REGION_PRIORITY so the
user's preference wins among the regions the file is actually tagged as.
Filename-tagged regions not present in the priority list keep their relative
order and follow the prioritized ones.
With SCAN_REGION_MODE set to "prefer_config" the configured priority is
authoritative instead: config regions come first and the rom's own tags
become the fallback. Everything region-selected reads this ordering, so a
game picked up in French comes back with its French artwork, title and
release date rather than a mix.
Everything region-selected reads this ordering, so a game picked up in French
comes back with its French artwork, title and release date rather than a mix.
"""
config = cm.get_config()
priority = config.SCAN_REGION_PRIORITY
rom_codes: list[str] = []
if rom is not None and isinstance(rom.regions, list):
for region_name in rom.regions:
code = region_name_to_provider_shortcode(region_name)
if code:
rom_codes.append(code)
rom_codes.sort(
key=lambda code: priority.index(code) if code in priority else len(priority)
)
if config.SCAN_REGION_MODE == "prefer_config":
ordered = priority + rom_codes
else:
ordered = rom_codes + priority
rom_regions = (
rom.regions if rom is not None and isinstance(rom.regions, list) else []
)
ordered = preferred_region_codes(rom_regions)
return list(dict.fromkeys(ordered + ["us", "wor", "ss", "eu", "jp", "cus"])) + [
"unk"
]

View File

@@ -17,6 +17,7 @@ from handler.filesystem.base_handler import (
normalize_language,
normalize_provider_languages,
normalize_provider_regions,
preferred_region_codes,
provider_language_name,
provider_region_name,
region_ranks_for_priority,
@@ -828,6 +829,39 @@ class TestFSHandlerInit:
mkdir.assert_not_called()
def _region_codes(regions: list[str], priority: list[str], mode: str) -> list[str]:
config = Mock(SCAN_REGION_PRIORITY=priority, SCAN_REGION_MODE=mode)
with patch("handler.filesystem.base_handler.cm.get_config", return_value=config):
return preferred_region_codes(regions)
class TestPreferredRegionCodes:
def test_prefer_rom_tags_puts_the_rom_s_tags_first(self):
assert _region_codes(["Japan"], ["us", "jp"], "prefer_rom_tags") == [
"jp",
"us",
]
def test_prefer_config_puts_the_config_first(self):
assert _region_codes(["Japan", "Brazil"], ["us", "jp"], "prefer_config") == [
"us",
"jp",
"br",
]
def test_the_rom_s_tags_follow_the_configured_order(self):
assert _region_codes(["USA", "Japan"], ["jp", "us"], "prefer_rom_tags") == [
"jp",
"us",
]
def test_uppercase_config_codes_match_the_rom_s_tags(self):
assert _region_codes(["Japan"], ["JP", "US"], "prefer_config") == ["jp", "us"]
def test_no_rom_tags_leaves_the_config(self):
assert _region_codes([], ["eu", "us"], "prefer_rom_tags") == ["eu", "us"]
class TestRegionRanksForPriority:
"""Ranking is per configured shortcode, not per expanded region name."""

View File

@@ -43,7 +43,7 @@ from handler.metadata.igdb_handler import (
derive_player_count,
extract_localized_data,
extract_metadata_from_igdb_rom,
get_igdb_preferred_locale,
get_igdb_preferred_locales,
)
from handler.redis_handler import as_text, async_cache
from utils.arcade_platforms import ARCADE_PLATFORMS
@@ -223,17 +223,48 @@ class TestGetPlatformDuplicateSlugs:
assert handler.get_platform(slug)["family_slug"] == "interton"
class TestGetIGDBPreferredLocale:
def _locales(regions: list[str], priority: list[str], mode: str) -> list[str]:
rom = MagicMock()
rom.regions = regions
config = MagicMock(SCAN_REGION_PRIORITY=priority, SCAN_REGION_MODE=mode)
with patch("handler.filesystem.base_handler.cm.get_config", return_value=config):
return get_igdb_preferred_locales(rom)
class TestGetIGDBPreferredLocales:
def test_multi_region_rom_respects_user_priority(self):
"""The configured priority wins over filename tag order."""
rom = MagicMock()
rom.regions = ["Japan", "USA"]
config = MagicMock(SCAN_REGION_PRIORITY=["JP", "us"])
assert _locales(["Japan", "USA"], ["JP", "us"], "prefer_rom_tags") == ["ja-JP"]
with patch("handler.metadata.igdb_handler.cm.get_config", return_value=config):
locale = get_igdb_preferred_locale(rom)
def test_prefer_rom_tags_keeps_the_rom_s_region(self):
assert _locales(["Japan"], ["us", "jp"], "prefer_rom_tags") == ["ja-JP"]
assert locale == "ja-JP"
def test_prefer_config_outranks_the_rom_s_region(self):
"""A Japan-tagged rom keeps the default title when the config lists USA first."""
assert _locales(["Japan"], ["us", "jp"], "prefer_config") == []
def test_prefer_config_falls_back_to_the_rom_s_region(self):
"""When IGDB has no locale for any config region, the rom's tags decide."""
assert _locales(["Japan"], ["br"], "prefer_config") == ["ja-JP"]
def test_prefer_config_keeps_later_config_regions_as_fallbacks(self):
assert _locales(["Japan"], ["eu", "jp", "us"], "prefer_config") == [
"EU",
"ja-JP",
]
def test_a_european_country_tag_uses_the_eu_locale(self):
assert _locales(["France"], ["jp", "us"], "prefer_rom_tags") == [
"EU",
"ja-JP",
]
def test_screenscraper_world_region_uses_the_default(self):
assert _locales(["Japan"], ["ss", "jp"], "prefer_config") == []
def test_untagged_rom_follows_the_config(self):
assert _locales([], ["kr", "us"], "prefer_rom_tags") == ["ko-KR"]
class TestSearchRomGameTypeFilter:
@@ -1500,29 +1531,41 @@ def _localized_game() -> Game:
class TestExtractLocalizedData:
def test_no_locale_keeps_the_default(self):
assert extract_localized_data(_localized_game(), None) == (
assert extract_localized_data(_localized_game(), []) == (
"Pocket Monsters",
"//images.igdb.com/default.jpg",
)
def test_a_matching_locale_uses_its_name_and_cover(self):
assert extract_localized_data(_localized_game(), "ja-JP") == (
assert extract_localized_data(_localized_game(), ["ja-JP"]) == (
"ポケットモンスター",
"//images.igdb.com/ja.jpg",
)
def test_a_locale_without_its_own_cover_keeps_the_default_cover(self):
assert extract_localized_data(_localized_game(), "EU") == (
assert extract_localized_data(_localized_game(), ["EU"]) == (
"Eu Monsters",
"//images.igdb.com/default.jpg",
)
def test_an_unknown_locale_keeps_the_default(self):
assert extract_localized_data(_localized_game(), "ko-KR") == (
assert extract_localized_data(_localized_game(), ["ko-KR"]) == (
"Pocket Monsters",
"//images.igdb.com/default.jpg",
)
def test_a_missing_locale_falls_through_to_the_next_one(self):
assert extract_localized_data(_localized_game(), ["ko-KR", "ja-JP"]) == (
"ポケットモンスター",
"//images.igdb.com/ja.jpg",
)
def test_the_first_available_locale_wins(self):
assert extract_localized_data(_localized_game(), ["EU", "ja-JP"]) == (
"Eu Monsters",
"//images.igdb.com/default.jpg",
)
class TestGetRom:
async def test_matches_by_name(
@@ -1635,7 +1678,7 @@ class TestAlternativeNames:
],
)
rom = build_igdb_rom(IGDBHandler(), game, None, GENESIS_IGDB_ID)
rom = build_igdb_rom(IGDBHandler(), game, [], GENESIS_IGDB_ID)
assert rom["name"] == "Bleach: The 3rd Phantom"
assert rom["igdb_metadata"]["alternative_names"] == [
@@ -1654,7 +1697,7 @@ class TestAlternativeNames:
)
]
rom = build_igdb_rom(IGDBHandler(), game, "ja-JP", GENESIS_IGDB_ID)
rom = build_igdb_rom(IGDBHandler(), game, ["ja-JP"], GENESIS_IGDB_ID)
assert rom["name"] == "ブリーチ ザ・サード・ファントム"
assert rom["igdb_metadata"]["alternative_names"] == [

View File

@@ -1490,6 +1490,27 @@ class TestRegionAwareCover:
codes = rom_region_shortcodes("007 - Nightfire (USA).chd")
assert codes[0] == "us"
def test_rom_region_shortcodes_follow_prefer_config(self):
config = MagicMock(
SCAN_REGION_PRIORITY=["eu", "us"], SCAN_REGION_MODE="prefer_config"
)
with patch(
"handler.metadata.launchbox_handler.media.cm.get_config",
return_value=config,
):
assert rom_region_shortcodes("007 - Nightfire (USA).chd") == ("eu", "us")
assert rom_region_shortcodes("007 - Nightfire.chd") == ("eu", "us")
def test_untagged_rom_has_no_region_shortcodes_under_prefer_rom_tags(self):
config = MagicMock(
SCAN_REGION_PRIORITY=["eu", "us"], SCAN_REGION_MODE="prefer_rom_tags"
)
with patch(
"handler.metadata.launchbox_handler.media.cm.get_config",
return_value=config,
):
assert rom_region_shortcodes("007 - Nightfire.chd") == ()
class TestRemoteMatchLocalImages:
"""Regression test for bug where remote-matched roms skipped local image lookup.

View File

@@ -142,13 +142,13 @@
# - igdb
# manual: # Game manuals only
# - launchbox
# region: # Used by IGDB and ScreenScraper for regional variants
# region: # Used by IGDB, ScreenScraper and LaunchBox for regional variants (quote "no" for Norway)
# - us
# - wor
# - ss
# - eu
# - jp
# region_mode: prefer_rom_tags # Region tags win over priority list
# region_mode: prefer_rom_tags # Region tags win over priority list; prefer_config makes the list win
# language: # Used by ScreenScraper for descriptions
# - en
# - fr