Merge pull request #4224 from sdornan/claude/launchbox-matching-regression-9cebe4

fix(launchbox): match titles differing only by punctuation
This commit is contained in:
Georges-Antoine Assi
2026-08-18 19:12:45 -04:00
committed by GitHub
9 changed files with 204 additions and 7 deletions

View File

@@ -39,7 +39,12 @@ from handler.filesystem import (
fs_rom_handler,
)
from handler.filesystem.roms_handler import FSRom
from handler.metadata import meta_gamelist_handler, meta_hltb_handler
from handler.metadata import (
meta_gamelist_handler,
meta_hltb_handler,
meta_launchbox_handler,
)
from handler.metadata.launchbox_handler.types import LAUNCHBOX_PLATFORMS_DIR
from handler.metadata.ss_handler import add_ss_auth_to_url
from handler.metadata.ss_handler import begin_scan as begin_ss_scan
from handler.metadata.ss_handler import get_preferred_media_types
@@ -1068,6 +1073,40 @@ async def scan_platforms(
if MetadataSource.HLTB in metadata_sources:
await meta_hltb_handler.initialize()
# A local install is read on every lookup; the per-scan switch only decides
# whether the cloud store is consulted as well. Both can be empty, and a
# lookup against an absent source is silent, so what LaunchBox can actually
# read is recorded here rather than left to be inferred from a platform's
# worth of empty results.
if MetadataSource.LAUNCHBOX in metadata_sources:
local_available = meta_launchbox_handler.is_local_enabled()
store_available = launchbox_remote_enabled and (
await meta_launchbox_handler.is_remote_store_populated()
)
readable = [
name
for name, present in (
(f"a {hl('local')} install", local_available),
(f"the {hl('cloud')} store", store_available),
)
if present
]
if readable:
log.info(f"LaunchBox is reading {' and '.join(readable)}")
elif launchbox_remote_enabled:
log.warning(
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} LaunchBox has nothing "
f"to read: no install at {hl(str(LAUNCHBOX_PLATFORMS_DIR))} and the "
"cloud store is empty. Run the LaunchBox metadata update task."
)
else:
log.warning(
f"{hl(emoji.EMOJI_WARNING, color=LIGHTYELLOW)} LaunchBox is set to "
f"local only and no install was found at "
f"{hl(str(LAUNCHBOX_PLATFORMS_DIR))}, so it will match nothing. "
"Switch it to cloud, or mount an install there."
)
# Resolve the platforms that will actually be scanned. When no platform ids
# are provided, every filesystem platform is scanned.
db_platforms = db_platform_handler.get_platforms()

View File

