trackflow-python-tensorrt 0.6.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.
trackflow/reid.py ADDED
@@ -0,0 +1,819 @@
1
+ """Person Re-ID, vision-language queries, Track Cards, opt-in cross-exit merges, and NL search.
2
+
3
+ Two different kinds of embeddings live here and must not be mixed up:
4
+
5
+ * :class:`ReidEmbedder` (``--reid osnet|color``) produces *identity* embeddings trained to tell
6
+ people apart. Only these are used for BoT-SORT appearance matching and cross-exit merges.
7
+ * :class:`VlmEmbedder` (``--vlm clip|siglip``) and :class:`EmbeddingGemmaEmbedder`
8
+ (``--vlm embeddinggemma``) produce image/text-aligned embeddings. They are
9
+ great for "person in a red jacket" queries and post-run search, but they barely separate
10
+ individuals (on vtest.avi, different people scored 0.83 cosine on average vs 0.86 for the same
11
+ person), so they are never used to decide identity.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+
20
+ import cv2
21
+ import numpy as np
22
+ from tokenizers import Tokenizer
23
+
24
+ from trackflow.detector import create_onnx_session
25
+ from trackflow.models import (
26
+ REID_REGISTRY,
27
+ VLM_REGISTRY,
28
+ Precision,
29
+ resolve_reid_model,
30
+ resolve_vlm_artifacts,
31
+ )
32
+ from trackflow.types import Track, TrackCard
33
+
34
+ ReidBackend = Literal["none", "color", "osnet"]
35
+ VlmBackend = Literal["none", "clip", "siglip", "siglip2", "embeddinggemma"]
36
+ # Default --query cut-off per model: text-image cosine scores sit on a different scale for each.
37
+ QUERY_THRESHOLDS: dict[str, float] = {
38
+ "clip": 0.27,
39
+ "siglip": 0.08,
40
+ "siglip2": 0.09,
41
+ "embeddinggemma": 0.71,
42
+ }
43
+
44
+ _IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
45
+ _IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
46
+ _IMAGENET_SCALE = (1.0 / (255.0 * _IMAGENET_STD)).astype(np.float32)
47
+ _IMAGENET_BIAS = (-_IMAGENET_MEAN / _IMAGENET_STD).astype(np.float32)
48
+ # Fixed padded batch size for OSNet on CoreML and TensorRT so the engine compiles once per
49
+ # session instead of stalling on dynamic per-frame crowd counts.
50
+ _STATIC_OSNET_BATCH = 8
51
+ _COREML_OSNET_BATCH = _STATIC_OSNET_BATCH
52
+
53
+
54
+ def _l2_normalize(vec: np.ndarray) -> np.ndarray:
55
+ arr = np.asarray(vec, dtype=np.float32).reshape(-1)
56
+ norm = float(np.linalg.norm(arr))
57
+ if norm <= 1e-8:
58
+ return arr
59
+ return arr / norm
60
+
61
+
62
+ def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
63
+ na = _l2_normalize(a)
64
+ nb = _l2_normalize(b)
65
+ if na.shape != nb.shape:
66
+ return 0.0
67
+ return float(np.dot(na, nb))
68
+
69
+
70
+ def _crop_bbox(frame_bgr: np.ndarray, bbox: tuple[float, float, float, float]) -> np.ndarray | None:
71
+ h, w = frame_bgr.shape[:2]
72
+ x1 = max(0, min(w - 1, int(round(bbox[0]))))
73
+ y1 = max(0, min(h - 1, int(round(bbox[1]))))
74
+ x2 = max(x1 + 1, min(w, int(round(bbox[2]))))
75
+ y2 = max(y1 + 1, min(h, int(round(bbox[3]))))
76
+ if x2 - x1 < 4 or y2 - y1 < 4:
77
+ return None
78
+ return frame_bgr[y1:y2, x1:x2]
79
+
80
+
81
+ def _color_spatial_embedding(crop_bgr: np.ndarray) -> np.ndarray:
82
+ """Fast 96-dim spatial upper/lower-body HSV color descriptor (zero external weights)."""
83
+ resized = cv2.resize(crop_bgr, (48, 96), interpolation=cv2.INTER_AREA)
84
+ hsv = cv2.cvtColor(resized, cv2.COLOR_BGR2HSV)
85
+ parts = [hsv[:48, :, :], hsv[48:, :, :]] # upper body + lower body
86
+ feats: list[np.ndarray] = []
87
+ for part in parts:
88
+ h_hist = cv2.calcHist([part], [0], None, [24], [0, 180]).ravel()
89
+ s_hist = cv2.calcHist([part], [1], None, [12], [0, 256]).ravel()
90
+ v_hist = cv2.calcHist([part], [2], None, [12], [0, 256]).ravel()
91
+ feats.extend([h_hist, s_hist, v_hist])
92
+ return _l2_normalize(np.concatenate(feats).astype(np.float32))
93
+
94
+
95
+ class ReidEmbedder:
96
+ """Person identity embeddings: OSNet-AIN (ONNX) or a weight-free HSV color descriptor."""
97
+
98
+ def __init__(
99
+ self,
100
+ backend: ReidBackend = "osnet",
101
+ *,
102
+ device: str = "auto",
103
+ cache_dir: str | Path | None = None,
104
+ ) -> None:
105
+ if backend not in ("color", "osnet"):
106
+ raise ValueError(f"Unknown Re-ID backend '{backend}'. Choose 'osnet' or 'color'.")
107
+ self.backend: ReidBackend = backend
108
+ self._sess = None
109
+ self._input_name = ""
110
+ self._input_hw = (256, 128)
111
+ self._static_batch: int | None = None
112
+ if backend == "osnet":
113
+ spec = REID_REGISTRY["osnet"]
114
+ self._input_hw = spec.input_hw
115
+ # ONNX Runtime has no MPS provider; map mps to CPU. CoreML and TensorRT run with a
116
+ # fixed padded batch size in encode_images so the engine compiles only once.
117
+ eff_dev = "cpu" if device.lower().strip() == "mps" else device
118
+ self._sess, active_provider = create_onnx_session(
119
+ resolve_reid_model("osnet", cache_dir=cache_dir),
120
+ device=eff_dev,
121
+ trt_fp16=True,
122
+ cache_dir=cache_dir,
123
+ )
124
+ self._input_name = self._sess.get_inputs()[0].name
125
+ if active_provider in ("CoreMLExecutionProvider", "TensorrtExecutionProvider"):
126
+ self._static_batch = _STATIC_OSNET_BATCH
127
+
128
+ def _preprocess(self, crop_bgr: np.ndarray) -> np.ndarray:
129
+ h, w = self._input_hw
130
+ resized = cv2.resize(crop_bgr, (w, h), interpolation=cv2.INTER_LINEAR)
131
+ rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
132
+ x = rgb.astype(np.float32)
133
+ x *= _IMAGENET_SCALE
134
+ x += _IMAGENET_BIAS
135
+ return x.transpose(2, 0, 1)
136
+
137
+ def encode_images(self, crops: list[np.ndarray | None]) -> list[np.ndarray | None]:
138
+ """Embed a batch of BGR crops; ``None``/empty crops map to ``None``."""
139
+ out: list[np.ndarray | None] = [None] * len(crops)
140
+ valid = [i for i, c in enumerate(crops) if c is not None and c.size > 0]
141
+ if not valid:
142
+ return out
143
+ if self.backend == "color":
144
+ for i in valid:
145
+ out[i] = _color_spatial_embedding(crops[i]) # type: ignore[arg-type]
146
+ return out
147
+ assert self._sess is not None
148
+ if self._static_batch is None:
149
+ batch = np.stack([self._preprocess(crops[i]) for i in valid]) # type: ignore[arg-type]
150
+ embs = self._sess.run(None, {self._input_name: batch})[0]
151
+ for i, e in zip(valid, embs, strict=True):
152
+ out[i] = _l2_normalize(e)
153
+ return out
154
+
155
+ bs = self._static_batch
156
+ h, w = self._input_hw
157
+ buf = np.empty((bs, 3, h, w), dtype=np.float32)
158
+ for start in range(0, len(valid), bs):
159
+ chunk = valid[start : start + bs]
160
+ m = len(chunk)
161
+ for slot, idx in enumerate(chunk):
162
+ buf[slot] = self._preprocess(crops[idx]) # type: ignore[arg-type]
163
+ if m < bs:
164
+ buf[m:] = 0.0
165
+ embs = self._sess.run(None, {self._input_name: buf})[0]
166
+ for slot, idx in enumerate(chunk):
167
+ out[idx] = _l2_normalize(embs[slot])
168
+ return out
169
+
170
+ def encode_image(self, crop_bgr: np.ndarray | None) -> np.ndarray | None:
171
+ return self.encode_images([crop_bgr])[0]
172
+
173
+
174
+ class VlmEmbedder:
175
+ """CLIP / SigLIP image+text embeddings for natural-language queries and search."""
176
+
177
+ def __init__(
178
+ self,
179
+ backend: VlmBackend = "clip",
180
+ *,
181
+ precision: Precision = "int8",
182
+ device: str = "auto",
183
+ cache_dir: str | Path | None = None,
184
+ ) -> None:
185
+ if backend not in ("clip", "siglip", "siglip2"):
186
+ raise ValueError(
187
+ f"Unknown VLM backend '{backend}'. Choose 'clip', 'siglip', 'siglip2' or 'embeddinggemma'."
188
+ )
189
+ self.backend: VlmBackend = backend
190
+ self.precision = precision
191
+ self._vision_sess = None
192
+ self._text_sess = None
193
+ self._tokenizer: Tokenizer | None = None
194
+ self._image_size = (224, 224)
195
+ self._shortest_edge: int | None = None
196
+ self._mean = np.array([0.5, 0.5, 0.5], dtype=np.float32).reshape(3, 1, 1)
197
+ self._std = np.array([0.5, 0.5, 0.5], dtype=np.float32).reshape(3, 1, 1)
198
+ self._max_length = 77 if backend == "clip" else 64
199
+ self._text_cache: dict[str, np.ndarray] = {}
200
+
201
+ artifacts = resolve_vlm_artifacts(backend=backend, precision=precision, cache_dir=cache_dir)
202
+ req_dev = device.lower().strip()
203
+ if req_dev == "auto" and precision == "int8":
204
+ eff_dev = "cpu"
205
+ elif req_dev == "tensorrt" and precision == "int8":
206
+ # INT8 VLM graphs run on CUDA in a few ms without a multi-minute TRT engine build.
207
+ eff_dev = "cuda"
208
+ else:
209
+ eff_dev = device
210
+ # ONNX Runtime's default CoreML setup: MLProgram can't load these INT8 graphs, and
211
+ # NeuralNetwork limited to CPU and GPU returns NaN for some CLIP crops.
212
+ self._vision_sess, _ = create_onnx_session(
213
+ artifacts["vision_onnx"], device=eff_dev, coreml_format=None, cache_dir=cache_dir
214
+ )
215
+ self._text_sess, _ = create_onnx_session(
216
+ artifacts["text_onnx"], device=eff_dev, coreml_format=None, cache_dir=cache_dir
217
+ )
218
+ self._tokenizer = Tokenizer.from_file(str(artifacts["tokenizer"]))
219
+ self._load_preprocess(artifacts["preprocessor"], artifacts["config"])
220
+
221
+ @property
222
+ def supports_text(self) -> bool:
223
+ return self._text_sess is not None and self._tokenizer is not None
224
+
225
+ def _load_preprocess(self, prep_path: Path, config_path: Path) -> None:
226
+ if prep_path.is_file():
227
+ cfg = json.loads(prep_path.read_text(encoding="utf-8"))
228
+ if cfg.get("do_center_crop") and isinstance(cfg.get("size"), dict):
229
+ self._shortest_edge = cfg["size"].get("shortest_edge")
230
+ size = cfg.get("crop_size") or cfg.get("size") or {}
231
+ if isinstance(size, int):
232
+ self._image_size = (size, size)
233
+ elif isinstance(size, dict):
234
+ h = int(size.get("height", size.get("shortest_edge", 224)))
235
+ w = int(size.get("width", size.get("shortest_edge", 224)))
236
+ self._image_size = (h, w)
237
+ if "image_mean" in cfg:
238
+ self._mean = np.array(cfg["image_mean"], dtype=np.float32).reshape(3, 1, 1)
239
+ if "image_std" in cfg:
240
+ self._std = np.array(cfg["image_std"], dtype=np.float32).reshape(3, 1, 1)
241
+
242
+ if config_path.is_file():
243
+ mcfg = json.loads(config_path.read_text(encoding="utf-8"))
244
+ tcfg = mcfg.get("text_config", {})
245
+ if isinstance(tcfg, dict) and "max_position_embeddings" in tcfg:
246
+ self._max_length = int(tcfg["max_position_embeddings"])
247
+
248
+ def _preprocess_crop(self, crop_bgr: np.ndarray) -> np.ndarray:
249
+ th, tw = self._image_size
250
+ rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB)
251
+ if self._shortest_edge:
252
+ h, w = rgb.shape[:2]
253
+ scale = self._shortest_edge / min(h, w)
254
+ rh, rw = max(th, int(h * scale)), max(tw, int(w * scale))
255
+ resized = cv2.resize(rgb, (rw, rh), interpolation=cv2.INTER_CUBIC)
256
+ top, left = (rh - th) // 2, (rw - tw) // 2
257
+ resized = resized[top : top + th, left : left + tw]
258
+ else:
259
+ resized = cv2.resize(rgb, (tw, th), interpolation=cv2.INTER_CUBIC)
260
+ arr = resized.astype(np.float32) * (1.0 / 255.0)
261
+ chw = np.transpose(arr, (2, 0, 1))
262
+ chw = (chw - self._mean) / self._std
263
+ return np.expand_dims(chw, axis=0).astype(np.float32)
264
+
265
+ def encode_image(self, crop_bgr: np.ndarray | None) -> np.ndarray | None:
266
+ """Encode a BGR crop into an L2-normalized image embedding (text-aligned)."""
267
+ if crop_bgr is None or crop_bgr.size == 0:
268
+ return None
269
+ assert self._vision_sess is not None
270
+ inp = self._vision_sess.get_inputs()[0]
271
+ tensor = self._preprocess_crop(crop_bgr)
272
+ if "float16" in inp.type:
273
+ tensor = tensor.astype(np.float16)
274
+
275
+ outputs = self._vision_sess.run(None, {inp.name: tensor})
276
+ out_names = [o.name for o in self._vision_sess.get_outputs()]
277
+ by_name = dict(zip(out_names, outputs, strict=False))
278
+ emb = by_name.get("image_embeds")
279
+ if emb is None:
280
+ emb = by_name.get("pooler_output", outputs[0])
281
+ emb_arr = np.asarray(emb, dtype=np.float32)
282
+ if emb_arr.ndim == 3:
283
+ emb_arr = emb_arr[:, 0, :]
284
+ return _l2_normalize(emb_arr[0])
285
+
286
+ def encode_text(self, query: str) -> np.ndarray:
287
+ """Encode a natural-language query into the shared vision-language embedding space."""
288
+ cleaned = query.strip()
289
+ if cleaned in self._text_cache:
290
+ return self._text_cache[cleaned]
291
+ assert self._tokenizer is not None and self._text_sess is not None
292
+ self._tokenizer.enable_truncation(max_length=self._max_length)
293
+ text = cleaned
294
+ if self.backend == "siglip":
295
+ self._tokenizer.enable_padding(length=self._max_length, pad_id=1)
296
+ elif self.backend == "siglip2":
297
+ self._tokenizer.enable_padding(length=self._max_length, pad_id=0)
298
+ text = cleaned.lower()
299
+ else:
300
+ self._tokenizer.no_padding()
301
+
302
+ enc = self._tokenizer.encode(text)
303
+ input_ids = np.array([enc.ids], dtype=np.int64)
304
+ attention_mask = np.array([enc.attention_mask], dtype=np.int64)
305
+
306
+ feed: dict[str, np.ndarray] = {}
307
+ for inp in self._text_sess.get_inputs():
308
+ if inp.name == "input_ids":
309
+ feed[inp.name] = input_ids
310
+ elif inp.name == "attention_mask":
311
+ feed[inp.name] = attention_mask
312
+
313
+ outputs = self._text_sess.run(None, feed)
314
+ out_names = [o.name for o in self._text_sess.get_outputs()]
315
+ by_name = dict(zip(out_names, outputs, strict=False))
316
+ emb = by_name.get("text_embeds")
317
+ if emb is None:
318
+ emb = by_name.get("pooler_output", outputs[0])
319
+ emb_arr = np.asarray(emb, dtype=np.float32)
320
+ if emb_arr.ndim == 3:
321
+ emb_arr = emb_arr[:, 0, :]
322
+ vec = _l2_normalize(emb_arr[0])
323
+ self._text_cache[cleaned] = vec
324
+ return vec
325
+
326
+ @staticmethod
327
+ def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
328
+ return cosine_similarity(a, b)
329
+
330
+
331
+ class EmbeddingGemmaEmbedder(VlmEmbedder):
332
+ """EmbeddingGemma 2 image+text embeddings in PyTorch, for ``--vlm embeddinggemma``.
333
+
334
+ Needs ``trackflow-python[transformers]``. The audio encoder is not loaded, and each crop is
335
+ encoded with 70 vision tokens instead of the model's default 280: on person crops that is
336
+ about 5 times faster and at least as accurate. Weights load in bfloat16 on MPS and on CUDA
337
+ GPUs that support it, else in float32.
338
+ """
339
+
340
+ _VISION_TOKENS = 70
341
+
342
+ def __init__(self, *, device: str = "auto", cache_dir: str | Path | None = None) -> None:
343
+ try:
344
+ import torch
345
+ from PIL import Image
346
+ from sentence_transformers import SentenceTransformer
347
+ except ImportError as exc:
348
+ raise ImportError(
349
+ "Install 'trackflow-python[transformers]' to use --vlm embeddinggemma."
350
+ ) from exc
351
+ if device == "auto":
352
+ device = (
353
+ "cuda"
354
+ if torch.cuda.is_available()
355
+ else "mps"
356
+ if torch.backends.mps.is_available()
357
+ else "cpu"
358
+ )
359
+ elif device == "coreml":
360
+ device = "mps"
361
+ if device not in ("cpu", "cuda", "mps"):
362
+ raise ValueError(
363
+ "--vlm embeddinggemma supports --device auto, cpu, cuda, mps or coreml."
364
+ )
365
+ bf16 = device == "mps" or (device == "cuda" and torch.cuda.is_bf16_supported())
366
+ spec = VLM_REGISTRY["embeddinggemma"]
367
+ self.backend = "embeddinggemma"
368
+ self._image_cls = Image
369
+ self._text_cache = {}
370
+ self._model = SentenceTransformer(
371
+ spec.repo_id,
372
+ revision=spec.revision,
373
+ device=device,
374
+ cache_folder=str(cache_dir) if cache_dir is not None else None,
375
+ config_kwargs={"audio_config": None},
376
+ model_kwargs={"dtype": torch.bfloat16 if bf16 else torch.float32},
377
+ )
378
+ processor = self._model[0].processor
379
+ processor.image_processor.max_soft_tokens = self._VISION_TOKENS
380
+ processor.image_processor.image_seq_length = self._VISION_TOKENS
381
+ processor.image_seq_length = self._VISION_TOKENS
382
+
383
+ @property
384
+ def supports_text(self) -> bool:
385
+ return True
386
+
387
+ def encode_image(self, crop_bgr: np.ndarray | None) -> np.ndarray | None:
388
+ """Encode a BGR crop into an L2-normalized image embedding (text-aligned)."""
389
+ if crop_bgr is None or crop_bgr.size == 0:
390
+ return None
391
+ image = self._image_cls.fromarray(cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB))
392
+ emb = self._model.encode([{"image": image}], show_progress_bar=False)
393
+ return _l2_normalize(emb[0])
394
+
395
+ def encode_text(self, query: str) -> np.ndarray:
396
+ """Encode a natural-language query with the model's search-query prompt."""
397
+ cleaned = query.strip()
398
+ if cleaned not in self._text_cache:
399
+ emb = self._model.encode([cleaned], prompt_name="SearchQuery", show_progress_bar=False)
400
+ self._text_cache[cleaned] = _l2_normalize(emb[0])
401
+ return self._text_cache[cleaned]
402
+
403
+
404
+ def create_vlm_embedder(
405
+ backend: str, *, device: str = "auto", cache_dir: str | Path | None = None
406
+ ) -> VlmEmbedder:
407
+ """Load the ``--vlm`` embedder: CLIP and SigLIP in ONNX Runtime, EmbeddingGemma 2 in PyTorch."""
408
+ if backend == "embeddinggemma":
409
+ return EmbeddingGemmaEmbedder(device=device, cache_dir=cache_dir)
410
+ # ONNX Runtime has no MPS provider; CLIP and SigLIP fall back to the CPU there.
411
+ onnx_device = "cpu" if device == "mps" else device
412
+ return VlmEmbedder(backend, device=onnx_device, cache_dir=cache_dir) # type: ignore[arg-type]
413
+
414
+
415
+ class TrackCardIndex:
416
+ """Persistent Track Cards, NL query scores, and opt-in cross-exit identity merges.
417
+
418
+ Cross-exit merging (``reid_merge=True``, requires a :class:`ReidEmbedder`) gives a returning
419
+ person their earlier ID. A new track is compared only after ``merge_min_samples`` identity
420
+ samples, only against cards that ended at least ``min_exit_gap_frames`` before it started (so
421
+ two people visible at the same time can never share an ID), and it merges only when the best
422
+ match clears ``reid_merge_threshold`` *and* beats the runner-up by ``reid_merge_margin``.
423
+ Look-alikes (e.g. several people in dark jackets) are left unmerged rather than guessed.
424
+ """
425
+
426
+ def __init__(
427
+ self,
428
+ *,
429
+ vlm: VlmEmbedder | None = None,
430
+ reid: ReidEmbedder | None = None,
431
+ query: str | None = None,
432
+ query_threshold: float | None = None,
433
+ reid_merge: bool = False,
434
+ reid_merge_threshold: float = 0.80,
435
+ reid_merge_margin: float = 0.05,
436
+ merge_min_samples: int = 3,
437
+ reid_sample_every: int = 3,
438
+ min_reid_height: float = 48.0,
439
+ min_exit_gap_frames: int = 8,
440
+ crops_dir: Path | None = None,
441
+ ) -> None:
442
+ if reid_merge and reid is None:
443
+ raise ValueError("Cross-exit merging needs a person Re-ID embedder (--reid osnet).")
444
+ self.vlm = vlm
445
+ self.reid = reid
446
+ self.query = query.strip() if query else None
447
+ if query_threshold is None:
448
+ query_threshold = QUERY_THRESHOLDS.get(vlm.backend if vlm else "none", 0.22)
449
+ self.query_threshold = float(query_threshold)
450
+ self.reid_merge = bool(reid_merge)
451
+ self.reid_merge_threshold = float(reid_merge_threshold)
452
+ self.reid_merge_margin = float(reid_merge_margin)
453
+ self.merge_min_samples = max(1, int(merge_min_samples))
454
+ self.reid_sample_every = max(1, int(reid_sample_every))
455
+ self.min_reid_height = float(min_reid_height)
456
+ self.min_exit_gap_frames = int(min_exit_gap_frames)
457
+ self.crops_dir = crops_dir
458
+
459
+ self._query_vec: np.ndarray | None = None
460
+ if self.query and self.vlm is not None and self.vlm.supports_text:
461
+ self._query_vec = self.vlm.encode_text(self.query)
462
+
463
+ self.cards: dict[int, TrackCard] = {}
464
+ self._vlm_sum: dict[int, np.ndarray] = {} # sum of a card's sampled crop embeddings
465
+ self._vlm_emb: dict[int, np.ndarray] = {} # its normalized mean
466
+ self._next_embed_s: dict[int, float] = {}
467
+ self._reid_sum: dict[int, np.ndarray] = {}
468
+ self._alias: dict[int, int] = {} # raw tracker ID -> canonical card ID
469
+ self._raw_first_frame: dict[int, int] = {}
470
+ self._pending: dict[int, list[np.ndarray]] = {}
471
+ self._decided: set[int] = set()
472
+ self.reid_merges: int = 0
473
+
474
+ def canonical_id(self, raw_track_id: int) -> int:
475
+ cid = raw_track_id
476
+ while cid in self._alias:
477
+ cid = self._alias[cid]
478
+ return cid
479
+
480
+ def _reid_vec(self, cid: int) -> np.ndarray | None:
481
+ s = self._reid_sum.get(cid)
482
+ return None if s is None else _l2_normalize(s)
483
+
484
+ def _try_merge(self, raw: int, class_name: str, visible: set[int]) -> tuple[int, float] | None:
485
+ samples = self._pending.pop(raw, [])
486
+ self._decided.add(raw)
487
+ if not samples:
488
+ return None
489
+ new_vec = _l2_normalize(np.mean(samples, axis=0))
490
+ start = self._raw_first_frame[raw]
491
+ sims: list[tuple[float, int]] = []
492
+ for cid, card in self.cards.items():
493
+ if cid in visible or card.class_name != class_name:
494
+ continue
495
+ if start - card.last_frame < self.min_exit_gap_frames:
496
+ continue # overlaps in time (or too recent) -> must be someone else
497
+ vec = self._reid_vec(cid)
498
+ if vec is not None:
499
+ sims.append((float(np.dot(new_vec, vec)), cid))
500
+ if not sims:
501
+ return None
502
+ sims.sort(reverse=True)
503
+ best, best_cid = sims[0]
504
+ runner_up = sims[1][0] if len(sims) > 1 else -1.0
505
+ if best >= self.reid_merge_threshold and best - runner_up >= self.reid_merge_margin:
506
+ return best_cid, best
507
+ return None
508
+
509
+ def _fold_card(self, src_id: int, dst_id: int) -> None:
510
+ src = self.cards.pop(src_id)
511
+ dst = self.cards[dst_id]
512
+ if src.first_frame < dst.first_frame:
513
+ dst.first_frame, dst.first_timestamp_s = src.first_frame, src.first_timestamp_s
514
+ if src.last_frame > dst.last_frame:
515
+ dst.last_frame, dst.last_timestamp_s = src.last_frame, src.last_timestamp_s
516
+ dst.frame_count += src.frame_count
517
+ if src.best_confidence > dst.best_confidence:
518
+ dst.best_confidence, dst.best_frame, dst.best_bbox = (
519
+ src.best_confidence,
520
+ src.best_frame,
521
+ src.best_bbox,
522
+ )
523
+ dst.thumbnail_relpath = src.thumbnail_relpath or dst.thumbnail_relpath
524
+ for z in src.zones_visited:
525
+ if z not in dst.zones_visited:
526
+ dst.zones_visited.append(z)
527
+ for z, s in src.dwell_seconds.items():
528
+ dst.dwell_seconds[z] = dst.dwell_seconds.get(z, 0.0) + s
529
+ dst.merged_track_ids.extend([src_id, *src.merged_track_ids])
530
+
531
+ if src_id in self._reid_sum:
532
+ self._reid_sum[dst_id] = self._reid_sum.get(dst_id, 0.0) + self._reid_sum.pop(src_id)
533
+ if src_id in self._vlm_sum:
534
+ self._vlm_sum[dst_id] = self._vlm_sum.get(dst_id, 0.0) + self._vlm_sum.pop(src_id)
535
+ self._vlm_emb.pop(src_id, None)
536
+ self._vlm_emb[dst_id] = _l2_normalize(self._vlm_sum[dst_id])
537
+ dst.embedding = [round(float(x), 5) for x in self._vlm_emb[dst_id].tolist()]
538
+
539
+ def update(
540
+ self,
541
+ frame_idx: int,
542
+ timestamp_s: float,
543
+ frame_bgr: np.ndarray,
544
+ tracks: list[Track],
545
+ frame_dt_s: float = 0.0,
546
+ ) -> list[dict[str, Any]]:
547
+ """Update Track Cards, perform opt-in cross-exit merges, and score NL queries."""
548
+ events: list[dict[str, Any]] = []
549
+
550
+ # Pass 1: crops + batched identity embeddings.
551
+ crops: list[np.ndarray | None] = []
552
+ reid_crops: list[np.ndarray | None] = []
553
+ for tr in tracks:
554
+ raw = tr.track_id
555
+ is_new = raw not in self._raw_first_frame
556
+ if is_new:
557
+ self._raw_first_frame[raw] = frame_idx
558
+ crop = _crop_bbox(frame_bgr, tr.bbox)
559
+ crops.append(crop)
560
+ want = (
561
+ self.reid_merge
562
+ and self.reid is not None
563
+ and tr.class_name.lower() == "person"
564
+ and crop is not None
565
+ and tr.height >= self.min_reid_height
566
+ and (is_new or frame_idx % self.reid_sample_every == 0)
567
+ )
568
+ reid_crops.append(crop if want else None)
569
+ reid_embs = (
570
+ self.reid.encode_images(reid_crops)
571
+ if self.reid is not None and any(c is not None for c in reid_crops)
572
+ else [None] * len(tracks)
573
+ )
574
+
575
+ # Pass 2: merges, cards, query scores.
576
+ visible = {self.canonical_id(tr.track_id) for tr in tracks} if self.reid_merge else set()
577
+ for tr, crop, remb in zip(tracks, crops, reid_embs, strict=True):
578
+ raw = tr.track_id
579
+ cid = self.canonical_id(raw)
580
+
581
+ card = self.cards.get(cid)
582
+ if card is None:
583
+ card = TrackCard(
584
+ track_id=cid,
585
+ class_name=tr.class_name,
586
+ first_frame=frame_idx,
587
+ last_frame=frame_idx,
588
+ first_timestamp_s=timestamp_s,
589
+ last_timestamp_s=timestamp_s,
590
+ frame_count=1,
591
+ best_confidence=tr.confidence,
592
+ best_frame=frame_idx,
593
+ best_bbox=tr.bbox,
594
+ )
595
+ self.cards[cid] = card
596
+ self._save_crop(card, crop)
597
+ else:
598
+ card.last_frame = frame_idx
599
+ card.last_timestamp_s = timestamp_s
600
+ card.frame_count += 1
601
+ if tr.confidence > card.best_confidence:
602
+ card.best_confidence = tr.confidence
603
+ card.best_frame = frame_idx
604
+ card.best_bbox = tr.bbox
605
+ self._save_crop(card, crop)
606
+
607
+ if remb is not None:
608
+ self._reid_sum[cid] = self._reid_sum.get(cid, 0.0) + remb
609
+
610
+ # Opt-in cross-exit merge, decided once per raw track after enough samples.
611
+ if self.reid_merge and raw not in self._decided and raw not in self._alias:
612
+ if remb is not None:
613
+ self._pending.setdefault(raw, []).append(remb)
614
+ if len(self._pending.get(raw, [])) >= self.merge_min_samples:
615
+ hit = self._try_merge(raw, tr.class_name, visible)
616
+ if hit is not None:
617
+ dst, sim = hit
618
+ self._fold_card(raw, dst)
619
+ self._alias[raw] = dst
620
+ self.reid_merges += 1
621
+ events.append(
622
+ {
623
+ "type": "reid_cross_exit_merge",
624
+ "raw_track_id": raw,
625
+ "canonical_track_id": dst,
626
+ "similarity": round(sim, 3),
627
+ }
628
+ )
629
+ cid = dst
630
+ visible.add(dst)
631
+ card = self.cards[cid]
632
+
633
+ if cid != raw:
634
+ tr.reid_merged_from = raw
635
+ tr.track_id = cid
636
+
637
+ if tr.zone is not None:
638
+ if tr.zone not in card.zones_visited:
639
+ card.zones_visited.append(tr.zone)
640
+ card.dwell_seconds[tr.zone] = card.dwell_seconds.get(tr.zone, 0.0) + frame_dt_s
641
+
642
+ # Text-aligned embedding for --query scoring and post-run search: the mean of crops
643
+ # taken when the track is first seen and at ages 1, 2, 4, 8 s and so on, so a long
644
+ # track costs a few encoder calls instead of one every few frames.
645
+ due = self._next_embed_s.get(cid)
646
+ if self.vlm is not None and crop is not None and (due is None or timestamp_s >= due):
647
+ vemb = self.vlm.encode_image(crop)
648
+ if vemb is not None:
649
+ self._vlm_sum[cid] = self._vlm_sum.get(cid, 0.0) + vemb
650
+ self._vlm_emb[cid] = _l2_normalize(self._vlm_sum[cid])
651
+ card.embedding = [round(float(x), 5) for x in self._vlm_emb[cid].tolist()]
652
+ age_s = timestamp_s - card.first_timestamp_s
653
+ self._next_embed_s[cid] = timestamp_s + max(1.0, age_s)
654
+
655
+ if self._query_vec is not None and cid in self._vlm_emb:
656
+ score = cosine_similarity(self._vlm_emb[cid], self._query_vec)
657
+ card.query_score = score
658
+ card.query_match = score >= self.query_threshold
659
+ tr.query_score = score
660
+ tr.query_match = card.query_match
661
+
662
+ return events
663
+
664
+ def _save_crop(self, card: TrackCard, crop_bgr: np.ndarray | None) -> None:
665
+ if self.crops_dir is None or crop_bgr is None:
666
+ return
667
+ self.crops_dir.mkdir(parents=True, exist_ok=True)
668
+ filename = f"track_{card.track_id:04d}.jpg"
669
+ out_path = self.crops_dir / filename
670
+ cv2.imwrite(str(out_path), crop_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 85])
671
+ card.thumbnail_relpath = f"crops/{filename}"
672
+
673
+ def sorted_cards(self) -> list[TrackCard]:
674
+ return sorted(self.cards.values(), key=lambda c: c.track_id)
675
+
676
+ def save_json(
677
+ self, path: Path, *, reid_backend: str = "none", vlm_backend: str = "none"
678
+ ) -> None:
679
+ payload = {
680
+ "reid_backend": reid_backend,
681
+ "vlm_backend": vlm_backend,
682
+ "query": self.query,
683
+ "query_threshold": self.query_threshold,
684
+ "reid_merges": self.reid_merges,
685
+ "cards": [c.to_dict(include_embedding=True) for c in self.sorted_cards()],
686
+ }
687
+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
688
+
689
+
690
+ def search_track_cards(
691
+ run_dir: str | Path,
692
+ query: str,
693
+ *,
694
+ top_k: int = 10,
695
+ min_score: float = -1.0,
696
+ embedder: VlmEmbedder | None = None,
697
+ ) -> list[dict[str, Any]]:
698
+ """Search saved Track Cards in a run directory using a natural-language query."""
699
+ run_path = Path(run_dir)
700
+ cards_path = run_path / "track_cards.json" if run_path.is_dir() else run_path
701
+ if not cards_path.is_file():
702
+ raise FileNotFoundError(f"No track_cards.json found at {cards_path}")
703
+
704
+ payload = json.loads(cards_path.read_text(encoding="utf-8"))
705
+ backend = payload.get("vlm_backend")
706
+ if backend in (None, "none") and payload.get("reid_backend") in ("clip", "siglip"):
707
+ backend = payload["reid_backend"] # runs recorded before --vlm existed
708
+ cards: list[dict[str, Any]] = payload.get("cards", [])
709
+
710
+ if embedder is None:
711
+ if backend not in ("clip", "siglip", "siglip2", "embeddinggemma"):
712
+ raise ValueError(
713
+ "This run has no text-aligned embeddings. Re-run with `--vlm clip` (or "
714
+ "`--vlm siglip`, `--vlm siglip2`, `--vlm embeddinggemma`, or any `--query`) "
715
+ "to enable natural-language search."
716
+ )
717
+ embedder = create_vlm_embedder(backend)
718
+
719
+ q_vec = embedder.encode_text(query)
720
+ scored: list[dict[str, Any]] = []
721
+ for card in cards:
722
+ emb = card.get("embedding")
723
+ if not emb:
724
+ continue
725
+ score = cosine_similarity(np.asarray(emb, dtype=np.float32), q_vec)
726
+ if score >= min_score:
727
+ item = {k: v for k, v in card.items() if k != "embedding"}
728
+ item["search_score"] = round(float(score), 4)
729
+ scored.append(item)
730
+
731
+ scored.sort(key=lambda r: r["search_score"], reverse=True)
732
+ return scored[:top_k]
733
+
734
+
735
+ def export_search_prompts(
736
+ run_dir: str | Path,
737
+ query: str,
738
+ hits: list[dict[str, Any]],
739
+ output_path: str | Path,
740
+ *,
741
+ pad_s: float = 0.0,
742
+ ) -> Path:
743
+ """Export top search hits as a prompt manifest for downstream mask models (e.g., SAM 3) or VLMs.
744
+
745
+ Uses only metadata already recorded in ``summary.json`` and ``track_cards.json``, adding zero
746
+ external dependencies. Each hit includes pixel ``bbox_xyxy``, normalized ``[0, 1]``
747
+ ``sam3_box_xywh_norm`` and ``sam3_point_xy_norm`` at ``prompt_frame`` (the track's highest-
748
+ confidence observation), plus padded time/frame bounds for windowed video propagation.
749
+ """
750
+ run_path = Path(run_dir)
751
+ if run_path.is_file():
752
+ run_path = run_path.parent
753
+ summary_path = run_path / "summary.json"
754
+ if not summary_path.is_file():
755
+ raise FileNotFoundError(
756
+ f"Exporting prompts requires summary.json with video dimensions and FPS at {summary_path}."
757
+ )
758
+ summary: dict[str, Any] = json.loads(summary_path.read_text(encoding="utf-8"))
759
+ width = float(summary.get("frame_width") or 0.0)
760
+ height = float(summary.get("frame_height") or 0.0)
761
+ fps = float(summary.get("source_fps") or 0.0)
762
+ if width <= 0.0 or height <= 0.0 or fps <= 0.0:
763
+ raise ValueError(
764
+ f"{summary_path} must contain positive frame_width, frame_height, and source_fps."
765
+ )
766
+ total_frames = int(summary.get("total_frames") or 0)
767
+ pad_frames = int(round(max(0.0, pad_s) * fps))
768
+
769
+ prompts: list[dict[str, Any]] = []
770
+ for h in hits:
771
+ first_f = int(h["first_frame"])
772
+ last_f = int(h["last_frame"])
773
+ start_f = max(0, first_f - pad_frames)
774
+ end_f = min(total_frames - 1, last_f + pad_frames) if total_frames > 0 else last_f + pad_frames
775
+ rx1, ry1, rx2, ry2 = [float(v) for v in h["best_bbox"]]
776
+ # Clip Kalman/raw boxes strictly inside the frame so SAM 3 normalized coordinates stay in [0, 1].
777
+ x1 = float(np.clip(rx1, 0.0, width))
778
+ y1 = float(np.clip(ry1, 0.0, height))
779
+ x2 = float(np.clip(rx2, 0.0, width))
780
+ y2 = float(np.clip(ry2, 0.0, height))
781
+ if x2 <= x1 or y2 <= y1:
782
+ continue
783
+ prompts.append(
784
+ {
785
+ "track_id": int(h["track_id"]),
786
+ "class_name": str(h["class_name"]),
787
+ "search_score": float(h["search_score"]),
788
+ "start_frame": start_f,
789
+ "end_frame": end_f,
790
+ "start_s": round(start_f / fps, 3),
791
+ "end_s": round(end_f / fps, 3),
792
+ "prompt_frame": int(h["best_frame"]),
793
+ "bbox_xyxy": [round(x1, 2), round(y1, 2), round(x2, 2), round(y2, 2)],
794
+ "sam3_box_xywh_norm": [
795
+ round(x1 / width, 6),
796
+ round(y1 / height, 6),
797
+ round((x2 - x1) / width, 6),
798
+ round((y2 - y1) / height, 6),
799
+ ],
800
+ "sam3_point_xy_norm": [
801
+ round(0.5 * (x1 + x2) / width, 6),
802
+ round(0.5 * (y1 + y2) / height, 6),
803
+ ],
804
+ }
805
+ )
806
+
807
+ manifest = {
808
+ "schema": "trackflow.prompts.v1",
809
+ "query": query,
810
+ "source": summary.get("source"),
811
+ "frame_width": int(width) if width > 0 else None,
812
+ "frame_height": int(height) if height > 0 else None,
813
+ "source_fps": fps if fps > 0 else None,
814
+ "prompts": prompts,
815
+ }
816
+ out = Path(output_path)
817
+ out.parent.mkdir(parents=True, exist_ok=True)
818
+ out.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
819
+ return out