Files
romm/backend/models/base.py
Tyler Vigario bbb7d98f53 fix(scan): look a file named by several titles up by each of them (#5478)
* fix(scan): look a file named by several titles up by each of them

No-Intro and Redump name a game released under several titles by all of
them, joined by " ~ ". Each file-name lookup now tries the full name
first and then each title, tags and extension kept, until one matches;
SteamGridDB searches the titles too. Only the title is split, never a
tag group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9

* fix(scan): search each SteamGridDB name once

From Greptile's review: a title can repeat a name a provider already
gave, so SteamGridDB's candidate names are deduplicated, first position
kept, with a test. The new test module's docstring is one sentence, as
AGENTS.md asks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eky1CPt1rz6BWLAqWVNmU9

* fix(scan): keep the full-name answer on a miss and cap title lookups

pr-ready step 2 (code-review xhigh --fix): return the full name's result when
every title misses, dedupe and cap titles at 4, and stop wrapping CSDb, whose
lookup only reads a (csdb-N) tag.

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

* refactor(scan): give SteamGridDB the bare titles and inline lookup args

pr-ready step 3 (simplify): add compute_titles so SteamGridDB stops re-attaching
and re-stripping tags, inline the Moby and SS platform ids, and merge the two
all-miss tests.

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

* fix(scan): keep the narrowed Moby and SS platform ids for mypy

pr-ready step 4 (review-polish): the locals inlined in step 3 narrow the
optional platform ids, which a lambda body cannot do; restore them.

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

* docs(scan): reword the title cap comment

pr-ready step 5 (humanizer).

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>
2026-11-08 16:40:43 -05:00

144 lines
4.7 KiB
Python

import re
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, NamedTuple
from sqlalchemy import TIMESTAMP
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, validates
FILE_NAME_MAX_LENGTH = 450
FILE_PATH_MAX_LENGTH = 1000
FILE_EXTENSION_MAX_LENGTH = 100
# Matches parenthesised/bracketed tag groups, e.g. " (USA)" or " [!]", or " (USA) (Rev 1) [!]"
TAG_GROUP_REGEX = re.compile(r"(?:\s*(?:\([^)]*\)|\[[^]]*\]))+\s*$")
# Matches a trailing file extension, including multi-part ones like ".tar.gz".
EXTENSION_REGEX = re.compile(r"\.(([a-z]+\.)*\w+)$")
# No-Intro and Redump name a game released under several titles by all of them.
TITLE_SEPARATOR = " ~ "
# Each title costs a lookup per provider, so only this many are tried.
MAX_TITLES = 4
# PICO-8 carts are often saved as PNG images, so the `.p8` outlives the extension.
PICO8_CARTRIDGE_EXTENSION = ".p8.png"
# Filename tags that mark a dump as a pre-release rather than the shipped game.
# Lowercase and unterminated so one prefix covers its variants: "demo" also
# matches "(Demo Kiosk)", "proto" also matches "(Prototype)".
PRERELEASE_FILENAME_TAGS = (
"demo",
"beta",
"proto",
"sample",
"kiosk",
"preview",
)
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def compute_file_name_no_ext(file_name: str) -> str:
"""Strip the trailing extension from a file name."""
return EXTENSION_REGEX.sub("", file_name).strip()
def compute_file_name_no_tags(file_name: str) -> str:
"""Strip the extension and any trailing tag groups from a file name.
Only tag groups at the end are removed (repeatedly), so a title that
legitimately contains parentheses/brackets mid-name is not truncated.
"""
name = compute_file_name_no_ext(file_name)
if file_name.lower().endswith(PICO8_CARTRIDGE_EXTENSION):
name = name[: -len(".p8")]
return TAG_GROUP_REGEX.sub("", name).strip()
def compute_titles(file_name: str) -> list[str]:
"""Each title of a game named by several, else []."""
parts = compute_file_name_no_tags(file_name).split(TITLE_SEPARATOR)
if len(parts) < 2:
return []
titles = [title for title in dict.fromkeys(part.strip() for part in parts) if title]
return titles[:MAX_TITLES]
def compute_title_file_names(file_name: str) -> list[str]:
"""The file name once per title of a game named by several, else []."""
title = compute_file_name_no_tags(file_name)
if not file_name.startswith(title):
return []
tags_and_extension = file_name[len(title) :]
return [part + tags_and_extension for part in compute_titles(file_name)]
def compute_file_extension(file_name: str) -> str:
"""Return the file's extension (without the leading dot), or ""."""
match = EXTENSION_REGEX.search(file_name)
return match.group(1) if match else ""
class FileNameParts(NamedTuple):
no_tags: str
no_ext: str
extension: str
def compute_file_name_parts(file_name: str) -> FileNameParts:
"""Precompute the derived columns stored alongside a file name.
These mirror the `*_no_tags` / `*_no_ext` / `*_extension` columns on
`Rom`, the asset models, and `Firmware`, which are kept in sync via a
`@validates` hook on the source name column.
"""
return FileNameParts(
no_tags=compute_file_name_no_tags(file_name),
no_ext=compute_file_name_no_ext(file_name),
extension=compute_file_extension(file_name),
)
def with_file_name_parts(data: dict[str, Any]) -> dict[str, Any]:
"""`data` plus the columns derived from its `file_name`, which a bulk
update() must write itself since it skips the `@validates` hook."""
if "file_name" not in data:
return data
parts = compute_file_name_parts(data["file_name"])
return {
**data,
"file_name_no_tags": parts.no_tags,
"file_name_no_ext": parts.no_ext,
"file_extension": parts.extension,
}
class FileNamePartsMixin:
"""Derives the `file_name_no_tags` / `file_name_no_ext` / `file_extension`
columns whenever `file_name` is assigned."""
if TYPE_CHECKING:
file_name_no_tags: str
file_name_no_ext: str
file_extension: str
@validates("file_name")
def _sync_file_name_parts(self, _key: str, file_name: str) -> str:
parts = compute_file_name_parts(file_name)
self.file_name_no_tags = parts.no_tags
self.file_name_no_ext = parts.no_ext
self.file_extension = parts.extension
return file_name
class BaseModel(DeclarativeBase):
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True), default=utc_now
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
)