@@ -9,10 +9,11 @@ from .types import (
LAUNCHBOX_MAME_KEY,
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
LAUNCHBOX_METADATA_IMAGE_KEY,
LAUNCHBOX_METADATA_NAME_KEY,
)
from .utils import deinvert_article, file_name_forms
from .utils import deinvert_article, file_name_forms, fold_title
class RemoteSource:
@@ -89,6 +90,20 @@ class RemoteSource:
if entry.get("Platform") == platform_name:
return entry
# Last resort: compare titles with punctuation, accents and spacing
# removed. A dump filename can only differ from the title it was cut
# from by characters `fold_title` drops, so this is checked after every
# exact form has missed.
for candidate in candidates:
folded = fold_title(candidate)
if not folded:
continue
folded_index_entry = await async_cache.hget(
LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}"
)
if folded_index_entry:
return json.loads(folded_index_entry)
return None
async def get_rom_by_file_name(

View File

@@ -13,6 +13,7 @@ LAUNCHBOX_METADATA_NAME_KEY: Final[str] = "romm:launchbox_metadata_name"
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: Final[str] = (
"romm:launchbox_metadata_alternate_name"
)
LAUNCHBOX_METADATA_FOLDED_NAME_KEY: Final[str] = "romm:launchbox_metadata_folded_name"
LAUNCHBOX_METADATA_IMAGE_KEY: Final[str] = "romm:launchbox_metadata_image"
LAUNCHBOX_MAME_KEY: Final[str] = "romm:launchbox_mame"
LAUNCHBOX_FILES_KEY: Final[str] = "romm:launchbox_files"

View File

@@ -1,4 +1,5 @@
import re
import unicodedata
from datetime import datetime
from pathlib import Path
@@ -41,6 +42,39 @@ def deinvert_article(term: str) -> str | None:
return f"{match.group('article')} {match.group('title')}{subtitle}"
def fold_title(title: str) -> str:
"""Reduce a title to letters and digits for punctuation-blind comparison.
Dump titles and ROM filenames disagree on punctuation constantly: LaunchBox
writes a colon a filename has no room for ("Burnout: Revenge"), keeps
diacritics a dump filename drops ("Astérix"), and uses characters a
filesystem forbids ("AC/DC"). Folding both sides to `burnoutrevenge` /
`asterix` / `acdc` makes those the same key.
Spaces go too, so "Area-51" and "Area 51" agree. Returns "" for a title
with nothing left to compare, which callers must treat as no key.
Letters of every script survive. Keeping only ASCII would reduce a title
written in one to whatever digits it carries, collapsing "三國立志傳2" and
"忍者村大战2" onto the same key.
A mark only goes when it sits on a Latin letter, where it is an accent the
two sides may disagree about ("Astérix" against "Asterix"). Elsewhere it
spells the word: Devanagari and Thai build syllables from marks, so dropping
them would reduce "हिन्दी" to "हनद" and collide titles that differ.
"""
kept: list[str] = []
for char in unicodedata.normalize("NFKD", title.casefold()):
if unicodedata.category(char).startswith("M"):
if kept and "a" <= kept[-1] <= "z":
continue
kept.append(char)
elif char.isalnum():
kept.append(char)
return "".join(kept)
def file_name_forms(file_name: str) -> list[str]:
"""Lowercased extension-less forms of a file name, most specific first.

View File

@@ -19,11 +19,13 @@ from handler.metadata.launchbox_handler.types import (
LAUNCHBOX_MAME_KEY,
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
LAUNCHBOX_METADATA_IMAGE_KEY,
LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY,
LAUNCHBOX_METADATA_NAME_KEY,
LAUNCHBOX_PLATFORMS_KEY,
)
from handler.metadata.launchbox_handler.utils import fold_title
from handler.redis_handler import async_cache
from logger.logger import log
from tasks.tasks import RemoteFilePullTask, TaskType
@@ -191,14 +193,25 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask):
and platform_elem is not None
and platform_elem.text
):
platform_name = platform_elem.text.strip()
game = _element_to_dict(elem)
# Use a unique combination of name and platform as the key
await writer.hset(
LAUNCHBOX_METADATA_NAME_KEY,
f"{name_elem.text.strip().lower()}"
f":{platform_elem.text.strip()}",
_element_to_dict(elem),
f":{platform_name}",
game,
)
folded = fold_title(name_elem.text)
if folded:
await writer.hset(
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
f"{folded}:{platform_name}",
game,
)
elif elem.tag == "GameAlternateName":
alternate_name_elem = elem.find("AlternateName")
if (

View File

@@ -36,6 +36,7 @@ from handler.metadata.launchbox_handler.types import (
LAUNCHBOX_MAME_KEY,
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
LAUNCHBOX_METADATA_IMAGE_KEY,
LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY,
LAUNCHBOX_METADATA_NAME_KEY,
@@ -46,6 +47,7 @@ from handler.metadata.launchbox_handler.types import (
from handler.metadata.launchbox_handler.utils import (
coalesce,
deinvert_article,
fold_title,
launchbox_region_to_shortcode,
parse_playmode,
parse_release_date,
@@ -667,6 +669,88 @@ class TestRemoteSourceGetRom:
# The literal name is still tried first.
assert queried[0] == "legend of zelda, the: ocarina of time:Nintendo 64"
@pytest.mark.parametrize(
("search_term", "dump_title"),
[
# LaunchBox adds a colon the filename has no room for.
("burnout revenge", "Burnout: Revenge"),
# The dump keeps diacritics a No-Intro filename drops.
("asterix at the olympic games", "Astérix at the Olympic Games"),
# "/" cannot appear in a filename at all.
("ac-dc live: rock band track pack", "AC/DC Live: Rock Band Track Pack"),
# Hyphen against space.
("area 51", "Area-51"),
],
)
async def test_folded_title_match(
self, source: RemoteSource, search_term: str, dump_title: str
):
"""Punctuation-only differences resolve through the folded index."""
entry = {"DatabaseID": "77", "Name": dump_title}
folded_field = f"{fold_title(dump_title)}:Sony Playstation 2"
async def side_effect(key, field):
if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY and field == folded_field:
return json.dumps(entry)
return None
with patch.object(
async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect
):
result = await source.get_rom(search_term, "ps2", assume_cache_present=True)
assert result is not None
assert result.get("DatabaseID", None) == "77"
@pytest.mark.parametrize(
("title", "expected"),
[
("Burnout: Revenge", "burnoutrevenge"),
("Astérix at the Olympic Games", "asterixattheolympicgames"),
("AC/DC Live", "acdclive"),
("Area-51", "area51"),
# A title in a non-Latin script keeps its letters. Reducing it to
# its digits would collide with every other title numbered alike.
("三國立志傳2", "三國立志傳2"),
("Зона 51", "зона51"),
# Scripts that build syllables from marks keep them; stripping to
# alphanumerics alone would spell these titles differently.
("हिन्दी गेम", "हिन्दीगेम"),
("สนุกเกอร์", "สนุกเกอร์"),
# Nothing comparable left, so callers must treat it as no key.
(":: -- ::", ""),
],
)
def test_fold_title(self, title: str, expected: str):
assert fold_title(title) == expected
def test_fold_title_separates_titles_sharing_only_their_digits(self):
assert fold_title("三國立志傳2") != fold_title("忍者村大战2")
async def test_folded_match_is_only_tried_after_exact_forms(
self, source: RemoteSource
):
"""Folding discards information, so an exact hit must always win."""
exact = {"DatabaseID": "1", "Name": "Burnout Revenge"}
folded = {"DatabaseID": "2", "Name": "Burnout: Revenge"}
async def side_effect(key, _field):
if key == LAUNCHBOX_METADATA_NAME_KEY:
return json.dumps(exact)
if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY:
return json.dumps(folded)
return None
with patch.object(
async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect
):
result = await source.get_rom(
"burnout revenge", "ps2", assume_cache_present=True
)
assert result is not None
assert result.get("DatabaseID", None) == "1"
async def test_no_match_returns_none(self, source: RemoteSource):
with patch.object(
async_cache, "hget", new_callable=AsyncMock, return_value=None

View File

@@ -11,6 +11,7 @@ from handler.metadata.launchbox_handler.types import (
LAUNCHBOX_MAME_KEY,
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
LAUNCHBOX_METADATA_IMAGE_KEY,
LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY,
LAUNCHBOX_METADATA_NAME_KEY,
@@ -151,7 +152,7 @@ class TestUpdateLaunchboxMetadataTask:
# Check hset call details
hset_calls = mock_pipe.hset.call_args_list
assert len(hset_calls) == 12
assert len(hset_calls) == 14
platform_calls = [
call for call in hset_calls if call[0][0] == LAUNCHBOX_PLATFORMS_KEY
@@ -174,11 +175,18 @@ class TestUpdateLaunchboxMetadataTask:
metadata_image_calls = [
call for call in hset_calls if call[0][0] == LAUNCHBOX_METADATA_IMAGE_KEY
]
metadata_folded_calls = [
call
for call in hset_calls
if call[0][0] == LAUNCHBOX_METADATA_FOLDED_NAME_KEY
]
assert len(metadata_id_calls) == 2
assert len(metadata_name_calls) == 2
assert len(metadata_alt_calls) == 1
assert len(metadata_image_calls) == 1
# Every named game is indexed under its folded title too.
assert len(metadata_folded_calls) == len(metadata_name_calls)
mame_calls = [call for call in hset_calls if call[0][0] == LAUNCHBOX_MAME_KEY]
assert len(mame_calls) == 2
@@ -324,7 +332,7 @@ class TestUpdateLaunchboxMetadataTaskIntegration:
# Check hset call details
hset_calls = mock_pipe.hset.call_args_list
assert len(hset_calls) == 12
assert len(hset_calls) == 14
# Verify that all expected Redis keys were used
redis_keys_used = [call[0][0] for call in hset_calls]
@@ -333,6 +341,7 @@ class TestUpdateLaunchboxMetadataTaskIntegration:
LAUNCHBOX_PLATFORMS_KEY,
LAUNCHBOX_METADATA_DATABASE_ID_KEY,
LAUNCHBOX_METADATA_NAME_KEY,
LAUNCHBOX_METADATA_FOLDED_NAME_KEY,
LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY,
LAUNCHBOX_METADATA_IMAGE_KEY,
LAUNCHBOX_MAME_KEY,

View File

@@ -174,7 +174,8 @@ RUN apk add --no-cache \
nodejs \
7zip \
tzdata \
valkey
valkey \
valkey-cli
# Add Python by copying it from the official Docker image. This way, we don't rely on Alpine's
# Python version, which could not be the same as the one used in the backend build stage.

View File

@@ -300,6 +300,7 @@ watchdog_process_pid() {
# Check if the pid we last wrote to our state file is actually active
PID=$(cat "/tmp/${PROCESS}.pid") || true
if [[ ! -d "/proc/${PID}" ]]; then
warn_log "${PROCESS} exited unexpectedly, restarting it"
start_bin_"${PROCESS}"
fi
else