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,25 @@
1
+ """Blind 1-vs-1 World-Change Diff for fixed-camera robot videos (zero VLM, 100% Apache-2.0).
2
+
3
+ Core principle:
4
+ In any fixed-camera robot rollout, the robot arm is transient while task progress and failures
5
+ live in the persistent world (what changed between start and end outside the robot). Comparing
6
+ raw frames A_t vs B_t alarms whenever the arm shifts 3 cm; comparing fixed-pixel change maps
7
+ alarms whenever a cup or cube sits 5 cm aside.
8
+
9
+ Instead, for each video independently:
10
+ 1. Segment the moving robot arm (Grounding DINO tiny + SAM 2.1 small + adaptive per-video
11
+ confidence & motion filter, Apache-2.0).
12
+ 2. Build clean per-pixel uncovered `start_plate` and `end_plate` from the earliest / latest
13
+ still, robot-free frame per pixel (K=1 so newly placed objects are never averaged out with
14
+ earlier empty frames), with robust quiet-pixel Lab white-balance alignment and zero-cliff fill.
15
+ 3. Extract changed world blobs (`start_plate -> end_plate`) using DINOv2-reg + shadow-invariant
16
+ CIE Lab chroma + strong-contrast luminance cues.
17
+ 4. Match Policy A's world-change events to Policy B's 1-to-1 (Hungarian) by appearance
18
+ (before, after, surrounding surface context, chroma transition, size, and soft position).
19
+
20
+ Outputs objective, task-agnostic outcome diffs for ANY two blind videos:
21
+ - MISSING OUTCOME : a world change happened in A that never happened in B
22
+ - EXTRA CHANGE : a world change happened in B that did not happen in A (spill, dropped part)
23
+ - WRONG PLACE : same kind of change happened, but on a different surface/container or far away
24
+ - SAME OUTCOME : matched cleanly (info-only when shifted), ignoring arm pose & table shadows
25
+ """
@@ -0,0 +1,154 @@
1
+ """Stage 2: changed world events between the start plate and the end plate of one video."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from .config import * # noqa: F401,F403
6
+ from .models import patch_tokens_reg
7
+ from .plates import build_plates
8
+
9
+
10
+ def _cell_lab_and_edges(img):
11
+ """(H, W, 3) RGB -> (G, G, 3) Lab means and (G, G) normalized Sobel edge strength."""
12
+ im448 = cv2.resize(img, (GRID_SIZE, GRID_SIZE), interpolation=cv2.INTER_AREA)
13
+ lab = cv2.cvtColor(im448, cv2.COLOR_RGB2LAB).astype(np.float32)
14
+ gray = cv2.cvtColor(im448, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0
15
+ gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
16
+ gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
17
+ edge = np.hypot(gx, gy)
18
+ lab_g = lab.reshape(G, 14, G, 14, 3).mean((1, 3))
19
+ edge_g = edge.reshape(G, 14, G, 14).mean((1, 3))
20
+ return lab_g, edge_g
21
+
22
+
23
+ def extract_world_changes(frames, use_robot_mask=True, change_model=None, plates=None, mix="model", mask_model=None):
24
+ """Run -> clean world plates + DINOv2-reg change map + list of changed world events."""
25
+ pl = plates if plates is not None else build_plates(frames, use_robot_mask=use_robot_mask, mask_model=mask_model)
26
+ # Extract DINOv2-reg tokens for clean plates AND raw start/end frames in one single GPU batch
27
+ F = patch_tokens_reg([pl["start_plate"], pl["end_plate"], pl["raw_start"], pl["raw_end"]])
28
+ F0, F1, F_raw0, F_raw1 = F[0], F[1], F[2], F[3]
29
+
30
+ lab0, edge0 = _cell_lab_and_edges(pl["start_plate"])
31
+ lab1, edge1 = _cell_lab_and_edges(pl["end_plate"])
32
+
33
+ d_feat = np.clip(1.0 - (F0 * F1).sum(-1), 0.0, 2.0)
34
+ d_ab = np.linalg.norm(lab1[..., 1:] - lab0[..., 1:], axis=-1) / 30.0
35
+ # Strong luminance contrast with a dead-zone of 38 Lab units:
36
+ # ignores soft cast shadows (|dL| < 35) while catching neutral dark/white objects (e.g. black coffee in glass)
37
+ d_L_strong = np.clip((np.abs(lab1[..., 0] - lab0[..., 0]) - 38.0) / 70.0, 0.0, 1.0)
38
+ d_edge = np.abs(edge1 - edge0) * 3.0
39
+
40
+ v448 = cv2.resize(pl["valid_world"].astype(np.float32), (GRID_SIZE, GRID_SIZE), interpolation=cv2.INTER_AREA)
41
+ valid_cell = v448.reshape(G, 14, G, 14).mean((1, 3)) >= 0.72
42
+
43
+ # Robot-frequency cell map: dampens faint shadows/cable edges in zones where the robot frequently parked
44
+ rc448 = cv2.resize(pl["robot_cov"], (GRID_SIZE, GRID_SIZE), interpolation=cv2.INTER_AREA)
45
+ rc_cell = rc448.reshape(G, 14, G, 14).mean((1, 3))
46
+
47
+ score = np.maximum(np.maximum(d_feat, np.minimum(d_ab, 1.0)), d_L_strong)
48
+ # Shadow suppression: low chroma, low strong-L, low edge, modest DINOv2 -> shadow/glare
49
+ shadow_like = (d_feat < 0.36) & (d_ab < 0.25) & (d_L_strong < 0.15) & (d_edge < 0.24)
50
+ score = np.where(shadow_like, score * 0.25, score)
51
+ # Near frequently-visited robot zone: require stronger photometric or semantic evidence (kills faint arm halos)
52
+ arm_halo = (rc_cell > 0.22) & (d_ab < 0.28) & (d_L_strong < 0.22) & (d_feat < 0.62)
53
+ score = np.where(arm_halo, score * 0.35, score)
54
+ seed_thr, grow_thr = CELL_SEED_THR, CELL_GROW_THR
55
+ if change_model is not None: # a trained start-vs-end change map replaces or joins the hand-made one
56
+ m4 = np.asarray(change_model(pl["start_plate"], pl["end_plate"]), np.float32)
57
+ if mix == "model":
58
+ score, (seed_thr, grow_thr) = m4, (M4_SEED_THR, M4_GROW_THR)
59
+ elif mix == "min": # both must see a change
60
+ score = np.minimum(score, m4)
61
+ elif mix == "mean":
62
+ score = (score + m4) / 2
63
+ elif mix == "max": # either one is enough
64
+ score, (seed_thr, grow_thr) = np.maximum(score, m4), (M4_SEED_THR, M4_GROW_THR)
65
+ else:
66
+ raise ValueError(f"mix must be model, min, mean or max, not {mix!r}")
67
+ score = np.where(valid_cell, score, 0.0).astype(np.float32)
68
+
69
+ grow = (score >= grow_thr).astype(np.uint8)
70
+ n_cc, cc_lab = cv2.connectedComponents(grow, connectivity=8)
71
+
72
+ events = []
73
+ k_ring = np.ones((5, 5), np.uint8)
74
+ for ci in range(1, n_cc):
75
+ comp = (cc_lab == ci)
76
+ peak = float(score[comp].max())
77
+ n_cells = int(comp.sum())
78
+ mass = float(score[comp].sum())
79
+ if peak < seed_thr:
80
+ continue
81
+ if not ((peak >= MIN_EVENT_PEAK and mass >= MIN_EVENT_MASS and n_cells >= 4) or
82
+ (peak >= SMALL_HIGH_PEAK and n_cells >= 3 and mass >= 1.3)):
83
+ continue
84
+ ys, xs = np.nonzero(comp)
85
+ on_edge = (ys.min() == 0) or (ys.max() == G - 1) or (xs.min() == 0) or (xs.max() == G - 1)
86
+ # Drop tiny border jitter (<=5c) or robot-base corners touching the outer frame border,
87
+ # while NEVER dropping a real bright object (e.g. cube on turntable edge) away from the robot base.
88
+ if on_edge and (n_cells <= 5 or (float(rc_cell[comp].mean()) > 0.25 and n_cells <= 20)):
89
+ continue
90
+
91
+ ring = (cv2.dilate(comp.astype(np.uint8), k_ring, iterations=1) > 0) & (~comp) & valid_cell & (score < grow_thr)
92
+ if not ring.any():
93
+ ring = (cv2.dilate(comp.astype(np.uint8), k_ring, iterations=2) > 0) & (~comp) & valid_cell
94
+
95
+ def _norm_mean(feat_grid, mask):
96
+ v = feat_grid[mask].mean(0)
97
+ return v / max(float(np.linalg.norm(v)), 1e-8)
98
+
99
+ f_start = _norm_mean(F0, comp)
100
+ f_end = _norm_mean(F1, comp)
101
+ f_ring = _norm_mean(F1, ring) if ring.any() else f_start.copy()
102
+
103
+ bg_start = float(1.0 - np.dot(f_start, f_ring))
104
+ bg_end = float(1.0 - np.dot(f_end, f_ring))
105
+ if bg_end - bg_start > 0.18:
106
+ role = "APPEARED"
107
+ elif bg_start - bg_end > 0.18:
108
+ role = "VANISHED"
109
+ else:
110
+ role = "ALTERED"
111
+
112
+ w_sc = score[comp]
113
+ cx = float((xs * w_sc).sum() / max(w_sc.sum(), 1e-6) + 0.5) / G
114
+ cy = float((ys * w_sc).sum() / max(w_sc.sum(), 1e-6) + 0.5) / G
115
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
116
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
117
+
118
+ events.append(dict(
119
+ role=role,
120
+ f_start=f_start,
121
+ f_end=f_end,
122
+ f_ring=f_ring,
123
+ ab_start=lab0[comp, 1:].mean(0),
124
+ ab_end=lab1[comp, 1:].mean(0),
125
+ d_ab=float(d_ab[comp].mean()),
126
+ d_ab_max=float(d_ab[comp].max()),
127
+ d_L=float(np.abs(lab1[comp, 0] - lab0[comp, 0]).mean()),
128
+ bg_start=bg_start,
129
+ bg_end=bg_end,
130
+ cx=cx,
131
+ cy=cy,
132
+ n_cells=n_cells,
133
+ area=n_cells / float(G * G),
134
+ peak=peak,
135
+ mass=mass,
136
+ box=box,
137
+ mask=comp,
138
+ F0_cells=F0[comp],
139
+ F1_cells=F1[comp],
140
+ ))
141
+
142
+ events.sort(key=lambda e: -e["mass"])
143
+ return dict(
144
+ plates=pl,
145
+ score_map=score,
146
+ valid_cell=valid_cell,
147
+ F0=F0,
148
+ F1=F1,
149
+ F_raw0=F_raw0,
150
+ F_raw1=F_raw1,
151
+ lab0=lab0.astype(np.float16),
152
+ lab1=lab1.astype(np.float16),
153
+ events=events,
154
+ )
@@ -0,0 +1,139 @@
1
+ """Moving-camera guard and the end-to-end A vs B world comparison."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from .changes import extract_world_changes
6
+ from .config import * # noqa: F401,F403
7
+ from .match import match_with_refs
8
+
9
+
10
+ def _camera_motion_score(frames):
11
+ """Detect moving / wrist-mounted cameras in <20 ms on CPU via global RANSAC affine shift
12
+ on spatially stratified corners (plus phase correlation on edges).
13
+ Fixed cameras (even with huge robot arms or spinning turntables) score <= 0.005;
14
+ real wrist/gripper cameras score 0.14 - 0.25 (70x separation)."""
15
+ n = len(frames)
16
+ if n < 4:
17
+ return 0.0
18
+ step = max(1, n // 18)
19
+ idx = list(range(0, n, step))
20
+ if len(idx) < 3:
21
+ idx = list(range(n))
22
+ W = 240
23
+ h0, w0 = frames.shape[1:3]
24
+ H = max(64, round(h0 * W / w0))
25
+ norm = float(min(H, W))
26
+ hann = cv2.createHanningWindow((W, H), cv2.CV_32F)
27
+ grays = [cv2.cvtColor(cv2.resize(frames[k], (W, H), interpolation=cv2.INTER_AREA), cv2.COLOR_RGB2GRAY) for k in idx]
28
+
29
+ ransac_shifts = []
30
+ pc_shifts = []
31
+ th, tw = max(16, H // 4), max(16, W // 4)
32
+ cx, cy = W * 0.5, H * 0.5
33
+ for g0, g1 in zip(grays[:-1], grays[1:]):
34
+ e0 = np.hypot(cv2.Sobel(g0, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(g0, cv2.CV_32F, 0, 1, ksize=3))
35
+ e1 = np.hypot(cv2.Sobel(g1, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(g1, cv2.CV_32F, 0, 1, ksize=3))
36
+ (dx, dy), resp = cv2.phaseCorrelate(e0, e1, hann)
37
+ pc_shifts.append(float(np.hypot(dx, dy)) / norm if resp > 0.08 else 0.0)
38
+
39
+ pts_list = []
40
+ for r in range(4):
41
+ for c in range(4):
42
+ tile = g0[r * th:(r + 1) * th, c * tw:(c + 1) * tw]
43
+ p = cv2.goodFeaturesToTrack(tile, maxCorners=10, qualityLevel=0.03, minDistance=5)
44
+ if p is not None:
45
+ p[:, 0, 0] += c * tw
46
+ p[:, 0, 1] += r * th
47
+ pts_list.append(p)
48
+ if not pts_list:
49
+ continue
50
+ pts = np.concatenate(pts_list, axis=0)
51
+ p1, st, _ = cv2.calcOpticalFlowPyrLK(g0, g1, pts, None, winSize=(21, 21), maxLevel=3)
52
+ if p1 is None or st is None:
53
+ continue
54
+ ok = st.ravel() == 1
55
+ if int(ok.sum()) < 12:
56
+ continue
57
+ M, inl = cv2.estimateAffinePartial2D(pts[ok, 0], p1[ok, 0], method=cv2.RANSAC, ransacReprojThreshold=2.5)
58
+ if M is not None and inl is not None and int(inl.sum()) >= 8:
59
+ nx = M[0, 0] * cx + M[0, 1] * cy + M[0, 2]
60
+ ny = M[1, 0] * cx + M[1, 1] * cy + M[1, 2]
61
+ ransac_shifts.append(float(np.hypot(nx - cx, ny - cy)) / norm)
62
+
63
+ r_p80 = float(np.percentile(ransac_shifts, 80)) if ransac_shifts else 0.0
64
+ p_p80 = float(np.percentile(pc_shifts, 80)) if pc_shifts else 0.0
65
+ # Require RANSAC agreement (or strong edge shift when RANSAC also confirms camera movement)
66
+ return max(r_p80, p_p80 if r_p80 >= 0.020 else 0.0)
67
+
68
+
69
+ def _median_edge_kept(frames):
70
+ """Share of the frames' edge strength that survives in the per-pixel median over the video. A fixed camera keeps
71
+ its background edges (0.62 to 0.95 measured on 17 laptop cameras, also a blank sheet); a moving camera blurs them
72
+ (wrist 0.48). Also checks the top 65% alone so static bottom-mounted white gripper jaws cannot inflate the score."""
73
+ if len(frames) < 4:
74
+ return 1.0
75
+ idx = np.linspace(0, len(frames) - 1, min(len(frames), 24)).astype(int)
76
+ g = np.stack([cv2.cvtColor(cv2.resize(frames[k], (240, 180), interpolation=cv2.INTER_AREA), cv2.COLOR_RGB2GRAY)
77
+ for k in idx]).astype(np.float32)
78
+ edge = lambda x: float(np.hypot(cv2.Sobel(x, cv2.CV_32F, 1, 0), cv2.Sobel(x, cv2.CV_32F, 0, 1)).mean())
79
+ kept_full = edge(np.median(g, 0)) / max(float(np.mean([edge(x) for x in g])), 1e-6)
80
+ top = g[:, :117, :] # top 65%: excludes static bottom gripper jaws
81
+ kept_top = edge(np.median(top, 0)) / max(float(np.mean([edge(x) for x in top])), 1e-6)
82
+ return min(kept_full, kept_top)
83
+
84
+
85
+ def moving_camera(frames):
86
+ """(moving?, global shift, median edges kept): checks full frame AND top 65% (plus a wider 7-frame stride on
87
+ top 65% for slow wrist cameras) so static bottom-mounted gripper jaws can neither drag down RANSAC shift nor
88
+ inflate median edge preservation, while blank upper walls on fixed cameras stay untouched."""
89
+ s_full = _camera_motion_score(frames)
90
+ h = frames.shape[1]
91
+ top65 = frames[:, :max(32, int(h * 0.65))] if h >= 48 else frames
92
+ s_top = _camera_motion_score(top65)
93
+ idx7 = np.linspace(0, len(frames) - 1, min(len(frames), 7)).astype(int)
94
+ s_wide = _camera_motion_score(top65[idx7]) if len(frames) >= 7 else 0.0
95
+ # When full-frame RANSAC is rock-solid static (<0.008), only trust top65 if it also moves consistently step-to-step
96
+ if s_full >= 0.008:
97
+ shift = max(s_full, s_top, 0.5 * s_wide)
98
+ else:
99
+ shift = max(s_full, s_top if s_top >= MOVING_CAM_THR else 0.0)
100
+ kept = _median_edge_kept(frames) if shift >= MOVING_CAM_THR else 1.0
101
+ hard = (s_full >= MOVING_CAM_HARD_THR) or (
102
+ s_full >= 0.008 and shift >= MOVING_CAM_HARD_THR and (s_wide >= 0.16 or kept < 0.72)
103
+ )
104
+ is_mv = hard or (shift >= MOVING_CAM_THR and kept < MEDIAN_KEPT_THR)
105
+ return is_mv, shift, kept
106
+
107
+
108
+ def compare_world(fa, fb, use_robot_mask=True, goods=(), change_model=None, mask_model=None, match_model=None):
109
+ """End-to-end blind world-change comparison of B against A (plus optional more good runs `goods`)."""
110
+ mv_a, cm_a, kept_a = moving_camera(fa)
111
+ mv_b, cm_b, kept_b = moving_camera(fb)
112
+ cm_max = max(cm_a if mv_a else 0.0, cm_b if mv_b else 0.0)
113
+ if mv_a or mv_b:
114
+ return dict(
115
+ findings=[dict(
116
+ kind="SETUP DIFF",
117
+ score=round(min(1.0, cm_max * 3.0), 2),
118
+ box=None,
119
+ info=True,
120
+ detail=f"moving / wrist camera detected (camera shift {cm_max*100:.1f}%/step, background edges kept "
121
+ f"{min(kept_a, kept_b):.2f}) — "
122
+ f"--world-diff requires a fixed camera; use an overhead or third-person camera",
123
+ )],
124
+ flagged=False,
125
+ score=0.0,
126
+ heat_end=np.zeros((G, G), np.float32),
127
+ matched=[],
128
+ world_a=None,
129
+ world_b=None,
130
+ cam_motion=(cm_a, cm_b),
131
+ )
132
+ kw = dict(use_robot_mask=use_robot_mask, change_model=change_model, mask_model=mask_model)
133
+ wa, wb = extract_world_changes(fa, **kw), extract_world_changes(fb, **kw)
134
+ wg = [extract_world_changes(g, **kw) for g in goods]
135
+ res = match_with_refs([wa] + wg, wb, match_model=match_model)
136
+ res["world_a"] = wa
137
+ res["world_b"] = wb
138
+ res["cam_motion"] = (cm_a, cm_b)
139
+ return res
@@ -0,0 +1,28 @@
1
+ """Task-agnostic thresholds of the world diff (cosine / Lab / 32 x 32 grid units)."""
2
+ GRID_SIZE = 448 # 32x32 DINOv2-reg patch grid (14 px patches)
3
+ G = GRID_SIZE // 14
4
+
5
+ # Task-agnostic thresholds (cosine / Lab / 32x32 grid units)
6
+ CELL_SEED_THR = 0.42 # seed cell change score for hysteresis blob extraction
7
+ CELL_GROW_THR = 0.28 # grow connected blob down to this cell score
8
+ MIN_EVENT_PEAK = 0.46 # minimum peak change score for a real world event
9
+ MIN_EVENT_MASS = 2.20 # minimum integrated score mass (drops tiny shadow/cable specks)
10
+ SMALL_HIGH_PEAK = 0.52 # allows compact crisp objects (e.g. filled glass cup or screw, 3+ cells)
11
+
12
+ MATCH_MAX_COST = 1.20 # max 1-to-1 Hungarian cost to treat two changes as the same event
13
+ END_APPEAR_MAX = 0.62 # max end-appearance DINOv2 distance (stops spill matching a pitcher)
14
+ CHROMA_DELTA_MAX = 0.35 # max difference in chroma-change magnitude (catches colorful spills)
15
+ RING_DIFF_THR = 0.44 # surrounding-surface DINOv2 distance above which -> WRONG PLACE
16
+ FAR_SHIFT_THR = 0.30 # normalized frame distance + moderate ring diff -> WRONG PLACE
17
+ AREA_EXPAND_RATIO = 2.3 # B blob >= 2.3x A blob (+ novel excess cells) -> EXTRA CHANGE (spill/mess)
18
+ MIN_EXCESS_CELLS = 14 # minimum extra 32x32 cells (~1.4% of frame) for expansion flag
19
+ SHIFT_INFO_THR = 0.07 # matched shift above 7% of frame logged as info-only SAME OUTCOME
20
+ MOVING_CAM_THR = 0.035 # global RANSAC/edge camera shift per step above which camera is moving/wrist-mounted
21
+ MOVING_CAM_HARD_THR = 0.13 # extreme global camera shift (>=13%/step): moving even if static gripper keeps median edges
22
+ MEDIAN_KEPT_THR = 0.55 # second camera vote: moving if the video median keeps less of the edges than this
23
+ SCENE_PIECE_SAME = 0.70 # a SAM 'robot' piece that matches frame 0's scene this much is scene (tray), not robot
24
+ HALO_FRAC = 0.044 # ring (share of the short side) around the robot never filled from moving pixels
25
+ ROBOT_LEFT_CHECK = False # experimental: keep end frames where the arm seems to have left the view (see plates.py)
26
+ TRACK_MAX = 2 # objects per run followed with SAM 2.1 video (largest first)
27
+ M4_SEED_THR = 0.50 # with a trained change map: seed / grow levels are the model's chance
28
+ M4_GROW_THR = 0.30