mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 14:28:54 -06:00
refactor: group scraper modules by subject
scraper/ held the platform scrapers next to three other subjects. The launcher readers move to scraper/launchers/ (their _launchers suffix dropped), the MAME and FBNeo hash scrapers and romset importers to scraper/arcade/, the DAT readers and dump catalog importers to scraper/dats/. The buildbot check is a freshness check and moves to freshness/buildbot.py. Every -m command, workflow job, schema description and page follows. The scraper discovery in scraper/__init__.py had no caller: the registry's scraper: field names the module, and the pages now say so.
This commit is contained in:
1 parent
4e01cff854
commit
e1bad01b82
130 files changed
+445
-414
No files matched your search
@@ -0,0 +1,4 @@
|
||||
"""DAT files and the dump catalogs read from them: the Logiqx, clrmamepro and
|
||||
-listxml readers, the No-Intro, Redump and TOSEC BIOS snapshots under
|
||||
provenance/, and the game catalogs under games/catalogs/.
|
||||
"""
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Import BIOS entries from a No-Intro or TOSEC DAT pack.
|
||||
|
||||
Dat-o-Matic blocks automated downloads and TOSEC ships yearly packs,
|
||||
so both are imported from a locally downloaded archive:
|
||||
|
||||
python -m scripts.scraper.dats.dat_pack_importer --source no-intro --pack lovepack.zip
|
||||
python -m scripts.scraper.dats.dat_pack_importer --source tosec --pack TOSEC-v2025-03-13.zip
|
||||
|
||||
No-Intro marks BIOS dumps with a "[BIOS]" game name prefix inside the
|
||||
system DATs. TOSEC groups firmware into dedicated DATs whose name
|
||||
contains "Firmware" or "BIOS". Only those entries are imported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from model.dumpcatalog import write_provenance_snapshot
|
||||
from .listxml import iter_dat_documents
|
||||
from .logiqx_parser import LogiqxDat, parse_logiqx
|
||||
|
||||
SOURCES = ("no-intro", "tosec")
|
||||
|
||||
|
||||
def _bios_entries(source: str, dat: LogiqxDat) -> list[dict]:
|
||||
"""Filter a parsed DAT down to its BIOS/firmware entries."""
|
||||
if source == "no-intro":
|
||||
roms = [r for r in dat.roms if r.game.startswith("[BIOS]")]
|
||||
else:
|
||||
dat_name = dat.name.casefold()
|
||||
if "firmware" not in dat_name and "bios" not in dat_name:
|
||||
return []
|
||||
roms = dat.roms
|
||||
return dat.provenance_entries(roms)
|
||||
|
||||
|
||||
def import_pack(source: str, pack: Path) -> tuple[dict, list[dict], int]:
|
||||
"""Import BIOS entries from a pack. Returns (dats, entries, skipped)."""
|
||||
dats = {}
|
||||
entries = []
|
||||
skipped = 0
|
||||
for _member, content in iter_dat_documents(pack):
|
||||
try:
|
||||
dat = parse_logiqx(content)
|
||||
except (ValueError, SyntaxError):
|
||||
skipped += 1
|
||||
continue
|
||||
dat_entries = _bios_entries(source, dat)
|
||||
if dat_entries:
|
||||
dats[dat.name] = dat.version
|
||||
entries.extend(dat_entries)
|
||||
return dats, entries, skipped
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Import BIOS provenance from a DAT pack")
|
||||
parser.add_argument(
|
||||
"--source", required=True, choices=SOURCES,
|
||||
help="catalog the pack comes from",
|
||||
)
|
||||
parser.add_argument("--pack", required=True, help="DAT pack (ZIP or directory)")
|
||||
parser.add_argument("--output", "-o", help="Snapshot output path")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Show imported entries")
|
||||
args = parser.parse_args()
|
||||
|
||||
pack = Path(args.pack)
|
||||
if not pack.exists():
|
||||
print(f"Error: pack '{pack}' not found", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
dats, entries, skipped = import_pack(args.source, pack)
|
||||
except zipfile.BadZipFile as e:
|
||||
print(f"Error: {pack} is not a valid ZIP archive: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if not entries:
|
||||
print(f"Error: no BIOS entries found in {pack}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if skipped:
|
||||
print(f" Skipped {skipped} non-Logiqx members")
|
||||
|
||||
if args.dry_run:
|
||||
for dat in sorted(dats):
|
||||
count = sum(1 for e in entries if e["dat"] == dat)
|
||||
print(f" {dat} ({dats[dat]}): {count} entries")
|
||||
print(f"\nTotal: {len(entries)} entries across {len(dats)} DATs")
|
||||
return 0
|
||||
|
||||
output = args.output or f"provenance/{args.source}.json"
|
||||
Path(output).parent.mkdir(parents=True, exist_ok=True)
|
||||
imported_at = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
written = write_provenance_snapshot(output, args.source, imported_at, dats, entries)
|
||||
status = "Written" if written else "Unchanged"
|
||||
print(f"{status} {output}: {len(entries)} entries from {len(dats)} DATs")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Parser for clrmamepro DAT format.
|
||||
|
||||
Parses files like libretro's System.dat which uses the format:
|
||||
game (
|
||||
name "System"
|
||||
comment "Platform Name"
|
||||
rom ( name filename size 12345 crc ABCD1234 md5 ... sha1 ... )
|
||||
)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatRom:
|
||||
"""A ROM entry from a DAT file."""
|
||||
|
||||
name: str
|
||||
size: int
|
||||
crc32: str
|
||||
md5: str
|
||||
sha1: str
|
||||
system: str # From the preceding comment line
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatMetadata:
|
||||
"""Metadata from a DAT file header."""
|
||||
|
||||
name: str = ""
|
||||
version: str = ""
|
||||
description: str = ""
|
||||
author: str = ""
|
||||
homepage: str = ""
|
||||
url: str = ""
|
||||
|
||||
|
||||
def parse_dat(content: str) -> list[DatRom]:
|
||||
"""Parse clrmamepro DAT content and return list of DatRom entries.
|
||||
|
||||
Handles:
|
||||
- Quoted filenames with spaces: name "7800 BIOS (U).rom"
|
||||
- Path filenames: name "pcsx2/bios/file.bin"
|
||||
- Unquoted filenames: name cpc464.rom
|
||||
- Inconsistent indentation (tabs vs spaces)
|
||||
"""
|
||||
roms = []
|
||||
current_system = ""
|
||||
|
||||
for line in content.split("\n"):
|
||||
stripped = line.strip()
|
||||
|
||||
if stripped.startswith("comment "):
|
||||
value = stripped[8:].strip().strip('"')
|
||||
if value in (
|
||||
"System",
|
||||
"System, firmware, and BIOS files used by libretro cores.",
|
||||
):
|
||||
continue
|
||||
current_system = value
|
||||
|
||||
elif stripped.startswith(("rom (", "rom(")):
|
||||
rom = _parse_rom_line(stripped, current_system)
|
||||
if rom:
|
||||
roms.append(rom)
|
||||
|
||||
return roms
|
||||
|
||||
|
||||
def parse_dat_metadata(content: str) -> DatMetadata:
|
||||
"""Extract metadata from the clrmamepro header block."""
|
||||
meta = DatMetadata()
|
||||
in_header = False
|
||||
|
||||
for line in content.split("\n"):
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("clrmamepro"):
|
||||
in_header = True
|
||||
continue
|
||||
if in_header and stripped == ")":
|
||||
break
|
||||
if in_header:
|
||||
for field in (
|
||||
"name",
|
||||
"version",
|
||||
"description",
|
||||
"author",
|
||||
"homepage",
|
||||
"url",
|
||||
):
|
||||
if stripped.startswith(f"{field} "):
|
||||
value = stripped[len(field) + 1 :].strip().strip('"')
|
||||
setattr(meta, field, value)
|
||||
|
||||
return meta
|
||||
|
||||
|
||||
def _parse_rom_line(line: str, system: str) -> DatRom | None:
|
||||
"""Parse a single rom ( ... ) line."""
|
||||
# rfind because filenames may contain parentheses like "(E).rom"
|
||||
start = line.find("(")
|
||||
end = line.rfind(")")
|
||||
if start == -1 or end == -1 or end <= start:
|
||||
return None
|
||||
|
||||
content = line[start + 1 : end].strip()
|
||||
|
||||
fields = {}
|
||||
i = 0
|
||||
tokens = _tokenize(content)
|
||||
|
||||
while i < len(tokens) - 1:
|
||||
key = tokens[i]
|
||||
value = tokens[i + 1]
|
||||
fields[key] = value
|
||||
i += 2
|
||||
|
||||
name = fields.get("name", "")
|
||||
if not name:
|
||||
return None
|
||||
|
||||
try:
|
||||
size = int(fields.get("size", "0"))
|
||||
except ValueError:
|
||||
size = 0
|
||||
|
||||
return DatRom(
|
||||
name=name,
|
||||
size=size,
|
||||
crc32=fields.get("crc", "").lower(),
|
||||
md5=fields.get("md5", ""),
|
||||
sha1=fields.get("sha1", ""),
|
||||
system=system,
|
||||
)
|
||||
|
||||
|
||||
def _tokenize(content: str) -> list[str]:
|
||||
"""Tokenize DAT content, handling quoted strings."""
|
||||
tokens = []
|
||||
i = 0
|
||||
while i < len(content):
|
||||
while i < len(content) and content[i] in (" ", "\t"):
|
||||
i += 1
|
||||
if i >= len(content):
|
||||
break
|
||||
|
||||
if content[i] == '"':
|
||||
i += 1
|
||||
start = i
|
||||
while i < len(content) and content[i] != '"':
|
||||
i += 1
|
||||
tokens.append(content[start:i])
|
||||
i += 1
|
||||
else:
|
||||
start = i
|
||||
while i < len(content) and content[i] not in (" ", "\t"):
|
||||
i += 1
|
||||
tokens.append(content[start:i])
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def validate_dat_format(content: str) -> bool:
|
||||
"""Validate that content is a valid clrmamepro DAT file.
|
||||
|
||||
Checks for:
|
||||
- clrmamepro header
|
||||
- game block
|
||||
- rom entries
|
||||
"""
|
||||
has_header = "clrmamepro" in content[:500]
|
||||
has_game = "game (" in content
|
||||
has_rom = "rom (" in content or "rom(" in content
|
||||
has_comment = 'comment "' in content
|
||||
|
||||
return has_header and has_game and has_rom and has_comment
|
||||
@@ -0,0 +1,466 @@
|
||||
"""Import game catalogs from No-Intro and Redump DATs, one file per system.
|
||||
|
||||
The games-on-card mode identifies a game from its bytes: a cartridge by the
|
||||
crc32 and size a ZIP central directory gives without inflating, a disc by
|
||||
the first data track or the serial its header carries. These catalogs hold
|
||||
those keys with the title and the territory the DAT names the game for.
|
||||
They are game catalogues, not dump catalogues of BIOS files, so they live in
|
||||
games/catalogs/ and never in provenance/.
|
||||
|
||||
python -m scripts.scraper.dats.game_dat_importer --fetch
|
||||
python -m scripts.scraper.dats.game_dat_importer --fetch --source redump
|
||||
python -m scripts.scraper.dats.game_dat_importer --offline --floor
|
||||
python -m scripts.scraper.dats.game_dat_importer --source no-intro --pack no-intro.zip
|
||||
|
||||
No-Intro comes from the auto-datfile-generator release asset (Dat-o-Matic
|
||||
bans automated clients), Redump from redump.info's per-system datfile route.
|
||||
The mirror is dantob's fork: hugo19941994's original has failed its daily
|
||||
rebuild since Dat-o-Matic's 2026-07 re-layout (no-intro.zip last rebuilt
|
||||
2026-07-08), and the fork carries the fix (d4a9d769, 2026-07-31).
|
||||
Every download is cached under .cache/game-dats/ with what the server said
|
||||
about it, so a second run reads nothing from the network and writes the same
|
||||
bytes. A DAT's region tag is a market label, never the value a core computes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_if_changed, write_text_atomic
|
||||
from model.region import REGIONS, WORLD
|
||||
from model.region import NOINTRO
|
||||
|
||||
from ..base_scraper import download, github_json
|
||||
from .listxml import iter_dat_documents
|
||||
from .logiqx_parser import LogiqxGame, LogiqxRom, parse_logiqx_games
|
||||
|
||||
SOURCES = ("no-intro", "redump")
|
||||
CACHE_DIR = Path(".cache") / "game-dats"
|
||||
OUTPUT_DIR = Path("games") / "catalogs"
|
||||
|
||||
NOINTRO_MIRROR = "https://github.com/dantob/auto-datfile-generator"
|
||||
NOINTRO_RELEASE = "Daily_Rebuild"
|
||||
NOINTRO_RELEASE_API = (
|
||||
NOINTRO_MIRROR.replace("https://github.com/", "https://api.github.com/repos/")
|
||||
+ f"/releases/tags/{NOINTRO_RELEASE}"
|
||||
)
|
||||
NOINTRO_ASSET = "no-intro.zip"
|
||||
REDUMP_DATFILE_URL = "https://redump.info/datfile/{code}"
|
||||
|
||||
# DAT header name -> (repository system id, floor). The floor is the least
|
||||
# number of games the DAT may hold before an import is refused as truncated:
|
||||
# 95 % of the count read on 2026-11-03, rounded down.
|
||||
NOINTRO_DATS: dict[str, tuple[str, int]] = {
|
||||
"Nintendo - Super Nintendo Entertainment System": ("nintendo-snes", 3920),
|
||||
"Nintendo - Game Boy": ("nintendo-gb", 1897),
|
||||
"Nintendo - Game Boy Color": ("nintendo-gbc", 1935),
|
||||
"Nintendo - Game Boy Advance": ("nintendo-gba", 3356),
|
||||
"Nintendo - Nintendo 64 (BigEndian)": ("nintendo-64", 1098),
|
||||
"Sega - Mega Drive - Genesis": ("sega-megadrive", 2718),
|
||||
"Nintendo - Nintendo Entertainment System (Headered)": ("nintendo-nes", 4276),
|
||||
"Nintendo - Nintendo DS (Decrypted)": ("nintendo-ds", 7289),
|
||||
"NEC - PC Engine - TurboGrafx-16": ("nec-pc-engine", 438),
|
||||
"Sega - Master System - Mark III": ("sega-mastersystem", 665),
|
||||
"Sega - Game Gear": ("sega-gamegear", 786),
|
||||
"Atari - Atari Lynx (LNX)": ("atari-lynx", 17),
|
||||
"Nintendo - Nintendo 64DD": ("nintendo-64dd", 33),
|
||||
"Nintendo - Family Computer Disk System (FDS)": ("nintendo-fds", 384),
|
||||
"Nintendo - Pokemon Mini": ("nintendo-pokemon-mini", 41),
|
||||
"Atari - Atari 7800 (A78)": ("atari-7800", 7),
|
||||
"Atari - Atari 5200": ("atari-5200", 197),
|
||||
"Mattel - Intellivision": ("intellivision", 197),
|
||||
"Coleco - ColecoVision": ("colecovision", 190),
|
||||
"Magnavox - Odyssey 2": ("odyssey2", 126),
|
||||
"GCE - Vectrex": ("vectrex", 45),
|
||||
"Nintendo - Satellaview": ("nintendo-satellaview", 570),
|
||||
"Nintendo - Sufami Turbo": ("nintendo-sufami-turbo", 12),
|
||||
"NEC - PC Engine SuperGrafx": ("nec-supergrafx", 4),
|
||||
"Sega - 32X": ("sega-32x", 202),
|
||||
"Bandai - WonderSwan": ("wonderswan", 244),
|
||||
"Bandai - WonderSwan Color": ("wonderswan-color", 229),
|
||||
"SNK - NeoGeo Pocket": ("snk-ngp", 12),
|
||||
"SNK - NeoGeo Pocket Color": ("snk-ngpc", 121),
|
||||
}
|
||||
|
||||
# redump.info datfile code -> (DAT header name, repository system id, floor).
|
||||
REDUMP_DATS: dict[str, tuple[str, str, int]] = {
|
||||
"PSX": ("Sony - PlayStation", "sony-playstation", 10432),
|
||||
"PS2": ("Sony - PlayStation 2", "sony-playstation-2", 11252),
|
||||
"SS": ("Sega - Saturn", "sega-saturn", 2340),
|
||||
"MCD": ("Sega - Mega CD & Sega CD", "sega-megacd", 521),
|
||||
"DC": ("Sega - Dreamcast", "sega-dreamcast", 1442),
|
||||
"GC": ("Nintendo - GameCube", "nintendo-gamecube", 1920),
|
||||
"PCE": ("NEC - PC Engine CD & TurboGrafx CD", "nec-pc-engine-cd", 523),
|
||||
"NGCD": ("SNK - Neo Geo CD", "snk-neogeo-cd", 107),
|
||||
"3DO": ("3DO Interactive Multiplayer", "panasonic-3do", 635),
|
||||
}
|
||||
|
||||
TERMS_READ = "2026-11-03"
|
||||
LICENCES: dict[str, dict] = {
|
||||
"no-intro": {
|
||||
"terms_url": "https://datomatic.no-intro.org/terms.html",
|
||||
"terms_title": "Data Usage License",
|
||||
"terms_updated": "2026-09-11",
|
||||
"read": TERMS_READ,
|
||||
"quote": (
|
||||
'Unless otherwise stated on the website, the data made available through '
|
||||
'this website ("Data") may be freely used, copied, reproduced, modified, '
|
||||
"adapted, combined, published, distributed, and otherwise reused by anyone "
|
||||
"for any lawful purpose, to the extent that the website operator owns or "
|
||||
"controls the applicable rights or is authorized to grant such permission. "
|
||||
"No permission, attribution, citation, backlink, or acknowledgment of the "
|
||||
"website or its operators is required for such use."
|
||||
),
|
||||
"mirror": {
|
||||
"repo": NOINTRO_MIRROR,
|
||||
"licence": "MIT",
|
||||
"scope": "the mirror's scripts only, the DATs it republishes stay under the terms above",
|
||||
},
|
||||
},
|
||||
"redump": {
|
||||
"terms_url": "https://redump.info/about",
|
||||
"read": TERMS_READ,
|
||||
"quote": (
|
||||
"Dumpers only submit metadata and Redump only stores metadata. This "
|
||||
"information is considered public domain to be used however people see fit"
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
# Territory words the DATs use that scripts/model/region.py has no member slug
|
||||
# for. Each falls under the one super-region that contains it.
|
||||
EXTRA_TERRITORIES = {
|
||||
"Scandinavia": "europe",
|
||||
"Belgium": "europe",
|
||||
"Switzerland": "europe",
|
||||
"Austria": "europe",
|
||||
"Ireland": "europe",
|
||||
"United Kingdom": "uk",
|
||||
}
|
||||
_TERRITORY = {**{k: v for k, v in NOINTRO.items()}, **EXTRA_TERRITORIES}
|
||||
# A territory word with no slug: the group is a territory tag, but the
|
||||
# catalog cannot name it and records no region.
|
||||
_UNMAPPED_TERRITORIES = {"South Africa"}
|
||||
|
||||
SERIAL_NOTE = (
|
||||
"Serials are written as the DAT writes them, and the DAT uses both forms: "
|
||||
"'SLES-01971' and 'SLPS 02251' in the PlayStation DAT of the same day. A "
|
||||
"core reads the serial from the disc in its own spelling (SYSTEM.CNF holds "
|
||||
"'SLPS_022.51', DuckStation reports 'SLPS-02251'). No source fixes a rule "
|
||||
"joining the two, so the comparison rule is the reader's to state."
|
||||
)
|
||||
|
||||
_PAREN = re.compile(r"\(([^)]+)\)")
|
||||
_NOINTRO_MEMBER = re.compile(r"^(?P<name>.+) \((?P<version>\d{8}-\d{6})\)\.dat$")
|
||||
DISPOSITION = re.compile(r'filename="(?P<file>[^"]+)"')
|
||||
REDUMP_FILE = re.compile(
|
||||
r"^(?P<name>.+) - Datfile \((?P<count>\d+)\) \((?P<date>\d{4}-\d{2}-\d{2}) (?P<time>[\d-]+)\)\.(?:zip|dat)$"
|
||||
)
|
||||
|
||||
|
||||
def datfile_name(disposition: str) -> str | None:
|
||||
"""The file name a redump.info Content-Disposition header gives a datfile."""
|
||||
match = DISPOSITION.search(disposition)
|
||||
return match["file"] if match else None
|
||||
|
||||
|
||||
def served_version(file: str) -> str:
|
||||
"""The version redump.info stamps in a datfile name, empty for another name.
|
||||
|
||||
The import records the name, and the freshness check reads the name the
|
||||
server gives now: both sides compare this stamp, never the DAT header.
|
||||
"""
|
||||
match = REDUMP_FILE.match(file)
|
||||
return f"{match['date']} {match['time']}" if match else ""
|
||||
|
||||
|
||||
def name_regions(name: str) -> list[str] | None:
|
||||
"""Region slugs of the first parenthesised group made only of territory
|
||||
words, or None when the name carries no such group or a word the
|
||||
vocabulary cannot name."""
|
||||
for group in _PAREN.findall(name):
|
||||
words = [w.strip() for w in group.split(",")]
|
||||
if not words or not all(w in _TERRITORY or w in _UNMAPPED_TERRITORIES for w in words):
|
||||
continue
|
||||
if any(w in _UNMAPPED_TERRITORIES for w in words):
|
||||
return None
|
||||
slugs = sorted({_TERRITORY[w] for w in words})
|
||||
if WORLD in slugs:
|
||||
return [WORLD]
|
||||
unknown = set(slugs) - REGIONS
|
||||
if unknown:
|
||||
raise ValueError(f"region slugs {sorted(unknown)} are outside scripts/model/region.py")
|
||||
return slugs
|
||||
return None
|
||||
|
||||
|
||||
def _first_data_track(roms: list[LogiqxRom]) -> LogiqxRom | None:
|
||||
for rom in roms:
|
||||
if rom.name.lower().endswith((".cue", ".gdi")) or not rom.crc32:
|
||||
continue
|
||||
return rom
|
||||
return None
|
||||
|
||||
|
||||
def build_catalog(source: str, system: str, dat_name: str, version: str,
|
||||
games: list[LogiqxGame], origin: dict) -> dict:
|
||||
"""The catalog document of one DAT."""
|
||||
region_ids: dict[tuple[str, ...], int] = {}
|
||||
rows: list[list] = []
|
||||
for game in games:
|
||||
regions = name_regions(game.name)
|
||||
index = None
|
||||
if regions is not None:
|
||||
index = region_ids.setdefault(tuple(regions), len(region_ids))
|
||||
if source == "redump":
|
||||
track = _first_data_track(game.roms)
|
||||
if track is None:
|
||||
continue
|
||||
rows.append([track.crc32, track.size, track.sha1, index, game.name,
|
||||
sorted(game.serials)])
|
||||
else:
|
||||
rows.extend([rom.crc32, rom.size, rom.sha1, index, game.name]
|
||||
for rom in game.roms if rom.crc32)
|
||||
# Region ids are renumbered in sorted order so the table does not depend
|
||||
# on the DAT's game order.
|
||||
order = sorted(region_ids, key=lambda r: (len(r), r))
|
||||
renumber = {region_ids[r]: i for i, r in enumerate(order)}
|
||||
for row in rows:
|
||||
if row[3] is not None:
|
||||
row[3] = renumber[row[3]]
|
||||
rows.sort(key=lambda r: (r[0], r[1], r[2], r[4]))
|
||||
fields = ["crc32", "size", "sha1", "region", "title"]
|
||||
doc = {
|
||||
"source": source,
|
||||
"system": system,
|
||||
"dat": dat_name,
|
||||
"version": version,
|
||||
**origin,
|
||||
"licence": LICENCES[source],
|
||||
"fields": fields + (["serials"] if source == "redump" else []),
|
||||
"regions": [list(r) for r in order],
|
||||
"games": rows,
|
||||
}
|
||||
if source == "redump":
|
||||
doc["serial_note"] = SERIAL_NOTE
|
||||
return doc
|
||||
|
||||
|
||||
def dump_catalog(doc: dict) -> str:
|
||||
"""Compact JSON, one game per line so a refresh diffs by game."""
|
||||
head = {k: v for k, v in doc.items() if k != "games"}
|
||||
text = json.dumps(head, ensure_ascii=False, separators=(",", ":"))[:-1]
|
||||
games = ",\n".join(json.dumps(g, ensure_ascii=False, separators=(",", ":")) for g in doc["games"])
|
||||
return f'{text},"games":[\n{games}\n]}}\n'
|
||||
|
||||
|
||||
# Fetching ---------------------------------------------------------------
|
||||
|
||||
|
||||
class NotCachedError(RuntimeError):
|
||||
"""An offline run asked for a download the cache does not hold."""
|
||||
|
||||
|
||||
def _today() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def fetch_nointro(cache_dir: Path, offline: bool, refresh: bool) -> tuple[Path, dict]:
|
||||
"""The No-Intro pack and what the release said about it."""
|
||||
meta_path = cache_dir / "no-intro.json"
|
||||
if meta_path.is_file() and not refresh:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
pack = cache_dir / meta["file"]
|
||||
if pack.is_file():
|
||||
return pack, meta
|
||||
if offline:
|
||||
raise NotCachedError(f"{meta_path} or its pack is not cached")
|
||||
release = github_json(NOINTRO_RELEASE_API, "cannot read the No-Intro release")
|
||||
asset = next(a for a in release["assets"] if a["name"] == NOINTRO_ASSET)
|
||||
stamp = asset["updated_at"].replace(":", "").replace("-", "")
|
||||
file = f"no-intro-{stamp}.zip"
|
||||
pack = cache_dir / file
|
||||
if not pack.is_file():
|
||||
download(asset["browser_download_url"], pack)
|
||||
if pack.stat().st_size != asset["size"]:
|
||||
pack.unlink()
|
||||
raise RuntimeError(f"{NOINTRO_ASSET}: size differs from the release's {asset['size']}")
|
||||
meta = {
|
||||
"file": file,
|
||||
"url": asset["browser_download_url"],
|
||||
"asset_updated_at": asset["updated_at"],
|
||||
"asset_size": asset["size"],
|
||||
"fetched": _today(),
|
||||
}
|
||||
write_text_atomic(str(meta_path), json.dumps(meta, indent=1) + "\n")
|
||||
return pack, meta
|
||||
|
||||
|
||||
def fetch_redump(code: str, cache_dir: Path, offline: bool, refresh: bool) -> tuple[Path, dict]:
|
||||
"""One redump.info datfile and the name its server gave it."""
|
||||
folder = cache_dir / "redump"
|
||||
meta_path = folder / f"{code}.json"
|
||||
pack = folder / f"{code}.zip"
|
||||
if meta_path.is_file() and pack.is_file() and not refresh:
|
||||
return pack, json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
if offline:
|
||||
raise NotCachedError(f"{pack} is not cached")
|
||||
url = REDUMP_DATFILE_URL.format(code=code)
|
||||
file = datfile_name(download(url, pack))
|
||||
if not file:
|
||||
raise RuntimeError(f"{url} answered without a datfile name")
|
||||
meta = {"file": file, "url": url, "fetched": _today()}
|
||||
write_text_atomic(str(meta_path), json.dumps(meta, indent=1) + "\n")
|
||||
return pack, meta
|
||||
|
||||
|
||||
# Reading packs ----------------------------------------------------------
|
||||
|
||||
|
||||
def import_nointro(pack: Path, meta: dict) -> list[dict]:
|
||||
docs = []
|
||||
for member, data in iter_dat_documents(pack, (".dat",)):
|
||||
match = _NOINTRO_MEMBER.match(member)
|
||||
name = match["name"] if match else None
|
||||
if name not in NOINTRO_DATS:
|
||||
# A member named without the version stamp is read for its header.
|
||||
if match:
|
||||
continue
|
||||
name = parse_logiqx_games(data)[0]
|
||||
if name not in NOINTRO_DATS:
|
||||
continue
|
||||
dat_name, version, games = parse_logiqx_games(data)
|
||||
origin = {
|
||||
"fetched_from": meta.get("url", ""),
|
||||
"fetched": meta.get("fetched", ""),
|
||||
"archive": {"member": member, "asset_updated_at": meta.get("asset_updated_at", "")},
|
||||
}
|
||||
docs.append(build_catalog("no-intro", NOINTRO_DATS[dat_name][0], dat_name, version,
|
||||
games, origin))
|
||||
return docs
|
||||
|
||||
|
||||
def import_redump(pack: Path, meta: dict) -> list[dict]:
|
||||
docs = []
|
||||
by_name = {name: (code, system) for code, (name, system, _) in REDUMP_DATS.items()}
|
||||
for member, data in iter_dat_documents(pack, (".dat",)):
|
||||
dat_name, version, games = parse_logiqx_games(data)
|
||||
if dat_name not in by_name:
|
||||
continue
|
||||
file = meta.get("file", member)
|
||||
stamp = REDUMP_FILE.match(file)
|
||||
origin = {
|
||||
"fetched_from": meta.get("url", ""),
|
||||
"fetched": meta.get("fetched", ""),
|
||||
"archive": {"member": member, "file": file,
|
||||
"dat_date": stamp["date"] if stamp else ""},
|
||||
}
|
||||
docs.append(build_catalog("redump", by_name[dat_name][1], dat_name, version,
|
||||
games, origin))
|
||||
return docs
|
||||
|
||||
|
||||
def coverage(doc: dict) -> dict:
|
||||
games = {row[4] for row in doc["games"]}
|
||||
out = {
|
||||
"system": doc["system"],
|
||||
"games": len(games),
|
||||
"rows": len(doc["games"]),
|
||||
"with_region": sum(1 for row in doc["games"] if row[3] is not None),
|
||||
}
|
||||
if doc["source"] == "redump":
|
||||
by_serial: dict[str, set] = {}
|
||||
for row in doc["games"]:
|
||||
for serial in row[5]:
|
||||
by_serial.setdefault(serial, set()).add(row[3])
|
||||
out["serials"] = len(by_serial)
|
||||
out["multi_region_serials"] = sum(1 for v in by_serial.values() if len(v) > 1)
|
||||
return out
|
||||
|
||||
|
||||
def floor_of(doc: dict) -> int:
|
||||
if doc["source"] == "no-intro":
|
||||
return NOINTRO_DATS[doc["dat"]][1]
|
||||
return next(f for name, _, f in REDUMP_DATS.values() if name == doc["dat"])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--source", choices=SOURCES, action="append",
|
||||
help="limit to one source (repeatable, default both)")
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument("--fetch", action="store_true", help="download what the cache lacks")
|
||||
mode.add_argument("--offline", action="store_true", help="read the cache only (default)")
|
||||
mode.add_argument("--pack", type=Path, help="import a local ZIP, directory or DAT")
|
||||
parser.add_argument("--refresh", action="store_true", help="ask the servers again")
|
||||
parser.add_argument("--floor", action="store_true",
|
||||
help="fail when a system holds fewer games than its stored floor")
|
||||
parser.add_argument("--cache-dir", type=Path, default=CACHE_DIR,
|
||||
help=f"downloaded packs (default {CACHE_DIR})")
|
||||
parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR,
|
||||
help=f"where the catalogs are written (default {OUTPUT_DIR})")
|
||||
parser.add_argument("--dry-run", action="store_true", help="print coverage, write nothing")
|
||||
args = parser.parse_args()
|
||||
|
||||
sources = args.source or list(SOURCES)
|
||||
if args.pack and len(sources) != 1:
|
||||
parser.error("--pack needs one --source")
|
||||
offline = not args.fetch
|
||||
docs: list[dict] = []
|
||||
try:
|
||||
for source in sources:
|
||||
if args.pack:
|
||||
meta = {"url": "", "fetched": ""}
|
||||
docs += (import_nointro if source == "no-intro" else import_redump)(args.pack, meta)
|
||||
elif source == "no-intro":
|
||||
pack, meta = fetch_nointro(args.cache_dir, offline, args.refresh)
|
||||
docs += import_nointro(pack, meta)
|
||||
else:
|
||||
for code in REDUMP_DATS:
|
||||
pack, meta = fetch_redump(code, args.cache_dir, offline, args.refresh)
|
||||
docs += import_redump(pack, meta)
|
||||
except (NotCachedError, OSError, RuntimeError, ValueError) as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
if isinstance(exc, NotCachedError):
|
||||
print("Run with --fetch to download it.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
expected = {(s, sid) for s in sources if not args.pack
|
||||
for sid in ([v[0] for v in NOINTRO_DATS.values()] if s == "no-intro"
|
||||
else [v[1] for v in REDUMP_DATS.values()])}
|
||||
missing = expected - {(d["source"], d["system"]) for d in docs}
|
||||
failures = [f"{s}/{sid}: DAT not in the pack" for s, sid in sorted(missing)]
|
||||
raw_total = gz_total = 0
|
||||
print(f"{'source':9} {'system':26} {'games':>6} {'rows':>6} {'region':>6} "
|
||||
f"{'serials':>7} {'multi':>5} {'raw':>9} {'gzip':>8}")
|
||||
for doc in sorted(docs, key=lambda d: (d["source"], d["system"])):
|
||||
text = dump_catalog(doc)
|
||||
raw = len(text.encode())
|
||||
gz = len(gzip.compress(text.encode(), compresslevel=9, mtime=0))
|
||||
raw_total += raw
|
||||
gz_total += gz
|
||||
cov = coverage(doc)
|
||||
print(f"{doc['source']:9} {doc['system']:26} {cov['games']:>6} {cov['rows']:>6} "
|
||||
f"{cov['with_region']:>6} {cov.get('serials', '-'):>7} "
|
||||
f"{cov.get('multi_region_serials', '-'):>5} {raw:>9} {gz:>8}")
|
||||
if args.floor and cov["games"] < floor_of(doc):
|
||||
failures.append(f"{doc['source']}/{doc['system']}: {cov['games']} games, "
|
||||
f"floor {floor_of(doc)}")
|
||||
if not args.dry_run:
|
||||
target = args.output_dir / doc["source"] / f"{doc['system']}.json"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_if_changed(str(target), text)
|
||||
print(f"{len(docs)} catalogs, {raw_total} bytes raw, {gz_total} bytes gzip")
|
||||
for failure in failures:
|
||||
print(f"FAIL {failure}", file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Streaming reader for MAME -listxml documents and Logiqx DATs.
|
||||
|
||||
The 0.289 listxml is 311 MB, so a document is read through a sliding window
|
||||
and never held whole. romset_dat_importer, mame_devices and
|
||||
arcade_parent_importer read elements, attributes and ROM members here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
from collections.abc import Callable, Collection, Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager
|
||||
from pathlib import Path
|
||||
from typing import IO, NamedTuple
|
||||
|
||||
LISTXML_CHUNK = 8 * 1024 * 1024
|
||||
# Longer than any start tag the documents write, shorter than any element.
|
||||
_TAG_TAIL = 4096
|
||||
|
||||
_ATTR = re.compile(rb'([\w:-]+)="([^"]*)"')
|
||||
_ROM = re.compile(rb"<rom\b([^>]*)>")
|
||||
|
||||
Opener = Callable[[], AbstractContextManager[IO[bytes]]]
|
||||
|
||||
|
||||
class Element(NamedTuple):
|
||||
tag: str
|
||||
attrs: dict[str, str]
|
||||
body: bytes
|
||||
|
||||
|
||||
def attrs(raw: bytes) -> dict[str, str]:
|
||||
"""Attributes of a start tag, entities decoded (``f&m.basic.bin``)."""
|
||||
return {
|
||||
key.decode(): html.unescape(value.decode())
|
||||
for key, value in _ATTR.findall(raw)
|
||||
}
|
||||
|
||||
|
||||
def iter_elements(
|
||||
stream: IO[bytes], tags: Collection[str] = ("machine",), head: bytes = b"",
|
||||
) -> Iterator[Element]:
|
||||
"""Every element named in *tags*, in document order.
|
||||
|
||||
Attributes come in any order (mame2003 writes ``<game runnable="no"
|
||||
name="neogeo">``). The window keeps the element still open from its start
|
||||
tag and grows until that element closes, whatever its size. *head* is
|
||||
what the caller already read from *stream*.
|
||||
"""
|
||||
element = re.compile(rb"<(" + b"|".join(t.encode() for t in tags) + rb")\b([^>]*)>")
|
||||
buffer = head
|
||||
while True:
|
||||
chunk = stream.read(LISTXML_CHUNK)
|
||||
buffer += chunk
|
||||
position = 0
|
||||
# Where the next read has to resume: the start of an element still
|
||||
# open, else a tail long enough to hold a start tag cut in two.
|
||||
keep_from = max(0, len(buffer) - _TAG_TAIL)
|
||||
while match := element.search(buffer, position):
|
||||
closing = b"</" + match.group(1) + b">"
|
||||
end = buffer.find(closing, match.end())
|
||||
if end == -1:
|
||||
keep_from = match.start()
|
||||
break
|
||||
yield Element(
|
||||
match.group(1).decode(), attrs(match.group(2)), buffer[match.end() : end]
|
||||
)
|
||||
position = end + len(closing)
|
||||
keep_from = max(position, len(buffer) - _TAG_TAIL)
|
||||
if not chunk:
|
||||
return
|
||||
buffer = buffer[keep_from:]
|
||||
|
||||
|
||||
def rom_members(
|
||||
body: bytes, dedupe: bool = False, extra: Collection[str] = (),
|
||||
) -> list[dict]:
|
||||
"""Dumped ROMs of one element: name, size, crc32, sha1.
|
||||
|
||||
A ROM without a crc is undumped and left out. *dedupe* keeps the first
|
||||
ROM of each name, as the loader does. *extra* names attributes copied
|
||||
when the ROM writes them.
|
||||
"""
|
||||
members: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
for match in _ROM.finditer(body):
|
||||
found = attrs(match.group(1))
|
||||
name, crc = found.get("name", ""), found.get("crc", "").lower()
|
||||
if not name or not crc or (dedupe and name in seen):
|
||||
continue
|
||||
seen.add(name)
|
||||
try:
|
||||
size = int(found.get("size", "0") or 0)
|
||||
except ValueError:
|
||||
size = 0
|
||||
member = {"name": name, "size": size, "crc32": crc, "sha1": found.get("sha1", "").lower()}
|
||||
member.update((key, found[key]) for key in extra if key in found)
|
||||
members.append(member)
|
||||
return members
|
||||
|
||||
|
||||
# A member past this is refused aloud rather than read into memory.
|
||||
MAX_DAT_MEMBER = 200 * 1024 * 1024
|
||||
|
||||
|
||||
def iter_dat_documents(
|
||||
pack: Path,
|
||||
suffixes: tuple[str, ...] = (".dat", ".xml"),
|
||||
max_member: int = MAX_DAT_MEMBER,
|
||||
) -> Iterator[tuple[str, bytes]]:
|
||||
"""(base name, bytes) of every DAT in a ZIP, a directory or a lone file.
|
||||
|
||||
A suffix matches in any case. A member past `max_member` is skipped and
|
||||
said on stderr: a DAT left out silently ended a run on "Unchanged" with
|
||||
a version missing.
|
||||
"""
|
||||
if pack.is_dir():
|
||||
for path in sorted(pack.rglob("*")):
|
||||
if path.suffix.lower() in suffixes and path.is_file():
|
||||
yield path.name, path.read_bytes()
|
||||
return
|
||||
if not zipfile.is_zipfile(pack):
|
||||
yield pack.name, pack.read_bytes()
|
||||
return
|
||||
with zipfile.ZipFile(pack) as archive:
|
||||
for info in sorted(archive.infolist(), key=lambda i: i.filename):
|
||||
if info.is_dir() or Path(info.filename).suffix.lower() not in suffixes:
|
||||
continue
|
||||
if info.file_size > max_member:
|
||||
print(
|
||||
f" Skipping {info.filename}: {info.file_size} bytes exceeds {max_member}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
yield Path(info.filename).name, archive.read(info)
|
||||
|
||||
|
||||
def xml_members(archive: zipfile.ZipFile) -> list[str]:
|
||||
return [n for n in archive.namelist() if n.lower().endswith(".xml")]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_listxml(path: Path) -> Iterator[IO[bytes]]:
|
||||
"""Byte stream over a -listxml document, plain or as MAME's release zip."""
|
||||
if path.suffix.lower() != ".zip":
|
||||
with path.open("rb") as stream:
|
||||
yield stream
|
||||
return
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = xml_members(archive)
|
||||
if len(names) != 1:
|
||||
raise ValueError(f"{path}: expected one .xml member, found {len(names)}")
|
||||
with archive.open(names[0]) as stream:
|
||||
yield stream
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Parser for Logiqx XML DAT format.
|
||||
|
||||
Parses files like No-Intro daily packs and TOSEC releases which use:
|
||||
<datafile>
|
||||
<header><name>...</name><version>...</version></header>
|
||||
<game name="[BIOS] Game Boy Advance (World)">
|
||||
<description>...</description>
|
||||
<rom name="..." size="16384" crc="..." md5="..." sha1="..."/>
|
||||
</game>
|
||||
</datafile>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from model.safeparse import parse_untrusted_xml
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogiqxRom:
|
||||
"""A ROM entry from a Logiqx DAT file."""
|
||||
|
||||
game: str
|
||||
description: str
|
||||
name: str
|
||||
size: int
|
||||
crc32: str
|
||||
md5: str
|
||||
sha1: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogiqxGame:
|
||||
"""A <game> or <machine> of a Logiqx DAT, its serials and named ROMs."""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
serials: list[str]
|
||||
roms: list[LogiqxRom]
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogiqxDat:
|
||||
"""A parsed Logiqx DAT file."""
|
||||
|
||||
name: str = ""
|
||||
version: str = ""
|
||||
roms: list[LogiqxRom] = field(default_factory=list)
|
||||
|
||||
def provenance_entries(self, roms: list[LogiqxRom] | None = None) -> list[dict]:
|
||||
"""The provenance snapshot form of the ROMs given, all of them by default."""
|
||||
return [
|
||||
{
|
||||
"dat": self.name,
|
||||
"name": rom.name,
|
||||
"description": rom.description,
|
||||
"size": rom.size,
|
||||
"crc32": rom.crc32,
|
||||
"md5": rom.md5,
|
||||
"sha1": rom.sha1,
|
||||
}
|
||||
for rom in (self.roms if roms is None else roms)
|
||||
]
|
||||
|
||||
|
||||
def parse_logiqx_games(content: str | bytes) -> tuple[str, str, list[LogiqxGame]]:
|
||||
"""Header name, version and games of Logiqx XML DAT content.
|
||||
|
||||
Handles both <game> and <machine> entries, and games with
|
||||
multiple <rom> children. A ROM without a name is left out. Content
|
||||
declaring XML entities is rejected: DAT files never define them, and
|
||||
expanding entities from untrusted packs opens entity-expansion attacks.
|
||||
"""
|
||||
root = parse_untrusted_xml(content, "DAT files")
|
||||
header = root.find("header")
|
||||
name = version = ""
|
||||
if header is not None:
|
||||
name = header.findtext("name", "").strip()
|
||||
version = header.findtext("version", "").strip()
|
||||
|
||||
games: list[LogiqxGame] = []
|
||||
for game in list(root.iter("game")) + list(root.iter("machine")):
|
||||
game_name = game.get("name", "")
|
||||
description = game.findtext("description", "").strip() or game_name
|
||||
serial = game.findtext("serial") or ""
|
||||
roms: list[LogiqxRom] = []
|
||||
for rom in game.iter("rom"):
|
||||
rom_name = rom.get("name", "")
|
||||
if not rom_name:
|
||||
continue
|
||||
try:
|
||||
size = int(rom.get("size", "0"))
|
||||
except ValueError:
|
||||
size = 0
|
||||
roms.append(
|
||||
LogiqxRom(
|
||||
game=game_name,
|
||||
description=description,
|
||||
name=rom_name,
|
||||
size=size,
|
||||
crc32=rom.get("crc", "").lower(),
|
||||
md5=rom.get("md5", "").lower(),
|
||||
sha1=rom.get("sha1", "").lower(),
|
||||
)
|
||||
)
|
||||
games.append(LogiqxGame(
|
||||
game_name, description, [s.strip() for s in serial.split(",") if s.strip()], roms,
|
||||
))
|
||||
return name, version, games
|
||||
|
||||
|
||||
def parse_logiqx(content: str | bytes) -> LogiqxDat:
|
||||
"""Parse Logiqx XML DAT content into its header and every named ROM."""
|
||||
name, version, games = parse_logiqx_games(content)
|
||||
return LogiqxDat(name, version, [rom for game in games for rom in game.roms])
|
||||
|
||||
|
||||
def validate_logiqx_format(content: str | bytes) -> bool:
|
||||
"""Validate that content parses as a Logiqx DAT with rom entries."""
|
||||
try:
|
||||
dat = parse_logiqx(content)
|
||||
except ET.ParseError:
|
||||
return False
|
||||
return bool(dat.roms)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Fetch Redump BIOS DAT files and write a provenance snapshot.
|
||||
|
||||
Redump serves BIOS DATs as Logiqx files linked from
|
||||
https://redump.info/downloads. The links were static files under
|
||||
/static/bios/<name>.dat and are now one route per system,
|
||||
/bios/<CODE> (PSX, PS2, GC, XBOX), served as an attachment. The
|
||||
downloads page is scanned for either shape, so new BIOS DATs are
|
||||
picked up without code changes.
|
||||
|
||||
Run manually, then commit the snapshot:
|
||||
python -m scripts.scraper.dats.redump_dat_scraper --dry-run
|
||||
python -m scripts.scraper.dats.redump_dat_scraper --output provenance/redump.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from model.dumpcatalog import write_provenance_snapshot
|
||||
from ..base_scraper import fetch_bytes
|
||||
from .logiqx_parser import parse_logiqx, validate_logiqx_format
|
||||
|
||||
BASE_URL = "https://redump.info"
|
||||
DOWNLOADS_URL = f"{BASE_URL}/downloads"
|
||||
|
||||
|
||||
def _fetch(url: str) -> str:
|
||||
return fetch_bytes(url).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def discover_bios_datfiles(downloads_html: str) -> list[str]:
|
||||
"""Extract BIOS DAT paths from the downloads page."""
|
||||
paths = set(re.findall(r'href="(/static/bios/[^"]+\.dat)"', downloads_html))
|
||||
paths.update(re.findall(r'href="(/bios/[A-Za-z0-9_-]+)"', downloads_html))
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def parse_redump_dat(content: str) -> tuple[str, str, list[dict]]:
|
||||
"""Parse a Redump Logiqx BIOS DAT into provenance entries.
|
||||
|
||||
The machine description carries the useful context (hardware
|
||||
model, kernel or firmware version), so it is kept per entry.
|
||||
"""
|
||||
dat = parse_logiqx(content)
|
||||
return dat.name, dat.version, dat.provenance_entries()
|
||||
|
||||
|
||||
def fetch_snapshot() -> tuple[dict, list[dict]]:
|
||||
"""Fetch all Redump BIOS DATs. Returns (dats metadata, entries)."""
|
||||
paths = discover_bios_datfiles(_fetch(DOWNLOADS_URL))
|
||||
if not paths:
|
||||
raise ValueError("No BIOS datfile links found on downloads page")
|
||||
dats = {}
|
||||
entries = []
|
||||
for path in paths:
|
||||
content = _fetch(f"{BASE_URL}{path}")
|
||||
if not validate_logiqx_format(content):
|
||||
raise ValueError(f"Unexpected DAT format for {path}")
|
||||
name, version, dat_entries = parse_redump_dat(content)
|
||||
dats[name] = version
|
||||
entries.extend(dat_entries)
|
||||
return dats, entries
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Fetch Redump BIOS DAT provenance")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Show fetched entries")
|
||||
parser.add_argument(
|
||||
"--output", "-o", default="provenance/redump.json", help="Snapshot output path"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
dats, entries = fetch_snapshot()
|
||||
except (ConnectionError, ValueError) as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if args.dry_run:
|
||||
for dat in sorted(dats):
|
||||
count = sum(1 for e in entries if e["dat"] == dat)
|
||||
print(f" {dat} ({dats[dat]}): {count} entries")
|
||||
print(f"\nTotal: {len(entries)} entries across {len(dats)} DATs")
|
||||
return 0
|
||||
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
imported_at = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
written = write_provenance_snapshot(args.output, "redump", imported_at, dats, entries)
|
||||
status = "Written" if written else "Unchanged"
|
||||
print(f"{status} {args.output}: {len(entries)} entries from {len(dats)} DATs")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user