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,238 @@
1
+ """Fast built-in Apache-2.0 robot-arm occupancy mask (`(N, 16, 16)` float32) for public mode.
2
+
3
+ Uses batched Grounding DINO tiny + SAM 2.1 small (both Apache-2.0) on ~12 strategic keyframes
4
+ (opening, mid-run, and closing frames) and smoothly propagates the robot occupancy to all `N`
5
+ frames using keyframe interpolation gated by per-frame motion against the static scene.
6
+
7
+ When no external `--mask-model` is provided, `compare(..., channels=True)` runs this once per
8
+ video (~2-3 s on GPU) and reuses the resulting `(N, 16, 16)` mask across:
9
+ 1. `spatial_diff` (suppresses arm-motion false alarms in `MID-RUN DIFF` / `END DIFF`)
10
+ 2. `object_diff` (builds sharp robot-free start/end plates in ~15 ms without re-running SAM 2.1)
11
+ 3. `arm_diff` (enables multi-ref stuck-arm detection and `--arm-diff` out of the box)
12
+ """
13
+ import cv2
14
+ import numpy as np
15
+
16
+
17
+ def _keyframe_indices(n, n_mid=4):
18
+ """Select ~12 strategic keyframes covering start (30%), middle (30-72%), and end (72-100%)."""
19
+ if n <= 12:
20
+ return np.arange(n, dtype=int)
21
+ s_idx = [0, max(1, int(0.14 * (n - 1))), max(2, int(0.28 * (n - 1)))]
22
+ m_idx = np.linspace(int(0.36 * (n - 1)), int(0.66 * (n - 1)), n_mid).astype(int).tolist()
23
+ e_idx = [
24
+ int(0.74 * (n - 1)),
25
+ int(0.83 * (n - 1)),
26
+ int(0.91 * (n - 1)),
27
+ max(0, n - 3),
28
+ n - 1,
29
+ ]
30
+ return np.array(sorted(set(s_idx + m_idx + e_idx)), dtype=int)
31
+
32
+
33
+ def _motion_envelope(frames):
34
+ """Exposure-invariant per-pixel 92nd-percentile motion across the clip."""
35
+ n = len(frames)
36
+ step = max(1, n // 32)
37
+ sub = frames[::step].astype(np.float32)
38
+ if len(sub) < 2:
39
+ return np.zeros(frames.shape[1:3], np.float32)
40
+ df = np.diff(sub, axis=0)
41
+ df -= np.median(df, axis=(1, 2), keepdims=True)
42
+ return np.percentile(np.abs(df).mean(-1), 92, axis=0)
43
+
44
+
45
+ def _propagate_keyframes_to_grid(kf_idx, kf_masks, frames, grid=16):
46
+ """Interpolate `(K, H, W)` bool keyframe masks onto `(N, grid, grid)` float32 occupancy.
47
+
48
+ Between keyframes, takes linear interpolation of neighboring keyframe occupancy boosted where
49
+ the intermediate frame visually departs from the static median background (captures fast mid-run
50
+ arm sweeps without blurring static table objects).
51
+ """
52
+ n = len(frames)
53
+ kf_g = np.stack([
54
+ cv2.resize(m.astype(np.float32), (grid, grid), interpolation=cv2.INTER_AREA)
55
+ for m in kf_masks
56
+ ])
57
+ if len(kf_idx) == n:
58
+ return np.clip(kf_g, 0.0, 1.0).astype(np.float32)
59
+
60
+ # Static median background at grid resolution for fast mid-frame motion boost
61
+ sub_step = max(1, n // 24)
62
+ small = np.stack([
63
+ cv2.resize(f, (grid, grid), interpolation=cv2.INTER_AREA) for f in frames
64
+ ]).astype(np.float32)
65
+ bg = np.median(small[::sub_step], axis=0)
66
+ # Normalize per-frame exposure shift before measuring departure from static background
67
+ diff_bg = small - bg[None]
68
+ diff_bg -= np.median(diff_bg, axis=(1, 2), keepdims=True)
69
+ fg_mag = np.clip(np.abs(diff_bg).mean(-1) / 28.0, 0.0, 1.0)
70
+
71
+ out = np.zeros((n, grid, grid), dtype=np.float32)
72
+ k_pos = 0
73
+ K = len(kf_idx)
74
+ for t in range(n):
75
+ while k_pos + 1 < K and kf_idx[k_pos + 1] <= t:
76
+ k_pos += 1
77
+ t0 = int(kf_idx[k_pos])
78
+ if t <= t0 or k_pos == K - 1:
79
+ out[t] = kf_g[k_pos]
80
+ continue
81
+ t1 = int(kf_idx[k_pos + 1])
82
+ a = float(t - t0) / max(t1 - t0, 1)
83
+ lin = (1.0 - a) * kf_g[k_pos] + a * kf_g[k_pos + 1]
84
+ # Union envelope between adjacent keyframes gated by actual foreground motion in frame t
85
+ env = np.maximum(kf_g[k_pos], kf_g[k_pos + 1])
86
+ # Keep keyframe mask strong near keyframes and allow smooth sweep through motion cells
87
+ swept = np.maximum(lin, env * fg_mag[t])
88
+ out[t] = np.clip(swept, 0.0, 1.0)
89
+ return out
90
+
91
+
92
+ def _strip_static_bg_bleed(m, img, f0, m0):
93
+ """Strip large static background slabs (e.g. a dark turntable or tray touching a dark arm)
94
+ that SAM 2.1 merged into a single combined mask with the robot arm.
95
+
96
+ Any large solid component (`>= 3.5%` of frame after morphological opening) outside frame-0's
97
+ robot mask (`~m0`) that still matches frame 0 pixel-for-pixel (`max|img - f0| < 18`) is
98
+ static scene background, never the moving robot arm.
99
+ """
100
+ if m0 is None or not m.any():
101
+ return m
102
+ hw = float(m.shape[0] * m.shape[1])
103
+ same0 = np.abs(img.astype(np.int16) - f0).max(-1) < 18
104
+ cand = m & (~m0) & same0
105
+ if float(cand.sum()) < 0.035 * hw:
106
+ return m
107
+ k_open = max(7, int(round(min(m.shape[:2]) * 0.032)) | 1)
108
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_open, k_open))
109
+ opened = cv2.morphologyEx(cand.astype(np.uint8), cv2.MORPH_OPEN, kern) > 0
110
+ if not opened.any():
111
+ return m
112
+ nc, lab = cv2.connectedComponents(opened.astype(np.uint8), connectivity=8)
113
+ strip = np.zeros_like(m, dtype=bool)
114
+ for ci in range(1, nc):
115
+ comp = (lab == ci)
116
+ if float(comp.sum()) >= 0.035 * hw:
117
+ grow = cv2.dilate(comp.astype(np.uint8), kern) > 0
118
+ strip |= (grow & cand)
119
+ if not strip.any():
120
+ return m
121
+ return m & (~strip)
122
+
123
+
124
+ def estimate_robot_cover(frames, grid=16, log=None, return_keyframes=False):
125
+ """Estimate `(N, grid, grid)` float32 robot-arm occupancy mask using Apache-2.0 Grounding DINO + SAM 2.1.
126
+
127
+ Uses a single batched Grounding DINO pass over ~12 keyframes + SAM 2.1 mask refinement, then
128
+ propagates cleanly to all `N` frames. Returns zeros if no robot arm is detected.
129
+ When `return_keyframes=True`, returns `(grid_cover, (kf_idx, tight_masks))` so `object_diff`
130
+ can build pixel-sharp start/end plates directly from the full-res SAM 2.1 masks without
131
+ 16x16 quantization halo loss around a stuck gripper.
132
+ """
133
+ import torch
134
+ from .world.models import _gdino, _sam2
135
+ from .world.plates import _guard_robot_dropouts, _scene_like_frame0
136
+
137
+ _log = log or (lambda _m: None)
138
+ n, h, w = frames.shape[:3]
139
+ if n < 2:
140
+ z = np.zeros((n, grid, grid), dtype=np.float32)
141
+ return (z, (np.arange(n, dtype=int), np.zeros((n, h, w), dtype=bool))) if return_keyframes else z
142
+
143
+ kf_idx = _keyframe_indices(n)
144
+ kf_imgs = [frames[k] for k in kf_idx]
145
+ run_motion = _motion_envelope(frames)
146
+ hw = float(h * w)
147
+
148
+ gd_proc, gd_mod = _gdino()
149
+ s2_proc, s2_mod = _sam2()
150
+ use_amp = gd_mod.device.type == "cuda"
151
+ prompt = "robot arm. robotic gripper."
152
+
153
+ # Single batched Grounding DINO forward pass across all keyframes
154
+ inp = gd_proc(
155
+ images=kf_imgs,
156
+ text=[prompt] * len(kf_imgs),
157
+ return_tensors="pt",
158
+ size={"shortest_edge": 384, "longest_edge": 560},
159
+ ).to(gd_mod.device)
160
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
161
+ out_gd = gd_mod(**inp)
162
+ results = gd_proc.post_process_grounded_object_detection(
163
+ out_gd, inp.input_ids, threshold=0.18, text_threshold=0.18,
164
+ target_sizes=[(h, w)] * len(kf_imgs),
165
+ )
166
+
167
+ frame_cands = []
168
+ all_top_scores = []
169
+ for res in results:
170
+ raw_boxes = res["boxes"].cpu().numpy()
171
+ raw_scores = res["scores"].cpu().numpy()
172
+ cands = []
173
+ for b, sc in sorted(zip(raw_boxes, raw_scores), key=lambda x: -x[1]):
174
+ x0, y0, x1, y1 = [int(np.clip(round(v), 0, lim)) for v, lim in zip(b, (w, h, w, h))]
175
+ if x1 <= x0 or y1 <= y0:
176
+ continue
177
+ area_frac = ((x1 - x0) * (y1 - y0)) / hw
178
+ if area_frac < 0.012 or area_frac > 0.60:
179
+ continue
180
+ mot_p85 = float(np.percentile(run_motion[y0:y1, x0:x1], 85))
181
+ mot_mean = float(run_motion[y0:y1, x0:x1].mean())
182
+ if mot_p85 < 5.0 or mot_mean < 3.5:
183
+ continue
184
+ cands.append((float(sc), [float(x0), float(y0), float(x1), float(y1)]))
185
+ if cands:
186
+ all_top_scores.append(cands[0][0])
187
+ frame_cands.append(cands)
188
+
189
+ ref_sc = float(np.percentile(all_top_scores, 85)) if all_top_scores else 0.35
190
+ score_thr = max(0.21, min(0.36, 0.58 * ref_sc))
191
+
192
+ k_dil = max(5, int(round(min(h, w) * 0.036)) | 1)
193
+ kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_dil, k_dil))
194
+ masks, raw_masks = [], []
195
+ f0, m0 = frames[kf_idx[0]].astype(np.int16), None
196
+
197
+ for k, img, cands in zip(kf_idx, kf_imgs, frame_cands):
198
+ kept = [bx for sc, bx in cands if sc >= score_thr][:4]
199
+ rmask = np.zeros((h, w), dtype=bool)
200
+ if kept:
201
+ sinp = s2_proc(images=img, input_boxes=[kept], return_tensors="pt").to(s2_mod.device)
202
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp):
203
+ sout = s2_mod(**sinp, multimask_output=True)
204
+ pm = s2_proc.post_process_masks(sout.pred_masks.float().cpu(), sinp["original_sizes"])[0]
205
+ ious = sout.iou_scores.float().cpu()[0]
206
+ for bi in range(pm.shape[0]):
207
+ bx = kept[bi]
208
+ b_area = max(1.0, (bx[2] - bx[0]) * (bx[3] - bx[1]))
209
+ got_any = False
210
+ for mi in np.argsort(-ious[bi].numpy()):
211
+ m = pm[bi, mi].numpy() > 0
212
+ if m0 is not None and _scene_like_frame0(m, img, f0, m0):
213
+ continue
214
+ if m0 is not None:
215
+ m = _strip_static_bg_bleed(m, img, f0, m0)
216
+ m_area = float(m.sum())
217
+ if m_area <= 0.0:
218
+ continue
219
+ if m_area <= 0.48 * hw and m_area <= 1.25 * b_area:
220
+ if float(ious[bi, mi]) >= 0.65 or not got_any:
221
+ rmask |= m
222
+ got_any = True
223
+ raw_masks.append(rmask)
224
+ rmask_dil = cv2.dilate(rmask.astype(np.uint8), kern, iterations=1) > 0
225
+ masks.append(rmask_dil)
226
+ if m0 is None and k == kf_idx[0] and kept:
227
+ m0 = rmask_dil
228
+
229
+ # Guard dropouts using dilated masks, then propagate UN-DILATED tight arm masks so callers
230
+ # (`spatial_diff` SPATIAL_ROBOT_RING=1 and `object_diff._upsample_rob`) dilate exactly once!
231
+ guarded = _guard_robot_dropouts(np.stack(masks), np.stack(raw_masks), frames, kf_idx)
232
+ raw_arr = np.stack(raw_masks)
233
+ # Where dropout guard forced a full-frame mask (covs < 0.015), keep the guard mask
234
+ tight_masks = np.where(guarded.reshape(len(guarded), -1).mean(1)[:, None, None] > 0.95, guarded, raw_arr)
235
+ cov = float(tight_masks.mean())
236
+ _log(f" robot mask ready ({len(kf_idx)} keyframes -> {n} frames, mean arm cover {cov * 100:.1f}%)")
237
+ grid_cov = _propagate_keyframes_to_grid(kf_idx, tight_masks, frames, grid=grid)
238
+ return (grid_cov, (kf_idx, tight_masks)) if return_keyframes else grid_cov