#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 6's triage table: each board frame of a sweep (scripts/sweep.sh) beside the closest frame of each detector within a window, and each title's status. For every board composite ``board/SLUG/fNNNNN.png`` the detectors' frames within ``--window`` frames either side are compared pixel by pixel (``compare_frames.compare``, ``--tolerance`` per channel) and the closest kept: the share of pixels that differ and how many frames away it is. The detectors are closed boxes (PicoDrive, BlastEm), so agreeing with one says only that the board has not gone wrong in a way it would show (docs/claims.md). A title's status: agree every board frame is within --threshold of some detector's closest frame (a blank frame counts when a detector has one blank too) look some frame is not: a person looks at the pictures and writes the cause in the triage file (``--triage``, default tests/sweep_triage.txt), which turns it into triaged with the cause shown (a cause starting "OPEN" leaves it "look") lockup the board's run stopped at megadrive-python's ``Lockup`` (the emulated bus hung; run_32x.py exits 2): a cause in the triage file turns it into "triaged: lockup ...", as for "look" error the board's run raised (a traceback) or exited otherwise non-zero: a fault of the board or its scripts, which no cause turns into "triaged" running the board's log has no exit line yet A blank frame (one colour) matches only a blank frame (``closest``). The summary's last line counts the rows still untriaged (look, lockup, error): milestone 6's acceptance is 0. Run with PyPy; ``--csv`` writes every frame's row. .venv-pypy/bin/python scripts/triage_sweep.py reference/sweep/NAME [--csv out.csv] """ from __future__ import annotations import argparse import csv import re import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from compare_frames import compare from megadrive_python.png import read_png DETECTORS = ("pico", "blastem") FRAME = re.compile(r"f(\d{5})\.png$") def board_status(log: Path) -> str: text = log.read_text(errors="replace") if log.exists() else "" match = re.search(r"EXIT (\d+) (\d+) s", text) lockup = re.search(r"frame (\d+): Lockup: (.*)", text) if lockup and "Traceback" not in text and match and match[1] == "2": return f"lockup: frame {lockup[1]}: {lockup[2]}"[:160] if "Lockup" in text or "Traceback" in text or (match and match[1] != "0"): last = [line for line in text.splitlines() if line.strip()][-2:] return "error: " + " | ".join(last)[:160] return f"exit 0 in {match[2]} s" if match else "running" def blank(picture: list[list[int]]) -> bool: first = picture[0][0] return all(p == first for row in picture for p in row) def closest( board: list[list[int]], frames: Path, n: int, window: int, tolerance: int ) -> tuple[int, float] | None: """The detector's frame nearest ``board`` within ``window`` of ``n``: (frame, share). A blank frame (one colour) matches only a blank frame: a share of 1 otherwise, however few pixels the other draws. Without that, a board frame holding one line of text over black "agreed" at 3 % with a detector that showed nothing (the Gnu Sierra sample on BlastEm, release wave, 2026-11-25) while the other detector drew a full picture.""" best: tuple[int, float] | None = None board_blank = blank(board) for m in range(max(2, n - window), n + window + 1): path = frames / f"f{m:05d}.png" if not path.exists(): continue theirs = read_png(path) h = min(len(board), len(theirs)) w = min(len(board[0]), len(theirs[0])) if blank(theirs) != board_blank: share = 1.0 else: share = len(compare([r[:w] for r in board[:h]], theirs[:h], 0, 0, tolerance)) / (w * h) if best is None or share < best[1] or (share == best[1] and abs(m - n) < abs(best[0] - n)): best = (m, share) if share == 0 and m >= n: break return best def triage_title(job: tuple[Path, str, int, int, float]) -> dict: out, slug, window, tolerance, threshold = job rows = [] worst = 0.0 for frame_png in sorted((out / "board" / slug).glob("f[0-9][0-9][0-9][0-9][0-9].png")): n = int(FRAME.search(frame_png.name)[1]) board = read_png(frame_png) row = {"slug": slug, "frame": n, "blank": blank(board)} shares = [] for det in DETECTORS: found = closest(board, out / det / slug, n, window, tolerance) row[f"{det}_frame"] = found[0] if found else "" row[f"{det}_share"] = f"{found[1]:.4f}" if found else "" if found: shares.append(found[1]) best = min(shares) if shares else 1.0 row["best"] = f"{best:.4f}" worst = max(worst, best) rows.append(row) return {"slug": slug, "rows": rows, "worst": worst, "threshold": threshold} def read_triage(path: Path) -> dict[str, str]: """``SLUG-or-name: cause`` per line, '#' comments.""" notes: dict[str, str] = {} if path.exists(): for line in path.read_text().splitlines(): if line.lstrip().startswith("#"): continue if ":" in line: key, cause = line.split(":", 1) key = re.sub(r"[^A-Za-z0-9]", "_", key.strip()) notes[key] = cause.strip() return notes def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("out", type=Path, help="a sweep's OUT folder") parser.add_argument("--window", type=int, default=300) parser.add_argument("--tolerance", type=int, default=12) parser.add_argument("--threshold", type=float, default=0.05) parser.add_argument("--triage", type=Path, default=Path("tests/sweep_triage.txt")) parser.add_argument("--csv", type=Path) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("only", nargs="*", help="substrings of the titles to triage") args = parser.parse_intermixed_args() slugs = sorted( d.name for d in (args.out / "board").iterdir() if not args.only or any(s in d.name for s in args.only) ) notes = read_triage(args.triage) jobs = [(args.out, s, args.window, args.tolerance, args.threshold) for s in slugs] with ProcessPoolExecutor(args.jobs) as pool: results = list(pool.map(triage_title, jobs)) counts: dict[str, int] = {} all_rows = [] for result in results: slug = result["slug"] status = board_status(args.out / "logs" / f"{slug}-board.log") if status.startswith("exit 0"): status = "agree" if result["worst"] <= args.threshold else "look" if status == "look" and slug in notes and not notes[slug].startswith("OPEN"): status = "triaged" elif status.startswith("lockup") and slug in notes and not notes[slug].startswith("OPEN"): status = "triaged: " + status kind = status.split(":")[0] counts[kind] = counts.get(kind, 0) + 1 cause = f" [{notes[slug]}]" if kind == "triaged" else "" print(f"== {slug}: {status}{cause}") for row in result["rows"]: parts = [f"f{row['frame']:5d}:"] parts.extend( f"{det} {row[f'{det}_frame']:>5} {float(row[f'{det}_share']):6.1%}" for det in DETECTORS if row[f"{det}_frame"] != "" ) if row["blank"]: parts.append("BLANK") if float(row["best"]) > args.threshold: parts.append("<-") print(" " + " ".join(parts)) all_rows.append({**row, "status": kind}) print("summary: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()))) untriaged = sum(counts.get(kind, 0) for kind in ("look", "lockup", "error")) print(f"untriaged: {untriaged} of {len(results)}") if args.csv: with args.csv.open("w", newline="") as handle: fields = ["slug", "frame", "blank", "best", "status"] fields += [f"{d}_{k}" for d in DETECTORS for k in ("frame", "share")] writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(all_rows) return 0 if __name__ == "__main__": sys.exit(main())