#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """A library sweep: every cart of the chosen No-Intro Lynx sets through ``lynx-sweep``. Each file is read in place from ``$NO_INTRO_DIR/`` and run by ``lynx-sweep`` (this tree's release build) under ``timeout`` and ``nice``, several at a time, each with a fresh, empty ``XDG_DATA_HOME`` (no override or EEPROM save from an earlier run is loaded, and none is left in the user's directory). The boot ROM comes the way the boards load it (``$MAME_ROMPATH``). Results go to ``OUT/results.jsonl`` (one JSON line per file, the fields of ``lynx-sweep`` plus ``set``, ``exit`` and ``wall``), pictures to ``OUT/png/`` (the picture at each ``--png-at`` slice and the last one), and a contact sheet per set and slice to ``OUT/sheets/`` when Pillow is importable. ``OUT`` defaults to ``external/sweep/`` (gitignored). Stdlib only, apart from the optional sheets. sweep.py [--sets LYX,LNX,BLL] [--slices 2700] [--input scripts/inputs/aab.txt] [--png-at 600,1200] [--jobs 8] [--timeout 300] [--out DIR] [--only REGEX] The default sets are the licensed ones: ``Atari - Atari Lynx (LYX)``, ``(LNX)`` and ``(BLL)``; never the ``(Aftermarket)`` or ``(Private)`` sets unless named. """ from __future__ import annotations import argparse import json import os import re import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parent SETS = { "LYX": "Atari - Atari Lynx (LYX)", "LNX": "Atari - Atari Lynx (LNX)", "BLL": "Atari - Atari Lynx (BLL)", "Aftermarket": "Atari - Atari Lynx (LYX) (Aftermarket)", "Private": "Atari - Atari Lynx (LYX) (Private)", } def stem(name: str) -> str: return re.sub(r"[^A-Za-z0-9.()-]+", "_", Path(name).stem) def run_one(item, args, binary: Path, out: Path) -> dict: label, path = item name = f"{label}-{stem(path.name)}" points = sorted(set(args.png_at) | {args.slices}) command = ["timeout", str(args.timeout), "nice", str(binary), str(path), "--slices", str(args.slices)] if args.input: command += ["--input", str(args.input)] if args.machine: command += ["--machine", args.machine] for p in points: command += ["--png-at", f"{p}:{out / 'png' / f'{name}-{p}.png'}"] started = time.monotonic() with tempfile.TemporaryDirectory(dir=out / "xdg") as xdg: done = subprocess.run(command, capture_output=True, text=True, env={**os.environ, "XDG_DATA_HOME": xdg}) wall = time.monotonic() - started line = done.stdout.strip().splitlines()[-1:] if done.stdout.strip() else [] try: result = json.loads(line[0]) if line else {"file": path.name} except json.JSONDecodeError: result = {"file": path.name, "unparsed": line[0][:200]} result.update(set=label, name=name, exit=done.returncode, wall=round(wall, 2)) if done.returncode == 124: result["timeout"] = True if done.returncode not in (0, 124): result["stderr"] = done.stderr.strip()[-400:] return result def sheets(out: Path, results: list[dict], points: list[int]) -> None: try: from PIL import Image, ImageDraw except ImportError: return (out / "sheets").mkdir(exist_ok=True) for label in sorted({r["set"] for r in results}): rows = [r for r in results if r["set"] == label] for p in points: for page in range(0, len(rows), 24): chunk = rows[page:page + 24] cell_w, cell_h, cols = 330, 240, 6 sheet = Image.new("RGB", (cell_w * cols, cell_h * ((len(chunk) + cols - 1) // cols)), "gray") draw = ImageDraw.Draw(sheet) for i, r in enumerate(chunk): x, y = (i % cols) * cell_w, (i // cols) * cell_h png = out / "png" / f"{r['name']}-{p}.png" if png.exists(): img = Image.open(png) img = img.resize((img.width * 2, img.height * 2), Image.NEAREST) sheet.paste(img, (x + 2, y + 18)) draw.text((x + 2, y + 2), f"{page + i}: {r['file'][:48]}", fill="white") sheet.save(out / "sheets" / f"{label}-{p}-{page // 24}.png") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--sets", default="LYX,LNX,BLL") parser.add_argument("--slices", type=int, default=2700) parser.add_argument("--input", type=Path, default=HERE / "inputs" / "aab.txt") parser.add_argument("--png-at", default="600,1200") parser.add_argument("--machine") parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--timeout", type=int, default=300) parser.add_argument("--out", type=Path, default=ROOT / "external" / "sweep") parser.add_argument("--only", help="a regular expression on the file name") parser.add_argument("--binary", type=Path, default=ROOT / "target" / "release" / "lynx-sweep") args = parser.parse_args() args.png_at = [int(v) for v in args.png_at.split(",") if v] root = os.environ.get("NO_INTRO_DIR") if not root: print("NO_INTRO_DIR is not set", file=sys.stderr) return 2 items = [] for label in args.sets.split(","): directory = Path(root) / SETS[label] for path in sorted(directory.iterdir()): if args.only is None or re.search(args.only, path.name): items.append((label, path)) for sub in ("png", "xdg"): (args.out / sub).mkdir(parents=True, exist_ok=True) print(f"{len(items)} files, {args.slices} slices each, {args.jobs} at a time", flush=True) results = [] with ThreadPoolExecutor(args.jobs) as pool, open(args.out / "results.jsonl", "w") as log: for r in pool.map(lambda it: run_one(it, args, args.binary, args.out), items): results.append(r) log.write(json.dumps(r, sort_keys=True) + "\n") log.flush() state = ("load error" if r.get("loaded") is False else "boot error" if "boot_error" in r else "timeout" if r.get("timeout") else "panic" if r.get("panic") else f"exit {r['exit']}" if r["exit"] else "blank at end" if r.get("final_blank") else "picture") print(f"{r['set']:4} {r['file'][:60]:60} {state} ({r['wall']} s)", flush=True) sheets(args.out, results, sorted(set(args.png_at) | {args.slices})) return 0 if __name__ == "__main__": sys.exit(main())