refactor: move the region audit library down

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 13:38:44 +01:00
1 parent a81c497e8d
commit 8738179f42
6 files changed
+150 -137

No files matched your search

+37
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
WORLD = "world"
# Two levels only: super-region -> member territories.
@@ -194,3 +195,39 @@ def region_tag(requested: list[str]) -> str:
return "_".join(
"".join(part.title() for part in slug.split("-")) for slug in requested
)
# No-Intro filename tokens: full English territory names.
NOINTRO = {
"World": "world",
"USA": "north-america",
"Canada": "canada",
"Europe": "europe",
"Japan": "japan",
"Asia": "asia",
"Korea": "south-korea",
"Brazil": "brazil",
"Taiwan": "taiwan",
"China": "china",
"Hong Kong": "hong-kong",
"France": "france",
"Germany": "germany",
"Spain": "spain",
"Italy": "italy",
"Netherlands": "netherlands",
"Sweden": "sweden",
"Norway": "norway",
"Denmark": "denmark",
"Finland": "finland",
"Australia": "australia",
"New Zealand": "new-zealand",
"Russia": "russia",
"UK": "uk",
"Portugal": "portugal",
"Greece": "greece",
"Poland": "poland",
"India": "india",
"Mexico": "mexico",
"Argentina": "argentina",
"Latin America": "latin-america",
}
+1 -130
View File
@@ -10,55 +10,16 @@ Read the limits printed in the header before acting on anything here.
from __future__ import annotations
import argparse
import collections
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from model import region
from model.database import load_database
from model.profiles import load_emulator_profiles
from resolve.localfile import resolve_local_file
from resolve.regionaudit import build_report
# No-Intro filename tokens: full English territory names.
NOINTRO = {
"World": "world",
"USA": "north-america",
"Canada": "canada",
"Europe": "europe",
"Japan": "japan",
"Asia": "asia",
"Korea": "south-korea",
"Brazil": "brazil",
"Taiwan": "taiwan",
"China": "china",
"Hong Kong": "hong-kong",
"France": "france",
"Germany": "germany",
"Spain": "spain",
"Italy": "italy",
"Netherlands": "netherlands",
"Sweden": "sweden",
"Norway": "norway",
"Denmark": "denmark",
"Finland": "finland",
"Australia": "australia",
"New Zealand": "new-zealand",
"Russia": "russia",
"UK": "uk",
"Portugal": "portugal",
"Greece": "greece",
"Poland": "poland",
"India": "india",
"Mexico": "mexico",
"Argentina": "argentina",
"Latin America": "latin-america",
}
_PAREN = re.compile(r"\(([^)]+)\)")
LIMITS = """Limits, read before trusting any line below.
@@ -77,96 +38,6 @@ LIMITS = """Limits, read before trusting any line below.
"""
def tokens_from_name(name: str) -> set[str]:
"""Extract geography slugs from a No-Intro style DAT entry name."""
found: set[str] = set()
for group in _PAREN.findall(name):
for part in (p.strip() for p in group.split(",")):
slug = NOINTRO.get(part)
if slug:
found.add(slug)
return found
def catalog_regions(db: dict) -> dict[str, tuple[set[str], str]]:
"""Map SHA1 to (geography slugs, source label) from No-Intro provenance."""
out: dict[str, tuple[set[str], str]] = {}
for sha1, record in db["files"].items():
entry = (record.get("provenance") or {}).get("no-intro")
if not entry:
continue
name = entry.get("name", "")
found = tokens_from_name(name)
if found:
out[sha1] = (found, name)
return out
def resolve_sha1(file_entry: dict, db: dict, by_path: dict | None = None) -> str | None:
"""The repo SHA1 a profile entry resolves to, by the pack's own resolver.
A private resolver read sha1, then md5, then a lone name: entries that
identify their file by path (Dolphin's three IPL.bin), by crc32
(geargrafx) or by sha256 (mednafen) were never checked at all.
"""
if by_path is None:
by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()}
path, status = resolve_local_file(
file_entry, db, dest_hint=file_entry.get("path") or ""
)
if not path or status in ("not_found", "hash_mismatch"):
return None
return by_path.get(path)
def build_report(profiles: dict, db: dict) -> dict:
"""Compare every declared region: against the No-Intro catalogue."""
catalog = catalog_regions(db)
agree = 0
unchecked = 0
conflicts: list[dict] = []
vocabulary: collections.Counter = collections.Counter()
for slugs, _name in catalog.values():
vocabulary.update(slugs)
by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()}
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
for f in profile.get("files") or []:
if not isinstance(f, dict) or not f.get("region"):
continue
declared = region.normalize_declared(f["region"])
sha1 = resolve_sha1(dict(f, source_profile=emu_name), db, by_path)
if not sha1 or sha1 not in catalog:
unchecked += 1
continue
found, name = catalog[sha1]
if region.WORLD in declared or any(
region.comparable(d, c) for d in declared for c in found
):
agree += 1
continue
conflicts.append(
{
"emulator": emu_name,
"file": f.get("name", ""),
"profile": sorted(declared),
"catalog": sorted(found),
"dat_name": name,
}
)
return {
"agree": agree,
"disagree": len(conflicts),
"unchecked": unchecked,
"catalog_files": len(catalog),
"repo_files": len(db["files"]),
"vocabulary": dict(vocabulary.most_common()),
"conflicts": conflicts,
}
def print_report(report: dict) -> None:
print(LIMITS)
print(
+106
View File
@@ -0,0 +1,106 @@
"""Profile region: values against the regions a dump catalogue gives the same file.
Advisory only: the emulator source decides what a region: value should be,
and a catalogue that disagrees is a second opinion, never a correction."""
from __future__ import annotations
import collections
import re
from model import region
from model.region import NOINTRO
from resolve.localfile import resolve_local_file
_PAREN = re.compile(r"\(([^)]+)\)")
def tokens_from_name(name: str) -> set[str]:
"""Extract geography slugs from a No-Intro style DAT entry name."""
found: set[str] = set()
for group in _PAREN.findall(name):
for part in (p.strip() for p in group.split(",")):
slug = NOINTRO.get(part)
if slug:
found.add(slug)
return found
def catalog_regions(db: dict) -> dict[str, tuple[set[str], str]]:
"""Map SHA1 to (geography slugs, source label) from No-Intro provenance."""
out: dict[str, tuple[set[str], str]] = {}
for sha1, record in db["files"].items():
entry = (record.get("provenance") or {}).get("no-intro")
if not entry:
continue
name = entry.get("name", "")
found = tokens_from_name(name)
if found:
out[sha1] = (found, name)
return out
def resolve_sha1(file_entry: dict, db: dict, by_path: dict | None = None) -> str | None:
"""The repo SHA1 a profile entry resolves to, by the pack's own resolver.
A private resolver read sha1, then md5, then a lone name: entries that
identify their file by path (Dolphin's three IPL.bin), by crc32
(geargrafx) or by sha256 (mednafen) were never checked at all.
"""
if by_path is None:
by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()}
path, status = resolve_local_file(
file_entry, db, dest_hint=file_entry.get("path") or ""
)
if not path or status in ("not_found", "hash_mismatch"):
return None
return by_path.get(path)
def build_report(profiles: dict, db: dict) -> dict:
"""Compare every declared region: against the No-Intro catalogue."""
catalog = catalog_regions(db)
agree = 0
unchecked = 0
conflicts: list[dict] = []
vocabulary: collections.Counter = collections.Counter()
for slugs, _name in catalog.values():
vocabulary.update(slugs)
by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()}
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
for f in profile.get("files") or []:
if not isinstance(f, dict) or not f.get("region"):
continue
declared = region.normalize_declared(f["region"])
sha1 = resolve_sha1(dict(f, source_profile=emu_name), db, by_path)
if not sha1 or sha1 not in catalog:
unchecked += 1
continue
found, name = catalog[sha1]
if region.WORLD in declared or any(
region.comparable(d, c) for d in declared for c in found
):
agree += 1
continue
conflicts.append(
{
"emulator": emu_name,
"file": f.get("name", ""),
"profile": sorted(declared),
"catalog": sorted(found),
"dat_name": name,
}
)
return {
"agree": agree,
"disagree": len(conflicts),
"unchecked": unchecked,
"catalog_files": len(catalog),
"repo_files": len(db["files"]),
"vocabulary": dict(vocabulary.most_common()),
"conflicts": conflicts,
}
+1 -1
View File
@@ -42,7 +42,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path:
from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic
from model.safeparse import parse_untrusted_xml
from model.region import REGIONS, WORLD
from region_audit import NOINTRO
from model.region import NOINTRO
from .base_scraper import github_headers
+4 -4
View File
@@ -28,8 +28,8 @@ try:
except ImportError:
jsonschema = None
import install
from scripts import pipeline, region_audit
from scripts.resolve import regions
from scripts import pipeline
from scripts.resolve import regionaudit, regions
from scripts.resolve.localfile import resolve_local_file
from scripts.core.ziptools import safe_extract_zip
from scripts.generate_pack import (
@@ -1896,11 +1896,11 @@ class RegionRegressions(unittest.TestCase):
db = {"files": files, "indexes": generate_db.build_indexes(files, {})}
by_md5 = {e["md5"]: s for s, e in files.items()}
self.assertEqual(
region_audit.resolve_sha1({"name": "IPL.bin", "md5": [files[shas["bios/GC/USA/IPL.bin"]]["md5"]]}, db),
regionaudit.resolve_sha1({"name": "IPL.bin", "md5": [files[shas["bios/GC/USA/IPL.bin"]]["md5"]]}, db),
shas["bios/GC/USA/IPL.bin"],
)
self.assertEqual(
region_audit.resolve_sha1({"name": "IPL.bin", "path": "GC/JAP/IPL.bin"}, db),
regionaudit.resolve_sha1({"name": "IPL.bin", "path": "GC/JAP/IPL.bin"}, db),
shas["bios/GC/JAP/IPL.bin"],
)
self.assertTrue(by_md5)
+1 -2
View File
@@ -37,7 +37,7 @@ NOT_YET_PACKAGED = frozenset({
"cross_reference", "dedup", "derivations", "export_native", "generate_event_schema",
"generate_pack", "generate_readme", "generate_site", "manifestselect", "measurement_records",
"packextras", "packpaths", "packreadme", "packresolve", "packverify", "pin_installer",
"pr_checks", "provenance_report", "refresh_data_dirs", "region_audit",
"pr_checks", "provenance_report", "refresh_data_dirs",
"release_record", "romfolders", "romset_recipes", "siteagents", "sitebootstrap",
"sitecollection", "sitediagrams", "siteentries", "siteexports", "siteguides", "sitehandheld",
"siteinputs", "sitemarkup", "sitemeasurements", "siterender", "sitesources", "sitestarlight",
@@ -48,7 +48,6 @@ NOT_YET_PACKAGED = frozenset({
# packages the top-level side.
PENDING_TOP_LEVEL_IMPORTS = frozenset({
("exporter.doubled", "slots"),
("scraper.game_dat_importer", "region_audit"),
})