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.
@@ -0,0 +1,312 @@
1
+ """Stage 1: robot masks and robot-free start / end plates per video."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from .config import HALO_FRAC, ROBOT_LEFT_CHECK, SCENE_PIECE_SAME
6
+ from .models import _gdino, _sam2
7
+
8
+
9
+ def _sample_indices(n):
10
+ """9 frames: 4 across opening 34% (for start_plate) + 5 across closing 28% (for end_plate)."""
11
+ if n <= 9:
12
+ return np.arange(n, dtype=int)
13
+ h1 = [0, max(1, int(0.08 * (n - 1))), max(1, int(0.20 * (n - 1))), max(1, int(0.34 * (n - 1)))]
14
+ h2 = [int(0.72 * (n - 1)), int(0.82 * (n - 1)), int(0.90 * (n - 1)),
15
+ max(0, n - 4), n - 1]
16
+ return np.array(sorted(set(h1 + h2)), dtype=int)
17
+
18
+
19
+ def _still_mask(frames, idx):
20
+ """Per sampled frame: (H, W) bool True where pixels are locally still (prevents motion-blur ghosts).
21
+
22
+ Smooth illumination shifts (moving cast shadows, auto-exposure steps) vary slowly in space without
23
+ changing local high-pass structure or chromaticity, so they stay marked still instead of punching
24
+ jagged splice holes across bare surfaces.
25
+ """
26
+ n, h, w = frames.shape[:3]
27
+ sigma = max(4.0, 0.024 * min(h, w))
28
+ out = []
29
+ for k in idx:
30
+ if n <= 1:
31
+ out.append(np.ones((h, w), dtype=bool))
32
+ continue
33
+ f = frames[k].astype(np.float32)
34
+ f_hp = f - cv2.GaussianBlur(f, (0, 0), sigmaX=sigma)
35
+ f_ab = cv2.cvtColor(frames[k], cv2.COLOR_RGB2LAB)[..., 1:].astype(np.float32)
36
+ d_raw = np.zeros((h, w), np.float32)
37
+ d_hp = np.zeros((h, w), np.float32)
38
+ d_ab = np.zeros((h, w), np.float32)
39
+ for nb in ([k - 1] if k > 0 else []) + ([k + 1] if k < n - 1 else []):
40
+ fn = frames[nb].astype(np.float32)
41
+ fn_hp = fn - cv2.GaussianBlur(fn, (0, 0), sigmaX=sigma)
42
+ fn_ab = cv2.cvtColor(frames[nb], cv2.COLOR_RGB2LAB)[..., 1:].astype(np.float32)
43
+ d_raw = np.maximum(d_raw, np.abs(f - fn).mean(-1))
44
+ d_hp = np.maximum(d_hp, np.abs(f_hp - fn_hp).mean(-1))
45
+ d_ab = np.maximum(d_ab, np.linalg.norm(f_ab - fn_ab, axis=-1))
46
+ d_raw = cv2.blur(d_raw, (7, 7))
47
+ d_hp = cv2.blur(d_hp, (7, 7))
48
+ d_ab = cv2.blur(d_ab, (7, 7))
49
+ moving = (d_raw >= 7.5) & ((d_hp >= 7.5) | (d_ab >= 7.5))
50
+ out.append(~moving)
51
+ return np.stack(out)
52
+
53
+
54
+ def _frame_motion_envelope(frames):
55
+ """Exposure-invariant per-pixel high-percentile frame-to-frame motion across the video."""
56
+ n = len(frames)
57
+ step = max(1, n // 35)
58
+ sub = frames[::step].astype(np.float32)
59
+ if len(sub) < 2:
60
+ return np.zeros(frames.shape[1:3], np.float32)
61
+ df = np.diff(sub, axis=0)
62
+ df -= np.median(df, axis=(1, 2), keepdims=True)
63
+ mag = np.abs(df).mean(-1)
64
+ return np.percentile(mag, 92, axis=0)
65
+
66
+
67
+ def _scene_like_frame0(m, img, f0, m0):
68
+ """True if SAM mask piece m mostly lies where frame 0 had no robot and still looks like frame 0 there: a static
69
+ thing SAM added to the robot (the tray holding the placed cube), not a robot part. Unmasking such pixels is
70
+ harmless (they look like the scene), while masking them hid the placed cube in the end plate."""
71
+ judge = m & ~m0
72
+ n = int(judge.sum())
73
+ if n < 50 or n < 0.5 * m.sum():
74
+ return False
75
+ same = np.abs(img.astype(np.int16) - f0)[judge].max(-1) < 18
76
+ return float(same.mean()) >= SCENE_PIECE_SAME
77
+
78
+
79
+ def _guard_robot_dropouts(masks, raw_masks, frames, idx):
80
+ """Guard against single-frame Grounding DINO dropouts WITHOUT throwing away frames where the robot
81
+ cleanly retracted off-screen (e.g. vifailback end frames with zero arm in view).
82
+ Marks a low-coverage frame `i` (`cov < 0.015`) as a dropout (`masks[i] = True`) ONLY if:
83
+ (a) it is sandwiched between two frames that both clearly contain the robot, OR
84
+ (b) inside the nearest robot frame's un-dilated core, frame `i` still looks like that robot
85
+ (mean |diff| < 20 after cancelling global exposure shift) — meaning the arm stayed on screen.
86
+ Off by default (ROBOT_LEFT_CHECK): the arm moves between sampled frames, so (b) often calls a missed arm
87
+ 'gone' and pastes it into the plate (tray good runs flagged 3 -> 6 of 8). The default is the plain rule: in a video
88
+ where the robot is usually seen, a frame with almost no robot is a detector dropout."""
89
+ masks = masks.copy()
90
+ covs = masks.reshape(len(masks), -1).mean(1)
91
+ if not ROBOT_LEFT_CHECK:
92
+ if covs.max() >= 0.05 and np.median(covs) >= 0.03:
93
+ masks[covs < 0.015] = True
94
+ return masks
95
+ good_idx = [j for j, c in enumerate(covs) if c >= 0.03]
96
+ if covs.max() >= 0.05 and len(good_idx) >= 2:
97
+ for i in range(len(masks)):
98
+ if covs[i] >= 0.015:
99
+ continue
100
+ if (0 < i < len(masks) - 1) and (covs[i - 1] >= 0.03) and (covs[i + 1] >= 0.03):
101
+ masks[i] = True
102
+ continue
103
+ j = min(good_idx, key=lambda g: abs(g - i))
104
+ core = raw_masks[j] if raw_masks[j].any() else masks[j]
105
+ if not core.any():
106
+ continue
107
+ fi = frames[idx[i]].astype(np.float32)
108
+ fj = frames[idx[j]].astype(np.float32)
109
+ d_glob = np.median(fi - fj, axis=(0, 1))
110
+ if float(np.abs((fi - d_glob) - fj)[core].mean()) < 20.0:
111
+ masks[i] = True
112
+ return masks
113
+
114
+
115
+ def _detect_robot_masks(frames, idx, run_motion):
116
+ """Per sampled frame: (H, W) bool mask of the robot arm (GroundingDINO + SAM 2.1 + adaptive filter)."""
117
+ import torch
118
+ gd_proc, gd_mod = _gdino()
119
+ s2_proc, s2_mod = _sam2()
120
+ h, w = frames.shape[1:3]
121
+ hw = float(h * w)
122
+ prompt = "robot arm. robotic gripper."
123
+ # Balance dilation (~4.4% of min-dim) to absorb gripper contours/shadows on dark & bimanual arms
124
+ # while still keeping placed objects visible (and `_achieved_in_raw_end` rescues parked-gripper placements).
125
+ k_dil = max(7, int(round(min(h, w) * 0.044)) | 1)
126
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_dil, k_dil))
127
+ use_amp = gd_mod.device.type == "cuda"
128
+
129
+ # Pass 1: collect candidate boxes across all sampled frames and calibrate adaptive confidence threshold
130
+ frame_cands = []
131
+ all_top_scores = []
132
+ for k in idx:
133
+ img = frames[k]
134
+ inp = gd_proc(images=[img], text=[prompt], return_tensors="pt",
135
+ size={"shortest_edge": 384, "longest_edge": 560}).to(gd_mod.device)
136
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
137
+ out_gd = gd_mod(**inp)
138
+ res = gd_proc.post_process_grounded_object_detection(
139
+ out_gd, inp.input_ids, threshold=0.18, text_threshold=0.18, target_sizes=[(h, w)]
140
+ )[0]
141
+ raw_boxes = res["boxes"].cpu().numpy()
142
+ raw_scores = res["scores"].cpu().numpy()
143
+ cands = []
144
+ for b, sc in sorted(zip(raw_boxes, raw_scores), key=lambda x: -x[1]):
145
+ x0, y0, x1, y1 = [int(np.clip(round(v), 0, lim)) for v, lim in zip(b, (w, h, w, h))]
146
+ if x1 <= x0 or y1 <= y0:
147
+ continue
148
+ area_frac = ((x1 - x0) * (y1 - y0)) / hw
149
+ if area_frac < 0.012 or area_frac > 0.60:
150
+ continue
151
+ # Require genuine arm motion across the box (rejects static baskets/bins brushed by arm)
152
+ mot_p85 = float(np.percentile(run_motion[y0:y1, x0:x1], 85))
153
+ mot_mean = float(run_motion[y0:y1, x0:x1].mean())
154
+ if mot_p85 < 5.0 or mot_mean < 3.5:
155
+ continue
156
+ cands.append((float(sc), [float(x0), float(y0), float(x1), float(y1)]))
157
+ if cands:
158
+ all_top_scores.append(cands[0][0])
159
+ frame_cands.append(cands)
160
+
161
+ # Adaptive per-video threshold: high when robot is visually obvious (rejects pitchers/props),
162
+ # gentler on dark/3D-printed arms so grippers are never missed.
163
+ ref_sc = float(np.percentile(all_top_scores, 85)) if all_top_scores else 0.35
164
+ score_thr = max(0.21, min(0.36, 0.58 * ref_sc))
165
+
166
+ masks, raw_masks = [], []
167
+ f0, m0 = frames[idx[0]].astype(np.int16), None # frame 0 and its robot mask judge later pieces
168
+ for k, cands in zip(idx, frame_cands):
169
+ img = frames[k]
170
+ kept = [bx for sc, bx in cands if sc >= score_thr][:4]
171
+ rmask = np.zeros((h, w), dtype=bool)
172
+ if kept:
173
+ sinp = s2_proc(images=img, input_boxes=[kept], return_tensors="pt").to(s2_mod.device)
174
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
175
+ sout = s2_mod(**sinp, multimask_output=True)
176
+ pm = s2_proc.post_process_masks(sout.pred_masks.float().cpu(), sinp["original_sizes"])[0]
177
+ ious = sout.iou_scores.float().cpu()[0]
178
+ for bi in range(pm.shape[0]):
179
+ bx = kept[bi]
180
+ b_area = max(1.0, (bx[2] - bx[0]) * (bx[3] - bx[1]))
181
+ # Union all valid high-IoU SAM2 masks (captures whole articulated arm + gripper + base,
182
+ # not just one sub-link that leaves arm slivers in the plate).
183
+ got_any = False
184
+ for mi in np.argsort(-ious[bi].numpy()):
185
+ m = pm[bi, mi].numpy() > 0
186
+ if m0 is not None and _scene_like_frame0(m, img, f0, m0):
187
+ continue
188
+ m_area = float(m.sum())
189
+ if m_area <= 0.48 * hw and m_area <= 1.25 * b_area:
190
+ if float(ious[bi, mi]) >= 0.65 or not got_any:
191
+ rmask |= m
192
+ got_any = True
193
+
194
+ raw_masks.append(rmask)
195
+ rmask_dil = cv2.dilate(rmask.astype(np.uint8), kern, iterations=1) > 0
196
+ masks.append(rmask_dil)
197
+ if m0 is None and k == idx[0] and kept: # only a real frame-0 detection may judge later pieces:
198
+ m0 = rmask_dil # if frame 0 missed the robot, it looks like 'scene'
199
+
200
+ return _guard_robot_dropouts(np.stack(masks), np.stack(raw_masks), frames, idx)
201
+
202
+
203
+ def _normalize_lab_white_balance(start_img, end_img, valid_mask):
204
+ """Align global Lab (L, a*, b*) offset of end_img to start_img over the quietest 50% of valid pixels.
205
+ Cancels camera auto-exposure & auto-white-balance tint shifts (e.g. green->pink) without distorting objects."""
206
+ if valid_mask.sum() < 200:
207
+ return end_img
208
+ ls = cv2.cvtColor(start_img, cv2.COLOR_RGB2LAB).astype(np.float32)
209
+ le = cv2.cvtColor(end_img, cv2.COLOR_RGB2LAB).astype(np.float32)
210
+ diff = np.linalg.norm(ls - le, axis=-1)
211
+ thr = float(np.percentile(diff[valid_mask], 55))
212
+ quiet = valid_mask & (diff <= max(thr, 3.0))
213
+ if quiet.sum() < 100:
214
+ quiet = valid_mask
215
+ # Additive median shift in perceptual Lab space (handles both brightness and WB tint cleanly)
216
+ dL = float(np.clip(np.median(ls[..., 0][quiet] - le[..., 0][quiet]), -18.0, 18.0))
217
+ da = float(np.clip(np.median(ls[..., 1][quiet] - le[..., 1][quiet]), -10.0, 10.0))
218
+ db = float(np.clip(np.median(ls[..., 2][quiet] - le[..., 2][quiet]), -10.0, 10.0))
219
+ if abs(dL) < 1.5 and abs(da) < 1.0 and abs(db) < 1.0:
220
+ return end_img
221
+ le[..., 0] = np.clip(le[..., 0] + dL, 0, 255)
222
+ le[..., 1] = np.clip(le[..., 1] + da, 0, 255)
223
+ le[..., 2] = np.clip(le[..., 2] + db, 0, 255)
224
+ return cv2.cvtColor(le.astype(np.uint8), cv2.COLOR_LAB2RGB)
225
+
226
+
227
+ def build_plates(frames, use_robot_mask=True, mask_model=None):
228
+ """Build clean per-pixel uncovered start_plate and end_plate (K=1 earliest/latest clean pixel).
229
+ When `mask_model` is provided (a trained robot cut-out model), Grounding DINO + SAM 2.1 are skipped."""
230
+ n, h, w = frames.shape[:3]
231
+ idx = _sample_indices(n)
232
+ samp = frames[idx]
233
+ run_motion = _frame_motion_envelope(frames)
234
+ still = _still_mask(frames, idx)
235
+ if not use_robot_mask:
236
+ rmasks = np.zeros((len(idx), h, w), dtype=bool)
237
+ elif mask_model is not None:
238
+ raw = mask_model(frames, idx, run_motion)
239
+ dil_frac = float(getattr(mask_model, "dilate_frac", 0.065))
240
+ k_dil = max(7, int(round(min(h, w) * dil_frac)) | 1)
241
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_dil, k_dil))
242
+ rmasks = np.stack([cv2.dilate(m.astype(np.uint8), kern, iterations=1) > 0 for m in raw])
243
+ else:
244
+ rmasks = _detect_robot_masks(frames, idx, run_motion)
245
+
246
+ # Moving pixels right next to the robot are motion blur, shadow or cable: never fill a plate with them
247
+ k_halo = max(7, int(round(min(h, w) * HALO_FRAC)) | 1)
248
+ halo = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_halo, k_halo))
249
+ near = np.stack([cv2.dilate(m.astype(np.uint8), halo) > 0 for m in rmasks])
250
+
251
+ half = max(1, (n - 1) // 2)
252
+ s_pos = [i for i, k in enumerate(idx) if k <= half] or [0]
253
+ e_pos = [i for i, k in enumerate(idx) if k >= half] or [len(idx) - 1]
254
+
255
+ def _pick_first_clean(positions, from_end=False):
256
+ """Per pixel, pick the SINGLE earliest (start) or latest (end) still robot-free observation,
257
+ matching local border exposure when filling holes from another timestamp so auto-exposure
258
+ or shadow shifts never leave sharp cutout seams on bare surfaces."""
259
+ order = list(reversed(positions)) if from_end else list(positions)
260
+ plate = np.zeros((h, w, 3), np.uint8)
261
+ got = np.zeros((h, w), dtype=bool)
262
+ ring_k = np.ones((15, 15), np.uint8)
263
+ for strict in (True, False):
264
+ for p in order:
265
+ ok = (still[p] & ~rmasks[p] if strict else ~near[p]) & (~got)
266
+ if ok.any():
267
+ src = samp[p]
268
+ if got.any():
269
+ ring = (cv2.dilate(ok.astype(np.uint8), ring_k) > 0) & got & (~rmasks[p])
270
+ ref = ring if int(ring.sum()) >= 30 else (got & (~rmasks[p]))
271
+ if int(ref.sum()) >= 30:
272
+ shift = np.clip(
273
+ np.median(plate[ref].astype(np.float32) - src[ref].astype(np.float32), axis=0),
274
+ -35.0, 35.0,
275
+ )
276
+ if float(np.max(np.abs(shift))) >= 1.5:
277
+ src = np.clip(src.astype(np.float32) + shift, 0, 255).astype(np.uint8)
278
+ plate[ok] = src[ok]
279
+ got[ok] = True
280
+ if got.all():
281
+ break
282
+ return plate, got
283
+
284
+ start_plate, has_start = _pick_first_clean(s_pos, from_end=False)
285
+ end_plate, has_end = _pick_first_clean(e_pos, from_end=True)
286
+
287
+ # Permanent robot base/fixture (never uncovered in >=92% of sampled frames) is never comparable world,
288
+ # while pick/place zones cleanly uncovered at both start and end stay valid.
289
+ robot_cov = rmasks.mean(axis=0).astype(np.float32)
290
+ valid_world = has_start & has_end & (robot_cov < 0.92)
291
+ valid_world = cv2.erode(valid_world.astype(np.uint8), np.ones((3, 3), np.uint8), iterations=1) > 0
292
+
293
+ # Cancel global camera auto-exposure & auto-white-balance shifts between start and end
294
+ end_plate = _normalize_lab_white_balance(start_plate, end_plate, valid_world)
295
+
296
+ # Zero-cliff fill: non-valid pixels get identical RGB in start & end so DINOv2 sees zero fake edges
297
+ fallback = frames[0]
298
+ fill = np.where(has_start[..., None], start_plate, np.where(has_end[..., None], end_plate, fallback))
299
+ inv = ~valid_world
300
+ start_clean = start_plate.copy()
301
+ end_clean = end_plate.copy()
302
+ start_clean[inv] = fill[inv]
303
+ end_clean[inv] = fill[inv]
304
+
305
+ return dict(
306
+ start_plate=start_clean,
307
+ end_plate=end_clean,
308
+ valid_world=valid_world,
309
+ robot_cov=robot_cov,
310
+ raw_start=frames[0],
311
+ raw_end=frames[-1],
312
+ )
@@ -0,0 +1,301 @@
1
+ """SAM 2.1 object tracking, change onsets, and the adapter to rollout-diff's HTML report."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from .compare import compare_world
6
+ from .config import G, TRACK_MAX
7
+ from .models import _sam2_video
8
+
9
+
10
+ def track_object_sam2(frames, seed_box_norm, fps=10, step=2):
11
+ """Track an auto-discovered world object across `frames` using SAM 2.1 video propagation (Apache-2.0).
12
+
13
+ Args:
14
+ frames : (N, H, W, 3) uint8 RGB frames at `fps`
15
+ seed_box_norm : [x0, y0, x1, y1] normalized box at frame 0
16
+ step : temporal stride (step=2 tracks at 5 fps -> ~5 s per 10 s video on an 8 GB GPU)
17
+
18
+ Returns dict with per-frame (length N) masks on the G x G grid, normalized boxes, areas,
19
+ `lost` bool (True if object vanished permanently before the end), and `lost_frame` (last
20
+ frame where the object was solidly visible before disappearing, e.g. exact drop frame).
21
+ """
22
+ import torch
23
+ n, h, w = frames.shape[:3]
24
+ sub_idx = list(range(0, n, max(1, step)))
25
+ if sub_idx[-1] != n - 1:
26
+ sub_idx.append(n - 1)
27
+ sub_frames = [frames[k] for k in sub_idx]
28
+ x0, y0, x1, y1 = seed_box_norm
29
+ box_px = [float(x0 * w), float(y0 * h), float(x1 * w), float(y1 * h)]
30
+
31
+ vp, vm, dev, dtype = _sam2_video()
32
+ sess = vp.init_video_session(
33
+ video=sub_frames,
34
+ inference_device=dev,
35
+ processing_device="cpu",
36
+ video_storage_device="cpu",
37
+ dtype=dtype,
38
+ )
39
+ vp.add_inputs_to_inference_session(
40
+ inference_session=sess, frame_idx=0, obj_ids=[1], input_boxes=[[box_px]]
41
+ )
42
+
43
+ sub_areas = []
44
+ sub_boxes = []
45
+ sub_grid = []
46
+ with torch.no_grad():
47
+ vm(inference_session=sess, frame_idx=0)
48
+ for out in vm.propagate_in_video_iterator(sess):
49
+ pm = vp.post_process_masks([out.pred_masks], original_sizes=[[h, w]], binarize=False)[0][0, 0].float().cpu().numpy()
50
+ m = pm > 0.0
51
+ area = int(m.sum())
52
+ sub_areas.append(area)
53
+ if area > 0:
54
+ ys, xs = np.nonzero(m)
55
+ sub_boxes.append([round(float(xs.min()) / w, 4), round(float(ys.min()) / h, 4),
56
+ round(float(xs.max() + 1) / w, 4), round(float(ys.max() + 1) / h, 4)])
57
+ gm = cv2.resize(m.astype(np.float32), (G, G), interpolation=cv2.INTER_AREA)
58
+ sub_grid.append(np.clip(gm * 1.4, 0.0, 1.0))
59
+ else:
60
+ sub_boxes.append(None)
61
+ sub_grid.append(np.zeros((G, G), np.float32))
62
+
63
+ # Nearest-neighbor upsample tracked arrays back to all N frames
64
+ areas = np.zeros(n, np.int32)
65
+ boxes = [None] * n
66
+ grid_masks = np.zeros((n, G, G), np.float32)
67
+ sub_arr = np.array(sub_idx, dtype=int)
68
+ for k in range(n):
69
+ j = int(np.argmin(np.abs(sub_arr - k)))
70
+ areas[k] = sub_areas[j]
71
+ boxes[k] = sub_boxes[j]
72
+ grid_masks[k] = sub_grid[j]
73
+
74
+ init_area = max(1, int(np.median(sub_areas[:max(1, min(3, len(sub_areas)))])))
75
+ # Solidly visible = at least 22% of initial mask area (ignores tiny 5% tracking residue after drop)
76
+ solid = areas >= max(25, int(0.22 * init_area))
77
+ tail_n = max(2, fps // 2)
78
+ lost = bool(solid[:max(1, n // 3)].any() and not solid[-tail_n:].any())
79
+ solid_idx = np.flatnonzero(solid)
80
+ lost_frame = int(solid_idx[-1]) if (lost and len(solid_idx)) else None
81
+ lost_box = boxes[lost_frame] if (lost_frame is not None and boxes[lost_frame] is not None) else seed_box_norm
82
+ # First frame the tracked box centre is more than one object size away from where it started
83
+ sx, sy, size = (x0 + x1) / 2, (y0 + y1) / 2, max(x1 - x0, y1 - y0)
84
+ away = [k for k, b in enumerate(boxes) if b is not None and solid[k]
85
+ and np.hypot((b[0] + b[2]) / 2 - sx, (b[1] + b[3]) / 2 - sy) > size]
86
+ left_frame = away[0] if away else None
87
+
88
+ return dict(
89
+ areas=areas,
90
+ boxes=boxes,
91
+ grid_masks=grid_masks,
92
+ init_area=init_area,
93
+ lost=lost,
94
+ lost_frame=lost_frame,
95
+ lost_box=lost_box,
96
+ left_frame=left_frame,
97
+ )
98
+
99
+
100
+ def _region_onset(frames, start_plate, end_plate, mask_g):
101
+ """Find the frame index `t` in `frames` where `mask_g` (G x G bool) transitions persistently
102
+ from `start_plate` toward `end_plate` (e.g. exact second a spill appears or cube leaves)."""
103
+ if mask_g is None or not mask_g.any() or len(frames) < 2:
104
+ return max(0, len(frames) - 1)
105
+ h, w = frames.shape[1:3]
106
+ m_px = cv2.resize(mask_g.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) > 0
107
+ if not m_px.any():
108
+ return max(0, len(frames) - 1)
109
+ s0 = cv2.cvtColor(start_plate, cv2.COLOR_RGB2LAB).astype(np.float32)[m_px]
110
+ s1 = cv2.cvtColor(end_plate, cv2.COLOR_RGB2LAB).astype(np.float32)[m_px]
111
+ # Per frame, measure closeness to end_plate vs start_plate inside mask_g
112
+ progress = np.empty(len(frames), np.float32)
113
+ for k, fr in enumerate(frames):
114
+ fk = cv2.cvtColor(fr, cv2.COLOR_RGB2LAB).astype(np.float32)[m_px]
115
+ d0 = np.linalg.norm(fk - s0, axis=-1).mean()
116
+ d1 = np.linalg.norm(fk - s1, axis=-1).mean()
117
+ progress[k] = d0 / max(d0 + d1, 1e-4)
118
+ # Last frame before the region stays persistently closer to end_plate (>0.55) until the end
119
+ below = np.flatnonzero(progress < 0.52)
120
+ return int(min(len(frames) - 1, below[-1] + 1)) if len(below) else 0
121
+
122
+
123
+ def spot_world(fa, fb, res, use_robot_mask=True, goods=(), change_model=None, mask_model=None, match_model=None):
124
+ """Adapter from compare_world() to rollout-diff's HTML report `spatial` dictionary.
125
+
126
+ Fixes two critical UX pitfalls:
127
+ 1. When DTW `open_end` stops early (e.g. B ended early), appends a final outcome step
128
+ `(len_a_trimmed - 1, len_b_trimmed - 1)` so A's TRUE final state (e.g. cube in basket)
129
+ is always shown next to B's final state (empty basket) — never A frozen mid-run!
130
+ 2. Computes the exact onset frame of every EXTRA CHANGE / WRONG PLACE (and object-vanish
131
+ moment for MISSING OUTCOME) so the timeline & heatmap light up the exact second the
132
+ spill or drop happens, not just the last frame.
133
+ """
134
+ wres = compare_world(fa, fb, use_robot_mask=use_robot_mask, goods=goods,
135
+ change_model=change_model, mask_model=mask_model, match_model=match_model)
136
+ wa, wb = wres["world_a"], wres["world_b"]
137
+ fps = res.get("fps", 10)
138
+ sa, ea = res["trim_a"]
139
+ sb, eb = res["trim_b"]
140
+ len_a_tr, len_b_tr = max(1, ea - sa), max(1, eb - sb)
141
+
142
+ # Ensure the path reaches the true final frame of BOTH A and B so outcome comparisons
143
+ # always display A's actual end frame next to B's actual end frame.
144
+ path = res["path"]
145
+ if path and (path[-1][0] != len_a_tr - 1 or path[-1][1] != len_b_tr - 1):
146
+ path.append((len_a_tr - 1, len_b_tr - 1))
147
+ if "cost" in res and res["cost"]:
148
+ res["cost"].append(res["cost"][-1])
149
+
150
+ S = len(path)
151
+ last = max(0, S - 1)
152
+ ia_last, jb_last = path[last] if S else (0, 0)
153
+ jb_of_step = np.array([j + sb for _, j in path], dtype=int) if S else np.zeros(0, int)
154
+ step_for_b = lambda b_idx: int(np.argmin(np.abs(jb_of_step - b_idx))) if S else 0
155
+
156
+ curve = np.zeros(S, np.float32)
157
+ heat = np.zeros((S, G, G), np.uint8)
158
+ items = []
159
+
160
+ for f in wres["findings"]:
161
+ kind = f["kind"]
162
+ mask_b = f.get("mask_b")
163
+ mask_a = f.get("mask_a")
164
+ onset_step = last
165
+ detail = f.get("detail", "")
166
+
167
+ if kind == "SETUP DIFF":
168
+ onset_step = 0
169
+ elif not f.get("info") and kind in ("EXTRA CHANGE", "WRONG PLACE", "END DIFF") and mask_b is not None:
170
+ t_b = _region_onset(fb, wb["plates"]["start_plate"], wb["plates"]["end_plate"], mask_b)
171
+ onset_step = step_for_b(t_b)
172
+ detail = f"{detail} (starts around B {t_b / fps:.1f} s)"
173
+ h_src = np.maximum(wb["score_map"], wres["heat_end"]) if kind == "END DIFF" else wb["score_map"]
174
+ h_u8 = np.clip(np.where(mask_b, h_src, 0.0) * 255.0, 0, 255).astype(np.uint8)
175
+ for s_idx in range(onset_step, S):
176
+ heat[s_idx] = np.maximum(heat[s_idx], h_u8)
177
+ curve[s_idx] = max(curve[s_idx], float(min(1.0, f["score"])))
178
+ elif not f.get("info") and kind == "MISSING OUTCOME" and mask_a is not None:
179
+ # Show missing outcome clearly at the true end state (A end vs B end)
180
+ tail = min(S, max(2, fps // 2))
181
+ h_u8 = np.clip(np.where(mask_a, wa["score_map"], 0.0) * 255.0, 0, 255).astype(np.uint8)
182
+ for s_idx in range(max(0, S - tail), S):
183
+ heat[s_idx] = np.maximum(heat[s_idx], h_u8)
184
+ curve[s_idx] = max(curve[s_idx], float(min(1.0, f["score"])))
185
+
186
+ ia_on, jb_on = path[onset_step] if S else (0, 0)
187
+ end_st = 0 if kind == "SETUP DIFF" else last
188
+ ia_end, jb_end = path[end_st] if S else (0, 0)
189
+ items.append(dict(
190
+ kind=kind,
191
+ a=[int(ia_on), int(ia_end)],
192
+ b=[int(jb_on), int(jb_end)],
193
+ step=onset_step,
194
+ end_step=end_st,
195
+ peak_step=end_st,
196
+ score=round(float(f["score"]), 2),
197
+ thr=0.5,
198
+ box=f.get("box"),
199
+ box_a=f.get("box_a", f.get("box")),
200
+ frames=int(max(0, end_st - onset_step)),
201
+ info=bool(f.get("info", False)),
202
+ detail=detail,
203
+ ))
204
+
205
+ # SAM 2.1 follows every object that leaves its start spot in B (up to TRACK_MAX, largest first) and the object it
206
+ # is paired with in A. Lost in B is a real difference when A keeps it in view, or A loses it over 1 s later on the
207
+ # aligned timeline (dropped on the way vs put into the basket); an unpaired object counts only if B misses an outcome.
208
+ has_missing = any(it["kind"] == "MISSING OUTCOME" and not it["info"] for it in items)
209
+ if S and wb is not None:
210
+ events_a = wres.get("events_a", wa["events"])
211
+ pair_a = {j: i for i, j, _, _ in wres["matched"]}
212
+ sa_trim = res["trim_a"][0]
213
+ moved_b = [(j, e) for j, e in enumerate(wb["events"]) if e["role"] == "VANISHED"][:TRACK_MAX]
214
+ for j, vb in moved_b:
215
+ trk = track_object_sam2(fb, vb["box"], fps=fps, step=2)
216
+ t_left = trk["left_frame"] if trk["left_frame"] is not None else min(
217
+ _region_onset(fb, wb["plates"]["start_plate"], wb["plates"]["end_plate"], vb["mask"]),
218
+ trk["lost_frame"] if trk["lost_frame"] is not None else len(fb))
219
+ b_lost = bool(trk["lost"] and trk["lost_frame"] is not None)
220
+ ea = events_a[pair_a[j]] if j in pair_a else None
221
+ a_lost_at, a_text = None, "no matching object in A"
222
+ if ea is not None and ea["role"] == "VANISHED":
223
+ trk_a = track_object_sam2(fa, ea["box"], fps=fps, step=2)
224
+ t_left_a = trk_a["left_frame"] if trk_a["left_frame"] is not None else min(
225
+ _region_onset(fa, wa["plates"]["start_plate"], wa["plates"]["end_plate"], ea["mask"]),
226
+ trk_a["lost_frame"] if trk_a["lost_frame"] is not None else len(fa))
227
+ a_lost_at = trk_a["lost_frame"] if (trk_a["lost"] and trk_a["lost_frame"] is not None) else len(fa)
228
+ a_text = f"A: leaves its spot at {t_left_a / fps:.1f} s, " + (
229
+ f"lost from view at {a_lost_at / fps:.1f} s" if a_lost_at < len(fa) else "in view to the end")
230
+ if b_lost:
231
+ t_drop = trk["lost_frame"]
232
+ st_drop = step_for_b(t_drop)
233
+ a_at_drop = path[st_drop][0] + sa_trim # A's frame at the same point of the job
234
+ earlier = (a_lost_at - a_at_drop > fps) if a_lost_at is not None else has_missing
235
+ if b_lost and earlier:
236
+ st_start = max(0, st_drop - max(5, int(1.5 * fps)))
237
+ ia_s, jb_s = path[st_start]
238
+ ia_d, jb_d = path[st_drop]
239
+ items.append(dict(
240
+ kind="OBJECT LOST",
241
+ a=[int(ia_s), int(ia_d)],
242
+ b=[int(jb_s), int(jb_d)],
243
+ step=st_start,
244
+ end_step=st_drop,
245
+ peak_step=st_drop,
246
+ score=1.0,
247
+ thr=0.5,
248
+ box=trk["lost_box"],
249
+ box_a=ea["box"] if ea is not None else vb["box"],
250
+ frames=max(1, st_drop - st_start + 1),
251
+ info=False,
252
+ detail=f"B: leaves its spot at {t_left / fps:.1f} s, lost from view at {t_drop / fps:.1f} s "
253
+ f"(last seen here) | {a_text}",
254
+ track=trk["boxes"], left_frame=int(t_left), lost_frame=int(t_drop), # B frame -> box (or None)
255
+ ))
256
+ # Paint live tracked object heatmap leading right up to the drop frame
257
+ for s_idx in range(st_start, min(S, st_drop + 3)):
258
+ b_f = int(jb_of_step[s_idx])
259
+ if 0 <= b_f < len(trk["grid_masks"]):
260
+ h_t = np.clip(trk["grid_masks"][b_f] * 255.0, 0, 255).astype(np.uint8)
261
+ if h_t.max() > 0:
262
+ heat[s_idx] = np.maximum(heat[s_idx], h_t)
263
+ curve[s_idx] = max(curve[s_idx], 0.90 if s_idx >= st_drop - 2 else 0.55)
264
+ else:
265
+ st_left = step_for_b(t_left)
266
+ ia_d, jb_d = path[st_left]
267
+ items.append(dict(
268
+ kind="MID-RUN DIFF",
269
+ a=[int(ia_d), int(ia_d)],
270
+ b=[int(jb_d), int(jb_d)],
271
+ step=st_left,
272
+ end_step=min(last, st_left + max(1, fps // 2)),
273
+ peak_step=st_left,
274
+ score=round(float(vb["peak"]), 2),
275
+ thr=0.5,
276
+ box=vb["box"],
277
+ box_a=ea["box"] if ea is not None else vb["box"],
278
+ frames=max(1, fps // 2),
279
+ info=True,
280
+ detail=f"B: leaves its spot at {t_left / fps:.1f} s, " + (
281
+ f"lost from view at {trk['lost_frame'] / fps:.1f} s" if b_lost else "in view to the end")
282
+ + f" | {a_text}",
283
+ track=trk["boxes"], left_frame=int(t_left),
284
+ lost_frame=int(trk["lost_frame"]) if b_lost else len(fb) - 1,
285
+ ))
286
+
287
+ real = [it for it in items if not it["info"]]
288
+ # Put OBJECT LOST / EXTRA CHANGE first if present so key cards highlight the exact failure moment + outcome
289
+ peaks = []
290
+ for it in real[:3]:
291
+ peaks.append(dict(step=it["peak_step"], score=it["score"], label=it["kind"], box=it["box"]))
292
+ return dict(
293
+ curve=curve,
294
+ heat=heat,
295
+ end_score=round(float(wres["score"]), 3),
296
+ end_thr=0.5,
297
+ mid_thr=0.5,
298
+ setup_score=0.0,
299
+ items=items,
300
+ peaks=peaks,
301
+ )
@@ -0,0 +1,11 @@
1
+ """Compatibility shim: the world diff lives in rollout_diff/world/ (config, models, plates, changes, match,
2
+ compare, track). Everything is re-exported here so the CLI, spot.py, the benches and the tests keep working."""
3
+ from .world.changes import _cell_lab_and_edges, extract_world_changes # noqa: F401
4
+ from .world.compare import _camera_motion_score, _median_edge_kept, compare_world, moving_camera # noqa: F401
5
+ from .world.config import * # noqa: F401,F403
6
+ from .world.match import _achieved_in_raw_end, _novel_excess, _pair_cost, match_with_refs, match_world_changes # noqa: F401,E501
7
+ from .world.models import _dinov2_reg, _gdino, _sam2, _sam2_video, patch_tokens_reg # noqa: F401
8
+ from .world.plates import (_detect_robot_masks, _frame_motion_envelope, _guard_robot_dropouts, # noqa: F401
9
+ _normalize_lab_white_balance, _scene_like_frame0,
10
+ _sample_indices, _still_mask, build_plates)
11
+ from .world.track import _region_onset, spot_world, track_object_sam2 # noqa: F401