#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 1, exit (c): every local dump through the one loader. Every file in the three No-Intro folders below ``$NO_INTRO_DIR`` (and the curated set below ``$RETROBAT_DIR`` when that optional variable is set) goes through ``a7800_python.cartridge.formats.load`` exactly as a user's file would (zip and 7z read in place, in memory), and must come back as a CartDescription or the documented refusal. The public test programs' ``.a78``/``.bin`` pairs are read from their zips in memory and their payloads matched. The outcome is cross-tabulated against the Phase 0 census (``tests/detector_runs/coverage.json``, written by ``scripts/count_carts.py``), whose typing-source column (MAME list / both emulator tables / one / size only / nothing) is the table in docs/cartridge.md. The loader never reads the GPL tables; the census's columns are used only to check that the loader's own answers fall where they must: - loader "softlist" == census "softlist" (126 No-Intro dumps); - the rest are typed by size (48 KiB or less and the BIOS says 7800), sent to 2600 mode by the BIOS's own test, or refused (over 48 KiB, in no table). python scripts/formats_census.py # needs a BIOS image for the BIOS test """ from __future__ import annotations import argparse import collections import json import sys import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) import hashlib # noqa: E402 from a7800_python import romsets # noqa: E402 from a7800_python.cartridge import a78, formats # noqa: E402 from a7800_python.cartridge.description import Refused # noqa: E402 SETS = { "licensed": romsets.no_intro(romsets.LICENSED_7800), "aftermarket": romsets.no_intro(romsets.AFTERMARKET_7800), "private": romsets.no_intro(romsets.PRIVATE_7800), } if (_retrobat := romsets.retrobat_7800()) is not None: # optional: $RETROBAT_DIR SETS["retrobat"] = _retrobat TEST_ZIPS = [ROOT / "reference/test_roms/7800utilitycart.beta.zip", ROOT / "reference/test_roms/Bankset_Test_Suite_v1.zip"] # fmt: skip ROM_SUFFIXES = (".zip", ".7z", ".a78", ".bin") def outcome(desc) -> str: if desc.console == "2600": return "2600 (" + desc.provenance.get("console", "?") + ")" source = desc.provenance.get("scheme", "default") if any(note.startswith("matched after trimming") for note in desc.notes): source += " (after trimming)" return source def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--json", type=Path, help="write per-dump outcomes here") args = parser.parse_args() began = time.monotonic() census = json.loads((ROOT / "tests/detector_runs/coverage.json").read_text()) tier_of = {(r["set"], r["sha1"]): r["tier"] for r in census} records = [] cache: dict[str, tuple[str, str]] = {} for set_name, folder in SETS.items(): for path in sorted(folder.iterdir()): if path.is_dir() or path.name.startswith("[BIOS]"): continue if path.suffix.lower() not in ROM_SUFFIXES: print(f"skipped (not a ROM file): {set_name}/{path.name}") continue data = formats.read_source(path)[1] sha1 = hashlib.sha1(data[128:] if a78.is_a78(data) else data).hexdigest() try: desc = formats.load(path) result, detail = outcome(desc), desc.summary() + " " + "; ".join(desc.notes) except Refused as refusal: result, detail = "refused", str(refusal) records.append({"set": set_name, "file": path.name, "outcome": result, "census": tier_of.get((set_name, sha1), "?"), "detail": detail}) # fmt: skip cache[path.name] = (result, sha1 or "") out = [] for set_name in SETS: rows = [r for r in records if r["set"] == set_name] out.append(f"\n== {set_name}: {len(rows)} files through the loader") table = collections.Counter((r["outcome"], r["census"]) for r in rows) for (result, tier), count in sorted(table.items()): out.append(f" {count:4} loader {result:22} census {tier}") by_census = collections.Counter(r["census"] for r in rows) out.append(" census columns: " + ", ".join(f"{k} {v}" for k, v in sorted(by_census.items()))) nointro = [r for r in records if r["set"] != "retrobat"] loader_soft = sum(r["outcome"] == "softlist" for r in nointro) census_soft = sum(r["census"] == "softlist" for r in nointro) columns = collections.Counter(r["census"] for r in nointro) out.append(f"\nNo-Intro: loader softlist {loader_soft}, census softlist {census_soft}; census columns " + ", ".join(f"{k} {v}" for k, v in sorted(columns.items()))) agree = all((r["outcome"] == "softlist") == (r["census"] == "softlist") for r in records) out.append(f"softlist rows agree dump by dump with the census: {agree}") unanswered = [r for r in records if r["outcome"] not in ("size", "refused") and not r["outcome"].startswith(("2600", "softlist"))] # fmt: skip out.append(f"files with neither a description nor the documented refusal: {len(unanswered)}") # The test pairs. out.append("\n== public test programs: .a78 / .bin pairs (members read in memory)") pairs_ok = 0 pairs = 0 for zpath in TEST_ZIPS: with zipfile.ZipFile(zpath) as z: names = {i.filename: z.read(i) for i in z.infolist() if not i.is_dir()} for name, data in sorted(names.items()): if not name.endswith(".a78"): continue partner = name[:-4] + ".bin" if partner not in names: continue pairs += 1 a = formats.load(data, use_bios_test=False) try: b_payload = formats.load(names[partner], use_bios_test=False).payload b_note = "described" except Refused: b_payload = names[partner] b_note = "refused (headerless, in no table: the documented refusal)" match = formats.match_payloads(a.payload, b_payload, bankset=a.bankset) pairs_ok += match is not None out.append(f" {Path(name).name}: a78 {a.summary()}; bin {b_note}; payloads: {match}") out.append(f"pairs resolving to the same cartridge: {pairs_ok} of {pairs}") out.append(f"\nwall {time.monotonic() - began:.0f} s") print("\n".join(out)) if args.json: args.json.write_text(json.dumps(records, indent=1), encoding="utf-8") return 0 if not unanswered and agree and pairs_ok == pairs else 1 if __name__ == "__main__": sys.exit(main())