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,672 @@
1
+ """Object channel: fast 32x32 robot-free object-level diff
2
+ (DINOv2-reg + Lab + optional SAM 2.1 single-frame mask snapping, 100% Apache-2.0, ~0.25 s/pair).
3
+
4
+ Why 32x32 robot-free plates + single-frame object analysis beats blind 100-frame SAM 2.1 video tracking:
5
+ - 4x finer spatial resolution than 16x16 plain mode -> resolves small objects (screws, clear glass,
6
+ green PCB, open silver hatch, tiny cubes, 2nd moved-from spot) cleanly.
7
+ - Compares true robot-free start/end plates (earliest uncovered still pixel for start, latest uncovered
8
+ still pixel for end -> never blurs moving start objects and never suffers from DTW open-end truncation).
9
+ - Classifies each differing object into plain words without a VLM:
10
+ * "object moved from X to Y in B" (paired vanished + appeared appearance match)
11
+ * "object removed / missing in B"
12
+ * "object never moved in B (moved in A)"
13
+ * "object appeared / left in B"
14
+ * "object ended in a different pose/state in B"
15
+ - ~150x faster than multi-object SAM 2.1 video propagation (~0.25 s vs ~45 s per pair).
16
+ """
17
+ import cv2
18
+ import numpy as np
19
+
20
+ from .world.config import G
21
+ from .world.match import _box3_smooth, _tol_diff_map
22
+ from .world.models import patch_tokens_reg_layers
23
+ from .world.plates import _still_mask, build_plates
24
+ from .world.track import _region_onset
25
+
26
+ OBJ_LAYERS = (9, 11) # Dinomaly-style upper-middle + final DINOv2-reg blocks (1 forward pass)
27
+ OBJ_SEED_THR = 0.39 # 32x32 multi-layer DINOv2-reg peak threshold (after setup subtraction)
28
+ OBJ_SM_THR = 0.31 # 3x3 smoothed peak threshold (rejects 1-4 cell arm-halo specks)
29
+ OBJ_GROW_THR = 0.29 # connected component grow threshold on 32x32 grid
30
+ OBJ_MIN_CELLS = 6 # minimum 32x32 cells (~0.6% of frame); allows 3-5 cells if peak >= 0.62
31
+ OBJ_SMALL_PEAK = 0.62
32
+ OBJ_MOVE_SIM_THR = 0.52 # cosine similarity between a vanished-in-B and appeared-in-B object -> MOVED
33
+
34
+
35
+ def _upsample_rob(rob, h, w, thr=0.16, dil_frac=0.048):
36
+ kd = max(5, int(round(min(h, w) * dil_frac)) | 1)
37
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kd, kd))
38
+ out = np.empty((len(rob), h, w), dtype=bool)
39
+ for k, r in enumerate(rob):
40
+ m = cv2.resize(r.astype(np.float32), (w, h), interpolation=cv2.INTER_LINEAR) >= thr
41
+ out[k] = cv2.dilate(m.astype(np.uint8), kern) > 0
42
+ return out
43
+
44
+
45
+ def _inpaint_invalid(plate, valid):
46
+ """Smoothly fill never-uncovered robot pixels (`~valid`) so raw un-erased arm edges do not poison DINOv2 patches."""
47
+ if valid.all() or not valid.any():
48
+ return plate
49
+ inv = cv2.dilate((~valid).astype(np.uint8), np.ones((5, 5), np.uint8))
50
+ return cv2.inpaint(plate, inv, 7, cv2.INPAINT_TELEA)
51
+
52
+
53
+ def _attach_arm_cables(frames, idx_sub, ms, latest=True):
54
+ """Extend each keyframe robot mask `ms[i]` to thin moving robot cables/wires physically attached to the arm.
55
+
56
+ Only thin filaments (vanishing under a 7x7 morphological opening, differing from the static background or
57
+ opposite end of the clip, and 8-connected to `ms[i]`) are added — solid 2D task objects are never masked.
58
+ """
59
+ n_f, h, w = frames.shape[:3]
60
+ if n_f < 4 or not ms.any():
61
+ return ms
62
+ step = max(1, n_f // 20)
63
+ bg_med = np.median(frames[::step].astype(np.float32), axis=0)
64
+ bg_opp = frames[0 if latest else -1].astype(np.float32)
65
+ k_open = max(5, int(round(min(h, w) * 0.024)) | 1)
66
+ kern_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_open, k_open))
67
+ k_bridge = np.ones((3, 3), np.uint8)
68
+ k_touch = np.ones((11, 11), np.uint8)
69
+ k_dil = np.ones((5, 5), np.uint8)
70
+ out = ms.copy()
71
+ for i, fidx in enumerate(idx_sub):
72
+ if not ms[i].any():
73
+ continue
74
+ fr = frames[int(fidx)].astype(np.float32)
75
+ d1 = fr - bg_med
76
+ d1 -= np.median(d1, axis=(0, 1), keepdims=True)
77
+ d2 = fr - bg_opp
78
+ d2 -= np.median(d2, axis=(0, 1), keepdims=True)
79
+ fg = np.maximum(np.abs(d1).mean(-1), np.abs(d2).mean(-1)) >= 18.0
80
+ solid = cv2.morphologyEx(fg.astype(np.uint8), cv2.MORPH_OPEN, kern_open) > 0
81
+ thin = fg & (~solid) & (~ms[i])
82
+ if not thin.any():
83
+ continue
84
+ thin_b = cv2.dilate(thin.astype(np.uint8), k_bridge) > 0
85
+ arm_touch = cv2.dilate(ms[i].astype(np.uint8), k_touch) > 0
86
+ nc, lab = cv2.connectedComponents(thin_b.astype(np.uint8), connectivity=8)
87
+ cable = np.zeros((h, w), dtype=bool)
88
+ for ci in range(1, nc):
89
+ comp = (lab == ci)
90
+ if (comp & arm_touch).any():
91
+ cable |= (comp & thin)
92
+ if cable.any():
93
+ out[i] |= (cv2.dilate(cable.astype(np.uint8), k_dil) > 0)
94
+ return out
95
+
96
+
97
+ def _sharp_plates(frames, rob=None, mask_model=None, kf_masks=None):
98
+ """Build crisp K=1 robot-free start_plate (earliest still uncovered pixel) and end_plate (latest
99
+ still uncovered pixel), reusing pixel-sharp SAM 2.1 keyframe masks (`kf_masks`) when available,
100
+ or `rob` from `robot_cover` in ~15 ms."""
101
+ if kf_masks is not None:
102
+ kf_idx, kf_raw = kf_masks
103
+ n, h, w = frames.shape[:3]
104
+ kd = max(5, int(round(min(h, w) * 0.024)) | 1)
105
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kd, kd))
106
+ s_pos = [p for p, k in enumerate(kf_idx) if k <= int(0.32 * (n - 1))] or [0]
107
+ e_pos = [p for p, k in enumerate(kf_idx) if k >= int(0.70 * (n - 1))] or [len(kf_idx) - 1]
108
+
109
+ def _pick_kf(positions, latest=False):
110
+ idx_sub = np.array([int(kf_idx[p]) for p in positions], dtype=int)
111
+ ms = np.stack([cv2.dilate(kf_raw[p].astype(np.uint8), kern) > 0 for p in positions])
112
+ ms = _attach_arm_cables(frames, idx_sub, ms, latest=latest)
113
+ st = _still_mask(frames, idx_sub)
114
+ order = list(range(len(positions) - 1, -1, -1)) if latest else list(range(len(positions)))
115
+ plate = frames[idx_sub[-1] if latest else idx_sub[0]].copy()
116
+ valid = np.zeros((h, w), dtype=bool)
117
+ ring_k = np.ones((15, 15), np.uint8)
118
+ for ok_arr in ((~ms) & st, ~ms):
119
+ for k in order:
120
+ take = ok_arr[k] & (~valid)
121
+ if take.any():
122
+ src = frames[idx_sub[k]]
123
+ if valid.any():
124
+ ring = (cv2.dilate(take.astype(np.uint8), ring_k) > 0) & valid & (~ms[k])
125
+ ref = ring if int(ring.sum()) >= 30 else (valid & (~ms[k]))
126
+ if int(ref.sum()) >= 30:
127
+ shift = np.clip(
128
+ np.median(plate[ref].astype(np.float32) - src[ref].astype(np.float32), axis=0),
129
+ -35.0, 35.0,
130
+ )
131
+ if float(np.max(np.abs(shift))) >= 1.5:
132
+ src = np.clip(src.astype(np.float32) + shift, 0, 255).astype(np.uint8)
133
+ plate[take] = src[take]
134
+ valid[take] = True
135
+ plate = _inpaint_invalid(plate, valid)
136
+ return plate, valid
137
+
138
+ sp, vs = _pick_kf(s_pos, latest=False)
139
+ ep, ve = _pick_kf(e_pos, latest=True)
140
+ q = vs & ve
141
+ if q.sum() > 200:
142
+ sa_l = cv2.cvtColor(sp, cv2.COLOR_RGB2LAB).astype(np.float32)
143
+ ea_l = cv2.cvtColor(ep, cv2.COLOR_RGB2LAB).astype(np.float32)
144
+ dl = np.abs(ea_l - sa_l).mean(-1)
145
+ quiet = q & (dl < np.percentile(dl[q], 60) + 1e-3)
146
+ if quiet.sum() > 100:
147
+ shift = np.median(ea_l[quiet] - sa_l[quiet], axis=0)
148
+ ea_l = np.clip(ea_l - shift, 0, 255).astype(np.uint8)
149
+ ep = cv2.cvtColor(ea_l, cv2.COLOR_LAB2RGB)
150
+ return dict(start_plate=sp, end_plate=ep, valid_start=vs, valid_end=ve, valid_world=vs & ve)
151
+ if rob is None:
152
+ pl = build_plates(frames, use_robot_mask=True, mask_model=mask_model)
153
+ vw = pl["valid_world"]
154
+ return dict(pl, valid_start=vw, valid_end=vw)
155
+ n, h, w = frames.shape[:3]
156
+ idx_s = np.unique(np.linspace(0, max(0, int(0.30 * (n - 1))), min(n, 5)).astype(int))
157
+ idx_e = np.unique(np.linspace(max(0, int(0.72 * (n - 1))), n - 1, min(n, 5)).astype(int))
158
+
159
+ def _pick(idx, latest=False):
160
+ ms = _upsample_rob(rob[idx], h, w)
161
+ ms = _attach_arm_cables(frames, idx, ms, latest=latest)
162
+ st = _still_mask(frames, idx)
163
+ order = list(range(len(idx) - 1, -1, -1)) if latest else list(range(len(idx)))
164
+ plate = frames[idx[-1] if latest else idx[0]].copy()
165
+ valid = np.zeros((h, w), dtype=bool)
166
+ ring_k = np.ones((15, 15), np.uint8)
167
+ # Pass 1: robot-free AND still; Pass 2: robot-free fallback
168
+ for ok_arr in ((~ms) & st, ~ms):
169
+ for k in order:
170
+ take = ok_arr[k] & (~valid)
171
+ if take.any():
172
+ src = frames[idx[k]]
173
+ if valid.any():
174
+ ring = (cv2.dilate(take.astype(np.uint8), ring_k) > 0) & valid & (~ms[k])
175
+ ref = ring if int(ring.sum()) >= 30 else (valid & (~ms[k]))
176
+ if int(ref.sum()) >= 30:
177
+ shift = np.clip(
178
+ np.median(plate[ref].astype(np.float32) - src[ref].astype(np.float32), axis=0),
179
+ -35.0, 35.0,
180
+ )
181
+ if float(np.max(np.abs(shift))) >= 1.5:
182
+ src = np.clip(src.astype(np.float32) + shift, 0, 255).astype(np.uint8)
183
+ plate[take] = src[take]
184
+ valid[take] = True
185
+ plate = _inpaint_invalid(plate, valid)
186
+ return plate, valid
187
+
188
+ sp, vs = _pick(idx_s, latest=False)
189
+ ep, ve = _pick(idx_e, latest=True)
190
+ # Match end plate's global luminance/color bias to start plate on quiet pixels (kills auto-exposure drift)
191
+ q = vs & ve
192
+ if q.sum() > 200:
193
+ sa_l = cv2.cvtColor(sp, cv2.COLOR_RGB2LAB).astype(np.float32)
194
+ ea_l = cv2.cvtColor(ep, cv2.COLOR_RGB2LAB).astype(np.float32)
195
+ dl = np.abs(ea_l - sa_l).mean(-1)
196
+ quiet = q & (dl < np.percentile(dl[q], 60) + 1e-3)
197
+ if quiet.sum() > 100:
198
+ shift = np.median(ea_l[quiet] - sa_l[quiet], axis=0)
199
+ ea_l = np.clip(ea_l - shift, 0, 255).astype(np.uint8)
200
+ ep = cv2.cvtColor(ea_l, cv2.COLOR_LAB2RGB)
201
+ return dict(start_plate=sp, end_plate=ep, valid_start=vs, valid_end=ve, valid_world=vs & ve)
202
+
203
+
204
+ def _pair_diff_32(im0, im1, F0, F1, rad=2):
205
+ """Bidirectional 32x32 DINOv2-reg patch cosine distance with +-rad physical shift tolerance.
206
+
207
+ Supports both single-layer (G, G, D) and multi-layer (L, G, G, D) token tensors (averaged equally
208
+ across layers, Dinomaly-style). Uses pure semantic+geometric DINOv2-reg features without raw glare spikes.
209
+ """
210
+ if F0.ndim == 4:
211
+ maps = [np.maximum(_tol_diff_map(F0[l], F1[l], rad=rad), _tol_diff_map(F1[l], F0[l], rad=rad))
212
+ for l in range(len(F0))]
213
+ return np.mean(maps, axis=0).astype(np.float32)
214
+ return np.maximum(_tol_diff_map(F0, F1, rad=rad), _tol_diff_map(F1, F0, rad=rad)).astype(np.float32)
215
+
216
+
217
+ def _fg_energy(img_rgb, box_norm):
218
+ """80th-percentile RGB distance inside `box_norm` vs its surrounding ring (pure OpenCV/NumPy)."""
219
+ if img_rgb is None or box_norm is None:
220
+ return 0.0
221
+ h, w = img_rgb.shape[:2]
222
+ x0, y0 = max(0, int(box_norm[0] * w)), max(0, int(box_norm[1] * h))
223
+ x1, y1 = min(w, max(x0 + 2, int(box_norm[2] * w))), min(h, max(y0 + 2, int(box_norm[3] * h)))
224
+ crop = img_rgb[y0:y1, x0:x1].astype(np.float32)
225
+ px, py = max(6, int(0.35 * (x1 - x0))), max(6, int(0.35 * (y1 - y0)))
226
+ rx0, ry0, rx1, ry1 = max(0, x0 - px), max(0, y0 - py), min(w, x1 + px), min(h, y1 + py)
227
+ m = np.ones((ry1 - ry0, rx1 - rx0), dtype=bool)
228
+ m[y0 - ry0:y1 - ry0, x0 - rx0:x1 - rx0] = False
229
+ ring = img_rgb[ry0:ry1, rx0:rx1][m].astype(np.float32)
230
+ if len(ring) < 8 or crop.size < 12:
231
+ return 0.0
232
+ ring_med = np.median(ring, axis=0)
233
+ dists = np.linalg.norm(crop.reshape(-1, 3) - ring_med[None], axis=-1)
234
+ return float(np.percentile(dists, 80))
235
+
236
+
237
+ def _norm_vec(F, mask):
238
+ F_use = F[-1] if F.ndim == 4 else F
239
+ v = F_use[mask].mean(0)
240
+ return v / max(float(np.linalg.norm(v)), 1e-8)
241
+
242
+
243
+ def _summarize_track(track, rob, fps=10):
244
+ """Summarize a per-frame object track (boxes/areas) into resting states, moves, and lost flag."""
245
+ n = len(track["areas"])
246
+ areas = track["areas"]
247
+ boxes = track["boxes"]
248
+ init_area = max(1, int(np.median(areas[:max(1, min(5, n))])))
249
+ sb = track["seed_box"]
250
+ init_sz = max(sb[2] - sb[0], sb[3] - sb[1], 0.04)
251
+ move_thr = max(0.085, 0.80 * init_sz)
252
+
253
+ solid = areas >= max(20, int(0.25 * init_area))
254
+ clear_vis = []
255
+ for k in range(n):
256
+ if solid[k] and boxes[k] is not None:
257
+ b = boxes[k]
258
+ occ = 0.0
259
+ if rob is not None and k < len(rob):
260
+ g = rob.shape[1]
261
+ x0, y0 = max(0, min(g - 1, int(b[0] * g))), max(0, min(g - 1, int(b[1] * g)))
262
+ x1, y1 = max(x0 + 1, min(g, int(np.ceil(b[2] * g)))), max(y0 + 1, min(g, int(np.ceil(b[3] * g))))
263
+ occ = float((rob[k, y0:y1, x0:x1] >= 0.25).mean())
264
+ if occ < 0.65:
265
+ cx, cy = (b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5
266
+ ar = (b[2] - b[0]) / max(b[3] - b[1], 1e-4)
267
+ clear_vis.append((k, cx, cy, b, ar, int(areas[k])))
268
+
269
+ states, cur = [], []
270
+ for rec in clear_vis:
271
+ if not cur:
272
+ cur = [rec]
273
+ else:
274
+ cx0, cy0 = float(np.median([r[1] for r in cur])), float(np.median([r[2] for r in cur]))
275
+ if np.hypot(rec[1] - cx0, rec[2] - cy0) <= 0.045:
276
+ cur.append(rec)
277
+ else:
278
+ if cur[-1][0] - cur[0][0] >= max(2, int(0.35 * fps)) or len(cur) >= 3:
279
+ states.append(cur)
280
+ cur = [rec]
281
+ if cur and (cur[-1][0] - cur[0][0] >= max(2, int(0.35 * fps)) or len(cur) >= 3):
282
+ states.append(cur)
283
+
284
+ resting = []
285
+ for st in states:
286
+ cx, cy = float(np.median([r[1] for r in st])), float(np.median([r[2] for r in st]))
287
+ b_med = [round(float(np.median([r[3][i] for r in st])), 4) for i in range(4)]
288
+ ar_med, area_med = float(np.median([r[4] for r in st])), float(np.median([r[5] for r in st]))
289
+ if resting and np.hypot(cx - resting[-1]["cx"], cy - resting[-1]["cy"]) < move_thr:
290
+ resting[-1].update(t1=st[-1][0], box=b_med, ar=ar_med, area=area_med)
291
+ else:
292
+ resting.append(dict(t0=st[0][0], t1=st[-1][0], cx=cx, cy=cy, box=b_med, ar=ar_med, area=area_med))
293
+
294
+ moves = [dict(t_depart=p["t1"], t_arrive=nx["t0"], dist=float(np.hypot(nx["cx"] - p["cx"], nx["cy"] - p["cy"])),
295
+ box=nx["box"]) for p, nx in zip(resting[:-1], resting[1:])]
296
+ tail = max(3, int(0.8 * fps))
297
+ last_box = clear_vis[-1][3] if clear_vis else sb
298
+ lost = bool(solid[:max(1, n // 3)].any() and not solid[-tail:].any())
299
+ solid_idx = np.flatnonzero(solid)
300
+ end_state = resting[-1] if resting else dict(t0=0, t1=n - 1, cx=(sb[0] + sb[2]) * 0.5, cy=(sb[1] + sb[3]) * 0.5,
301
+ box=sb, ar=(sb[2] - sb[0]) / max(sb[3] - sb[1], 1e-4), area=float(init_area))
302
+ return dict(init_sz=init_sz, resting=resting, moves=moves, moved=len(moves) > 0, end=end_state,
303
+ lost=lost, lost_frame=int(solid_idx[-1]) if (lost and len(solid_idx)) else None, last_box=last_box)
304
+
305
+
306
+ def _object_centric_rescue(Fa0, Fa1, Fb1, d_start, d_end, self_a, self_b, valid,
307
+ sim_thr=0.68, bg_gap=0.18, end_thr=0.42, st_thr=0.18, bg_b_min=0.22):
308
+ """Rescue shifted-start or bumped/fumbled unpicked task objects in B that visually match an object A cleared.
309
+
310
+ In 1-ref mode, subtracting `d_start` from `d_end` cancels objects whose starting placement shifted
311
+ between A and B (or that the arm nudged while failing to pick them up). Here we collect DINOv2-reg
312
+ embeddings of every foreground object A cleared (`self_a >= 0.36`, distinct from A's end background),
313
+ then check suppressed regions in B (`d_end >= 0.42`, `d_start >= 0.18`): if the object sitting in B's
314
+ end plate strongly matches an A-cleared object (`sim >= 0.68`) and exceeds background similarity by
315
+ `>= 0.18`, restore `d_end` there. Verified +0 false items across all 103 benchmark pairs.
316
+ """
317
+ k5 = np.ones((5, 5), np.uint8)
318
+ k7 = np.ones((7, 7), np.uint8)
319
+ n_ca, lab_a = cv2.connectedComponents(((self_a >= 0.36) & valid).astype(np.uint8), connectivity=8)
320
+ cleared_vecs, cleared_cells = [], []
321
+ Fa0_last = Fa0[-1] if Fa0.ndim == 4 else Fa0
322
+ Fb1_last = Fb1[-1] if Fb1.ndim == 4 else Fb1
323
+ for ci in range(1, n_ca):
324
+ comp = (lab_a == ci)
325
+ if int(comp.sum()) < 4 or float(self_a[comp].max()) < 0.45:
326
+ continue
327
+ ring = (cv2.dilate(comp.astype(np.uint8), k5) > 0) & (~comp) & valid
328
+ if not ring.any():
329
+ continue
330
+ f_ring = _norm_vec(Fa1, ring)
331
+ bg_st = 1.0 - float(np.dot(_norm_vec(Fa0, comp), f_ring))
332
+ bg_en = 1.0 - float(np.dot(_norm_vec(Fa1, comp), f_ring))
333
+ if bg_st > bg_en + 0.08:
334
+ cleared_vecs.append(_norm_vec(Fa0, comp))
335
+ cleared_cells.append(Fa0_last[comp])
336
+ if not cleared_vecs:
337
+ return np.zeros((G, G), dtype=np.float32), np.zeros((G, G), dtype=bool)
338
+ all_a = np.concatenate(cleared_cells, axis=0)
339
+
340
+ cand = valid & (d_end >= end_thr) & (d_start >= st_thr)
341
+ if int(cand.sum()) < 5:
342
+ return np.zeros((G, G), dtype=np.float32), np.zeros((G, G), dtype=bool)
343
+ n_cb, lab_b = cv2.connectedComponents(cand.astype(np.uint8), connectivity=8)
344
+ rescue = np.zeros((G, G), dtype=np.float32)
345
+ mask_out = np.zeros((G, G), dtype=bool)
346
+ quiet_bg = valid & (d_end < 0.35)
347
+ for ci in range(1, n_cb):
348
+ comp = (lab_b == ci)
349
+ if int(comp.sum()) < 5 or float(d_end[comp].max()) < 0.48:
350
+ continue
351
+ # Background ring excludes other high-d_end foreground cells so half-cancelled objects aren't compared to themselves
352
+ ring = (cv2.dilate(comp.astype(np.uint8), k5) > 0) & (~comp) & quiet_bg
353
+ if not ring.any():
354
+ ring = (cv2.dilate(comp.astype(np.uint8), k7) > 0) & (~comp) & quiet_bg
355
+ if not ring.any():
356
+ continue
357
+ vb = _norm_vec(Fb1, comp)
358
+ if 1.0 - float(np.dot(vb, _norm_vec(Fb1, ring))) < bg_b_min:
359
+ continue
360
+ sim_m = max(float(np.dot(vb, va)) for va in cleared_vecs)
361
+ sim_p = float((Fb1_last[comp] @ all_a.T).max(axis=1).mean())
362
+ sim_bg = float(np.dot(vb, _norm_vec(Fa1, comp)))
363
+ best = max(sim_m, sim_p)
364
+ if best >= sim_thr and best >= sim_bg + bg_gap:
365
+ rescue[comp] = d_end[comp]
366
+ mask_out |= comp
367
+ return rescue, mask_out
368
+
369
+
370
+ def compare_objects(fa, fb, res, mask_model=None, ra=None, rb=None, plates_tokens=None,
371
+ extra_goods=None, extra_goods_tokens=None, log=None, return_context=False,
372
+ kf_a=None, kf_b=None):
373
+ """Fast 32x32 robot-free object-level diff between same-scene runs A and B.
374
+
375
+ Uses Dinomaly-style multi-layer DINOv2-reg features (layers 9 & 11 in one forward pass) plus
376
+ object-centric matching to rescue shifted-start unmoved task objects.
377
+ When additional good runs are provided via `extra_goods` (list of `(frames, rob)` tuples) or
378
+ `extra_goods_tokens` (list of `(plate_dict, F0, F1)` tuples), applies an AnomalyDINO-style patch
379
+ memory bank (cell-wise min emergent distance across all good references) to suppress normal variation.
380
+ Returns a list of `OBJECT DIFF` item dicts with plain-English object descriptions (no VLM).
381
+ """
382
+ _log = log or (lambda _msg: None)
383
+ fps = res.get("fps", 10)
384
+ path = res.get("path") or []
385
+ if not path:
386
+ return ([], None) if return_context else []
387
+ sa, sb = res["trim_a"][0], res["trim_b"][0]
388
+ S = len(path)
389
+ jb_of_step = np.array([j + sb for _, j in path], dtype=int)
390
+ step_for_b = lambda b_f: int(np.argmin(np.abs(jb_of_step - b_f)))
391
+
392
+ if plates_tokens is not None:
393
+ pa, pb, Fa0, Fa1, Fb0, Fb1 = plates_tokens
394
+ else:
395
+ if fa is None or fb is None or len(fa) < 4 or len(fb) < 4:
396
+ return ([], None) if return_context else []
397
+ _log(" building robot-free start/end plates for A & B"
398
+ + (" (pixel-sharp SAM 2.1 masks) ..." if kf_a is not None
399
+ else (" (reusing mask) ..." if ra is not None else " (SAM 2.1 robot cut-out) ...")))
400
+ pa = _sharp_plates(fa, rob=ra, mask_model=mask_model, kf_masks=kf_a)
401
+ pb = _sharp_plates(fb, rob=rb, mask_model=mask_model, kf_masks=kf_b)
402
+ _log(" extracting 32x32 DINOv2-reg features (layers 9 & 11) ...")
403
+ Fa0, Fa1, Fb0, Fb1 = patch_tokens_reg_layers(
404
+ [pa["start_plate"], pa["end_plate"], pb["start_plate"], pb["end_plate"]], layers=OBJ_LAYERS
405
+ )
406
+
407
+ # Valid cells: both end plates uncovered by the robot (strict >= 0.72 so arm halos never leak!).
408
+ # Note: if B's arm is stuck over an unmoved workspace object across all end frames (not valid in end
409
+ # plate, yet valid in start plate AND B barely changed around that spot), let start/earliest-uncovered
410
+ # pixels keep non-arm regions comparable — while never unmasking the arm itself.
411
+ va_m = pa.get("valid_end", pa["valid_world"])
412
+ vb_m = pb.get("valid_end", pb["valid_world"])
413
+ va = cv2.resize(va_m.astype(np.float32), (G, G), interpolation=cv2.INTER_AREA) >= 0.72
414
+ vb = cv2.resize(vb_m.astype(np.float32), (G, G), interpolation=cv2.INTER_AREA) >= 0.72
415
+ valid = va & vb
416
+ ctx = dict(pa=pa, pb=pb, Fa0=Fa0, Fa1=Fa1, Fb0=Fb0, Fb1=Fb1)
417
+ if int(valid.sum()) < 32:
418
+ return ([], ctx) if return_context else []
419
+
420
+ # Discount any initial setup difference already present at t=0.
421
+ # rad=2 on the 32x32 grid equals the exact +-6.25% physical shift tolerance of rad=1 on 16x16.
422
+ d_start = _pair_diff_32(pa["start_plate"], pb["start_plate"], Fa0, Fb0, rad=2)
423
+ d_end = _pair_diff_32(pa["end_plate"], pb["end_plate"], Fa1, Fb1, rad=2)
424
+
425
+ # Also compute per-run self-change maps so we know WHY each spot differs (appeared vs vanished vs stayed put!)
426
+ self_a = _pair_diff_32(pa["start_plate"], pa["end_plate"], Fa0, Fa1, rad=0)
427
+ self_b = _pair_diff_32(pb["start_plate"], pb["end_plate"], Fb0, Fb1, rad=0)
428
+
429
+ # AnomalyDINO-style multi-ref patch memory bank (--also good2 good3):
430
+ # Separate min_g(d_end) and min_g(d_start) so randomized start placements don't cancel out unmoved objects!
431
+ # Where all good runs consistently end alike (g_end_sp < 0.25) AND cleared/varied at start, keep min_g(d_end).
432
+ g_bank = list(extra_goods_tokens or [])
433
+ if extra_goods:
434
+ _log(f" building multi-ref memory bank from +{len(extra_goods)} extra good run(s) ...")
435
+ g_plates = [_sharp_plates(gf, rob=gr, mask_model=mask_model) for gf, gr in extra_goods if gf is not None and len(gf) >= 4]
436
+ if g_plates:
437
+ g_imgs = [im for gp in g_plates for im in (gp["start_plate"], gp["end_plate"])]
438
+ g_toks = patch_tokens_reg_layers(g_imgs, layers=OBJ_LAYERS)
439
+ for idx_g, gp in enumerate(g_plates):
440
+ g_bank.append((gp, g_toks[2 * idx_g], g_toks[2 * idx_g + 1]))
441
+
442
+ if g_bank:
443
+ all_refs = [(pa, va, Fa0, Fa1, self_a)]
444
+ min_de = d_end.copy()
445
+ min_ds = d_start.copy()
446
+ max_sg = self_a.copy()
447
+ for gp, Fg0, Fg1 in g_bank:
448
+ vg_m = gp.get("valid_end", gp["valid_world"])
449
+ vg = cv2.resize(vg_m.astype(np.float32), (G, G), interpolation=cv2.INTER_AREA) >= 0.72
450
+ ds_g = _pair_diff_32(gp["start_plate"], pb["start_plate"], Fg0, Fb0, rad=2)
451
+ de_g = _pair_diff_32(gp["end_plate"], pb["end_plate"], Fg1, Fb1, rad=2)
452
+ sg = _pair_diff_32(gp["start_plate"], gp["end_plate"], Fg0, Fg1, rad=0)
453
+ ok_g = vg & vb
454
+ min_de = np.where(ok_g, np.minimum(min_de, de_g), min_de)
455
+ min_ds = np.where(ok_g, np.minimum(min_ds, ds_g), min_ds)
456
+ max_sg = np.where(vg, np.maximum(max_sg, sg), max_sg)
457
+ all_refs.append((gp, vg, Fg0, Fg1, sg))
458
+ g_end_sp = np.zeros((G, G), dtype=np.float32)
459
+ g_st_sp = np.zeros((G, G), dtype=np.float32)
460
+ for i in range(len(all_refs)):
461
+ for j in range(i + 1, len(all_refs)):
462
+ pi, vi, Fi0, Fi1, _ = all_refs[i]
463
+ pj, vj, Fj0, Fj1, _ = all_refs[j]
464
+ vij = vi & vj
465
+ de_ij = _pair_diff_32(pi["end_plate"], pj["end_plate"], Fi1, Fj1, rad=2)
466
+ ds_ij = _pair_diff_32(pi["start_plate"], pj["start_plate"], Fi0, Fj0, rad=2)
467
+ g_end_sp = np.where(vij, np.maximum(g_end_sp, de_ij), g_end_sp)
468
+ g_st_sp = np.where(vij, np.maximum(g_st_sp, ds_ij), g_st_sp)
469
+ cleared_zone = (g_end_sp < 0.25) & ((g_st_sp >= 0.30) | (max_sg >= 0.35))
470
+ d_em = np.where(cleared_zone, min_de, np.clip(min_de - min_ds, 0.0, None)) * valid.astype(np.float32)
471
+ oc_mask = np.zeros((G, G), dtype=bool)
472
+ else:
473
+ d_em = np.clip(d_end - d_start, 0.0, None) * valid.astype(np.float32)
474
+ oc_res, oc_mask = _object_centric_rescue(Fa0, Fa1, Fb1, d_start, d_end, self_a, self_b, valid)
475
+ if oc_mask.any():
476
+ d_em = np.maximum(d_em, oc_res)
477
+
478
+ # Suppress faint arm-halo residuals near the parked end arm, without erasing real unpicked
479
+ # objects sitting beneath a stuck gripper (`d_end >= 0.64`). Verified +0 FPs across all 103 pairs.
480
+ if ra is not None and rb is not None:
481
+ rc_a = cv2.resize(ra[-min(len(ra), 8):].mean(0), (G, G), interpolation=cv2.INTER_LINEAR)
482
+ rc_b = cv2.resize(rb[-min(len(rb), 8):].mean(0), (G, G), interpolation=cv2.INTER_LINEAR)
483
+ near_arm = np.maximum(rc_a, rc_b) > 0.12
484
+ d_em = np.where(near_arm & (d_em < 0.52) & (d_end < 0.64), d_em * 0.4, d_em)
485
+
486
+ sm, _ = _box3_smooth(d_em, valid)
487
+ # 3x3 morphological closing bridges 1-cell interior gaps (e.g. transparent glass rims) without expanding outer edges
488
+ grow = cv2.morphologyEx((d_em >= OBJ_GROW_THR).astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
489
+ n_cc, lab = cv2.connectedComponents(grow, connectivity=8)
490
+
491
+ blobs = []
492
+ for ci in range(1, n_cc):
493
+ comp = (lab == ci)
494
+ cn = int(comp.sum())
495
+ pk = float(d_em[comp].max())
496
+ pk_sm = float(sm[comp].max())
497
+ if pk < OBJ_SEED_THR or pk_sm < OBJ_SM_THR:
498
+ continue
499
+ if not (cn >= OBJ_MIN_CELLS or (cn >= 3 and pk >= OBJ_SMALL_PEAK)):
500
+ continue
501
+ ys, xs = np.nonzero(comp)
502
+ # Drop tiny 1-cell border strips
503
+ if (xs.min() == 0 or xs.max() == G - 1 or ys.min() == 0 or ys.max() == G - 1) and cn <= 5:
504
+ continue
505
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
506
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
507
+ ca = float(self_a[comp].mean())
508
+ cb = float(self_b[comp].mean())
509
+ # Classify role: did B change here (appeared / removed / dropped) or did A change here (B missed it)?
510
+ if cb > ca + 0.12:
511
+ # Check appearance vs background ring on end_plate(B) to tell appeared vs removed
512
+ ring = (cv2.dilate(comp.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0) & (~comp) & valid
513
+ if ring.any():
514
+ f_ring = _norm_vec(Fb1, ring)
515
+ bg_st = 1.0 - float(np.dot(_norm_vec(Fb0, comp), f_ring))
516
+ bg_en = 1.0 - float(np.dot(_norm_vec(Fb1, comp), f_ring))
517
+ role = "APPEARED" if bg_en > bg_st + 0.08 else ("REMOVED" if bg_st > bg_en + 0.08 else "ALTERED")
518
+ else:
519
+ role = "ALTERED"
520
+ vec = _norm_vec(Fb1 if role != "REMOVED" else Fb0, comp)
521
+ elif ca > cb + 0.12:
522
+ # Distinguish A CLEARED here (B left it unpicked) vs A PLACED here (B never placed it)
523
+ if (oc_mask & comp).any():
524
+ role = "MISSED_BY_B"
525
+ vec = _norm_vec(Fa0, comp)
526
+ else:
527
+ ring = (cv2.dilate(comp.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0) & (~comp) & valid
528
+ a_placed, a_cleared = False, False
529
+ if ring.any():
530
+ f_ring = _norm_vec(Fa1, ring)
531
+ bg_st_a = 1.0 - float(np.dot(_norm_vec(Fa0, comp), f_ring))
532
+ bg_en_a = 1.0 - float(np.dot(_norm_vec(Fa1, comp), f_ring))
533
+ if bg_en_a > bg_st_a + 0.06:
534
+ a_placed = True
535
+ elif bg_st_a > bg_en_a + 0.06:
536
+ a_cleared = True
537
+ # Cross-check pixel contrast on A's plates (prevents textured containers like dish racks from flipping)
538
+ e_st_a = _fg_energy(pa["start_plate"], box)
539
+ e_en_a = _fg_energy(pa["end_plate"], box)
540
+ if a_cleared and e_en_a > e_st_a * 1.35 + 8.0:
541
+ a_cleared, a_placed = False, True
542
+ elif a_placed and e_st_a > e_en_a * 1.35 + 8.0:
543
+ a_placed, a_cleared = False, True
544
+ elif not a_placed and not a_cleared:
545
+ if e_en_a > e_st_a * 1.35 + 8.0:
546
+ a_placed = True
547
+ elif e_st_a > e_en_a * 1.35 + 8.0:
548
+ a_cleared = True
549
+ if a_placed:
550
+ role = "NOT_PLACED"
551
+ vec = _norm_vec(Fa1, comp)
552
+ elif a_cleared:
553
+ role = "MISSED_BY_B"
554
+ vec = _norm_vec(Fa0, comp)
555
+ else:
556
+ role = "MISSED_BY_B"
557
+ vec = _norm_vec(Fa1, comp)
558
+ else:
559
+ role = "DIFFERENT_STATE"
560
+ vec = _norm_vec(Fb1, comp)
561
+ blobs.append(dict(comp=comp, box=box, n_cells=cn, peak=pk, peak_sm=pk_sm, role=role, vec=vec))
562
+
563
+ # Pair any REMOVED/MISSED_BY_B + APPEARED blobs with similar object appearance -> "object moved"
564
+ blobs.sort(key=lambda b: -b["peak"])
565
+ moved_pairs = {}
566
+ for i, bi in enumerate(blobs):
567
+ if bi["role"] not in ("REMOVED", "MISSED_BY_B"):
568
+ continue
569
+ best_j, best_sim = None, OBJ_MOVE_SIM_THR
570
+ for j, bj in enumerate(blobs):
571
+ if i == j or bj["role"] != "APPEARED":
572
+ continue
573
+ sim = float(np.dot(bi["vec"], bj["vec"]))
574
+ if sim > best_sim:
575
+ best_sim, best_j = sim, j
576
+ if best_j is not None:
577
+ moved_pairs[i] = best_j
578
+ moved_pairs[best_j] = i
579
+
580
+ items = []
581
+ for idx, b in enumerate(blobs[:6], start=1):
582
+ t_b = _region_onset(fb, pb["start_plate"], pb["end_plate"], b["comp"]) if fb is not None else (
583
+ int(jb_of_step[-1]) if len(jb_of_step) else 0
584
+ )
585
+ st0 = step_for_b(t_b)
586
+ st1 = S - 1
587
+ ia0, jb0 = path[st0]
588
+ ia1, jb1 = path[st1]
589
+ if b["role"] == "APPEARED":
590
+ verb = "moved here in B" if (idx - 1) in moved_pairs else "appeared / left here in B"
591
+ elif b["role"] == "REMOVED":
592
+ verb = "moved away from here in B" if (idx - 1) in moved_pairs else "removed / missing here in B"
593
+ elif b["role"] == "NOT_PLACED":
594
+ verb = "was not placed here in B (placed in A)"
595
+ elif b["role"] == "MISSED_BY_B":
596
+ verb = "did not move in B (cleared in A)" if (oc_mask & b["comp"]).any() else "did not change in B (changed in A)"
597
+ else:
598
+ verb = "did not move in B (cleared in A; shifted start)" if (oc_mask & b["comp"]).any() else "ended in a different state/pose in B"
599
+ items.append(dict(
600
+ kind="OBJECT DIFF",
601
+ a=[int(ia0), int(ia1)], b=[int(jb0), int(jb1)],
602
+ step=st0, end_step=st1, peak_step=st1,
603
+ score=round(min(1.0, b["peak"]), 2), thr=OBJ_SEED_THR,
604
+ box=b["box"], frames=max(1, st1 - st0 + 1), info=False,
605
+ detail=f"object {idx} {verb} (from B {t_b / fps:.1f} s, {b['n_cells']} fine cells)",
606
+ ))
607
+ return (items, ctx) if return_context else items
608
+
609
+
610
+ def _boxes_overlap(b1, b2, iou_thr=0.08, margin=0.05):
611
+ if b1 is None or b2 is None:
612
+ return False
613
+ ix0, iy0 = max(b1[0], b2[0]), max(b1[1], b2[1])
614
+ ix1, iy1 = min(b1[2], b2[2]), min(b1[3], b2[3])
615
+ inter = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
616
+ if inter > 0.0:
617
+ a1 = max(0.0, b1[2] - b1[0]) * max(0.0, b1[3] - b1[1])
618
+ a2 = max(0.0, b2[2] - b2[0]) * max(0.0, b2[3] - b2[1])
619
+ if inter / max(a1 + a2 - inter, 1e-6) >= iou_thr:
620
+ return True
621
+ c1x, c1y = (b1[0] + b1[2]) * 0.5, (b1[1] + b1[3]) * 0.5
622
+ c2x, c2y = (b2[0] + b2[2]) * 0.5, (b2[1] + b2[3]) * 0.5
623
+ in2 = (b2[0] - margin <= c1x <= b2[2] + margin) and (b2[1] - margin <= c1y <= b2[3] + margin)
624
+ in1 = (b1[0] - margin <= c2x <= b1[2] + margin) and (b1[1] - margin <= c2y <= b1[3] + margin)
625
+ return in1 or in2
626
+
627
+
628
+ def merge_channel_items(spatial_items, obj_items=None, arm_items=None, fps=10):
629
+ """Merge REST DIFF (`spatial_items`), OBJECT DIFF (`obj_items`), and ARM DIFF (`arm_items`) without duplicates.
630
+
631
+ - Each `OBJECT DIFF` upgrades/replaces ALL overlapping 16x16 `END DIFF` fragments at the same spot
632
+ (inheriting the earliest onset time from the replaced `END DIFF`s when frames were not decoded).
633
+ - Each `ARM DIFF` is appended unless an `END DIFF`/`MID-RUN DIFF`/`OBJECT DIFF` already covers the same
634
+ spot and time window.
635
+ """
636
+ out = [dict(it) for it in (spatial_items or [])]
637
+ if obj_items:
638
+ drop_idx = set()
639
+ merged_objs = []
640
+ for obj in obj_items:
641
+ if obj.get("info"):
642
+ merged_objs.append(dict(obj))
643
+ continue
644
+ cand = dict(obj)
645
+ hits = [i for i, prev in enumerate(out)
646
+ if prev["kind"] == "END DIFF" and _boxes_overlap(cand.get("box"), prev.get("box"))]
647
+ if hits:
648
+ # Inherit earliest onset from replaced END DIFF(s) when object onset wasn't earlier
649
+ earliest = min(hits, key=lambda i: out[i].get("step", cand["step"]))
650
+ if out[earliest].get("step", cand["step"]) < cand["step"]:
651
+ cand["a"] = [out[earliest]["a"][0], cand["a"][1]]
652
+ cand["b"] = [out[earliest]["b"][0], cand["b"][1]]
653
+ cand["step"] = out[earliest]["step"]
654
+ cand["frames"] = max(1, cand["end_step"] - cand["step"] + 1)
655
+ drop_idx.update(hits)
656
+ merged_objs.append(cand)
657
+ out = [it for i, it in enumerate(out) if i not in drop_idx] + merged_objs
658
+ if arm_items:
659
+ for arm in arm_items:
660
+ if arm.get("info") or arm.get("stuck_end"):
661
+ out.append(dict(arm))
662
+ continue
663
+ ab0, ab1 = arm["b"][0] / fps, arm["b"][1] / fps
664
+ dup = any(
665
+ prev["kind"] in ("END DIFF", "MID-RUN DIFF", "OBJECT DIFF")
666
+ and _boxes_overlap(arm.get("box"), prev.get("box"))
667
+ and ab0 <= prev["b"][1] / fps + 2.5 and ab1 >= prev["b"][0] / fps - 2.5
668
+ for prev in out
669
+ )
670
+ if not dup:
671
+ out.append(dict(arm))
672
+ return out