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 return list(gc.count_tool_classes(text).keys())
298
299
300def describe(path: Path, supported: set[str], fam: dict[str, str]) -> dict:
301 text = path.read_text(encoding="utf-8", errors="replace")
302 classes = set(top_level_classes(text))
303 tags = classes | {fam[c] for c in classes if c in fam}
304 tags |= {"expr"} if re.search(r"(?m)^\s*Expression\s*=", text) else set()
305 return {
306 "path": path,
307 "year": path.relative_to(SAMPLES).parts[0],
308 "classes": classes,
309 "tags": tags,
310 "unsupported": sorted(c for c in classes if c not in supported),
311 "fuses": sorted(c for c in classes if c.startswith("Fuse.")),
312 "size": len(text),
313 "renderable": bool(classes - {"BezierSpline", "PolyPath", "LUTBezier"} - COSMETIC),
314 }
315
316
317def stratified_sample(comps: list[dict], limit: int) -> list[dict]:
318 """Round-robin over years; within a year prefer 0 unsupported, then new tags, then small.
319 Fuse comps are skipped: the render node hangs on Fuses it lacks."""
320 by_year = defaultdict(list)
321 for c in comps:
322 if c["renderable"] and not c["fuses"]:
323 by_year[c["year"]].append(c)
324 seen: set[str] = set()
325 picked: list[dict] = []
326 while len(picked) < limit and any(by_year.values()):
327 for year in sorted(by_year):
328 pool = by_year[year]
329 if not pool or len(picked) >= limit:
330 continue
331 best = min(pool, key=lambda c: (bool(c["unsupported"]), -len(c["tags"] - seen), c["size"], str(c["path"])))
332 pool.remove(best)
333 seen |= best["tags"]
334 picked.append(best)
335 return picked
336
337
338# ---------------------------------------------------------------------------------------------
339# Rendering and comparison
340# ---------------------------------------------------------------------------------------------
341
342
343def case_id(path: Path) -> str:
344 rel = path.relative_to(SAMPLES).with_suffix("")
345 slug = re.sub(r"[^A-Za-z0-9]+", "_", "_".join(rel.parts)).strip("_")[:60]
346 return f"{slug}_{binascii.crc32(str(rel).encode()):08x}"
347
348
349def run(cmd: list[str], timeout: int) -> tuple[int, str]:
350 try:
351 p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, errors="replace")
352 return p.returncode, p.stdout + "\n" + p.stderr
353 except subprocess.TimeoutExpired as e:
354 partial = b"\n".join(x or b"" for x in (e.stdout, e.stderr))
355 return -1, f"timeout after {timeout}s\n" + partial.decode(errors="replace")
356
357
358def last_lines(out: str, n: int = 3) -> str:
359 lines = [ln.strip() for ln in out.splitlines() if ln.strip()]
360 return " | ".join(lines[-n:])[:300]
361
362
363FUSION_CAUSES = (
364 (r'Unknown tool found: "[^"]*" \(([^)]+)\)', "unknown tool {}"),
365 (r"Could not find font: ([^\n]+)", "missing font {}"),
366 (r"(\w+) failed at time", "{} failed"),
367)
368
369
370def fusion_causes(out: str) -> list[str]:
371 """Distinct, comp-content-free reasons Fusion reported (tool classes, font names)."""
372 found = {fmt.format(m[1]) for pat, fmt in FUSION_CAUSES for m in re.finditer(pat, out)}
373 return sorted(found)[:6]
374
375
376def fission(comp: Path, frame: int, out_png: Path, node: str | None, ref: Path | None) -> dict:
377 cmd = [str(fp.RENDER_CHECK), str(comp), str(frame), "--out", str(out_png)]
378 cmd += ["--node", node] if node else []
379 cmd += ["--ref", str(ref)] if ref else []
380 code, out = run(cmd, FISSION_TIMEOUT_S)
381 res = {"ok": code == 0 and out_png.exists(), "log": "" if code == 0 else last_lines(out)}
382 if m := re.search(r"viewing (\S+) at frame", out):
383 res["node"] = m[1]
384 if m := re.search(r"unsupported=\[(.*?)\]", out):
385 res["unsupported"] = re.findall(r'"([^"]+)"', m[1])
386 if m := re.search(r"MAE=([\d.]+)/255 \(([\d.]+)%\), (?:A_MAE=([\d.]+)/255, )?RMSE=([\d.]+)/255", out):
387 res.update(mae_pct=float(m[2]), rmse=float(m[4]))
388 if m[3] is not None:
389 res["a_mae"] = float(m[3])
390 return res
391
392
393def fusion(comp: Path, frame: int, case: str) -> dict:
394 target = comp
395 if SHARED == LOCAL:
396 target = f"{REMOTE}/comps/{comp.name}"
397 subprocess.run(["sg", "upload", str(comp), target], check=True)
398 for old in (SHARED / "gt").glob(f"{case}_*.png"):
399 old.unlink()
400 for _ in range(2): # the shared render node intermittently fails with no cause in its log
401 code, out = run(["sg", "render", str(target), "--start", str(frame), "--end", str(frame)], FUSION_TIMEOUT_S)
402 if code == -1: # a hung node would otherwise keep the render slot
403 run(["ssh", "root@10.0.0.1", f"pkill -f 'FusionRenderNode .*{case}'"], 30)
404 if SHARED == LOCAL:
405 run(["sg", "download", f"{REMOTE}/gt/", str(SHARED / "gt")], 120)
406 # Success is the GT file, not the exit code or log text: both are unreliable through a pipe.
407 for _ in range(20 if code == 0 and not fusion_causes(out) else 1): # SMB lags the node's write
408 if gt := sorted((SHARED / "gt").glob(f"{case}_*.png")):
409 break
410 time.sleep(0.5)
411 if gt or code == -1 or fusion_causes(out):
412 break
413 ok = bool(gt)
414 log = "" if ok else ("timeout; " if code == -1 else f"exit {code}; ") + (", ".join(fusion_causes(out)) or last_lines(out, 2))
415 return {"ok": ok, "gt": gt[0] if gt else None, "log": log}
416
417
418def png_size(p: Path) -> tuple[int, int]:
419 return struct.unpack(">II", p.read_bytes()[16:24])
420
421
422def process(path: Path, fonts: bool) -> dict:
423 case = case_id(path)
424 rec = {"case": case, "comp": str(path.relative_to(SAMPLES)), "year": path.relative_to(SAMPLES).parts[0]}
425 text, frame = retarget(path.read_text(encoding="utf-8", errors="replace"), fonts)
426 rec["frame"] = frame
427 comps = SHARED / "comps"
428 comps.mkdir(parents=True, exist_ok=True)
429 ours = LOCAL / "ours" / f"{case}.png"
430 ours.parent.mkdir(parents=True, exist_ok=True)
431
432 def local_copy(t: str, name: str) -> Path:
433 p = comps / name
434 p.write_text(t.replace(CONTAINER, str(SHARED)))
435 return p
436
437 # Pass 1 renders the retargeted comp to learn which node render-check views.
438 first = fission(local_copy(text, f"{case}.pre.comp"), frame, ours, None, None)
439 rec["fission"] = {k: v for k, v in first.items() if k in ("ok", "log", "unsupported")}
440 view = first.get("node")
441 if not view:
442 rec["status"] = "fission_fail"
443 return rec
444
445 final = add_diff_saver(text, case, view)
446 comp = comps / f"{case}.comp"
447 comp.write_text(final)
448 fus = fusion(comp, frame, case)
449 rec["fusion"] = {"ok": fus["ok"], "log": fus["log"]}
450 rec["view_node"] = view
451 if not first["ok"] or not fus["ok"]:
452 rec["status"] = "both_fail" if not first["ok"] and not fus["ok"] else ("fission_fail" if not first["ok"] else "fusion_fail")
453 return rec
454
455 second = fission(local_copy(final, f"{case}.local.comp"), frame, ours, view, fus["gt"])
456 if "mae_pct" not in second:
457 rec["status"], rec["fission"]["log"] = "fission_fail", second["log"]
458 return rec
459 rec.update(status="ok", mae_pct=second["mae_pct"], rmse=second["rmse"], size_fusion=png_size(fus["gt"]), size_fission=png_size(ours))
460 rec["size_mismatch"] = rec["size_fusion"] != rec["size_fission"]
461 return rec
462
463
464# ---------------------------------------------------------------------------------------------
465# Reporting
466# ---------------------------------------------------------------------------------------------
467
468
469def report(records: list[dict], classes_by_comp: dict[str, set[str]], fam: dict[str, str]) -> dict:
470 ok = [r for r in records if r["status"] == "ok"]
471 passed = [r for r in ok if r["mae_pct"] < FAIL_MAE_PCT and not r["size_mismatch"]]
472 failing = [r for r in ok if r not in passed]
473 status = Counter(r["status"] for r in records)
474
475 print(f"\n{'comp':<58} {'yr':<5} {'fr':>5} {'view':<16} {'MAE%':>7} {'RMSE':>7} status")
476 for r in sorted(records, key=lambda r: -r.get("mae_pct", -1)):
477 if r["status"] == "ok":
478 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'}")
479 else:
480 why = (r.get("fusion", {}).get("log") or r.get("fission", {}).get("log") or "")[:70]
481 print(f"{r['comp'][-58:]:<58} {r['year']:<5} {r['frame']:>5} {r.get('view_node', '-')[:16]:<16} {'-':>7} {'-':>7} {r['status']}: {why}")
482
483 n = len(records)
484 print(f"\nattempted {n} | clean on both {len(ok)} | pass <{FAIL_MAE_PCT}% MAE {len(passed)}/{len(ok)} | {dict(status)}")
485 if ok:
486 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}%")
487
488 # Counts are comps (not tool instances) that rendered on both sides.
489 per_tool, per_family = defaultdict(lambda: [0, 0]), defaultdict(lambda: [0, 0])
490 for r in ok:
491 tools = classes_by_comp[r["comp"]] - {"BezierSpline", "PolyPath", "LUTBezier", "Saver"} - COSMETIC
492 for c in tools:
493 per_tool[c][0] += 1
494 per_tool[c][1] += r in failing
495 for f in {fam.get(c, "Unsupported / other") for c in tools}:
496 per_family[f][0] += 1
497 per_family[f][1] += r in failing
498 print(f"\nfailing comps (>{FAIL_MAE_PCT}% MAE) by tool family: [comps-with-failure / comps-containing]")
499 for f, (seen, bad) in sorted(per_family.items(), key=lambda kv: -kv[1][1]):
500 print(f" {f:<28} {bad:>3} / {seen:<3}")
501 print("top tool types in failing comps:")
502 for c, (seen, bad) in sorted(per_tool.items(), key=lambda kv: (-kv[1][1], -kv[1][0]))[:15]:
503 if bad:
504 print(f" {c:<26} {bad:>3} / {seen:<3} ({fam.get(c, 'Unsupported / other')})")
505
506 return {
507 "attempted": n,
508 "status": dict(status),
509 "clean_on_both": len(ok),
510 "pass": len(passed),
511 "fail_threshold_mae_pct": FAIL_MAE_PCT,
512 "per_family": {f: {"failing": b, "containing": s} for f, (s, b) in per_family.items()},
513 "per_tool": {c: {"failing": b, "containing": s} for c, (s, b) in per_tool.items()},
514 "cases": records,
515 }
516
517
518def main() -> int:
519 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
520 ap.add_argument("--limit", type=int, default=25)
521 ap.add_argument("--comp", type=Path, action="append", help="debug a single comp (repeatable)")
522 ap.add_argument("--report-json", type=Path)
523 ap.add_argument("--keep-fonts", action="store_true", help="keep original Font/Style (Fusion fails renders whose fonts it lacks)")
524 args = ap.parse_args()
525
526 supported, fam = supported_classes(), family_map()
527 corpus = [describe(p, supported, fam) for p in sorted(SAMPLES.rglob("*.comp"))]
528 if args.comp:
529 wanted = {(fp.REPO / p).resolve() for p in args.comp}
530 picked = [c for c in corpus if c["path"].resolve() in wanted]
531 else:
532 picked = stratified_sample(corpus, args.limit)
533 if not picked:
534 print("no comps selected", file=sys.stderr)
535 return 1
536 print(f"selected {len(picked)} of {len(corpus)} comps: years {dict(Counter(c['year'] for c in picked))}")
537
538 ensure_assets()
539 for sub in ("comps", "gt"):
540 (SHARED / sub).mkdir(parents=True, exist_ok=True)
541 if SHARED == LOCAL:
542 for sub in ("comps", "gt"):
543 subprocess.run(["sg", "upload", str(SHARED / sub), f"{REMOTE}/"], check=True)
544
545 records = []
546 for i, c in enumerate(picked, 1):
547 rec = process(c["path"], not args.keep_fonts)
548 rec["unsupported_static"] = c["unsupported"]
549 rec["tools"] = sorted(c["classes"])
550 records.append(rec)
551 print(f"[{i}/{len(picked)}] {rec['comp'][-60:]} -> {rec['status']}" + (f" MAE {rec['mae_pct']:.2f}%" if rec["status"] == "ok" else ""), flush=True)
552
553 out = report(records, {str(c["path"].relative_to(SAMPLES)): c["classes"] for c in picked}, fam)
554 if args.report_json:
555 args.report_json.write_text(json.dumps(out, indent=2, default=str))
556 return 0
557
558
559if __name__ == "__main__":
560 sys.exit(main())