trackflow-python-cuda 0.7.0__cp310-abi3-win_amd64.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,1025 @@
1
+ """Ambiguity-triggered selective mask fallback (pure NumPy/SciPy/OpenCV core).
2
+
3
+ Monitors a box tracker online using a bounded in-RAM frame ring buffer, detects
4
+ ambiguous occlusion/collision windows with backward clean-seed lookup, dispatches
5
+ only high-value windows to a pluggable :class:`MaskPropagator` (such as Apache-2.0
6
+ SAM 2.1 / EdgeTAM in :mod:`trackflow.sam2_adapter` or an external SAM 3 predictor
7
+ wrapped via :class:`Sam3MaskPropagator`), and reconciles identities using a
8
+ collision-free bijective permutation.
9
+
10
+ Core ``MaskFallbackResolver`` never writes frames to disk and has zero PyTorch,
11
+ CUDA, Transformers, or Meta-licensed dependencies so core ``trackflow-python``
12
+ stays lightweight and 100% Apache-2.0.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import bisect
18
+ import contextlib
19
+ import tempfile
20
+ import time
21
+ from collections import defaultdict
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Protocol
26
+
27
+ import cv2
28
+ import numpy as np
29
+ from scipy.optimize import linear_sum_assignment
30
+
31
+ from trackflow.tracker import compute_ioa_matrix, compute_iou_matrix
32
+ from trackflow.types import Track
33
+
34
+ BBox = tuple[float, float, float, float]
35
+ FRESH_ID_OFFSET = 1_000_000_000
36
+
37
+
38
+ class MaskPropagator(Protocol):
39
+ """Pluggable mask propagation backend for short ambiguity windows.
40
+
41
+ ``frames_rgb`` holds consecutive RGB uint8 frames for ``[window.start_frame .. window.end_frame]``.
42
+ ``seeds`` maps ``seed_track_id -> (local_frame_idx, bbox_xyxy_orig_pixels)``.
43
+ Returns ``{local_frame_idx: {seed_track_id: mask_bool}}``, where each ``mask_bool`` is a 2D
44
+ boolean array at either full frame resolution or a smaller native mask grid (e.g. 256x256);
45
+ box coordinates are automatically scaled to match ``mask_bool.shape``.
46
+ """
47
+
48
+ def propagate_window(
49
+ self,
50
+ frames_rgb: Sequence[np.ndarray],
51
+ seeds: dict[int, tuple[int, BBox]],
52
+ frame_size_wh: tuple[int, int],
53
+ ) -> dict[int, dict[int, np.ndarray]]: ...
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class MaskFallbackConfig:
58
+ """Configuration for online ambiguity detection and two-tier safe reconciliation."""
59
+
60
+ # Stage A: collision & occlusion window detection
61
+ iou_overlap_thresh: float = 0.60
62
+ occlusion_ioa_thresh: float = 0.65
63
+ min_track_age: int = 6
64
+ min_track_conf: float = 0.50
65
+ lookback_frames: int = 4
66
+ clean_exit_frames: int = 2
67
+ max_window_len: int = 16
68
+ max_cluster_tracks: int = 3
69
+ cooldown_frames: int = 5
70
+ clean_seed_max_iou: float = 0.20
71
+
72
+ # Stage B: zero-cost causal CPU gate & optional frame budget
73
+ # Conservative default: pure transient-occlusion recovery (zero unseen regressions);
74
+ # set include_fragmentation=True to also relink occlusion-split newborn tracks.
75
+ require_lifecycle_event: bool = True
76
+ include_fragmentation: bool = False
77
+ fragmentation_newborn_iou: float = 0.20
78
+ max_frame_rate: float | None = None
79
+ bucket_cap_frames: float = 20.0
80
+
81
+ # Two-Tier Safe Bijective Reconciliation
82
+ min_seed_score: float = 0.60
83
+ min_mask_area_ratio: float = 0.12
84
+ confirm_frames: int = 2
85
+ # Tier 1: mutual swap cycles (A <-> B)
86
+ mutual_min_score: float = 0.45
87
+ mutual_min_containment: float = 0.55
88
+ mutual_min_margin: float = 0.05
89
+ # Tier 2: area-guarded unilateral overrides / relinks
90
+ unilateral_min_score: float = 0.72
91
+ unilateral_min_containment: float = 0.85
92
+ unilateral_min_margin: float = 0.28
93
+ unilateral_min_area_ratio: float = 0.45
94
+ unilateral_max_area_ratio: float = 1.85
95
+ apply_in_window: bool = True
96
+
97
+ def __post_init__(self) -> None:
98
+ if self.max_window_len < 4:
99
+ raise ValueError("max_window_len must be at least 4.")
100
+ if self.max_cluster_tracks < 2:
101
+ raise ValueError("max_cluster_tracks must be at least 2.")
102
+ if self.lookback_frames < 0:
103
+ raise ValueError("lookback_frames must be nonnegative.")
104
+ if self.confirm_frames < 1:
105
+ raise ValueError("confirm_frames must be at least 1.")
106
+ if self.clean_exit_frames < 1:
107
+ raise ValueError("clean_exit_frames must be at least 1.")
108
+ if self.max_frame_rate is not None and not (0.0 < self.max_frame_rate <= 1.0):
109
+ raise ValueError("max_frame_rate must be in (0, 1] when set.")
110
+
111
+
112
+ @dataclass(slots=True)
113
+ class AmbiguityWindow:
114
+ """Closed ambiguity window eligible for selective mask propagation."""
115
+
116
+ start_frame: int
117
+ trigger_frame: int
118
+ end_frame: int
119
+ seeds: dict[int, tuple[int, BBox]]
120
+ reason: str
121
+
122
+
123
+ @dataclass(slots=True)
124
+ class MaskFallbackStats:
125
+ """Cumulative dispatch and reconciliation counters for a run."""
126
+
127
+ processed_frames: int = 0
128
+ windows_detected: int = 0
129
+ windows_dispatched: int = 0
130
+ windows_skipped_gate: int = 0
131
+ windows_skipped_budget: int = 0
132
+ dispatched_frames: int = 0
133
+ overrides: int = 0
134
+ mutual_links: int = 0
135
+ unilateral_links: int = 0
136
+ swaps: int = 0
137
+ relinks: int = 0
138
+ abstained: int = 0
139
+ propagation_ms: float = 0.0
140
+
141
+ @property
142
+ def pct_frames(self) -> float:
143
+ if self.processed_frames <= 0:
144
+ return 0.0
145
+ return 100.0 * self.dispatched_frames / self.processed_frames
146
+
147
+ def to_dict(self) -> dict[str, Any]:
148
+ return {
149
+ "processed_frames": self.processed_frames,
150
+ "windows_detected": self.windows_detected,
151
+ "windows_dispatched": self.windows_dispatched,
152
+ "windows_skipped_gate": self.windows_skipped_gate,
153
+ "windows_skipped_budget": self.windows_skipped_budget,
154
+ "dispatched_frames": self.dispatched_frames,
155
+ "pct_frames": round(self.pct_frames, 2),
156
+ "overrides": self.overrides,
157
+ "mutual_links": self.mutual_links,
158
+ "unilateral_links": self.unilateral_links,
159
+ "swaps": self.swaps,
160
+ "relinks": self.relinks,
161
+ "abstained": self.abstained,
162
+ "propagation_ms": round(self.propagation_ms, 2),
163
+ }
164
+
165
+
166
+ def compute_mask_box_affinities(
167
+ mask_bool: np.ndarray,
168
+ boxes_xyxy: Sequence[BBox],
169
+ orig_w: int,
170
+ orig_h: int,
171
+ ) -> tuple[int, list[tuple[float, float, float]]]:
172
+ """Score a 2D boolean mask against candidate boxes in original pixel coordinates.
173
+
174
+ Works on either native SAM 256x256 masks or full-resolution masks by scaling boxes to
175
+ ``mask_bool.shape``. Returns ``(mask_area_pixels, [(combined, containment, bbox_iou), ...])``.
176
+ """
177
+ mask = np.asarray(mask_bool, dtype=bool)
178
+ if mask.ndim != 2:
179
+ raise ValueError(f"Expected 2D boolean mask, got shape {mask.shape}")
180
+ mh, mw = mask.shape
181
+ ys, xs = np.nonzero(mask)
182
+ area = int(ys.size)
183
+ min_px = 6 if max(mh, mw) <= 320 else 64
184
+ if area < min_px:
185
+ return area, [(0.0, 0.0, 0.0) for _ in boxes_xyxy]
186
+
187
+ if area >= 40:
188
+ xs_s = np.sort(xs)
189
+ ys_s = np.sort(ys)
190
+ k = int(0.02 * area)
191
+ mx1, mx2 = float(xs_s[k]), float(xs_s[area - 1 - k])
192
+ my1, my2 = float(ys_s[k]), float(ys_s[area - 1 - k])
193
+ else:
194
+ mx1, mx2 = float(xs.min()), float(xs.max())
195
+ my1, my2 = float(ys.min()), float(ys.max())
196
+ m_area_box = max(1.0, (mx2 - mx1 + 1.0) * (my2 - my1 + 1.0))
197
+
198
+ sx = mw / max(float(orig_w), 1.0)
199
+ sy = mh / max(float(orig_h), 1.0)
200
+
201
+ scores: list[tuple[float, float, float]] = []
202
+ for bx1, by1, bx2, by2 in boxes_xyxy:
203
+ sbx1, sby1, sbx2, sby2 = bx1 * sx, by1 * sy, bx2 * sx, by2 * sy
204
+ ix1 = max(0, int(np.floor(sbx1)))
205
+ iy1 = max(0, int(np.floor(sby1)))
206
+ ix2 = min(mw, int(np.ceil(sbx2)))
207
+ iy2 = min(mh, int(np.ceil(sby2)))
208
+ if ix2 <= ix1 or iy2 <= iy1:
209
+ scores.append((0.0, 0.0, 0.0))
210
+ continue
211
+ in_box = int(mask[iy1:iy2, ix1:ix2].sum())
212
+ containment = in_box / max(area, 1)
213
+
214
+ ox1, oy1 = max(mx1, sbx1), max(my1, sby1)
215
+ ox2, oy2 = min(mx2, sbx2), min(my2, sby2)
216
+ inter = max(0.0, ox2 - ox1) * max(0.0, oy2 - oy1)
217
+ b_area = max(1.0, (sbx2 - sbx1) * (sby2 - sby1))
218
+ biou = inter / max(m_area_box + b_area - inter, 1e-6)
219
+ comb = 0.55 * containment + 0.45 * biou
220
+ scores.append((comb, containment, biou))
221
+ return area, scores
222
+
223
+
224
+ @dataclass(slots=True)
225
+ class _CommittedOverride:
226
+ start_frame: int
227
+ end_frame: int
228
+ in_window_maps: dict[int, dict[int, int]]
229
+ suffix_perm: dict[int, int]
230
+
231
+
232
+ def _close_bijective_frame_map(
233
+ cur_to_tgt: dict[int, int],
234
+ perm: dict[int, int],
235
+ ) -> dict[int, int]:
236
+ """Close ``cur_to_tgt`` (a subset of bijective ``perm``) along full ``perm`` orbits.
237
+
238
+ Because ``perm`` is a bijection (closed cycles and chains ending in fresh IDs outside
239
+ existing active IDs), closing every orbit touched by ``cur_to_tgt`` guarantees that the
240
+ resulting per-frame map is strictly bijective across both active and coasting tracks.
241
+ """
242
+ fmap: dict[int, int] = {}
243
+ for start_id in cur_to_tgt:
244
+ if start_id in fmap:
245
+ continue
246
+ cur = start_id
247
+ while cur in perm and cur not in fmap:
248
+ nxt = perm[cur]
249
+ fmap[cur] = nxt
250
+ cur = nxt
251
+ return fmap
252
+
253
+
254
+ def _compose_perm(base: dict[int, int], update: dict[int, int]) -> dict[int, int]:
255
+ """Return ``lambda x: update.get(base.get(x, x), base.get(x, x))`` in dict form."""
256
+ if not update:
257
+ return base
258
+ out: dict[int, int] = {}
259
+ for k, v in base.items():
260
+ nv = update.get(v, v)
261
+ if nv != k:
262
+ out[k] = nv
263
+ for k, v in update.items():
264
+ if k not in base and v != k:
265
+ out[k] = v
266
+ return out
267
+
268
+
269
+ class MaskFallbackResolver:
270
+ """Online ambiguity monitor and bijective ID reconciler with bounded frame memory.
271
+
272
+ Feed raw box-tracker outputs one frame at a time via :meth:`observe`. The resolver mutates
273
+ each frame's :class:`Track` objects to apply already-committed identity fixes in real time,
274
+ buffers at most ``max_window_len + lookback_frames + 4`` RGB frames in RAM (never writing
275
+ frames to disk), and supports retrospective relabeling via :meth:`resolve_id` when flushing
276
+ spooled exports.
277
+ """
278
+
279
+ def __init__(
280
+ self,
281
+ propagator: MaskPropagator,
282
+ config: MaskFallbackConfig | None = None,
283
+ ) -> None:
284
+ self.propagator = propagator
285
+ self.config = config or MaskFallbackConfig()
286
+ self.stats = MaskFallbackStats()
287
+
288
+ # Bounded per-frame RAM buffers keyed by frame_idx (pruned every step)
289
+ self._frames_rgb: dict[int, np.ndarray] = {}
290
+ self._raw_tracks_by_f: dict[int, list[tuple[int, BBox, float]]] = {}
291
+ self._frame_wh: tuple[int, int] = (0, 0)
292
+ self._seen_frame_order: list[int] = []
293
+
294
+ # Online track lifecycle metadata (keyed by raw box-tracker track_id; stale keys pruned)
295
+ self._track_age: dict[int, int] = defaultdict(int)
296
+ self._track_max_conf: dict[int, float] = defaultdict(float)
297
+ self._track_last_step: dict[int, int] = {}
298
+ self._last_clean: dict[int, tuple[int, BBox]] = {}
299
+ self._last_seen: dict[int, tuple[int, BBox]] = {}
300
+ self._prev_active: dict[int, BBox] = {}
301
+ self._prev2_active: dict[int, BBox] = {}
302
+ self._pair_last_closed: dict[tuple[int, int], int] = {}
303
+ self._open_windows: list[dict[str, Any]] = []
304
+
305
+ # Causal leaky-bucket frame budget state (recent dispatched frames kept for dedup only)
306
+ self._recent_dispatched_frames: set[int] = set()
307
+ self._budget_tokens: float = self.config.bucket_cap_frames
308
+ self._budget_last_step: int = 0
309
+
310
+ # Committed bijective reconciliation history + O(1) live permutation for current/future frames
311
+ self._commits: list[_CommittedOverride] = []
312
+ self._commit_end_frames: list[int] = []
313
+ self._live_perm: dict[int, int] = {}
314
+ self._next_fresh_id: int = FRESH_ID_OFFSET
315
+
316
+ def resolve_id(self, frame_idx: int, raw_track_id: int) -> int:
317
+ """Map a raw tracker ID at ``frame_idx`` through all committed bijective fixes."""
318
+ cid = int(raw_track_id)
319
+ if not self._commits:
320
+ return cid
321
+ if frame_idx >= self._commit_end_frames[-1]:
322
+ return self._live_perm.get(cid, cid)
323
+ # Skip commits whose entire window lies strictly after frame_idx? Not needed if we scan
324
+ # from the earliest commit with start_frame <= frame_idx, or apply only relevant commits.
325
+ # Since commits are appended in non-decreasing end_frame order, suffix_perm applies to
326
+ # frame_idx >= end_frame and in_window_maps applies to start_frame <= frame_idx < end_frame.
327
+ for commit in self._commits:
328
+ if frame_idx >= commit.end_frame:
329
+ cid = commit.suffix_perm.get(cid, cid)
330
+ elif commit.start_frame <= frame_idx:
331
+ fmap = commit.in_window_maps.get(frame_idx)
332
+ if fmap is not None:
333
+ cid = fmap.get(cid, cid)
334
+ return cid
335
+
336
+ def _eligible(self, raw_tid: int) -> bool:
337
+ return (
338
+ self._track_age[raw_tid] >= self.config.min_track_age
339
+ and self._track_max_conf[raw_tid] >= self.config.min_track_conf
340
+ )
341
+
342
+ def _make_seed(self, raw_tid: int) -> tuple[int, BBox] | None:
343
+ min_keep = (
344
+ self._seen_frame_order[
345
+ max(0, len(self._seen_frame_order) - 1 - self.config.lookback_frames)
346
+ ]
347
+ if self._seen_frame_order
348
+ else 0
349
+ )
350
+ lc = self._last_clean.get(raw_tid)
351
+ if lc is not None and lc[0] >= min_keep and lc[0] in self._frames_rgb:
352
+ return lc
353
+ ls = self._last_seen.get(raw_tid)
354
+ if ls is not None and ls[0] >= min_keep and ls[0] in self._frames_rgb:
355
+ return ls
356
+ return None
357
+
358
+ def _passes_stage_b(self, win: dict[str, Any], end_frame: int) -> bool:
359
+ cfg = self.config
360
+ if not cfg.require_lifecycle_event:
361
+ return True
362
+
363
+ start_f = int(win["start"])
364
+ seeds: dict[int, tuple[int, BBox]] = win["seeds"]
365
+ window_frames = [f for f in self._seen_frame_order if start_f <= f <= end_frame]
366
+ if len(window_frames) < 2:
367
+ return False
368
+
369
+ exit_frames = window_frames[-2:]
370
+ alive_exit: dict[int, BBox] = {}
371
+ for ef in exit_frames:
372
+ for tid, bbox, _ in self._raw_tracks_by_f.get(ef, ()):
373
+ alive_exit[tid] = bbox
374
+
375
+ before_tids: set[int] = set()
376
+ for f in self._seen_frame_order:
377
+ if f <= start_f:
378
+ for tid, _, _ in self._raw_tracks_by_f.get(f, ()):
379
+ before_tids.add(tid)
380
+
381
+ any_recovered = False
382
+ any_died = False
383
+ for st, (sf, _sb) in seeds.items():
384
+ missing_mid = False
385
+ for f in window_frames:
386
+ if f <= sf:
387
+ continue
388
+ present = any(tid == st for tid, _, _ in self._raw_tracks_by_f.get(f, ()))
389
+ if not present:
390
+ missing_mid = True
391
+ elif missing_mid:
392
+ any_recovered = True
393
+ if st not in alive_exit:
394
+ any_died = True
395
+
396
+ if any_recovered:
397
+ return True
398
+ if cfg.include_fragmentation and any_died:
399
+ nb_first: dict[int, BBox] = {}
400
+ for f in window_frames:
401
+ for tid, bbox, _ in self._raw_tracks_by_f.get(f, ()):
402
+ if tid not in before_tids and tid not in seeds and tid not in nb_first:
403
+ nb_first[tid] = bbox
404
+ nb_boxes = list(nb_first.values()) + [
405
+ b for tid, b in alive_exit.items() if tid not in before_tids and tid not in seeds
406
+ ]
407
+ ref_boxes = [sb for _, sb in seeds.values()] + [
408
+ self._last_seen[st][1] for st in seeds if st in self._last_seen
409
+ ]
410
+ if nb_boxes and ref_boxes:
411
+ max_iou = float(
412
+ compute_iou_matrix(
413
+ np.asarray(ref_boxes, dtype=np.float64),
414
+ np.asarray(nb_boxes, dtype=np.float64),
415
+ ).max()
416
+ )
417
+ if max_iou >= cfg.fragmentation_newborn_iou:
418
+ return True
419
+ return False
420
+
421
+ def _consume_budget(self, window_frames: list[int], step_idx: int) -> bool:
422
+ new_frames = [f for f in window_frames if f not in self._recent_dispatched_frames]
423
+ rate = self.config.max_frame_rate
424
+ if rate is not None:
425
+ dt = max(0, step_idx - self._budget_last_step)
426
+ self._budget_tokens = min(
427
+ self.config.bucket_cap_frames, self._budget_tokens + dt * rate
428
+ )
429
+ self._budget_last_step = step_idx
430
+ if len(new_frames) > self._budget_tokens:
431
+ return False
432
+ self._budget_tokens -= len(new_frames)
433
+ self._recent_dispatched_frames.update(new_frames)
434
+ self.stats.dispatched_frames += len(new_frames)
435
+ return True
436
+
437
+ def _dispatch_and_reconcile(self, win: AmbiguityWindow) -> dict[str, Any] | None:
438
+ cfg = self.config
439
+ window_frames = [
440
+ f
441
+ for f in self._seen_frame_order
442
+ if win.start_frame <= f <= win.end_frame and f in self._frames_rgb
443
+ ]
444
+ if len(window_frames) < 2:
445
+ self.stats.abstained += 1
446
+ return None
447
+
448
+ f_to_local = {f: i for i, f in enumerate(window_frames)}
449
+ frames_rgb = [self._frames_rgb[f] for f in window_frames]
450
+ local_seeds: dict[int, tuple[int, BBox]] = {}
451
+ for st, (sf, sb) in win.seeds.items():
452
+ lf = f_to_local.get(sf)
453
+ if lf is not None:
454
+ local_seeds[st] = (lf, sb)
455
+ if len(local_seeds) < 2:
456
+ self.stats.abstained += 1
457
+ return None
458
+
459
+ t0 = time.perf_counter()
460
+ masks_by_lf = self.propagator.propagate_window(frames_rgb, local_seeds, self._frame_wh)
461
+ self.stats.propagation_ms += (time.perf_counter() - t0) * 1000.0
462
+ self.stats.windows_dispatched += 1
463
+
464
+ orig_w, orig_h = self._frame_wh
465
+ seed_areas: dict[int, int] = {}
466
+ frame_scores: dict[int, dict[int, tuple[int, list[tuple[int, float, float, float]]]]] = {}
467
+
468
+ for lf, f_masks in masks_by_lf.items():
469
+ if not (0 <= lf < len(window_frames)):
470
+ continue
471
+ vid_f = window_frames[lf]
472
+ rows_f = self._raw_tracks_by_f.get(vid_f, [])
473
+ boxes_f = [r[1] for r in rows_f]
474
+ f_entry: dict[int, tuple[int, list[tuple[int, float, float, float]]]] = {}
475
+ for st, mbool in f_masks.items():
476
+ if st not in local_seeds:
477
+ continue
478
+ area, affs = compute_mask_box_affinities(mbool, boxes_f, orig_w, orig_h)
479
+ if lf == local_seeds[st][0] or (st not in seed_areas and area > 0):
480
+ seed_areas[st] = area
481
+ matches = [
482
+ (rows_f[di][0], comb, cont, biou)
483
+ for di, (comb, cont, biou) in enumerate(affs)
484
+ if comb >= 0.05
485
+ ]
486
+ f_entry[st] = (area, matches)
487
+ frame_scores[vid_f] = f_entry
488
+
489
+ # Map each seeded raw_tid -> unique canonical ID at its seed frame, filtering poor seeds
490
+ seed_raw_to_cur: dict[int, int] = {}
491
+ seen_seed_curs: set[int] = set()
492
+ for st, (sf, _sb) in sorted(win.seeds.items()):
493
+ if st not in seed_areas or seed_areas[st] <= 0:
494
+ continue
495
+ if cfg.min_seed_score > 0.0:
496
+ srec = frame_scores.get(sf, {}).get(st)
497
+ if srec is None:
498
+ continue
499
+ self_sc = next((comb for ot, comb, _c, _b in srec[1] if ot == st), 0.0)
500
+ if self_sc < cfg.min_seed_score:
501
+ continue
502
+ scur = self.resolve_id(sf, st)
503
+ if scur in seen_seed_curs:
504
+ continue
505
+ seen_seed_curs.add(scur)
506
+ seed_raw_to_cur[st] = scur
507
+
508
+ if not seed_raw_to_cur:
509
+ self.stats.abstained += 1
510
+ return None
511
+
512
+ # 1-to-1 Hungarian mask-to-track matching per window frame
513
+ per_f_match: dict[int, dict[int, tuple[int, float, float, float, float]]] = {}
514
+ for vid_f in window_frames:
515
+ f_rec = frame_scores.get(vid_f)
516
+ rows_f = self._raw_tracks_by_f.get(vid_f, [])
517
+ if not f_rec or not rows_f:
518
+ continue
519
+ valid_seeds = [
520
+ st
521
+ for st in seed_raw_to_cur
522
+ if st in f_rec
523
+ and f_rec[st][0] >= max(6, int(cfg.min_mask_area_ratio * max(seed_areas[st], 1)))
524
+ ]
525
+ if not valid_seeds:
526
+ continue
527
+ raw_tids_f = [r[0] for r in rows_f]
528
+ raw_to_col = {rt: ci for ci, rt in enumerate(raw_tids_f)}
529
+ raw_to_cur = {rt: self.resolve_id(vid_f, rt) for rt in raw_tids_f}
530
+
531
+ score_mat = np.zeros((len(valid_seeds), len(rows_f)), dtype=np.float64)
532
+ cont_mat = np.zeros((len(valid_seeds), len(rows_f)), dtype=np.float64)
533
+ for ri, st in enumerate(valid_seeds):
534
+ for ot, comb, cont, _biou in f_rec[st][1]:
535
+ ci = raw_to_col.get(ot)
536
+ if ci is not None:
537
+ score_mat[ri, ci] = comb
538
+ cont_mat[ri, ci] = cont
539
+
540
+ r_ind, c_ind = linear_sum_assignment(-score_mat)
541
+ f_matches: dict[int, tuple[int, float, float, float, float]] = {}
542
+ for ri, ci in zip(r_ind.tolist(), c_ind.tolist(), strict=True):
543
+ sc = float(score_mat[ri, ci])
544
+ ct = float(cont_mat[ri, ci])
545
+ if sc < 0.35 or ct < 0.45:
546
+ continue
547
+ row_other = np.delete(score_mat[ri], ci)
548
+ col_other = np.delete(score_mat[:, ci], ri)
549
+ s2 = max(
550
+ float(row_other.max()) if row_other.size else 0.0,
551
+ float(col_other.max()) if col_other.size else 0.0,
552
+ )
553
+ margin = sc - s2
554
+ st = valid_seeds[ri]
555
+ area_ratio = float(f_rec[st][0]) / max(float(seed_areas[st]), 1.0)
556
+ f_matches[st] = (raw_to_cur[raw_tids_f[ci]], sc, ct, margin, area_ratio)
557
+ if f_matches:
558
+ per_f_match[vid_f] = f_matches
559
+
560
+ exit_frames = [f for f in window_frames if f >= win.trigger_frame][
561
+ -max(cfg.confirm_frames + 1, 3) :
562
+ ]
563
+ if not exit_frames:
564
+ exit_frames = window_frames[-max(cfg.confirm_frames, 2) :]
565
+
566
+ seeded_cur_set = set(seed_raw_to_cur.values())
567
+
568
+ # Tier 1: Mutual swap cycles (A <-> B)
569
+ cand_mut: dict[int, int] = {}
570
+ for st, seed_cur in seed_raw_to_cur.items():
571
+ obs: list[int] = []
572
+ for ef in exit_frames:
573
+ m = per_f_match.get(ef, {}).get(st)
574
+ if m is None:
575
+ continue
576
+ ex_cur, sc, ct, marg, _ar = m
577
+ if (
578
+ sc >= cfg.mutual_min_score
579
+ and ct >= cfg.mutual_min_containment
580
+ and marg >= cfg.mutual_min_margin
581
+ ):
582
+ obs.append(ex_cur)
583
+ if len(obs) >= cfg.confirm_frames and len(set(obs[-cfg.confirm_frames :])) == 1:
584
+ ex_cur = obs[-1]
585
+ if ex_cur != seed_cur and ex_cur in seeded_cur_set and ex_cur not in cand_mut:
586
+ cand_mut[ex_cur] = seed_cur
587
+
588
+ desired: dict[int, int] = {}
589
+ n_mut = 0
590
+ for ex_cur, seed_cur in cand_mut.items():
591
+ if seed_cur in cand_mut and cand_mut[seed_cur] == ex_cur:
592
+ desired[ex_cur] = seed_cur
593
+ n_mut += 1
594
+
595
+ # Tier 2: High-confidence area-guarded unilateral overrides / relinks
596
+ n_uni = 0
597
+ for st, seed_cur in seed_raw_to_cur.items():
598
+ if seed_cur in desired.values():
599
+ continue
600
+ obs_u: list[int] = []
601
+ for ef in exit_frames:
602
+ m = per_f_match.get(ef, {}).get(st)
603
+ if m is None:
604
+ continue
605
+ ex_cur, sc, ct, marg, ar = m
606
+ if (
607
+ sc >= cfg.unilateral_min_score
608
+ and ct >= cfg.unilateral_min_containment
609
+ and marg >= cfg.unilateral_min_margin
610
+ and cfg.unilateral_min_area_ratio <= ar <= cfg.unilateral_max_area_ratio
611
+ ):
612
+ obs_u.append(ex_cur)
613
+ if len(obs_u) >= cfg.confirm_frames and len(set(obs_u[-cfg.confirm_frames :])) == 1:
614
+ ex_cur = obs_u[-1]
615
+ if ex_cur != seed_cur and ex_cur not in desired:
616
+ desired[ex_cur] = seed_cur
617
+ n_uni += 1
618
+
619
+ if not desired or len(desired.values()) != len(set(desired.values())):
620
+ self.stats.abstained += 1
621
+ return None
622
+
623
+ # Strictly bijective suffix permutation (prevents future ID collisions)
624
+ perm = dict(desired)
625
+ n_swaps = sum(1 for k in desired if k in seeded_cur_set)
626
+ n_relinks = len(desired) - n_swaps
627
+ relink_pairs: list[tuple[int, int]] = []
628
+ for k, v in desired.items():
629
+ if k not in seeded_cur_set:
630
+ relink_pairs.append((k, v))
631
+ for tgt in sorted(set(desired.values())):
632
+ if tgt not in perm:
633
+ perm[tgt] = self._next_fresh_id
634
+ self._next_fresh_id += 1
635
+
636
+ # In-window bijective maps for frames strictly before win.end_frame;
637
+ # win.end_frame and all later frames use suffix_perm directly (zero end_frame flicker).
638
+ in_window_maps: dict[int, dict[int, int]] = {}
639
+ if cfg.apply_in_window:
640
+ for vid_f in window_frames:
641
+ if vid_f >= win.end_frame:
642
+ continue
643
+ fm = per_f_match.get(vid_f, {})
644
+ cur_to_tgt: dict[int, int] = {}
645
+ for st, (ex_cur, sc, ct, _marg, _ar) in fm.items():
646
+ if sc >= 0.45 and ct >= 0.55:
647
+ tgt = seed_raw_to_cur[st]
648
+ if perm.get(ex_cur) == tgt:
649
+ cur_to_tgt[ex_cur] = tgt
650
+ if cur_to_tgt:
651
+ in_window_maps[vid_f] = _close_bijective_frame_map(cur_to_tgt, perm)
652
+
653
+ commit = _CommittedOverride(
654
+ start_frame=win.start_frame,
655
+ end_frame=win.end_frame,
656
+ in_window_maps=in_window_maps,
657
+ suffix_perm=perm,
658
+ )
659
+ self._commits.append(commit)
660
+ bisect.insort(self._commit_end_frames, win.end_frame)
661
+ self._live_perm = _compose_perm(self._live_perm, perm)
662
+
663
+ self.stats.overrides += 1
664
+ self.stats.mutual_links += n_mut
665
+ self.stats.unilateral_links += n_uni
666
+ self.stats.swaps += n_swaps
667
+ self.stats.relinks += n_relinks
668
+ return {
669
+ "type": "mask_fallback_resolved",
670
+ "window_start": win.start_frame,
671
+ "window_end": win.end_frame,
672
+ "reason": win.reason,
673
+ "swaps": n_swaps,
674
+ "relinks": n_relinks,
675
+ "relink_pairs": relink_pairs,
676
+ "permutation": {str(k): v for k, v in perm.items()},
677
+ }
678
+
679
+ def observe(
680
+ self, frame_idx: int, frame_bgr: np.ndarray, tracks: list[Track]
681
+ ) -> list[dict[str, Any]]:
682
+ """Ingest one tracked frame, dispatch any closed qualifying ambiguity windows, and relabel ``tracks``."""
683
+ cfg = self.config
684
+ self.stats.processed_frames += 1
685
+ step_idx = self.stats.processed_frames
686
+ h, w = frame_bgr.shape[:2]
687
+ self._frame_wh = (w, h)
688
+ self._frames_rgb[frame_idx] = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
689
+ self._seen_frame_order.append(frame_idx)
690
+
691
+ raw_rows: list[tuple[int, BBox, float]] = [
692
+ (int(t.track_id), tuple(float(v) for v in t.bbox), float(t.confidence)) for t in tracks
693
+ ]
694
+ self._raw_tracks_by_f[frame_idx] = raw_rows
695
+ if raw_rows:
696
+ max_raw = max(r[0] for r in raw_rows)
697
+ if max_raw >= self._next_fresh_id - 10_000:
698
+ self._next_fresh_id = max(self._next_fresh_id, max_raw + FRESH_ID_OFFSET)
699
+
700
+ active_boxes = {tid: box for tid, box, _ in raw_rows}
701
+ tids = [tid for tid, _, _ in raw_rows]
702
+ active_set = set(tids)
703
+
704
+ # Pairwise active IoU on current frame
705
+ track_max_iou: dict[int, float] = {t: 0.0 for t in tids}
706
+ trig_pairs: list[tuple[int, int, str, float]] = []
707
+ if len(tids) >= 2:
708
+ arr = np.asarray([active_boxes[t] for t in tids], dtype=np.float64)
709
+ iou_m = compute_iou_matrix(arr, arr)
710
+ np.fill_diagonal(iou_m, 0.0)
711
+ for i, tid in enumerate(tids):
712
+ track_max_iou[tid] = float(iou_m[i].max())
713
+ for i in range(len(tids)):
714
+ for j in range(i + 1, len(tids)):
715
+ v = float(iou_m[i, j])
716
+ if (
717
+ v >= cfg.iou_overlap_thresh
718
+ and self._eligible(tids[i])
719
+ and self._eligible(tids[j])
720
+ ):
721
+ trig_pairs.append((tids[i], tids[j], "overlap", v))
722
+
723
+ # Update age, confidence, and clean-seed snapshots
724
+ for tid, box, conf in raw_rows:
725
+ self._track_age[tid] += 1
726
+ self._track_last_step[tid] = step_idx
727
+ if conf > self._track_max_conf[tid]:
728
+ self._track_max_conf[tid] = conf
729
+ if track_max_iou[tid] < cfg.clean_seed_max_iou:
730
+ self._last_clean[tid] = (frame_idx, box)
731
+ self._last_seen[tid] = (frame_idx, box)
732
+
733
+ # Detect tracks that just vanished while covered by an overlapping active track (lost_occl).
734
+ # Use 1-step constant-velocity extrapolation when available so fast crossings match at frame t.
735
+ just_lost = [t for t in self._prev_active if t not in active_set]
736
+ if just_lost and tids:
737
+ pred_lost: list[BBox] = []
738
+ for t in just_lost:
739
+ b1 = self._prev_active[t]
740
+ b0 = self._prev2_active.get(t)
741
+ if b0 is not None:
742
+ pred_lost.append(
743
+ (
744
+ b1[0] + (b1[0] - b0[0]),
745
+ b1[1] + (b1[1] - b0[1]),
746
+ b1[2] + (b1[2] - b0[2]),
747
+ b1[3] + (b1[3] - b0[3]),
748
+ )
749
+ )
750
+ else:
751
+ pred_lost.append(b1)
752
+ lost_arr = np.asarray(pred_lost, dtype=np.float64)
753
+ act_arr = np.asarray([active_boxes[t] for t in tids], dtype=np.float64)
754
+ ioa_m = compute_ioa_matrix(lost_arr, act_arr)
755
+ for li, ltid in enumerate(just_lost):
756
+ if not self._eligible(ltid):
757
+ continue
758
+ aj = int(np.argmax(ioa_m[li]))
759
+ val = float(ioa_m[li, aj])
760
+ atid = tids[aj]
761
+ if val >= cfg.occlusion_ioa_thresh and self._eligible(atid):
762
+ trig_pairs.append((ltid, atid, "lost_occl", val + 0.3))
763
+
764
+ # Open or extend pair-scoped ambiguity windows
765
+ matched_wins: set[int] = set()
766
+ trig_pairs.sort(key=lambda x: x[3], reverse=True)
767
+ for ta, tb, rsn, sev in trig_pairs:
768
+ pkey = (min(ta, tb), max(ta, tb))
769
+ if step_idx - self._pair_last_closed.get(pkey, -999) < cfg.cooldown_frames:
770
+ continue
771
+ target_wi = None
772
+ for wi, wobj in enumerate(self._open_windows):
773
+ if ta in wobj["tracks"] and tb in wobj["tracks"]:
774
+ target_wi = wi
775
+ break
776
+ if target_wi is None:
777
+ for wi, wobj in enumerate(self._open_windows):
778
+ if (ta in wobj["tracks"] or tb in wobj["tracks"]) and len(
779
+ wobj["tracks"] | {ta, tb}
780
+ ) <= cfg.max_cluster_tracks:
781
+ target_wi = wi
782
+ break
783
+ if target_wi is not None:
784
+ wobj = self._open_windows[target_wi]
785
+ wobj["tracks"].update((ta, tb))
786
+ wobj["clean_streak"] = 0
787
+ if sev > wobj["severity"]:
788
+ wobj["severity"] = sev
789
+ wobj["reason"] = rsn
790
+ for t in (ta, tb):
791
+ if t not in wobj["seeds"]:
792
+ sd = self._make_seed(t)
793
+ if sd is not None and sd[0] >= wobj["start"]:
794
+ wobj["seeds"][t] = sd
795
+ matched_wins.add(target_wi)
796
+ else:
797
+ seeds: dict[int, tuple[int, BBox]] = {}
798
+ for t in (ta, tb):
799
+ sd = self._make_seed(t)
800
+ if sd is not None:
801
+ seeds[t] = sd
802
+ if len(seeds) < 2:
803
+ continue
804
+ start_f = min(sf for sf, _ in seeds.values())
805
+ self._open_windows.append(
806
+ {
807
+ "start": start_f,
808
+ "start_step": step_idx
809
+ - (len(self._seen_frame_order) - 1 - self._seen_frame_order.index(start_f)),
810
+ "trig": frame_idx,
811
+ "tracks": {ta, tb},
812
+ "seeds": seeds,
813
+ "clean_streak": 0,
814
+ "reason": rsn,
815
+ "severity": sev,
816
+ }
817
+ )
818
+ matched_wins.add(len(self._open_windows) - 1)
819
+
820
+ # Close resolved or max-length windows and dispatch qualifying ones
821
+ events: list[dict[str, Any]] = []
822
+ still_open: list[dict[str, Any]] = []
823
+ for wi, wobj in enumerate(self._open_windows):
824
+ win_steps = step_idx - wobj["start_step"] + 1
825
+ if wi not in matched_wins:
826
+ active_seeded = [t for t in wobj["seeds"] if t in active_set]
827
+ still_tangled = False
828
+ if len(active_seeded) >= 2:
829
+ sarr = np.asarray([active_boxes[t] for t in active_seeded], dtype=np.float64)
830
+ siou = compute_iou_matrix(sarr, sarr)
831
+ np.fill_diagonal(siou, 0.0)
832
+ if float(siou.max()) >= 0.25:
833
+ still_tangled = True
834
+ if not still_tangled:
835
+ for stid in wobj["seeds"]:
836
+ if stid not in active_set:
837
+ ls = self._last_seen.get(stid)
838
+ if ls is not None and ls[0] in self._seen_frame_order[-6:]:
839
+ still_tangled = True
840
+ break
841
+ if still_tangled:
842
+ wobj["clean_streak"] = 0
843
+ else:
844
+ wobj["clean_streak"] += 1
845
+
846
+ if wobj["clean_streak"] >= cfg.clean_exit_frames or win_steps >= cfg.max_window_len:
847
+ self.stats.windows_detected += 1
848
+ if not self._passes_stage_b(wobj, frame_idx):
849
+ self.stats.windows_skipped_gate += 1
850
+ else:
851
+ w_frames = [
852
+ f for f in self._seen_frame_order if wobj["start"] <= f <= frame_idx
853
+ ]
854
+ if not self._consume_budget(w_frames, step_idx):
855
+ self.stats.windows_skipped_budget += 1
856
+ else:
857
+ ev = self._dispatch_and_reconcile(
858
+ AmbiguityWindow(
859
+ start_frame=wobj["start"],
860
+ trigger_frame=wobj["trig"],
861
+ end_frame=frame_idx,
862
+ seeds=dict(wobj["seeds"]),
863
+ reason=wobj["reason"],
864
+ )
865
+ )
866
+ if ev is not None:
867
+ events.append(ev)
868
+ tlist = sorted(wobj["tracks"])
869
+ for i in range(len(tlist)):
870
+ for j in range(i + 1, len(tlist)):
871
+ self._pair_last_closed[(tlist[i], tlist[j])] = step_idx
872
+ else:
873
+ still_open.append(wobj)
874
+ self._open_windows = still_open
875
+ self._prev2_active = self._prev_active
876
+ self._prev_active = active_boxes
877
+
878
+ # Prune RAM ring buffer & stale per-track metadata so memory stays O(1) on long streams
879
+ max_keep = cfg.max_window_len + cfg.lookback_frames + 4
880
+ if len(self._seen_frame_order) > max_keep:
881
+ oldest_open = min((w["start"] for w in self._open_windows), default=frame_idx)
882
+ cutoff = min(oldest_open, self._seen_frame_order[-max_keep])
883
+ while self._seen_frame_order and self._seen_frame_order[0] < cutoff:
884
+ old_f = self._seen_frame_order.pop(0)
885
+ self._frames_rgb.pop(old_f, None)
886
+ self._raw_tracks_by_f.pop(old_f, None)
887
+ self._recent_dispatched_frames.discard(old_f)
888
+
889
+ if step_idx % 256 == 0:
890
+ stale_step = step_idx - max(max_keep * 4, 256)
891
+ open_tids = {t for w in self._open_windows for t in w["tracks"]} | active_set
892
+ for tid in [t for t, ls in self._track_last_step.items() if ls < stale_step and t not in open_tids]:
893
+ self._track_last_step.pop(tid, None)
894
+ self._track_age.pop(tid, None)
895
+ self._track_max_conf.pop(tid, None)
896
+ self._last_clean.pop(tid, None)
897
+ self._last_seen.pop(tid, None)
898
+ cd_cutoff = step_idx - max(cfg.cooldown_frames * 2, 32)
899
+ for pkey in [p for p, cs in self._pair_last_closed.items() if cs < cd_cutoff]:
900
+ self._pair_last_closed.pop(pkey, None)
901
+
902
+ # Apply committed canonical IDs to live tracks for this frame in O(1)
903
+ for tr, (raw_tid, _, _) in zip(tracks, raw_rows, strict=True):
904
+ tr.track_id = self.resolve_id(frame_idx, raw_tid)
905
+
906
+ return events
907
+
908
+
909
+ def _to_bool_mask(arr: Any) -> np.ndarray:
910
+ """Convert a NumPy array or PyTorch CPU/CUDA tensor to a 2D boolean NumPy mask without importing torch."""
911
+ if hasattr(arr, "detach"):
912
+ arr = arr.detach()
913
+ if hasattr(arr, "cpu"):
914
+ arr = arr.cpu()
915
+ if hasattr(arr, "numpy"):
916
+ arr = arr.numpy()
917
+ m = np.asarray(arr)
918
+ while m.ndim > 2:
919
+ m = m[0]
920
+ return m > 0
921
+
922
+
923
+ class Sam3MaskPropagator:
924
+ """External zero-dependency adapter wrapping a user-supplied SAM 3 video predictor.
925
+
926
+ Keeps Meta's SAM 3 code, weights, and non-OSI Meta SAM License completely outside
927
+ Trackflow. Compatible with ``sam3.model_builder.build_sam3_video_predictor()``
928
+ (``handle_request`` + ``handle_stream_request`` with ``out_obj_ids``/``out_binary_masks``)
929
+ as well as custom predictors returning ``{"outputs": [...]}``.
930
+
931
+ Because SAM 3's ``start_session`` reads a directory of JPEG frames, this adapter writes
932
+ short temporary window JPEGs to disk (``writes_frames_to_disk = True``) and is rejected
933
+ by :class:`TrackflowPipeline` when ``anonymize != "none"``.
934
+ """
935
+
936
+ writes_frames_to_disk: bool = True
937
+
938
+ def __init__(self, predictor: Any) -> None:
939
+ if not hasattr(predictor, "handle_request"):
940
+ raise TypeError(
941
+ "Sam3MaskPropagator expects a SAM 3 video predictor with a handle_request() method."
942
+ )
943
+ self.predictor = predictor
944
+
945
+ def propagate_window(
946
+ self,
947
+ frames_rgb: Sequence[np.ndarray],
948
+ seeds: dict[int, tuple[int, BBox]],
949
+ frame_size_wh: tuple[int, int],
950
+ ) -> dict[int, dict[int, np.ndarray]]:
951
+ if not frames_rgb or not seeds:
952
+ return {}
953
+ orig_w, orig_h = max(1, int(frame_size_wh[0])), max(1, int(frame_size_wh[1]))
954
+ with tempfile.TemporaryDirectory(prefix="trackflow_sam3_") as tmp_dir:
955
+ clip_dir = Path(tmp_dir)
956
+ for idx, rgb in enumerate(frames_rgb):
957
+ bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
958
+ cv2.imwrite(str(clip_dir / f"{idx:06d}.jpg"), bgr)
959
+
960
+ start_resp = self.predictor.handle_request(
961
+ {"type": "start_session", "resource_path": str(clip_dir)}
962
+ )
963
+ session_id = start_resp["session_id"]
964
+ try:
965
+ for obj_id in sorted(seeds.keys()):
966
+ lf, (x1, y1, x2, y2) = seeds[obj_id]
967
+ cx1 = max(0.0, min(float(orig_w), float(x1)))
968
+ cy1 = max(0.0, min(float(orig_h), float(y1)))
969
+ cx2 = max(cx1, min(float(orig_w), float(x2)))
970
+ cy2 = max(cy1, min(float(orig_h), float(y2)))
971
+ norm_xywh = [
972
+ cx1 / orig_w,
973
+ cy1 / orig_h,
974
+ max(1e-4, (cx2 - cx1) / orig_w),
975
+ max(1e-4, (cy2 - cy1) / orig_h),
976
+ ]
977
+ self.predictor.handle_request(
978
+ {
979
+ "type": "add_prompt",
980
+ "session_id": session_id,
981
+ "frame_index": int(lf),
982
+ "obj_id": int(obj_id),
983
+ "bounding_boxes": [norm_xywh],
984
+ "bounding_box_labels": [1],
985
+ }
986
+ )
987
+
988
+ prop_req = {"type": "propagate_in_video", "session_id": session_id}
989
+ if hasattr(self.predictor, "handle_stream_request"):
990
+ outputs = self.predictor.handle_stream_request(prop_req)
991
+ else:
992
+ prop_resp = self.predictor.handle_request(prop_req)
993
+ outputs = (
994
+ prop_resp.get("outputs", []) if isinstance(prop_resp, dict) else prop_resp
995
+ )
996
+
997
+ masks_by_lf: dict[int, dict[int, np.ndarray]] = {}
998
+ for item in outputs:
999
+ lf = int(item["frame_index"])
1000
+ f_masks: dict[int, np.ndarray] = {}
1001
+ # Real facebookresearch/sam3 schema: item["outputs"]["out_obj_ids" / "out_binary_masks"]
1002
+ nested = item.get("outputs") if isinstance(item, dict) else None
1003
+ if isinstance(nested, dict) and "out_binary_masks" in nested:
1004
+ oids = nested.get("out_obj_ids", ())
1005
+ if hasattr(oids, "tolist"):
1006
+ oids = oids.tolist()
1007
+ bmasks = nested["out_binary_masks"]
1008
+ for oid, arr in zip(oids, bmasks, strict=True):
1009
+ f_masks[int(oid)] = _to_bool_mask(arr)
1010
+ else:
1011
+ raw_masks = item.get("masks", {})
1012
+ if isinstance(raw_masks, dict):
1013
+ for oid, arr in raw_masks.items():
1014
+ f_masks[int(oid)] = _to_bool_mask(arr)
1015
+ elif "obj_ids" in item:
1016
+ for oid, arr in zip(item["obj_ids"], raw_masks, strict=True):
1017
+ f_masks[int(oid)] = _to_bool_mask(arr)
1018
+ if f_masks:
1019
+ masks_by_lf[lf] = f_masks
1020
+ return masks_by_lf
1021
+ finally:
1022
+ with contextlib.suppress(Exception):
1023
+ self.predictor.handle_request(
1024
+ {"type": "close_session", "session_id": session_id}
1025
+ )