From f3867c38013bb69990703e7a09894e0be7641ada Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 2 Oct 2026 08:49:08 -0400 Subject: [PATCH] refactor: share the PNG signature and provider region/language spellings PNG_SIGNATURE lives in utils.images for rom-converto, savestate screenshots and audio covers. The general region spellings (North America, NTSC-U, PAL, RegionFree) and regional language variants move into the provider normalizer, so every metadata source gets them; rom-converto keeps only readings of its own region labels. Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/adapters/services/rom_converto.py | 34 ++++----------- backend/handler/filesystem/base_handler.py | 24 +++++++++++ backend/handler/streaming/states.py | 4 +- .../adapters/services/test_rom_converto.py | 41 +++++++++---------- backend/tests/endpoints/sockets/test_scan.py | 10 ++--- backend/tests/endpoints/test_streaming.py | 3 +- .../handler/filesystem/test_base_handler.py | 25 +++++++++++ backend/utils/audio_tags.py | 3 +- backend/utils/images.py | 3 ++ 9 files changed, 89 insertions(+), 58 deletions(-) diff --git a/backend/adapters/services/rom_converto.py b/backend/adapters/services/rom_converto.py index 98ab03629..341df6a94 100644 --- a/backend/adapters/services/rom_converto.py +++ b/backend/adapters/services/rom_converto.py @@ -20,6 +20,7 @@ from models.rom import ( RomFileContentType, ) from utils.filesystem import SERVED_FILE_MODE +from utils.images import PNG_SIGNATURE from utils.platform_slugs import UniversalPlatformSlug as UPS # Wider than the conversion targets: `info` only reads headers, so every @@ -53,7 +54,6 @@ _BINARY: Final = "rom-converto" CUE_EXT: Final = ".cue" -_PNG_SIGNATURE: Final[bytes] = b"\x89PNG\r\n\x1a\n" _PSP_TITLE_ID_PATTERN: Final[re.Pattern[str]] = re.compile(r"[A-Z]{4}[0-9]{5}") @@ -98,9 +98,8 @@ class RomConvertoInfo: # rom-converto's `ContentKind`: "game", "update", "dlc", "demo" or "system". content_type: RomFileContentType | None = None display_version: str | None = None - # RomM spellings where rom-converto's differ ("NorthAmerica" -> "USA"). + # Region and language names as rom-converto spells them. regions: tuple[str, ...] = () - # Regional variants folded ("AmericanEnglish" -> "English"). languages: tuple[str, ...] = () publisher: str | None = None min_firmware_version: str | None = None @@ -452,7 +451,7 @@ def _image(value: Any) -> bytes | None: image = bytes(png_bytes) except TypeError, ValueError: return None - return image if image.startswith(_PNG_SIGNATURE) else None + return image if image.startswith(PNG_SIGNATURE) else None def _list(value: Any) -> list[Any]: @@ -516,13 +515,10 @@ def _english_entry(value: Any) -> Any: return entry[1] if entry else None +# Readings of rom-converto's own region labels; normalize_provider_regions +# handles the spellings other sources share. _REGION_ALIASES: Final[dict[str, str]] = { - "northamerica": "USA", - "north america": "USA", - "ntsc-u": "USA", - "pal": "Europe", "rest of world": "Europe", - "regionfree": "World", "ntsc-j japan": "Japan", "ntsc-j china": "China", "ntsc-j": "Asia", @@ -545,27 +541,11 @@ def _regions(labels: Any) -> tuple[str, ...]: ) -_LANGUAGE_FOLDS: Final[dict[str, str]] = { - "americanenglish": "English", - "britishenglish": "English", - "canadianfrench": "French", - "latinamericanspanish": "Spanish", - "brazilianportuguese": "Portuguese", - "simplifiedchinese": "Chinese", - "traditionalchinese": "Chinese", - "taiwanesechinese": "Chinese", -} - - def _languages(names: Any) -> tuple[str, ...]: - """The language names with regional variants folded.""" + """The language names, with no `Default` slot.""" # A GameCube BNR1 banner's one slot is named `Default`, which is no language. texts = (_text(name) for name in _list(names)) - return tuple( - _LANGUAGE_FOLDS.get(_lang_key(text), text) - for text in texts - if text and _lang_key(text) != "default" - ) + return tuple(text for text in texts if text and _lang_key(text) != "default") _SWITCH_CONTENT_TYPES: Final[dict[str, RomFileContentType]] = { diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index f1e31324c..039a9d02f 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -209,6 +209,13 @@ def region_ranks_for_priority(shortcodes: Sequence[str]) -> dict[str, int]: _REGION_BY_PROVIDER_ALIAS = { **{name.lower(): name for name in REGION_NAME_TO_PROVIDER_SHORTCODE}, **{code: names[0] for code, names in _REGION_NAMES_BY_PROVIDER_SHORTCODE.items()}, + # Console header and video-standard spellings. + "north america": "USA", + "northamerica": "USA", + "ntsc-u": "USA", + "pal": "Europe", + "region free": "World", + "regionfree": "World", } @@ -309,9 +316,26 @@ PROVIDER_LANGUAGES: Final = ( ("vi", "Vietnamese"), ) +# Regional variants fold into their language, however the words are joined. +_LANGUAGE_VARIANTS: Final = { + "american english": "English", + "british english": "English", + "canadian french": "French", + "latin american spanish": "Spanish", + "brazilian portuguese": "Portuguese", + "simplified chinese": "Chinese", + "traditional chinese": "Chinese", + "taiwanese chinese": "Chinese", +} + _LANGUAGE_BY_PROVIDER_ALIAS = { **{name.lower(): name for _, name in PROVIDER_LANGUAGES}, **{code: name for code, name in PROVIDER_LANGUAGES}, + **{ + variant.replace(" ", joiner): name + for variant, name in _LANGUAGE_VARIANTS.items() + for joiner in (" ", "", "_") + }, } # Region shortcodes a filename can also carry, as TOSEC and similar sets write diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index e48061842..4a94fce66 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -46,6 +46,7 @@ from models.assets import State from models.rom import Rom from models.user import User from utils.filesystem import check_filename_length, sanitize_filename +from utils.images import PNG_SIGNATURE # Slot number encoded in each emulator's state filename, e.g. PCSX2 writes # "SERIAL (CRC).03.p2s" for slot 3 and Dolphin writes "GAMEID.s03". Resuming @@ -227,11 +228,10 @@ def push_state_file( # under this entry name (pcsx2/SaveState.cpp: EntryFilename_Screenshot). _SCREENSHOT_ZIP_ENTRY = "Screenshot.png" SCREENSHOT_MAX_BYTES = 16 * 1024 * 1024 -PNG_MAGIC = b"\x89PNG\r\n\x1a\n" def _is_png(data: bytes | None) -> bool: - return data is not None and data.startswith(PNG_MAGIC) + return data is not None and data.startswith(PNG_SIGNATURE) def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | None: diff --git a/backend/tests/adapters/services/test_rom_converto.py b/backend/tests/adapters/services/test_rom_converto.py index 2630cf43c..7b17b28f7 100644 --- a/backend/tests/adapters/services/test_rom_converto.py +++ b/backend/tests/adapters/services/test_rom_converto.py @@ -358,7 +358,7 @@ class TestRomConvertoInfoBatch: batch.read_infos([first]), batch.read_infos([second]) ) - assert results == [ + assert list(results) == [ {first: RomConvertoInfo(title="a.chd")}, {second: RomConvertoInfo(title="b.chd")}, ] @@ -561,7 +561,7 @@ class TestParseInfo: title="The Legend of Zelda", content_type=RomFileContentType.GAME, display_version="1.0.0", - languages=("English", "French"), + languages=("AmericanEnglish", "CanadianFrench"), publisher="Nintendo", min_firmware_version="16.0.0", is_compressed=True, @@ -613,7 +613,7 @@ class TestParseInfo: title="Mega Man Zero", serial="CTR-P-AZRE", content_type=RomFileContentType.GAME, - regions=("USA", "Japan"), + regions=("North America", "Japan"), languages=("Japanese", "English"), publisher="Capcom", is_compressed=True, @@ -760,7 +760,7 @@ class TestParseInfo: serial="SMNE01", content_type=RomFileContentType.GAME, display_version="v3", - regions=("Europe",), + regions=("PAL",), languages=("Japanese", "English"), publisher="Nintendo", is_compressed=False, @@ -825,7 +825,7 @@ class TestParseInfo: serial="TT-027", content_type=RomFileContentType.GAME, display_version="1", - regions=("USA",), + regions=("NTSC-U",), is_compressed=False, file_format="DISC", images=RomConvertoImages(icon=_FAKE_PNG), @@ -848,7 +848,7 @@ class TestParseInfo: title="Halo 3", content_type=RomFileContentType.GAME, display_version="1.0.0.0", - regions=("USA", "Europe"), + regions=("NTSC-U", "PAL"), is_compressed=False, file_format="DISC", images=RomConvertoImages(icon=_FAKE_PNG), @@ -887,7 +887,7 @@ class TestParseInfo: title="Halo 3", content_type=RomFileContentType.GAME, display_version="2.0.4552.0", - regions=("World",), + regions=("RegionFree",), is_compressed=True, file_format="ZAR", uncompressed_size_bytes=786432000, @@ -1207,12 +1207,11 @@ class TestParseInfo: }, }, RomConvertoInfo( - # The scan handler drops the duplicates once names are canonical. regions=( - "USA", + "NorthAmerica", + "PAL", "Europe", - "Europe", - "World", + "RegionFree", "Japan", "China", "Asia", @@ -1220,7 +1219,7 @@ class TestParseInfo: "Korea", ) ), - id="region-names-map-aliases-and-drop-junk", + id="region-names-read-converto-labels-and-drop-junk", ), pytest.param( { @@ -1245,19 +1244,19 @@ class TestParseInfo: }, RomConvertoInfo( languages=( - "English", - "English", - "French", - "Spanish", - "Portuguese", - "Chinese", - "Chinese", - "Chinese", + "AmericanEnglish", + "BritishEnglish", + "CanadianFrench", + "LatinAmericanSpanish", + "BrazilianPortuguese", + "SimplifiedChinese", + "TraditionalChinese", + "TaiwaneseChinese", "Japanese", "german", ) ), - id="language-variants-fold-and-default-drops", + id="languages-drop-the-default-slot", ), pytest.param( { diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index a2fd14c56..7bf739f35 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -752,13 +752,11 @@ class TestConvertoInfoBatch: @pytest.fixture def candidates(self, mocker) -> AsyncMock: - return mocker.patch.object( - fs_rom_handler, - "converto_candidates", - AsyncMock( - side_effect=lambda _slug, fs_path, fs_name: [f"{fs_path}/{fs_name}"] - ), + candidates = AsyncMock( + side_effect=lambda _slug, fs_path, fs_name: [f"{fs_path}/{fs_name}"] ) + mocker.patch.object(fs_rom_handler, "converto_candidates", candidates) + return candidates @pytest.mark.parametrize( ("scan_type", "roms_ids", "expected"), diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 935839cc0..a01ac5ebd 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -88,6 +88,7 @@ from models.permission import HiddenEntity, PermEntity from models.platform import Platform from models.rom import Rom, RomFile, SaveTargetLayout from models.user import User +from utils.images import PNG_SIGNATURE from utils.memory_cards import content_hash_of_bytes # ── Fixtures / helpers ──────────────────────────────────────────────────────── @@ -4754,7 +4755,7 @@ def test_pull_state_prefers_broker_screenshot_over_embedded(rom: Rom, admin_user container = {**_container_for(rom), "label": "PCSX2"} scanned = _state_for(rom, admin_user, "Game.05.p2s", "pcsx2") scanned_shot = _screenshot_for(rom, "Game.05") - embedded = states.PNG_MAGIC + b"embedded-frame" + embedded = PNG_SIGNATURE + b"embedded-frame" with ( patch( "handler.streaming.states.fetch_state_file", diff --git a/backend/tests/handler/filesystem/test_base_handler.py b/backend/tests/handler/filesystem/test_base_handler.py index 93adfd1d0..5e1a6ec2d 100644 --- a/backend/tests/handler/filesystem/test_base_handler.py +++ b/backend/tests/handler/filesystem/test_base_handler.py @@ -861,6 +861,11 @@ class TestNormalizeProviderRegions: def test_duplicate_spellings_collapse_to_one_value(self): assert normalize_provider_regions(["us", "USA", "U"]) == ["USA"] + def test_header_and_video_standard_spellings_resolve(self): + assert normalize_provider_regions( + ["NorthAmerica", "North America", "NTSC-U", "PAL", "RegionFree"] + ) == ["USA", "Europe", "World"] + def test_unknown_value_is_kept_as_given(self): assert normalize_provider_regions([" Neptune "]) == ["Neptune"] @@ -878,6 +883,26 @@ class TestNormalizeProviderLanguages: "Japanese", ] + @pytest.mark.parametrize( + "spelling", + ["Brazilian Portuguese", "BrazilianPortuguese", "brazilian_portuguese"], + ) + def test_regional_variants_fold_into_their_language(self, spelling: str): + assert normalize_provider_languages([spelling]) == ["Portuguese"] + + def test_every_variant_folds(self): + assert normalize_provider_languages( + [ + "AmericanEnglish", + "BritishEnglish", + "CanadianFrench", + "LatinAmericanSpanish", + "SimplifiedChinese", + "TraditionalChinese", + "TaiwaneseChinese", + ] + ) == ["English", "French", "Spanish", "Chinese"] + def test_duplicate_spellings_collapse_to_one_value(self): assert normalize_provider_languages(["en", "English", "EN"]) == ["English"] diff --git a/backend/utils/audio_tags.py b/backend/utils/audio_tags.py index 84ada6502..958716d70 100644 --- a/backend/utils/audio_tags.py +++ b/backend/utils/audio_tags.py @@ -14,6 +14,7 @@ from mutagen.oggopus import OggOpus from mutagen.oggvorbis import OggVorbis from logger.logger import log +from utils.images import PNG_SIGNATURE from utils.media_types import IMAGE_EXT_BY_MIME_TYPE ALLOWED_AUDIO_EXTENSIONS = frozenset( @@ -143,7 +144,7 @@ def _mp4_track_tuple(value: object) -> str | None: def _allowed_mime_types(data: bytes) -> str: """Return MIME type for embedded cover bytes; only JPEG and PNG are allowed.""" - if data.startswith(b"\x89PNG\r\n\x1a\n"): + if data.startswith(PNG_SIGNATURE): return "image/png" if data.startswith(b"\xff\xd8\xff"): return "image/jpeg" diff --git a/backend/utils/images.py b/backend/utils/images.py index ba20fde84..181565c75 100644 --- a/backend/utils/images.py +++ b/backend/utils/images.py @@ -1,7 +1,10 @@ from collections.abc import Callable +from typing import Final from PIL import Image, ImageSequence +PNG_SIGNATURE: Final = b"\x89PNG\r\n\x1a\n" + # Multi-frame formats browsers play as animations (MPO/TIFF pages are not) ANIMATED_FORMATS = frozenset({"GIF", "PNG", "WEBP"})