1"""Render both engines (sg render + render-check), batch/bisect fuzz graphs, and print result tables."""
2
3import shutil
4import subprocess
5import time
6from pathlib import Path
7from typing import Any, Dict, List, Optional, Tuple
8
9from .assets import (
10 CONTAINER_ROOT,
11 REMOTE_ROOT,
12 compute_diff_metrics,
13 ensure_dirs,
14 ensure_render_check,
15 make_comp,
16 make_saver,
17 read_png_rgba,
18 build_switch_chain,
19 use_smb,
20)
21from .fuzzer import FuzzGraph, SplineParam
22
23
24
25
26def alpha_mae_pct(ours_path: Path, gt_path: Path) -> float:
27 """Mean absolute alpha error as a percentage; GT is nearest-sampled onto our size when they differ."""
28 ow, oh, ob = read_png_rgba(ours_path)
29 gw, gh, gb = read_png_rgba(gt_path)
30 if (ow, oh) == (gw, gh):
31 total = sum(abs(a - b) for a, b in zip(ob[3::4], gb[3::4]))
32 else:
33 total = sum(
34 abs(ob[(y * ow + x) * 4 + 3] - gb[(min(gh - 1, int((y + 0.5) * gh / oh)) * gw + min(gw - 1, int((x + 0.5) * gw / ow))) * 4 + 3])
35 for y in range(oh)
36 for x in range(ow)
37 )
38 return total / (ow * oh) / 2.55
39
40
41def run_comp_both(
42 comp_path: Path,
43 prefix: str,
44 frames: List[int],
45 labels: Dict[int, str],
46 render_gt: bool = True,
47 timeout_sec: int = 180,
48) -> Dict[int, Dict[str, Any]]:
49 """Renders comp via sg render (if render_gt) and render-check --render, returning per-frame metrics."""
50 root = ensure_dirs()
51 rc_bin = ensure_render_check()
52 start_f, end_f = min(frames), max(frames)
53
54 gt_error: Optional[str] = None
55 if render_gt:
56 if use_smb():
57 target_comp = str(comp_path)
58 else:
59 remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}"
60 subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True, timeout=60)
61 target_comp = remote_comp
62
63 # Clear stale GT frames for this prefix
64 gt_dir = root / "gt"
65 for f in frames:
66 p = gt_dir / f"{prefix}_{f:04d}.png"
67 if p.exists():
68 p.unlink()
69
70 try:
71 cmd = ["sg", "render", target_comp, "--start", str(start_f), "--end", str(end_f)]
72 proc = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=timeout_sec)
73 combined_out = (proc.stdout or "") + "\n" + (proc.stderr or "")
74 if "ERROR: Render failed" in combined_out:
75 err_lines = [ln.strip() for ln in combined_out.splitlines() if "fail" in ln.lower() or "error" in ln.lower()]
76 gt_error = "sg render error: " + " | ".join(err_lines[:4])
77 except subprocess.TimeoutExpired:
78 gt_error = f"sg render timed out after {timeout_sec}s"
79 except subprocess.CalledProcessError as e:
80 gt_error = f"sg render failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
81
82 if use_smb() and gt_error is None:
83 # Wait briefly for SMB directory cache to surface newly written GT frames
84 expected_gt = [gt_dir / f"{prefix}_{f:04d}.png" for f in frames]
85 deadline = time.time() + 8.0
86 while not all(p.exists() for p in expected_gt) and time.time() < deadline:
87 _ = list(gt_dir.glob(f"{prefix}_*.png"))
88 time.sleep(0.25)
89
90 if not use_smb() and gt_error is None:
91 for f in frames:
92 fname = f"{prefix}_{f:04d}.png"
93 try:
94 subprocess.run(
95 ["sg", "download", f"{REMOTE_ROOT}/gt/{fname}", str(gt_dir / fname)],
96 check=True,
97 capture_output=True,
98 timeout=60,
99 )
100 except subprocess.CalledProcessError as e:
101 gt_error = f"sg download failed for {fname}: {e}"
102 break
103
104 eval_comp = comp_path
105 if not use_smb():
106 txt = comp_path.read_text().replace(CONTAINER_ROOT, str(root))
107 eval_comp = comp_path.with_suffix(".local.comp")
108 eval_comp.write_text(txt)
109
110 ours_sub = root / "ours" / prefix
111 if ours_sub.exists():
112 shutil.rmtree(ours_sub, ignore_errors=True)
113 ours_sub.mkdir(parents=True, exist_ok=True)
114
115 rc_error: Optional[str] = None
116 try:
117 subprocess.run(
118 [str(rc_bin), str(eval_comp), "--render", f"{start_f}..{end_f}", "--out-dir", str(ours_sub)],
119 check=True,
120 capture_output=True,
121 text=True,
122 timeout=timeout_sec,
123 )
124 except subprocess.TimeoutExpired:
125 rc_error = f"render-check timed out after {timeout_sec}s"
126 except subprocess.CalledProcessError as e:
127 rc_error = f"render-check failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
128
129 results: Dict[int, Dict[str, Any]] = {}
130 for f in frames:
131 label = labels.get(f, f"f{f}")
132 if gt_error is not None:
133 results[f] = {"frame": f, "label": label, "error": gt_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
134 continue
135 if rc_error is not None:
136 results[f] = {"frame": f, "label": label, "error": rc_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
137 continue
138 gt_p = root / "gt" / f"{prefix}_{f:04d}.png"
139 ours_p = ours_sub / f"{f:04d}.png"
140 m = compute_diff_metrics(ours_p, gt_p)
141 if "error" not in m:
142 m["alpha_mae_pct"] = alpha_mae_pct(ours_p, gt_p)
143 m["frame"] = f
144 m["label"] = label
145 results[f] = m
146 return results
147
148
149
150
151def write_standalone_graph_comp(graph: FuzzGraph, prefix: str) -> Path:
152 root = ensure_dirs()
153 tool_blocks, aux_blocks, out_op = graph.to_lua_defs(prefix="", frame_shift=0)
154 # Normalize over BlackBG so Saver compares RGB over opaque black consistently
155 tool_blocks.append('\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },')
156 tool_blocks.append(f'\t\t_NormOut = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "_BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{out_op}", Source = "Output", }}, }}, }},')
157 tool_blocks.append(make_saver("_NormOut", prefix))
158 comp_path = root / "comps" / f"{prefix}.comp"
159 comp_path.write_text(make_comp("\n".join(tool_blocks + aux_blocks), graph.eval_frame, start_frame=graph.eval_frame))
160 return comp_path
161
162
163def run_multi_graph_batch(
164 items: List[Tuple[str, FuzzGraph]],
165 batch_prefix: str,
166 render_gt: bool = True,
167 timeout_sec: int = 180,
168) -> Dict[int, Dict[str, Any]]:
169 """Packs multiple FuzzGraphs into one multi-frame .comp using a Merge switch chain."""
170 root = ensure_dirs()
171 all_tools = [
172 '\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },'
173 ]
174 all_aux: List[str] = []
175 cases: List[Tuple[int, str, str]] = []
176 labels: Dict[int, str] = {}
177
178 for f_idx, (label, g) in enumerate(items):
179 pfx = f"G{f_idx}_"
180 frame_shift = f_idx - g.eval_frame
181 tb, ab, out_op = g.to_lua_defs(prefix=pfx, frame_shift=frame_shift)
182 all_tools.extend(tb)
183 all_aux.extend(ab)
184 cases.append((f_idx, label, out_op))
185 labels[f_idx] = label
186
187 sw_nodes, sw_splines, final_op = build_switch_chain(cases, "_BlackBG", "FB")
188 all_tools.extend(sw_nodes)
189 all_aux.extend(sw_splines)
190 all_tools.append(make_saver(final_op, batch_prefix))
191
192 comp_path = root / "comps" / f"{batch_prefix}.comp"
193 comp_path.write_text(make_comp("\n".join(all_tools + all_aux), len(cases) - 1, start_frame=0))
194 return run_comp_both(
195 comp_path,
196 batch_prefix,
197 list(range(len(cases))),
198 labels,
199 render_gt=render_gt,
200 timeout_sec=timeout_sec,
201 )
202
203
204def _exceeds_threshold(m: Dict[str, Any], threshold_pct: float) -> bool:
205 """Return True if either RGB MAE% or Alpha MAE% exceeds threshold_pct."""
206 return m["mae_pct"] > threshold_pct or m.get("alpha_mae_pct", 0.0) > threshold_pct
207
208
209def bisect_failing_graph(
210 graph: FuzzGraph,
211 threshold_pct: float,
212 render_gt: bool = True,
213 timeout_sec: int = 180,
214) -> Dict[str, Any]:
215 """Node-by-node graph bisection that trims downstream & upstream nodes while preserving MAE > threshold."""
216 seed = graph.seed
217 print(f" [bisect] seed={seed} ({len(graph.nodes)} nodes) ...", flush=True)
218
219 # Step 0: Verify standalone reproduction
220 st_prefix = f"bisect_s{seed}_orig"
221 st_comp = write_standalone_graph_comp(graph, st_prefix)
222 st_res = run_comp_both(
223 st_comp, st_prefix, [graph.eval_frame], {graph.eval_frame: f"seed_{seed}"}, render_gt=render_gt, timeout_sec=timeout_sec
224 )[graph.eval_frame]
225 orig_mae = st_res["mae_pct"]
226 if not _exceeds_threshold(st_res, threshold_pct):
227 return {
228 "seed": seed,
229 "reproduced_standalone": False,
230 "orig_mae_pct": orig_mae,
231 "min_mae_pct": orig_mae,
232 "min_rmse_255": st_res["rmse_255"],
233 "note": "batch failure did not reproduce standalone",
234 "tools": graph.summary_tools(),
235 }
236
237 # Step 1: Prefix trim (find earliest failing sink node in topological order)
238 non_src = [n for n in graph.nodes if not n.is_source]
239 cur = graph.clone()
240 if len(non_src) > 1:
241 prefix_items = [(f"prefix_{nd.name}", graph.prune_to(nd.name)) for nd in non_src]
242 pref_res = run_multi_graph_batch(
243 prefix_items, f"bisect_s{seed}_prefixes", render_gt=render_gt, timeout_sec=timeout_sec
244 )
245 for idx, nd in enumerate(non_src):
246 if _exceeds_threshold(pref_res[idx], threshold_pct):
247 cur = graph.prune_to(nd.name)
248 print(f" [prefix] trimmed sink to {nd.name} ({len(cur.nodes)} nodes, MAE={pref_res[idx]['mae_pct']:.2f}%)", flush=True)
249 break
250
251 # Step 2: Iterative upstream node & mask removal + spline flattening
252 for rnd in range(6):
253 candidates: List[Tuple[str, str, FuzzGraph]] = [] # (desc, action, candidate_graph)
254 # Try flattening splines first
255 flat = cur.flatten_splines()
256 if flat is not None:
257 candidates.append(("flatten_splines", "flatten", flat))
258 # Try stripping masks
259 for nd in cur.nodes:
260 if nd.mask is not None:
261 sm = cur.strip_mask(nd.name)
262 if sm is not None:
263 candidates.append((f"strip_mask:{nd.name}", "mask", sm))
264 # Try bypassing each upstream non-source node
265 for nd in cur.nodes:
266 if not nd.is_source and nd.name != cur.output_node():
267 bp = cur.bypass_node(nd.name)
268 if bp is not None:
269 candidates.append((f"bypass:{nd.name}", "bypass", bp))
270
271 if not candidates:
272 break
273
274 batch_items = [(desc, cg) for desc, _act, cg in candidates]
275 cand_res = run_multi_graph_batch(
276 batch_items, f"bisect_s{seed}_r{rnd}", render_gt=render_gt, timeout_sec=timeout_sec
277 )
278
279 # Pick best failing candidate: fewest nodes, fewest masks, no splines
280 failing: List[Tuple[Tuple[int, int, int], str, FuzzGraph, float]] = []
281 for idx, (desc, _act, cg) in enumerate(candidates):
282 m = cand_res[idx]
283 if _exceeds_threshold(m, threshold_pct):
284 mask_cnt = sum(1 for x in cg.nodes if x.mask is not None)
285 spline_cnt = sum(
286 1 for x in cg.nodes for v in x.params.values() if isinstance(v, SplineParam)
287 )
288 score = (len(cg.nodes), mask_cnt, spline_cnt)
289 failing.append((score, desc, cg, m["mae_pct"]))
290
291 if not failing:
292 break
293 failing.sort(key=lambda t: t[0])
294 _score, best_desc, best_cg, best_mae = failing[0]
295 cur = best_cg
296 print(f" [round {rnd}] {best_desc} -> {len(cur.nodes)} nodes (MAE={best_mae:.2f}%)", flush=True)
297
298 # Step 3: Standalone verification of minimal reproducer
299 repro_prefix = f"repro_seed_{seed}"
300 repro_comp = write_standalone_graph_comp(cur, repro_prefix)
301 final_res = run_comp_both(
302 repro_comp, repro_prefix, [cur.eval_frame], {cur.eval_frame: repro_prefix}, render_gt=render_gt, timeout_sec=timeout_sec
303 )[cur.eval_frame]
304
305 return {
306 "seed": seed,
307 "reproduced_standalone": True,
308 "orig_node_count": len(graph.nodes),
309 "min_node_count": len(cur.nodes),
310 "orig_mae_pct": orig_mae,
311 "min_mae_pct": final_res["mae_pct"],
312 "min_rmse_255": final_res["rmse_255"],
313 "comp_path": str(repro_comp),
314 "eval_frame": cur.eval_frame,
315 "tools": cur.summary_tools(),
316 }
317
318
319def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None:
320 print(f"\n=== {title} ===")
321 print(f" {'Case':<44s} | {'MAE%':>7s} | {'A_MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}")
322 print(f" {'-'*44}-+-{'-'*7}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}")
323 for r in rows:
324 label = str(r.get("label", ""))[:44]
325 mae_pct = r.get("mae_pct", 100.0)
326 a_pct = r.get("alpha_mae_pct", 0.0)
327 mae = r.get("mae_255", 255.0)
328 rmse = r.get("rmse_255", 255.0)
329 if r.get("error"):
330 status = f"ERR: {str(r['error'])[:28]}"
331 elif r.get("size_mismatch"):
332 status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}"
333 elif mae_pct > threshold_pct:
334 status = "FAIL"
335 elif a_pct > threshold_pct:
336 status = "FAIL (ALPHA)"
337 else:
338 status = "PASS"
339 print(f" {label:<44s} | {mae_pct:6.2f}% | {a_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}")