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