From 6ff029e096a6cbb192512d9fddccd47317c0543f Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 16:13:36 -0800 Subject: [PATCH] Add synthetic-media archive differential harness (#22) scripts/archive_diff.py rewrites real private/samples comps so every Loader reads a generated plate and a DiffSaver captures the node render-check views, renders one frame on Snow Globe Fusion and on Fission, and reports MAE/RMSE per comp and per tool family. Only .comp text is read; all media is synthetic. Assisted-by: claude-sonnet-5.5 --- scripts/archive_diff.py | 565 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 565 insertions(+) create mode 100644 scripts/archive_diff.py diff --git a/scripts/archive_diff.py b/scripts/archive_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..82e810f91d9134855129980032c2da44cb1bad1b --- /dev/null +++ b/scripts/archive_diff.py @@ -0,0 +1,565 @@ +#!/usr/bin/env python3 +"""Privacy-safe archive differential harness: real .comp graphs, synthetic media. + +Rewrites comps from private/samples/ so every Loader reads one of four generated plates and a +DiffSaver captures the node render-check views, renders one frame on Snow Globe Fusion +(`sg render`) and on Fission (`render-check`), then reports per-comp and per-tool-family error. + + python3 scripts/archive_diff.py --limit 25 --report-json /tmp/archive_diff_report.json + python3 scripts/archive_diff.py --comp "private/samples/2024/technique for improvement/technique.comp" + +No archive media is ever read; only .comp text. Outputs live under /tmp/fission_archive_diff +(and the Snow Globe share when mounted) and are never committed. +""" + +from __future__ import annotations + +import argparse +import binascii +import json +import math +import re +import struct +import subprocess +import sys +import time +from collections import Counter, defaultdict +from pathlib import Path + +import fusion_probes as fp +import gen_compatibility as gc + +SAMPLES = fp.REPO / "private" / "samples" +LOCAL = Path("/tmp/fission_archive_diff") +SHARED = fp.SMB_ROOT / "archive_diff" if fp.use_smb() else LOCAL +CONTAINER = f"{fp.CONTAINER_ROOT}/archive_diff" +REMOTE = f"{fp.REMOTE_ROOT}/archive_diff" +PLATE_W, PLATE_H, PLATES = 640, 360, 4 +FAIL_MAE_PCT = 1.5 +FUSION_TIMEOUT_S, FISSION_TIMEOUT_S = 90, 120 +# Cosmetic classes with no render behavior; never count as unsupported. +COSMETIC = {"Note", "Underlay"} + +# --------------------------------------------------------------------------------------------- +# Synthetic media +# --------------------------------------------------------------------------------------------- + + +def make_plate(k: int) -> bytes: + """RGBA plate k: hue/value gradient, diagonal gridlines, alpha cutouts, shapes, id bars.""" + w, h = PLATE_W, PLATE_H + buf = bytearray(w * h * 4) + flip = k % 2 + for y in range(h): + ny = y / (h - 1) + for x in range(w): + nx = x / (w - 1) + t = nx if k < 2 else ny + r, g, b = fp.hsv_to_rgb(k * 0.23 + 0.55 * t, 0.55 + 0.4 * (1 - ny if flip else ny), 0.35 + 0.6 * (ny if flip else nx)) + a = 255 + if (x + y * (1 + k % 3)) % 48 < 2: + r, g, b = (1.0 - r, 1.0 - g, 1.0 - b) + if y > h - 50: # soft alpha ramp keeps RGB, so premultiply bugs show + a = int(255 * (h - 1 - y) / 49) + if y < 16 and x < 16 * 4: # plate id in binary, one cell per bit + on = ((k + 1) >> (x // 16)) & 1 + r = g = b = 1.0 if on else 0.0 + buf[(y * w + x) * 4 : (y * w + x) * 4 + 4] = bytes((int(r * 255), int(g * 255), int(b * 255), a)) + + def px(x, y, rgb, a=255): + i = (y * w + x) * 4 + buf[i : i + 4] = bytes((*rgb, a)) + + # Asymmetric shapes, positions rotate per plate so flips and rotations are detectable. + cx, cy = (w * (0.25 + 0.5 * flip), h * (0.3 + 0.35 * (k // 2))) + palette = [(255, 40, 40), (40, 255, 80), (60, 90, 255), (255, 230, 30)] + for y in range(h): + for x in range(w): + d = math.hypot(x - cx, y - cy) + if d < 70: + px(x, y, palette[k], 255) + if 24 < d < 36 and x > cx: # alpha-0 cutout ring (half), RGB kept + px(x, y, palette[(k + 1) % 4], 0) + if abs(x - (w - cx)) < 55 and abs(y - (h - cy)) < 38: # translucent block + px(x, y, palette[(k + 2) % 4], 128) + if 0 <= x - 10 < 24 and 60 <= y < 220 or 0 <= x - 10 < 110 and 196 <= y < 220: # asymmetric "L" + px(x, y, (255, 255, 255)) + if y > h * 0.55 and abs(x - w / 2) < (y - h * 0.55) * 0.4 and y < h - 60: # triangle + px(x, y, palette[(k + 3) % 4], 255) + return bytes(buf) + + +# The FBX SDK names OBJ meshes by their `g` group and ignores `o`; ObjName must match it. +MESH_OBJ = """g synth_cube +v -50 -50 50 +v 50 -50 50 +v 50 50 50 +v -50 50 50 +v -50 -50 -50 +v 50 -50 -50 +v 50 50 -50 +v -50 50 -50 +vt 0 0 +vt 1 0 +vt 1 1 +vt 0 1 +vn 0 0 1 +vn 0 0 -1 +vn 1 0 0 +vn -1 0 0 +vn 0 1 0 +vn 0 -1 0 +f 1/1/1 2/2/1 3/3/1 4/4/1 +f 6/1/2 5/2/2 8/3/2 7/4/2 +f 2/1/3 6/2/3 7/3/3 3/4/3 +f 5/1/4 1/2/4 4/3/4 8/4/4 +f 4/1/5 3/2/5 7/3/5 8/4/5 +f 5/1/6 6/2/6 2/3/6 1/4/6 +""" + + +def ensure_assets(): + """Write the plates and mesh into SHARED/assets (and sg upload them when SMB isn't mounted).""" + d = SHARED / "assets" + d.mkdir(parents=True, exist_ok=True) + for k in range(PLATES): + p = d / f"synth_{k}.png" + if not p.exists(): + fp.write_png_rgba(p, PLATE_W, PLATE_H, make_plate(k)) + mesh = d / "synth_mesh.obj" + mesh.write_text(MESH_OBJ) + if SHARED == LOCAL: + subprocess.run(["sg", "upload", str(d), f"{REMOTE}/"], check=True) + + +# --------------------------------------------------------------------------------------------- +# Comp text: brace-aware helpers and the rewriter +# --------------------------------------------------------------------------------------------- + +_TOKEN = re.compile(r'[{}"]|\\.', re.S) +_STR = r'"((?:[^"\\]|\\.)*)"' + + +def block_end(text: str, open_i: int) -> int: + """Index of the `}` matching the `{` at open_i, skipping quoted strings.""" + depth, in_str = 0, False + for m in _TOKEN.finditer(text, open_i): + t = m.group() + if t[0] == "\\": + continue + if t == '"': + in_str = not in_str + elif not in_str: + depth += 1 if t == "{" else -1 + if depth == 0: + return m.start() + raise ValueError("unbalanced braces") + + +def tool_blocks(text: str, kind: str): + """(open_brace, close_brace) of every `name = kind {` at any depth, in file order.""" + pat = re.compile(rf'(?m)^[ \t]*(?:\["[^"]+"\]|[A-Za-z_]\w*)\s*=\s*{re.escape(kind)}\s*\{{') + return [(m.end() - 1, block_end(text, m.end() - 1)) for m in pat.finditer(text)] + + +def replace_blocks(text: str, blocks, fn) -> str: + """Replace each block's inner text (between braces) with fn(inner), back to front.""" + for o, c in reversed(blocks): + text = text[: o + 1] + fn(text[o + 1 : c]) + text[c:] + return text + + +def drop_inputs(body: str, names) -> str: + """Remove `Name = Input { ... },` entries (single or multi-line) from a tool body.""" + for name in names: + pat = re.compile(rf'(?m)^[ \t]*(?:\["{re.escape(name)}"\]|{re.escape(name)})\s*=\s*Input\s*\{{') + while m := pat.search(body): + end = block_end(body, m.end() - 1) + 1 + end += 1 if body[end : end + 1] == "," else 0 + end += 1 if body[end : end + 1] == "\n" else 0 + body = body[: m.start()] + body[end:] + return body + + +def add_inputs(body: str, entries: str) -> str: + """Insert entries at the top of the tool's `Inputs = {` table, creating it if absent.""" + m = re.search(r"Inputs\s*=\s*\{", body) + if m: + return body[: m.end()] + "\n" + entries + body[m.end() :] + return "\n\t\t\tInputs = {\n" + entries + "\t\t\t},\n" + body + + +def synth_index(original: str) -> int: + return binascii.crc32(original.encode()) % PLATES + + +def retarget_loader(body: str, frame: int) -> str: + """Point a Loader at one synthetic still that is present on every frame.""" + m = re.search(r"Clips\s*=\s*\{", body) + if not m: + return body + end = block_end(body, m.end() - 1) + clips = body[m.start() : end + 1] + cid = (re.search(rf"ID\s*=\s*{_STR}", clips) or [None, "Clip1"])[1] + k = synth_index((re.search(rf"Filename\s*=\s*{_STR}", clips) or [None, ""])[1]) + new = ( + 'Clips = {\n\t\t\t\tClip {\n' + f'\t\t\t\t\tID = "{cid}",\n' + f'\t\t\t\t\tFilename = "{CONTAINER}/assets/synth_{k}.png",\n' + '\t\t\t\t\tFormatID = "PNGFormat",\n' + "\t\t\t\t\tLength = 1,\n\t\t\t\t\tLengthSetManually = true,\n" + f"\t\t\t\t\tStartFrame = {k},\n" # Fusion scans synth_N.png as one numbered sequence; this pins plate k + "\t\t\t\t\tTrimIn = 0,\n\t\t\t\t\tTrimOut = 0,\n\t\t\t\t\tExtendFirst = 0,\n\t\t\t\t\tExtendLast = 0,\n\t\t\t\t\tLoop = 1,\n" + f"\t\t\t\t\tGlobalStart = {frame},\n\t\t\t\t\tGlobalEnd = {frame},\n" + "\t\t\t\t}\n\t\t\t}" + ) + body = body[: m.start()] + new + body[end + 1 :] + # Global range and clip trim inputs describe the real footage; the still must exist at `frame`. + body = drop_inputs(body, ["GlobalIn", "GlobalOut", "ClipTimeStart", "ClipTimeEnd", "HoldFirstFrame", "HoldLastFrame"]) + return add_inputs(body, f"\t\t\t\tGlobalIn = Input {{ Value = {frame}, }},\n\t\t\t\tGlobalOut = Input {{ Value = {frame}, }},\n") + + +def retarget_mesh(body: str) -> str: + """Map a missing ImportFile (and the mesh name selected inside it) to the synthetic mesh.""" + + def sub(m): + return m.group(0) if Path(m.group(2).replace("\\\\", "\\")).exists() else f'{m.group(1)}"{CONTAINER}/assets/synth_mesh.obj"' + + mapped = re.sub(rf"(ImportFile\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}", sub, body) + if mapped == body: + return body + return re.sub(rf"(ObjName\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}", r'\1"synth_cube"', mapped) + + +def normalize_fonts(text: str) -> str: + """Map every font family/style (inputs and character-level styling 100/109) to Liberation Sans/Regular.""" + for pat, value in ( + (rf'(?m)^(\s*Font\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}', "Liberation Sans"), + (rf'(?m)^(\s*Style\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}', "Regular"), + (rf"(Parameter\s*=\s*100,[^{{}}]*?String\s*=\s*){_STR}", "Liberation Sans"), + (rf"(Parameter\s*=\s*109,[^{{}}]*?String\s*=\s*){_STR}", "Regular"), + ): + text = re.sub(pat, rf'\1"{value}"', text) + return text + + +def pick_frame(text: str) -> int: + """Midpoint of the original RenderRange, else CurrentTime, else 0.""" + rr = re.search(r"(?m)^\tRenderRange\s*=\s*\{\s*(-?\d+)\s*,\s*(-?\d+)", text) + if rr and int(rr[1]) < int(rr[2]): + return (int(rr[1]) + int(rr[2])) // 2 + ct = re.search(r"(?m)^\tCurrentTime\s*=\s*(-?\d+)", text) + return int(ct[1]) if ct else 0 + + +def retarget(text: str, fonts: bool) -> tuple[str, int]: + """Comp text with synthetic media and a single-frame range; node graph untouched.""" + frame = pick_frame(text) + text = normalize_fonts(text) if fonts else text + text = replace_blocks(text, tool_blocks(text, "Loader"), lambda b: retarget_loader(b, frame)) + text = replace_blocks(text, tool_blocks(text, "SurfaceFBXMesh"), retarget_mesh) + text = re.sub(r"(?m)^\tRenderRange\s*=\s*\{[^}]*\},", f"\tRenderRange = {{ {frame}, {frame} }},", text, count=1) + text = re.sub(r"(?m)^\tCurrentTime\s*=\s*-?\d+,", f"\tCurrentTime = {frame},", text, count=1) + text = re.sub(r"(?m)^\tAudioFilename\s*=.*\n", "", text, count=1) + return text, frame + + +def add_diff_saver(text: str, case_id: str, view: str) -> str: + """Disable every existing Saver and append a DiffSaver wired to `view`.""" + text = replace_blocks(text, tool_blocks(text, "Saver"), lambda b: "\n\t\t\tPassThrough = true," + b) + saver = fp.make_saver(view, case_id).replace("Saver1 =", "DiffSaver =").replace(f"{fp.CONTAINER_ROOT}/gt", f"{CONTAINER}/gt") + m = re.search(r"(?m)^\tTools\s*=\s*(?:ordered\(\)\s*)?\{", text) + end = block_end(text, m.end() - 1) + head = text[:end].rstrip() + head += "," if not head.endswith(",") and not head.endswith("{") else "" + return head + "\n" + saver + "\n\t" + text[end:] + + +# --------------------------------------------------------------------------------------------- +# Sampling +# --------------------------------------------------------------------------------------------- + + +def family_map() -> dict[str, str]: + fam = {} + for t in gc.TOOL_METADATA: + for n in (t.name, *t.aliases): + fam[n] = t.category + return fam + + +def supported_classes() -> set[str]: + declared, _ = gc.parse_comp_rs_modifiers(gc.COMP_RS) + return gc.parse_eval_rs(gc.EVAL_RS) | gc.parse_scene3d_rs(gc.SCENE3D_RS) | set(declared) | COSMETIC + + +def top_level_classes(text: str) -> list[str]: + m = gc.TOOLS_START_RE.search(text) + out = [] + for line in text[m.end() :].splitlines() if m else []: + if line.startswith("\t}"): + break + if tm := gc.TOP_TOOL_RE.match(line): + out.append(tm.group(1)) + return out + + +def describe(path: Path, supported: set[str], fam: dict[str, str]) -> dict: + text = path.read_text(encoding="utf-8", errors="replace") + classes = set(top_level_classes(text)) + tags = classes | {fam[c] for c in classes if c in fam} + tags |= {"expr"} if re.search(r"(?m)^\s*Expression\s*=", text) else set() + return { + "path": path, + "year": path.relative_to(SAMPLES).parts[0], + "classes": classes, + "tags": tags, + "unsupported": sorted(c for c in classes if c not in supported), + "fuses": sorted(c for c in classes if c.startswith("Fuse.")), + "size": len(text), + "renderable": bool(classes - {"BezierSpline", "PolyPath", "LUTBezier"} - COSMETIC), + } + + +def stratified_sample(comps: list[dict], limit: int) -> list[dict]: + """Round-robin over years; within a year prefer 0 unsupported, then new tags, then small. + Fuse comps are skipped: the render node hangs on Fuses it lacks.""" + by_year = defaultdict(list) + for c in comps: + if c["renderable"] and not c["fuses"]: + by_year[c["year"]].append(c) + seen: set[str] = set() + picked: list[dict] = [] + while len(picked) < limit and any(by_year.values()): + for year in sorted(by_year): + pool = by_year[year] + if not pool or len(picked) >= limit: + continue + best = min(pool, key=lambda c: (bool(c["unsupported"]), -len(c["tags"] - seen), c["size"], str(c["path"]))) + pool.remove(best) + seen |= best["tags"] + picked.append(best) + return picked + + +# --------------------------------------------------------------------------------------------- +# Rendering and comparison +# --------------------------------------------------------------------------------------------- + + +def case_id(path: Path) -> str: + rel = path.relative_to(SAMPLES).with_suffix("") + slug = re.sub(r"[^A-Za-z0-9]+", "_", "_".join(rel.parts)).strip("_")[:60] + return f"{slug}_{binascii.crc32(str(rel).encode()):08x}" + + +def run(cmd: list[str], timeout: int) -> tuple[int, str]: + try: + p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, errors="replace") + return p.returncode, p.stdout + "\n" + p.stderr + except subprocess.TimeoutExpired as e: + partial = b"\n".join(x or b"" for x in (e.stdout, e.stderr)) + return -1, f"timeout after {timeout}s\n" + partial.decode(errors="replace") + + +def last_lines(out: str, n: int = 3) -> str: + lines = [ln.strip() for ln in out.splitlines() if ln.strip()] + return " | ".join(lines[-n:])[:300] + + +FUSION_CAUSES = ( + (r'Unknown tool found: "[^"]*" \(([^)]+)\)', "unknown tool {}"), + (r"Could not find font: ([^\n]+)", "missing font {}"), + (r"(\w+) failed at time", "{} failed"), +) + + +def fusion_causes(out: str) -> list[str]: + """Distinct, comp-content-free reasons Fusion reported (tool classes, font names).""" + found = {fmt.format(m[1]) for pat, fmt in FUSION_CAUSES for m in re.finditer(pat, out)} + return sorted(found)[:6] + + +def fission(comp: Path, frame: int, out_png: Path, node: str | None, ref: Path | None) -> dict: + cmd = [str(fp.RENDER_CHECK), str(comp), str(frame), "--out", str(out_png)] + cmd += ["--node", node] if node else [] + cmd += ["--ref", str(ref)] if ref else [] + code, out = run(cmd, FISSION_TIMEOUT_S) + res = {"ok": code == 0 and out_png.exists(), "log": "" if code == 0 else last_lines(out)} + if m := re.search(r"viewing (\S+) at frame", out): + res["node"] = m[1] + if m := re.search(r"unsupported=\[(.*?)\]", out): + res["unsupported"] = re.findall(r'"([^"]+)"', m[1]) + if m := re.search(r"MAE=([\d.]+)/255 \(([\d.]+)%\), RMSE=([\d.]+)/255", out): + res.update(mae_pct=float(m[2]), rmse=float(m[3])) + return res + + +def fusion(comp: Path, frame: int, case: str) -> dict: + target = comp + if SHARED == LOCAL: + target = f"{REMOTE}/comps/{comp.name}" + subprocess.run(["sg", "upload", str(comp), target], check=True) + for old in (SHARED / "gt").glob(f"{case}_*.png"): + old.unlink() + for _ in range(2): # the shared render node intermittently fails with no cause in its log + code, out = run(["sg", "render", str(target), "--start", str(frame), "--end", str(frame)], FUSION_TIMEOUT_S) + if code == -1: # a hung node would otherwise keep the render slot + run(["ssh", "root@10.0.0.1", f"pkill -f 'FusionRenderNode .*{case}'"], 30) + if SHARED == LOCAL: + run(["sg", "download", f"{REMOTE}/gt/", str(SHARED / "gt")], 120) + # Success is the GT file, not the exit code or log text: both are unreliable through a pipe. + for _ in range(20 if code == 0 and not fusion_causes(out) else 1): # SMB lags the node's write + if gt := sorted((SHARED / "gt").glob(f"{case}_*.png")): + break + time.sleep(0.5) + if gt or code == -1 or fusion_causes(out): + break + ok = bool(gt) + log = "" if ok else ("timeout; " if code == -1 else f"exit {code}; ") + (", ".join(fusion_causes(out)) or last_lines(out, 2)) + return {"ok": ok, "gt": gt[0] if gt else None, "log": log} + + +def png_size(p: Path) -> tuple[int, int]: + return struct.unpack(">II", p.read_bytes()[16:24]) + + +def process(path: Path, fonts: bool) -> dict: + case = case_id(path) + rec = {"case": case, "comp": str(path.relative_to(SAMPLES)), "year": path.relative_to(SAMPLES).parts[0]} + text, frame = retarget(path.read_text(encoding="utf-8", errors="replace"), fonts) + rec["frame"] = frame + comps = SHARED / "comps" + comps.mkdir(parents=True, exist_ok=True) + ours = LOCAL / "ours" / f"{case}.png" + ours.parent.mkdir(parents=True, exist_ok=True) + + def local_copy(t: str, name: str) -> Path: + p = comps / name + p.write_text(t.replace(CONTAINER, str(SHARED))) + return p + + # Pass 1 renders the retargeted comp to learn which node render-check views. + first = fission(local_copy(text, f"{case}.pre.comp"), frame, ours, None, None) + rec["fission"] = {k: v for k, v in first.items() if k in ("ok", "log", "unsupported")} + view = first.get("node") + if not view: + rec["status"] = "fission_fail" + return rec + + final = add_diff_saver(text, case, view) + comp = comps / f"{case}.comp" + comp.write_text(final) + fus = fusion(comp, frame, case) + rec["fusion"] = {"ok": fus["ok"], "log": fus["log"]} + rec["view_node"] = view + if not first["ok"] or not fus["ok"]: + rec["status"] = "both_fail" if not first["ok"] and not fus["ok"] else ("fission_fail" if not first["ok"] else "fusion_fail") + return rec + + second = fission(local_copy(final, f"{case}.local.comp"), frame, ours, view, fus["gt"]) + if "mae_pct" not in second: + rec["status"], rec["fission"]["log"] = "fission_fail", second["log"] + return rec + rec.update(status="ok", mae_pct=second["mae_pct"], rmse=second["rmse"], size_fusion=png_size(fus["gt"]), size_fission=png_size(ours)) + rec["size_mismatch"] = rec["size_fusion"] != rec["size_fission"] + return rec + + +# --------------------------------------------------------------------------------------------- +# Reporting +# --------------------------------------------------------------------------------------------- + + +def report(records: list[dict], classes_by_comp: dict[str, set[str]], fam: dict[str, str]) -> dict: + ok = [r for r in records if r["status"] == "ok"] + passed = [r for r in ok if r["mae_pct"] < FAIL_MAE_PCT and not r["size_mismatch"]] + failing = [r for r in ok if r not in passed] + status = Counter(r["status"] for r in records) + + print(f"\n{'comp':<58} {'yr':<5} {'fr':>5} {'view':<16} {'MAE%':>7} {'RMSE':>7} status") + for r in sorted(records, key=lambda r: -r.get("mae_pct", -1)): + if r["status"] == "ok": + print(f"{r['comp'][-58:]:<58} {r['year']:<5} {r['frame']:>5} {r['view_node'][:16]:<16} {r['mae_pct']:7.2f} {r['rmse']:7.2f} {'SIZE ' if r['size_mismatch'] else ''}{'FAIL' if r in failing else 'pass'}") + else: + why = (r.get("fusion", {}).get("log") or r.get("fission", {}).get("log") or "")[:70] + print(f"{r['comp'][-58:]:<58} {r['year']:<5} {r['frame']:>5} {r.get('view_node', '-')[:16]:<16} {'-':>7} {'-':>7} {r['status']}: {why}") + + n = len(records) + print(f"\nattempted {n} | clean on both {len(ok)} | pass <{FAIL_MAE_PCT}% MAE {len(passed)}/{len(ok)} | {dict(status)}") + if ok: + print(f"mean MAE {sum(r['mae_pct'] for r in ok) / len(ok):.2f}% | median {sorted(r['mae_pct'] for r in ok)[len(ok) // 2]:.2f}%") + + # Counts are comps (not tool instances) that rendered on both sides. + per_tool, per_family = defaultdict(lambda: [0, 0]), defaultdict(lambda: [0, 0]) + for r in ok: + tools = classes_by_comp[r["comp"]] - {"BezierSpline", "PolyPath", "LUTBezier", "Saver"} - COSMETIC + for c in tools: + per_tool[c][0] += 1 + per_tool[c][1] += r in failing + for f in {fam.get(c, "Unsupported / other") for c in tools}: + per_family[f][0] += 1 + per_family[f][1] += r in failing + print(f"\nfailing comps (>{FAIL_MAE_PCT}% MAE) by tool family: [comps-with-failure / comps-containing]") + for f, (seen, bad) in sorted(per_family.items(), key=lambda kv: -kv[1][1]): + print(f" {f:<28} {bad:>3} / {seen:<3}") + print("top tool types in failing comps:") + for c, (seen, bad) in sorted(per_tool.items(), key=lambda kv: (-kv[1][1], -kv[1][0]))[:15]: + if bad: + print(f" {c:<26} {bad:>3} / {seen:<3} ({fam.get(c, 'Unsupported / other')})") + + return { + "attempted": n, + "status": dict(status), + "clean_on_both": len(ok), + "pass": len(passed), + "fail_threshold_mae_pct": FAIL_MAE_PCT, + "per_family": {f: {"failing": b, "containing": s} for f, (s, b) in per_family.items()}, + "per_tool": {c: {"failing": b, "containing": s} for c, (s, b) in per_tool.items()}, + "cases": records, + } + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--limit", type=int, default=25) + ap.add_argument("--comp", type=Path, action="append", help="debug a single comp (repeatable)") + ap.add_argument("--report-json", type=Path) + ap.add_argument("--keep-fonts", action="store_true", help="keep original Font/Style (Fusion fails renders whose fonts it lacks)") + args = ap.parse_args() + + supported, fam = supported_classes(), family_map() + corpus = [describe(p, supported, fam) for p in sorted(SAMPLES.rglob("*.comp"))] + if args.comp: + wanted = {(fp.REPO / p).resolve() for p in args.comp} + picked = [c for c in corpus if c["path"].resolve() in wanted] + else: + picked = stratified_sample(corpus, args.limit) + if not picked: + print("no comps selected", file=sys.stderr) + return 1 + print(f"selected {len(picked)} of {len(corpus)} comps: years {dict(Counter(c['year'] for c in picked))}") + + ensure_assets() + for sub in ("comps", "gt"): + (SHARED / sub).mkdir(parents=True, exist_ok=True) + if SHARED == LOCAL: + for sub in ("comps", "gt"): + subprocess.run(["sg", "upload", str(SHARED / sub), f"{REMOTE}/"], check=True) + + records = [] + for i, c in enumerate(picked, 1): + rec = process(c["path"], not args.keep_fonts) + rec["unsupported_static"] = c["unsupported"] + rec["tools"] = sorted(c["classes"]) + records.append(rec) + print(f"[{i}/{len(picked)}] {rec['comp'][-60:]} -> {rec['status']}" + (f" MAE {rec['mae_pct']:.2f}%" if rec["status"] == "ok" else ""), flush=True) + + out = report(records, {str(c["path"].relative_to(SAMPLES)): c["classes"] for c in picked}, fam) + if args.report_json: + args.report_json.write_text(json.dumps(out, indent=2, default=str)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) -- 2.54.1