Coverage for src/romfarmer/analysis/catalog_builder.py: 67%
279 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""CatalogBuilder — CATALOG phase: scan + hash + DAT-match + grouping → Catalog.
3This module absorbs the *identity* half of ``stages/filter_dat.py``: it
4discovers source files, builds partial ``Identity`` objects (zip_identity from
5ZIP central-dir + MD5 from the metadata DB cache), optionally matches against
6a ``DATFile``, strips disc tags, groups multi-disc sets, and enriches each
7``GameUnit`` with metadata from the ``KnowledgeBase``.
9It does **not** create symlinks, write to the work directory, or modify any
10global state. It returns an immutable ``Catalog``.
12Multi-disc atomicity: grouping happens *here* and nowhere else. Once the
13``Catalog`` is returned, every downstream planner pass operates at unit
14granularity — there is no API to reach an individual ``DiscRef``.
15See ``docs/compiler-refactor/04-edge-case-designs.md`` §1.
16"""
18from __future__ import annotations
20import hashlib
21import logging
22import re
23import time
24import zipfile
25from collections import defaultdict
26from concurrent.futures import ThreadPoolExecutor, as_completed
27from pathlib import Path
28from typing import TYPE_CHECKING
30from romfarmer.ir.catalog import (
31 Catalog,
32 CatalogWarning,
33 DiscRef,
34 GameUnit,
35 PlatformId,
36 SourceRef,
37 UnitId,
38)
39from romfarmer.ir.identity import Identity, ZipIdentity
41if TYPE_CHECKING:
42 from romfarmer.analysis.file_digest_cache import FileDigestCache
43 from romfarmer.analysis.knowledge import KnowledgeBase
45logger = logging.getLogger(__name__)
47# ---------------------------------------------------------------------------
48# Filename parsing helpers
49# ---------------------------------------------------------------------------
51_DISC_TAG = re.compile(r"\s*\((?:Disc|Disk|CD)\s*(\d+)\)", re.IGNORECASE)
52_REGION_TAG = re.compile(r"\(([^)]+)\)")
54# Ordered region-string keywords (matches against parenthetical tags)
55_REGION_KEYWORDS: dict[str, frozenset[str]] = {
56 "USA": frozenset({"usa", "us", "ntsc-u", "ntsc"}),
57 "Europe": frozenset({"europe", "eur", "pal"}),
58 "Japan": frozenset({"japan", "jpn", "ntsc-j"}),
59 "World": frozenset({"world"}),
60 "Germany": frozenset({"germany", "ger"}),
61 "France": frozenset({"france", "fra"}),
62 "Spain": frozenset({"spain", "spa"}),
63 "Italy": frozenset({"italy", "ita"}),
64 "Australia": frozenset({"australia", "aus"}),
65 "Korea": frozenset({"korea", "kor"}),
66 "China": frozenset({"china", "chi"}),
67 "Brazil": frozenset({"brazil", "bra"}),
68 "Netherlands": frozenset({"netherlands", "nld"}),
69 "Sweden": frozenset({"sweden", "swe"}),
70}
72_LANG_TAG = re.compile(
73 r"\((?:En|Fr|De|Es|It|Ja|Nl|Pt|Sv|No|Da|Fi|Pl|Ru|Zh|Ko)(?:[,+][A-Za-z]{2})*\)"
74)
77def _strip_disc_tag(stem: str) -> str:
78 """Return the disc-tag-stripped canonical name for grouping."""
79 return _DISC_TAG.sub("", stem).strip()
82def _disc_index(stem: str) -> int:
83 """Return the disc number (1-based) parsed from a filename stem."""
84 m = _DISC_TAG.search(stem)
85 return int(m.group(1)) if m else 1
88def _parse_regions(name: str) -> frozenset[str]:
89 """Extract known region strings from parenthetical tags."""
90 found: set[str] = set()
91 for tag in _REGION_TAG.findall(name):
92 for part in re.split(r"[,;+/]", tag):
93 token = part.strip().lower()
94 for region, keywords in _REGION_KEYWORDS.items():
95 if token in keywords:
96 found.add(region)
97 return frozenset(found)
100def _parse_languages(name: str) -> frozenset[str]:
101 """Extract ISO-639-1 language codes from parenthetical tags."""
102 found: set[str] = set()
103 for m in _LANG_TAG.finditer(name):
104 tag_inner = m.group().strip("()")
105 for code in re.split(r"[,+]", tag_inner):
106 found.add(code.strip())
107 return frozenset(found)
110# ---------------------------------------------------------------------------
111# Identity helpers
112# ---------------------------------------------------------------------------
115def _dominant_member(members: list[zipfile.ZipInfo]) -> zipfile.ZipInfo:
116 """The .cue sheet for CD sets, otherwise the largest member (mirrors FilterDAT)."""
117 cue_members = [m for m in members if m.filename.lower().endswith(".cue")]
118 return cue_members[0] if cue_members else max(members, key=lambda m: m.file_size)
121def _zip_identity(path: Path) -> ZipIdentity | None:
122 """Read ZIP central-dir to build a ``ZipIdentity`` (no extraction)."""
123 try:
124 with zipfile.ZipFile(path, "r") as zf:
125 members = zf.infolist()
126 if not members:
127 return None
128 dominant = _dominant_member(members)
129 return ZipIdentity(
130 member_crc32=dominant.CRC,
131 member_size=dominant.file_size,
132 member_name=dominant.filename,
133 )
134 except (zipfile.BadZipFile, OSError) as exc:
135 logger.debug("_zip_identity(%s): %s", path, exc)
136 return None
139def _md5_and_identity_from_zip(path: Path) -> tuple[str | None, ZipIdentity | None]:
140 """One zip open: MD5 of the dominant member plus its ``ZipIdentity``."""
141 try:
142 with zipfile.ZipFile(path, "r") as zf:
143 members = zf.infolist()
144 if not members:
145 return None, None
146 dominant = _dominant_member(members)
147 zip_id = ZipIdentity(
148 member_crc32=dominant.CRC,
149 member_size=dominant.file_size,
150 member_name=dominant.filename,
151 )
152 h = hashlib.md5()
153 with zf.open(dominant) as fh:
154 for chunk in iter(lambda: fh.read(1 << 20), b""):
155 h.update(chunk)
156 return h.hexdigest(), zip_id
157 except (zipfile.BadZipFile, OSError, KeyError) as exc:
158 logger.debug("_md5_and_identity_from_zip(%s): %s", path, exc)
159 return None, None
162def _md5_from_zip(path: Path) -> str | None:
163 """Compute MD5 of the dominant member of a ZIP."""
164 return _md5_and_identity_from_zip(path)[0]
167# ---------------------------------------------------------------------------
168# CatalogBuilder
169# ---------------------------------------------------------------------------
172class CatalogBuilder:
173 """Scans a source directory and builds a typed ``Catalog``.
175 Usage::
177 builder = CatalogBuilder(
178 platform=PlatformId("psx"),
179 source_dir=Path("/roms/psx"),
180 knowledge_base=kb,
181 )
182 catalog = builder.build()
184 Args:
185 platform: Platform identifier (e.g. ``"psx"``).
186 source_dir: Directory containing the source ROM files (ZIPs or raw).
187 knowledge_base: Read-only metadata facade. Used to enrich GameUnits
188 with rating / tier / generation fields.
189 dat_file: Optional parsed DAT file for canonical name resolution.
190 md5_cache: Pre-populated {Path → md5} map (e.g. from the ActionCache
191 or the metadata DB). Avoids re-hashing known files.
192 file_digest_cache: Optional ``FileDigestCache`` instance. When
193 provided, ``(size, mtime_ns, inode)`` triples are checked before
194 computing MD5s. Unchanged files are served from cache; newly
195 computed values are stored back. ``None`` disables the cache.
196 max_workers: Thread pool size for parallel MD5 computation.
197 extensions: File extensions to scan. Defaults to a broad ROM set.
198 """
200 _DEFAULT_EXTENSIONS: frozenset[str] = frozenset(
201 {
202 ".zip",
203 ".7z",
204 ".iso",
205 ".bin",
206 ".cue",
207 ".img",
208 ".chd",
209 ".rvz",
210 ".wbfs",
211 ".gcm",
212 ".xiso",
213 ".wux",
214 ".nes",
215 ".sfc",
216 ".smc",
217 ".gb",
218 ".gbc",
219 ".gba",
220 ".nds",
221 ".3ds",
222 ".nsp",
223 ".xci",
224 ".rom",
225 ".a26",
226 ".a52",
227 ".lnx",
228 }
229 )
231 def __init__(
232 self,
233 platform: PlatformId,
234 source_dir: Path,
235 knowledge_base: KnowledgeBase,
236 dat_file: object | None = None,
237 md5_cache: dict[Path, str] | None = None,
238 file_digest_cache: FileDigestCache | None = None,
239 max_workers: int = 4,
240 extensions: frozenset[str] | None = None,
241 source_dirs: tuple[tuple[Path, bool], ...] | None = None,
242 ) -> None:
243 self._platform = platform
244 self._source_dir = source_dir
245 # (dir, recursive) pairs; defaults to the single non-recursive source_dir
246 self._source_dirs: tuple[tuple[Path, bool], ...] = source_dirs or ((source_dir, False),)
247 self._kb = knowledge_base
248 self._dat_file = dat_file
249 self._md5_cache: dict[Path, str] = dict(md5_cache or {})
250 self._file_digest_cache = file_digest_cache
251 self._max_workers = max_workers
252 self._extensions = extensions or self._DEFAULT_EXTENSIONS
253 # Dominant zip member per path, filled alongside md5s (one zip read per file)
254 self._zip_ids: dict[Path, ZipIdentity] = {}
255 self._matcher: object | None = None
257 # ------------------------------------------------------------------
258 # Public
259 # ------------------------------------------------------------------
261 def build(self) -> Catalog:
262 """Scan the source directory and return an immutable ``Catalog``."""
263 source_files = self._discover_files()
264 if not source_files:
265 logger.debug(
266 "CatalogBuilder(%s): no files found in %s", self._platform, self._source_dir
267 )
268 return Catalog(platform=self._platform, units=(), warnings=())
270 # Cheap identity first (zip central directory), DAT match by name/CRC,
271 # and MD5 only for files that still have no DAT match.
272 self._populate_zip_ids(source_files)
273 matcher = self._dat_matcher()
274 dat_names: dict[Path, str | None] = {}
275 for path in source_files:
276 dat_names[path] = self._dat_name_for(path, self._identity_for(path), matcher)
277 unmatched = [
278 p
279 for p in source_files
280 if dat_names[p] is None
281 and p not in self._md5_cache
282 and not self._crc_decided(p, matcher)
283 ]
284 if matcher is not None and unmatched and self._md5_can_match(matcher, unmatched):
285 logger.debug("CatalogBuilder: hashing %d unmatched files for MD5 match", len(unmatched))
286 self._populate_md5s(unmatched)
287 for path in unmatched:
288 dat_names[path] = self._dat_name_for(path, self._identity_for(path), matcher)
289 elif matcher is None:
290 self._populate_md5s(source_files)
292 # Build DiscRef per file
293 disc_refs: list[tuple[str, DiscRef]] = []
294 for path in source_files:
295 canonical = _strip_disc_tag(path.stem)
296 disc_idx = _disc_index(path.stem)
297 identity = self._identity_for(path)
298 dat_name = dat_names[path]
299 source_ref = SourceRef(path=path, platform=self._platform)
300 disc_refs.append(
301 (
302 canonical,
303 DiscRef(
304 index=disc_idx,
305 source=source_ref,
306 identity=identity,
307 dat_name=dat_name,
308 ),
309 )
310 )
312 # Group into multi-disc sets
313 groups: dict[str, list[DiscRef]] = defaultdict(list)
314 for canonical, disc_ref in disc_refs:
315 groups[canonical].append(disc_ref)
317 # Build GameUnits, collect warnings
318 units: list[GameUnit] = []
319 warnings: list[CatalogWarning] = []
321 for canonical, discs in groups.items():
322 # Sort by index
323 sorted_discs = sorted(discs, key=lambda d: d.index)
324 indices = [d.index for d in sorted_discs]
326 # Check for non-contiguous indices (quarantine warning)
327 if len(indices) > 1:
328 expected = list(range(1, len(indices) + 1))
329 if indices != expected:
330 warnings.append(
331 CatalogWarning(
332 unit_key=canonical,
333 reason=f"non-contiguous disc set: {indices}",
334 )
335 )
337 # Derive metadata from the first disc's filename (stable)
338 sample_path = sorted_discs[0].source.path
339 regions = _parse_regions(sample_path.stem)
340 languages = _parse_languages(sample_path.stem)
342 # Enrich from KnowledgeBase
343 rating = self._kb.get_rating(str(self._platform), canonical)
345 unit = GameUnit(
346 unit_id=UnitId(hashlib.sha1(f"{self._platform}:{canonical}".encode()).hexdigest()),
347 platform=self._platform,
348 canonical_name=canonical,
349 discs=tuple(sorted_discs),
350 region=regions,
351 languages=languages,
352 rating=rating,
353 )
354 units.append(unit)
356 logger.info(
357 "CatalogBuilder(%s): %d units (%d files, %d warnings)",
358 self._platform,
359 len(units),
360 len(source_files),
361 len(warnings),
362 )
363 return Catalog(
364 platform=self._platform,
365 units=tuple(units),
366 warnings=tuple(warnings),
367 )
369 # ------------------------------------------------------------------
370 # Private
371 # ------------------------------------------------------------------
373 # ------------------------------------------------------------------
374 # Per-file helpers
375 # ------------------------------------------------------------------
377 def _identity_for(self, path: Path) -> Identity:
378 """Build a partial ``Identity`` for *path* without re-reading the zip."""
379 size = path.stat().st_size if path.exists() else None
380 md5 = self._md5_cache.get(path)
381 if path.suffix.lower() == ".zip":
382 zip_id = self._zip_ids.get(path)
383 if zip_id is None:
384 zip_id = _zip_identity(path)
385 if zip_id is not None:
386 self._zip_ids[path] = zip_id
387 return Identity(size=size, md5=md5, zip_identity=zip_id)
388 return Identity(size=size, md5=md5)
390 def _dat_matcher(self) -> object | None:
391 if self._dat_file is None:
392 return None
393 if self._matcher is None:
394 from romfarmer.dat_parser import ROMMatcher
396 self._matcher = ROMMatcher(self._dat_file) # type: ignore[arg-type]
397 return self._matcher
399 def _crc_decided(self, path: Path, matcher: object | None) -> bool:
400 """A zip member whose CRC32 missed a DAT that carries CRC32s is settled:
401 MD5 of the same bytes cannot match either."""
402 if matcher is None or not getattr(matcher, "crc_index", None):
403 return False
404 zid = self._zip_ids.get(path)
405 return zid is not None and bool(zid.member_crc32)
407 def _md5_can_match(self, matcher: object, files: list[Path]) -> bool:
408 """Is hashing worth it? Only if the DAT has MD5s *and* the files are the
409 same byte format the DAT describes.
411 Redump DATs hash the .iso; Myrient's GameCube/Wii sets ship .rvz (a
412 different byte stream), so no MD5 can ever match and hashing 1.5 TB
413 would be pure waste. Compare the dominant member's extension against
414 the DAT's ROM extensions.
415 """
416 md5_index = getattr(matcher, "md5_index", None)
417 if not md5_index:
418 return False
419 dat_exts = {Path(name).suffix.lower() for name in getattr(matcher, "rom_name_index", {})}
420 if not dat_exts:
421 return True
422 sample = files[:50]
423 for path in sample:
424 ext = path.suffix.lower()
425 if ext == ".zip":
426 zid = self._zip_ids.get(path) or _zip_identity(path)
427 ext = Path(zid.member_name).suffix.lower() if zid else ext
428 if ext in dat_exts:
429 return True
430 return False
432 def _dat_name_for(self, path: Path, identity: Identity, matcher: object | None) -> str | None:
433 """Canonical DAT name for *path*; ``None`` if unmatched.
435 Order: set/file name, then the zip member's CRC32 (free — central
436 directory), then MD5 if one is already known. Name first because
437 arcade sets share ROM chunks across parent/clone/bootleg zips — a
438 chunk hash would attribute the zip to whichever set the DAT listed
439 first. MD5 is computed lazily by ``build()`` only for files no other
440 rule matched.
441 """
442 if matcher is None:
443 return None
444 try:
445 if identity.zip_identity is not None:
446 result = matcher.match_zip_member( # type: ignore[attr-defined]
447 path, identity.zip_identity.member_name
448 )
449 else:
450 result = matcher.match_file(path) # type: ignore[attr-defined]
451 if result is not None and getattr(result, "dat_game", None) is not None:
452 return str(result.dat_game.name)
453 if identity.zip_identity is not None and identity.zip_identity.member_crc32:
454 crc = f"{identity.zip_identity.member_crc32:08x}"
455 result = matcher.match_by_hash(path, crc=crc) # type: ignore[attr-defined]
456 if result is not None and getattr(result, "dat_game", None) is not None:
457 return str(result.dat_game.name)
458 if identity.md5:
459 result = matcher.match_by_hash(path, md5=identity.md5) # type: ignore[attr-defined]
460 if result is not None and getattr(result, "dat_game", None) is not None:
461 return str(result.dat_game.name)
462 return None
463 except Exception as exc:
464 logger.debug("_dat_name_for(%s): %s", path, exc)
465 return None
467 def _discover_files(self) -> list[Path]:
468 """Return sorted list of ROM files across all source directories."""
469 files: list[Path] = []
470 for src_dir, recursive in self._source_dirs:
471 if not src_dir.exists():
472 logger.warning("CatalogBuilder: source_dir does not exist: %s", src_dir)
473 continue
474 it = src_dir.rglob("*") if recursive else src_dir.iterdir()
475 files.extend(p for p in it if p.is_file() and p.suffix.lower() in self._extensions)
476 return sorted(files)
478 def _populate_zip_ids(self, files: list[Path]) -> None:
479 """Fill ``_zip_ids`` (and any cached md5) from the digest cache or the zip central dir."""
480 scan_start_ns = time.time_ns()
481 for path in files:
482 if path.suffix.lower() != ".zip" or path in self._zip_ids:
483 continue
484 stat = None
485 if self._file_digest_cache is not None:
486 try:
487 stat = path.stat()
488 entry = self._file_digest_cache.lookup_entry(path, stat, scan_start_ns)
489 except OSError:
490 entry = None
491 if entry is not None and entry.member_name is not None:
492 self._zip_ids[path] = ZipIdentity(
493 member_crc32=int(entry.member_crc32 or 0),
494 member_size=int(entry.member_size or 0),
495 member_name=entry.member_name,
496 )
497 if entry.md5 and path not in self._md5_cache:
498 self._md5_cache[path] = entry.md5
499 continue
500 zip_id = _zip_identity(path)
501 if zip_id is None:
502 continue
503 self._zip_ids[path] = zip_id
504 if self._file_digest_cache is not None and stat is not None:
505 self._file_digest_cache.store(
506 path,
507 stat,
508 self._md5_cache.get(path),
509 (zip_id.member_name, zip_id.member_crc32, zip_id.member_size),
510 )
512 def _populate_md5s(self, files: list[Path]) -> None:
513 """Fill ``_md5_cache`` (and ``_zip_ids``) for files not already present."""
514 # Paths with a preloaded md5 only need their zip identity (cheap, no hashing)
515 for f in files:
516 if f in self._md5_cache and f not in self._zip_ids and f.suffix.lower() == ".zip":
517 zip_id = _zip_identity(f)
518 if zip_id is not None:
519 self._zip_ids[f] = zip_id
520 missing = [f for f in files if f not in self._md5_cache]
521 if not missing:
522 return
524 # ── Fast-path: check FileDigestCache before hashing ───────────
525 scan_start_ns = time.time_ns()
526 if self._file_digest_cache is not None:
527 still_missing: list[Path] = []
528 for path in missing:
529 try:
530 stat = path.stat()
531 entry = self._file_digest_cache.lookup_entry(path, stat, scan_start_ns)
532 is_zip = path.suffix.lower() == ".zip"
533 # A zip entry is only complete if the member triple was stored too
534 if entry is None or entry.md5 is None or (is_zip and entry.member_name is None):
535 still_missing.append(path)
536 continue
537 self._md5_cache[path] = entry.md5
538 if is_zip:
539 self._zip_ids[path] = ZipIdentity(
540 member_crc32=int(entry.member_crc32 or 0),
541 member_size=int(entry.member_size or 0),
542 member_name=entry.member_name or "",
543 )
544 except OSError:
545 still_missing.append(path)
546 missing = still_missing
547 if not missing:
548 logger.debug(
549 "CatalogBuilder: all %d MD5s served from digest cache",
550 len(list(self._md5_cache)),
551 )
552 return
554 logger.debug("CatalogBuilder: computing MD5s for %d files", len(missing))
556 def _compute(path: Path) -> tuple[Path, str | None, ZipIdentity | None]:
557 if path.suffix.lower() == ".zip":
558 return (path, *_md5_and_identity_from_zip(path))
559 try:
560 h = hashlib.md5()
561 with open(path, "rb") as fh:
562 for chunk in iter(lambda: fh.read(65536), b""):
563 h.update(chunk)
564 return path, h.hexdigest(), None
565 except OSError:
566 return path, None, None
568 with ThreadPoolExecutor(max_workers=self._max_workers) as pool:
569 futures = {pool.submit(_compute, p): p for p in missing}
570 for future in as_completed(futures):
571 path, md5, zip_id = future.result()
572 if zip_id is not None:
573 self._zip_ids[path] = zip_id
574 if md5:
575 self._md5_cache[path] = md5
576 # Store back to digest cache
577 if self._file_digest_cache is not None:
578 try:
579 stat = path.stat()
580 member = (
581 (zip_id.member_name, zip_id.member_crc32, zip_id.member_size)
582 if zip_id is not None
583 else None
584 )
585 self._file_digest_cache.store(path, stat, md5, member)
586 except OSError:
587 pass