diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rollout_diff/cli.py ADDED
@@ -0,0 +1,475 @@
1
+ """rollout-diff: compare two videos of the same robot job.
2
+
3
+ rollout-diff good.mp4 new.mp4 --world-diff --out report.html (what changed in the world, plus timing)
4
+ rollout-diff good.mp4 new.mp4 --world-diff --also good2.mp4 good3.mp4 (several good runs: normal variation)
5
+ rollout-diff good.mp4 new.mp4 --out report.html (timing only)
6
+ rollout-diff data/bb/b1#7 data/bb/b2#5 --cam top --fp residual --out report.html --json diff.json
7
+
8
+ rollout-diff calibrate REF GOOD1 GOOD2 GOOD3 ... --out floor.json [--cam top --fp residual]
9
+ rollout-diff REF NEW --floor floor.json --out report.html [--end-check]
10
+ rollout-diff batch REF_OR_DIR_A DIR_OR_DS_B --out dashboard_dir/ [--episodes 0-9 --world-diff]
11
+ rollout-diff teach GOOD_RUNS... --out task.teach (learn the task from good runs)
12
+ rollout-diff check task.teach RUNS... --out check.html (check any run against it)
13
+
14
+ --model / --change-model / --mask-model load trained models from a separate package (not part of this repository).
15
+
16
+ A run is a video file or a LeRobot v3 dataset folder with '#episode'. Exit code 0 = PASS, 1 = FAIL.
17
+ """
18
+ import argparse
19
+ import json
20
+ import sys
21
+ import time
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+
26
+ from .core import calibrate, check_floor, compare, load_run
27
+ from .report import diff_badge, summary, write_html
28
+
29
+
30
+ def _make_logger(quiet=False):
31
+ t0 = time.perf_counter()
32
+ if quiet:
33
+ return (lambda _msg: None), t0
34
+
35
+ def _log(msg):
36
+ dt = time.perf_counter() - t0
37
+ print(f"[{dt:5.1f}s] {msg}", flush=True)
38
+
39
+ return _log, t0
40
+
41
+
42
+ def _common(ap):
43
+ ap.add_argument("--cam", default=None,
44
+ help="camera name for LeRobot datasets (default: auto-pick a fixed camera and list available ones)")
45
+ ap.add_argument("--fp", choices=["global", "residual"], default="global",
46
+ help="global: whole-image fingerprint; residual: ignore the static scene (robot small in view)")
47
+ ap.add_argument("--fps", type=int, default=10)
48
+
49
+
50
+ def _spot():
51
+ """diffnet/ sits next to this package, not inside it: make it importable (editable install or copied folder)."""
52
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
53
+ try:
54
+ from diffnet import spot
55
+ except ImportError:
56
+ raise SystemExit("--model, --change-model and --mask-model need the trained-model package (diffnet/), "
57
+ "which is not part of this repository. Leave them out to use the built-in diff.") from None
58
+ return spot
59
+
60
+
61
+ def main_calibrate(argv):
62
+ ap = argparse.ArgumentParser(prog="rollout-diff calibrate",
63
+ description="Learn what 'normal' looks like from good runs of the same job.")
64
+ ap.add_argument("ref", help="reference run (later used as A)")
65
+ ap.add_argument("good", nargs="+", help="at least 3 more good runs")
66
+ _common(ap)
67
+ ap.add_argument("--out", required=True, help="write the calibration (JSON) here")
68
+ ap.add_argument("--model", help="also learn the alarm level of a trained DiffNet (last.pt) for this job")
69
+ ap.add_argument("--adapt", type=int, nargs="?", const=300, default=0, metavar="STEPS",
70
+ help="with --model: first tune the model to this job on the good runs (default 300 steps, a few "
71
+ "minutes; needs 5+ good runs) and save it next to --out as <name>.model.pt")
72
+ args = ap.parse_args(argv)
73
+ if args.model and args.fps != 10:
74
+ ap.error("--model needs --fps 10 (the model was trained at 10 fps)")
75
+
76
+ print(f"calibrating on {len(args.good)} good runs against {args.ref}")
77
+ if args.fp == "global": # timing + a normal profile (what normally varies, where)
78
+ from . import profile
79
+ from .core import fingerprints
80
+ A = fingerprints(load_run(args.ref, args.fps, args.cam))
81
+ goods = (fingerprints(load_run(g, args.fps, args.cam)) for g in args.good)
82
+ prof, light = profile.build(A, goods, fps=args.fps)
83
+ floor = calibrate(A, light, fps=args.fps, fp=args.fp)
84
+ npz = str(Path(args.out).with_suffix(".npz"))
85
+ profile.save(prof, npz)
86
+ floor["profile"] = Path(npz).name
87
+ print(f"normal profile: {len(args.good)} runs -> {npz}")
88
+ else:
89
+ fa = load_run(args.ref, args.fps, args.cam)
90
+ good = [load_run(g, args.fps, args.cam) for g in args.good]
91
+ floor = calibrate(fa, good, fps=args.fps, fp=args.fp)
92
+ if args.model:
93
+ sp = _spot()
94
+ model, s = sp.load_model(args.model)
95
+ print(f"model alarm level from {len(args.good)} good runs ({args.model}):")
96
+ ref, good = load_run(args.ref, args.fps, args.cam), [load_run(g, args.fps, args.cam) for g in args.good]
97
+ tuned = str(Path(args.out).with_suffix(".model.pt")) if args.adapt else None
98
+ floor["model"] = dict(sp.calibrate(model, s, ref, good, tune=args.adapt, save_to=tuned, source=args.model),
99
+ ckpt=tuned or str(args.model))
100
+ if tuned:
101
+ print(f"model tuned to this job: {tuned}")
102
+ print(f"model: good runs score up to {max(floor['model']['good']):.2f} "
103
+ f"-> unusual above {floor['model']['thr']:.2f}; end state differs above {floor['model']['end_thr']:.2f}")
104
+ floor.update(ref=args.ref, cam=args.cam, good_runs=args.good)
105
+ with open(args.out, "w", encoding="utf-8") as fh:
106
+ json.dump(floor, fh)
107
+ print(f"looks alike below {floor['alike']:.3f} (p99 path cost)")
108
+ for sc in floor["timing"]:
109
+ print(f"timing, {sc['seconds']} s windows: normal spread median {np.nanmedian(sc['spread']):.2f} s, "
110
+ f"alarm above z {sc['thr']:.1f}")
111
+ print(f"end state (experimental): good runs up to {max(floor['end']['good']):.3f} "
112
+ f"-> differs above {floor['end']['thr']:.3f}")
113
+ print(f"wrote {args.out}")
114
+ return 0
115
+
116
+
117
+ def main_batch(argv):
118
+ from .batch import match_starts, resolve_batch_pairs, run_batch
119
+
120
+ ap = argparse.ArgumentParser(
121
+ prog="rollout-diff batch",
122
+ description="Compare many video pairs at once and write a checkpoint HTML dashboard + Markdown/JSON summary.",
123
+ )
124
+ ap.add_argument("a", help="reference video/episode, folder of videos, or LeRobot dataset (local or HF Hub)")
125
+ ap.add_argument("b", help="folder of videos or LeRobot dataset to compare against A")
126
+ _common(ap)
127
+ ap.add_argument("--episodes", help="episode indices/ranges, e.g. '0-9' or '0,2,5-8'")
128
+ ap.add_argument("--max", dest="max_pairs", type=int, help="maximum number of pairs to compare")
129
+ ap.add_argument("--out", required=True, help="output directory for index.html, per-episode HTMLs, summary.md/json")
130
+ ap.add_argument("--markdown", help="optional extra path to write the PR-ready Markdown summary table")
131
+ ap.add_argument("--json", help="optional extra path to write the batch JSON summary")
132
+ ap.add_argument("--alike", type=float, help="cost below which matched frames look alike")
133
+ ap.add_argument("--idle", type=float, help="still-frame threshold")
134
+ ap.add_argument("--no-spatial", action="store_true", help="disable patch-level spatial visual diff")
135
+ ap.add_argument("--spatial-thr", type=float, help="override spatial end-diff threshold")
136
+ ap.add_argument("--mid-thr", type=float, help="override mid-run spatial diff threshold")
137
+ ap.add_argument("--check", action="store_true", help="enable PASS/FAIL gating (exit code 1 if any episode fails)")
138
+ ap.add_argument("--world-diff", action="store_true", help="robot-free world-change diff (SAM 2.1 + DINOv2-reg)")
139
+ ap.add_argument("--mask-model", help="trained robot cut-out model (separate package)")
140
+ ap.add_argument("--change-model", help="with --world-diff: trained start-vs-end change map (separate package)")
141
+ ap.add_argument("--match-model", help="with --world-diff: trained outcome matcher (separate package)")
142
+ ap.add_argument("--channels", action="store_true", help="enable 32x32 OBJECT DIFF and joint-state ARM DIFF")
143
+ ap.add_argument("--arm-diff", action="store_true", help="enable experimental visual arm-mask ARM DIFF")
144
+ ap.add_argument("--track", action="store_true", help="track differing objects with LocoTrack-S (Apache-2.0)")
145
+ ap.add_argument("--no-channels", action="store_true", help="with --mask-model: disable OBJECT DIFF channel")
146
+ ap.add_argument("--also", nargs="*", default=[], help="more good reference runs to suppress normal variation")
147
+ ap.add_argument("--min", type=float, default=1.0, help="hide timing items shorter than this many seconds")
148
+ ap.add_argument("--pair", choices=["name", "start"], default="name",
149
+ help="name: pair by file name / episode index; start: compare each B with the A run whose first "
150
+ "frame is most alike, and skip B runs that no A run starts like (fair A/B on eval sets)")
151
+ ap.add_argument("--floor", help="calibration from 'rollout-diff calibrate' with A as its reference: adds the "
152
+ "learnt step-timing check and PASS/FAIL (sets --cam/--fp/--fps/--alike)")
153
+ ap.add_argument("--reports", choices=["all", "diff"], default="all",
154
+ help="per-episode HTML reports for all pairs, or only for pairs with differences")
155
+ args = ap.parse_args(argv)
156
+
157
+ floor = None
158
+ if args.floor:
159
+ floor = json.load(open(args.floor, encoding="utf-8"))
160
+ args.cam, args.fp, args.fps = floor["cam"], floor["fp"], floor["fps"]
161
+ args.alike = args.alike or floor["alike"]
162
+ if args.spatial_thr is None and "spatial" in floor:
163
+ args.spatial_thr = floor["spatial"]["end_thr"]
164
+ pairs = resolve_batch_pairs(args.a, args.b, episodes=args.episodes, max_pairs=args.max_pairs)
165
+ if not pairs:
166
+ raise SystemExit(f"No video pairs found for A='{args.a}' and B='{args.b}'.")
167
+ if floor and any(p["a"] != floor["ref"] for p in pairs):
168
+ raise SystemExit(f"--floor was calibrated with reference {floor['ref']}: use it as A (one reference vs runs).")
169
+ if args.pair == "start":
170
+ print("pairing by start scene (first frames) ...", flush=True)
171
+ pairs = match_starts(pairs, fps=args.fps, cam=args.cam, log=lambda m: print(m, flush=True))
172
+
173
+ robot = _spot().mask_model(args.mask_model) if args.mask_model else None
174
+ cm = _spot().change_model(args.change_model) if (args.world_diff and args.change_model) else None
175
+ mtm = _spot().match_model(args.match_model) if (args.world_diff and args.match_model) else None
176
+ use_channels = bool((args.mask_model or args.channels or args.arm_diff or args.track)
177
+ and not args.no_channels and not args.no_spatial and not args.world_diff)
178
+ notes = []
179
+ if args.world_diff and not args.no_spatial:
180
+ notes.append("world-diff (SAM 2.1 + DINOv2-reg)")
181
+ elif use_channels:
182
+ notes.append("OBJECT DIFF (32x32 plates) + REST DIFF + TIMING")
183
+ if args.track and use_channels:
184
+ notes.append("LocoTrack-S tracking")
185
+ if args.also:
186
+ notes.append(f"{1 + len(args.also)} good runs")
187
+ if args.pair == "start":
188
+ notes.append("paired by start scene")
189
+ if floor:
190
+ notes.append(f"step timing calibrated on {floor['runs']} good runs")
191
+ note = " · ".join(notes)
192
+
193
+ print(f"rollout-diff batch: {len(pairs)} pairs A={args.a} B={args.b}", flush=True)
194
+ out = run_batch(
195
+ pairs, args.out, name_a=args.a, name_b=args.b, fps=args.fps, cam=args.cam, fp=args.fp,
196
+ alike=args.alike, idle=args.idle, spatial=not args.no_spatial, spatial_thr=args.spatial_thr,
197
+ mid_thr=args.mid_thr, world_diff_mode=bool(args.world_diff), channels=use_channels,
198
+ arm_diff=bool(args.arm_diff), track=bool(args.track), robot=robot, change_model=cm,
199
+ match_model=mtm, also=args.also, min_s=args.min, gated=bool(args.check or floor), note=note,
200
+ floor=floor, reports=args.reports, log=lambda m: print(m, flush=True),
201
+ )
202
+ if args.markdown:
203
+ Path(args.markdown).write_text(out["markdown"], encoding="utf-8")
204
+ print(f"wrote {args.markdown}")
205
+ if args.json:
206
+ Path(args.json).write_text((Path(args.out) / "summary.json").read_text(encoding="utf-8"), encoding="utf-8")
207
+ print(f"wrote {args.json}")
208
+ st = out["stats"]
209
+ print(f"Batch complete: {st['n_clean']}/{st['n_ok']} clean ({st['clean_pct']:.1f}%), "
210
+ f"median active {st['median_active_a']:.1f} s -> {st['median_active_b']:.1f} s ({st['median_active_delta_s']:+.1f} s)"
211
+ + (f", {st['n_skipped']} skipped (no matching start)" if st["n_skipped"] else ""))
212
+ print(f"Dashboard: {Path(args.out) / 'index.html'}")
213
+ if args.check or floor:
214
+ failed = any(r["status"] in ("FAIL", "ERROR") for r in out["records"])
215
+ return 1 if failed else 0
216
+ return 0
217
+
218
+
219
+ def main(argv=None):
220
+ argv = sys.argv[1:] if argv is None else argv
221
+ if argv and argv[0] == "calibrate":
222
+ return main_calibrate(argv[1:])
223
+ if argv and argv[0] == "batch":
224
+ return main_batch(argv[1:])
225
+ if argv and argv[0] in ("teach", "check"): # learn the task from good runs, then check any run
226
+ from . import teach
227
+ return (teach.main_teach if argv[0] == "teach" else teach.main_check)(argv[1:])
228
+ ap = argparse.ArgumentParser(
229
+ prog="rollout-diff",
230
+ description="Compare robot runs on video and see what went differently.",
231
+ formatter_class=argparse.RawDescriptionHelpFormatter,
232
+ epilog=(
233
+ "commands:\n"
234
+ " rollout-diff teach GOOD... --out task.teach learn a task from a few good runs\n"
235
+ " rollout-diff check task.teach RUNS... --out c.html check new runs against a taught task\n"
236
+ " rollout-diff batch A B --out dashboard/ compare two folders or datasets\n"
237
+ " rollout-diff calibrate REF GOOD... --out f.json calibrate two-video timing thresholds\n"
238
+ " rollout-diff A B --world-diff --out report.html compare just two runs directly\n"
239
+ "\n"
240
+ "Run 'rollout-diff <command> --help' for command-specific options."
241
+ ),
242
+ )
243
+ ap.add_argument("a", help="reference run: video file or LeRobot folder#episode")
244
+ ap.add_argument("b", help="run to check")
245
+ _common(ap)
246
+ ap.add_argument("--floor", help="calibration from 'rollout-diff calibrate' (sets --cam/--fp/--fps/--alike)")
247
+ ap.add_argument("--end-check", action="store_true",
248
+ help="experimental: also check B's final view on the task patches (needs --floor; "
249
+ "only meaningful when the robot returns to its start pose)")
250
+ ap.add_argument("--alike", type=float, help="cost below which matched frames look alike (default per --fp)")
251
+ ap.add_argument("--idle", type=float, help="still-frame threshold (default per --fp)")
252
+ ap.add_argument("--no-spatial", action="store_true", help="disable patch-level spatial visual diff")
253
+ ap.add_argument("--spatial-thr", type=float, help="override spatial end-diff threshold (default 0.44)")
254
+ ap.add_argument("--mid-thr", type=float, help="override mid-run spatial diff threshold (default 0.52)")
255
+ ap.add_argument("--check", action="store_true",
256
+ help="enable PASS/FAIL gating and exit code 1 on failure (automatic with --floor or --object)")
257
+ ap.add_argument("--object", help="also check where this object ends, e.g. 'cube' (name it simply; "
258
+ "leave out the colour if it varies between runs)")
259
+ ap.add_argument("--target", help="where the object should end, e.g. 'basket': then B passes when the object ends "
260
+ "inside it, like in A, even if the target stands elsewhere in the picture")
261
+ ap.add_argument("--object-tol", type=float, default=3.0,
262
+ help="the object may end this many object sizes away from where it ends in A (default 3)")
263
+ ap.add_argument("--model", help="trained DiffNet (last.pt): its heatmap and differences instead of the hand-made "
264
+ "spatial diff (default: the model of a --floor made with --model)")
265
+ ap.add_argument("--also", nargs="*", default=[],
266
+ help="with --model or --world-diff: more good runs to compare B with (a --floor adds its good runs; "
267
+ "--world-diff counts an A change only if half of the good runs make it)")
268
+ ap.add_argument("--model-thr", type=float, default=0.5,
269
+ help="with --model and no --floor made with --model: the model's chance that counts as different")
270
+ ap.add_argument("--align-view", action="store_true",
271
+ help="with --model: moving/wrist camera mode (homography-align reference frames + mask out-of-FOV edges)")
272
+ ap.add_argument("--world-diff", action="store_true",
273
+ help="blind 1-vs-1 robot-free world-change diff (SAM 2.1 + DINOv2-reg, Apache-2.0): masks the moving arm "
274
+ "and matches persistent start->end world changes 1-to-1 instead of flagging arm shifts")
275
+ ap.add_argument("--change-model", help="with --world-diff: a trained start-vs-end change map (separate package)")
276
+ ap.add_argument("--mask-model", help="a trained robot cut-out model (separate package): with --world-diff it "
277
+ "builds the robot-free plates; otherwise enables OBJECT DIFF (32x32 plates) "
278
+ "+ robot-masked REST DIFF + TIMING (+ joint-state ARM DIFF when available)")
279
+ ap.add_argument("--channels", action="store_true",
280
+ help="explicitly enable OBJECT DIFF (32x32 robot-free plates) and joint-state ARM DIFF "
281
+ "(automatic with --mask-model)")
282
+ ap.add_argument("--arm-diff", action="store_true",
283
+ help="also enable experimental visual arm-mask ARM DIFF on video-only runs (for arm-only tasks like buttons)")
284
+ ap.add_argument("--track", action="store_true",
285
+ help="track differing objects with LocoTrack-S (Apache-2.0, 33 MB; adds motion arrows & trajectory details)")
286
+ ap.add_argument("--explain", action="store_true",
287
+ help="generate a grounded VLM summary on key synced A|B frames (local Qwen2.5-VL via Ollama or HF)")
288
+ ap.add_argument("--explain-model", help="VLM model name/ID (default: qwen2.5vl:7b for Ollama, Qwen/Qwen2.5-VL-7B-Instruct for HF)")
289
+ ap.add_argument("--explain-backend", choices=["auto", "openai", "hf"], default="auto",
290
+ help="VLM backend: auto (uses running Ollama/URL if available, else local HF), openai (Ollama/vLLM/API), or hf")
291
+ ap.add_argument("--explain-url", help="OpenAI-compatible VLM base URL (e.g. http://127.0.0.1:11434/v1 for Ollama or http://127.0.0.1:8000/v1 for vLLM)")
292
+ ap.add_argument("--explain-4bit", action="store_true", help="with HF VLM backend: load weights in 4-bit quantization (for 8-12 GB GPUs)")
293
+ ap.add_argument("--explain-panels", type=int, default=5, help="max images sent to VLM (overview + B burst + zoomed diff crops; default 5)")
294
+ ap.add_argument("--explain-debug", help="folder to save the exact images and prompt sent to the VLM")
295
+ ap.add_argument("--no-channels", action="store_true",
296
+ help="with --mask-model: disable OBJECT DIFF channel (16x16 REST DIFF + TIMING only)")
297
+ ap.add_argument("--match-model", help="with --world-diff: a trained Stage 3 world-outcome matcher (separate package)")
298
+ ap.add_argument("--min", type=float, default=1.0, help="hide items shorter than this many seconds")
299
+ ap.add_argument("--out", help="write an HTML report here")
300
+ ap.add_argument("--video", help="write a shareable synced side-by-side diff video (.mp4) or animated GIF (.gif)")
301
+ ap.add_argument("--json", help="write the items as JSON here")
302
+ ap.add_argument("-q", "--quiet", action="store_true", help="hide step-by-step workflow progress logs")
303
+ args = ap.parse_args(argv)
304
+ log, t0 = _make_logger(quiet=args.quiet)
305
+
306
+ floor = None
307
+ if args.floor:
308
+ log(f"Loading calibration floor: {args.floor}")
309
+ floor = json.load(open(args.floor, encoding="utf-8"))
310
+ args.cam, args.fp, args.fps = floor["cam"], floor["fp"], floor["fps"]
311
+ args.alike = args.alike or floor["alike"]
312
+ if args.spatial_thr is None and "spatial" in floor:
313
+ args.spatial_thr = floor["spatial"]["end_thr"]
314
+ if args.a != floor["ref"]:
315
+ print(f"note: the calibration was made with reference {floor['ref']}, not {args.a}")
316
+
317
+ log(f"Stage: loading videos at {args.fps} fps ...")
318
+ try:
319
+ fa = load_run(args.a, args.fps, args.cam)
320
+ log(f" A loaded: {Path(args.a).name} ({len(fa)} frames, {len(fa) / args.fps:.1f}s, {fa.shape[2]}x{fa.shape[1]})")
321
+ fb = load_run(args.b, args.fps, args.cam)
322
+ log(f" B loaded: {Path(args.b).name} ({len(fb)} frames, {len(fb) / args.fps:.1f}s, {fb.shape[2]}x{fb.shape[1]})")
323
+ except (FileNotFoundError, ValueError) as exc:
324
+ raise SystemExit(f"Error: {exc}") from None
325
+ kw = dict(spatial=not args.no_spatial, log=log)
326
+ if args.spatial_thr is not None:
327
+ kw["spatial_thr"] = args.spatial_thr
328
+ if args.mid_thr is not None:
329
+ kw["mid_thr"] = args.mid_thr
330
+ cal = (floor or {}).get("model")
331
+ args.model = args.model or (cal or {}).get("ckpt")
332
+ model_note = []
333
+ if args.world_diff and not args.no_spatial:
334
+ from . import world_diff
335
+ res = compare(fa, fb, fps=args.fps, fp=args.fp, alike=args.alike, idle=args.idle, spatial=False, log=log)
336
+ goods = [load_run(g, args.fps, args.cam) for g in args.also]
337
+ if goods:
338
+ log(f" loaded +{len(goods)} extra good reference run(s)")
339
+ cm = _spot().change_model(args.change_model) if args.change_model else None
340
+ mm = _spot().mask_model(args.mask_model) if args.mask_model else None
341
+ mtm = _spot().match_model(args.match_model) if args.match_model else None
342
+ log("Stage: running robot-free world-change diff (SAM 2.1 + DINOv2-reg) ...")
343
+ res["spatial"] = world_diff.spot_world(fa, fb, res, goods=goods, change_model=cm, mask_model=mm, match_model=mtm)
344
+ res["spatial_items"] = res["spatial"]["items"]
345
+ log(f" world-diff found {len(res['spatial_items'])} item(s)")
346
+ model_note = ["robot-free world-change diff (SAM 2.1 + DINOv2-reg, Apache-2.0; arm shifts ignored)"
347
+ + (f" against {1 + len(goods)} good runs" if goods else "")]
348
+ elif args.model and not args.no_spatial: # the trained model's heatmap and differences
349
+ if args.fps != 10:
350
+ ap.error("--model needs --fps 10 (the model was trained at 10 fps)")
351
+ sp = _spot()
352
+ log(f"Loading trained model: {args.model}")
353
+ model, s = sp.load_model(args.model)
354
+ goods = [fa] + [load_run(g, args.fps, args.cam) for g in (floor["good_runs"] if floor else []) + args.also]
355
+ thr = cal["thr"] if cal else args.model_thr
356
+ res = compare(fa, fb, fps=args.fps, fp=args.fp, alike=args.alike, idle=args.idle, spatial=False, log=log)
357
+ log("Stage: scoring with trained DiffNet ...")
358
+ res["spatial"] = sp.spot(model, s, goods, fb, res, thr, cal["refs"] if cal else sp.REFS, calibrated=bool(cal),
359
+ end_thr=(cal or {}).get("end_thr"), align_view=args.align_view)
360
+ res["spatial_items"] = res["spatial"]["items"]
361
+ model_note = [f"heatmap from the model {Path(args.model).name} against {min(len(goods), sp.REFS)} good runs, "
362
+ f"alarm level {thr:.2f}" + (" (learnt from good runs)" if cal else "")
363
+ + (" · view-aligned" if args.align_view else "")]
364
+ elif floor and floor.get("profile") and not args.no_spatial: # only what no normal run shows, ranked
365
+ from . import profile
366
+ from .core import fingerprints
367
+ log(f"Stage: checking against normal profile ({floor['profile']}) ...")
368
+ prof = profile.load(Path(args.floor).with_name(floor["profile"]))
369
+ A, B = fingerprints(fa), fingerprints(fb)
370
+ res = compare(A, B, fps=args.fps, fp=args.fp, alike=args.alike, idle=args.idle, spatial=False, log=log)
371
+ res["spatial"] = profile.check(prof, A, B, res)
372
+ res["spatial_items"] = res["spatial"]["items"]
373
+ else:
374
+ use_channels = bool((args.mask_model or args.channels or args.arm_diff or args.track) and not args.no_channels and not args.no_spatial)
375
+ if args.mask_model:
376
+ log(f"Loading robot mask model: {args.mask_model}")
377
+ kw["robot"] = _spot().mask_model(args.mask_model)
378
+ model_note = [("4-channel diff (OBJECT + visual ARM + robot-masked REST + TIMING)" if args.arm_diff
379
+ else "OBJECT DIFF (32x32 plates) + robot-masked REST DIFF + TIMING")
380
+ if use_channels else "robot cells skipped (robot cut-out model)"]
381
+ elif use_channels:
382
+ model_note = ["OBJECT DIFF (32x32 plates) + REST DIFF + TIMING"]
383
+ if use_channels:
384
+ goods = []
385
+ for g in args.also:
386
+ gf = load_run(g, args.fps, args.cam)
387
+ log(f" +good ref loaded: {Path(g).name} ({len(gf)} frames, {len(gf) / args.fps:.1f}s)")
388
+ goods.append(gf)
389
+ kw.update(channels=True, arm_diff=bool(args.arm_diff), track=bool(args.track),
390
+ spec_a=args.a, spec_b=args.b, goods=goods)
391
+ if args.track:
392
+ model_note.append("LocoTrack-S point tracking (Apache-2.0)")
393
+ if goods:
394
+ model_note.append(f"multi-ref object memory bank ({1 + len(goods)} good runs)")
395
+ res = compare(fa, fb, fps=args.fps, fp=args.fp, alike=args.alike, idle=args.idle, **kw)
396
+ floor_items = check_floor(res, floor, args.end_check) if floor else None
397
+ obj_items, notes = None, model_note
398
+ if args.object:
399
+ from .objects import draw, object_items
400
+ log(f"Stage: locating '{args.object}' in both runs (Grounding DINO) ...")
401
+ msgs = []
402
+ obj_items, ta, tb, _ = object_items(fa, fb, args.object, fps=args.fps, tol=args.object_tol,
403
+ target=args.target, log=msgs.append)
404
+ fa, fb = draw(fa, ta), draw(fb, tb) # boxes in the report
405
+ notes += msgs
406
+ shown, verdict = summary(res, args.min, floor_items, obj_items)
407
+ if args.explain:
408
+ from .explain import explain_diff
409
+ try:
410
+ exp = explain_diff(
411
+ res, fa, fb, shown,
412
+ backend=args.explain_backend,
413
+ model=args.explain_model,
414
+ url=args.explain_url,
415
+ load_4bit=bool(args.explain_4bit),
416
+ max_panels=max(2, int(args.explain_panels)),
417
+ debug_dir=args.explain_debug,
418
+ log=log,
419
+ )
420
+ res["explanation"] = exp
421
+ notes = list(notes) + [f"VLM explanation ({exp['model']})"]
422
+ except RuntimeError as exc:
423
+ raise SystemExit(f"Error (--explain): {exc}") from None
424
+ gated = bool(args.check or floor is not None or args.object)
425
+ badge, _ = diff_badge(shown, gated=gated, verdict=verdict)
426
+
427
+ print(f"rollout-diff A {args.a} ({len(fa) / args.fps:.1f} s) B {args.b} ({len(fb) / args.fps:.1f} s)", flush=True)
428
+ if res.get("start_scene_warning"):
429
+ print(f" WARNING: {res['start_scene_warning']}", flush=True)
430
+ for it in shown:
431
+ print(f" {it['kind']:12s} {it['text']}", flush=True)
432
+ if not shown:
433
+ print(f" no differences spotted above threshold", flush=True)
434
+ if res.get("explanation"):
435
+ exp = res["explanation"]
436
+ print(f"VLM Explanation ({exp.get('model', 'vlm')} · outcome={exp.get('outcome_match', 'uncertain')}):", flush=True)
437
+ print(f" {exp.get('headline', '')}", flush=True)
438
+ if exp.get("root_cause") and exp["root_cause"].lower() != "none":
439
+ print(f" Root cause: {exp['root_cause']}", flush=True)
440
+ for od in exp.get("object_diffs") or []:
441
+ bid = f"[#{od['box_id']}] " if od.get("box_id") is not None else ""
442
+ print(f" - {bid}{od.get('object', 'object')}: {od.get('what_happened', '')}", flush=True)
443
+ for ob in exp.get("observations") or []:
444
+ print(f" * {ob}", flush=True)
445
+ print(f"Result: {verdict}" if gated else f"Summary: {badge}", flush=True)
446
+ for n in notes:
447
+ print(f" note: {n}", flush=True)
448
+ note = " · ".join(([f"calibrated on {floor['runs']} good runs"] if floor else []) + notes)
449
+ if args.out:
450
+ log(f"Stage: writing interactive HTML report -> {args.out} ...")
451
+ write_html(res, fa, fb, args.out, args.a, args.b, args.min, floor_items, note, obj_items, gated=gated)
452
+ print(f"wrote {args.out}", flush=True)
453
+ if args.video:
454
+ from .export import write_video
455
+ log(f"Stage: rendering synced side-by-side video -> {args.video} ...")
456
+ write_video(res, fa, fb, args.video, args.a, args.b, min_s=args.min,
457
+ floor_items=floor_items, obj_items=obj_items, gated=gated)
458
+ print(f"wrote {args.video}", flush=True)
459
+ if args.json:
460
+ log(f"Stage: writing JSON summary -> {args.json} ...")
461
+ with open(args.json, "w", encoding="utf-8") as fh:
462
+ json.dump(dict(a=args.a, b=args.b, summary=badge, verdict=verdict if gated else None,
463
+ fps=args.fps, fp=args.fp, alike=res["alike"],
464
+ trim_a=res["trim_a"], trim_b=res["trim_b"],
465
+ start_scene_score=res.get("start_scene_score"),
466
+ start_scene_warning=res.get("start_scene_warning"),
467
+ explanation=res.get("explanation"),
468
+ items=shown, all_items=res["items"]), fh, indent=1, default=float)
469
+ print(f"wrote {args.json}", flush=True)
470
+ log(f"Done in {time.perf_counter() - t0:.1f}s.")
471
+ return (0 if verdict == "PASS" else 1) if gated else 0
472
+
473
+
474
+ if __name__ == "__main__":
475
+ sys.exit(main())