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,245 @@
1
+ """Object check: find a named object in every frame and compare where it ends in run A and run B.
2
+
3
+ The fingerprints follow the arm; a failure where the arm moves normally but the object ends up somewhere
4
+ else (knocked off the table) is invisible to them. Here an open-vocabulary detector (Grounding DINO tiny,
5
+ Apache-2.0) finds the object by name, and its final place in B is compared with A's.
6
+
7
+ Measured on the spinning-table runs (README): good runs end at most 0.15 picture widths apart (about 2 cube
8
+ sizes); the knocked-off cube ends 0.29 away from the nearest good end.
9
+ """
10
+ import functools
11
+
12
+ import numpy as np
13
+
14
+ # Which box is the object: score, and size and shape like the object at the start of A. Measured on the
15
+ # spinning table: the cube in the basket scores 0.27-0.39 for "cube"; the basket (15x larger) often scores more,
16
+ # and a flat strip of red tape (about as large) 0.21-0.33. Stretch = long side / short side of a box: the cube's
17
+ # boxes 1.0-1.75 (seen at an angle on the turntable it looks taller, in the basket from above square), the tape's
18
+ # 2.25-3.0, over all 28 runs.
19
+ DETECT_MIN = 0.15 # detector boxes kept (picking happens later, so thresholds can change without re-detecting)
20
+ MIN_SCORE = 0.25
21
+ SIZE_RANGE = 4.0 # area within 4x of the object's
22
+ STRETCH = 1.5 # a box may be at most 1.5x more stretched than the object at A's start (counted from 1.2)
23
+ SETTLED = 1.0 # object sizes: within this of its final place, the object has arrived there
24
+ COLOR_DIFF = 25.0 # CIE Lab chroma distance (Delta ab) above which B's object is a different color from A's
25
+
26
+
27
+ @functools.lru_cache(maxsize=1)
28
+ def _detector():
29
+ import os
30
+ os.environ.setdefault("USE_TF", "0") # PyTorch only; don't import an installed TensorFlow
31
+ from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
32
+ from .world.models import quiet_model_load, select_device
33
+ name = "IDEA-Research/grounding-dino-tiny"
34
+ dev = select_device()
35
+ with quiet_model_load():
36
+ proc = AutoProcessor.from_pretrained(name)
37
+ mod = AutoModelForZeroShotObjectDetection.from_pretrained(name)
38
+ return proc, mod.to(dev).eval()
39
+
40
+
41
+ def detect(frames, idx, query, min_score=DETECT_MIN):
42
+ """All boxes (k, 5: x0, y0, x1, y1, score) scoring above min_score for `query`, one array per frame of idx.
43
+ All, not only the best: for "cube" the basket often scores higher than the cube inside it.
44
+ ponytail: one frame per call; batches of 8 large images overflowed an 8 GB laptop GPU."""
45
+ import torch
46
+ proc, model = _detector()
47
+ text = query.strip().lower().rstrip(".") + "."
48
+ h, w = frames.shape[1:3]
49
+ out = []
50
+ for k in idx:
51
+ inp = proc(images=[frames[k]], text=[text], return_tensors="pt",
52
+ size={"shortest_edge": 480, "longest_edge": 1333}).to(model.device)
53
+ with torch.no_grad():
54
+ r = proc.post_process_grounded_object_detection(model(**inp), inp.input_ids, threshold=min_score,
55
+ text_threshold=min_score, target_sizes=[(h, w)])[0]
56
+ out.append(np.c_[r["boxes"].cpu().numpy(), r["scores"].cpu().numpy()].reshape(-1, 5))
57
+ return out
58
+
59
+
60
+ def _stretch(w, h):
61
+ w = np.maximum(w, 1e-3)
62
+ h = np.maximum(h, 1e-3)
63
+ return np.maximum(w / h, h / w)
64
+
65
+
66
+ def _crop_ab(frames, track, fps):
67
+ """Median CIE Lab (a*, b*) chroma of the inner 60% of the object's final box (ignores brightness/shadows).
68
+ Returns None on blank/synthetic all-zero frames or if no valid box exists in the last second."""
69
+ import cv2
70
+ if frames.max() == 0:
71
+ return None
72
+ tail_idx = [k for k in range(max(0, len(frames) - fps), len(frames)) if np.isfinite(track.box[k, 0])]
73
+ if not tail_idx:
74
+ return None
75
+ k = tail_idx[-1]
76
+ x0, y0, x1, y1 = track.box[k, :4]
77
+ h_img, w_img = frames.shape[1:3]
78
+ mx, my = 0.2 * (x1 - x0), 0.2 * (y1 - y0)
79
+ ix0, ix1 = max(0, int(round(x0 + mx))), min(w_img, int(round(x1 - mx)))
80
+ iy0, iy1 = max(0, int(round(y0 + my))), min(h_img, int(round(y1 - my)))
81
+ if ix1 <= ix0 or iy1 <= iy0:
82
+ return None
83
+ crop = frames[k, iy0:iy1, ix0:ix1]
84
+ lab = cv2.cvtColor(crop, cv2.COLOR_RGB2LAB).astype(np.float32)
85
+ return np.median(lab[..., 1:].reshape(-1, 2), axis=0)
86
+
87
+
88
+ class Track:
89
+ """Boxes of one object in one run, detected on demand (every `every`-th frame first, more where needed)."""
90
+
91
+ def __init__(self, frames, query, every=5, tail=5):
92
+ self.frames, self.query = frames, query
93
+ self.cands = [np.zeros((0, 5))] * len(frames)
94
+ self.done = np.zeros(len(frames), bool)
95
+ self.box = np.full((len(frames), 5), np.nan) # the picked box per frame, see pick()
96
+ self.shape = None # (area, stretch) of the object, see pick()
97
+ n = len(frames)
98
+ self.fill(sorted(set(range(0, n, every)) | set(range(max(0, n - tail), n))))
99
+
100
+ def fill(self, idx):
101
+ idx = [k for k in idx if not self.done[k]]
102
+ if idx:
103
+ for k, c in zip(idx, detect(self.frames, idx, self.query)):
104
+ self.cands[k] = c
105
+ self.done[idx] = True
106
+
107
+ def pick(self):
108
+ """Per frame the best-scoring box that looks like the object (score, size, shape); NaN where none.
109
+ ponytail: fixed size and shape; an object that turns a lot or comes close to the camera needs more."""
110
+ area, stretch = self.shape
111
+ self.box[:] = np.nan
112
+ for k, c in enumerate(self.cands):
113
+ w, h = np.maximum(c[:, 2] - c[:, 0], 1e-3), np.maximum(c[:, 3] - c[:, 1], 1e-3)
114
+ ok = (c[:, 4] >= MIN_SCORE) & (np.abs(np.log(w * h / area)) < np.log(SIZE_RANGE)) & \
115
+ (_stretch(w, h) <= max(stretch, 1.2) * STRETCH)
116
+ if ok.any():
117
+ self.box[k] = c[ok][np.argmax(c[ok, 4])]
118
+ return self.box
119
+
120
+ def centres(self):
121
+ """(N, 2) centres in pixels of the picked boxes; NaN where the object was not found."""
122
+ b = self.pick()
123
+ return np.c_[(b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2]
124
+
125
+
126
+ def target_box(frames, target):
127
+ """Best box (x0, y0, x1, y1) of the target (e.g. "basket") in the last frame, or None.
128
+ No MIN_SCORE: the basket scored only 0.21-0.27 for "basket" but was always the best box."""
129
+ c = detect(frames, [len(frames) - 1], target)[0]
130
+ return c[np.argmax(c[:, 4]), :4] if len(c) else None
131
+
132
+
133
+ def _inside(p, box):
134
+ return box is not None and box[0] <= p[0] <= box[2] and box[1] <= p[1] <= box[3]
135
+
136
+
137
+ def _iou(boxes, b):
138
+ """Overlap (intersection over union) of every box in `boxes` (k, >=4) with box b."""
139
+ w = np.clip(np.minimum(boxes[:, 2], b[2]) - np.maximum(boxes[:, 0], b[0]), 0, None)
140
+ h = np.clip(np.minimum(boxes[:, 3], b[3]) - np.maximum(boxes[:, 1], b[1]), 0, None)
141
+ area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
142
+ return w * h / (area(boxes) + area(b) - w * h)
143
+
144
+
145
+ def _moved_boxes(track, fps):
146
+ """Per checked frame of A's first 2 s, the best box that is NOT still in the same place at A's end.
147
+ The object is what the robot moves; for "cube", the basket and the turntable often score higher than
148
+ the cube at the start (spinning table: in 4 of 25 runs), but they stay where they are."""
149
+ end = [c for c in track.cands[-fps:] if len(c)]
150
+ end = np.concatenate(end) if end else np.zeros((0, 5))
151
+ out = []
152
+ for c in track.cands[:2 * fps]:
153
+ c = c[c[:, 4] >= MIN_SCORE]
154
+ moved = [b for b in c if not len(end) or _iou(end, b).max() < 0.5]
155
+ if moved:
156
+ out.append(max(moved, key=lambda b: b[4]))
157
+ return np.array(out)
158
+
159
+
160
+ def object_items(fa, fb, query, fps=10, tol=3.0, log=print, ta=None, target=None):
161
+ """Compare where `query` ends in A and in B. Returns (items, track A, track B, object size in pixels).
162
+
163
+ Items (kind OBJECT, they fail the run):
164
+ - without a target: the object ends more than `tol` object sizes away from where it ends in A;
165
+ with a target (e.g. "basket"), when it ends inside the target in A: it ends outside the target in B
166
+ (works when the target is somewhere else in B's picture). Both with the moment it got there,
167
+ refined to single frames;
168
+ - it is visible at the end of A but not at the end of B (with the moment it was last seen).
169
+ When the check passes, one item of kind OBJECT OK says so (the outcome is confirmed; see report.summary).
170
+ The object's size and shape are learned from A's first 2 s (boxes that are no longer there at A's end),
171
+ so it must be visible there and the robot must move it in A."""
172
+ ta, tb = ta or Track(fa, query), Track(fb, query) # ta: A's track, to reuse it for many B
173
+ start = _moved_boxes(ta, fps)
174
+ if not len(start):
175
+ log(f"object check: no '{query}' found at the start of A that A moves, skipped")
176
+ return [], ta, tb, None
177
+ w, h = start[:, 2] - start[:, 0], start[:, 3] - start[:, 1]
178
+ ta.shape = tb.shape = float(np.median(w * h)), float(np.median(_stretch(w, h)))
179
+ size = ta.shape[0] ** 0.5
180
+ last = lambda c: c[-fps:][np.isfinite(c[-fps:, 0])]
181
+ end_a = last(ta.centres())
182
+ cb = tb.centres()
183
+ end_b = last(cb)
184
+ if not len(end_a):
185
+ if len(end_b):
186
+ msg = f"{query} is not visible at the end of A (bad reference), but is present at the end of B"
187
+ else:
188
+ msg = f"{query} is not visible at the end of A or B (cannot confirm outcome)"
189
+ return [dict(kind="OBJECT", b_frame=len(fb) - 1, text=msg)], ta, tb, size
190
+ end_a = np.median(end_a, 0)
191
+ if not len(end_b): # gone: find the last frame where B still shows it
192
+ seen = np.flatnonzero(np.isfinite(cb[:, 0]))
193
+ if not len(seen):
194
+ return [dict(kind="OBJECT", b_frame=0, text=f"no '{query}' found anywhere in B")], ta, tb, size
195
+ k = seen[-1]
196
+ tb.fill(range(k + 1, min(k + 6, len(fb)))) # pin it down to one frame
197
+ k = np.flatnonzero(np.isfinite(tb.centres()[:, 0]))[-1]
198
+ return [dict(kind="OBJECT", b_frame=int(k), text=f"{query} is not seen at the end of B (it is in A); "
199
+ f"last seen at B {k / fps:.1f} s")], ta, tb, size
200
+ end_b = np.median(end_b, 0)
201
+ d = np.linalg.norm(end_b - end_a) / size
202
+ box_a = target_box(fa, target) if target else None
203
+ box_b = target_box(fb, target) if _inside(end_a, box_a) else None
204
+ ab_a, ab_b = _crop_ab(fa, ta, fps), _crop_ab(fb, tb, fps)
205
+ color_diff = float(np.linalg.norm(ab_a - ab_b)) if (ab_a is not None and ab_b is not None) else 0.0
206
+ place_ok = (_inside(end_b, box_b) if box_b is not None else d <= tol)
207
+ if place_ok:
208
+ where_txt = f"inside the {target}, like in A" if box_b is not None else f"{d:.1f} object sizes from where it ends in A"
209
+ if color_diff > COLOR_DIFF:
210
+ return [dict(kind="OBJECT", b_frame=len(fb) - 1, color_diff=color_diff,
211
+ text=f"{query} ends {where_txt}, but its color differs from A (Lab Δab={color_diff:.0f})")], ta, tb, size
212
+ return [dict(kind="OBJECT OK", b_frame=len(fb) - 1, text=f"{query} ends {where_txt}")], ta, tb, size
213
+ if box_b is not None: # A puts it into the target: B must too
214
+ what = f"{query} ends outside the {target} (in A it ends inside)"
215
+ else:
216
+ if target:
217
+ log(f"object check: '{target}' not found, or '{query}' not inside it in A; comparing places instead")
218
+ what = f"{query} ends {d:.1f} object sizes away from where it ends in A"
219
+ for _ in range(2): # when did it get to its final place? (refine once)
220
+ cb = tb.centres()
221
+ far = np.flatnonzero(np.linalg.norm(cb - end_b, axis=1) / size > SETTLED)
222
+ k0 = far[-1] if len(far) else 0 # last frame it was seen somewhere else
223
+ near = np.flatnonzero(np.isfinite(cb[:, 0]) & (np.arange(len(cb)) > k0))
224
+ k1 = near[0] if len(near) else len(cb) - 1 # first frame it is seen at its final place
225
+ tb.fill(range(k0 + 1, k1))
226
+ tb.pick() # boxes for draw(), including the refined frames
227
+ when = f"it arrives there at B {k1 / fps:.1f} s" + (f" (not seen, or elsewhere, since B {k0 / fps:.1f} s)"
228
+ if len(far) and k1 - k0 > 1 else "")
229
+ return [dict(kind="OBJECT", b_frame=int(k1), dist=float(d),
230
+ text=f"{what}; {when}")], ta, tb, size
231
+
232
+
233
+ def draw(frames, track, color=(20, 184, 166)):
234
+ """Copy of the frames with the object's box drawn (nearest detection within 2 frames)."""
235
+ import cv2
236
+ out = frames.copy()
237
+ found = np.flatnonzero(np.isfinite(track.box[:, 0]))
238
+ if not len(found):
239
+ return out
240
+ for k in range(len(out)):
241
+ n = found[np.argmin(np.abs(found - k))]
242
+ if abs(n - k) <= 2:
243
+ x0, y0, x1, y1 = track.box[n, :4].astype(int)
244
+ cv2.rectangle(out[k], (x0, y0), (x1, y1), color, 2)
245
+ return out