authoravatarclover caruso<git@paperclover.net>2026-11-30 16:13:36-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 17:11:04-08:00
log6ff029e096a6cbb192512d9fddccd47317c0543f
treec523831a82dc4624bce3ee9eab187cf7e8ae8243
parent8ee57b10bd34e1327dca9974ff6854a7c8b0a3eb
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

1 files changed, 565 insertions(+), 0 deletions(-)

scripts/archive_diff.py created+565
......@@ -0,0 +1,565 @@
1#!/usr/bin/env python3
2"""Privacy-safe archive differential harness: real .comp graphs, synthetic media.
3
4Rewrites comps from private/samples/ so every Loader reads one of four generated plates and a
5DiffSaver captures the node render-check views, renders one frame on Snow Globe Fusion
6(`sg render`) and on Fission (`render-check`), then reports per-comp and per-tool-family error.
7
8 python3 scripts/archive_diff.py --limit 25 --report-json /tmp/archive_diff_report.json
9 python3 scripts/archive_diff.py --comp "private/samples/2024/technique for improvement/technique.comp"
10
11No archive media is ever read; only .comp text. Outputs live under /tmp/fission_archive_diff
12(and the Snow Globe share when mounted) and are never committed.
13"""
14
15from __future__ import annotations
16
17import argparse
18import binascii
19import json
20import math
21import re
22import struct
23import subprocess
24import sys
25import time
26from collections import Counter, defaultdict
27from pathlib import Path
28
29import fusion_probes as fp
30import gen_compatibility as gc
31
32SAMPLES = fp.REPO / "private" / "samples"
33LOCAL = Path("/tmp/fission_archive_diff")
34SHARED = fp.SMB_ROOT / "archive_diff" if fp.use_smb() else LOCAL
35CONTAINER = f"{fp.CONTAINER_ROOT}/archive_diff"
36REMOTE = f"{fp.REMOTE_ROOT}/archive_diff"
37PLATE_W, PLATE_H, PLATES = 640, 360, 4
38FAIL_MAE_PCT = 1.5
39FUSION_TIMEOUT_S, FISSION_TIMEOUT_S = 90, 120
40# Cosmetic classes with no render behavior; never count as unsupported.
41COSMETIC = {"Note", "Underlay"}
42
43# ---------------------------------------------------------------------------------------------
44# Synthetic media
45# ---------------------------------------------------------------------------------------------
46
47
48def make_plate(k: int) -> bytes:
49 """RGBA plate k: hue/value gradient, diagonal gridlines, alpha cutouts, shapes, id bars."""
50 w, h = PLATE_W, PLATE_H
51 buf = bytearray(w * h * 4)
52 flip = k % 2
53 for y in range(h):
54 ny = y / (h - 1)
55 for x in range(w):
56 nx = x / (w - 1)
57 t = nx if k < 2 else ny
58 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))
59 a = 255
60 if (x + y * (1 + k % 3)) % 48 < 2:
61 r, g, b = (1.0 - r, 1.0 - g, 1.0 - b)
62 if y > h - 50: # soft alpha ramp keeps RGB, so premultiply bugs show
63 a = int(255 * (h - 1 - y) / 49)
64 if y < 16 and x < 16 * 4: # plate id in binary, one cell per bit
65 on = ((k + 1) >> (x // 16)) & 1
66 r = g = b = 1.0 if on else 0.0
67 buf[(y * w + x) * 4 : (y * w + x) * 4 + 4] = bytes((int(r * 255), int(g * 255), int(b * 255), a))
68
69 def px(x, y, rgb, a=255):
70 i = (y * w + x) * 4
71 buf[i : i + 4] = bytes((*rgb, a))
72
73 # Asymmetric shapes, positions rotate per plate so flips and rotations are detectable.
74 cx, cy = (w * (0.25 + 0.5 * flip), h * (0.3 + 0.35 * (k // 2)))
75 palette = [(255, 40, 40), (40, 255, 80), (60, 90, 255), (255, 230, 30)]
76 for y in range(h):
77 for x in range(w):
78 d = math.hypot(x - cx, y - cy)
79 if d < 70:
80 px(x, y, palette[k], 255)
81 if 24 < d < 36 and x > cx: # alpha-0 cutout ring (half), RGB kept
82 px(x, y, palette[(k + 1) % 4], 0)
83 if abs(x - (w - cx)) < 55 and abs(y - (h - cy)) < 38: # translucent block
84 px(x, y, palette[(k + 2) % 4], 128)
85 if 0 <= x - 10 < 24 and 60 <= y < 220 or 0 <= x - 10 < 110 and 196 <= y < 220: # asymmetric "L"
86 px(x, y, (255, 255, 255))
87 if y > h * 0.55 and abs(x - w / 2) < (y - h * 0.55) * 0.4 and y < h - 60: # triangle
88 px(x, y, palette[(k + 3) % 4], 255)
89 return bytes(buf)
90
91
92# The FBX SDK names OBJ meshes by their `g` group and ignores `o`; ObjName must match it.
93MESH_OBJ = """g synth_cube
94v -50 -50 50
95v 50 -50 50
96v 50 50 50
97v -50 50 50
98v -50 -50 -50
99v 50 -50 -50
100v 50 50 -50
101v -50 50 -50
102vt 0 0
103vt 1 0
104vt 1 1
105vt 0 1
106vn 0 0 1
107vn 0 0 -1
108vn 1 0 0
109vn -1 0 0
110vn 0 1 0
111vn 0 -1 0
112f 1/1/1 2/2/1 3/3/1 4/4/1
113f 6/1/2 5/2/2 8/3/2 7/4/2
114f 2/1/3 6/2/3 7/3/3 3/4/3
115f 5/1/4 1/2/4 4/3/4 8/4/4
116f 4/1/5 3/2/5 7/3/5 8/4/5
117f 5/1/6 6/2/6 2/3/6 1/4/6
118"""
119
120
121def ensure_assets():
122 """Write the plates and mesh into SHARED/assets (and sg upload them when SMB isn't mounted)."""
123 d = SHARED / "assets"
124 d.mkdir(parents=True, exist_ok=True)
125 for k in range(PLATES):
126 p = d / f"synth_{k}.png"
127 if not p.exists():
128 fp.write_png_rgba(p, PLATE_W, PLATE_H, make_plate(k))
129 mesh = d / "synth_mesh.obj"
130 mesh.write_text(MESH_OBJ)
131 if SHARED == LOCAL:
132 subprocess.run(["sg", "upload", str(d), f"{REMOTE}/"], check=True)
133
134
135# ---------------------------------------------------------------------------------------------
136# Comp text: brace-aware helpers and the rewriter
137# ---------------------------------------------------------------------------------------------
138
139_TOKEN = re.compile(r'[{}"]|\\.', re.S)
140_STR = r'"((?:[^"\\]|\\.)*)"'
141
142
143def block_end(text: str, open_i: int) -> int:
144 """Index of the `}` matching the `{` at open_i, skipping quoted strings."""
145 depth, in_str = 0, False
146 for m in _TOKEN.finditer(text, open_i):
147 t = m.group()
148 if t[0] == "\\":
149 continue
150 if t == '"':
151 in_str = not in_str
152 elif not in_str:
153 depth += 1 if t == "{" else -1
154 if depth == 0:
155 return m.start()
156 raise ValueError("unbalanced braces")
157
158
159def tool_blocks(text: str, kind: str):
160 """(open_brace, close_brace) of every `name = kind {` at any depth, in file order."""
161 pat = re.compile(rf'(?m)^[ \t]*(?:\["[^"]+"\]|[A-Za-z_]\w*)\s*=\s*{re.escape(kind)}\s*\{{')
162 return [(m.end() - 1, block_end(text, m.end() - 1)) for m in pat.finditer(text)]
163
164
165def replace_blocks(text: str, blocks, fn) -> str:
166 """Replace each block's inner text (between braces) with fn(inner), back to front."""
167 for o, c in reversed(blocks):
168 text = text[: o + 1] + fn(text[o + 1 : c]) + text[c:]
169 return text
170
171
172def drop_inputs(body: str, names) -> str:
173 """Remove `Name = Input { ... },` entries (single or multi-line) from a tool body."""
174 for name in names:
175 pat = re.compile(rf'(?m)^[ \t]*(?:\["{re.escape(name)}"\]|{re.escape(name)})\s*=\s*Input\s*\{{')
176 while m := pat.search(body):
177 end = block_end(body, m.end() - 1) + 1
178 end += 1 if body[end : end + 1] == "," else 0
179 end += 1 if body[end : end + 1] == "\n" else 0
180 body = body[: m.start()] + body[end:]
181 return body
182
183
184def add_inputs(body: str, entries: str) -> str:
185 """Insert entries at the top of the tool's `Inputs = {` table, creating it if absent."""
186 m = re.search(r"Inputs\s*=\s*\{", body)
187 if m:
188 return body[: m.end()] + "\n" + entries + body[m.end() :]
189 return "\n\t\t\tInputs = {\n" + entries + "\t\t\t},\n" + body
190
191
192def synth_index(original: str) -> int:
193 return binascii.crc32(original.encode()) % PLATES
194
195
196def retarget_loader(body: str, frame: int) -> str:
197 """Point a Loader at one synthetic still that is present on every frame."""
198 m = re.search(r"Clips\s*=\s*\{", body)
199 if not m:
200 return body
201 end = block_end(body, m.end() - 1)
202 clips = body[m.start() : end + 1]
203 cid = (re.search(rf"ID\s*=\s*{_STR}", clips) or [None, "Clip1"])[1]
204 k = synth_index((re.search(rf"Filename\s*=\s*{_STR}", clips) or [None, ""])[1])
205 new = (
206 'Clips = {\n\t\t\t\tClip {\n'
207 f'\t\t\t\t\tID = "{cid}",\n'
208 f'\t\t\t\t\tFilename = "{CONTAINER}/assets/synth_{k}.png",\n'
209 '\t\t\t\t\tFormatID = "PNGFormat",\n'
210 "\t\t\t\t\tLength = 1,\n\t\t\t\t\tLengthSetManually = true,\n"
211 f"\t\t\t\t\tStartFrame = {k},\n" # Fusion scans synth_N.png as one numbered sequence; this pins plate k
212 "\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"
213 f"\t\t\t\t\tGlobalStart = {frame},\n\t\t\t\t\tGlobalEnd = {frame},\n"
214 "\t\t\t\t}\n\t\t\t}"
215 )
216 body = body[: m.start()] + new + body[end + 1 :]
217 # Global range and clip trim inputs describe the real footage; the still must exist at `frame`.
218 body = drop_inputs(body, ["GlobalIn", "GlobalOut", "ClipTimeStart", "ClipTimeEnd", "HoldFirstFrame", "HoldLastFrame"])
219 return add_inputs(body, f"\t\t\t\tGlobalIn = Input {{ Value = {frame}, }},\n\t\t\t\tGlobalOut = Input {{ Value = {frame}, }},\n")
220
221
222def retarget_mesh(body: str) -> str:
223 """Map a missing ImportFile (and the mesh name selected inside it) to the synthetic mesh."""
224
225 def sub(m):
226 return m.group(0) if Path(m.group(2).replace("\\\\", "\\")).exists() else f'{m.group(1)}"{CONTAINER}/assets/synth_mesh.obj"'
227
228 mapped = re.sub(rf"(ImportFile\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}", sub, body)
229 if mapped == body:
230 return body
231 return re.sub(rf"(ObjName\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}", r'\1"synth_cube"', mapped)
232
233
234def normalize_fonts(text: str) -> str:
235 """Map every font family/style (inputs and character-level styling 100/109) to Liberation Sans/Regular."""
236 for pat, value in (
237 (rf'(?m)^(\s*Font\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}', "Liberation Sans"),
238 (rf'(?m)^(\s*Style\s*=\s*Input\s*\{{\s*Value\s*=\s*){_STR}', "Regular"),
239 (rf"(Parameter\s*=\s*100,[^{{}}]*?String\s*=\s*){_STR}", "Liberation Sans"),
240 (rf"(Parameter\s*=\s*109,[^{{}}]*?String\s*=\s*){_STR}", "Regular"),
241 ):
242 text = re.sub(pat, rf'\1"{value}"', text)
243 return text
244
245
246def pick_frame(text: str) -> int:
247 """Midpoint of the original RenderRange, else CurrentTime, else 0."""
248 rr = re.search(r"(?m)^\tRenderRange\s*=\s*\{\s*(-?\d+)\s*,\s*(-?\d+)", text)
249 if rr and int(rr[1]) < int(rr[2]):
250 return (int(rr[1]) + int(rr[2])) // 2
251 ct = re.search(r"(?m)^\tCurrentTime\s*=\s*(-?\d+)", text)
252 return int(ct[1]) if ct else 0
253
254
255def retarget(text: str, fonts: bool) -> tuple[str, int]:
256 """Comp text with synthetic media and a single-frame range; node graph untouched."""
257 frame = pick_frame(text)
258 text = normalize_fonts(text) if fonts else text
259 text = replace_blocks(text, tool_blocks(text, "Loader"), lambda b: retarget_loader(b, frame))
260 text = replace_blocks(text, tool_blocks(text, "SurfaceFBXMesh"), retarget_mesh)
261 text = re.sub(r"(?m)^\tRenderRange\s*=\s*\{[^}]*\},", f"\tRenderRange = {{ {frame}, {frame} }},", text, count=1)
262 text = re.sub(r"(?m)^\tCurrentTime\s*=\s*-?\d+,", f"\tCurrentTime = {frame},", text, count=1)
263 text = re.sub(r"(?m)^\tAudioFilename\s*=.*\n", "", text, count=1)
264 return text, frame
265
266
267def add_diff_saver(text: str, case_id: str, view: str) -> str:
268 """Disable every existing Saver and append a DiffSaver wired to `view`."""
269 text = replace_blocks(text, tool_blocks(text, "Saver"), lambda b: "\n\t\t\tPassThrough = true," + b)
270 saver = fp.make_saver(view, case_id).replace("Saver1 =", "DiffSaver =").replace(f"{fp.CONTAINER_ROOT}/gt", f"{CONTAINER}/gt")
271 m = re.search(r"(?m)^\tTools\s*=\s*(?:ordered\(\)\s*)?\{", text)
272 end = block_end(text, m.end() - 1)
273 head = text[:end].rstrip()
274 head += "," if not head.endswith(",") and not head.endswith("{") else ""
275 return head + "\n" + saver + "\n\t" + text[end:]
276
277
278# ---------------------------------------------------------------------------------------------
279# Sampling
280# ---------------------------------------------------------------------------------------------
281
282
283def family_map() -> dict[str, str]:
284 fam = {}
285 for t in gc.TOOL_METADATA:
286 for n in (t.name, *t.aliases):
287 fam[n] = t.category
288 return fam
289
290
291def supported_classes() -> set[str]:
292 declared, _ = gc.parse_comp_rs_modifiers(gc.COMP_RS)
293 return gc.parse_eval_rs(gc.EVAL_RS) | gc.parse_scene3d_rs(gc.SCENE3D_RS) | set(declared) | COSMETIC
294
295
296def top_level_classes(text: str) -> list[str]:
297 m = gc.TOOLS_START_RE.search(text)
298 out = []
299 for line in text[m.end() :].splitlines() if m else []:
300 if line.startswith("\t}"):
301 break
302 if tm := gc.TOP_TOOL_RE.match(line):
303 out.append(tm.group(1))
304 return out
305
306
307def describe(path: Path, supported: set[str], fam: dict[str, str]) -> dict:
308 text = path.read_text(encoding="utf-8", errors="replace")
309 classes = set(top_level_classes(text))
310 tags = classes | {fam[c] for c in classes if c in fam}
311 tags |= {"expr"} if re.search(r"(?m)^\s*Expression\s*=", text) else set()
312 return {
313 "path": path,
314 "year": path.relative_to(SAMPLES).parts[0],
315 "classes": classes,
316 "tags": tags,
317 "unsupported": sorted(c for c in classes if c not in supported),
318 "fuses": sorted(c for c in classes if c.startswith("Fuse.")),
319 "size": len(text),
320 "renderable": bool(classes - {"BezierSpline", "PolyPath", "LUTBezier"} - COSMETIC),
321 }
322
323
324def stratified_sample(comps: list[dict], limit: int) -> list[dict]:
325 """Round-robin over years; within a year prefer 0 unsupported, then new tags, then small.
326 Fuse comps are skipped: the render node hangs on Fuses it lacks."""
327 by_year = defaultdict(list)
328 for c in comps:
329 if c["renderable"] and not c["fuses"]:
330 by_year[c["year"]].append(c)
331 seen: set[str] = set()
332 picked: list[dict] = []
333 while len(picked) < limit and any(by_year.values()):
334 for year in sorted(by_year):
335 pool = by_year[year]
336 if not pool or len(picked) >= limit:
337 continue
338 best = min(pool, key=lambda c: (bool(c["unsupported"]), -len(c["tags"] - seen), c["size"], str(c["path"])))
339 pool.remove(best)
340 seen |= best["tags"]
341 picked.append(best)
342 return picked
343
344
345# ---------------------------------------------------------------------------------------------
346# Rendering and comparison
347# ---------------------------------------------------------------------------------------------
348
349
350def case_id(path: Path) -> str:
351 rel = path.relative_to(SAMPLES).with_suffix("")
352 slug = re.sub(r"[^A-Za-z0-9]+", "_", "_".join(rel.parts)).strip("_")[:60]
353 return f"{slug}_{binascii.crc32(str(rel).encode()):08x}"
354
355
356def run(cmd: list[str], timeout: int) -> tuple[int, str]:
357 try:
358 p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, errors="replace")
359 return p.returncode, p.stdout + "\n" + p.stderr
360 except subprocess.TimeoutExpired as e:
361 partial = b"\n".join(x or b"" for x in (e.stdout, e.stderr))
362 return -1, f"timeout after {timeout}s\n" + partial.decode(errors="replace")
363
364
365def last_lines(out: str, n: int = 3) -> str:
366 lines = [ln.strip() for ln in out.splitlines() if ln.strip()]
367 return " | ".join(lines[-n:])[:300]
368
369
370FUSION_CAUSES = (
371 (r'Unknown tool found: "[^"]*" \(([^)]+)\)', "unknown tool {}"),
372 (r"Could not find font: ([^\n]+)", "missing font {}"),
373 (r"(\w+) failed at time", "{} failed"),
374)
375
376
377def fusion_causes(out: str) -> list[str]:
378 """Distinct, comp-content-free reasons Fusion reported (tool classes, font names)."""
379 found = {fmt.format(m[1]) for pat, fmt in FUSION_CAUSES for m in re.finditer(pat, out)}
380 return sorted(found)[:6]
381
382
383def fission(comp: Path, frame: int, out_png: Path, node: str | None, ref: Path | None) -> dict:
384 cmd = [str(fp.RENDER_CHECK), str(comp), str(frame), "--out", str(out_png)]
385 cmd += ["--node", node] if node else []
386 cmd += ["--ref", str(ref)] if ref else []
387 code, out = run(cmd, FISSION_TIMEOUT_S)
388 res = {"ok": code == 0 and out_png.exists(), "log": "" if code == 0 else last_lines(out)}
389 if m := re.search(r"viewing (\S+) at frame", out):
390 res["node"] = m[1]
391 if m := re.search(r"unsupported=\[(.*?)\]", out):
392 res["unsupported"] = re.findall(r'"([^"]+)"', m[1])
393 if m := re.search(r"MAE=([\d.]+)/255 \(([\d.]+)%\), RMSE=([\d.]+)/255", out):
394 res.update(mae_pct=float(m[2]), rmse=float(m[3]))
395 return res
396
397
398def fusion(comp: Path, frame: int, case: str) -> dict:
399 target = comp
400 if SHARED == LOCAL:
401 target = f"{REMOTE}/comps/{comp.name}"
402 subprocess.run(["sg", "upload", str(comp), target], check=True)
403 for old in (SHARED / "gt").glob(f"{case}_*.png"):
404 old.unlink()
405 for _ in range(2): # the shared render node intermittently fails with no cause in its log
406 code, out = run(["sg", "render", str(target), "--start", str(frame), "--end", str(frame)], FUSION_TIMEOUT_S)
407 if code == -1: # a hung node would otherwise keep the render slot
408 run(["ssh", "root@10.0.0.1", f"pkill -f 'FusionRenderNode .*{case}'"], 30)
409 if SHARED == LOCAL:
410 run(["sg", "download", f"{REMOTE}/gt/", str(SHARED / "gt")], 120)
411 # Success is the GT file, not the exit code or log text: both are unreliable through a pipe.
412 for _ in range(20 if code == 0 and not fusion_causes(out) else 1): # SMB lags the node's write
413 if gt := sorted((SHARED / "gt").glob(f"{case}_*.png")):
414 break
415 time.sleep(0.5)
416 if gt or code == -1 or fusion_causes(out):
417 break
418 ok = bool(gt)
419 log = "" if ok else ("timeout; " if code == -1 else f"exit {code}; ") + (", ".join(fusion_causes(out)) or last_lines(out, 2))
420 return {"ok": ok, "gt": gt[0] if gt else None, "log": log}
421
422
423def png_size(p: Path) -> tuple[int, int]:
424 return struct.unpack(">II", p.read_bytes()[16:24])
425
426
427def process(path: Path, fonts: bool) -> dict:
428 case = case_id(path)
429 rec = {"case": case, "comp": str(path.relative_to(SAMPLES)), "year": path.relative_to(SAMPLES).parts[0]}
430 text, frame = retarget(path.read_text(encoding="utf-8", errors="replace"), fonts)
431 rec["frame"] = frame
432 comps = SHARED / "comps"
433 comps.mkdir(parents=True, exist_ok=True)
434 ours = LOCAL / "ours" / f"{case}.png"
435 ours.parent.mkdir(parents=True, exist_ok=True)
436
437 def local_copy(t: str, name: str) -> Path:
438 p = comps / name
439 p.write_text(t.replace(CONTAINER, str(SHARED)))
440 return p
441
442 # Pass 1 renders the retargeted comp to learn which node render-check views.
443 first = fission(local_copy(text, f"{case}.pre.comp"), frame, ours, None, None)
444 rec["fission"] = {k: v for k, v in first.items() if k in ("ok", "log", "unsupported")}
445 view = first.get("node")
446 if not view:
447 rec["status"] = "fission_fail"
448 return rec
449
450 final = add_diff_saver(text, case, view)
451 comp = comps / f"{case}.comp"
452 comp.write_text(final)
453 fus = fusion(comp, frame, case)
454 rec["fusion"] = {"ok": fus["ok"], "log": fus["log"]}
455 rec["view_node"] = view
456 if not first["ok"] or not fus["ok"]:
457 rec["status"] = "both_fail" if not first["ok"] and not fus["ok"] else ("fission_fail" if not first["ok"] else "fusion_fail")
458 return rec
459
460 second = fission(local_copy(final, f"{case}.local.comp"), frame, ours, view, fus["gt"])
461 if "mae_pct" not in second:
462 rec["status"], rec["fission"]["log"] = "fission_fail", second["log"]
463 return rec
464 rec.update(status="ok", mae_pct=second["mae_pct"], rmse=second["rmse"], size_fusion=png_size(fus["gt"]), size_fission=png_size(ours))
465 rec["size_mismatch"] = rec["size_fusion"] != rec["size_fission"]
466 return rec
467
468
469# ---------------------------------------------------------------------------------------------
470# Reporting
471# ---------------------------------------------------------------------------------------------
472
473
474def report(records: list[dict], classes_by_comp: dict[str, set[str]], fam: dict[str, str]) -> dict:
475 ok = [r for r in records if r["status"] == "ok"]
476 passed = [r for r in ok if r["mae_pct"] < FAIL_MAE_PCT and not r["size_mismatch"]]
477 failing = [r for r in ok if r not in passed]
478 status = Counter(r["status"] for r in records)
479
480 print(f"\n{'comp':<58} {'yr':<5} {'fr':>5} {'view':<16} {'MAE%':>7} {'RMSE':>7} status")
481 for r in sorted(records, key=lambda r: -r.get("mae_pct", -1)):
482 if r["status"] == "ok":
483 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'}")
484 else:
485 why = (r.get("fusion", {}).get("log") or r.get("fission", {}).get("log") or "")[:70]
486 print(f"{r['comp'][-58:]:<58} {r['year']:<5} {r['frame']:>5} {r.get('view_node', '-')[:16]:<16} {'-':>7} {'-':>7} {r['status']}: {why}")
487
488 n = len(records)
489 print(f"\nattempted {n} | clean on both {len(ok)} | pass <{FAIL_MAE_PCT}% MAE {len(passed)}/{len(ok)} | {dict(status)}")
490 if ok:
491 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}%")
492
493 # Counts are comps (not tool instances) that rendered on both sides.
494 per_tool, per_family = defaultdict(lambda: [0, 0]), defaultdict(lambda: [0, 0])
495 for r in ok:
496 tools = classes_by_comp[r["comp"]] - {"BezierSpline", "PolyPath", "LUTBezier", "Saver"} - COSMETIC
497 for c in tools:
498 per_tool[c][0] += 1
499 per_tool[c][1] += r in failing
500 for f in {fam.get(c, "Unsupported / other") for c in tools}:
501 per_family[f][0] += 1
502 per_family[f][1] += r in failing
503 print(f"\nfailing comps (>{FAIL_MAE_PCT}% MAE) by tool family: [comps-with-failure / comps-containing]")
504 for f, (seen, bad) in sorted(per_family.items(), key=lambda kv: -kv[1][1]):
505 print(f" {f:<28} {bad:>3} / {seen:<3}")
506 print("top tool types in failing comps:")
507 for c, (seen, bad) in sorted(per_tool.items(), key=lambda kv: (-kv[1][1], -kv[1][0]))[:15]:
508 if bad:
509 print(f" {c:<26} {bad:>3} / {seen:<3} ({fam.get(c, 'Unsupported / other')})")
510
511 return {
512 "attempted": n,
513 "status": dict(status),
514 "clean_on_both": len(ok),
515 "pass": len(passed),
516 "fail_threshold_mae_pct": FAIL_MAE_PCT,
517 "per_family": {f: {"failing": b, "containing": s} for f, (s, b) in per_family.items()},
518 "per_tool": {c: {"failing": b, "containing": s} for c, (s, b) in per_tool.items()},
519 "cases": records,
520 }
521
522
523def main() -> int:
524 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
525 ap.add_argument("--limit", type=int, default=25)
526 ap.add_argument("--comp", type=Path, action="append", help="debug a single comp (repeatable)")
527 ap.add_argument("--report-json", type=Path)
528 ap.add_argument("--keep-fonts", action="store_true", help="keep original Font/Style (Fusion fails renders whose fonts it lacks)")
529 args = ap.parse_args()
530
531 supported, fam = supported_classes(), family_map()
532 corpus = [describe(p, supported, fam) for p in sorted(SAMPLES.rglob("*.comp"))]
533 if args.comp:
534 wanted = {(fp.REPO / p).resolve() for p in args.comp}
535 picked = [c for c in corpus if c["path"].resolve() in wanted]
536 else:
537 picked = stratified_sample(corpus, args.limit)
538 if not picked:
539 print("no comps selected", file=sys.stderr)
540 return 1
541 print(f"selected {len(picked)} of {len(corpus)} comps: years {dict(Counter(c['year'] for c in picked))}")
542
543 ensure_assets()
544 for sub in ("comps", "gt"):
545 (SHARED / sub).mkdir(parents=True, exist_ok=True)
546 if SHARED == LOCAL:
547 for sub in ("comps", "gt"):
548 subprocess.run(["sg", "upload", str(SHARED / sub), f"{REMOTE}/"], check=True)
549
550 records = []
551 for i, c in enumerate(picked, 1):
552 rec = process(c["path"], not args.keep_fonts)
553 rec["unsupported_static"] = c["unsupported"]
554 rec["tools"] = sorted(c["classes"])
555 records.append(rec)
556 print(f"[{i}/{len(picked)}] {rec['comp'][-60:]} -> {rec['status']}" + (f" MAE {rec['mae_pct']:.2f}%" if rec["status"] == "ok" else ""), flush=True)
557
558 out = report(records, {str(c["path"].relative_to(SAMPLES)): c["classes"] for c in picked}, fam)
559 if args.report_json:
560 args.report_json.write_text(json.dumps(out, indent=2, default=str))
561 return 0
562
563
564if __name__ == "__main__":
565 sys.exit(main())