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,458 @@
1
+ """Stage 3: blind one-to-one matching of run A's world changes with run B's."""
2
+ import cv2
3
+ import numpy as np
4
+ from scipy.optimize import linear_sum_assignment
5
+
6
+ from .config import * # noqa: F401,F403
7
+
8
+
9
+ def _pair_cost(a, b):
10
+ """Task-agnostic match cost between change event `a` (Policy A) and `b` (Policy B)."""
11
+ d_ring = float(1.0 - np.dot(a["f_ring"], b["f_ring"]))
12
+ d_start = float(1.0 - np.dot(a["f_start"], b["f_start"]))
13
+ d_end = float(1.0 - np.dot(a["f_end"], b["f_end"]))
14
+ d_trans = 0.5 * (d_start + d_end)
15
+ d_size = abs(float(np.log((a["n_cells"] + 3.0) / (b["n_cells"] + 3.0))))
16
+ d_pos = float(np.hypot(a["cx"] - b["cx"], a["cy"] - b["cy"]))
17
+ d_chroma = abs(a["d_ab"] - b["d_ab"])
18
+ if {a["role"], b["role"]} == {"APPEARED", "VANISHED"}:
19
+ role_pen = 0.90
20
+ elif a["role"] != b["role"]:
21
+ role_pen = 0.15
22
+ else:
23
+ role_pen = 0.0
24
+ cost = 1.05 * d_ring + 1.10 * d_trans + 0.30 * d_size + 0.65 * d_pos + 0.50 * d_chroma + role_pen
25
+ return cost, dict(d_ring=d_ring, d_start=d_start, d_end=d_end, d_trans=d_trans,
26
+ d_size=d_size, d_pos=d_pos, d_chroma=d_chroma, role_pen=role_pen)
27
+
28
+
29
+ def _novel_excess(big, small):
30
+ """Check if a larger matched blob contains genuinely NOVEL end appearance (e.g. a spill or mess)
31
+ rather than merely the same object shifted a bit further (whose union footprint only shows the
32
+ same object + clean table). Uses cell-to-cell max similarity against the partner's end cells,
33
+ the blob's own start cells, and its surrounding clean surface ring. Returns (n_novel_cells, box, mask)."""
34
+ sim_small = (big["F1_cells"] @ small["F1_cells"].T).max(1)
35
+ sim_self0 = (big["F1_cells"] @ big["F0_cells"].T).max(1)
36
+ sim_ring = big["F1_cells"] @ big["f_ring"]
37
+ best_known = np.maximum(np.maximum(sim_small, sim_self0), sim_ring)
38
+ novel = best_known < 0.72
39
+ n_novel = int(novel.sum())
40
+ ys, xs = np.nonzero(big["mask"])
41
+ nov_mask = np.zeros((G, G), dtype=bool)
42
+ if n_novel > 0:
43
+ nov_mask[ys[novel], xs[novel]] = True
44
+ # Keep the largest connected novel component so 1-2 stray cells on another object never stretch the box
45
+ n_cc, cc_lab, stats, _ = cv2.connectedComponentsWithStats(nov_mask.astype(np.uint8), connectivity=8)
46
+ if n_cc > 1:
47
+ best_ci = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
48
+ nov_mask = (cc_lab == best_ci)
49
+ wys, wxs = np.nonzero(nov_mask)
50
+ else:
51
+ k = max(1, len(sim_small) - small["n_cells"])
52
+ worst = np.argsort(best_known)[:k]
53
+ wxs, wys = xs[worst], ys[worst]
54
+ nov_mask[wys, wxs] = True
55
+ box = [round(float(wxs.min()) / G, 4), round(float(wys.min()) / G, 4),
56
+ round(float(wxs.max() + 1) / G, 4), round(float(wys.max() + 1) / G, 4)]
57
+ return n_novel, box, nov_mask
58
+
59
+
60
+ def _achieved_in_raw_end(ev, w_other, rad=3):
61
+ """Cross-check guard against two harmless false-alarm sources on unmatched events:
62
+ 1. VANISHED start-position setup differences: an object (or arm at t=0) started at `mask` in
63
+ one run and was cleared, while the other run ALREADY ended with that same cleared surface
64
+ (not the original object) because the object simply started elsewhere.
65
+ 2. Gripper-occluded placed objects: the robot parked right next to a placed object in the
66
+ other video (e.g. a spoon dropped inside a box while the gripper stays above it), so
67
+ `end_plate` stepped back to an earlier empty frame even though `raw_end` clearly shows it."""
68
+ F_r0 = w_other.get("F_raw0")
69
+ F_r1 = w_other.get("F_raw1")
70
+ if ev["role"] == "VANISHED":
71
+ F_o1 = w_other.get("F1")
72
+ if F_o1 is None:
73
+ F_o1 = F_r1
74
+ if F_o1 is None:
75
+ return False
76
+ m = ev["mask"]
77
+ med_cleared = float(np.median((ev["F1_cells"] * F_o1[m]).sum(-1)))
78
+ med_object = float(np.median((ev["F0_cells"] * F_o1[m]).sum(-1)))
79
+ return med_cleared >= 0.78 and (med_cleared - med_object) >= 0.12
80
+ if F_r0 is None or F_r1 is None:
81
+ return False
82
+ win = cv2.dilate(ev["mask"].astype(np.uint8), np.ones((2 * rad + 1, 2 * rad + 1), np.uint8), iterations=1) > 0
83
+ if not win.any():
84
+ return False
85
+ sim_end = (ev["F1_cells"] @ F_r1[win].T).max(1)
86
+ sim_start = (ev["F1_cells"] @ F_r0[win].T).max(1)
87
+ med_end = float(np.median(sim_end))
88
+ med_start = float(np.median(sim_start))
89
+ # Strongly present in the other run's final frame (either visually identical >=0.84,
90
+ # or strong match >=0.74 that genuinely appeared relative to start)
91
+ return med_end >= 0.84 or (med_end >= 0.74 and (med_end - med_start) >= 0.08)
92
+
93
+
94
+ def match_world_changes(wa, wb, known_b=()):
95
+ """Compare Policy A's world changes vs Policy B's blindly (1-vs-1, zero calibration runs).
96
+ known_b: indices of B's changes that another good run also made; they are never reported as EXTRA CHANGE."""
97
+ # Guard against comparing two videos from completely different rooms/cameras (e.g. multi-desk datasets):
98
+ # pixel-aligned world diffing requires a shared fixed camera; warn cleanly instead of projecting bogus heatmaps.
99
+ Fa0, Fb0 = wa.get("F0"), wb.get("F0")
100
+ if Fa0 is not None and Fb0 is not None:
101
+ both_v = wa["valid_cell"] & wb["valid_cell"]
102
+ if int(both_v.sum()) >= 32:
103
+ scene_sim = float(np.median((Fa0[both_v] * Fb0[both_v]).sum(-1)))
104
+ if scene_sim < 0.50:
105
+ return dict(
106
+ findings=[dict(
107
+ kind="SETUP DIFF",
108
+ score=round(1.0 - scene_sim, 2),
109
+ box=None,
110
+ info=True,
111
+ detail=f"different camera viewpoint or room between A and B "
112
+ f"(scene similarity {scene_sim:.2f} < 0.50) — world-diff requires a shared fixed camera",
113
+ )],
114
+ flagged=False,
115
+ score=0.0,
116
+ heat_end=np.zeros((G, G), np.float32),
117
+ matched=[],
118
+ scene_sim=scene_sim,
119
+ )
120
+
121
+ ea, eb = wa["events"], wb["events"]
122
+ na, nb = len(ea), len(eb)
123
+ findings = []
124
+ matched = []
125
+ used_a, used_b = set(), set()
126
+
127
+ if na > 0 and nb > 0:
128
+ C = np.zeros((na, nb), np.float32)
129
+ meta = {}
130
+ for i, a in enumerate(ea):
131
+ for j, b in enumerate(eb):
132
+ c, d = _pair_cost(a, b)
133
+ C[i, j] = c
134
+ meta[(i, j)] = d
135
+ ri, cj = linear_sum_assignment(C)
136
+ for i, j in zip(ri, cj):
137
+ c = float(C[i, j])
138
+ d = meta[(i, j)]
139
+ # Reject false matches between visually unrelated outcomes (e.g. brown spill vs clear pitcher)
140
+ if c <= MATCH_MAX_COST and d["d_end"] <= END_APPEAR_MAX:
141
+ used_a.add(i)
142
+ used_b.add(j)
143
+ matched.append((i, j, c, d))
144
+
145
+ heat_end = np.zeros((G, G), np.float32)
146
+ for i, j, c, d in matched:
147
+ a, b = ea[i], eb[j]
148
+ ratio_ba = b["n_cells"] / max(a["n_cells"], 1)
149
+ ratio_ab = a["n_cells"] / max(b["n_cells"], 1)
150
+ excess_ba = b["n_cells"] - a["n_cells"]
151
+ excess_ab = a["n_cells"] - b["n_cells"]
152
+ # Always run fast cell-to-cell novelty check on matched blobs (>=12 cells):
153
+ # catches a spill/mess merged into an object even when total area ratio is <2x (e.g. 89c vs 47c),
154
+ # while staying 0-1 novel cells on cleanly shifted objects (e.g. moved pitchers).
155
+ n_nov_b, box_nov_b, mask_nov_b = _novel_excess(b, a) if b["n_cells"] >= 12 else (0, b["box"], b["mask"])
156
+ n_nov_a, box_nov_a, mask_nov_a = _novel_excess(a, b) if (ratio_ab >= AREA_EXPAND_RATIO and excess_ab >= MIN_EXCESS_CELLS) else (0, a["box"], a["mask"])
157
+
158
+ if d["d_ring"] > RING_DIFF_THR or (d["d_pos"] > FAR_SHIFT_THR and d["d_ring"] > 0.25):
159
+ sev = round(max(d["d_ring"] / RING_DIFF_THR, d["d_pos"] / FAR_SHIFT_THR), 2)
160
+ findings.append(dict(
161
+ kind="WRONG PLACE",
162
+ score=sev,
163
+ box=b["box"],
164
+ box_a=a["box"],
165
+ mask_b=b["mask"],
166
+ info=False,
167
+ detail=f"similar change ({b['role'].lower()}) landed on a different surface/place "
168
+ f"(shift {d['d_pos']*100:.0f}%, surface diff {d['d_ring']:.2f})",
169
+ metrics=d,
170
+ ))
171
+ heat_end = np.maximum(heat_end, np.where(b["mask"], wb["score_map"], 0.0))
172
+ elif n_nov_b >= 10 or (
173
+ b["d_ab"] - a["d_ab"] > CHROMA_DELTA_MAX and b["d_ab_max"] > 0.55 and b["n_cells"] >= 12
174
+ ):
175
+ use_nov = n_nov_b >= 10
176
+ ebox = box_nov_b if use_nov else b["box"]
177
+ emask = mask_nov_b if use_nov else b["mask"]
178
+ sev = round(min(2.0, max(n_nov_b / 10.0, (b["d_ab"] - a["d_ab"]) / CHROMA_DELTA_MAX)), 2)
179
+ findings.append(dict(
180
+ kind="EXTRA CHANGE",
181
+ score=sev,
182
+ box=ebox,
183
+ box_a=a["box"],
184
+ mask_b=emask,
185
+ info=False,
186
+ detail=f"novel extra end appearance in B ({n_nov_b} novel cells, chroma delta +{b['d_ab'] - a['d_ab']:.2f})",
187
+ metrics=d,
188
+ ))
189
+ heat_end = np.maximum(heat_end, np.where(emask, wb["score_map"], 0.0))
190
+ elif n_nov_a >= 10:
191
+ sev = round(min(2.0, n_nov_a / 10.0), 2)
192
+ findings.append(dict(
193
+ kind="MISSING OUTCOME",
194
+ score=sev,
195
+ box=box_nov_a,
196
+ box_a=a["box"],
197
+ mask_a=mask_nov_a,
198
+ info=False,
199
+ detail=f"novel outcome region in A ({n_nov_a} cells) missing in B",
200
+ metrics=d,
201
+ ))
202
+ heat_end = np.maximum(heat_end, np.where(mask_nov_a, wa["score_map"], 0.0))
203
+ elif d["d_pos"] >= SHIFT_INFO_THR:
204
+ findings.append(dict(
205
+ kind="SAME OUTCOME",
206
+ score=round(d["d_pos"], 2),
207
+ box=b["box"],
208
+ box_a=a["box"],
209
+ mask_b=b["mask"],
210
+ info=True,
211
+ detail=f"same {b['role'].lower()} change matched across A and B (shifted {d['d_pos']*100:.0f}%)",
212
+ metrics=d,
213
+ ))
214
+
215
+ for i, a in enumerate(ea):
216
+ if i in used_a:
217
+ continue
218
+ obs_in_b = float(wb["valid_cell"][a["mask"]].mean())
219
+ if obs_in_b < 0.40:
220
+ continue
221
+ if _achieved_in_raw_end(a, wb):
222
+ if a["role"] != "VANISHED":
223
+ findings.append(dict(
224
+ kind="SAME OUTCOME",
225
+ score=0.0,
226
+ box=a["box"],
227
+ box_a=a["box"],
228
+ info=True,
229
+ detail="outcome confirmed in B's final frame near parked gripper",
230
+ ))
231
+ continue
232
+ sev = round(float(a["peak"]), 2)
233
+ findings.append(dict(
234
+ kind="MISSING OUTCOME",
235
+ score=sev,
236
+ box=a["box"],
237
+ box_a=a["box"],
238
+ mask_a=a["mask"],
239
+ info=False,
240
+ detail=f"world change in A ({a['role'].lower()}, {a['n_cells']} cells) did not happen in B",
241
+ ))
242
+ heat_end = np.maximum(heat_end, np.where(a["mask"], wa["score_map"], 0.0))
243
+
244
+ for j, b in enumerate(eb):
245
+ if j in used_b or j in known_b:
246
+ continue
247
+ obs_in_a = float(wa["valid_cell"][b["mask"]].mean())
248
+ if obs_in_a < 0.40:
249
+ continue
250
+ if _achieved_in_raw_end(b, wa):
251
+ if b["role"] != "VANISHED":
252
+ findings.append(dict(
253
+ kind="SAME OUTCOME",
254
+ score=0.0,
255
+ box=b["box"],
256
+ box_a=b["box"],
257
+ info=True,
258
+ detail="outcome confirmed in A's final frame near parked gripper",
259
+ ))
260
+ continue
261
+ sev = round(float(b["peak"]), 2)
262
+ findings.append(dict(
263
+ kind="EXTRA CHANGE",
264
+ score=sev,
265
+ box=b["box"],
266
+ box_a=b["box"],
267
+ mask_b=b["mask"],
268
+ info=False,
269
+ detail=f"extra world change in B ({b['role'].lower()}, {b['n_cells']} cells) absent in A",
270
+ ))
271
+ heat_end = np.maximum(heat_end, np.where(b["mask"], wb["score_map"], 0.0))
272
+
273
+ real = [f for f in findings if not f.get("info")]
274
+ real.sort(key=lambda x: -x["score"])
275
+ infos = [f for f in findings if f.get("info")]
276
+ all_f = real + infos
277
+ return dict(
278
+ findings=all_f,
279
+ flagged=len(real) > 0,
280
+ score=float(real[0]["score"]) if real else 0.0,
281
+ heat_end=heat_end,
282
+ matched=matched,
283
+ )
284
+
285
+
286
+ FIXED_CELL_REF_EM_MAX = 0.32 # fixed-cell gate: good refs' pairwise emergent end-plate diff max must stay <= this
287
+ FIXED_CELL_EM_THR = 0.25 # candidate emergent end-plate 3x3 peak (with +-1-cell shift tolerance)
288
+ FIXED_CELL_EXC_THR = 0.16 # excess over the good refs' own per-cell end-plate variation at that spot
289
+
290
+
291
+ def _tol_diff_map(Fa, Fb, rad=1):
292
+ """Per-cell min cosine distance 1 - max_{dy,dx in [-rad,rad]} dot(Fb[y,x], Fa[y+dy,x+dx])."""
293
+ h, w = Fa.shape[:2]
294
+ best = np.full((h, w), -1.0, np.float32)
295
+ for dy in range(-rad, rad + 1):
296
+ for dx in range(-rad, rad + 1):
297
+ y0a, y1a = max(0, dy), min(h, h + dy)
298
+ x0a, x1a = max(0, dx), min(w, w + dx)
299
+ y0b, y1b = max(0, -dy), min(h, h - dy)
300
+ x0b, x1b = max(0, -dx), min(w, w - dx)
301
+ s = (Fb[y0b:y1b, x0b:x1b] * Fa[y0a:y1a, x0a:x1a]).sum(-1)
302
+ best[y0b:y1b, x0b:x1b] = np.maximum(best[y0b:y1b, x0b:x1b], s)
303
+ return np.clip(1.0 - best, 0.0, 2.0)
304
+
305
+
306
+ def _box3_smooth(diff_map, valid):
307
+ """3x3 box-smoothed diff map over valid cells (requires >=5/9 valid neighbors to reject border specks)."""
308
+ vf = valid.astype(np.float32)
309
+ num = cv2.boxFilter(np.where(valid, diff_map, 0.0).astype(np.float32), -1, (3, 3), normalize=False)
310
+ den = cv2.boxFilter(vf, -1, (3, 3), normalize=False)
311
+ ok = (den >= 5.0) & valid
312
+ if not ok.any():
313
+ return np.zeros_like(diff_map, np.float32), 0.0
314
+ sm = np.where(ok, num / np.maximum(den, 1.0), 0.0).astype(np.float32)
315
+ return sm, float(sm[ok].max())
316
+
317
+
318
+ def _emergent_end_map(wa, wb, rad=1):
319
+ """Per-cell emergent end-plate difference: how much more end plates differ (with +-1-cell shift tolerance)
320
+ than start plates did — discounts harmless initial scene clutter while catching wrong end poses/stacking."""
321
+ d1t = _tol_diff_map(wa["F1"], wb["F1"], rad=rad)
322
+ d0 = 1.0 - (wa["F0"] * wb["F0"]).sum(-1)
323
+ return np.maximum(0.0, d1t - d0)
324
+
325
+
326
+ def _fixed_cell_end_check(w_refs, wb):
327
+ """Gated direct robot-free end-plate check for fixed-outcome cells (requires >=2 good refs).
328
+
329
+ Measures pairwise emergent end-plate variation across the good refs themselves (`ref_em_max`, plus a
330
+ per-cell baseline map `ref_cell_max`). If `ref_em_max <= FIXED_CELL_REF_EM_MAX`, the task has a tight,
331
+ repeatable end state and B's robot-free end plate is compared directly against all refs to catch subtle
332
+ in-place pose/stacking failures (e.g. flat-stacked plates). Otherwise stays completely off (0 extra FPs).
333
+ """
334
+ if len(w_refs) < 2:
335
+ return None
336
+ for w in list(w_refs) + [wb]:
337
+ if w.get("F0") is None or w.get("F1") is None or w.get("valid_cell") is None:
338
+ return None
339
+
340
+ h, w_g = wb["F1"].shape[:2]
341
+ ref_cell_max = np.zeros((h, w_g), np.float32)
342
+ ref_peaks = []
343
+ for i in range(len(w_refs)):
344
+ for j in range(len(w_refs)):
345
+ if i == j:
346
+ continue
347
+ v = w_refs[i]["valid_cell"] & w_refs[j]["valid_cell"]
348
+ if int(v.sum()) < 32:
349
+ return None
350
+ sm, mx = _box3_smooth(_emergent_end_map(w_refs[i], w_refs[j]), v)
351
+ ref_peaks.append(mx)
352
+ ref_cell_max = np.maximum(ref_cell_max, sm)
353
+
354
+ if not ref_peaks or max(ref_peaks) > FIXED_CELL_REF_EM_MAX:
355
+ return None
356
+
357
+ shared_v = wb["valid_cell"].copy()
358
+ for wr in w_refs:
359
+ shared_v &= wr["valid_cell"]
360
+ if int(shared_v.sum()) < 32:
361
+ return None
362
+
363
+ em_min = np.minimum.reduce([_emergent_end_map(wr, wb) for wr in w_refs])
364
+ sm, _ = _box3_smooth(em_min, shared_v)
365
+ exc = np.maximum(0.0, sm - ref_cell_max) * shared_v.astype(np.float32)
366
+
367
+ seed = (sm >= FIXED_CELL_EM_THR) & (exc >= FIXED_CELL_EXC_THR) & shared_v
368
+ if not seed.any():
369
+ return None
370
+
371
+ grow = (sm >= 0.80 * FIXED_CELL_EM_THR) & (exc >= 0.70 * FIXED_CELL_EXC_THR) & shared_v
372
+ n_cc, cc_lab = cv2.connectedComponents(grow.astype(np.uint8), connectivity=8)
373
+ findings = []
374
+ heat = np.zeros((h, w_g), np.float32)
375
+ for ci in range(1, n_cc):
376
+ cm = (cc_lab == ci)
377
+ if not (cm & seed).any():
378
+ continue
379
+ ys, xs = np.nonzero(cm)
380
+ pk_em = float(sm[cm].max())
381
+ pk_exc = float(exc[cm].max())
382
+ sev = round(min(2.0, max(pk_em / FIXED_CELL_EM_THR, pk_exc / FIXED_CELL_EXC_THR)), 2)
383
+ box = [round(float(xs.min()) / w_g, 4), round(float(ys.min()) / h, 4),
384
+ round(float(xs.max() + 1) / w_g, 4), round(float(ys.max() + 1) / h, 4)]
385
+ findings.append(dict(
386
+ kind="END DIFF",
387
+ score=sev,
388
+ box=box,
389
+ box_a=box,
390
+ mask_b=cm,
391
+ info=False,
392
+ detail=f"end plate differs from good runs in a fixed-outcome cell "
393
+ f"(emergent diff {pk_em:.2f}, +{pk_exc:.2f} over ref spread)",
394
+ ))
395
+ heat = np.maximum(heat, np.where(cm, np.clip(sm * 2.0, 0.0, 1.0), 0.0))
396
+
397
+ if not findings:
398
+ return None
399
+ findings.sort(key=lambda x: -x["score"])
400
+ return findings[:2], heat
401
+
402
+
403
+ def match_with_refs(w_refs, wb, min_share=0.5, match_model=None):
404
+ """B against one or more good runs. w_refs[0] is A. With more good runs:
405
+ - an A change counts only if at least `min_share` of all good runs make it (drops one-off noise in A);
406
+ - a B change is EXTRA only if no good run makes it.
407
+ When `match_model` (an optional Stage 3 matcher callable) is provided, replaces the hand-made matching rules after the SETUP DIFF check.
408
+ On tight fixed-outcome cells (>=2 good refs), adds a gated direct end-plate check to catch in-place pose/stacking diffs."""
409
+ wa, others = w_refs[0], list(w_refs[1:])
410
+ if match_model is not None:
411
+ Fa0, Fb0 = wa.get("F0"), wb.get("F0")
412
+ if Fa0 is not None and Fb0 is not None:
413
+ both_v = wa["valid_cell"] & wb["valid_cell"]
414
+ if int(both_v.sum()) >= 32:
415
+ scene_sim = float(np.median((Fa0[both_v] * Fb0[both_v]).sum(-1)))
416
+ if scene_sim < 0.50:
417
+ return dict(
418
+ findings=[dict(
419
+ kind="SETUP DIFF",
420
+ score=round(1.0 - scene_sim, 2),
421
+ box=None,
422
+ info=True,
423
+ detail=f"different camera viewpoint or room between A and B "
424
+ f"(scene similarity {scene_sim:.2f} < 0.50) — world-diff requires a shared fixed camera",
425
+ )],
426
+ flagged=False,
427
+ score=0.0,
428
+ heat_end=np.zeros((G, G), np.float32),
429
+ matched=[],
430
+ scene_sim=scene_sim,
431
+ events_a=wa["events"],
432
+ )
433
+ res = match_model(w_refs, wb)
434
+ res.setdefault("events_a", wa["events"])
435
+ elif not others:
436
+ return dict(match_world_changes(wa, wb), events_a=wa["events"])
437
+ else:
438
+ seen = np.ones(len(wa["events"]))
439
+ for wo in others:
440
+ for i, _, _, _ in match_world_changes(wa, wo)["matched"]:
441
+ seen[i] += 1
442
+ keep = [e for e, s in zip(wa["events"], seen) if s >= min_share * len(w_refs)]
443
+ known = {j for wo in others for _, j, _, _ in match_world_changes(wo, wb)["matched"]}
444
+ res = match_world_changes(dict(wa, events=keep), wb, known_b=known)
445
+ res["dropped_a"] = len(wa["events"]) - len(keep)
446
+ res["events_a"] = keep # res["matched"] indexes these, not wa["events"]
447
+
448
+ # Gated fixed-cell end-plate check: runs only when not already flagged and scene is a shared fixed camera
449
+ is_setup_diff = any(f.get("kind") == "SETUP DIFF" for f in res.get("findings", []))
450
+ if not res.get("flagged") and not is_setup_diff and len(w_refs) >= 2:
451
+ fc = _fixed_cell_end_check(w_refs, wb)
452
+ if fc is not None:
453
+ fc_findings, fc_heat = fc
454
+ res["findings"] = fc_findings + list(res.get("findings", []))
455
+ res["flagged"] = True
456
+ res["score"] = max(float(res.get("score", 0.0)), float(fc_findings[0]["score"]))
457
+ res["heat_end"] = np.maximum(res["heat_end"], fc_heat)
458
+ return res
@@ -0,0 +1,214 @@
1
+ """Lazy cached Apache-2.0 models: DINOv2-reg, Grounding DINO tiny, SAM 2.1 small (image and video)."""
2
+ import contextlib
3
+ import functools
4
+ import os
5
+ import sys
6
+ import warnings
7
+
8
+ import cv2
9
+ import numpy as np
10
+
11
+ from .config import G, GRID_SIZE
12
+
13
+ os.environ.setdefault("USE_TF", "0")
14
+ os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
15
+ os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
16
+
17
+ _WARNED_CPU = False
18
+
19
+
20
+ def select_device(log=None):
21
+ """Return 'cuda' when available, else 'cpu' after printing a single clear install hint."""
22
+ global _WARNED_CPU
23
+ import torch
24
+ if torch.cuda.is_available():
25
+ return "cuda"
26
+ if not _WARNED_CPU:
27
+ _WARNED_CPU = True
28
+ emit = log or (lambda msg: print(msg, file=sys.stderr, flush=True))
29
+ if getattr(torch.version, "cuda", None) is None:
30
+ emit(
31
+ "warning: PyTorch is CPU-only (no CUDA support), so runs will be very slow. "
32
+ "On Windows, 'pip install torch' installs the CPU build by default. "
33
+ "If you have an NVIDIA GPU, install CUDA PyTorch first:\n"
34
+ " pip install --force-reinstall torch torchvision --index-url https://download.pytorch.org/whl/cu128"
35
+ )
36
+ else:
37
+ emit(
38
+ "warning: no NVIDIA CUDA GPU available, running on CPU (runs will be very slow). "
39
+ "Check your GPU driver or 'nvidia-smi'."
40
+ )
41
+ return "cpu"
42
+
43
+
44
+ @contextlib.contextmanager
45
+ def quiet_model_load():
46
+ """Silence harmless transformers/xFormers/triton warnings & noisy shard bars during model init."""
47
+ tlog = None
48
+ prev_verb = None
49
+ had_pbar = None
50
+ try:
51
+ from transformers.utils import logging as tlog
52
+ prev_verb = tlog.get_verbosity()
53
+ tlog.set_verbosity_error()
54
+ if hasattr(tlog, "is_progress_bar_enabled") and hasattr(tlog, "disable_progress_bar"):
55
+ had_pbar = tlog.is_progress_bar_enabled()
56
+ tlog.disable_progress_bar()
57
+ except Exception:
58
+ tlog = None
59
+ with warnings.catch_warnings():
60
+ warnings.filterwarnings("ignore", message=r"xFormers is not available.*", category=UserWarning)
61
+ warnings.filterwarnings("ignore", message=r"Failed to find CUDA\.", category=UserWarning)
62
+ try:
63
+ yield
64
+ finally:
65
+ if tlog is not None:
66
+ if prev_verb is not None:
67
+ tlog.set_verbosity(prev_verb)
68
+ if had_pbar and hasattr(tlog, "enable_progress_bar"):
69
+ tlog.enable_progress_bar()
70
+
71
+
72
+ @functools.lru_cache(maxsize=1)
73
+ def _dinov2_reg():
74
+ import torch
75
+ dev = select_device()
76
+ with quiet_model_load():
77
+ m = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14_reg", verbose=False).to(dev).eval()
78
+ return m.half() if dev == "cuda" else m
79
+
80
+
81
+ @functools.lru_cache(maxsize=1)
82
+ def _gdino():
83
+ from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
84
+ name = "IDEA-Research/grounding-dino-tiny"
85
+ dev = select_device()
86
+ local_only = os.environ.get("HF_HUB_OFFLINE", "0") == "1"
87
+ with quiet_model_load():
88
+ try:
89
+ proc = AutoProcessor.from_pretrained(name, local_files_only=True)
90
+ mod = AutoModelForZeroShotObjectDetection.from_pretrained(name, local_files_only=True)
91
+ except ImportError:
92
+ raise
93
+ except Exception:
94
+ if local_only:
95
+ raise
96
+ print("downloading Grounding DINO tiny (first run only; cached afterwards) ...", flush=True)
97
+ proc = AutoProcessor.from_pretrained(name)
98
+ mod = AutoModelForZeroShotObjectDetection.from_pretrained(name)
99
+ return proc, mod.to(dev).eval()
100
+
101
+
102
+ @functools.lru_cache(maxsize=1)
103
+ def _sam2():
104
+ from transformers import Sam2Model, Sam2Processor
105
+ name = "facebook/sam2.1-hiera-small"
106
+ dev = select_device()
107
+ local_only = os.environ.get("HF_HUB_OFFLINE", "0") == "1"
108
+ with quiet_model_load():
109
+ try:
110
+ proc = Sam2Processor.from_pretrained(name, local_files_only=True)
111
+ mod = Sam2Model.from_pretrained(name, local_files_only=True)
112
+ except ImportError:
113
+ raise
114
+ except Exception:
115
+ if local_only:
116
+ raise
117
+ print("downloading SAM 2.1 small (first run only; cached afterwards) ...", flush=True)
118
+ proc = Sam2Processor.from_pretrained(name)
119
+ mod = Sam2Model.from_pretrained(name)
120
+ return proc, mod.to(dev).eval()
121
+
122
+
123
+ @functools.lru_cache(maxsize=1)
124
+ def _sam2_video():
125
+ import torch
126
+ from transformers import Sam2VideoModel, Sam2VideoProcessor
127
+ name = "facebook/sam2.1-hiera-small"
128
+ dev = select_device()
129
+ dtype = torch.bfloat16 if dev == "cuda" else torch.float32
130
+ local_only = os.environ.get("HF_HUB_OFFLINE", "0") == "1"
131
+ with quiet_model_load():
132
+ try:
133
+ proc = Sam2VideoProcessor.from_pretrained(name, local_files_only=True)
134
+ mod = Sam2VideoModel.from_pretrained(name, local_files_only=True)
135
+ except ImportError:
136
+ raise
137
+ except Exception:
138
+ if local_only:
139
+ raise
140
+ print("downloading SAM 2.1 small video tracker (first run only; cached afterwards) ...", flush=True)
141
+ proc = Sam2VideoProcessor.from_pretrained(name)
142
+ mod = Sam2VideoModel.from_pretrained(name)
143
+ return proc, mod.to(dev, dtype=dtype).eval(), dev, dtype
144
+
145
+
146
+ @functools.lru_cache(maxsize=1)
147
+ def _sam3(ckpt=None):
148
+ """Load unified SAM 3 video model (shared backbone for Sam3Processor detector + Sam3TrackerPredictor)."""
149
+ from pathlib import Path
150
+ import torch
151
+ from sam3.model_builder import build_sam3_video_model
152
+ from sam3.model.sam3_image_processor import Sam3Processor
153
+
154
+ ckpt = ckpt or os.environ.get("SAM3_CKPT") or None
155
+ if not ckpt:
156
+ for cand in (
157
+ "/content/drive/MyDrive/rollout_colab/sam3.pt",
158
+ "/content/sam3.pt",
159
+ ):
160
+ if Path(cand).is_file():
161
+ ckpt = cand
162
+ break
163
+ if ckpt and not Path(ckpt).is_file():
164
+ raise FileNotFoundError(f"SAM 3 checkpoint not found: {ckpt}")
165
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
166
+ mod = build_sam3_video_model(
167
+ checkpoint_path=ckpt,
168
+ load_from_HF=(ckpt is None),
169
+ device=dev,
170
+ )
171
+ mod = mod.to(dev).eval()
172
+ tracker = mod.tracker
173
+ tracker.backbone = mod.detector.backbone
174
+ proc = Sam3Processor(mod.detector, device=dev, confidence_threshold=0.30)
175
+ return proc, tracker, dev
176
+
177
+
178
+ def patch_tokens_reg(imgs):
179
+ """(K, H, W, 3) uint8 RGB -> (K, G, G, 384) L2-normalized float32 DINOv2-reg patch tokens."""
180
+ import torch
181
+ sq = np.stack([cv2.resize(im, (GRID_SIZE, GRID_SIZE), interpolation=cv2.INTER_AREA) for im in imgs])
182
+ model = _dinov2_reg()
183
+ dev = next(model.parameters()).device
184
+ use_half = next(model.parameters()).dtype == torch.float16
185
+ mean = torch.tensor([0.485, 0.456, 0.406], device=dev).view(1, 3, 1, 1)
186
+ std = torch.tensor([0.229, 0.224, 0.225], device=dev).view(1, 3, 1, 1)
187
+ with torch.no_grad():
188
+ x = torch.as_tensor(sq, device=dev).permute(0, 3, 1, 2).float() / 255.0
189
+ x = (x - mean) / std
190
+ out = model.forward_features(x.half() if use_half else x)["x_norm_patchtokens"].float()
191
+ out = torch.nn.functional.normalize(out, dim=-1).cpu().numpy()
192
+ return out.reshape(len(imgs), G, G, -1)
193
+
194
+
195
+ def patch_tokens_reg_layers(imgs, layers=(9, 11)):
196
+ """(K, H, W, 3) uint8 RGB -> (K, L, G, G, 384) L2-normalized float32 intermediate DINOv2-reg tokens
197
+ in a single forward pass (Dinomaly multi-layer fusion, zero extra backbone cost)."""
198
+ import torch
199
+ sq = np.stack([cv2.resize(im, (GRID_SIZE, GRID_SIZE), interpolation=cv2.INTER_AREA) for im in imgs])
200
+ model = _dinov2_reg()
201
+ dev = next(model.parameters()).device
202
+ use_half = next(model.parameters()).dtype == torch.float16
203
+ mean = torch.tensor([0.485, 0.456, 0.406], device=dev).view(1, 3, 1, 1)
204
+ std = torch.tensor([0.229, 0.224, 0.225], device=dev).view(1, 3, 1, 1)
205
+ with torch.no_grad():
206
+ x = torch.as_tensor(sq, device=dev).permute(0, 3, 1, 2).float() / 255.0
207
+ x = (x - mean) / std
208
+ feats = model.get_intermediate_layers(x.half() if use_half else x, n=layers, norm=True)
209
+ stacked = []
210
+ for f in feats:
211
+ f = f[:, -G * G:, :].float()
212
+ f = torch.nn.functional.normalize(f, dim=-1).cpu().numpy()
213
+ stacked.append(f.reshape(len(imgs), G, G, -1))
214
+ return np.stack(stacked, axis=1)