Files
romm/backend/handler/metadata/libretro_handler.py
Spinnich 60703be09c chore(platforms): split arcade aliases into per-emulator-family slugs (#5273)
* feat(platforms): split arcade aliases into per-emulator-family slugs

Give MAME, AdvanceMAME, FBNeo, FBA, Daphne, Singe and the arcade boards
that need their own emulator (NAOMI/NAOMI 2/NAOMI GD-ROM, Model 2/3,
Hikaru, Triforce, Lindbergh, Namco System 246/3xx, Gaelco, ...) their own
slugs with verified provider IDs. Providers without a dedicated entry fall
back to their Arcade platform via arcade_fallbacks(). MAME-only boards
(CPS1-3, System 16/32, Model 1, Namco 22) stay aliases of arcade.

Refs #5272

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

* fix(platforms): code-review pass on arcade slugs

- Retry IGDB on unmatched scans for every platform IGDB resolves, not
  just slugs in IGDB_PLATFORM_LIST.
- Resolve config binding/version values through the alias table, so a
  binding to a retired slug (cps2, model1, ...) still lands on a platform.
- Alias the Batocera `typex` folder to type-x.
- Build provider id->slug reverse maps before merging Arcade fallbacks.
- Share one MAME title lookup between base_handler and libretro.

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

* refactor(platforms): simplify pass on arcade slugs

- Alias the three RomM-keyed IGDB versions inside IGDB_PLATFORM_VERSIONS,
  dropping IGDB_VERSION_SLUGS and _version_slug.
- Derive EmulatorJS arcade entries from ARCADE_SET_PLATFORMS.
- Remove the unused provider id->slug reverse maps, so the Arcade
  fallback merge no longer has an ordering constraint.

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

* docs(platforms): humanizer pass on arcade slug comments

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

* fix(platforms): settle arcade slug review decisions

- Migration 0154 moves platforms still on a retired MAME-only board slug
  (cps1-3, model1, system16, system32, system-32) to arcade, so no row
  carries a slug the enum no longer has.
- MAME shortname expansion keys off the RomM slug via
  MAME_SHORTNAME_PLATFORMS instead of per-provider arcade ids, so Daphne,
  Singe, Type X and Lindbergh sets are no longer read as MAME sets. Neo Geo
  now expands at ScreenScraper too, as it already did at IGDB and Moby.
- fba offers fbneo before the FinalBurn Alpha CPS cores.
- AdvanceMAME leaves the WebRcade feed; EmulatorJS and WebRcade share
  PLAYABLE_ARCADE_SET_PLATFORMS.

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

* fix(platforms): code-review pass (xhigh) on arcade slugs

Verify arcade-board BIOS files against the known list's arcade entries,
and make migration 0154 match retired slugs case-insensitively.

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

* refactor(platforms): simplify pass on arcade slugs

Apply IGDB family overrides once in get_platform instead of on each
return path.

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

* test(platforms): use a slug with no shipped icon

singe now ships an icon, so the no-icon prefetch test needs a slug that never will.

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

* feat(platforms): add a teknoparrot arcade slug

TeknoParrot runs PC-based arcade boards outside the MAME/FinalBurn family,
so its folder gets its own platform (RetroBat and ES-DE both use
`teknoparrot`). Providers fall back to their Arcade entry, MAME shortname
expansion skips it, and it gets a placeholder icon copied from `arcade`.

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

* feat(platforms): give each arcade-family icon its own marquee title

Redraws the ARCADE marquee on the copied cabinet icons with each
platform's name, in the Bungee typeface with the original inline and
extrusion styling. Sega boards use Sega blue, Namco systems Namco red,
and Type X Taito blue; the rest keep the original amber.

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

* fix(platforms): code-review pass (xhigh) on arcade slugs

Neo Geo BIOS lives under arcade in the known BIOS list, so map
neogeoaes and neogeomvs there too.

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

* refactor(platforms): simplify pass on arcade slug tests

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-10-28 19:53:06 -04:00

283 lines
10 KiB
Python

import asyncio
import hashlib
import os
import re
from typing import Final, NotRequired, TypedDict
from adapters.services.libretro_thumbnails import LibretroThumbnailsService
from adapters.services.libretro_thumbnails_types import LibretroArtType
from config.config_manager import MetadataMediaType
from config.config_manager import config_manager as cm
from logger.logger import log
from utils.arcade_platforms import MAME_SHORTNAME_PLATFORMS
from utils.platform_slugs import UniversalPlatformSlug as UPS
from utils.platform_slugs import fill_duplicate_slugs
from .base_handler import MetadataHandler, mame_title
_PAREN_TAG_PATTERN = re.compile(r"\([^)]*\)")
# Characters libretro replaces with `_` in its art filenames.
_UNSAFE_NAME_CHARS = re.compile(r'[&*/:`<>?\\|"]')
# Only fetched when the user has the corresponding MetadataMediaType in SCAN_MEDIA
_GATED_ART_TYPES: list[tuple[LibretroArtType, MetadataMediaType]] = [
(LibretroArtType.SCREENSHOT, MetadataMediaType.SCREENSHOT),
(LibretroArtType.TITLE_SCREEN, MetadataMediaType.TITLE_SCREEN),
(LibretroArtType.LOGO, MetadataMediaType.LOGO),
]
def get_preferred_media_types() -> list[MetadataMediaType]:
"""Get preferred media types from config."""
config = cm.get_config()
return [MetadataMediaType(media) for media in config.SCAN_MEDIA]
class LibretroPlatform(TypedDict):
slug: str
libretro_slug: str | None
class LibretroRom(TypedDict):
libretro_id: str | None
url_cover: NotRequired[str]
url_screenshots: NotRequired[list[str]]
name: NotRequired[str]
def _remove_file_extension(filename: str) -> str:
return os.path.splitext(filename)[0]
def _strip_paren_tags(s: str) -> str:
"""Remove parenthetical tags like (USA), (SGB Enhanced) from a filename."""
return _PAREN_TAG_PATTERN.sub("", s).strip()
def libretro_id_for(filename: str) -> str:
"""Deterministic ID for a libretro art filename.
SHA1 hex of the full filename (extension included). Stable across scans
for the same matched art, fits in the `roms.libretro_id` column (40 chars
in a varchar(64)).
"""
return hashlib.sha1(filename.encode("utf-8"), usedforsecurity=False).hexdigest()
class LibretroHandler(MetadataHandler):
"""Handler for libretro thumbnails (https://thumbnails.libretro.com).
Artwork-only source, supplies box-art URLs but no game IDs, summaries,
or metadata. Follows the same integration pattern as SGDBBaseHandler.
"""
def __init__(self) -> None:
self.service = LibretroThumbnailsService()
self.min_similarity_score: Final = 0.8
@classmethod
def is_enabled(cls) -> bool:
return True
async def heartbeat(self) -> bool:
try:
return await self.service.head()
except Exception as exc:
log.error("Error checking libretro thumbnails: %s", exc)
return False
def get_platform(self, slug: str) -> LibretroPlatform:
if slug in LIBRETRO_PLATFORM_LIST:
libretro_slug = LIBRETRO_PLATFORM_LIST[UPS(slug)]
return LibretroPlatform(slug=slug, libretro_slug=libretro_slug)
return LibretroPlatform(slug=slug, libretro_slug=None)
def _find_exact_match(self, target: str, listing: list[str]) -> str | None:
"""Case-insensitive exact match on filename (extension stripped)."""
target_lower = target.lower()
for filename in listing:
if _remove_file_extension(filename).lower() == target_lower:
return filename
return None
def _find_fuzzy_match(self, target: str, listing: list[str]) -> str | None:
"""Fuzzy fallback, strips parenthetical tags from both sides and uses
JaroWinkler via MetadataHandler.find_best_match."""
if not listing:
return None
query = _strip_paren_tags(target)
# Build candidate list of tag-stripped names that map back to original filenames
stripped_to_original: dict[str, str] = {}
for filename in listing:
stripped = _strip_paren_tags(_remove_file_extension(filename))
# Keep the first occurrence, libretro typically has one canonical
# entry per region; ties are acceptable since we fall back here.
stripped_to_original.setdefault(stripped, filename)
match, _score = self.find_best_match(
query,
list(stripped_to_original.keys()),
min_similarity_score=self.min_similarity_score,
)
if not match:
return None
return stripped_to_original[match]
def _match_art_name(self, name: str, listing: list[str]) -> str | None:
target = _UNSAFE_NAME_CHARS.sub("_", name)
exact = self._find_exact_match(target, listing)
if exact:
return exact
return self._find_fuzzy_match(target, listing)
async def get_rom(self, fs_name: str, platform_slug: str) -> LibretroRom:
"""Find libretro artwork for a ROM.
Always fetches Named_Boxarts (used for `url_cover` and `libretro_id`).
Additionally fetches Named_Snaps / Named_Titles / Named_Logos when the
matching MetadataMediaType (SCREENSHOT / TITLE_SCREEN / LOGO) is in
SCAN_MEDIA, and appends any matches to `url_screenshots` so the
scan_handler artwork loop picks them up. `name` is deliberately
omitted, since libretro artwork filenames aren't proper game names.
"""
platform = self.get_platform(platform_slug)
if not platform or not platform["libretro_slug"]:
return LibretroRom(libretro_id=None)
system_name = platform["libretro_slug"]
preferred = get_preferred_media_types()
extra_art_types = [art for art, media in _GATED_ART_TYPES if media in preferred]
art_types = [LibretroArtType.BOX_ART, *extra_art_types]
listings = await asyncio.gather(
*(self.service.fetch_listing(system_name, t) for t in art_types)
)
box_listing = listings[0]
if not box_listing:
return LibretroRom(libretro_id=None)
art_name = _remove_file_extension(fs_name)
# Libretro names arcade art by MAME's full title, not the set's shortname.
if platform_slug in MAME_SHORTNAME_PLATFORMS:
art_name = await mame_title(art_name) or art_name
matched = self._match_art_name(art_name, box_listing)
if not matched:
return LibretroRom(libretro_id=None)
url_cover = LibretroThumbnailsService.build_art_url(
system_name, LibretroArtType.BOX_ART, matched
)
url_screenshots: list[str] = []
for art_type, listing in zip(extra_art_types, listings[1:], strict=False):
if not listing:
continue
extra = self._match_art_name(art_name, listing)
if extra:
url_screenshots.append(
LibretroThumbnailsService.build_art_url(
system_name, art_type, extra
)
)
rom = LibretroRom(
libretro_id=libretro_id_for(matched),
url_cover=url_cover,
)
if url_screenshots:
rom["url_screenshots"] = url_screenshots
return rom
LIBRETRO_PLATFORM_LIST: Final[dict[UPS, str]] = {
UPS.ADVENTURE_VISION: "Entex - Adventure Vision",
UPS.AMIGA: "Commodore - Amiga",
UPS.AMIGA_CD32: "Commodore - Amiga",
UPS.ACPC: "Amstrad - CPC",
UPS.ATOMISWAVE: "Atomiswave",
UPS.ATARI2600: "Atari - 2600",
UPS.ATARI5200: "Atari - 5200",
UPS.ATARI7800: "Atari - 7800",
UPS.ATARI_ST: "Atari - ST",
UPS.JAGUAR: "Atari - Jaguar",
UPS.LYNX: "Atari - Lynx",
UPS.WONDERSWAN: "Bandai - WonderSwan",
UPS.WONDERSWAN_COLOR: "Bandai - WonderSwan Color",
UPS.COLECOVISION: "Coleco - ColecoVision",
UPS.C64: "Commodore - 64",
UPS.VIC_20: "Commodore - VIC-20",
UPS.DOOM: "DOOM",
UPS.DOS: "DOS",
UPS.FAIRCHILD_CHANNEL_F: "Fairchild - Channel F",
UPS.FBNEO: "FBNeo - Arcade Games",
UPS.VECTREX: "GCE - Vectrex",
UPS.MAME: "MAME",
UPS.MAME_ADVMAME: "MAME",
UPS.ODYSSEY_2: "Magnavox - Odyssey2",
UPS.INTELLIVISION: "Mattel - Intellivision",
UPS.MSX: "Microsoft - MSX",
UPS.MSX2: "Microsoft - MSX2",
UPS.XBOX: "Microsoft - XBOX",
UPS.PC_8800_SERIES: "NEC - PC Engine - TurboGrafx 16",
UPS.PC_FX: "NEC - PC-FX",
UPS.PC_9800_SERIES: "NEC - PC-98",
UPS.SUPERGRAFX: "NEC - PC Engine SuperGrafx",
UPS.TG16: "NEC - PC Engine - TurboGrafx 16",
UPS.TURBOGRAFX_CD: "NEC - PC Engine CD - TurboGrafx-CD",
UPS.FDS: "Nintendo - Family Computer Disk System",
UPS.GB: "Nintendo - Game Boy",
UPS.GBA: "Nintendo - Game Boy Advance",
UPS.GBC: "Nintendo - Game Boy Color",
UPS.NGC: "Nintendo - GameCube",
UPS.N64: "Nintendo - Nintendo 64",
UPS.N64DD: "Nintendo - Nintendo 64DD",
UPS.N3DS: "Nintendo - Nintendo 3DS",
UPS.NDS: "Nintendo - Nintendo DS",
UPS.NES: "Nintendo - Nintendo Entertainment System",
UPS.FAMICOM: "Nintendo - Nintendo Entertainment System",
UPS.POKEMON_MINI: "Nintendo - Pokemon Mini",
UPS.SATELLAVIEW: "Nintendo - Satellaview",
UPS.SUFAMI_TURBO: "Nintendo - Sufami Turbo",
UPS.SNES: "Nintendo - Super Nintendo Entertainment System",
UPS.SFAM: "Nintendo - Super Nintendo Entertainment System",
UPS.VIRTUALBOY: "Nintendo - Virtual Boy",
UPS.WII: "Nintendo - Wii",
UPS.WIIU: "Nintendo - Wii U",
UPS.RPG_MAKER: "RPG Maker",
UPS.SCUMMVM: "ScummVM",
UPS.SEGA32: "Sega - 32X",
UPS.DC: "Sega - Dreamcast",
UPS.GAMEGEAR: "Sega - Game Gear",
UPS.GENESIS: "Sega - Mega Drive - Genesis",
UPS.SEGACD: "Sega - Mega-CD - Sega CD",
UPS.SMS: "Sega - Master System - Mark III",
UPS.SG1000: "Sega - SG-1000",
UPS.NAOMI: "Sega - Naomi",
UPS.NAOMI2: "Sega - Naomi 2",
UPS.SATURN: "Sega - Saturn",
UPS.X1: "Sharp - X1",
UPS.SHARP_X68000: "Sharp - X68000",
UPS.ZX81: "Sinclair - ZX 81",
UPS.ZXS: "Sinclair - ZX Spectrum",
UPS.NEOGEOAES: "SNK - Neo Geo",
UPS.NEOGEOMVS: "SNK - Neo Geo",
UPS.NEO_GEO_CD: "SNK - Neo Geo CD",
UPS.NEO_GEO_POCKET: "SNK - Neo Geo Pocket",
UPS.NEO_GEO_POCKET_COLOR: "SNK - Neo Geo Pocket Color",
UPS.PSX: "Sony - PlayStation",
UPS.PS2: "Sony - PlayStation 2",
UPS.PSP: "Sony - PlayStation Portable",
UPS.TIC_80: "TIC-80",
UPS.ZELDA_CLASSIC: "Zelda Classic",
UPS.TOMY_TUTOR: "Tomy - Tutor",
UPS.SUPERVISION: "Watara - Supervision",
}
fill_duplicate_slugs(LIBRETRO_PLATFORM_LIST)