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/teach.py ADDED
@@ -0,0 +1,1374 @@
1
+ """Teach once from good runs, then check every new run (`rollout-diff teach` / `rollout-diff check`).
2
+
3
+ No VLM, no per-task rules, no fixed object lists. Everything is learnt from good runs of the task:
4
+ - robot-free start / end pictures of each run (Grounding DINO + SAM 2.1 robot cut-out, or --mask-model),
5
+ - 32x32 DINOv2-reg features of those pictures,
6
+ - zones: places that receive things in most good runs (empty-looking alike at the start, varied at the end),
7
+ - the normal end state: good-run end features around every cell,
8
+ - thresholds from leave-one-out over the good runs (no good run is flagged by the others).
9
+
10
+ A check reports task-agnostic end-state claims, each with the evidence it rests on:
11
+ UNEXPECTED something looks unexpected at the end outside the task regions
12
+ INCOMPLETE a task region changed much less from start to end than in every good run
13
+ WRONG TARGET what ended up in one task region looks like what good runs leave in another
14
+ WRONG STATE a spot inside a task region looks unlike every good run's end
15
+ WRONG LAYOUT a task region's overall end arrangement is unlike every good run's
16
+ """
17
+ import base64
18
+ import functools
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import cv2
23
+ import numpy as np
24
+
25
+ from . import report as R
26
+ from .core import load_run
27
+ from .object_diff import OBJ_LAYERS, _pair_diff_32, _sharp_plates
28
+ from .world.config import G
29
+ from .world.match import _box3_smooth
30
+ from .world.models import patch_tokens_reg_layers
31
+
32
+ # Let the usual side-by-side video report (report.write_html) draw and grade check claims too.
33
+ R.COLORS.update({"UNEXPECTED": "#dc2626", "INCOMPLETE": "#ea580c", "WRONG TARGET": "#c026d3", "WRONG STATE": "#0891b2",
34
+ "WRONG SPOT": "#7c3aed", "SPOT EMPTY": "#a16207", "WRONG LAYOUT": "#0e7490", "VANISHED": "#be123c",
35
+ "ALREADY DONE": "#d97706"})
36
+ R.FAILS.update({"UNEXPECTED", "INCOMPLETE", "WRONG TARGET", "WRONG STATE", "WRONG SPOT", "SPOT EMPTY", "WRONG LAYOUT", "VANISHED"})
37
+
38
+ WIN = 2 # +-2 cells (about +-6 % of the frame) of position tolerance against good runs
39
+ CHANGE_THR = 0.35 # start-vs-end distance (same run) that counts as "something changed here"
40
+ ZONE_SHARE = 0.6 # a zone receives things in at least 60 % of good runs
41
+ MIN_CELLS = 4 # smallest claim: 4 of 32x32 cells
42
+ LEFT_FLOOR = 0.30 # UNEXPECTED never fires below this end-state distance, however quiet the good runs were
43
+ LEFT_MARGIN = 0.05 # ... and needs this much more than the worst good run at that place (leave-one-out)
44
+ SHORT_FRAC = 0.5 # a region fill below half of the smallest good-run fill -> INCOMPLETE
45
+ SMALL_CELLS = 2 # a thin or small thing on the unsmoothed map: at least 2 patches over its own leave-one-out bar
46
+ OBJ_THR = 0.5 # a placed thing: cells whose start-vs-end distance is at least this (stronger than CHANGE_THR)
47
+ WRONG_MARGIN = 0.02 # WRONG TARGET needs this much more than the worst good-run item (leave-one-out)
48
+ SUBZONES = False # (off: no measured gain) keep separate landing spots separate (knife, fork, plate, glass) instead of merging them
49
+ IN_ZONE = True # also judge each zone's end look against the good runs (wrong pose or state in the right place)
50
+ SPOTS = False # (off: +14 false claims, 1/22 good runs flagged) inside a zone: things put where no good run puts anything / a place every good run fills left empty
51
+ ZONE_LOOK = True # the whole zone's end arrangement (4x4 layout fingerprint) vs every good run's
52
+ VANISH = False # (off: +15 false claims, 7/22 good runs flagged) something left its place and arrived nowhere
53
+ SPOT_TOL = 1 # one cell of slack for places inside a zone (finer than WIN: placement inside a zone is precise)
54
+ DEPTH = False # (off: flagged 16/22 good runs) Depth Anything V2 Small (Apache-2.0) on the start/end pictures as a second channel
55
+ DEPTH_MULT = 1.1 # depth bar = worst held-out good run x 1.1 (the convention calibrate uses for timing)
56
+ LAYOUT_STRONG = 1.35 # strong 4x4 spatial rearrangement ratio that triggers WRONG LAYOUT on its own
57
+ CONTENT_STRONG = 1.25 # strong order-invariant (k=1) content shift ratio that triggers WRONG LAYOUT on its own
58
+ LAYOUT_FLOOR = 0.035 # minimum 4x4 cosine bar (prevents 97%+ identical rigid placements firing WRONG LAYOUT)
59
+ CONTENT_FLOOR = 0.020 # minimum 1x1 cosine bar (prevents 98%+ identical content firing WRONG LAYOUT)
60
+ ZONE_VIS_MIN = 0.65 # minimum unoccluded share of a region required before flagging INCOMPLETE
61
+ SELF_BG = True # within-frame self-background check under cross-session lighting shifts (off when lighting matches)
62
+ SELF_BG_K = 8 # distant static background anchors used per cell
63
+ SELF_BG_STORE = 24 # candidate anchors stored (sorted best-first) so arm-occluded anchors fall back cleanly
64
+ SELF_BG_DIST = 4 # minimum grid distance (cells) from a cell to its background anchors
65
+ SELF_BG_LUMA = 15.0 # minimum static-background luminance shift (LAB L) to activate cross-session self-bg
66
+ SELF_BG_MAT = 24.0 # max teach material distance (chroma + texture + mild L) to treat a cell as background-like
67
+ SELF_BG_CHK = 32.0 # max same-frame full LAB+texture distance to confirm a cell matches this run's own background
68
+ SELF_BG_FLAT = 12.0 # max local std_L and edge gradient for flat background surfaces (excludes textured/3D objects)
69
+
70
+
71
+ # ---------------------------------------------------------------- one run -> robot-free state
72
+ def _grid(mask, g=G):
73
+ return cv2.resize(mask.astype(np.float32), (g, g), interpolation=cv2.INTER_AREA) >= 0.72
74
+
75
+
76
+ def _fuse(F):
77
+ """(L, G, G, D) multi-layer tokens -> (G, G, D) unit vectors."""
78
+ v = F.mean(0) if F.ndim == 4 else F
79
+ return (v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-8)).astype(np.float32)
80
+
81
+
82
+ FINE_WIDTH = 768 # full-resolution pictures for small things: native size, at most twice the normal width (memory)
83
+
84
+
85
+ def _load_fine(spec, fps, cam):
86
+ from .core import episode_frames, video_frames
87
+ if "#" in str(spec):
88
+ root, ep = str(spec).rsplit("#", 1)
89
+ return episode_frames(int(ep), fps, size=None, root=root, cam=cam, width=FINE_WIDTH)
90
+ w = int(cv2.VideoCapture(str(spec)).get(cv2.CAP_PROP_FRAME_WIDTH)) or FINE_WIDTH
91
+ return video_frames(spec, fps, size=None, width=min(w, FINE_WIDTH))
92
+
93
+
94
+ def _fine_features(start, end):
95
+ """Two full-resolution pictures -> (G2, G2, D) features each (G2 = 2 G): DINOv2 on 2 x 2 tiles, stitched."""
96
+ def tiles(im):
97
+ h, w = im.shape[:2]
98
+ return [im[:h // 2, :w // 2], im[:h // 2, w // 2:], im[h // 2:, :w // 2], im[h // 2:, w // 2:]]
99
+ T = patch_tokens_reg_layers(tiles(start) + tiles(end), layers=OBJ_LAYERS)
100
+ stitch = lambda t: np.concatenate([np.concatenate([t[0], t[1]], axis=-2), np.concatenate([t[2], t[3]], axis=-2)], axis=-3)
101
+ return _fuse(stitch(T[:4])), _fuse(stitch(T[4:]))
102
+
103
+
104
+ @functools.lru_cache(maxsize=1)
105
+ def _depth_model():
106
+ from transformers import DepthAnythingForDepthEstimation # USE_TF=0 is set by .world.models
107
+ from .world.models import quiet_model_load, select_device
108
+ name = "depth-anything/Depth-Anything-V2-Small-hf" # Apache-2.0 (Base/Large are non-commercial)
109
+ dev = select_device()
110
+ with quiet_model_load():
111
+ try:
112
+ m = DepthAnythingForDepthEstimation.from_pretrained(name, local_files_only=True)
113
+ except ImportError:
114
+ raise
115
+ except Exception:
116
+ print("downloading Depth Anything V2 Small (first run only; cached afterwards) ...", flush=True)
117
+ m = DepthAnythingForDepthEstimation.from_pretrained(name)
118
+ m = m.to(dev).eval()
119
+ return m.half() if dev == "cuda" else m
120
+
121
+
122
+ def depth_maps(imgs):
123
+ """RGB pictures -> (G, G) relative depth per picture, normalised by its own median and spread, so runs of the
124
+ same fixed camera can be compared cell by cell."""
125
+ import torch
126
+ m = _depth_model()
127
+ dev, dt = next(m.parameters()).device, next(m.parameters()).dtype
128
+ x = np.stack([cv2.resize(im, (518, 392), interpolation=cv2.INTER_AREA) for im in imgs]).astype(np.float32) / 255
129
+ x = (x - np.array([0.485, 0.456, 0.406], np.float32)) / np.array([0.229, 0.224, 0.225], np.float32)
130
+ with torch.no_grad():
131
+ d = m(pixel_values=torch.as_tensor(x).permute(0, 3, 1, 2).to(dev, dt)).predicted_depth.float().cpu().numpy()
132
+ out = []
133
+ for di in d:
134
+ g = cv2.resize(di, (G, G), interpolation=cv2.INTER_AREA)
135
+ med = float(np.median(g))
136
+ out.append(((g - med) / (1.4826 * float(np.median(np.abs(g - med))) + 1e-6)).astype(np.float32))
137
+ return out
138
+
139
+
140
+ def window_min_absdiff(D, bank, bank_valid, win=WIN):
141
+ """Per cell, the smallest |depth difference| to any valid bank cell within +-win cells."""
142
+ best = np.full(D.shape, np.inf, np.float32)
143
+ gh, gw = D.shape
144
+ for X, V in zip(bank, bank_valid):
145
+ for dy in range(-win, win + 1):
146
+ for dx in range(-win, win + 1):
147
+ ya0, ya1, yb0, yb1 = max(0, -dy), gh - max(0, dy), max(0, dy), gh - max(0, -dy)
148
+ xa0, xa1, xb0, xb1 = max(0, -dx), gw - max(0, dx), max(0, dx), gw - max(0, -dx)
149
+ diff = np.where(V[yb0:yb1, xb0:xb1], np.abs(D[ya0:ya1, xa0:xa1] - X[yb0:yb1, xb0:xb1]), np.inf)
150
+ np.minimum(best[ya0:ya1, xa0:xa1], diff, out=best[ya0:ya1, xa0:xa1])
151
+ return np.where(np.isfinite(best), best, 0.0).astype(np.float32)
152
+
153
+
154
+ def run_state(run, fps=10, cam="side", mask_model=None, log=None, fine=False, spec=None):
155
+ """A video / LeRobot episode (or its frames) -> robot-free start and end pictures plus 32x32 features."""
156
+ frames = load_run(run, fps=fps, cam=cam) if isinstance(run, (str, Path)) else run
157
+ if mask_model is None:
158
+ from .robot_mask import estimate_robot_cover
159
+ rob, kf = estimate_robot_cover(frames, log=log, return_keyframes=True)
160
+ pl = _sharp_plates(frames, rob=rob, kf_masks=kf)
161
+ cover = np.asarray(rob, np.float32).max(0) # where the arm was at any time (16x16)
162
+ kf_idx, kf_m = kf
163
+ arm_end = (kf_m[-1].astype(bool)
164
+ if len(kf_m) and int(kf_idx[-1]) == len(frames) - 1 and float(kf_m[-1].mean()) < 0.90
165
+ else cv2.resize(np.asarray(rob[-1], np.float32), frames.shape[2:0:-1], interpolation=cv2.INTER_LINEAR) >= 0.2)
166
+ else:
167
+ from .world.plates import _frame_motion_envelope, _sample_indices
168
+ pl = _sharp_plates(frames, mask_model=mask_model)
169
+ idx = _sample_indices(len(frames))
170
+ env = _frame_motion_envelope(frames)
171
+ cover = np.asarray(mask_model(frames, idx, env)).any(0).astype(np.float32)
172
+ arm_end = np.asarray(mask_model(frames, [len(frames) - 1], env))[0]
173
+ reach = cv2.resize(cover, (G, G), interpolation=cv2.INTER_AREA) >= 0.2
174
+ F0, F1 = patch_tokens_reg_layers([pl["start_plate"], pl["end_plate"]], layers=OBJ_LAYERS)
175
+ out = dict(S=_fuse(F0), E=_fuse(F1), valid_s=_grid(pl["valid_start"]), valid_e=_grid(pl["valid_end"]),
176
+ change=_pair_diff_32(None, None, F0, F1, rad=1), start_img=pl["start_plate"],
177
+ end_img=pl["end_plate"], reach=reach, n=len(frames), arm_end=arm_end)
178
+ if DEPTH:
179
+ out["D_s"], out["D_e"] = depth_maps([pl["start_plate"], pl["end_plate"]])
180
+ spec = spec or (run if isinstance(run, (str, Path)) else None)
181
+ if fine and spec is not None: # same robot cut-out, applied to full-resolution frames
182
+ ff = _load_fine(spec, fps, cam)
183
+ if mask_model is None:
184
+ kf_idx, kf_m = kf
185
+ up = [cv2.resize(np.asarray(m, np.uint8), (ff.shape[2], ff.shape[1]), interpolation=cv2.INTER_NEAREST) > 0
186
+ for m in kf_m]
187
+ pf = _sharp_plates(ff, rob=rob, kf_masks=(kf_idx, up))
188
+ else:
189
+ pf = _sharp_plates(ff, mask_model=mask_model)
190
+ g2 = 2 * G
191
+ out.update(zip(("S_fine", "E_fine"), _fine_features(pf["start_plate"], pf["end_plate"])))
192
+ out.update(valid_s_fine=_grid(pf["valid_start"], g2), valid_e_fine=_grid(pf["valid_end"], g2),
193
+ end_img_fine=pf["end_plate"])
194
+ return out
195
+
196
+
197
+ # ---------------------------------------------------------------- shared maths
198
+ def window_max_sim(F, bank, bank_valid, win=WIN):
199
+ """Per cell, the best cosine similarity of F[y, x] to any valid bank feature within +-win cells."""
200
+ best = np.full(F.shape[:2], -1.0, np.float32)
201
+ gh, gw = F.shape[:2]
202
+ for X, V in zip(bank, bank_valid):
203
+ X = X.astype(np.float32)
204
+ for dy in range(-win, win + 1):
205
+ for dx in range(-win, win + 1):
206
+ ya0, ya1, yb0, yb1 = max(0, -dy), gh - max(0, dy), max(0, dy), gh - max(0, -dy)
207
+ xa0, xa1, xb0, xb1 = max(0, -dx), gw - max(0, dx), max(0, dx), gw - max(0, -dx)
208
+ sim = (F[ya0:ya1, xa0:xa1] * X[yb0:yb1, xb0:xb1]).sum(-1)
209
+ sim = np.where(V[yb0:yb1, xb0:xb1], sim, -1.0)
210
+ np.maximum(best[ya0:ya1, xa0:xa1], sim, out=best[ya0:ya1, xa0:xa1])
211
+ return best
212
+
213
+
214
+ def _spread(feats):
215
+ """Mean pairwise cosine distance across runs, per cell: how much a place varies between good runs."""
216
+ n, acc = len(feats), np.zeros((G, G), np.float32)
217
+ for i in range(n):
218
+ for j in range(i + 1, n):
219
+ acc += 1.0 - (feats[i] * feats[j]).sum(-1)
220
+ return acc / max(1, n * (n - 1) // 2)
221
+
222
+
223
+ def _components(mask, min_cells=MIN_CELLS):
224
+ n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
225
+ return [lab == k for k in range(1, n) if stats[k, cv2.CC_STAT_AREA] >= min_cells]
226
+
227
+
228
+ def zone_layout(E, valid, zm, k=4):
229
+ """A zone's end arrangement: its box split into k x k blocks, mean feature per block (zone and robot-free cells
230
+ only), concatenated and normalised. Things lying elsewhere or in another pose change the layout, not just a spot."""
231
+ ys, xs = np.nonzero(zm)
232
+ sub, m = E[ys.min():ys.max() + 1, xs.min():xs.max() + 1], (zm & valid)[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
233
+ parts = []
234
+ for rows in np.array_split(np.arange(sub.shape[0]), k):
235
+ for cols in np.array_split(np.arange(sub.shape[1]), k):
236
+ blk, mk = sub[np.ix_(rows, cols)], m[np.ix_(rows, cols)]
237
+ parts.append(blk[mk].mean(0) if mk.any() else np.zeros(E.shape[-1], np.float32))
238
+ v = np.concatenate(parts)
239
+ return (v / max(float(np.linalg.norm(v)), 1e-8)).astype(np.float32)
240
+
241
+
242
+ def _residual(A, B):
243
+ """What is in A but not in B, per cell: A minus its part along B, normalised."""
244
+ r = A - (A * B).sum(-1, keepdims=True) * B
245
+ return r / np.maximum(np.linalg.norm(r, axis=-1, keepdims=True), 1e-6)
246
+
247
+
248
+ def departures_and_matches(s, d_end, d_start, bar, outside, arrive):
249
+ """Things that left their place in this run: changed, clear at the end like good runs (d_end <= bar) and occupied
250
+ at the start (d_start > bar), outside the zones. For each, how well its look matches anything that arrived
251
+ (best cosine between what left and what came, cell by cell). Returns [(component, best match)]."""
252
+ changed = _changed(s)
253
+ left = _residual(s["S"], s["E"]) # what was there at the start
254
+ came = _residual(s["E"], s["S"])[changed & arrive] # what is new at the end, where things arrive
255
+ out = []
256
+ for comp in _components(changed & outside & (d_end <= bar) & (d_start > bar)):
257
+ v = left[comp].mean(0)
258
+ v = v / max(float(np.linalg.norm(v)), 1e-6)
259
+ out.append((comp, float((came @ v).max()) if len(came) else -1.0))
260
+ return out
261
+
262
+
263
+ def _grow_apart(comps, steps):
264
+ """Grow each component by `steps` cells (8-neighbour), a cell going to whichever reaches it first: no merging."""
265
+ lab = np.zeros((G, G), np.int32)
266
+ for k, c in enumerate(comps, 1):
267
+ lab[c] = k
268
+ k3 = np.ones((3, 3), np.uint8)
269
+ for _ in range(steps):
270
+ free = lab == 0
271
+ for k in range(1, len(comps) + 1):
272
+ grow = (cv2.dilate((lab == k).astype(np.uint8), k3) > 0) & free & (lab == 0)
273
+ lab[grow] = k
274
+ return [lab == k for k in range(1, len(comps) + 1)]
275
+
276
+
277
+ def _box(mask):
278
+ ys, xs = np.nonzero(mask)
279
+ gh, gw = mask.shape
280
+ return [round(xs.min() / gw, 4), round(ys.min() / gh, 4), round((xs.max() + 1) / gw, 4), round((ys.max() + 1) / gh, 4)]
281
+
282
+
283
+ def where(box):
284
+ cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
285
+ v = "top" if cy < 0.34 else "bottom" if cy > 0.66 else ""
286
+ h = "left" if cx < 0.34 else "right" if cx > 0.66 else ""
287
+ return "-".join(p for p in (v, h) if p) or "middle"
288
+
289
+
290
+ def colour(img, box):
291
+ """Plain colour word of the dominant pixels in `box` (HSV bins, no model)."""
292
+ h, w = img.shape[:2]
293
+ crop = img[int(box[1] * h):max(int(box[1] * h) + 1, int(box[3] * h)),
294
+ int(box[0] * w):max(int(box[0] * w) + 1, int(box[2] * w))]
295
+ hsv = cv2.cvtColor(crop, cv2.COLOR_RGB2HSV).reshape(-1, 3).astype(np.float32)
296
+ sat = hsv[hsv[:, 1] >= 60]
297
+ if len(sat) < 0.25 * len(hsv):
298
+ v = float(np.median(hsv[:, 2]))
299
+ return "dark" if v < 70 else "white" if v > 185 else "grey"
300
+ hue = float(np.median(sat[:, 0]))
301
+ for lim, name in ((8, "red"), (20, "orange"), (33, "yellow"), (80, "green"), (100, "cyan"), (130, "blue"),
302
+ (150, "purple"), (170, "pink")):
303
+ if hue < lim:
304
+ return name
305
+ return "red"
306
+
307
+
308
+ # ---------------------------------------------------------------- teach
309
+ def _changed(s):
310
+ return (s["change"] >= CHANGE_THR) & s["valid_s"] & s["valid_e"]
311
+
312
+
313
+ def _objects(s, zones):
314
+ """Things placed in each zone: strongly changed cell groups, each described by WHAT WAS ADDED there
315
+ (end feature minus its own start feature), so the container around it does not decide the match."""
316
+ r = s["E"] - (s["E"] * s["S"]).sum(-1, keepdims=True) * s["S"]
317
+ r /= np.maximum(np.linalg.norm(r, axis=-1, keepdims=True), 1e-6)
318
+ strong = (s["change"] >= OBJ_THR) & s["valid_s"] & s["valid_e"]
319
+ out = []
320
+ for z, zm in enumerate(zones):
321
+ for comp in _components(strong & zm, min_cells=3):
322
+ v = r[comp].mean(0)
323
+ out.append((z, comp, (v / max(float(np.linalg.norm(v)), 1e-6)).astype(np.float32)))
324
+ return out
325
+
326
+
327
+ def _margin(v, z, descs, zone_of):
328
+ """How much more a placed thing looks like another zone's good-run things than like its own zone's."""
329
+ if not len(descs):
330
+ return -2.0, z
331
+ sims = descs @ v
332
+ own = sims[zone_of == z].max() if (zone_of == z).any() else -1.0
333
+ if not (zone_of != z).any():
334
+ return -2.0, z
335
+ k = int(np.argmax(np.where(zone_of != z, sims, -9.0)))
336
+ return float(sims[k] - own), int(zone_of[k])
337
+
338
+
339
+ def teach(states, runs=(), task="", log=print):
340
+ """Good-run states -> a taught model (dict of arrays + meta)."""
341
+ n = len(states)
342
+ if n < 2:
343
+ raise ValueError("teach needs at least 2 good runs (3-5 recommended)")
344
+ changed = np.stack([_changed(s) for s in states])
345
+ share = changed.mean(0)
346
+ var_s, var_e = _spread([s["S"] for s in states]), _spread([s["E"] for s in states])
347
+ raw = (share >= ZONE_SHARE) & (var_e > var_s) # receives things, rather than gives them away
348
+ if SUBZONES: # each landing spot grows by WIN on its own; neighbours never merge into one zone
349
+ zones = _grow_apart(_components(raw, min_cells=2), WIN) # (no gap closing first: that joins neighbours)
350
+ zones = [z for z in zones if z.sum() >= MIN_CELLS]
351
+ else:
352
+ raw = cv2.morphologyEx(raw.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
353
+ raw = cv2.dilate(raw, np.ones((2 * WIN + 1, 2 * WIN + 1), np.uint8)) > 0 # things land a little apart each run
354
+ zones = _components(raw)
355
+ zones.sort(key=lambda m: _box(m)[0])
356
+ zone_any = np.any(zones, axis=0) if zones else np.zeros((G, G), bool)
357
+ near_zone = cv2.dilate(zone_any.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
358
+
359
+ fills = [[int((changed[r] & zm).sum()) for r in range(n)] for zm in zones]
360
+ # The slot map: where inside the zones good runs put things, and (leave-one-out) how large a held-out good run's
361
+ # odd spots and empty usual places can get, so normal slot-to-slot variation is not reported.
362
+ look, look_meta = {}, {}
363
+ if ZONE_LOOK and zones and n >= 3: # each zone's 4x4 spatial layout + 1x1 order-invariant content
364
+ L = np.stack([[zone_layout(s["E"], s["valid_e"], zm, k=4) for zm in zones] for s in states]) # (n, Z, 16*D)
365
+ L1 = np.stack([[zone_layout(s["E"], s["valid_e"], zm, k=1) for zm in zones] for s in states]) # (n, Z, D)
366
+ bars, c_bars = [], []
367
+ for z in range(len(zones)):
368
+ sims = L[:, z] @ L[:, z].T
369
+ bars.append(round(float(max(1.0 - np.max(np.delete(sims[r], r)) for r in range(n))) * DEPTH_MULT, 4))
370
+ s1 = L1[:, z] @ L1[:, z].T
371
+ c_bars.append(round(float(max(1.0 - np.max(np.delete(s1[r], r)) for r in range(n))) * DEPTH_MULT, 4))
372
+ look = dict(zone_layouts=L.astype(np.float16), zone_contents=L1.astype(np.float16))
373
+ look_meta = dict(zone_look_bar=bars, zone_content_bar=c_bars)
374
+ spots, spot_meta = {}, {}
375
+ if SPOTS and zones:
376
+ zone_all = np.any(zones, axis=0)
377
+ arr = np.stack([changed[r] & zone_all for r in range(n)])
378
+ tk = np.ones((2 * SPOT_TOL + 1, 2 * SPOT_TOL + 1), np.uint8)
379
+ nov, mis = [0], [0]
380
+ for r in range(n):
381
+ others = np.delete(arr, r, 0)
382
+ nov += [int(c.sum()) for c in _components(arr[r] & ~(cv2.dilate(others.any(0).astype(np.uint8), tk) > 0), 1)]
383
+ mis += [int(c.sum()) for c in _components(others.all(0) & ~(cv2.dilate(arr[r].astype(np.uint8), tk) > 0), 1)]
384
+ spots, spot_meta = dict(arr_bank=arr), dict(spot_novel_max=max(nov), spot_missing_max=max(mis))
385
+ # Workspace: where the arm reaches or things change in good runs (+-WIN). Chairs, shelves and people in the
386
+ # background are outside it, so nothing is reported there.
387
+ seen = changed.any(0) | np.any([s.get("reach", np.zeros((G, G), bool)) for s in states], axis=0)
388
+ k5 = np.ones((2 * WIN + 1, 2 * WIN + 1), np.uint8)
389
+ workspace = (cv2.dilate(seen.astype(np.uint8), k5) > 0) if seen.any() else np.ones((G, G), bool)
390
+ objs = [(z, v, r) for r, s in enumerate(states) for z, _, v in _objects(s, zones)]
391
+ D = states[0]["E"].shape[-1]
392
+ obj_desc = np.stack([v for _, v, _ in objs]) if objs else np.zeros((0, D), np.float32)
393
+ obj_zone = np.array([z for z, _, _ in objs], int)
394
+ obj_run = np.array([r for _, _, r in objs], int)
395
+
396
+ # Leave-one-out: how far each good run's end state is from the other good runs, per place.
397
+ E_bank, Ve_bank = [s["E"] for s in states], [s["valid_e"] for s in states]
398
+ loo, loo_raw = np.zeros((n, G, G), np.float32), np.zeros((n, G, G), np.float32)
399
+ for r in range(n):
400
+ others = [k for k in range(n) if k != r]
401
+ d = 1.0 - window_max_sim(E_bank[r], [E_bank[k] for k in others], [Ve_bank[k] for k in others])
402
+ loo[r] = np.where(Ve_bank[r], _box3_smooth(d, Ve_bank[r])[0], 0.0)
403
+ loo_raw[r] = np.where(Ve_bank[r], d, 0.0)
404
+ k3 = np.ones((3, 3), np.uint8)
405
+ left_thr = np.maximum(cv2.dilate(loo.max(0), k3) + LEFT_MARGIN, LEFT_FLOOR).astype(np.float32)
406
+ # VANISHED bar: in good runs everything that leaves its place arrives somewhere; the worst such match.
407
+ van_meta = {}
408
+ if VANISH and zones:
409
+ arrive = np.ones((G, G), bool) # what arrived: anywhere newly occupied
410
+ matches = []
411
+ for r in range(n):
412
+ others = [k for k in range(n) if k != r]
413
+ d0 = 1.0 - window_max_sim(states[r]["S"], [E_bank[k] for k in others], [Ve_bank[k] for k in others])
414
+ d0 = np.where(states[r]["valid_s"], _box3_smooth(d0, states[r]["valid_s"])[0], 0.0)
415
+ matches += [m for _, m in departures_and_matches(states[r], loo[r], d0, left_thr, ~near_zone & workspace,
416
+ arrive)]
417
+ if matches:
418
+ van_meta = dict(vanish_bar=round(min(matches), 4), n_departures=len(matches))
419
+ # Same idea on the unsmoothed map (thin or small things the smoothing erases), but that map is noisier, so its
420
+ # margin is learnt: the smallest margin at which no good run, held out, shows a single small spot against the
421
+ # bar built from the other good runs.
422
+ def _spots(m):
423
+ for r in range(n):
424
+ bar = np.maximum(cv2.dilate(np.delete(loo_raw, r, 0).max(0), k3) + m, LEFT_FLOOR)
425
+ if _components((loo_raw[r] > bar) & Ve_bank[r] & ~near_zone, min_cells=SMALL_CELLS):
426
+ return True
427
+ return False
428
+ small_margin = next((m for m in np.arange(LEFT_MARGIN, 1.0, 0.01) if not _spots(m)), None)
429
+ left_thr_raw = (np.maximum(cv2.dilate(loo_raw.max(0), k3) + small_margin, LEFT_FLOOR).astype(np.float32)
430
+ if small_margin is not None and n >= 3 else np.full((G, G), 9.0, np.float32)) # 9 = path off
431
+ fine = {}
432
+ if n >= 3 and all("E_fine" in s for s in states): # full-resolution 64x64 grid for small things
433
+ Ef, Vf = [s["E_fine"] for s in states], [s["valid_e_fine"] for s in states]
434
+ g2 = Ef[0].shape[0]
435
+ wf = WIN * g2 // G # same tolerance in real distance
436
+ up = lambda m: cv2.resize(m.astype(np.uint8), (g2, g2), interpolation=cv2.INTER_NEAREST) > 0
437
+ near_f, ws_f = up(near_zone), up(workspace)
438
+ loo_f = np.stack([np.where(Vf[r], 1.0 - window_max_sim(Ef[r], [Ef[k] for k in range(n) if k != r],
439
+ [Vf[k] for k in range(n) if k != r], win=wf), 0.0)
440
+ for r in range(n)])
441
+
442
+ def _spots_f(m):
443
+ for r in range(n):
444
+ bar = np.maximum(cv2.dilate(np.delete(loo_f, r, 0).max(0), k3) + m, LEFT_FLOOR)
445
+ if _components((loo_f[r] > bar) & Vf[r] & ~near_f & ws_f, min_cells=SMALL_CELLS):
446
+ return True
447
+ return False
448
+ mf = next((m for m in np.arange(LEFT_MARGIN, 1.0, 0.01) if not _spots_f(m)), None)
449
+ if mf is not None:
450
+ fine = dict(E_fine_bank=np.stack(Ef).astype(np.float16), Ve_fine_bank=np.stack(Vf),
451
+ left_thr_fine=np.maximum(cv2.dilate(loo_f.max(0), k3) + mf, LEFT_FLOOR).astype(np.float32))
452
+
453
+ depth = {}
454
+ if DEPTH and all("D_e" in s for s in states):
455
+ DE = [s["D_e"] for s in states]
456
+ dl = np.zeros((n, G, G), np.float32)
457
+ for r in range(n):
458
+ dd = window_min_absdiff(DE[r], [DE[k] for k in range(n) if k != r], [Ve_bank[k] for k in range(n) if k != r])
459
+ dl[r] = np.where(Ve_bank[r], _box3_smooth(dd, Ve_bank[r])[0], 0.0)
460
+ depth = dict(D_bank=np.stack(DE).astype(np.float32),
461
+ depth_thr=np.maximum(cv2.dilate(dl.max(0), k3) * DEPTH_MULT, 1e-3).astype(np.float32))
462
+
463
+ # WRONG ZONE bar: no good-run object may look more like another zone than the other good runs allow,
464
+ # and a claim can only fire when the item actually looks closer to another zone than its own (margin >= WRONG_MARGIN).
465
+ loo_m = [_margin(v, z, obj_desc[obj_run != r], obj_zone[obj_run != r])[0] for z, v, r in objs]
466
+ wrong_thr = max(max(loo_m) + WRONG_MARGIN, WRONG_MARGIN) if len(zones) > 1 and loo_m else None
467
+
468
+ meta = dict(version=1, task=task, runs=[str(x) for x in runs], n_runs=n, grid=G,
469
+ zones=[dict(id=z + 1, box=_box(zm), where=where(_box(zm)), fills=fills[z],
470
+ receives_in=int((changed[:, zm].any(1)).sum())) for z, zm in enumerate(zones)],
471
+ wrong_thr=None if wrong_thr is None else round(float(wrong_thr), 3), n_objects=len(objs), **spot_meta, **look_meta, **van_meta,
472
+ left_thr_median=round(float(np.median(left_thr[~near_zone])) if (~near_zone).any() else LEFT_FLOOR, 3),
473
+ params=dict(WIN=WIN, CHANGE_THR=CHANGE_THR, ZONE_SHARE=ZONE_SHARE, MIN_CELLS=MIN_CELLS,
474
+ LEFT_FLOOR=LEFT_FLOOR, LEFT_MARGIN=LEFT_MARGIN, SHORT_FRAC=SHORT_FRAC,
475
+ OBJ_THR=OBJ_THR, WRONG_MARGIN=WRONG_MARGIN))
476
+ if log:
477
+ if meta["zones"]:
478
+ log(f"taught from {n} good runs: {len(zones)} region(s) "
479
+ + ", ".join(f"region {z['id']} ({z['where']}) receives in {z['receives_in']}/{n} runs, fill {min(z['fills'])}-{max(z['fills'])} cells"
480
+ for z in meta["zones"]))
481
+ else:
482
+ log(f"taught from {n} good runs: 0 fixed end-state region(s) "
483
+ "(normal when objects return to their start spot or end in varying places; "
484
+ "check still watches for unexpected leftovers and timing shifts; add --objects to track moved items)")
485
+ self_bg = _learn_self_bg(states, zones, changed)
486
+ return dict(meta=meta, E_bank=np.stack(E_bank).astype(np.float16), Ve_bank=np.stack(Ve_bank),
487
+ zones=np.stack(zones) if zones else np.zeros((0, G, G), bool), obj_desc=obj_desc.astype(np.float16),
488
+ obj_zone=obj_zone, left_thr=left_thr, left_thr_raw=left_thr_raw, workspace=workspace, S_small=np.stack([_pool(s["S"]) for s in states]).astype(np.float16),
489
+ preview=states[0]["end_img"], **fine, **depth, **spots, **look, **self_bg)
490
+
491
+
492
+ def _patch_mat(img_rgb):
493
+ """RGB image -> (G, G, 5) local LAB + texture descriptor [L, a, b, std_L, grad] with zero positional bias."""
494
+ lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32)
495
+ L = lab[..., 0]
496
+ gx = cv2.Sobel(L, cv2.CV_32F, 1, 0, ksize=3)
497
+ gy = cv2.Sobel(L, cv2.CV_32F, 0, 1, ksize=3)
498
+ grad = cv2.magnitude(gx, gy) * 0.25
499
+ m_lab = cv2.resize(lab, (G, G), interpolation=cv2.INTER_AREA)
500
+ m_L2 = cv2.resize(L * L, (G, G), interpolation=cv2.INTER_AREA)
501
+ std_L = np.sqrt(np.maximum(0.0, m_L2 - m_lab[..., 0] ** 2))
502
+ m_g = cv2.resize(grad, (G, G), interpolation=cv2.INTER_AREA)
503
+ return np.stack([m_lab[..., 0], m_lab[..., 1], m_lab[..., 2], std_L, m_g], axis=-1).astype(np.float32)
504
+
505
+
506
+ _W_MAT = np.array([0.25, 2.5, 2.5, 1.8, 1.2], np.float32) # material match across illumination gradients
507
+ _W_CHK = np.array([0.80, 2.5, 2.5, 1.8, 1.2], np.float32) # same-frame verification (full brightness + chroma + texture)
508
+
509
+
510
+ def _learn_self_bg(states, zones, changed):
511
+ """Learn per-cell distant static background anchors from good runs so cross-session lighting shifts on bare
512
+ surfaces (table, desk mat) are recognised within-frame without ever absorbing real objects."""
513
+ if not SELF_BG or len(states) < 3 or any(s.get("end_img") is None for s in states):
514
+ return {}
515
+ if float(np.std(states[0]["end_img"])) < 5.0: # constant synthetic test image
516
+ return {}
517
+ n = len(states)
518
+ tE = np.stack([s["E"] for s in states])
519
+ tVs = np.stack([s["valid_s"] for s in states])
520
+ tVe = np.stack([s["valid_e"] for s in states])
521
+ tM = np.stack([_patch_mat(s["end_img"]) for s in states])
522
+ za = np.any(zones, axis=0) if len(zones) else np.zeros((G, G), bool)
523
+ pool = (changed.mean(0) < 0.1) & (tVs.mean(0) > 0.8) & (tVe.mean(0) > 0.8) & ~za
524
+ pool_idx = np.flatnonzero(pool.ravel())
525
+ if len(pool_idx) < SELF_BG_K + 4:
526
+ return {}
527
+ py, px = np.divmod(pool_idx, G)
528
+ gy, gx = np.divmod(np.arange(G * G), G)
529
+ dist2 = (gy[:, None] - py[None, :]) ** 2 + (gx[:, None] - px[None, :]) ** 2
530
+ F_mat = (tM * _W_MAT).reshape(n, G * G, 5)
531
+ avg_d = np.zeros((G * G, len(pool_idx)), np.float32)
532
+ for r in range(n):
533
+ avg_d += np.linalg.norm(F_mat[r][:, None, :] - F_mat[r][pool_idx][None, :, :], axis=-1)
534
+ avg_d = np.where(dist2 >= SELF_BG_DIST ** 2, avg_d / n, 1e6)
535
+ k_store = min(SELF_BG_STORE, len(pool_idx))
536
+ anchors = pool_idx[np.argsort(avg_d, axis=1)[:, :k_store]]
537
+ anc_top = anchors[:, :SELF_BG_K]
538
+ d_mat = np.stack([np.median(np.linalg.norm(F_mat[r][:, None, :] - F_mat[r][anc_top], axis=-1), axis=1) for r in range(n)])
539
+ p90_mat = np.percentile(d_mat, 90, axis=0).reshape(G, G)
540
+ F_chk = (tM * _W_CHK).reshape(n, G * G, 5)
541
+ d_chk = np.stack([np.median(np.linalg.norm(F_chk[r][:, None, :] - F_chk[r][anc_top], axis=-1), axis=1) for r in range(n)])
542
+ p90_chk = np.percentile(d_chk, 90, axis=0).reshape(G, G)
543
+ bg_end = tE.mean(0)
544
+ bg_end /= np.maximum(np.linalg.norm(bg_end, axis=-1, keepdims=True), 1e-8)
545
+ flat = (np.median(tM[..., 3], axis=0) < SELF_BG_FLAT) & (np.median(tM[..., 4], axis=0) < SELF_BG_FLAT)
546
+ return dict(
547
+ self_bg_anc=anchors.astype(np.int16),
548
+ self_bg_mat=p90_mat.astype(np.float16),
549
+ self_bg_chk=p90_chk.astype(np.float16),
550
+ self_bg_end=bg_end.astype(np.float16),
551
+ self_bg_L=tM[..., 0].mean(0).astype(np.float16),
552
+ self_bg_pool=pool,
553
+ self_bg_flat=flat,
554
+ )
555
+
556
+
557
+ def _local_flat_bg(model, s, rc=None):
558
+ """Per-cell mask of flat bare-background cells confirmed against THIS run's own distant static anchors
559
+ in chroma & texture (allowing localized soft-shadow brightness shifts without absorbing real objects)."""
560
+ if not SELF_BG or "self_bg_anc" not in model or s.get("end_img") is None:
561
+ return None
562
+ if float(np.std(s["end_img"])) < 5.0:
563
+ return None
564
+ rM = _patch_mat(s["end_img"])
565
+ if rc is None:
566
+ rc = _changed(s)
567
+ rF = (rM * _W_MAT).reshape(G * G, 5)
568
+ anc = model["self_bg_anc"].astype(np.int32)
569
+ ok_a = (~rc & s["valid_e"]).ravel()
570
+ med_m = np.full(G * G, 1e6, np.float32)
571
+ for p in range(G * G):
572
+ valid_a = anc[p][ok_a[anc[p]]][:SELF_BG_K]
573
+ if len(valid_a) >= 3:
574
+ med_m[p] = float(np.median(np.linalg.norm(rF[p] - rF[valid_a], axis=-1)))
575
+ med_m = med_m.reshape(G, G)
576
+ p90_mat = model["self_bg_mat"].astype(np.float32)
577
+ flat_ok = model["self_bg_flat"].astype(bool) & (rM[..., 3] < SELF_BG_FLAT) & (rM[..., 4] < SELF_BG_FLAT)
578
+ return (p90_mat <= SELF_BG_MAT) & flat_ok & (med_m <= np.maximum(SELF_BG_MAT, p90_mat + 6.0)) & s["valid_e"]
579
+
580
+
581
+ def _apply_self_bg(model, s):
582
+ """When a run has a genuine cross-session lighting shift on static background pixels, replace DINOv2 end features
583
+ ONLY on flat background-like cells confirmed to match this run's own distant static background anchors."""
584
+ if not SELF_BG or "self_bg_anc" not in model or s.get("end_img") is None:
585
+ return s
586
+ if float(np.std(s["end_img"])) < 5.0:
587
+ return s
588
+ rM = _patch_mat(s["end_img"])
589
+ rc = _changed(s)
590
+ pool = model["self_bg_pool"].astype(bool)
591
+ L_t = model["self_bg_L"].astype(np.float32)
592
+ L_b = rM[..., 0]
593
+ mid = pool & ~rc & s["valid_e"] & (L_t >= 25.0) & (L_t <= 235.0)
594
+ if int(mid.sum()) < 20:
595
+ return s
596
+ luma_shift = float(np.median(np.abs(L_b[mid] - L_t[mid])))
597
+ if luma_shift < SELF_BG_LUMA: # same lighting session: stay 100% untouched
598
+ return s
599
+ rF = (rM * _W_CHK).reshape(G * G, 5)
600
+ anc = model["self_bg_anc"].astype(np.int32)
601
+ ok_a = (~rc & s["valid_e"]).ravel()
602
+ med_b = np.full(G * G, 1e6, np.float32)
603
+ for p in range(G * G):
604
+ valid_a = anc[p][ok_a[anc[p]]][:SELF_BG_K] # first K valid anchors (gracefully skips arm-occluded ones)
605
+ if len(valid_a) >= 3:
606
+ med_b[p] = float(np.median(np.linalg.norm(rF[p] - rF[valid_a], axis=-1)))
607
+ med_b = med_b.reshape(G, G)
608
+ p90_mat = model["self_bg_mat"].astype(np.float32)
609
+ p90_chk = model["self_bg_chk"].astype(np.float32)
610
+ flat_ok = model["self_bg_flat"].astype(bool) & (rM[..., 3] < SELF_BG_FLAT) & (rM[..., 4] < SELF_BG_FLAT)
611
+ is_own_bg = (p90_mat <= SELF_BG_MAT) & flat_ok & (med_b <= np.maximum(SELF_BG_CHK, p90_chk + 8.0)) & s["valid_e"]
612
+ if not is_own_bg.any():
613
+ return s
614
+ bg_end = model["self_bg_end"].astype(np.float32)
615
+ return dict(s, E=np.where(is_own_bg[..., None], bg_end, s["E"]).astype(np.float32))
616
+
617
+
618
+ def _pool(F):
619
+ """(G, G, D) -> (G/2, G/2, D) unit vectors: a small start picture, to find the good run that started most alike."""
620
+ v = F.reshape(G // 2, 2, G // 2, 2, -1).mean((1, 3))
621
+ return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-8)
622
+
623
+
624
+ def pick_ref(model, s):
625
+ """The taught good run whose start looks most like this run's start (the A side of the video report)."""
626
+ runs = model["meta"]["runs"]
627
+ if not runs:
628
+ return None
629
+ if "S_small" not in model: # file taught before this was stored
630
+ return runs[0]
631
+ sims = (model["S_small"].astype(np.float32) * _pool(s["S"])[None]).sum(-1).mean((1, 2))
632
+ return runs[int(np.argmax(sims))]
633
+
634
+
635
+ def save(model, path):
636
+ ok, jpg = cv2.imencode(".jpg", cv2.cvtColor(model["preview"], cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 80])
637
+ with open(path, "wb") as fh: # open file handle: numpy keeps the name (no '.npz' appended)
638
+ np.savez_compressed(fh, meta=np.array(json.dumps(model["meta"])), preview=np.frombuffer(jpg, np.uint8),
639
+ **{k: v for k, v in model.items() if isinstance(v, np.ndarray) and k != "preview"})
640
+
641
+
642
+ def load(path):
643
+ z = np.load(path, allow_pickle=False)
644
+ m = {k: z[k] for k in z.files if k not in ("meta", "preview")}
645
+ m["meta"] = json.loads(str(z["meta"]))
646
+ m["preview"] = cv2.cvtColor(cv2.imdecode(z["preview"], cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
647
+ return m
648
+
649
+
650
+ # ---------------------------------------------------------------- check
651
+ def check(model, s, small_parts=False):
652
+ """A run's state -> list of claims (kind, text, box, evidence), checked against the taught good runs."""
653
+ s = _apply_self_bg(model, s)
654
+ meta, zones = model["meta"], model["zones"].astype(bool)
655
+ E_bank = model["E_bank"].astype(np.float32)
656
+ obj_desc, obj_zone = model["obj_desc"].astype(np.float32), model["obj_zone"]
657
+ n_good, nz = meta["n_runs"], len(zones)
658
+ changed = _changed(s)
659
+ claims = []
660
+ ws = model["workspace"].astype(bool) if "workspace" in model else np.ones((G, G), bool)
661
+
662
+ zone_any = np.any(zones, axis=0) if nz else np.zeros((G, G), bool)
663
+ near_zone = cv2.dilate(zone_any.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
664
+ short = []
665
+ for z in range(nz):
666
+ info, zm = meta["zones"][z], zones[z]
667
+ vis = float(((s["valid_s"] & s["valid_e"]) & zm).sum()) / max(int(zm.sum()), 1)
668
+ if vis < ZONE_VIS_MIN:
669
+ continue # arm occludes this region; cannot reliably claim incomplete
670
+ fill, lo = int((changed & zm).sum()), min(info["fills"])
671
+ if fill < SHORT_FRAC * lo:
672
+ short.append(f"region {info['id']} ({info['where']})")
673
+ claims.append(dict(kind="INCOMPLETE", box=info["box"], score=round(fill / max(lo, 1), 3), since="end",
674
+ zone_idx=z, fill=fill, lo=lo, hi=max(info["fills"]),
675
+ text=f"region {info['id']} ({info['where']}) changed much less than in good runs",
676
+ evidence=f"{fill} changed cells; good runs {lo}-{max(info['fills'])}"))
677
+
678
+ # End state vs good runs' end states; and, at the same spots, this run's START vs good runs' end states:
679
+ # occupied at the start AND at the end = the things there were never put away.
680
+ # Only compare cells actually observed unoccluded in at least half of the taught good runs (never flag
681
+ # cells permanently occluded by a parked robot arm in the teach bank as "differing from all good runs").
682
+ bank_seen = model["Ve_bank"].astype(np.float32).mean(0) >= 0.5
683
+ ve_cmp = s["valid_e"] & bank_seen
684
+ vs_cmp = s["valid_s"] & bank_seen
685
+ raw = np.where(ve_cmp, 1.0 - window_max_sim(s["E"], E_bank, model["Ve_bank"]), 0.0)
686
+ raw0 = np.where(vs_cmp, 1.0 - window_max_sim(s["S"], E_bank, model["Ve_bank"]), 0.0)
687
+ d = np.where(ve_cmp, _box3_smooth(raw, ve_cmp)[0], 0.0)
688
+ d0 = np.where(vs_cmp, _box3_smooth(raw0, vs_cmp)[0], 0.0)
689
+ # Second channel: depth, with its own leave-one-out bar. A spot is judged by the stronger channel relative to its
690
+ # bar: 1.0 = as far as the worst held-out good run went, in look or in depth.
691
+ use_depth = DEPTH and "depth_thr" in model and "D_e" in s
692
+ ratio, ratio0 = d / model["left_thr"], d0 / model["left_thr"]
693
+ if use_depth:
694
+ Db, Vb = list(model["D_bank"]), list(model["Ve_bank"])
695
+ dd = np.where(ve_cmp, _box3_smooth(window_min_absdiff(s["D_e"], Db, Vb), ve_cmp)[0], 0.0)
696
+ dd0 = np.where(vs_cmp, _box3_smooth(window_min_absdiff(s["D_s"], Db, Vb), vs_cmp)[0], 0.0)
697
+ ratio, ratio0 = np.maximum(ratio, dd / model["depth_thr"]), np.maximum(ratio0, dd0 / model["depth_thr"])
698
+
699
+ def ev(comp):
700
+ e = f"look {float(d[comp].max()):.2f} vs at most {float(model['left_thr'][comp].min()):.2f}"
701
+ if use_depth:
702
+ e += f", depth {float(dd[comp].max()):.2f} vs at most {float(model['depth_thr'][comp].min()):.2f}"
703
+ return e + f" in {n_good} good runs (leave-one-out)"
704
+ ones = np.ones((G, G), np.float32)
705
+ local_flat_bg = _local_flat_bg(model, s, rc=changed)
706
+ found = []
707
+ for c in _components((ratio > 1.0) & ve_cmp & ~near_zone & ws):
708
+ # Suppress purely flat featureless shadow gradients whose cells all match this frame's own bare background
709
+ if local_flat_bg is not None and bool(local_flat_bg[c].all()):
710
+ continue
711
+ found.append((c, ratio, ratio0, ones, vs_cmp, s["end_img"], ev(c)))
712
+ taken = np.zeros((G, G), bool)
713
+ for c, *_ in found:
714
+ taken |= cv2.dilate(c.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0
715
+ if small_parts and "left_thr_fine" in model and "E_fine" in s: # opt-in: small things, full-resolution grid
716
+ g2 = s["E_fine"].shape[0]
717
+ up = lambda m: cv2.resize(m.astype(np.uint8), (g2, g2), interpolation=cv2.INTER_NEAREST) > 0
718
+ Ebf, Vbf, wf = model["E_fine_bank"].astype(np.float32), model["Ve_fine_bank"], WIN * g2 // G
719
+ vef_cmp = s["valid_e_fine"] & (Vbf.astype(np.float32).mean(0) >= 0.5)
720
+ vsf_cmp = s["valid_s_fine"] & (Vbf.astype(np.float32).mean(0) >= 0.5)
721
+ rawf = np.where(vef_cmp, 1.0 - window_max_sim(s["E_fine"], Ebf, Vbf, win=wf), 0.0)
722
+ raw0f = np.where(vsf_cmp, 1.0 - window_max_sim(s["S_fine"], Ebf, Vbf, win=wf), 0.0)
723
+ found += [(c, rawf, raw0f, model["left_thr_fine"], vsf_cmp, s["end_img_fine"],
724
+ f"look {float(rawf[c].max()):.2f} vs at most {float(model['left_thr_fine'][c].min()):.2f} in {n_good} "
725
+ f"good runs (leave-one-out, full-resolution grid)") for c in _components(
726
+ (rawf > model["left_thr_fine"]) & vef_cmp & up(~near_zone) & ~up(taken) & up(ws), min_cells=SMALL_CELLS)]
727
+ elif small_parts and "left_thr_raw" in model: # older files: coarse unsmoothed map, its own learnt bar
728
+ found += [(c, raw, raw0, model["left_thr_raw"], vs_cmp, s["end_img"],
729
+ f"look {float(raw[c].max()):.2f} vs at most {float(model['left_thr_raw'][c].min()):.2f} in {n_good} "
730
+ f"good runs (leave-one-out)") for c in _components(
731
+ (raw > model["left_thr_raw"]) & ve_cmp & ~near_zone & ~taken & ws, min_cells=SMALL_CELLS)]
732
+ for comp, dm, dm0, bar, vs, img, evid in found:
733
+ box, peak = _box(comp), float(dm[comp].max())
734
+ seen0 = comp & vs
735
+ from_start = bool(seen0.any()) and float(dm0[seen0].mean()) > float(bar[seen0].mean())
736
+ what = f"{colour(img, box)} area"
737
+ text = (f"{what} here ({where(box)}) at the end; already present at the start (unchanged)"
738
+ if from_start else f"{what} here ({where(box)}) at the end; changed or appeared during the run")
739
+ text += f"; differs from all {n_good} good runs at the end"
740
+ if short:
741
+ text += f", and {' and '.join(short)} changed much less than in good runs"
742
+ claims.append(dict(kind="UNEXPECTED", text=text, box=box, score=round(peak, 3),
743
+ since="start" if from_start else "end", evidence=evid))
744
+ claims.sort(key=lambda c: c["kind"] != "UNEXPECTED") # outside-region claims first, then task regions
745
+ if meta.get("wrong_thr") is not None:
746
+ w_thr = max(float(meta["wrong_thr"]), WRONG_MARGIN)
747
+ for z, comp, v in _objects(s, zones):
748
+ m, other = _margin(v, z, obj_desc, obj_zone)
749
+ if m > w_thr:
750
+ info, box = meta["zones"][z], _box(comp)
751
+ claims.append(dict(kind="WRONG TARGET", box=box, score=round(m, 3),
752
+ text=f"{colour(s['end_img'], box)} item in region {info['id']} ({info['where']}); "
753
+ f"it looks like what good runs leave in region {other + 1} ({meta['zones'][other]['where']})",
754
+ evidence=f"look-alike margin {m:+.2f} vs at most {w_thr - WRONG_MARGIN:+.2f} "
755
+ f"for any good-run item (leave-one-out over {meta['n_objects']} items)"))
756
+ if VANISH and meta.get("vanish_bar") is not None: # left its place, arrived nowhere (worse than any good run)
757
+ for comp, best in departures_and_matches(s, d, d0, model["left_thr"], ~near_zone & ws, np.ones((G, G), bool)):
758
+ if best < meta["vanish_bar"]:
759
+ box = _box(comp)
760
+ claims.append(dict(kind="VANISHED", box=box, score=round(best, 3),
761
+ text=f"{colour(s['start_img'], box)} object(s) left this place ({where(box)}) and "
762
+ f"are not visible anywhere at the end",
763
+ evidence=f"best look match with anything that arrived {best:.2f}; in the "
764
+ f"{n_good} good runs every thing that left matched at least "
765
+ f"{meta['vanish_bar']:.2f} ({meta['n_departures']} departures)"))
766
+ if ZONE_LOOK and nz and "zone_layouts" in model: # two-scale region layout (4x4 spatial + 1x1 content)
767
+ L = model["zone_layouts"].astype(np.float32)
768
+ L1 = model["zone_contents"].astype(np.float32) if "zone_contents" in model else None
769
+ c_bars = meta.get("zone_content_bar")
770
+ for z in range(nz):
771
+ dist = 1.0 - float(np.max(L[:, z] @ zone_layout(s["E"], s["valid_e"], zones[z], k=4)))
772
+ bar = max(float(meta["zone_look_bar"][z]), LAYOUT_FLOOR)
773
+ r4 = dist / bar
774
+ if L1 is not None and c_bars is not None and z < len(c_bars):
775
+ dist1 = 1.0 - float(np.max(L1[:, z] @ zone_layout(s["E"], s["valid_e"], zones[z], k=1)))
776
+ bar1 = max(float(c_bars[z]), CONTENT_FLOOR)
777
+ r1 = dist1 / bar1
778
+ fired = (r4 > LAYOUT_STRONG) or (r4 > 1.0 and r1 > 1.0) or (r1 > CONTENT_STRONG)
779
+ score = round(max(r4, r1), 3)
780
+ ev_str = (f"layout {dist:.3f} vs {bar:.3f} ({r4:.2f}x), "
781
+ f"content {dist1:.3f} vs {bar1:.3f} ({r1:.2f}x)")
782
+ else:
783
+ fired = r4 > 1.0
784
+ score = round(r4, 3)
785
+ ev_str = f"layout distance {dist:.3f} vs at most {bar:.3f} (worst held-out good run x 1.1)"
786
+ if fired:
787
+ info = meta["zones"][z]
788
+ claims.append(dict(kind="WRONG LAYOUT", box=info["box"], score=score,
789
+ text=f"region {info['id']} ({info['where']}): overall arrangement at the end is unlike every "
790
+ f"good run's",
791
+ evidence=ev_str))
792
+ if SPOTS and nz and "arr_bank" in model: # inside a zone, but not where the good runs put things
793
+ arrb, tk = model["arr_bank"].astype(bool), np.ones((2 * SPOT_TOL + 1, 2 * SPOT_TOL + 1), np.uint8)
794
+ mine = changed & zone_any
795
+ zone_of = lambda comp: meta["zones"][int(np.argmax([(comp & z).sum() for z in zones]))]
796
+ for comp in _components(mine & ~(cv2.dilate(arrb.any(0).astype(np.uint8), tk) > 0), meta["spot_novel_max"] + 1):
797
+ info, box = zone_of(comp), _box(comp)
798
+ claims.append(dict(kind="WRONG SPOT", box=box, score=int(comp.sum()),
799
+ text=f"{colour(s['end_img'], box)} area in region {info['id']} ({info['where']}), where "
800
+ f"({where(box)}) no good run changes",
801
+ evidence=f"{int(comp.sum())} cells used by none of the {n_good} good runs; a held-out good "
802
+ f"run had at most {meta['spot_novel_max']}"))
803
+ for comp in _components(arrb.all(0) & ~(cv2.dilate(mine.astype(np.uint8), tk) > 0), meta["spot_missing_max"] + 1):
804
+ info, box = zone_of(comp), _box(comp)
805
+ claims.append(dict(kind="SPOT EMPTY", box=box, score=int(comp.sum()),
806
+ text=f"region {info['id']} ({info['where']}): the spot every good run changes ({where(box)}) "
807
+ f"is unchanged in this run",
808
+ evidence=f"{int(comp.sum())} cells filled in all {n_good} good runs; a held-out good run "
809
+ f"missed at most {meta['spot_missing_max']}"))
810
+ if IN_ZONE and nz: # the region's end state itself (wrong pose, state, or shape), same bars
811
+ wrong = np.zeros((G, G), bool)
812
+ for c in claims:
813
+ if c["kind"] in ("WRONG TARGET", "WRONG SPOT"):
814
+ b = c["box"]
815
+ wrong[int(b[1] * G):int(np.ceil(b[3] * G)), int(b[0] * G):int(np.ceil(b[2] * G))] = True
816
+ for comp in _components((ratio > 1.0) & s["valid_e"] & near_zone & ws & ~wrong):
817
+ info, box = meta["zones"][int(np.argmax([(comp & z).sum() for z in zones]))], _box(comp)
818
+ claims.append(dict(kind="WRONG STATE", box=box, score=round(float(ratio[comp].max()), 3),
819
+ text=f"{colour(s['end_img'], box)} area in region {info['id']} ({info['where']}): "
820
+ f"the end here looks unlike every good run's end", evidence=ev(comp)))
821
+ # If a region had low start->end change ONLY because it ALREADY started in the goal end state (and ends
822
+ # matching the good runs, with no WRONG STATE / WRONG LAYOUT / WRONG TARGET there), report amber ALREADY DONE.
823
+ if nz and "S_small" in model and any(c["kind"] == "INCOMPLETE" for c in claims):
824
+ Sb = list(model["S_small"].astype(np.float32))
825
+ d_to_sg = 1.0 - window_max_sim(_pool(s["S"]), Sb, [np.ones((G // 2, G // 2), bool)] * len(Sb), win=1)
826
+ reg_bad_kinds = ("WRONG STATE", "WRONG LAYOUT", "WRONG TARGET", "WRONG SPOT", "SPOT EMPTY")
827
+ for c in claims:
828
+ if c["kind"] != "INCOMPLETE" or "zone_idx" not in c:
829
+ continue
830
+ z = c["zone_idx"]
831
+ info, zm = meta["zones"][z], zones[z]
832
+ zb = info["box"]
833
+ end_bad = any(
834
+ x["kind"] in reg_bad_kinds and x.get("box") and _touch(x["box"], zb, m=0.0)
835
+ for x in claims
836
+ )
837
+ if end_bad:
838
+ continue
839
+ zm_v = zm & s["valid_s"]
840
+ zm16 = zm.reshape(G // 2, 2, G // 2, 2).any((1, 3))
841
+ if not zm_v.any() or not zm16.any():
842
+ continue
843
+ d_eg = float(raw0[zm_v].mean())
844
+ d_sg = float(d_to_sg[zm16].mean())
845
+ if d_eg + 0.08 < d_sg:
846
+ c.update(
847
+ kind="ALREADY DONE", type="difference", box=None,
848
+ text=f"region {info['id']} ({info['where']}) was already in the goal state at the start and matches good runs at the end",
849
+ evidence=f"{c['fill']} changed cells (good runs {c['lo']}-{c['hi']}); start matched taught end {d_eg:.2f} vs taught start {d_sg:.2f}",
850
+ )
851
+ for c in claims:
852
+ for k in ("zone_idx", "fill", "lo", "hi"):
853
+ c.pop(k, None)
854
+ return claims
855
+
856
+
857
+ # ---------------------------------------------------------------- pictures and report
858
+ def draw(img, items, zones=(), workspace=None):
859
+ out = cv2.cvtColor(img, cv2.COLOR_RGB2BGR).copy()
860
+ h, w = out.shape[:2]
861
+ if workspace is not None and not workspace.all(): # the taught workspace: nothing is reported outside it
862
+ m = cv2.resize(workspace.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST)
863
+ cs, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
864
+ cv2.drawContours(out, cs, -1, (255, 255, 255), 1)
865
+ for z in zones:
866
+ b = z["box"]
867
+ cv2.rectangle(out, (int(b[0] * w), int(b[1] * h)), (int(b[2] * w), int(b[3] * h)), (200, 160, 40), 1)
868
+ lbl = f"region {z['id']}"
869
+ (tw, th), _ = cv2.getTextSize(lbl, 0, 0.45, 1)
870
+ tx = max(2, min(int(b[0] * w) + 3, w - tw - 3))
871
+ ty = max(th + 2, min(int(b[1] * h) + 14, h - 4))
872
+ cv2.putText(out, lbl, (tx, ty), 0, 0.45, (200, 160, 40), 1)
873
+ col = {"UNEXPECTED": (40, 40, 230), "INCOMPLETE": (0, 165, 255), "WRONG TARGET": (200, 40, 200), "WRONG STATE": (178, 145, 8),
874
+ "WRONG SPOT": (237, 58, 124), "SPOT EMPTY": (7, 98, 161), "WRONG LAYOUT": (144, 116, 14), "VANISHED": (60, 18, 190)}
875
+ for i, it in enumerate(items, 1):
876
+ b = it.get("box")
877
+ if not b or it.get("kind") == "WRONG LAYOUT": # timing items & whole-region layout claims: no box
878
+ continue
879
+ cv2.rectangle(out, (int(b[0] * w), int(b[1] * h)), (int(b[2] * w), int(b[3] * h)), col.get(it["kind"], (0, 0, 255)), 2)
880
+ num = str(i)
881
+ (nw, nh), _ = cv2.getTextSize(num, 0, 0.6, 2)
882
+ nx = max(2, min(int(b[0] * w) + 3, w - nw - 3))
883
+ ny = max(nh + 2, min(int(b[3] * h) - 4, h - 4))
884
+ cv2.putText(out, num, (nx, ny), 0, 0.6, col.get(it["kind"], (0, 0, 255)), 2)
885
+ return out
886
+
887
+
888
+ def settled_at(frames, box, tail=5, floor=8.0):
889
+ """First frame from which the box region looks like its final state and stays that way (pixel distance to the
890
+ mean of the last `tail` frames, lightly smoothed). Anything passing over it (the arm) pushes this LATER, never
891
+ earlier, so a box is never shown before what it marks is true."""
892
+ h, w = frames.shape[1:3]
893
+ x0, y0 = int(box[0] * w), int(box[1] * h)
894
+ x1, y1 = max(x0 + 2, int(box[2] * w)), max(y0 + 2, int(box[3] * h))
895
+ crops = np.stack([cv2.resize(f[y0:y1, x0:x1], (24, 24), interpolation=cv2.INTER_AREA) for f in frames]).astype(np.float32)
896
+ end = crops[-tail:].mean(0)
897
+ dist = np.abs(crops - end).mean((1, 2, 3))
898
+ dist = np.convolve(dist, np.ones(3) / 3, mode="same")
899
+ thr = max(floor, 3.0 * float(np.median(dist[-tail:])))
900
+ away = np.nonzero(dist[:-tail] > thr)[0]
901
+ return int(away[-1] + 1) if len(away) else 0
902
+
903
+
904
+ def teach_timing(runs, fps, cam, prof_path):
905
+ """How long every part of the task normally takes (calibrate) and what normally varies mid-run (profile), learnt
906
+ from the good runs against the first one (leave-one-out bars), plus each good run's active time in seconds."""
907
+ from . import profile
908
+ from .core import calibrate, compare, fingerprints
909
+ A = fingerprints(load_run(runs[0], fps=fps, cam=cam))
910
+ active = []
911
+
912
+ def goods():
913
+ for g in runs[1:]:
914
+ Gf = fingerprints(load_run(g, fps=fps, cam=cam))
915
+ r = compare(A, Gf, fps=fps, spatial=False)
916
+ if not active:
917
+ active.append((r["trim_a"][1] - r["trim_a"][0]) / fps) # the reference run itself
918
+ active.append((r["trim_b"][1] - r["trim_b"][0]) / fps)
919
+ yield Gf
920
+
921
+ quiet = lambda *_a, **_k: None
922
+ prof, light = profile.build(A, goods(), fps=fps, log=quiet)
923
+ floor = calibrate(A, light, fps=fps, fp="global", log=quiet)
924
+ profile.save(prof, prof_path)
925
+ # Whole-run time bars, leave-one-out: how far a good run can fall outside the others' range.
926
+ act = np.array(active, float)
927
+ over = max(0.0, max(act[r] - np.delete(act, r).max() for r in range(len(act))))
928
+ under = max(0.0, max(np.delete(act, r).min() - act[r] for r in range(len(act))))
929
+ floor.update(ref=str(runs[0]), cam=cam, profile=Path(prof_path).name, active=[round(a, 2) for a in active],
930
+ slow_bar=round(float(act.max() + over), 2), fast_bar=round(float(act.min() - under), 2))
931
+ return json.loads(json.dumps(floor, default=lambda o: o.tolist() if hasattr(o, "tolist") else float(o)))
932
+
933
+
934
+ def in_workspace(model, box):
935
+ """At least half of the box lies in the taught workspace (always true for files taught without one)."""
936
+ if "workspace" not in model:
937
+ return True
938
+ ws = model["workspace"].astype(bool)
939
+ y0, y1 = int(box[1] * G), max(int(box[1] * G) + 1, int(np.ceil(box[3] * G)))
940
+ x0, x1 = int(box[0] * G), max(int(box[0] * G) + 1, int(np.ceil(box[2] * G)))
941
+ return float(ws[y0:y1, x0:x1].mean()) >= 0.5
942
+
943
+
944
+ def _touch(b1, b2, m=1 / 16):
945
+ """Two boxes overlap or touch (one 16x16 cell of slack)."""
946
+ return not (b1[2] + m < b2[0] or b2[2] + m < b1[0] or b1[3] + m < b2[1] or b2[3] + m < b1[1])
947
+
948
+
949
+ # A failure is a wrong end state; everything else (timing, a mid-run moment) is a difference from the good runs.
950
+ END_KINDS = ("UNEXPECTED", "INCOMPLETE", "WRONG TARGET", "WRONG STATE", "WRONG SPOT", "SPOT EMPTY", "WRONG LAYOUT", "VANISHED",
951
+ "NOT MOVED", "NOT PLACED", "DROPPED", "STILL HELD", "WRONG POSE", "EXTRA") # the last six: --objects
952
+ OBJECTS_HELP = ("also follow every object the robot moves with SAM 2.1 (NOT MOVED, NOT PLACED, WRONG TARGET, DROPPED, "
953
+ "STILL HELD, WRONG POSE, EXTRA); about 40 s per run on a cloud GPU, minutes on a laptop")
954
+
955
+
956
+ def lasting(changed, box, win=WIN):
957
+ """Something stays different at this spot (+-win cells) between the start and the end picture. Dropped or moved
958
+ things do; reflections, shadows and arm edges seen mid-run do not."""
959
+ g = changed.shape[0]
960
+ r0, r1 = max(0, int(box[1] * g) - win), min(g, int(np.ceil(box[3] * g)) + win)
961
+ c0, c1 = max(0, int(box[0] * g) - win), min(g, int(np.ceil(box[2] * g)) + win)
962
+ return bool(changed[r0:r1, c0:c1].any())
963
+
964
+
965
+ def group_unusual(items):
966
+ """Mid-run UNUSUAL moments at the same spot -> one item per spot: from its first to its last moment, at its
967
+ strongest level, over the union of their boxes. Many short blips at one place become one clear item."""
968
+ groups = []
969
+ for it in sorted(items, key=lambda x: x["b"][0]):
970
+ g = next((g for g in groups if _touch(it["box"], g[0]["box"])), None) # same spot as the first: no chaining
971
+ if g is None:
972
+ groups.append([it])
973
+ else:
974
+ g.append(it)
975
+ out = []
976
+ for g in groups:
977
+ top = max(g, key=lambda x: x["score"])
978
+ spans = [] # the separate moments, in time order
979
+ for x in sorted(g, key=lambda x: x["b"][0]):
980
+ if spans and x["b"][0] <= spans[-1][1] + 1:
981
+ spans[-1][1] = max(spans[-1][1], x["b"][1])
982
+ else:
983
+ spans.append([x["b"][0], x["b"][1]])
984
+ out.append(dict(top, a=[min(x["a"][0] for x in g), max(x["a"][1] for x in g)], spans=spans,
985
+ b=[min(x["b"][0] for x in g), max(x["b"][1] for x in g)],
986
+ step=min(x["step"] for x in g), end_step=max(x["end_step"] for x in g),
987
+ box=[min(x["box"][0] for x in g), min(x["box"][1] for x in g),
988
+ max(x["box"][2] for x in g), max(x["box"][3] for x in g)],
989
+ frames=sum(x["frames"] for x in g), moments=len(g)))
990
+ return sorted(out, key=lambda x: -x["score"])
991
+
992
+
993
+ def write_video_report(model, ref, run, fa, fb, claims, out, fps=10, res=None, floor_items=None, ref_note=None):
994
+ """The usual side-by-side video report of A and B in sync. Each claim is drawn on B from the moment its spot
995
+ reached its final state (`settled_at`) to the end; a zone that received too little is drawn on the last two
996
+ seconds. `res` (A = the timing reference) and `floor_items` add the learnt timing and mid-run checks."""
997
+ if res is None:
998
+ from .core import compare
999
+ res = compare(fa, fb, fps=fps, spatial=False)
1000
+ res["items"] = [] # timing against one good run is not part of a check: only taught items are shown
1001
+ (sa, ea), (sb, eb) = res["trim_a"], res["trim_b"]
1002
+ na, nb, w = ea - sa, eb - sb, int(2 * fps)
1003
+ end_only = {"INCOMPLETE", "STILL HELD", "NOT MOVED"}
1004
+ settle_kinds = {"UNEXPECTED", "WRONG TARGET", "WRONG STATE", "WRONG SPOT",
1005
+ "NOT PLACED", "DROPPED", "WRONG POSE", "SLIGHT SHIFT", "POSE DIFF", "EXTRA"}
1006
+ items = []
1007
+ for c in claims:
1008
+ if c["kind"] not in R.COLORS:
1009
+ continue
1010
+ if c["kind"] in end_only:
1011
+ t0 = max(0, nb - 1 - w)
1012
+ elif c["kind"] == "ALREADY DONE":
1013
+ t0 = 0
1014
+ else:
1015
+ t_settle = min(nb - 1, settled_at(fb[sb:eb], c["box"])) if c.get("box") else 0
1016
+ if c.get("from_b") is not None:
1017
+ t_cand = int(np.clip(c["from_b"], 0, nb - 1))
1018
+ # Never draw an outcome box before the object/change has actually arrived & settled in `box`
1019
+ t0 = max(t_cand, t_settle) if c["kind"] in settle_kinds else t_cand
1020
+ else:
1021
+ t0 = t_settle
1022
+ frac = t0 / max(nb - 1, 1)
1023
+ when = "" if (c.get("from_b") is not None or c["kind"] == "ALREADY DONE") else f" (from B {(t0 + sb) / fps:.1f} s)"
1024
+ box = None if c["kind"] in ("WRONG LAYOUT", "ALREADY DONE") else c["box"]
1025
+ items.append(dict(kind=c["kind"], box=box, score=c.get("score", 0.0), info=False,
1026
+ detail=f"{c['text']}{when} [{c['evidence']}]", track=c.get("track"),
1027
+ track_f=c.get("track_f"), a=[int(frac * (na - 1)), na - 1], b=[t0, nb - 1]))
1028
+ res["spatial_items"] = list(res.get("spatial_items") or []) + items
1029
+ verdict = "FAIL" if any(c["kind"] in END_KINDS for c in claims) else "PASS"
1030
+ R.write_html(res, fa, fb, str(out), f"{ref} ({ref_note or 'taught good run that started most like B'})", run,
1031
+ floor_items=floor_items, gated=True, verdict=verdict,
1032
+ floor_note=f"checked against {model['meta']['n_runs']} taught good runs")
1033
+
1034
+
1035
+ def _slug(run):
1036
+ p, _, ep = str(run).partition("#")
1037
+ return "".join(ch if ch.isalnum() else "_" for ch in Path(p).stem + (f"_ep{ep}" if ep else ""))
1038
+
1039
+
1040
+ def _b64(bgr):
1041
+ ok, buf = cv2.imencode(".jpg", bgr, [cv2.IMWRITE_JPEG_QUALITY, 82])
1042
+ return base64.b64encode(buf).decode()
1043
+
1044
+
1045
+ def write_report(model, results, out):
1046
+ """One self-contained HTML page: what was taught, then every checked run with its claims and evidence."""
1047
+ import html as H
1048
+ meta = model["meta"]
1049
+ zl = "".join(f"<li>region {z['id']} ({z['where']}): receives things in {z['receives_in']}/{meta['n_runs']} good runs, "
1050
+ f"{min(z['fills'])}-{max(z['fills'])} changed cells</li>" for z in meta["zones"]) or (
1051
+ "<li>no fixed end-state region (normal when objects return to their start spot or end in varying places; "
1052
+ "check still watches for unexpected leftovers and timing shifts &mdash; add <code>--objects</code> to track moved items)</li>"
1053
+ )
1054
+ cards = []
1055
+ li = lambda c: f"<li><b>{H.escape(c['kind'])}</b> {H.escape(c['text'])}<br><span class=ev>{H.escape(c['evidence'])}</span></li>"
1056
+ has_obj_model = bool(meta.get("objects"))
1057
+ for r in results:
1058
+ fl = [c for c in r["claims"] if c.get("type", "failure") in ("failure", "error")] # end-state claims fail a run
1059
+ df = [c for c in r["claims"] if c.get("type", "failure") == "difference"]
1060
+ nt = r.get("notes") or []
1061
+ note_html = ""
1062
+ if not fl and nt:
1063
+ tip = " &mdash; open the video report to verify, or retry with <code>--objects</code> if something was missed." if not has_obj_model else " &mdash; open the video report to verify."
1064
+ note_html = f"<li class=ev>{len(nt)} mid-run moment(s) noted with no lasting grid change detected{tip}</li>"
1065
+ items = (("<li class=hd>Failed</li>" + "".join(map(li, fl)) if fl else "")
1066
+ + ("<li class=hd>Differs from the good runs</li>" + "".join(map(li, df)) if df else "")) \
1067
+ or "<li class=ok>matches the good runs: nothing to report</li>"
1068
+ items += note_html
1069
+ img = f"<img src='data:image/jpeg;base64,{_b64(draw(r['end_img'], fl, meta['zones'], model.get('workspace')))}'>" if r.get("end_img") is not None else ""
1070
+ state, tag = ("bad", f"FAIL ({len(fl)})") if fl else (("diff", f"PASS &middot; {len(df)} diff") if df else ("good", "PASS"))
1071
+ link = f" <a href='{H.escape(r['href'])}'>open video report &rarr;</a>" if r.get("href") else ""
1072
+ cards.append(f"<section class='card {state}'><h2>{H.escape(r['name'])} <span class=tag>{tag}</span>{link}</h2>"
1073
+ f"<div class=row>{img}<ul>{items}</ul></div></section>")
1074
+ page = f"""<!doctype html><html lang=en><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
1075
+ <title>rollout-diff check</title><style>
1076
+ :root{{--bg:#f5f6f8;--card:#fff;--ink:#17202a;--muted:#5c6773;--line:#d9dee4}}
1077
+ @media (prefers-color-scheme:dark){{:root{{--bg:#11151b;--card:#1a2029;--ink:#e6ebf0;--muted:#97a3b1;--line:#2c3644}}}}
1078
+ body{{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 system-ui,Segoe UI,sans-serif}}
1079
+ main{{max-width:1100px;margin:0 auto;padding:16px;display:grid;gap:12px}}
1080
+ .card{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px 16px}}
1081
+ .card.bad{{border-left:5px solid #dc2626}} .card.good{{border-left:5px solid #16a34a}} .card.diff{{border-left:5px solid #d97706}}
1082
+ .hd{{list-style:none;font-weight:600;margin:6px 0 0 -18px}}
1083
+ h1{{font-size:20px;margin:0}} h2{{font-size:15px;margin:0 0 8px;word-break:break-all}}
1084
+ .row{{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-start}} img{{width:min(440px,100%);border-radius:6px}}
1085
+ ul{{margin:0;padding-left:18px;flex:1;min-width:240px}} li{{margin:4px 0}} .ev{{color:var(--muted);font-size:12.5px}}
1086
+ .ok{{color:#16a34a;list-style:none}} .tag{{font-weight:400;color:var(--muted);font-size:12.5px}} .muted{{color:var(--muted)}}
1087
+ </style></head><body><main>
1088
+ <section class=card><h1>rollout-diff check</h1><div class=muted>{H.escape(meta.get('task') or '')}</div>
1089
+ <p>Taught from {meta['n_runs']} good runs. The white outline is the workspace (where the arm reaches or things change in good runs); nothing outside it is reported. Task regions found:</p><ul>{zl}</ul>
1090
+ {(f"<p>Normal active time {min(meta['timing']['active']):.1f}-{max(meta['timing']['active']):.1f} s; speed of every part "
1091
+ f"and mid-run look learnt against {H.escape(meta['timing']['ref'])}.</p>") if meta.get('timing') else
1092
+ "<p class=muted>Timing not learnt (needs 4+ good runs).</p>"}
1093
+ <p class=muted>Red = failed: the end state is unlike every good run's (UNEXPECTED: an area outside the task regions differs from
1094
+ every good run's end; INCOMPLETE: a task region changed much less from start to end; WRONG TARGET: an item in one task region
1095
+ looks like what good runs leave in another; WRONG STATE / WRONG LAYOUT: a task region's local state or overall arrangement differs
1096
+ from the good runs'). Amber = differs: slower or faster,
1097
+ or a mid-run moment unlike the good runs at a spot that changed for good. Mid-run moments with no strong lasting grid change
1098
+ (reflections, shadows, or subtle low-contrast objects) are only listed in the video report. Bars come from leave-one-out over the good runs.{"" if has_obj_model else " If an obvious failure was missed (such as a low-contrast or dropped object), re-run both <code>teach</code> and <code>check</code> with <code>--objects</code> (SAM 2.1 tracking) or try <code>--small-parts</code>."}</p></section>
1099
+ {''.join(cards)}
1100
+ </main></body></html>"""
1101
+ Path(out).write_text(page, encoding="utf-8")
1102
+
1103
+
1104
+ def expand_runs(specs, episodes=None):
1105
+ """Videos, folders of videos, LeRobot datasets (local or Hub) or 'dataset#ep' -> list of run specs."""
1106
+ from .batch import _is_lerobot_dataset, _lerobot_total_episodes, _list_videos, parse_episodes
1107
+ out = []
1108
+ for s in specs:
1109
+ if "#" in str(s) or Path(str(s)).is_file():
1110
+ out.append(str(s))
1111
+ elif _is_lerobot_dataset(s):
1112
+ eps = parse_episodes(episodes, total=None if episodes else _lerobot_total_episodes(s), default_limit=5)
1113
+ out += [f"{s}#{e}" for e in eps]
1114
+ else:
1115
+ vids = _list_videos(s)
1116
+ if episodes:
1117
+ vids = [vids[i] for i in parse_episodes(episodes, total=len(vids)) if 0 <= i < len(vids)]
1118
+ out += [str(v) for v in vids]
1119
+ return out
1120
+
1121
+
1122
+ def _args(prog, extra):
1123
+ import argparse
1124
+ ap = argparse.ArgumentParser(prog=prog)
1125
+ ap.add_argument("--episodes", help="episodes / video indices to use, e.g. '0-4' (default: first 5 of a dataset)")
1126
+ ap.add_argument("--cam", default=None,
1127
+ help="camera name for LeRobot datasets (default: auto-pick a fixed camera and list available ones)")
1128
+ ap.add_argument("--fps", type=int, default=10)
1129
+ ap.add_argument("--mask-model", help="trained robot cut-out (separate package); default: Grounding DINO + SAM 2.1")
1130
+ extra(ap)
1131
+ return ap
1132
+
1133
+
1134
+ def _mask(args):
1135
+ if not args.mask_model:
1136
+ return None
1137
+ from .cli import _spot
1138
+ return _spot().mask_model(args.mask_model)
1139
+
1140
+
1141
+ def main_teach(argv):
1142
+ ap = _args("rollout-diff teach", lambda ap: (
1143
+ ap.add_argument("good", nargs="+", help="good runs: videos, a folder of videos, or a LeRobot dataset"),
1144
+ ap.add_argument("--out", required=True, help="taught model file, e.g. my_task.teach"),
1145
+ ap.add_argument("--objects", action="store_true", help=OBJECTS_HELP),
1146
+ ap.add_argument("--tracker", choices=("sam2", "sam3"), default="sam2",
1147
+ help="object segmenter/tracker for --objects (sam2 default, sam3 requires sam3 package + weights)")))
1148
+ args = ap.parse_args(argv)
1149
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True) # the model, its timing profile and report go here
1150
+ runs = expand_runs(args.good, args.episodes)
1151
+ if len(runs) < 2:
1152
+ raise SystemExit(f"teach needs at least 2 good runs (3-5 recommended), got {len(runs)}")
1153
+ mm = _mask(args)
1154
+ states, logs = [], []
1155
+ for i, r in enumerate(runs, 1):
1156
+ print(f"[{i}/{len(runs)}] {r}", flush=True)
1157
+ if args.objects:
1158
+ from . import objlog
1159
+ fr = load_run(r, fps=args.fps, cam=args.cam)
1160
+ states.append(run_state(fr, fps=args.fps, cam=args.cam, mask_model=mm, fine=True, spec=r))
1161
+ logs.append(objlog.run_log(fr, states[-1], states[-1]["arm_end"], args.fps, tracker=args.tracker))
1162
+ else:
1163
+ states.append(run_state(r, fps=args.fps, cam=args.cam, mask_model=mm, fine=True))
1164
+ model = teach(states, runs=runs, task=task_text(runs[0]))
1165
+ saved_cam = args.cam
1166
+ if saved_cam is None and "#" in runs[0]:
1167
+ from .hub import last_resolved_cam
1168
+ saved_cam = last_resolved_cam(runs[0].rsplit("#", 1)[0])
1169
+ model["meta"].update(fps=args.fps, cam=saved_cam)
1170
+ if args.objects:
1171
+ model["meta"]["tracker"] = args.tracker
1172
+ model["meta"]["objects"] = objlog.teach_objects(logs, zones=model["zones"])
1173
+ print("objects taught: " + ("; ".join(
1174
+ f"{p['colour']} from {where([*p['start'], *p['start']])} "
1175
+ + ("ends on what stood there at the start" if p["rel"] == "anchor" else
1176
+ f"ends at object {p['rel']}" if p["rel"] is not None else
1177
+ f"ends in region {p['zone_id'] + 1}" if p.get("zone_id") is not None else
1178
+ f"ends within {p['bar']:.2f} of good-run spots")
1179
+ for p in model["meta"]["objects"]["objects"]) or "none"), flush=True)
1180
+ if len(runs) >= 4: # timing needs a reference + 3 good runs
1181
+ print("learning the normal speed of every part of the task ...", flush=True)
1182
+ try:
1183
+ tm = teach_timing(runs, args.fps, args.cam, str(Path(args.out).with_suffix(".profile.npz")))
1184
+ model["meta"]["timing"] = tm
1185
+ print(f"normal active time {min(tm['active']):.1f}-{max(tm['active']):.1f} s (reference {runs[0]})")
1186
+ except Exception as exc:
1187
+ print(f"(timing not learnt: {exc})")
1188
+ else:
1189
+ print("(timing not learnt: needs at least 4 good runs)")
1190
+ save(model, args.out)
1191
+ rep = str(Path(args.out).with_suffix(".teach.html"))
1192
+ write_report(model, [dict(name=f"good run {i}: {r}", claims=[], end_img=s["end_img"])
1193
+ for i, (r, s) in enumerate(zip(runs, states), 1)], rep)
1194
+ prof_note = f"timing: {model['meta']['timing']['profile']} (keep alongside .teach); " if model["meta"].get("timing") else ""
1195
+ print(f"wrote {args.out} ({prof_note}teach report: {rep})")
1196
+ return 0
1197
+
1198
+
1199
+ def main_check(argv):
1200
+ ap = _args("rollout-diff check", lambda ap: (
1201
+ ap.add_argument("model", help="file written by 'rollout-diff teach'"),
1202
+ ap.add_argument("runs", nargs="+", help="runs to check: videos, a folder of videos, or a LeRobot dataset"),
1203
+ ap.add_argument("--out", default="check.html",
1204
+ help="HTML report: the video report for one run; a summary linking one video report per run for several"),
1205
+ ap.add_argument("--json", help="also write the claims as JSON"),
1206
+ ap.add_argument("--small-parts", action="store_true", help="also look for thin or small things (screws); noisier on cluttered scenes"),
1207
+ ap.add_argument("--objects", action="store_true", help=OBJECTS_HELP + " (the model must be taught with --objects)"),
1208
+ ap.add_argument("--tracker", choices=("sam2", "sam3"), default=None,
1209
+ help="object tracker override for --objects (defaults to the tracker used in teach)")))
1210
+ args = ap.parse_args(argv)
1211
+ for f in (args.out, args.json):
1212
+ if f:
1213
+ Path(f).parent.mkdir(parents=True, exist_ok=True)
1214
+ model = load(args.model)
1215
+ fps = model["meta"].get("fps", args.fps)
1216
+ cam = args.cam if args.cam is not None else model["meta"].get("cam")
1217
+ if args.objects and not model["meta"].get("objects"):
1218
+ print(f"note: --objects ignored because {args.model} was taught without --objects; "
1219
+ "re-run 'rollout-diff teach ... --objects' first to enable SAM 2.1 tracking.", flush=True)
1220
+ runs = expand_runs(args.runs, args.episodes)
1221
+ mm = _mask(args)
1222
+ out, single = Path(args.out), len(runs) == 1
1223
+ results, ref_frames = [], {}
1224
+ tm, tref = model["meta"].get("timing"), None
1225
+ if tm: # learnt timing + mid-run profile (see teach)
1226
+ from . import profile
1227
+ from .core import check_floor, compare, fingerprints
1228
+ try:
1229
+ fa_t = load_run(tm["ref"], fps=fps, cam=cam)
1230
+ pp = Path(args.model).with_name(tm["profile"])
1231
+ if not pp.exists():
1232
+ print(f"(note: timing profile {pp.name} not found next to {Path(args.model).name}; "
1233
+ "mid-run UNUSUAL checks disabled)", flush=True)
1234
+ tref = (fa_t, fingerprints(fa_t), profile.load(pp) if pp.exists() else None)
1235
+ except Exception as exc:
1236
+ print(f"(timing check off: timing reference {tm['ref']} could not be loaded: {exc})", flush=True)
1237
+ for i, r in enumerate(runs, 1):
1238
+ res = floor_items = obj_info = None
1239
+ notes = []
1240
+ try:
1241
+ fb = load_run(r, fps=fps, cam=cam)
1242
+ s = run_state(fb, fps=fps, cam=cam, mask_model=mm, fine=args.small_parts, spec=r)
1243
+ claims = check(model, s, small_parts=args.small_parts)
1244
+ info = ""
1245
+ if tref:
1246
+ fa_t, A_fp, prof = tref
1247
+ B_fp = fingerprints(fb)
1248
+ res = compare(A_fp, B_fp, fps=fps, fp="global", alike=tm.get("alike"), spatial=False)
1249
+ # res["items"] (MORE TIME / LESS TIME / SKIPPED / ENDS EARLY against the timing reference) stay in the
1250
+ # video report and are printed as information; only what is learnt from all good runs becomes a claim.
1251
+ act = (res["trim_b"][1] - res["trim_b"][0]) / fps
1252
+ lo, hi = min(tm["active"]), max(tm["active"])
1253
+ slow_bar, fast_bar = tm.get("slow_bar", hi), tm.get("fast_bar", lo)
1254
+ info = f"active {act:.1f} s (good runs {lo:.1f}-{hi:.1f} s)"
1255
+ # A part can only be "slow" when the whole run is slower than good runs allow; inside a normal-length
1256
+ # run a stretched part is a different order or the alignment, not slowness.
1257
+ floor_items = check_floor(res, tm) if act > slow_bar else []
1258
+ if act > slow_bar:
1259
+ claims.append(dict(kind="SLOWER", box=None, text=f"active {act:.1f} s: slower than every good run "
1260
+ f"({lo:.1f}-{hi:.1f} s)", evidence=f"bar {slow_bar:.1f} s, learnt leave-one-out"))
1261
+ elif act < fast_bar:
1262
+ claims.append(dict(kind="FASTER", box=None, text=f"active {act:.1f} s: faster than every good run "
1263
+ f"({lo:.1f}-{hi:.1f} s)", evidence=f"bar {fast_bar:.1f} s, learnt leave-one-out"))
1264
+ # Before B first looks like the reference as well as good runs do, its frames do not line up yet.
1265
+ ok = np.flatnonzero(np.array(res["cost"]) < tm.get("alike", np.inf))
1266
+ b_start = res["path"][ok[0]][1] if len(ok) else 0
1267
+ if b_start > 0:
1268
+ info += f"; B's first {b_start / fps:.1f} s do not line up with the reference (left out)"
1269
+ if prof is not None:
1270
+ res["spatial"] = profile.check(prof, A_fp, B_fp, res)
1271
+ sp = res["spatial"]["items"]
1272
+ unusual = group_unusual([x for x in sp if x["kind"] == "UNUSUAL" and x["b"][1] >= b_start
1273
+ and in_workspace(model, x["box"])])
1274
+ for c in claims: # an end-state claim takes the time its spot first looked unusual
1275
+ g = next((g for g in unusual if c["kind"] in ("UNEXPECTED", "WRONG TARGET", "WRONG STATE", "WRONG SPOT")
1276
+ and _touch(g["box"], c["box"])), None)
1277
+ if g:
1278
+ c["from_b"] = int(g["b"][0])
1279
+ c["text"] += f" (unusual here from B {(g['b'][0] + res['trim_b'][0]) / fps:.1f} s)"
1280
+ unusual.remove(g)
1281
+ sb = res["trim_b"][0]
1282
+ ch = _changed(s)
1283
+ for g in unusual: # name every separate moment, not one long misleading range
1284
+ t = lambda f: f"{(f + sb) / fps:.1f}"
1285
+ when = ", ".join(t(a) if a == b else f"{t(a)}-{t(b)}" for a, b in g["spans"])
1286
+ g["info"] = not lasting(ch, g["box"])
1287
+ g["detail"] = (f"unusual at B {when} s ({where(g['box'])}): up to {g['score']:.1f}x what "
1288
+ f"normal runs reach there" + ("; no lasting grid change detected afterwards" if g["info"] else ""))
1289
+ res["spatial_items"] = unusual + [x for x in sp if x["kind"] != "UNUSUAL"]
1290
+ shown, _ = R.summary(res, 1.0, floor_items)
1291
+ claims += [dict(kind=it["kind"], text=it["text"], box=it.get("box"), evidence="learnt from the good runs")
1292
+ for it in shown if it["kind"] in ("SLOW STEP", "UNUSUAL") and not it.get("info")]
1293
+ notes = [dict(kind=it["kind"], text=it["text"], box=it.get("box"), type="info", evidence="no lasting change")
1294
+ for it in shown if it["kind"] == "UNUSUAL" and it.get("info")]
1295
+ timing_info = [it for it in shown if it["kind"] in ("MORE TIME", "LESS TIME", "SKIPPED", "ENDS EARLY")]
1296
+ if args.objects and model["meta"].get("objects"): # what happened to every object (SAM 2.1 / SAM 3)
1297
+ from . import objlog
1298
+ trk = args.tracker or model["meta"].get("tracker", "sam2")
1299
+ zones = model["zones"].astype(bool)
1300
+ zone_fail_kinds = ("INCOMPLETE", "WRONG TARGET", "WRONG LAYOUT", "WRONG STATE", "WRONG SPOT", "SPOT EMPTY")
1301
+ zone_failed = {z for z in range(len(zones)) if any(
1302
+ c.get("box") and objlog._in_zone(c["box"], zones[z], dilate=1)
1303
+ for c in claims if c["kind"] in zone_fail_kinds
1304
+ )}
1305
+ log = objlog.run_log(fb, s, s["arm_end"], fps, tracker=trk)
1306
+ oc = objlog.check_objects(model["meta"]["objects"], log, zones=zones, zone_failed=zone_failed)
1307
+ obj_info = objlog.summary(log)
1308
+ for c in oc:
1309
+ if c.get("frame") is not None: # shown from that moment in the video report
1310
+ c["from_b"] = max(0, c["frame"] - (res["trim_b"][0] if res else 0))
1311
+ claims += oc
1312
+ for c in claims:
1313
+ c["type"] = "failure" if c["kind"] in END_KINDS else "difference"
1314
+ fails = [c for c in claims if c["type"] == "failure"]
1315
+ print(f"[{i}/{len(runs)}] {r}: " + (f"FAIL ({len(fails)})" if fails else "PASS")
1316
+ + (f", {len(claims) - len(fails)} difference(s)" if len(claims) > len(fails) else "")
1317
+ + (f" | {info}" if info else ""), flush=True)
1318
+ for c in sorted(claims, key=lambda c: c["type"] != "failure"):
1319
+ print(f" {c['kind']:10s} {c['text']} [{c['evidence']}]")
1320
+ for it in (notes if tref else []):
1321
+ print(f" info {it['kind']:10s} {it['text']}")
1322
+ for it in (timing_info if tref else []):
1323
+ print(f" info {it['kind']:10s} {it['text']} [against the timing reference, one good run]")
1324
+ except Exception as exc: # one bad video must not stop the batch
1325
+ results.append(dict(name=r, claims=[dict(kind="ERROR", type="error", text=str(exc), box=[0, 0, 0, 0],
1326
+ evidence="")], end_img=None))
1327
+ print(f"[{i}/{len(runs)}] {r}: ERROR {exc}", flush=True)
1328
+ continue
1329
+ href, ref = None, (tm["ref"] if tref else pick_ref(model, s))
1330
+ try: # the video report needs the good run's video
1331
+ vid = out if single else out.with_name(f"{out.stem}_{i:02d}_{_slug(r)}.html")
1332
+ end_claims = [c for c in claims if c["kind"] in END_KINDS or c["kind"] == "ALREADY DONE"]
1333
+ if tref:
1334
+ write_video_report(model, ref, r, tref[0], fb, end_claims, vid, fps=fps, res=res,
1335
+ floor_items=floor_items, ref_note=f"timing reference; {info}")
1336
+ else:
1337
+ if ref not in ref_frames:
1338
+ ref_frames = {ref: load_run(ref, fps=fps, cam=cam)} # keep one reference video in memory
1339
+ write_video_report(model, ref, r, ref_frames[ref], fb, end_claims, vid, fps=fps)
1340
+ href = vid.name
1341
+ except Exception as exc:
1342
+ print(f" (no video report: good run {ref} could not be loaded: {exc})", flush=True)
1343
+ results.append(dict(name=r, claims=claims, notes=notes, end_img=s["end_img"], href=href, objects=obj_info))
1344
+ if not single or not results[0].get("href"):
1345
+ write_report(model, results, out) # summary page (or the picture-only fallback)
1346
+ failed = lambda r: any(c.get("type") in ("failure", "error") for c in r["claims"])
1347
+ if args.json:
1348
+ Path(args.json).write_text(json.dumps([dict(run=r["name"], failed=failed(r), claims=r["claims"] + r.get("notes", []),
1349
+ **({"objects": r["objects"]} if r.get("objects") else {}))
1350
+ for r in results], indent=1), encoding="utf-8")
1351
+ n_bad = sum(1 for r in results if failed(r))
1352
+ n_diff = sum(1 for r in results if r["claims"] and not failed(r))
1353
+ n_ok = len(results) - n_bad - n_diff
1354
+ print(f"checked {len(results)} run(s): {n_ok} passed, {n_diff} passed with differences, {n_bad} failed - report {out}")
1355
+ obj_active = bool(args.objects and model["meta"].get("objects"))
1356
+ has_unusual_pass = any((not failed(r)) and r.get("notes") for r in results)
1357
+ if not obj_active and (has_unusual_pass or (not model["meta"].get("zones") and n_bad < len(results))):
1358
+ print("hint: some passing runs had transient mid-run differences (or the task has 0 fixed regions). "
1359
+ "If a real failure was missed (e.g. a dropped or low-contrast object), inspect the HTML report "
1360
+ "or re-run both 'teach' and 'check' with --objects (or try --small-parts).")
1361
+ return 1 if n_bad else 0
1362
+
1363
+
1364
+ def task_text(spec):
1365
+ """The LeRobot task sentence of a run, if its dataset has one (meta/tasks.jsonl or tasks.parquet)."""
1366
+ p = Path(str(spec).split("#")[0]).resolve()
1367
+ for root in [p] + list(p.parents)[:5]:
1368
+ f = root / "meta" / "tasks.jsonl"
1369
+ if f.exists():
1370
+ try:
1371
+ return json.loads(f.read_text(encoding="utf-8").splitlines()[0]).get("task", "")
1372
+ except (ValueError, IndexError):
1373
+ return ""
1374
+ return ""