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.
- diffvid-1.0.1.dist-info/METADATA +275 -0
- diffvid-1.0.1.dist-info/RECORD +38 -0
- diffvid-1.0.1.dist-info/WHEEL +5 -0
- diffvid-1.0.1.dist-info/entry_points.txt +2 -0
- diffvid-1.0.1.dist-info/licenses/LICENSE +202 -0
- diffvid-1.0.1.dist-info/licenses/NOTICE +5 -0
- diffvid-1.0.1.dist-info/top_level.txt +1 -0
- rollout_diff/__init__.py +169 -0
- rollout_diff/__main__.py +5 -0
- rollout_diff/_locotrack/__init__.py +1 -0
- rollout_diff/_locotrack/cmdtop.py +47 -0
- rollout_diff/_locotrack/locotrack_model.py +1077 -0
- rollout_diff/_locotrack/nets.py +429 -0
- rollout_diff/_locotrack/utils.py +301 -0
- rollout_diff/arm_diff.py +324 -0
- rollout_diff/batch.py +692 -0
- rollout_diff/cli.py +475 -0
- rollout_diff/core.py +879 -0
- rollout_diff/explain.py +538 -0
- rollout_diff/export.py +215 -0
- rollout_diff/hub.py +207 -0
- rollout_diff/object_diff.py +672 -0
- rollout_diff/objects.py +245 -0
- rollout_diff/objlog.py +903 -0
- rollout_diff/point_diff.py +221 -0
- rollout_diff/profile.py +215 -0
- rollout_diff/report.py +758 -0
- rollout_diff/robot_mask.py +238 -0
- rollout_diff/teach.py +1374 -0
- rollout_diff/world/__init__.py +25 -0
- rollout_diff/world/changes.py +154 -0
- rollout_diff/world/compare.py +139 -0
- rollout_diff/world/config.py +28 -0
- rollout_diff/world/match.py +458 -0
- rollout_diff/world/models.py +214 -0
- rollout_diff/world/plates.py +312 -0
- rollout_diff/world/track.py +301 -0
- rollout_diff/world_diff.py +11 -0
rollout_diff/objlog.py
ADDED
|
@@ -0,0 +1,903 @@
|
|
|
1
|
+
"""Object log: what happened to every object the robot moved, followed with SAM 2.1 or SAM 3.
|
|
2
|
+
|
|
3
|
+
run_log(frames, s, arm_end, fps=10, tracker="sam2") one record per object of one run:
|
|
4
|
+
forward - things whose own start pixels changed by the end are cut out on the robot-free start picture
|
|
5
|
+
(SAM 2.1 point prompts or SAM 3 concept/box-grounded masks) and followed forward: when each
|
|
6
|
+
moved, where it ended (box, oriented shape, end DINO look), or when it was lost from view,
|
|
7
|
+
and whether the arm still holds it at the end.
|
|
8
|
+
backward - new things in the end picture (changed cells + small pixel spots), not the robot, are cut out
|
|
9
|
+
and followed back in time: when each arrived.
|
|
10
|
+
teach_objects(logs, zones=None) match objects across good runs by look; per object learn whether it moves,
|
|
11
|
+
which taught ROI (zone) it normally lands in, where it ends (relative to another object,
|
|
12
|
+
start-frame anchor, ROI, or tabletop spots), its oriented end shape & end look, and where
|
|
13
|
+
new things normally appear.
|
|
14
|
+
check_objects(taught, log, zones=None, zone_failed=None)
|
|
15
|
+
Failures (red): NOT MOVED, NOT PLACED, DROPPED, STILL HELD, WRONG POSE, EXTRA.
|
|
16
|
+
Differences (amber): SLIGHT SHIFT, POSE DIFF (minor shift/tilt that is not a task failure).
|
|
17
|
+
"""
|
|
18
|
+
import contextlib
|
|
19
|
+
import gc
|
|
20
|
+
import cv2
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from . import report as R
|
|
24
|
+
from . import teach as T
|
|
25
|
+
|
|
26
|
+
KINDS = {"NOT MOVED": "#b91c1c", "NOT PLACED": "#ea580c", "DROPPED": "#be123c", "STILL HELD": "#9333ea",
|
|
27
|
+
"WRONG POSE": "#0e7490", "EXTRA": "#ca8a04"}
|
|
28
|
+
DIFF_KINDS = {"SLIGHT SHIFT": "#d97706", "POSE DIFF": "#0284c7"}
|
|
29
|
+
R.COLORS.update(KINDS)
|
|
30
|
+
R.COLORS.update(DIFF_KINDS)
|
|
31
|
+
R.FAILS.update(KINDS)
|
|
32
|
+
|
|
33
|
+
MAX_OBJ = 8 # objects followed per direction (keeps GPU memory bounded)
|
|
34
|
+
STEP = 2 # base stride (5 fps at 10 fps)
|
|
35
|
+
MAX_TRACK_FRAMES = 80 # adaptive cap on followed frames per video pass (prevents OOM on long clips)
|
|
36
|
+
SOLID = 0.22 # a mask counts as "seen" at >= 22 % of its first area
|
|
37
|
+
NEW_SHARE = 0.5 # a thing is new / gone when half its own pixels differ between start and end
|
|
38
|
+
ARRIVE_MIN = 1.0 # something "arriving" in the first second was there from the start
|
|
39
|
+
MATCH_MIN = 0.5 # cosine of two object looks to count as the same object across runs
|
|
40
|
+
MARGIN = 1.5 # leave-one-out bars are the worst good run times this
|
|
41
|
+
SHAPE_TOL = 1.4 # legacy axis-aligned h/w tolerance (used for mild / extreme flip checks)
|
|
42
|
+
ELONG_FAIL_TOL = 1.8 # rotation-invariant elongation factor required for WRONG POSE failure
|
|
43
|
+
ELONG_DIFF_TOL = 1.5 # milder elongation factor -> amber POSE DIFF (difference, not failure)
|
|
44
|
+
PLACE_FLOOR = 0.055 # minimum tabletop placement bar when rel is None (prevents razor-thin bars)
|
|
45
|
+
SHIFT_MULT = 1.8 # small overshoot up to this multiple of bar -> amber SLIGHT SHIFT
|
|
46
|
+
SAM3_SCORE = 0.32 # minimum SAM 3 confidence score for concept-detected objects
|
|
47
|
+
EXTRA_SCORE = 0.45 # minimum mask confidence to emit an EXTRA / NOT MOVED failure
|
|
48
|
+
DROP_SCORE = 0.60 # minimum mask confidence to emit an external DROPPED when target ROI failed
|
|
49
|
+
DROP_MAX_JUMP = 0.25 # maximum single-step centroid jump for a smooth physical fall/drop track
|
|
50
|
+
HELD_COVER = 0.55 # minimum end-arm mask coverage for STILL HELD
|
|
51
|
+
ID_SWITCH_JUMP = 0.60 # single-step centroid jump threshold for SAM ID-switch guard
|
|
52
|
+
EDGE_SLIVER_MAX = 0.06 # max perpendicular depth of thin frame-border artifacts
|
|
53
|
+
END_LOOK_CAP = 0.85 # upper cap on anchor end_look cosine bar (avoids razor-thin 0.91 bars)
|
|
54
|
+
SAM3_PROMPTS = ("object", "utensil or tool or screw or part")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------- geometry & ROI helpers
|
|
58
|
+
def _box(m):
|
|
59
|
+
ys, xs = np.nonzero(m)
|
|
60
|
+
h, w = m.shape
|
|
61
|
+
return [float(xs.min() / w), float(ys.min() / h), float((xs.max() + 1) / w), float((ys.max() + 1) / h)]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
ctr = lambda b: (0.5 * (b[0] + b[2]), 0.5 * (b[1] + b[3]))
|
|
65
|
+
size = lambda b: max(b[2] - b[0], b[3] - b[1])
|
|
66
|
+
dist = lambda p, q: float(np.hypot(p[0] - q[0], p[1] - q[1]))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _iou(a, b):
|
|
70
|
+
ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
|
|
71
|
+
iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
|
|
72
|
+
u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - ix * iy
|
|
73
|
+
return ix * iy / max(u, 1e-9)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _touches(a, b, pad=0.015):
|
|
77
|
+
return (min(a[2], b[2]) - max(a[0], b[0]) >= -pad) and (min(a[3], b[3]) - max(a[1], b[1]) >= -pad)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _edge_sliver(box, max_depth=EDGE_SLIVER_MAX):
|
|
81
|
+
"""True for thin masks wedged against the camera border (cable/arm-base/edge flicker, not a real object)."""
|
|
82
|
+
x0, y0, x1, y1 = box
|
|
83
|
+
w, h = x1 - x0, y1 - y0
|
|
84
|
+
return ((y0 <= 0.005 and h <= max_depth) or (y1 >= 0.995 and h <= max_depth)
|
|
85
|
+
or (x0 <= 0.005 and w <= max_depth) or (x1 >= 0.995 and w <= max_depth))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _max_jump(path):
|
|
89
|
+
"""Largest single-step centroid jump along a tracked path."""
|
|
90
|
+
if not path or len(path) < 2:
|
|
91
|
+
return 0.0
|
|
92
|
+
return max((dist(a, b) for a, b in zip(path[:-1], path[1:]) if a and b), default=0.0)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _is_id_switch(o, fwd_objs):
|
|
96
|
+
"""True when a tracker jumped across most of the frame in one step and latched onto another tracked object."""
|
|
97
|
+
j = _max_jump(o.get("path"))
|
|
98
|
+
if j < ID_SWITCH_JUMP:
|
|
99
|
+
return False
|
|
100
|
+
for q in fwd_objs:
|
|
101
|
+
if q is o or q.get("lost"):
|
|
102
|
+
continue
|
|
103
|
+
if _iou(o["end"], q["end"]) >= 0.65:
|
|
104
|
+
qj = _max_jump(q.get("path"))
|
|
105
|
+
if qj + 0.15 < j or float(q.get("score", 0.0)) > float(o.get("score", 0.0)) + 0.05:
|
|
106
|
+
return True
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _cover(box, mask):
|
|
111
|
+
"""Share of the box covered by a (H, W) bool mask."""
|
|
112
|
+
h, w = mask.shape
|
|
113
|
+
x0, y0 = int(box[0] * w), int(box[1] * h)
|
|
114
|
+
crop = mask[y0:max(y0 + 1, int(np.ceil(box[3] * h))), x0:max(x0 + 1, int(np.ceil(box[2] * w)))]
|
|
115
|
+
return float(crop.mean()) if crop.size else 0.0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _shape(b, h, w):
|
|
119
|
+
return float((b[3] - b[1]) * h / max(1e-6, (b[2] - b[0]) * w))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _mask_elong(m, fallback_shape=1.0):
|
|
123
|
+
"""Rotation-invariant major/minor elongation (>= 1.0) from minAreaRect of a bool mask."""
|
|
124
|
+
if m is not None:
|
|
125
|
+
ys, xs = np.nonzero(m)
|
|
126
|
+
if xs.size >= 5:
|
|
127
|
+
pts = np.stack([xs, ys], axis=1).astype(np.float32)
|
|
128
|
+
(_, (rw, rh), _) = cv2.minAreaRect(pts)
|
|
129
|
+
lo, hi = min(rw, rh), max(rw, rh)
|
|
130
|
+
return float(max(hi, 1.0) / max(lo, 1.0))
|
|
131
|
+
s = max(float(fallback_shape), 1e-4)
|
|
132
|
+
return float(max(s, 1.0 / s))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _eff_step(n, step=STEP):
|
|
136
|
+
"""Adaptive stride capping tracked frames at MAX_TRACK_FRAMES so long clips never OOM."""
|
|
137
|
+
if n <= 1:
|
|
138
|
+
return 1
|
|
139
|
+
if n <= MAX_TRACK_FRAMES:
|
|
140
|
+
return max(1, int(step))
|
|
141
|
+
return max(int(step), int(np.ceil((n - 1) / MAX_TRACK_FRAMES)))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _in_zone(box_or_pt, zm, dilate=0):
|
|
145
|
+
"""Whether a normalized box [x0,y0,x1,y1] or point (x,y) lands inside a (G, G) bool zone mask."""
|
|
146
|
+
zm = np.asarray(zm, dtype=bool)
|
|
147
|
+
if not zm.any():
|
|
148
|
+
return False
|
|
149
|
+
if dilate > 0:
|
|
150
|
+
k = 2 * dilate + 1
|
|
151
|
+
zm = cv2.dilate(zm.astype(np.uint8), np.ones((k, k), np.uint8)) > 0
|
|
152
|
+
g = zm.shape[0]
|
|
153
|
+
if len(box_or_pt) == 2:
|
|
154
|
+
c = min(g - 1, max(0, int(box_or_pt[0] * g)))
|
|
155
|
+
r = min(g - 1, max(0, int(box_or_pt[1] * g)))
|
|
156
|
+
return bool(zm[r, c])
|
|
157
|
+
x0, y0, x1, y1 = box_or_pt
|
|
158
|
+
cx, cy = ctr(box_or_pt)
|
|
159
|
+
cr = min(g - 1, max(0, int(cy * g)))
|
|
160
|
+
cc = min(g - 1, max(0, int(cx * g)))
|
|
161
|
+
if zm[cr, cc]:
|
|
162
|
+
return True
|
|
163
|
+
r0, r1 = max(0, int(y0 * g)), min(g, max(int(y0 * g) + 1, int(np.ceil(y1 * g))))
|
|
164
|
+
c0, c1 = max(0, int(x0 * g)), min(g, max(int(x0 * g) + 1, int(np.ceil(x1 * g))))
|
|
165
|
+
sub = zm[r0:r1, c0:c1]
|
|
166
|
+
return bool(sub.size and float(sub.mean()) >= 0.25)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _zone_of(box_or_pt, zones, dilate=0):
|
|
170
|
+
"""Best matching zone index (0-based) for a normalized box or point, or None."""
|
|
171
|
+
if zones is None or len(zones) == 0:
|
|
172
|
+
return None
|
|
173
|
+
best_z, best_ov = None, 0.0
|
|
174
|
+
for z, zm in enumerate(zones):
|
|
175
|
+
zm_b = np.asarray(zm, dtype=bool)
|
|
176
|
+
if dilate > 0:
|
|
177
|
+
k = 2 * dilate + 1
|
|
178
|
+
zm_b = cv2.dilate(zm_b.astype(np.uint8), np.ones((k, k), np.uint8)) > 0
|
|
179
|
+
if not _in_zone(box_or_pt, zm_b, dilate=0):
|
|
180
|
+
continue
|
|
181
|
+
if len(box_or_pt) == 2:
|
|
182
|
+
return z
|
|
183
|
+
g = zm_b.shape[0]
|
|
184
|
+
x0, y0, x1, y1 = box_or_pt
|
|
185
|
+
r0, r1 = max(0, int(y0 * g)), min(g, max(int(y0 * g) + 1, int(np.ceil(y1 * g))))
|
|
186
|
+
c0, c1 = max(0, int(x0 * g)), min(g, max(int(x0 * g) + 1, int(np.ceil(x1 * g))))
|
|
187
|
+
ov = float(zm_b[r0:r1, c0:c1].mean()) if (r1 > r0 and c1 > c0) else 1.0
|
|
188
|
+
if ov > best_ov:
|
|
189
|
+
best_z, best_ov = z, ov
|
|
190
|
+
return best_z
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _dedup_scored(cand):
|
|
194
|
+
"""NMS over (score, mask) candidates, keeping highest confidence first."""
|
|
195
|
+
keep = []
|
|
196
|
+
for sc, m in sorted(cand, key=lambda x: -x[0]):
|
|
197
|
+
if all((m & k).sum() < 0.5 * min(m.sum(), k.sum()) for _, k in keep):
|
|
198
|
+
keep.append((float(sc), m))
|
|
199
|
+
return keep
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# ---------------------------------------------------------------- per run: SAM 2.1 / SAM 3 cut & follow
|
|
203
|
+
def _cut_sam2(img, pts, near, min_frac=0.0003, max_frac=0.05):
|
|
204
|
+
"""One SAM 2.1 point prompt per point -> de-duplicated (score, mask) single-object masks."""
|
|
205
|
+
import torch
|
|
206
|
+
from .world.models import _sam2
|
|
207
|
+
if not pts:
|
|
208
|
+
return []
|
|
209
|
+
proc, mod = _sam2()
|
|
210
|
+
cand = []
|
|
211
|
+
for i0 in range(0, len(pts), 64):
|
|
212
|
+
chunk = pts[i0:i0 + 64]
|
|
213
|
+
inp = proc(images=img, input_points=[[[p] for p in chunk]], input_labels=[[[1]] * len(chunk)],
|
|
214
|
+
return_tensors="pt").to(mod.device)
|
|
215
|
+
with torch.no_grad():
|
|
216
|
+
out = mod(**inp, multimask_output=True)
|
|
217
|
+
pm = proc.post_process_masks(out.pred_masks.float().cpu(), inp["original_sizes"])[0] > 0
|
|
218
|
+
ious = out.iou_scores.float().cpu()[0]
|
|
219
|
+
del inp, out
|
|
220
|
+
for p in range(pm.shape[0]):
|
|
221
|
+
for k in np.argsort(-ious[p].numpy()):
|
|
222
|
+
m = pm[p, k].numpy()
|
|
223
|
+
if min_frac <= m.mean() <= max_frac and (m & near).sum() >= 0.6 * m.sum():
|
|
224
|
+
cand.append((float(ious[p, k]), m))
|
|
225
|
+
break
|
|
226
|
+
if torch.cuda.is_available():
|
|
227
|
+
torch.cuda.empty_cache()
|
|
228
|
+
return _dedup_scored(cand)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _cut_sam3(img, pts, near, min_frac=0.0003, max_frac=0.05, score_thr=SAM3_SCORE):
|
|
232
|
+
"""Concept-grounded SAM 3 detection + box-exemplar rescue on uncovered changed regions -> (score, mask)."""
|
|
233
|
+
import torch
|
|
234
|
+
from PIL import Image
|
|
235
|
+
from .world.models import _sam3
|
|
236
|
+
h, w = img.shape[:2]
|
|
237
|
+
if not near.any():
|
|
238
|
+
return []
|
|
239
|
+
proc, _, dev = _sam3()
|
|
240
|
+
amp = torch.autocast("cuda", dtype=torch.bfloat16) if dev == "cuda" else contextlib.nullcontext()
|
|
241
|
+
cand = []
|
|
242
|
+
pil_img = Image.fromarray(img)
|
|
243
|
+
|
|
244
|
+
def collect(state, min_sc, near_req):
|
|
245
|
+
masks_t = state.get("masks")
|
|
246
|
+
scores_t = state.get("scores")
|
|
247
|
+
if masks_t is None or scores_t is None or len(scores_t) == 0:
|
|
248
|
+
return
|
|
249
|
+
masks_np = masks_t.detach().cpu().numpy()
|
|
250
|
+
scores_np = scores_t.detach().float().cpu().numpy()
|
|
251
|
+
for m, sc in zip(masks_np, scores_np):
|
|
252
|
+
if float(sc) < min_sc:
|
|
253
|
+
continue
|
|
254
|
+
mb = m[0] if m.ndim == 3 else m
|
|
255
|
+
if mb.shape != (h, w):
|
|
256
|
+
mb = cv2.resize(mb.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) > 0
|
|
257
|
+
else:
|
|
258
|
+
mb = mb.astype(bool)
|
|
259
|
+
area = int(mb.sum())
|
|
260
|
+
if area == 0:
|
|
261
|
+
continue
|
|
262
|
+
frac = area / float(h * w)
|
|
263
|
+
if min_frac <= frac <= max_frac and (mb & near).sum() >= near_req * area:
|
|
264
|
+
cand.append((float(sc), mb))
|
|
265
|
+
|
|
266
|
+
with torch.inference_mode(), amp:
|
|
267
|
+
proc.set_confidence_threshold(min(score_thr, 0.25))
|
|
268
|
+
state = proc.set_image(pil_img)
|
|
269
|
+
for prompt in SAM3_PROMPTS:
|
|
270
|
+
proc.reset_all_prompts(state)
|
|
271
|
+
st = proc.set_text_prompt(prompt, state)
|
|
272
|
+
collect(st, score_thr, 0.55)
|
|
273
|
+
kept_so_far = _dedup_scored(cand)
|
|
274
|
+
covered = np.zeros((h, w), bool)
|
|
275
|
+
for _, km in kept_so_far:
|
|
276
|
+
covered |= km
|
|
277
|
+
# Rescue small / unusual changed blobs missed by text concepts via SAM 3 geometric box prompts
|
|
278
|
+
nc, lab, stats, _ = cv2.connectedComponentsWithStats(near.astype(np.uint8), 8)
|
|
279
|
+
for cid in range(1, nc):
|
|
280
|
+
comp = lab == cid
|
|
281
|
+
area = int(stats[cid, cv2.CC_STAT_AREA])
|
|
282
|
+
if area < max(16, int(0.5 * min_frac * h * w)) or area > int(3.0 * max_frac * h * w):
|
|
283
|
+
continue
|
|
284
|
+
if (comp & covered).sum() >= 0.25 * area:
|
|
285
|
+
continue
|
|
286
|
+
x0, y0 = stats[cid, cv2.CC_STAT_LEFT], stats[cid, cv2.CC_STAT_TOP]
|
|
287
|
+
bw, bh = stats[cid, cv2.CC_STAT_WIDTH], stats[cid, cv2.CC_STAT_HEIGHT]
|
|
288
|
+
box_cxcywh = [float((x0 + 0.5 * bw) / w), float((y0 + 0.5 * bh) / h),
|
|
289
|
+
float(max(bw / w, 0.02)), float(max(bh / h, 0.02))]
|
|
290
|
+
proc.reset_all_prompts(state)
|
|
291
|
+
st = proc.add_geometric_prompt(box=box_cxcywh, label=True, state=state)
|
|
292
|
+
collect(st, max(score_thr + 0.05, 0.35), 0.60)
|
|
293
|
+
del state
|
|
294
|
+
return _dedup_scored(cand)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _cut(img, pts, near, min_frac=0.0003, max_frac=0.05, tracker="sam2"):
|
|
298
|
+
if tracker == "sam3":
|
|
299
|
+
return _cut_sam3(img, pts, near, min_frac=min_frac, max_frac=max_frac)
|
|
300
|
+
return _cut_sam2(img, pts, near, min_frac=min_frac, max_frac=max_frac)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _follow_sam2(frames, masks, step=STEP):
|
|
304
|
+
"""All objects in one SAM 2.1 video pass -> (idx, per-object tracks, last non-empty mask per object)."""
|
|
305
|
+
import torch
|
|
306
|
+
from .world.models import _sam2_video
|
|
307
|
+
n, h, w = frames.shape[:3]
|
|
308
|
+
eff = _eff_step(n, step)
|
|
309
|
+
idx = list(range(0, n, eff)) + ([n - 1] if (n - 1) % eff else [])
|
|
310
|
+
proc, mod, dev, dtype = _sam2_video()
|
|
311
|
+
ids = list(range(len(masks)))
|
|
312
|
+
track = {i: [] for i in ids}
|
|
313
|
+
last_masks = {i: masks[i].astype(bool) for i in ids}
|
|
314
|
+
with torch.inference_mode():
|
|
315
|
+
sess = proc.init_video_session(
|
|
316
|
+
video=frames[idx],
|
|
317
|
+
inference_device=dev,
|
|
318
|
+
processing_device="cpu",
|
|
319
|
+
video_storage_device="cpu",
|
|
320
|
+
inference_state_device=dev,
|
|
321
|
+
dtype=dtype,
|
|
322
|
+
)
|
|
323
|
+
try:
|
|
324
|
+
proc.add_inputs_to_inference_session(sess, frame_idx=0, obj_ids=list(ids), input_masks=[m.astype(np.float32) for m in masks])
|
|
325
|
+
for out in mod.propagate_in_video_iterator(sess, start_frame_idx=0):
|
|
326
|
+
ms = proc.post_process_masks([out.pred_masks], original_sizes=[(h, w)], binarize=True)[0]
|
|
327
|
+
for k, i in enumerate(sess.obj_ids):
|
|
328
|
+
m = ms[k, 0].cpu().numpy().astype(bool)
|
|
329
|
+
a = int(m.sum())
|
|
330
|
+
track[int(i)].append((_box(m) if a else None, a))
|
|
331
|
+
if a:
|
|
332
|
+
last_masks[int(i)] = m
|
|
333
|
+
finally:
|
|
334
|
+
try:
|
|
335
|
+
sess.reset_inference_session()
|
|
336
|
+
except Exception:
|
|
337
|
+
pass
|
|
338
|
+
del sess
|
|
339
|
+
gc.collect()
|
|
340
|
+
if torch.cuda.is_available():
|
|
341
|
+
torch.cuda.empty_cache()
|
|
342
|
+
return idx, [track[i] for i in ids], [last_masks[i] for i in ids]
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _follow_sam3(frames, masks, step=STEP):
|
|
346
|
+
"""All objects in one SAM 3 video pass -> (idx, per-object tracks, last non-empty mask per object)."""
|
|
347
|
+
import torch
|
|
348
|
+
from .world.models import _sam3
|
|
349
|
+
n, h, w = frames.shape[:3]
|
|
350
|
+
eff = _eff_step(n, step)
|
|
351
|
+
idx = list(range(0, n, eff)) + ([n - 1] if (n - 1) % eff else [])
|
|
352
|
+
_, tracker, dev = _sam3()
|
|
353
|
+
img_sz = int(getattr(tracker, "image_size", 1008))
|
|
354
|
+
ids = list(range(len(masks)))
|
|
355
|
+
track = {i: [] for i in ids}
|
|
356
|
+
last_masks = {i: masks[i].astype(bool) for i in ids}
|
|
357
|
+
|
|
358
|
+
# Build CPU float16 normalized video tensor matching SAM 3 load_video_frames (mean=0.5, std=0.5)
|
|
359
|
+
images = torch.empty((len(idx), 3, img_sz, img_sz), dtype=torch.float16)
|
|
360
|
+
for t_i, f_i in enumerate(idx):
|
|
361
|
+
rs = cv2.resize(frames[f_i], (img_sz, img_sz), interpolation=cv2.INTER_LINEAR)
|
|
362
|
+
ten = torch.from_numpy(rs).permute(2, 0, 1).to(dtype=torch.float16)
|
|
363
|
+
images[t_i] = (ten / 255.0 - 0.5) / 0.5
|
|
364
|
+
|
|
365
|
+
amp = torch.autocast("cuda", dtype=torch.bfloat16) if dev == "cuda" else contextlib.nullcontext()
|
|
366
|
+
st = None
|
|
367
|
+
with torch.inference_mode(), amp:
|
|
368
|
+
try:
|
|
369
|
+
st = tracker.init_state(
|
|
370
|
+
video_height=h,
|
|
371
|
+
video_width=w,
|
|
372
|
+
num_frames=len(idx),
|
|
373
|
+
offload_video_to_cpu=True,
|
|
374
|
+
offload_state_to_cpu=False,
|
|
375
|
+
)
|
|
376
|
+
st["images"] = images
|
|
377
|
+
for i, m in enumerate(masks):
|
|
378
|
+
tracker.add_new_mask(st, frame_idx=0, obj_id=i, mask=torch.as_tensor(m.astype(np.bool_)))
|
|
379
|
+
for _, obj_ids, _, video_res_masks, obj_scores in tracker.propagate_in_video(
|
|
380
|
+
st,
|
|
381
|
+
start_frame_idx=0,
|
|
382
|
+
max_frame_num_to_track=len(idx),
|
|
383
|
+
reverse=False,
|
|
384
|
+
propagate_preflight=True,
|
|
385
|
+
tqdm_disable=True,
|
|
386
|
+
):
|
|
387
|
+
scores_flat = None
|
|
388
|
+
if obj_scores is not None:
|
|
389
|
+
scores_flat = obj_scores.detach().float().cpu().reshape(-1).numpy()
|
|
390
|
+
for k, oid in enumerate(obj_ids):
|
|
391
|
+
present = True if scores_flat is None or k >= len(scores_flat) else float(scores_flat[k]) > -2.0
|
|
392
|
+
if present:
|
|
393
|
+
m = (video_res_masks[k, 0] > 0.0).detach().cpu().numpy().astype(bool)
|
|
394
|
+
a = int(m.sum())
|
|
395
|
+
else:
|
|
396
|
+
m, a = None, 0
|
|
397
|
+
track[int(oid)].append((_box(m) if a else None, a))
|
|
398
|
+
if a:
|
|
399
|
+
last_masks[int(oid)] = m
|
|
400
|
+
finally:
|
|
401
|
+
if st is not None:
|
|
402
|
+
try:
|
|
403
|
+
tracker.clear_all_points_in_video(st)
|
|
404
|
+
except Exception:
|
|
405
|
+
pass
|
|
406
|
+
del st
|
|
407
|
+
del images
|
|
408
|
+
gc.collect()
|
|
409
|
+
if torch.cuda.is_available():
|
|
410
|
+
torch.cuda.empty_cache()
|
|
411
|
+
return idx, [track[i] for i in ids], [last_masks[i] for i in ids]
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _follow(frames, masks, step=STEP, tracker="sam2"):
|
|
415
|
+
if tracker == "sam3":
|
|
416
|
+
return _follow_sam3(frames, masks, step=step)
|
|
417
|
+
return _follow_sam2(frames, masks, step=step)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _feat(F, m):
|
|
421
|
+
"""Mean unit feature (G x G x D) over the grid cells an object's mask covers."""
|
|
422
|
+
g = F.shape[0]
|
|
423
|
+
cells = cv2.resize(m.astype(np.float32), (g, g), interpolation=cv2.INTER_AREA)
|
|
424
|
+
sel = cells >= 0.3 if (cells >= 0.3).any() else cells >= cells.max()
|
|
425
|
+
v = F[sel].mean(0)
|
|
426
|
+
return v / max(float(np.linalg.norm(v)), 1e-8)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def run_log(frames, s, arm_end=None, fps=10, tracker="sam2"):
|
|
430
|
+
"""One run -> dict(objects=[...]). `s` is teach.run_state of the same frames."""
|
|
431
|
+
n, h, w = frames.shape[:3]
|
|
432
|
+
changed = T._changed(s)
|
|
433
|
+
g = changed.shape[0]
|
|
434
|
+
lab = lambda im: cv2.cvtColor(im, cv2.COLOR_RGB2LAB).astype(np.float32)
|
|
435
|
+
differ = np.linalg.norm(lab(s["start_img"]) - lab(s["end_img"]), axis=-1) > 12 # pixel changed start -> end
|
|
436
|
+
cells = [[float((c + 0.5) * w / g), float((r + 0.5) * h / g)] for r, c in zip(*np.nonzero(changed))]
|
|
437
|
+
near = cv2.resize(cv2.dilate(changed.astype(np.uint8), np.ones((3, 3), np.uint8)), (w, h),
|
|
438
|
+
interpolation=cv2.INTER_NEAREST) > 0
|
|
439
|
+
arm = arm_end if arm_end is not None else np.zeros((h, w), bool)
|
|
440
|
+
objs = []
|
|
441
|
+
# forward: things that left their start spot (ignore low-confidence tracker artifacts)
|
|
442
|
+
fwd_scored = sorted(
|
|
443
|
+
((sc, m) for sc, m in _cut(s["start_img"], cells, near, tracker=tracker)
|
|
444
|
+
if float(sc) >= EXTRA_SCORE and differ[m].mean() >= NEW_SHARE),
|
|
445
|
+
key=lambda x: -(x[0] * differ[x[1]].mean()),
|
|
446
|
+
)[:MAX_OBJ]
|
|
447
|
+
if fwd_scored:
|
|
448
|
+
fwd_scores, fwd = [sc for sc, _ in fwd_scored], [m for _, m in fwd_scored]
|
|
449
|
+
idx, tracks, last_ms = _follow(frames, fwd, tracker=tracker)
|
|
450
|
+
for sc, m, tr, m_end in zip(fwd_scores, fwd, tracks, last_ms):
|
|
451
|
+
b0 = _box(m)
|
|
452
|
+
a0 = max(1.0, float(np.median([a for _, a in tr[:3]])))
|
|
453
|
+
seen = [k for k, (b, a) in enumerate(tr) if b is not None and a >= max(25, SOLID * a0)]
|
|
454
|
+
moved = [k for k in seen if dist(ctr(tr[k][0]), ctr(b0)) > 0.5 * size(b0)]
|
|
455
|
+
lost = bool(seen) and seen[-1] < len(tr) - 2
|
|
456
|
+
end = tr[seen[-1]][0] if seen else b0
|
|
457
|
+
k0 = max(0, moved[0] - 3) if moved else 0
|
|
458
|
+
sh = _shape(end, h, w)
|
|
459
|
+
acov = _cover(end, arm)
|
|
460
|
+
end_area = float(tr[seen[-1]][1]) if seen else float(a0)
|
|
461
|
+
area_ratio = round(end_area / max(a0, 1.0), 3)
|
|
462
|
+
ef = _feat(s["E"], m_end) if (m_end is not None and m_end.any() and not lost) else _cell(s["E"], ctr(end))
|
|
463
|
+
# Arrival frame: first tracked frame where the object reaches its final spot `end` and stays there
|
|
464
|
+
end_c, end_sz = ctr(end), max(size(end), 0.03)
|
|
465
|
+
away = [k for k in seen if dist(ctr(tr[k][0]), end_c) > 0.5 * end_sz]
|
|
466
|
+
if lost:
|
|
467
|
+
f_arrive = int(idx[seen[-1]]) if seen else None
|
|
468
|
+
elif away:
|
|
469
|
+
after = [k for k in seen if k > away[-1]]
|
|
470
|
+
f_arrive = int(idx[after[0]]) if after else (int(idx[seen[-1]]) if seen else None)
|
|
471
|
+
else:
|
|
472
|
+
f_arrive = int(idx[moved[0]]) if moved else None
|
|
473
|
+
path_pts = [list(ctr(b0))] + [list(ctr(tr[k][0])) for k in seen if k >= k0]
|
|
474
|
+
path_f = [int(idx[k0])] + [int(idx[k]) for k in seen if k >= k0]
|
|
475
|
+
objs.append(dict(src="fwd", feat=_feat(s["S"], m), end_feat=ef, colour=T.colour(s["start_img"], b0), b0=b0,
|
|
476
|
+
moved=bool(moved), f_move=idx[moved[0]] if moved else None, f_arrive=f_arrive,
|
|
477
|
+
end=end, lost=lost, f_lost=idx[seen[-1]] if lost else None,
|
|
478
|
+
held=(not lost) and acov >= HELD_COVER,
|
|
479
|
+
arm_cover=round(acov, 3), area_ratio=area_ratio, shape=sh,
|
|
480
|
+
elong=_mask_elong(m_end if not lost else None, sh),
|
|
481
|
+
score=round(float(sc), 3), track_len=len(seen),
|
|
482
|
+
path=path_pts, path_f=path_f))
|
|
483
|
+
# backward: new things at the end that are not a forward object's end and not the robot
|
|
484
|
+
k, _, st, cen = cv2.connectedComponentsWithStats(cv2.morphologyEx(differ.astype(np.uint8), cv2.MORPH_OPEN,
|
|
485
|
+
np.ones((2, 2), np.uint8)), 8)
|
|
486
|
+
pts = cells + [[float(cen[i][0]), float(cen[i][1])] for i in range(1, k) if 8 <= st[i, 4] <= 0.01 * h * w]
|
|
487
|
+
near_e = near | (cv2.dilate(differ.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0)
|
|
488
|
+
ends = [o["end"] for o in objs if o["moved"] and not o["lost"]]
|
|
489
|
+
k_arm = max(3, int(0.05 * max(h, w))) | 1 # next to the arm at the end: cannot tell what it is
|
|
490
|
+
arm_near = cv2.dilate(arm.astype(np.uint8), np.ones((k_arm, k_arm), np.uint8)) > 0
|
|
491
|
+
back_scored = [
|
|
492
|
+
(sc, m) for sc, m in _cut(s["end_img"], pts, near_e, tracker=tracker)
|
|
493
|
+
if differ[m].mean() >= NEW_SHARE and not (m & arm_near).any()
|
|
494
|
+
and not _edge_sliver(_box(m))
|
|
495
|
+
and not any(_iou(_box(m), e) >= 0.3 for e in ends)
|
|
496
|
+
]
|
|
497
|
+
back_scored = sorted(
|
|
498
|
+
back_scored,
|
|
499
|
+
key=lambda x: -(x[0] * differ[x[1]].mean() if tracker == "sam3" else differ[x[1]].mean()),
|
|
500
|
+
)[:MAX_OBJ]
|
|
501
|
+
if back_scored:
|
|
502
|
+
back_scores, back = [sc for sc, _ in back_scored], [m for _, m in back_scored]
|
|
503
|
+
idx_r, tracks_r, _ = _follow(np.ascontiguousarray(frames[::-1]), back, tracker=tracker)
|
|
504
|
+
eff = _eff_step(n, STEP)
|
|
505
|
+
tail_steps = max(10, int(round(30 * STEP / max(eff, 1))))
|
|
506
|
+
for sc, m, tr in zip(back_scores, back, tracks_r):
|
|
507
|
+
bE = _box(m)
|
|
508
|
+
a0 = max(1.0, float(np.median([a for _, a in tr[:3]])))
|
|
509
|
+
ok = lambda b, a: b is not None and a >= max(25, SOLID * a0)
|
|
510
|
+
j = next((j for j, (b, a) in enumerate(tr) if not (ok(b, a) and dist(ctr(b), ctr(bE)) <= 0.5 * size(bE))), len(tr))
|
|
511
|
+
f_arrive = n - 1 - idx_r[j - 1] if j > 0 else n - 1
|
|
512
|
+
if f_arrive / fps <= ARRIVE_MIN or (n - 1 - f_arrive) / fps < ARRIVE_MIN:
|
|
513
|
+
continue # first second: there from the start; last second: not told apart from the robot
|
|
514
|
+
before_idx = [i for i in range(j, min(len(tr), j + tail_steps)) if ok(*tr[i])]
|
|
515
|
+
before = [list(ctr(tr[i][0])) for i in before_idx]
|
|
516
|
+
before_f = [int(n - 1 - idx_r[i]) for i in before_idx]
|
|
517
|
+
sh = _shape(bE, h, w)
|
|
518
|
+
objs.append(dict(src="back", feat=_feat(s["E"], m), end_feat=_feat(s["E"], m),
|
|
519
|
+
colour=T.colour(s["end_img"], bE), b0=None, moved=True,
|
|
520
|
+
f_move=f_arrive, f_arrive=f_arrive, end=bE, lost=False, f_lost=None, held=False, arm_cover=0.0,
|
|
521
|
+
shape=sh, elong=_mask_elong(m, sh), score=round(float(sc), 3),
|
|
522
|
+
track_len=j + len(before), path=before[::-1] + [list(ctr(bE))],
|
|
523
|
+
path_f=before_f[::-1] + [int(f_arrive)]))
|
|
524
|
+
return dict(objects=objs, n=n, fps=fps, hw=[h, w], S=s["S"], valid=s["valid_s"], E=s["E"], tracker=tracker)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def summary(log):
|
|
528
|
+
"""JSON-able digest of a run's log (for the scorer and for debugging)."""
|
|
529
|
+
r = lambda b: None if b is None else [round(float(v), 3) for v in b]
|
|
530
|
+
return [dict(src=o["src"], colour=o["colour"], b0=r(o["b0"]), end=r(o["end"]), moved=bool(o["moved"]),
|
|
531
|
+
lost=bool(o["lost"]), held=bool(o["held"]), shape=round(float(o["shape"]), 2),
|
|
532
|
+
elong=round(float(o.get("elong", max(o["shape"], 1.0 / max(o["shape"], 1e-4)))), 2),
|
|
533
|
+
score=round(float(o.get("score", 1.0)), 2),
|
|
534
|
+
f_move=o["f_move"], f_lost=o["f_lost"]) for o in log["objects"]]
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _cell(S, p):
|
|
538
|
+
"""Unit feature around a point (3x3 cells) of a G x G x D start picture."""
|
|
539
|
+
g = S.shape[0]
|
|
540
|
+
r, c = min(g - 1, max(0, int(p[1] * g))), min(g - 1, max(0, int(p[0] * g)))
|
|
541
|
+
v = S[max(0, r - 1):r + 2, max(0, c - 1):c + 2].reshape(-1, S.shape[-1]).mean(0)
|
|
542
|
+
return v / max(float(np.linalg.norm(v)), 1e-8)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _locate(S, A, valid=None):
|
|
546
|
+
"""Where the thing that looks like A stands in a start picture: centre of the best-matching patch of cells."""
|
|
547
|
+
m = (S @ np.asarray(A, np.float32)).astype(np.float32)
|
|
548
|
+
if valid is not None:
|
|
549
|
+
m = np.where(valid, m, -1.0)
|
|
550
|
+
g = m.shape[0]
|
|
551
|
+
r, c = np.unravel_index(int(np.argmax(m)), m.shape)
|
|
552
|
+
_, lab = cv2.connectedComponents((m >= m.max() - 0.1).astype(np.uint8), connectivity=8)
|
|
553
|
+
ys, xs = np.nonzero(lab == lab[r, c])
|
|
554
|
+
return (float((xs.mean() + 0.5) / g), float((ys.mean() + 0.5) / g))
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
# ---------------------------------------------------------------- teach
|
|
558
|
+
def _loo(points):
|
|
559
|
+
"""Leave-one-out spread: the worst distance from a run's point to the nearest point of the other runs."""
|
|
560
|
+
worst = 0.0
|
|
561
|
+
for i, p in enumerate(points):
|
|
562
|
+
others = [q for j, q in enumerate(points) if j != i]
|
|
563
|
+
if others:
|
|
564
|
+
worst = max(worst, min(dist(p, q) for q in others))
|
|
565
|
+
return worst
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _scatter(points):
|
|
569
|
+
"""Global spatial spread (max distance from median point): stays meaningful even when N is large."""
|
|
570
|
+
if len(points) < 2:
|
|
571
|
+
return 0.0
|
|
572
|
+
med = np.median(np.asarray(points, np.float64), axis=0)
|
|
573
|
+
return max(dist(p, med) for p in points)
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _match_score(o, p):
|
|
577
|
+
"""Start appearance cosine with a mild end-appearance tie-breaker for objects packed together at t=0."""
|
|
578
|
+
s_sim = float(np.asarray(o["feat"], np.float32) @ np.asarray(p["feat"], np.float32))
|
|
579
|
+
if not o.get("lost") and o.get("end_feat") is not None and p.get("end_feat") is not None:
|
|
580
|
+
e_sim = float(np.asarray(o["end_feat"], np.float32) @ np.asarray(p["end_feat"], np.float32))
|
|
581
|
+
return s_sim, 0.80 * s_sim + 0.20 * e_sim
|
|
582
|
+
return s_sim, s_sim
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def teach_objects(logs, zones=None):
|
|
586
|
+
"""Good-run logs (+ optional taught ROI zones) -> JSON-able taught objects."""
|
|
587
|
+
from scipy.optimize import linear_sum_assignment
|
|
588
|
+
n_runs = len(logs)
|
|
589
|
+
has_zones = zones is not None and len(zones) > 0
|
|
590
|
+
protos = [] # dict(feat, end_feat, members={run: obj})
|
|
591
|
+
for r, L in enumerate(logs):
|
|
592
|
+
objs = [o for o in L["objects"] if o["src"] == "fwd" and float(o.get("score", 1.0)) >= EXTRA_SCORE]
|
|
593
|
+
if protos and objs:
|
|
594
|
+
s_sim = np.zeros((len(objs), len(protos)), np.float32)
|
|
595
|
+
c_sim = np.zeros((len(objs), len(protos)), np.float32)
|
|
596
|
+
for i, o in enumerate(objs):
|
|
597
|
+
for j, p in enumerate(protos):
|
|
598
|
+
s_sim[i, j], c_sim[i, j] = _match_score(o, p)
|
|
599
|
+
rows, cols = linear_sum_assignment(-c_sim)
|
|
600
|
+
used = set()
|
|
601
|
+
for i, j in zip(rows, cols):
|
|
602
|
+
if s_sim[i, j] >= MATCH_MIN:
|
|
603
|
+
protos[j]["members"][r] = objs[i]
|
|
604
|
+
used.add(i)
|
|
605
|
+
objs = [o for i, o in enumerate(objs) if i not in used]
|
|
606
|
+
protos += [dict(members={r: o}) for o in objs]
|
|
607
|
+
for p in protos:
|
|
608
|
+
v = np.mean([o["feat"] for o in p["members"].values()], 0)
|
|
609
|
+
p["feat"] = v / max(float(np.linalg.norm(v)), 1e-8)
|
|
610
|
+
efs = [np.asarray(o["end_feat"], np.float32) for o in p["members"].values()
|
|
611
|
+
if not o.get("lost") and o.get("end_feat") is not None]
|
|
612
|
+
if efs:
|
|
613
|
+
ve = np.mean(efs, 0)
|
|
614
|
+
p["end_feat"] = ve / max(float(np.linalg.norm(ve)), 1e-8)
|
|
615
|
+
else:
|
|
616
|
+
p["end_feat"] = None
|
|
617
|
+
protos = [p for p in protos if len(p["members"]) >= max(2, (n_runs + 1) // 2)]
|
|
618
|
+
out = []
|
|
619
|
+
for pi, p in enumerate(protos):
|
|
620
|
+
mem = p["members"]
|
|
621
|
+
feats = [np.asarray(o["feat"], np.float32) for o in mem.values()]
|
|
622
|
+
look = [float(f @ (np.sum(feats, 0) - f) / max(1e-8, np.linalg.norm(np.sum(feats, 0) - f))) for f in feats] \
|
|
623
|
+
if len(feats) > 1 else [1.0]
|
|
624
|
+
ends = {r: ctr(o["end"]) for r, o in mem.items() if o["moved"] or not o["lost"]}
|
|
625
|
+
end_boxes = {r: o["end"] for r, o in mem.items() if o["moved"] or not o["lost"]}
|
|
626
|
+
sz = float(np.median([size(o["end"]) for o in mem.values()]))
|
|
627
|
+
# Learn target ROI (zone_id) if most good runs place this object inside the same zone
|
|
628
|
+
zone_id = None
|
|
629
|
+
if has_zones and end_boxes:
|
|
630
|
+
z_votes = [_zone_of(b, zones, dilate=0) for b in end_boxes.values()]
|
|
631
|
+
valid_z = [z for z in z_votes if z is not None]
|
|
632
|
+
if valid_z:
|
|
633
|
+
top_z = max(set(valid_z), key=valid_z.count)
|
|
634
|
+
if valid_z.count(top_z) >= max(2, int(np.ceil(0.6 * len(end_boxes)))):
|
|
635
|
+
zone_id = int(top_z)
|
|
636
|
+
if zone_id is None:
|
|
637
|
+
z_near = [_zone_of(b, zones, dilate=1) for b in end_boxes.values()]
|
|
638
|
+
valid_zn = [z for z in z_near if z is not None]
|
|
639
|
+
if valid_zn:
|
|
640
|
+
top_z = max(set(valid_zn), key=valid_zn.count)
|
|
641
|
+
if valid_zn.count(top_z) >= max(2, int(np.ceil(0.75 * len(end_boxes)))):
|
|
642
|
+
zone_id = int(top_z)
|
|
643
|
+
elongs = [float(o.get("elong", max(o["shape"], 1.0 / max(o["shape"], 1e-4)))) for o in mem.values()]
|
|
644
|
+
end_feats = [np.asarray(o["end_feat"], np.float32) for o in mem.values() if o.get("end_feat") is not None]
|
|
645
|
+
end_feat, end_feat_bar = None, -1.0
|
|
646
|
+
if len(end_feats) >= 2:
|
|
647
|
+
tot = np.sum(end_feats, 0)
|
|
648
|
+
ef_loo = [float(f @ ((tot - f) / max(1e-8, np.linalg.norm(tot - f)))) for f in end_feats]
|
|
649
|
+
ef_mean = tot / max(1e-8, float(np.linalg.norm(tot)))
|
|
650
|
+
end_feat = ef_mean.tolist()
|
|
651
|
+
end_feat_bar = round(float(np.clip(min(ef_loo) - 0.08, 0.35, 0.65)), 3)
|
|
652
|
+
bar = round(max(MARGIN * _loo(list(ends.values())), 0.75 * sz, PLACE_FLOOR), 3)
|
|
653
|
+
fail_bar = round(max(SHIFT_MULT * bar, bar + 0.06), 3)
|
|
654
|
+
out.append(dict(id=pi, feat=p["feat"].tolist(), colour=next(iter(mem.values()))["colour"],
|
|
655
|
+
start=[round(v, 3) for v in np.median([ctr(o["b0"]) for o in mem.values()], 0)],
|
|
656
|
+
n=len(mem), moved=float(np.mean([o["moved"] for o in mem.values()])),
|
|
657
|
+
held_ok=any(o["held"] for o in mem.values()), look_bar=round(min(look) - 0.05, 3),
|
|
658
|
+
ends={str(r): list(e) for r, e in ends.items()}, size=round(sz, 3),
|
|
659
|
+
shape=[round(min(o["shape"] for o in mem.values()), 3),
|
|
660
|
+
round(max(o["shape"] for o in mem.values()), 3)],
|
|
661
|
+
elong=[round(min(elongs), 3), round(max(elongs), 3)],
|
|
662
|
+
end_feat=end_feat, end_feat_bar=end_feat_bar, zone_id=zone_id,
|
|
663
|
+
bar=bar, fail_bar=fail_bar, rel=None))
|
|
664
|
+
for P in sorted(out, key=lambda x: x["size"]): # smaller objects attach to larger anchors (DAG)
|
|
665
|
+
best = None
|
|
666
|
+
for Q in out:
|
|
667
|
+
if Q is P or Q["rel"] == P["id"]:
|
|
668
|
+
continue
|
|
669
|
+
if P["zone_id"] is not None and Q["zone_id"] is not None and P["zone_id"] != Q["zone_id"]:
|
|
670
|
+
continue # objects in different bins are independent
|
|
671
|
+
both = [r for r in P["ends"] if r in Q["ends"]]
|
|
672
|
+
if len(both) < max(3, len(P["ends"]) - 1):
|
|
673
|
+
continue
|
|
674
|
+
offs = [np.subtract(P["ends"][r], Q["ends"][r]).tolist() for r in both]
|
|
675
|
+
spread = _loo(offs)
|
|
676
|
+
if best is None or spread < best[0] - 1e-6 or (abs(spread - best[0]) <= 1e-6 and Q["size"] > best[3]):
|
|
677
|
+
best = (spread, Q["id"], offs, Q["size"])
|
|
678
|
+
end_pts = list(P["ends"].values())
|
|
679
|
+
end_spread = max(_loo(end_pts), _scatter(end_pts))
|
|
680
|
+
# Inside a taught ROI (bin/table), require genuinely rigid geometry (spread <= 0.05) so loose sorting piles
|
|
681
|
+
# never invent spurious pairwise constraints while structured layouts (fork/knife next to plate) still do.
|
|
682
|
+
max_rel = (min(0.05, 0.4 * end_spread) if P["zone_id"] is not None else 0.5 * end_spread)
|
|
683
|
+
if best and end_spread >= 0.04 and best[0] < max_rel:
|
|
684
|
+
if P["size"] <= best[3] + 0.02 or best[0] < 0.25 * end_spread:
|
|
685
|
+
rel_bar = round(max(MARGIN * best[0], 0.5 * P["size"]), 3)
|
|
686
|
+
P.update(rel=best[1], offs=best[2], bar=rel_bar, fail_bar=rel_bar)
|
|
687
|
+
for P, p in zip(out, protos): # ends where the same-looking thing stood at the
|
|
688
|
+
runs = [r for r, o in p["members"].items() # start (the blue cup, a plate, the rack)?
|
|
689
|
+
if o["moved"] and not o["lost"] and "S" in logs[r]]
|
|
690
|
+
if len(runs) < 3:
|
|
691
|
+
continue
|
|
692
|
+
a = [_cell(logs[r]["S"], ctr(p["members"][r]["end"])) for r in runs]
|
|
693
|
+
A = np.mean(a, 0)
|
|
694
|
+
A /= max(float(np.linalg.norm(A)), 1e-8)
|
|
695
|
+
if min(float(v @ A) for v in a) < MATCH_MIN:
|
|
696
|
+
continue # different things stood there: no anchor
|
|
697
|
+
locs = {r: _locate(logs[r]["S"], A, logs[r].get("valid")) for r in runs}
|
|
698
|
+
offs = [np.subtract(ctr(p["members"][r]["end"]), locs[r]).tolist() for r in runs]
|
|
699
|
+
spread = _loo(offs)
|
|
700
|
+
own = MARGIN * spread if P["rel"] is None else P["bar"]
|
|
701
|
+
raw_ends = [P["ends"][str(r)] for r in runs]
|
|
702
|
+
end_spread = max(_loo(raw_ends), _scatter(raw_ends))
|
|
703
|
+
if end_spread >= 0.04 and spread < 0.5 * end_spread and MARGIN * spread < own + 1e-9:
|
|
704
|
+
anc_bar = round(max(MARGIN * spread, 0.5 * P["size"]), 3)
|
|
705
|
+
P.update(rel="anchor", anchor=A.tolist(), offs=offs, bar=anc_bar, fail_bar=anc_bar)
|
|
706
|
+
looks = [_cell(logs[r]["E"], locs[r]) for r in runs if "E" in logs[r]]
|
|
707
|
+
if len(looks) >= 3: # how that place looks at the end (the orange cup in the blue
|
|
708
|
+
tot = np.sum(looks, 0) # cup): position alone cannot tell "in" from "right beside"
|
|
709
|
+
loo = [float(v @ ((tot - v) / max(float(np.linalg.norm(tot - v)), 1e-8))) for v in looks]
|
|
710
|
+
B = tot / max(float(np.linalg.norm(tot)), 1e-8)
|
|
711
|
+
end_bar = round(min(END_LOOK_CAP, 1.0 - MARGIN * max(1.0 - min(loo), 0.05)), 3)
|
|
712
|
+
P.update(end_look=B.tolist(), end_bar=end_bar)
|
|
713
|
+
spots = [(ctr(o["end"]), size(o["end"]), r) for r, L in enumerate(logs) for o in L["objects"]
|
|
714
|
+
if not o["lost"] and (o["src"] == "back" or o["moved"])]
|
|
715
|
+
worst = 0.0
|
|
716
|
+
for p, s, r in spots: # leave-one-out: new things land near another
|
|
717
|
+
others = [dist(p, q) - 0.5 * (s + sq) for q, sq, rr in spots if rr != r] # good run's new things
|
|
718
|
+
if others:
|
|
719
|
+
worst = max(worst, min(others))
|
|
720
|
+
floor = 0.5 * float(np.median([s for _, s, _ in spots])) if spots else 0.05 # few runs: at least half a thing
|
|
721
|
+
return dict(objects=out, n_runs=n_runs, has_zones=has_zones,
|
|
722
|
+
spots=[[round(v, 3) for v in p] + [round(s, 3)] for p, s, _ in spots],
|
|
723
|
+
extra_bar=round(max(MARGIN * max(worst, 0.0), floor), 3))
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
# ---------------------------------------------------------------- check
|
|
727
|
+
def check_objects(taught, log, zones=None, zone_failed=None):
|
|
728
|
+
"""One run's log against the taught objects (+ optional taught ROIs) -> failure & difference claims."""
|
|
729
|
+
from scipy.optimize import linear_sum_assignment
|
|
730
|
+
P = taught["objects"]
|
|
731
|
+
nrun = taught["n_runs"]
|
|
732
|
+
fps = log.get("fps", 10)
|
|
733
|
+
z_fail = set(zone_failed or ())
|
|
734
|
+
has_zones = zones is not None and len(zones) > 0
|
|
735
|
+
t = lambda f: f"{f / fps:.1f} s"
|
|
736
|
+
objs = [o for o in log["objects"] if o["src"] == "fwd" and float(o.get("score", 1.0)) >= EXTRA_SCORE]
|
|
737
|
+
match = {}
|
|
738
|
+
if P and objs:
|
|
739
|
+
s_sim = np.zeros((len(objs), len(P)), np.float32)
|
|
740
|
+
c_sim = np.zeros((len(objs), len(P)), np.float32)
|
|
741
|
+
for i, o in enumerate(objs):
|
|
742
|
+
for j, p in enumerate(P):
|
|
743
|
+
s_sim[i, j], c_sim[i, j] = _match_score(o, p)
|
|
744
|
+
for i, j in zip(*linear_sum_assignment(-c_sim)):
|
|
745
|
+
if s_sim[i, j] >= min(P[j]["look_bar"], MATCH_MIN + 0.1):
|
|
746
|
+
match[j] = objs[i]
|
|
747
|
+
claims = []
|
|
748
|
+
|
|
749
|
+
def add(kind, o, box, text, ev, f=None, ctype="failure"):
|
|
750
|
+
claims.append(dict(kind=kind, box=[round(v, 3) for v in box], text=text, evidence=ev, type=ctype, frame=f,
|
|
751
|
+
track=o.get("path") if o else None, track_f=o.get("path_f") if o else None))
|
|
752
|
+
|
|
753
|
+
all_end_boxes = [o["end"] for o in log["objects"] if not o["lost"]]
|
|
754
|
+
switched = {id(o) for o in objs if _is_id_switch(o, objs)}
|
|
755
|
+
|
|
756
|
+
for j, p in enumerate(P):
|
|
757
|
+
o = match.get(j)
|
|
758
|
+
if o is None:
|
|
759
|
+
continue
|
|
760
|
+
name = f"the {o['colour']} thing from {T.where(o['b0'])}"
|
|
761
|
+
if p["moved"] >= 1.0 and not o["moved"]:
|
|
762
|
+
if not o["lost"] and float(o.get("score", 1.0)) >= EXTRA_SCORE:
|
|
763
|
+
add("NOT MOVED", o, o["b0"], f"{name} was never moved", f"it moved in all {p['n']} good runs")
|
|
764
|
+
continue
|
|
765
|
+
if not o["moved"] or p["moved"] < 0.5: # only things good runs normally move have a learnt end
|
|
766
|
+
continue
|
|
767
|
+
if id(o) in switched:
|
|
768
|
+
continue
|
|
769
|
+
|
|
770
|
+
# Target ROI awareness ("Know the ROI"):
|
|
771
|
+
# Free bin/rack targets (rel is None) pass anywhere inside their ROI;
|
|
772
|
+
# rigid relative placements (rel is not None, e.g. fork relative to plate) still verify offset `d`.
|
|
773
|
+
z_id = p.get("zone_id")
|
|
774
|
+
in_roi = bool(z_id is not None and has_zones and z_id < len(zones) and _in_zone(o["end"], zones[z_id], dilate=0))
|
|
775
|
+
near_roi = bool(z_id is not None and has_zones and z_id < len(zones) and _in_zone(o["end"], zones[z_id], dilate=1))
|
|
776
|
+
in_passing_roi = in_roi and (z_id not in z_fail)
|
|
777
|
+
use_roi_pass = in_roi and (p["rel"] is None)
|
|
778
|
+
|
|
779
|
+
end = ctr(o["end"])
|
|
780
|
+
look = 1.0
|
|
781
|
+
if p["rel"] == "anchor" and "S" in log:
|
|
782
|
+
loc = _locate(log["S"], p["anchor"], log.get("valid"))
|
|
783
|
+
off = np.subtract(end, loc)
|
|
784
|
+
d = min(dist(off, x) for x in p["offs"])
|
|
785
|
+
where_ok = "on the same thing as in every good run (where it stood at the start)"
|
|
786
|
+
if "end_look" in p and "E" in log:
|
|
787
|
+
look = float(_cell(log["E"], loc) @ np.asarray(p["end_look"], np.float32))
|
|
788
|
+
elif (p["rel"] not in (None, "anchor") and p["rel"] in match
|
|
789
|
+
and not match[p["rel"]]["lost"] and id(match[p["rel"]]) not in switched):
|
|
790
|
+
q = match[p["rel"]]
|
|
791
|
+
qp = P[p["rel"]]
|
|
792
|
+
q_zid = qp.get("zone_id")
|
|
793
|
+
q_ok = (q_zid is None or not has_zones or q_zid >= len(zones)
|
|
794
|
+
or _in_zone(q["end"], zones[q_zid], dilate=1))
|
|
795
|
+
if q_ok:
|
|
796
|
+
off = np.subtract(end, ctr(q["end"]))
|
|
797
|
+
d = min(dist(off, x) for x in p["offs"])
|
|
798
|
+
where_ok = f"next to the {q['colour']} thing, as in every good run"
|
|
799
|
+
else:
|
|
800
|
+
d = min(dist(end, x) for x in p["ends"].values()) if p["ends"] else 0.0
|
|
801
|
+
where_ok = f"in region {z_id + 1}" if z_id is not None else "where good runs put it"
|
|
802
|
+
else:
|
|
803
|
+
d = min(dist(end, x) for x in p["ends"].values()) if p["ends"] else 0.0
|
|
804
|
+
where_ok = f"in region {z_id + 1}" if z_id is not None else "where good runs put it"
|
|
805
|
+
|
|
806
|
+
# STILL HELD: only flag if NOT already placed inside its passing target ROI or within target bar.
|
|
807
|
+
# If good runs also end with this object covered by the arm (e.g. wrist camera / arm attachment), skip it.
|
|
808
|
+
if o["held"] and o.get("arm_cover", 1.0) >= HELD_COVER:
|
|
809
|
+
if p["held_ok"]:
|
|
810
|
+
continue
|
|
811
|
+
if not in_passing_roi and d > p["bar"]:
|
|
812
|
+
add("STILL HELD", o, o["end"], f"{name} is still in the gripper at the end",
|
|
813
|
+
"no good run ends holding it")
|
|
814
|
+
continue
|
|
815
|
+
|
|
816
|
+
# Placement check: free ROI landing counts as placed; external DROPPED requires a smooth high-conf track
|
|
817
|
+
# whose target region also failed (catches cubes knocked off-table without flagging tracker occlusions).
|
|
818
|
+
if use_roi_pass:
|
|
819
|
+
if o["lost"] and (z_id in z_fail) and not _edge_sliver(o["end"]):
|
|
820
|
+
add("DROPPED", o, o["end"], f"{name} was picked up at {t(o['f_move'])} and lost inside region {z_id + 1} "
|
|
821
|
+
f"at {t(o['f_lost'])}", f"region {z_id + 1} also failed end-state check", o["f_lost"])
|
|
822
|
+
continue
|
|
823
|
+
elif d > p["bar"]:
|
|
824
|
+
if o["lost"]:
|
|
825
|
+
if in_roi and (z_id in z_fail) and not _edge_sliver(o["end"]):
|
|
826
|
+
add("DROPPED", o, o["end"], f"{name} was picked up at {t(o['f_move'])} and lost inside region {z_id + 1} "
|
|
827
|
+
f"at {t(o['f_lost'])}", f"region {z_id + 1} also failed end-state check", o["f_lost"])
|
|
828
|
+
elif ((z_id in z_fail) and float(o.get("score", 1.0)) >= DROP_SCORE
|
|
829
|
+
and _max_jump(o.get("path")) < DROP_MAX_JUMP
|
|
830
|
+
and o.get("b0") is not None and not _edge_sliver(o["b0"])):
|
|
831
|
+
add("DROPPED", o, o["end"], f"{name} was lost from view at {t(o['f_lost'])} "
|
|
832
|
+
f"(last seen {T.where(o['end'])}), never landed {where_ok}",
|
|
833
|
+
f"last seen {d:.2f} away while region {z_id + 1} failed end-state check", o["f_lost"])
|
|
834
|
+
continue
|
|
835
|
+
landed_z = _zone_of(o["end"], zones, dilate=0) if has_zones else None
|
|
836
|
+
f_end = o.get("f_arrive")
|
|
837
|
+
if landed_z is not None and z_id is not None and landed_z != z_id:
|
|
838
|
+
add("WRONG TARGET", o, o["end"],
|
|
839
|
+
f"{name} was placed in region {landed_z + 1} ({T.where(o['end'])}), not region {z_id + 1}",
|
|
840
|
+
f"{d:.2f} away; good runs within {p['bar']:.2f} (leave-one-out)", f_end)
|
|
841
|
+
continue
|
|
842
|
+
fail_bar = float(p.get("fail_bar", SHIFT_MULT * p["bar"]))
|
|
843
|
+
if (near_roi and p["rel"] is None and z_id not in z_fail) or (p["rel"] is None and d <= fail_bar):
|
|
844
|
+
add("SLIGHT SHIFT", o, o["end"], f"{name} ends slightly off target ({T.where(o['end'])}), "
|
|
845
|
+
f"close to {where_ok}", f"{d:.2f} away (bar {p['bar']:.2f}, fail bar {fail_bar:.2f})",
|
|
846
|
+
f_end, ctype="difference")
|
|
847
|
+
continue
|
|
848
|
+
add("NOT PLACED", o, o["end"], f"{name} ends {T.where(o['end'])}, not {where_ok}",
|
|
849
|
+
f"{d:.2f} away; good runs within {p['bar']:.2f} (leave-one-out)", f_end)
|
|
850
|
+
continue
|
|
851
|
+
|
|
852
|
+
if p["rel"] == "anchor" and look < p.get("end_bar", -1.0):
|
|
853
|
+
add("NOT PLACED", o, o["end"], f"{name} ends right next to the thing it belongs in or on, but not in or "
|
|
854
|
+
f"on it: at the end that place does not look as in the good runs",
|
|
855
|
+
f"end look {look:.2f}; good runs at least {p['end_bar']:.2f} (leave-one-out)", o.get("f_arrive"))
|
|
856
|
+
continue
|
|
857
|
+
|
|
858
|
+
# Smart pose check: suppress on occluded objects / passing busy ROIs; use rotation-invariant elong + DINO
|
|
859
|
+
if o["lost"] or in_passing_roi:
|
|
860
|
+
continue
|
|
861
|
+
partial_view = float(o.get("area_ratio", 1.0)) < 0.65
|
|
862
|
+
touches_neighbor = any(_touches(o["end"], eb) and eb != o["end"] for eb in all_end_boxes)
|
|
863
|
+
if partial_view and (touches_neighbor or in_roi):
|
|
864
|
+
continue
|
|
865
|
+
lo, hi = p["shape"]
|
|
866
|
+
sh = float(o["shape"])
|
|
867
|
+
sh_ratio = max(lo / max(sh, 1e-4), sh / max(hi, 1e-4))
|
|
868
|
+
flipped = (lo > 1.25 and sh < 0.80) or (hi < 0.80 and sh > 1.25)
|
|
869
|
+
e_lo, e_hi = p.get("elong", [min(max(lo, 1.0 / max(lo, 1e-4)), max(hi, 1.0 / max(hi, 1e-4))),
|
|
870
|
+
max(max(lo, 1.0 / max(lo, 1e-4)), max(hi, 1.0 / max(hi, 1e-4)))])
|
|
871
|
+
el = float(o.get("elong", max(sh, 1.0 / max(sh, 1e-4))))
|
|
872
|
+
el_ratio = max(e_lo / max(el, 1e-4), el / max(e_hi, 1e-4))
|
|
873
|
+
end_look_ok = True
|
|
874
|
+
if p.get("end_feat") is not None and o.get("end_feat") is not None:
|
|
875
|
+
ef_sim = float(np.asarray(o["end_feat"], np.float32) @ np.asarray(p["end_feat"], np.float32))
|
|
876
|
+
end_look_ok = ef_sim >= float(p.get("end_feat_bar", 0.45))
|
|
877
|
+
if (flipped and (not end_look_ok or sh_ratio >= 2.0)) or (el_ratio >= ELONG_FAIL_TOL and not end_look_ok):
|
|
878
|
+
add("WRONG POSE", o, o["end"], f"{name} ends in the right place but its pose is unlike the good runs' "
|
|
879
|
+
f"(lying instead of standing, or the other way round)",
|
|
880
|
+
f"box h/w {sh:.2f} (good {lo:.2f}-{hi:.2f}), elong {el:.2f} (good {e_lo:.2f}-{e_hi:.2f})",
|
|
881
|
+
o.get("f_arrive"))
|
|
882
|
+
elif el_ratio >= ELONG_DIFF_TOL or (flipped and end_look_ok):
|
|
883
|
+
add("POSE DIFF", o, o["end"], f"{name} ends at a slightly different angle or view than the good runs",
|
|
884
|
+
f"box h/w {sh:.2f} (good {lo:.2f}-{hi:.2f}), elong {el:.2f} (good {e_lo:.2f}-{e_hi:.2f})",
|
|
885
|
+
o.get("f_arrive"), ctype="difference")
|
|
886
|
+
|
|
887
|
+
# Backward EXTRA objects: gate by confidence, persistence, border slivers, and passing ROI awareness
|
|
888
|
+
for o in log["objects"]:
|
|
889
|
+
if o["src"] != "back":
|
|
890
|
+
continue
|
|
891
|
+
if float(o.get("score", 1.0)) < EXTRA_SCORE or int(o.get("track_len", 99)) < 3 or _edge_sliver(o["end"]):
|
|
892
|
+
continue
|
|
893
|
+
if has_zones:
|
|
894
|
+
bz = _zone_of(o["end"], zones, dilate=0)
|
|
895
|
+
if bz is not None and bz not in z_fail:
|
|
896
|
+
continue # arrived inside a passing receiving ROI
|
|
897
|
+
c = ctr(o["end"])
|
|
898
|
+
d = min((dist(c, x[:2]) - 0.5 * (size(o["end"]) + x[2]) for x in taught["spots"]), default=1.0)
|
|
899
|
+
if d > taught["extra_bar"]:
|
|
900
|
+
add("EXTRA", o, o["end"], f"a {o['colour']} thing lands {T.where(o['end'])} at {t(o['f_move'])}; "
|
|
901
|
+
f"no good run leaves anything there", f"{d:.2f} from the nearest place good runs put things "
|
|
902
|
+
f"(bar {taught['extra_bar']:.2f}, leave-one-out over {nrun} good runs)", o["f_move"])
|
|
903
|
+
return claims
|