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.
trackflow/pipeline.py ADDED
@@ -0,0 +1,1473 @@
1
+ """End-to-end Trackflow video/webcam/directory tracking pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import queue
8
+ import re
9
+ import signal
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import warnings
14
+ from collections import defaultdict
15
+ from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
16
+ from itertools import count
17
+ from pathlib import Path
18
+ from typing import Any
19
+ from urllib.parse import urlsplit, urlunsplit
20
+
21
+ import cv2
22
+ import numpy as np
23
+
24
+ from trackflow.detector import Detector, _allowed_classes, _class_key, create_detector
25
+ from trackflow.homography import FloorplanHomography
26
+ from trackflow.lines import CountingLine, LineCounter
27
+ from trackflow.mask_fallback import (
28
+ MaskFallbackConfig,
29
+ MaskFallbackResolver,
30
+ MaskPropagator,
31
+ )
32
+ from trackflow.models import Precision
33
+ from trackflow.postprocess import postprocess_records
34
+ from trackflow.privacy import AnonymizeMode, PrivacyAnonymizer
35
+ from trackflow.reid import (
36
+ QUERY_THRESHOLDS,
37
+ ReidBackend,
38
+ ReidEmbedder,
39
+ TrackCardIndex,
40
+ VlmBackend,
41
+ VlmEmbedder,
42
+ create_vlm_embedder,
43
+ )
44
+ from trackflow.sinks import ObservationWriter, draw_tracks, write_run_report
45
+ from trackflow.tracker import Tracker, compute_iou_matrix, create_tracker, iou_buffer_for_interval
46
+ from trackflow.types import Detection, FrameResult, RunSummary, Track
47
+
48
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
49
+
50
+
51
+ def fresh_run_dir(stem: str = "run", parent: str | Path = "runs") -> Path:
52
+ """Create and return the first unused ``<parent>/<stem>-N`` directory."""
53
+ for number in count(1):
54
+ path = Path(parent) / f"{stem}-{number}"
55
+ try:
56
+ path.mkdir(parents=True)
57
+ except FileExistsError:
58
+ continue
59
+ return path
60
+ raise AssertionError("unreachable")
61
+
62
+
63
+ @contextlib.contextmanager
64
+ def _stop_on_interrupt() -> Iterator[threading.Event]:
65
+ """Turn the first Ctrl-C into a stop request that ``run`` checks between frames.
66
+
67
+ After that first Ctrl-C the previous handler is back, so a second one interrupts as usual.
68
+ Signal handlers can only be set from the main thread; elsewhere Ctrl-C keeps its default.
69
+ """
70
+ stop = threading.Event()
71
+ previous = signal.getsignal(signal.SIGINT)
72
+ if threading.current_thread() is not threading.main_thread() or previous is None:
73
+ yield stop
74
+ return
75
+
76
+ def request_stop(signum: int, frame: Any) -> None:
77
+ stop.set()
78
+ signal.signal(signal.SIGINT, previous)
79
+
80
+ signal.signal(signal.SIGINT, request_stop)
81
+ try:
82
+ yield stop
83
+ finally:
84
+ signal.signal(signal.SIGINT, previous)
85
+
86
+
87
+ @contextlib.contextmanager
88
+ def _run_directory(output_dir: str | Path | None) -> Iterator[Path]:
89
+ if output_dir is None:
90
+ path = fresh_run_dir()
91
+ created = True
92
+ else:
93
+ path = Path(output_dir)
94
+ created = not path.exists()
95
+ path.mkdir(parents=True, exist_ok=True)
96
+
97
+ # Two callers can arrive at an existing empty directory simultaneously.
98
+ lock = path / ".trackflow-running"
99
+ try:
100
+ lock.touch(exist_ok=False)
101
+ except FileExistsError as exc:
102
+ raise FileExistsError(f"Output {path} is in use. Choose a fresh output directory.") from exc
103
+ try:
104
+ if any(p != lock for p in path.iterdir()):
105
+ raise FileExistsError(
106
+ f"Output {path} is not empty. Choose a fresh output directory (-o)."
107
+ )
108
+ yield path
109
+ except BaseException:
110
+ # A run that fails before writing anything leaves no empty folder behind.
111
+ lock.unlink(missing_ok=True)
112
+ if created and not any(path.iterdir()):
113
+ path.rmdir()
114
+ raise
115
+ finally:
116
+ lock.unlink(missing_ok=True)
117
+
118
+
119
+ def _is_stream_url(source: str | Path | int) -> bool:
120
+ return isinstance(source, str) and source.lower().startswith(
121
+ ("rtsp://", "rtsps://", "http://", "https://")
122
+ )
123
+
124
+
125
+ def _is_camera_source(source: str | Path | int) -> bool:
126
+ return isinstance(source, int) or (
127
+ isinstance(source, str)
128
+ and (source.isdigit() or source.lower() == "camera")
129
+ and not Path(source).exists()
130
+ )
131
+
132
+
133
+ def _is_live_source(source: str | Path | int) -> bool:
134
+ return _is_camera_source(source) or _is_stream_url(source)
135
+
136
+
137
+ _WRITER_STOP = object()
138
+
139
+
140
+ @contextlib.contextmanager
141
+ def _prefetch_frames(
142
+ frame_iter: Generator[tuple[int, float, np.ndarray], None, None],
143
+ *,
144
+ maxsize: int = 2,
145
+ ) -> Iterator[Iterator[tuple[int, float, np.ndarray]]]:
146
+ """Decode frames one step ahead on a worker thread so file I/O overlaps inference."""
147
+ q: queue.Queue[tuple[str, Any]] = queue.Queue(maxsize=maxsize)
148
+ cancel = threading.Event()
149
+
150
+ def _put(item: tuple[str, Any]) -> bool:
151
+ while not cancel.is_set():
152
+ try:
153
+ q.put(item, timeout=0.05)
154
+ return True
155
+ except queue.Full:
156
+ continue
157
+ return False
158
+
159
+ def _reader() -> None:
160
+ try:
161
+ for item in frame_iter:
162
+ if not _put(("frame", item)):
163
+ return
164
+ _put(("eof", None))
165
+ except BaseException as exc:
166
+ _put(("error", exc))
167
+ finally:
168
+ frame_iter.close()
169
+
170
+ thread = threading.Thread(target=_reader, name="trackflow-frame-reader", daemon=True)
171
+ thread.start()
172
+
173
+ def _consume() -> Iterator[tuple[int, float, np.ndarray]]:
174
+ while True:
175
+ kind, payload = q.get()
176
+ if kind == "frame":
177
+ yield payload
178
+ elif kind == "eof":
179
+ return
180
+ else:
181
+ raise payload
182
+
183
+ try:
184
+ yield _consume()
185
+ finally:
186
+ cancel.set()
187
+ while True:
188
+ try:
189
+ q.get_nowait()
190
+ except queue.Empty:
191
+ break
192
+ thread.join()
193
+
194
+
195
+ class _AsyncVideoWriter:
196
+ """Render annotations and encode video frames on a worker thread with bounded backpressure."""
197
+
198
+ def __init__(
199
+ self,
200
+ video_writer: cv2.VideoWriter,
201
+ render_fn: Callable[..., np.ndarray],
202
+ *,
203
+ maxsize: int = 2,
204
+ ) -> None:
205
+ self._video_writer = video_writer
206
+ self._render_fn = render_fn
207
+ self._queue: queue.Queue[Any] = queue.Queue(maxsize=maxsize)
208
+ self._abort = threading.Event()
209
+ self._error: BaseException | None = None
210
+ self._closed = False
211
+ self._thread = threading.Thread(
212
+ target=self._worker, name="trackflow-video-writer", daemon=True
213
+ )
214
+ self._thread.start()
215
+
216
+ def _worker(self) -> None:
217
+ try:
218
+ while True:
219
+ item = self._queue.get()
220
+ if item is _WRITER_STOP:
221
+ return
222
+ if self._abort.is_set():
223
+ continue
224
+ rendered = self._render_fn(*item)
225
+ self._video_writer.write(rendered)
226
+ except BaseException as exc:
227
+ self._error = exc
228
+ self._abort.set()
229
+
230
+ def submit(self, *args: Any) -> None:
231
+ while True:
232
+ if self._error is not None:
233
+ raise self._error
234
+ try:
235
+ self._queue.put(args, timeout=0.05)
236
+ return
237
+ except queue.Full:
238
+ continue
239
+
240
+ def close(self, *, abort: bool = False) -> None:
241
+ if self._closed:
242
+ return
243
+ self._closed = True
244
+ if abort:
245
+ self._abort.set()
246
+ while True:
247
+ try:
248
+ self._queue.get_nowait()
249
+ except queue.Empty:
250
+ break
251
+ while self._thread.is_alive():
252
+ try:
253
+ self._queue.put(_WRITER_STOP, timeout=0.05)
254
+ break
255
+ except queue.Full:
256
+ continue
257
+ self._thread.join()
258
+ if not abort and self._error is not None:
259
+ raise self._error
260
+
261
+
262
+ def _source_label(source: str | Path | int) -> str:
263
+ if not _is_stream_url(source):
264
+ return str(source)
265
+ url = urlsplit(str(source))
266
+ return urlunsplit((url.scheme, url.netloc.rsplit("@", 1)[-1], url.path, "", ""))
267
+
268
+
269
+ def _iter_frames(
270
+ source: str | Path | int,
271
+ *,
272
+ max_frames: int | None = None,
273
+ fps: float | None = None,
274
+ ) -> tuple[Generator[tuple[int, float, np.ndarray], None, None], float, int, int, int]:
275
+ """Open files, image sequences, OpenCV network streams or cameras."""
276
+ if fps is not None and (not np.isfinite(fps) or fps <= 0):
277
+ raise ValueError("fps must be positive and finite.")
278
+ is_camera = _is_camera_source(source)
279
+ if is_camera:
280
+ capture_source = 0 if str(source).lower() == "camera" else int(source)
281
+ elif _is_stream_url(source):
282
+ capture_source = str(source)
283
+ else:
284
+ path = Path(source)
285
+ if path.is_dir():
286
+
287
+ def natural_order(p: Path) -> list[int | str]:
288
+ return [
289
+ int(part) if part.isdecimal() else part
290
+ for part in re.split(r"(\d+)", p.name.casefold())
291
+ ]
292
+
293
+ images = sorted(
294
+ (p for p in path.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXTS),
295
+ key=natural_order,
296
+ )
297
+ if not images:
298
+ raise FileNotFoundError(f"No images found in directory: {path}")
299
+ first = cv2.imread(str(images[0]))
300
+ if first is None:
301
+ raise RuntimeError(f"Failed to read image: {images[0]}")
302
+ h, w = first.shape[:2]
303
+ rate = fps or 25.0
304
+ total = min(len(images), max_frames) if max_frames is not None else len(images)
305
+
306
+ def images_iter() -> Generator[tuple[int, float, np.ndarray], None, None]:
307
+ for idx, p in enumerate(images[:total]):
308
+ frame = first if idx == 0 else cv2.imread(str(p))
309
+ if frame is None or frame.shape[:2] != (h, w):
310
+ raise ValueError(f"Expected a readable {w}x{h} image at {p}")
311
+ yield idx, idx / rate, frame
312
+
313
+ return images_iter(), rate, w, h, total
314
+ if not path.is_file():
315
+ raise FileNotFoundError(f"Video source not found: {path}")
316
+ capture_source = str(path)
317
+
318
+ cap = cv2.VideoCapture(capture_source)
319
+ ok, first = cap.read()
320
+ if not ok or first is None:
321
+ cap.release()
322
+ raise RuntimeError(f"Could not read video source: {_source_label(source)}")
323
+ h, w = first.shape[:2]
324
+ rate = fps or cap.get(cv2.CAP_PROP_FPS)
325
+ if not np.isfinite(rate) or rate <= 0:
326
+ rate = 30.0
327
+ reported = cap.get(cv2.CAP_PROP_FRAME_COUNT)
328
+ total = int(reported) if np.isfinite(reported) and reported > 0 else 0
329
+ if max_frames is not None:
330
+ total = min(total, max_frames) if total else max_frames
331
+
332
+ def capture_iter() -> Generator[tuple[int, float, np.ndarray], None, None]:
333
+ try:
334
+ idx, frame = 0, first
335
+ while True:
336
+ if frame.shape[:2] != (h, w):
337
+ raise ValueError("Video dimensions changed during tracking.")
338
+ yield idx, idx / rate, frame
339
+ idx += 1
340
+ if max_frames is not None and idx >= max_frames:
341
+ break
342
+ ok, frame = cap.read()
343
+ if not ok:
344
+ break
345
+ finally:
346
+ cap.release()
347
+
348
+ return capture_iter(), rate, w, h, total
349
+
350
+
351
+ def _crop(frame_bgr: np.ndarray, bbox: tuple[float, float, float, float]) -> np.ndarray | None:
352
+ h, w = frame_bgr.shape[:2]
353
+ x1, y1 = max(0, int(round(bbox[0]))), max(0, int(round(bbox[1])))
354
+ x2, y2 = min(w, int(round(bbox[2]))), min(h, int(round(bbox[3])))
355
+ if x2 - x1 < 4 or y2 - y1 < 4:
356
+ return None
357
+ return frame_bgr[y1:y2, x1:x2]
358
+
359
+
360
+ def _match_track_embeddings(
361
+ tracks: list[Track],
362
+ detections: list[Detection],
363
+ frame_bgr: np.ndarray | None,
364
+ reid_embedder: ReidEmbedder | None,
365
+ *,
366
+ seen_counts: dict[int, int] | None = None,
367
+ sample_every: int = 3,
368
+ ) -> list[np.ndarray | None]:
369
+ """Attach a float16 Re-ID embedding to each track, reusing detection embeddings when present.
370
+
371
+ When a tracker did not attach embeddings to detections (e.g. ByteTrack/OC-SORT with
372
+ ``--reid osnet``), crops are encoded on track birth and every ``sample_every`` observations of
373
+ each raw track to match ``TrackCardIndex.reid_sample_every`` and bound CPU overhead.
374
+ """
375
+ if not tracks:
376
+ return []
377
+
378
+ out: list[np.ndarray | None] = [None] * len(tracks)
379
+ det_with_emb = [d for d in detections if d.embedding is not None]
380
+ if det_with_emb:
381
+ t_boxes = np.array([t.bbox for t in tracks], dtype=np.float64).reshape(-1, 4)
382
+ d_boxes = np.array([d.bbox for d in det_with_emb], dtype=np.float64).reshape(-1, 4)
383
+ iou = compute_iou_matrix(t_boxes, d_boxes)
384
+ for i, tr in enumerate(tracks):
385
+ j = int(np.argmax(iou[i]))
386
+ if float(iou[i, j]) >= 0.5 and det_with_emb[j].class_id == tr.class_id:
387
+ emb = det_with_emb[j].embedding
388
+ if emb is not None:
389
+ out[i] = np.asarray(emb, dtype=np.float16)
390
+
391
+ if reid_embedder is None or frame_bgr is None:
392
+ return out
393
+
394
+ missing: list[int] = []
395
+ for i, tr in enumerate(tracks):
396
+ obs_n = seen_counts.get(tr.track_id, 0) if seen_counts is not None else 0
397
+ if seen_counts is not None:
398
+ seen_counts[tr.track_id] = obs_n + 1
399
+ if (
400
+ out[i] is None
401
+ and tr.class_name.lower() == "person"
402
+ and (sample_every <= 1 or obs_n % sample_every == 0)
403
+ ):
404
+ missing.append(i)
405
+ if missing:
406
+ crops = [_crop(frame_bgr, tracks[i].bbox) for i in missing]
407
+ for i, emb in zip(missing, reid_embedder.encode_images(crops), strict=True):
408
+ if emb is not None:
409
+ out[i] = np.asarray(emb, dtype=np.float16)
410
+ return out
411
+
412
+
413
+ def _pack_postprocess_embeddings(
414
+ embs: Sequence[np.ndarray | None],
415
+ ) -> tuple[np.ndarray | None, np.ndarray | None]:
416
+ """Pack per-observation optional embeddings into dense ``(N, D)`` float32 + bool mask."""
417
+ dim = next((int(e.shape[0]) for e in embs if e is not None), 0)
418
+ if dim <= 0:
419
+ return None, None
420
+ dense = np.zeros((len(embs), dim), dtype=np.float32)
421
+ valid = np.zeros((len(embs),), dtype=bool)
422
+ for i, emb in enumerate(embs):
423
+ if emb is not None:
424
+ dense[i] = np.asarray(emb, dtype=np.float32)
425
+ valid[i] = True
426
+ return dense, valid
427
+
428
+
429
+ def _remap_tracker_events(
430
+ raw_events: list[dict[str, Any]],
431
+ records: list[dict[str, Any]],
432
+ source_row_indices: np.ndarray,
433
+ raw_tids: list[int],
434
+ raw_frames: list[int],
435
+ ) -> list[dict[str, Any]]:
436
+ """Remap Pass-1 tracker lifecycle events from raw IDs to finalized post-processed IDs."""
437
+ exact: dict[tuple[int, int], int] = {}
438
+ by_raw: dict[int, list[tuple[int, int]]] = defaultdict(list)
439
+ for rec, si in zip(records, source_row_indices.tolist(), strict=True):
440
+ if si < 0:
441
+ continue
442
+ fid = int(rec["track_id"])
443
+ rid = raw_tids[si]
444
+ f_i = raw_frames[si]
445
+ exact[(f_i, rid)] = fid
446
+ by_raw[rid].append((f_i, fid))
447
+
448
+ def _resolve(frame_idx: int, raw_id: int) -> int | None:
449
+ hit = exact.get((frame_idx, raw_id))
450
+ if hit is not None:
451
+ return hit
452
+ hist = by_raw.get(raw_id)
453
+ if not hist:
454
+ return None
455
+ return min(hist, key=lambda pair: abs(pair[0] - frame_idx))[1]
456
+
457
+ remapped: list[dict[str, Any]] = []
458
+ for ev in raw_events:
459
+ f_i = int(ev.get("frame_idx", 0))
460
+ et = ev.get("type")
461
+ if et == "possible_id_switch":
462
+ new_id = _resolve(f_i, int(ev["new_track_id"]))
463
+ prev_id = _resolve(f_i, int(ev["previous_track_id"]))
464
+ if new_id is None or prev_id is None or new_id == prev_id:
465
+ continue
466
+ remapped.append({**ev, "new_track_id": new_id, "previous_track_id": prev_id})
467
+ elif "track_id" in ev:
468
+ fid = _resolve(f_i, int(ev["track_id"]))
469
+ if fid is None:
470
+ continue
471
+ remapped.append({**ev, "track_id": fid})
472
+ else:
473
+ remapped.append(ev)
474
+ return remapped
475
+
476
+
477
+ class TrackflowPipeline:
478
+ """Unified real-time tracking pipeline combining detection, MOT, Re-ID/NL query, privacy & floorplan."""
479
+
480
+ def __init__(
481
+ self,
482
+ *,
483
+ model: str | Path | None = None,
484
+ precision: Precision = "fp32",
485
+ tracker: str = "bytetrack",
486
+ use_cmc: bool = True,
487
+ device: str = "auto",
488
+ threshold: float = 0.45,
489
+ classes: Sequence[str] | None = ("person",),
490
+ reid: ReidBackend = "none",
491
+ vlm: VlmBackend | None = None,
492
+ reid_merge: bool = False,
493
+ postprocess: bool = False,
494
+ query: str | None = None,
495
+ query_threshold: float | None = None,
496
+ anonymize: AnonymizeMode = "none",
497
+ homography: FloorplanHomography | str | Path | None = None,
498
+ lines: Sequence[CountingLine] = (),
499
+ detector: Detector | None = None,
500
+ tracker_factory: Callable[[], Tracker] | None = None,
501
+ reid_embedder: ReidEmbedder | None = None,
502
+ vlm_embedder: VlmEmbedder | None = None,
503
+ mask_fallback: str | None = None,
504
+ mask_propagator: MaskPropagator | None = None,
505
+ mask_fallback_config: MaskFallbackConfig | None = None,
506
+ cache_dir: str | Path | None = None,
507
+ ) -> None:
508
+ self.model_name = (
509
+ str(model)
510
+ if model is not None
511
+ else (
512
+ getattr(detector, "model_name", type(detector).__name__)
513
+ if detector is not None
514
+ else "rtdetr-v2-r18"
515
+ )
516
+ )
517
+ self.tracker_name = tracker
518
+ self.use_cmc = bool(use_cmc)
519
+ self.tracker_factory = tracker_factory
520
+ if tracker_factory is None:
521
+ create_tracker(tracker, use_cmc=self.use_cmc) # reject an unknown name before any model loads
522
+ self.threshold = float(threshold)
523
+ if not 0 <= self.threshold <= 1:
524
+ raise ValueError("threshold must be between 0 and 1.")
525
+ self._allowed = _allowed_classes(classes)
526
+ self.classes = sorted(self._allowed) if self._allowed is not None else ["all"]
527
+ self.query = query.strip() if query else None
528
+ self.anonymize_mode: AnonymizeMode = anonymize
529
+
530
+ # Validate mask fallback options early before loading detectors/embedders.
531
+ mf_name = mask_fallback.strip() if isinstance(mask_fallback, str) else None
532
+ if mf_name and mf_name.lower() == "none":
533
+ mf_name = None
534
+ if mask_fallback_config is not None and mf_name is None and mask_propagator is None:
535
+ raise ValueError(
536
+ "--mask-budget / mask_fallback_config requires --mask-fallback or mask_propagator."
537
+ )
538
+ if mask_propagator is not None:
539
+ if self.anonymize_mode != "none" and getattr(
540
+ mask_propagator, "writes_frames_to_disk", False
541
+ ):
542
+ raise ValueError(
543
+ "Cannot use a mask propagator that writes raw frames to disk "
544
+ "(such as Sam3MaskPropagator) when anonymize != 'none'. "
545
+ "Use an in-memory propagator such as Sam2MaskPropagator."
546
+ )
547
+ self.mask_propagator: MaskPropagator | None = mask_propagator
548
+ self.mask_fallback_backend: str | None = getattr(
549
+ mask_propagator, "model_name", type(mask_propagator).__name__
550
+ )
551
+ elif mf_name is not None:
552
+ from trackflow.sam2_adapter import create_mask_propagator
553
+
554
+ self.mask_propagator = create_mask_propagator(
555
+ mf_name, device=device, cache_dir=cache_dir
556
+ )
557
+ self.mask_fallback_backend = mf_name
558
+ else:
559
+ self.mask_propagator = None
560
+ self.mask_fallback_backend = None
561
+ self.mask_fallback_config = mask_fallback_config
562
+
563
+ if reid in ("clip", "siglip"):
564
+ # Pre-0.1 runs used `--reid clip` for queries. CLIP can't tell people apart, so it is
565
+ # now only a vision-language model for --query / search, never an identity model.
566
+ warnings.warn(
567
+ f"--reid {reid} is now `--vlm {reid}` (text queries & search only). Use "
568
+ "`--reid osnet` for person re-identification.",
569
+ stacklevel=2,
570
+ )
571
+ vlm = vlm if vlm not in (None, "none") else reid # type: ignore[assignment]
572
+ reid = "none"
573
+ if vlm is None:
574
+ vlm = "clip" if self.query else "none"
575
+ if reid_merge and reid == "none" and reid_embedder is None:
576
+ raise ValueError("--reid-merge needs a person Re-ID model: add `--reid osnet`.")
577
+
578
+ self.reid_backend: ReidBackend = reid_embedder.backend if reid_embedder else reid
579
+ self.vlm_backend: VlmBackend = vlm_embedder.backend if vlm_embedder else vlm
580
+ self.query_threshold = float(
581
+ QUERY_THRESHOLDS.get(self.vlm_backend, 0.22)
582
+ if query_threshold is None
583
+ else query_threshold
584
+ )
585
+ self.reid_merge = bool(reid_merge)
586
+ self.postprocess = bool(postprocess)
587
+ if self.query and self.vlm_backend == "none":
588
+ raise ValueError(
589
+ "A text query needs a vision-language model. Choose clip, siglip, siglip2 or embeddinggemma."
590
+ )
591
+
592
+ detect_classes = self._allowed
593
+ if detect_classes is not None and anonymize in ("blur", "pixelate", "face-blur"):
594
+ detect_classes = detect_classes | {"person"}
595
+ self.detector = (
596
+ detector
597
+ if detector is not None
598
+ else create_detector(
599
+ model=self.model_name,
600
+ precision=precision,
601
+ device=device,
602
+ threshold=min(0.15, threshold, max(0.10, threshold * 0.35)),
603
+ classes=sorted(detect_classes) if detect_classes else None,
604
+ cache_dir=cache_dir,
605
+ )
606
+ )
607
+ self.reid_embedder = reid_embedder or (
608
+ ReidEmbedder(
609
+ backend=self.reid_backend,
610
+ device=device,
611
+ cache_dir=cache_dir,
612
+ )
613
+ if self.reid_backend != "none"
614
+ else None
615
+ )
616
+ self.vlm_embedder = vlm_embedder or (
617
+ create_vlm_embedder(self.vlm_backend, device=device, cache_dir=cache_dir)
618
+ if self.vlm_backend != "none"
619
+ else None
620
+ )
621
+ self.anonymizer = PrivacyAnonymizer(mode=anonymize)
622
+ if isinstance(homography, (str, Path)):
623
+ self.homography: FloorplanHomography | None = FloorplanHomography.from_json(homography)
624
+ else:
625
+ self.homography = homography
626
+ self.lines = list(lines)
627
+ LineCounter(self.lines) # reject duplicate names before any frame is read
628
+
629
+ def _new_mask_resolver(self) -> MaskFallbackResolver | None:
630
+ if self.mask_propagator is None:
631
+ return None
632
+ return MaskFallbackResolver(self.mask_propagator, self.mask_fallback_config)
633
+
634
+ def _new_counter(self) -> LineCounter | None:
635
+ return LineCounter(self.lines) if self.lines else None
636
+
637
+ def _new_tracker(self, frame_dt: float) -> Tracker:
638
+ if self.tracker_factory is not None:
639
+ return self.tracker_factory()
640
+ return create_tracker(
641
+ self.tracker_name,
642
+ track_high_thresh=self.threshold,
643
+ track_low_thresh=min(self.threshold, max(0.10, self.threshold * 0.35)),
644
+ new_track_thresh=max(self.threshold, min(0.95, self.threshold + 0.05)),
645
+ iou_buffer=iou_buffer_for_interval(frame_dt),
646
+ use_cmc=self.use_cmc,
647
+ )
648
+
649
+ def _new_cards(
650
+ self,
651
+ tracker: Tracker,
652
+ stride: int,
653
+ crops_dir: Path | None = None,
654
+ *,
655
+ enable_online_reid_merge: bool | None = None,
656
+ ) -> TrackCardIndex:
657
+ online_merge = self.reid_merge if enable_online_reid_merge is None else enable_online_reid_merge
658
+ buffer = getattr(tracker, "track_buffer", None)
659
+ if online_merge and buffer is None:
660
+ raise ValueError(
661
+ "A custom tracker using reid_merge must expose its track_buffer in processed frames."
662
+ )
663
+ return TrackCardIndex(
664
+ vlm=self.vlm_embedder,
665
+ reid=self.reid_embedder,
666
+ query=self.query,
667
+ query_threshold=self.query_threshold,
668
+ reid_merge=online_merge,
669
+ # A lost raw ID can still be recovered during the track buffer. Merging a
670
+ # different raw ID into it during that window can give two objects the same ID.
671
+ min_exit_gap_frames=max(8, ((buffer or 0) + 1) * stride),
672
+ crops_dir=crops_dir,
673
+ )
674
+
675
+ def _process_frame(
676
+ self,
677
+ frame: np.ndarray,
678
+ idx: int,
679
+ timestamp: float,
680
+ dt: float,
681
+ tracker: Tracker,
682
+ cards: TrackCardIndex | None,
683
+ floorplan: FloorplanHomography | None,
684
+ counter: LineCounter | None = None,
685
+ mask_resolver: MaskFallbackResolver | None = None,
686
+ *,
687
+ record_floorplan: bool = False,
688
+ ) -> tuple[FrameResult, list[Detection], list[int]]:
689
+ start = time.perf_counter()
690
+ raw = self.detector.detect(frame)
691
+ detected = time.perf_counter()
692
+ targets = (
693
+ raw
694
+ if self._allowed is None
695
+ else [d for d in raw if _class_key(d.class_name) in self._allowed]
696
+ )
697
+ min_conf = getattr(tracker, "embedding_min_confidence", None)
698
+ if min_conf is not None and self.reid_embedder is not None:
699
+ people = [
700
+ d for d in targets if d.confidence >= min_conf and d.class_name.lower() == "person"
701
+ ]
702
+ for det, emb in zip(
703
+ people,
704
+ self.reid_embedder.encode_images([_crop(frame, d.bbox) for d in people]),
705
+ strict=True,
706
+ ):
707
+ det.embedding = emb
708
+ tracks = tracker.update(targets, frame_bgr=frame)
709
+ raw_track_ids = [int(tr.track_id) for tr in tracks]
710
+ mask_events = (
711
+ mask_resolver.observe(idx, frame, tracks) if mask_resolver is not None else []
712
+ )
713
+ tracked = time.perf_counter()
714
+ if floorplan is not None:
715
+ for tr in tracks:
716
+ if record_floorplan:
717
+ tr.world_xy, tr.zone = floorplan.observe(tr.track_id, tr.foot_point, dt_s=dt)
718
+ else:
719
+ tr.world_xy = floorplan.project(tr.foot_point)
720
+ tr.zone = floorplan.locate_zone(tr.world_xy)
721
+ events = list(getattr(tracker, "last_events", ()))
722
+ events.extend(mask_events)
723
+ if counter is not None:
724
+ # Raw tracker IDs: a Re-ID merge would join a track to a point from before it left.
725
+ events.extend(counter.update(tracks, timestamp))
726
+ if cards is not None:
727
+ for ev in mask_events:
728
+ for src_id, dst_id in ev.get("relink_pairs", ()):
729
+ cards.reconcile_relink(int(src_id), int(dst_id))
730
+ events.extend(cards.update(idx, timestamp, frame, tracks, frame_dt_s=dt))
731
+ return (
732
+ FrameResult(
733
+ frame_idx=idx,
734
+ timestamp_s=timestamp,
735
+ tracks=tracks,
736
+ num_detections=len(targets),
737
+ inference_ms=(detected - start) * 1000,
738
+ tracking_ms=(tracked - detected) * 1000,
739
+ events=events,
740
+ ),
741
+ raw,
742
+ raw_track_ids,
743
+ )
744
+
745
+ def stream(self, frames: Iterable[np.ndarray], *, fps: float = 30.0) -> Iterator[FrameResult]:
746
+ """Yield observations for consecutive BGR uint8 frames without writing any files.
747
+
748
+ Each call starts a fresh tracker. With re-entry merging or mask fallback enabled,
749
+ committed fixes apply to subsequent frames; observations already yielded keep their
750
+ original ID.
751
+ """
752
+ if not np.isfinite(fps) or fps <= 0:
753
+ raise ValueError("fps must be positive and finite.")
754
+ dt = 1.0 / fps
755
+ tracker = self._new_tracker(dt)
756
+ cards = self._new_cards(tracker, 1) if self.vlm_embedder or self.reid_merge else None
757
+ counter = self._new_counter()
758
+ mask_resolver = self._new_mask_resolver()
759
+ shape = None
760
+ for idx, frame in enumerate(frames):
761
+ if (
762
+ not isinstance(frame, np.ndarray)
763
+ or frame.ndim != 3
764
+ or frame.shape[2] != 3
765
+ or frame.dtype != np.uint8
766
+ or not frame.size
767
+ ):
768
+ raise ValueError(f"Frame {idx} must be a nonempty H×W×3 uint8 BGR array.")
769
+ if shape is not None and frame.shape != shape:
770
+ raise ValueError(
771
+ f"Frame {idx} changed size. Start a new stream when geometry changes."
772
+ )
773
+ shape = frame.shape
774
+ result, _, _ = self._process_frame(
775
+ frame, idx, idx / fps, dt, tracker, cards, self.homography, counter, mask_resolver
776
+ )
777
+ yield result
778
+
779
+ def _finalize_postprocess(
780
+ self,
781
+ pp_records: list[dict[str, Any]],
782
+ pp_embs: list[np.ndarray | None],
783
+ pp_cmc_by_frame: dict[int, np.ndarray],
784
+ pp_frame_indices: list[int],
785
+ raw_events: list[dict[str, Any]],
786
+ *,
787
+ tracker: Tracker,
788
+ card_index: TrackCardIndex,
789
+ floorplan: FloorplanHomography | None,
790
+ counter: LineCounter | None,
791
+ src_fps: float,
792
+ frame_dt_s: float,
793
+ stride: int,
794
+ width: int,
795
+ height: int,
796
+ ) -> tuple[
797
+ list[dict[str, Any]],
798
+ dict[int, list[dict[str, Any]]],
799
+ list[dict[str, Any]],
800
+ dict[int, dict[str, dict[str, int]]],
801
+ int,
802
+ ]:
803
+ """Run offline post-processing and recompute floorplan, line counts, cards, and events."""
804
+ raw_tids = [int(r["track_id"]) for r in pp_records]
805
+ raw_frames = [int(r["frame_idx"]) for r in pp_records]
806
+ emb_dense, emb_valid = _pack_postprocess_embeddings(pp_embs)
807
+
808
+ cmc_warps: np.ndarray | None = None
809
+ cmc_valid: np.ndarray | None = None
810
+ if pp_cmc_by_frame:
811
+ n_cmc = max(pp_frame_indices[-1] + 1, max(pp_cmc_by_frame) + 1)
812
+ cmc_warps = np.broadcast_to(
813
+ np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float32),
814
+ (n_cmc, 2, 3),
815
+ ).copy()
816
+ cmc_valid = np.zeros((n_cmc,), dtype=bool)
817
+ for f_i, w_mat in pp_cmc_by_frame.items():
818
+ cmc_warps[f_i] = w_mat
819
+ cmc_valid[f_i] = True
820
+
821
+ buf = getattr(tracker, "track_buffer", None)
822
+ min_exit_gap = max(8, ((buf or 0) + 1) * stride)
823
+ pp_res = postprocess_records(
824
+ pp_records,
825
+ fps=src_fps,
826
+ frame_width=width,
827
+ frame_height=height,
828
+ embeddings=emb_dense,
829
+ emb_valid=emb_valid,
830
+ cmc_warps=cmc_warps,
831
+ cmc_valid=cmc_valid,
832
+ frame_stride=stride,
833
+ allow_long_reid_merge=self.reid_merge,
834
+ min_exit_gap_frames=min_exit_gap,
835
+ )
836
+ final_records = pp_res.records
837
+
838
+ by_frame: dict[int, list[dict[str, Any]]] = defaultdict(list)
839
+ by_frame_src: dict[int, list[int]] = defaultdict(list)
840
+ for rec, si in zip(final_records, pp_res.source_row_indices.tolist(), strict=True):
841
+ f_i = int(rec["frame_idx"])
842
+ by_frame[f_i].append(rec)
843
+ by_frame_src[f_i].append(int(si))
844
+
845
+ if floorplan is not None:
846
+ for f_i in pp_frame_indices:
847
+ for rec in by_frame.get(f_i, ()):
848
+ foot = (0.5 * (rec["x1"] + rec["x2"]), rec["y2"])
849
+ wxy, zone = floorplan.observe(int(rec["track_id"]), foot, dt_s=frame_dt_s)
850
+ rec["world_x"] = round(float(wxy[0]), 3)
851
+ rec["world_y"] = round(float(wxy[1]), 3)
852
+ rec["zone"] = zone
853
+
854
+ final_events = _remap_tracker_events(
855
+ raw_events, final_records, pp_res.source_row_indices, raw_tids, raw_frames
856
+ )
857
+ for ev in pp_res.reid_merge_events:
858
+ final_events.append(
859
+ {**ev, "timestamp_s": round(int(ev["frame_idx"]) / max(src_fps, 1e-6), 3)}
860
+ )
861
+
862
+ line_counts_by_frame: dict[int, dict[str, dict[str, int]]] = {}
863
+ if counter is not None:
864
+ last_seen_frame: dict[int, int] = {}
865
+ last_raw_id: dict[int, int] = {}
866
+ for f_i in pp_frame_indices:
867
+ f_recs = by_frame.get(f_i, ())
868
+ f_srcs = by_frame_src.get(f_i, ())
869
+ if f_recs:
870
+ f_tracks: list[Track] = []
871
+ ts = float(f_recs[0]["timestamp_s"])
872
+ for rec, si in zip(f_recs, f_srcs, strict=True):
873
+ tid = int(rec["track_id"])
874
+ prev_frame = last_seen_frame.get(tid)
875
+ if si >= 0:
876
+ cur_raw = raw_tids[si]
877
+ prev_raw = last_raw_id.get(tid)
878
+ # Reset line state only across an un-interpolated stitched exit gap
879
+ # between different raw IDs (never mid-trajectory after interpolation).
880
+ if (
881
+ prev_raw is not None
882
+ and prev_frame is not None
883
+ and cur_raw != prev_raw
884
+ and f_i - prev_frame >= min_exit_gap
885
+ ):
886
+ counter.forget_track(tid)
887
+ last_raw_id[tid] = cur_raw
888
+ last_seen_frame[tid] = f_i
889
+ f_tracks.append(
890
+ Track(
891
+ track_id=tid,
892
+ bbox=(rec["x1"], rec["y1"], rec["x2"], rec["y2"]),
893
+ confidence=rec["confidence"],
894
+ class_id=rec["class_id"],
895
+ class_name=rec["class_name"],
896
+ )
897
+ )
898
+ for ev in counter.update(f_tracks, ts):
899
+ final_events.append({"frame_idx": f_i, "timestamp_s": round(ts, 3), **ev})
900
+ line_counts_by_frame[f_i] = {name: dict(c) for name, c in counter.counts.items()}
901
+
902
+ card_index.rebuild_from_postprocess(
903
+ final_records,
904
+ pp_res.source_row_indices,
905
+ raw_tids,
906
+ frame_dt_s=frame_dt_s,
907
+ reid_merges=pp_res.reid_merges,
908
+ )
909
+ final_events.append(
910
+ {
911
+ "frame_idx": pp_frame_indices[-1],
912
+ "timestamp_s": round(pp_frame_indices[-1] / src_fps, 3),
913
+ "type": "offline_postprocess",
914
+ "unique_tracks_before": pp_res.unique_tracks_before,
915
+ "unique_tracks_after": pp_res.unique_tracks_after,
916
+ "interpolated_rows": pp_res.interpolated_rows,
917
+ "merges": pp_res.merges,
918
+ "reid_merges": pp_res.reid_merges,
919
+ "splits": pp_res.splits,
920
+ "elapsed_ms": round(pp_res.elapsed_ms, 2),
921
+ }
922
+ )
923
+ final_events.sort(key=lambda e: int(e.get("frame_idx", 0)))
924
+ return final_records, by_frame, final_events, line_counts_by_frame, min_exit_gap
925
+
926
+ def _replay_postprocess_video(
927
+ self,
928
+ source: str | Path | int,
929
+ video_path: Path,
930
+ by_frame: dict[int, list[dict[str, Any]]],
931
+ pp_privacy_masks: dict[int, tuple[list[Detection], list[Track]]],
932
+ line_counts_by_frame: dict[int, dict[str, dict[str, int]]],
933
+ *,
934
+ seen_frames: int,
935
+ src_fps: float,
936
+ skip: int,
937
+ width: int,
938
+ height: int,
939
+ gap_reset_frames: int,
940
+ ) -> None:
941
+ """Render ``annotated.mp4`` from finalized post-processed tracks while preserving masks."""
942
+ replay_iter, _, _, _, _ = _iter_frames(source, max_frames=seen_frames, fps=src_fps)
943
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
944
+ out_fps = src_fps / max(1, skip + 1)
945
+ v_writer = cv2.VideoWriter(str(video_path), fourcc, out_fps, (width, height))
946
+ if not v_writer.isOpened():
947
+ replay_iter.close()
948
+ v_writer.release()
949
+ video_path.unlink(missing_ok=True)
950
+ raise RuntimeError(f"Could not open MP4 video writer at {video_path}")
951
+ pp_trails: dict[int, list[tuple[int, int]]] = defaultdict(list)
952
+ last_trail_frame: dict[int, int] = {}
953
+ written_frames = 0
954
+ try:
955
+ with _stop_on_interrupt() as replay_stop:
956
+ for f_i, _ts, f_bgr in replay_iter:
957
+ if replay_stop.is_set():
958
+ break
959
+ if skip > 0 and (f_i % (skip + 1) != 0):
960
+ continue
961
+ f_recs = by_frame.get(f_i, ())
962
+ f_tracks = [
963
+ Track(
964
+ track_id=int(r["track_id"]),
965
+ bbox=(r["x1"], r["y1"], r["x2"], r["y2"]),
966
+ confidence=float(r["confidence"]),
967
+ class_id=int(r["class_id"]),
968
+ class_name=str(r["class_name"]),
969
+ query_score=r["query_score"],
970
+ query_match=bool(r["query_match"]),
971
+ zone=r["zone"],
972
+ )
973
+ for r in f_recs
974
+ ]
975
+ for tr in f_tracks:
976
+ prev_f = last_trail_frame.get(tr.track_id)
977
+ if prev_f is not None and f_i - prev_f >= gap_reset_frames:
978
+ pp_trails[tr.track_id].clear()
979
+ last_trail_frame[tr.track_id] = f_i
980
+ fx, fy = tr.foot_point
981
+ trl = pp_trails[tr.track_id]
982
+ trl.append((int(round(fx)), int(round(fy))))
983
+ del trl[:-48]
984
+ saved_dets, saved_coasting = pp_privacy_masks.get(f_i, ([], []))
985
+ # In skeleton mode, draw only finalized tracks (avoid double-drawing stale coasting).
986
+ mask_coasting = () if self.anonymize_mode == "skeleton" else saved_coasting
987
+ anon_frame = self.anonymizer.apply(
988
+ f_bgr,
989
+ f_tracks,
990
+ detections=saved_dets,
991
+ coasting=mask_coasting,
992
+ )
993
+ rendered = draw_tracks(
994
+ anon_frame,
995
+ f_tracks,
996
+ trails=pp_trails,
997
+ query=self.query,
998
+ anonymize_mode=self.anonymize_mode,
999
+ lines=self.lines,
1000
+ line_counts=line_counts_by_frame.get(f_i) if self.lines else None,
1001
+ )
1002
+ v_writer.write(rendered)
1003
+ written_frames += 1
1004
+ finally:
1005
+ replay_iter.close()
1006
+ v_writer.release()
1007
+ if written_frames == 0:
1008
+ video_path.unlink(missing_ok=True)
1009
+
1010
+ def run(
1011
+ self,
1012
+ source: str | Path | int,
1013
+ *,
1014
+ output_dir: str | Path | None = None,
1015
+ skip: int = 0,
1016
+ fps: float | None = None,
1017
+ max_frames: int | None = None,
1018
+ save_video: bool = True,
1019
+ exports: Sequence[str] = ("parquet", "jsonl", "html"),
1020
+ display: bool = False,
1021
+ progress_callback: Callable[[int, int, float], None] | None = None,
1022
+ ) -> RunSummary:
1023
+ """Execute tracking on ``source`` and write requested artifacts into ``output_dir``.
1024
+
1025
+ Ctrl-C stops reading frames and still writes every artifact for the frames processed so
1026
+ far, which is how a camera or stream run ends. A second Ctrl-C aborts.
1027
+ """
1028
+ if skip < 0 or (max_frames is not None and max_frames < 1):
1029
+ raise ValueError("skip must be nonnegative and max_frames must be positive.")
1030
+ if self.postprocess and _is_live_source(source):
1031
+ raise ValueError("--postprocess requires a recorded video file or image directory.")
1032
+ if isinstance(exports, str):
1033
+ exports = exports.split(",")
1034
+ export_set = {e.lower().strip() for e in exports}
1035
+ unknown = export_set - {"parquet", "jsonl", "csv", "mot", "html"}
1036
+ if unknown:
1037
+ raise ValueError(f"Unknown export format(s): {', '.join(sorted(unknown))}")
1038
+ stride = skip + 1
1039
+ with contextlib.ExitStack() as stack:
1040
+ out_dir = stack.enter_context(_run_directory(output_dir))
1041
+ frame_iter, src_fps, width, height, total_frames = _iter_frames(
1042
+ source, max_frames=max_frames, fps=fps
1043
+ )
1044
+
1045
+ capture_stack = stack.enter_context(contextlib.ExitStack())
1046
+ capture_stack.callback(frame_iter.close)
1047
+ frame_dt_s = stride / src_fps
1048
+ tracker = self._new_tracker(frame_dt_s)
1049
+ # In offline --postprocess mode, defer Re-ID merging to the global post-processor
1050
+ # instead of mutating raw IDs greedily mid-pass.
1051
+ card_index = self._new_cards(
1052
+ tracker,
1053
+ stride,
1054
+ out_dir / "crops" if self.anonymize_mode == "none" else None,
1055
+ enable_online_reid_merge=False if self.postprocess else None,
1056
+ )
1057
+ floorplan = self.homography.fresh() if self.homography else None
1058
+ counter = self._new_counter()
1059
+ mask_resolver = self._new_mask_resolver()
1060
+
1061
+ defer_video = self.postprocess and save_video
1062
+ video_writer: cv2.VideoWriter | None = None
1063
+ video_path = out_dir / "annotated.mp4"
1064
+ if save_video and not defer_video:
1065
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
1066
+ out_fps = src_fps / max(1, skip + 1)
1067
+ video_writer = cv2.VideoWriter(str(video_path), fourcc, out_fps, (width, height))
1068
+ if not video_writer.isOpened():
1069
+ video_writer.release()
1070
+ raise RuntimeError(f"Could not open MP4 video writer at {video_path}")
1071
+ capture_stack.callback(video_writer.release)
1072
+
1073
+ counts: list[int] = []
1074
+ extensions = {"parquet": "parquet", "jsonl": "jsonl", "csv": "csv", "mot": "txt"}
1075
+ paths = {
1076
+ fmt: out_dir / f"tracks.{ext}"
1077
+ for fmt, ext in extensions.items()
1078
+ if fmt in export_set
1079
+ }
1080
+ writer_stack = stack.enter_context(contextlib.ExitStack())
1081
+ sink = ObservationWriter(paths, writer_stack)
1082
+ # Re-entry and mask-fallback IDs can change retrospectively. Only non-postprocess
1083
+ # modes need a disk spool; offline postprocess buffers full-precision records in memory.
1084
+ spool = (
1085
+ stack.enter_context(
1086
+ tempfile.TemporaryFile(mode="w+", encoding="utf-8", dir=out_dir)
1087
+ )
1088
+ if (self.reid_merge or mask_resolver is not None) and not self.postprocess and paths
1089
+ else None
1090
+ )
1091
+ pp_records: list[dict[str, Any]] = []
1092
+ pp_embs: list[np.ndarray | None] = []
1093
+ pp_seen_counts: dict[int, int] = {}
1094
+ pp_cmc_by_frame: dict[int, np.ndarray] = {}
1095
+ pp_frame_indices: list[int] = []
1096
+ pp_privacy_masks: dict[int, tuple[list[Detection], list[Track]]] = {}
1097
+ trails: dict[int, list[tuple[int, int]]] = defaultdict(list)
1098
+ all_events: list[dict[str, Any]] = []
1099
+
1100
+ total_dets = 0
1101
+ recovered_count = 0
1102
+ total_inf_ms = total_trk_ms = 0.0
1103
+ observations = 0
1104
+
1105
+ t_start = time.perf_counter()
1106
+ processed = 0
1107
+ seen_frames = 0
1108
+
1109
+ def _render_frame(
1110
+ frame_bgr: np.ndarray,
1111
+ tracks: list[Any],
1112
+ dets: list[Detection],
1113
+ coasting: list[Any],
1114
+ trails_snap: dict[int, list[tuple[int, int]]],
1115
+ live_fps: float,
1116
+ line_counts_snap: dict[str, dict[str, int]] | None,
1117
+ ) -> np.ndarray:
1118
+ anon_frame = self.anonymizer.apply(
1119
+ frame_bgr, tracks, detections=dets, coasting=coasting
1120
+ )
1121
+ return draw_tracks(
1122
+ anon_frame,
1123
+ tracks,
1124
+ coasting=coasting,
1125
+ trails=trails_snap,
1126
+ fps=live_fps,
1127
+ query=self.query,
1128
+ anonymize_mode=self.anonymize_mode,
1129
+ lines=self.lines,
1130
+ line_counts=line_counts_snap,
1131
+ )
1132
+
1133
+ frames: Iterator[tuple[int, float, np.ndarray]] = (
1134
+ capture_stack.enter_context(_prefetch_frames(frame_iter))
1135
+ if not _is_live_source(source) and total_frames != 1
1136
+ else frame_iter
1137
+ )
1138
+ async_writer = (
1139
+ _AsyncVideoWriter(video_writer, _render_frame)
1140
+ if video_writer is not None and not display
1141
+ else None
1142
+ )
1143
+
1144
+ interrupted_pass1 = False
1145
+ aborted = False
1146
+ with _stop_on_interrupt() as stop:
1147
+ try:
1148
+ for frame_idx, timestamp_s, frame_bgr in frames:
1149
+ if stop.is_set():
1150
+ break
1151
+ seen_frames += 1
1152
+ if skip > 0 and (frame_idx % (skip + 1) != 0):
1153
+ continue
1154
+
1155
+ fr, dets, raw_track_ids = self._process_frame(
1156
+ frame_bgr,
1157
+ frame_idx,
1158
+ timestamp_s,
1159
+ frame_dt_s,
1160
+ tracker,
1161
+ card_index,
1162
+ floorplan if not self.postprocess else None,
1163
+ counter if not self.postprocess else None,
1164
+ mask_resolver,
1165
+ record_floorplan=not self.postprocess,
1166
+ )
1167
+ tracks = fr.tracks
1168
+ observations += len(tracks)
1169
+ total_dets += fr.num_detections
1170
+ total_inf_ms += fr.inference_ms
1171
+ total_trk_ms += fr.tracking_ms
1172
+ for ev in fr.events:
1173
+ all_events.append(
1174
+ {"frame_idx": frame_idx, "timestamp_s": round(timestamp_s, 3), **ev}
1175
+ )
1176
+
1177
+ if self.postprocess:
1178
+ pp_frame_indices.append(frame_idx)
1179
+ warp = getattr(tracker, "last_cmc_warp", None)
1180
+ if warp is not None:
1181
+ pp_cmc_by_frame[frame_idx] = np.asarray(warp, dtype=np.float32)
1182
+ obs_embs = _match_track_embeddings(
1183
+ tracks,
1184
+ dets,
1185
+ frame_bgr,
1186
+ self.reid_embedder,
1187
+ seen_counts=pp_seen_counts,
1188
+ sample_every=card_index.reid_sample_every,
1189
+ )
1190
+ for tr, raw_tid, emb in zip(tracks, raw_track_ids, obs_embs, strict=True):
1191
+ if tr.recovered:
1192
+ recovered_count += 1
1193
+ rec = tr.to_record(frame_idx, timestamp_s)
1194
+ # Keep full-precision coordinates for offline post-processing.
1195
+ rec["x1"], rec["y1"], rec["x2"], rec["y2"] = tr.bbox
1196
+ if mask_resolver is not None:
1197
+ rec["_raw_track_id"] = raw_tid
1198
+ pp_records.append(rec)
1199
+ pp_embs.append(emb)
1200
+ if display:
1201
+ fx, fy = tr.foot_point
1202
+ trail = trails[tr.track_id]
1203
+ trail.append((int(round(fx)), int(round(fy))))
1204
+ del trail[:-48]
1205
+ else:
1206
+ for tr, raw_tid in zip(tracks, raw_track_ids, strict=True):
1207
+ if tr.recovered:
1208
+ recovered_count += 1
1209
+ if paths:
1210
+ record = tr.to_record(frame_idx, timestamp_s)
1211
+ if spool is None:
1212
+ sink.append(record)
1213
+ else:
1214
+ if mask_resolver is not None:
1215
+ record["_raw_track_id"] = raw_tid
1216
+ spool.write(json.dumps(record) + "\n")
1217
+ if save_video or display:
1218
+ fx, fy = tr.foot_point
1219
+ trail = trails[tr.track_id]
1220
+ trail.append((int(round(fx)), int(round(fy))))
1221
+ del trail[:-48]
1222
+ if "html" in export_set:
1223
+ counts.append(len(tracks))
1224
+ processed += 1
1225
+
1226
+ elapsed_now = max(time.perf_counter() - t_start, 1e-6)
1227
+ live_fps = processed / elapsed_now
1228
+
1229
+ if defer_video and self.anonymize_mode != "none":
1230
+ coasting = (
1231
+ tracker.coasting_tracks(3)
1232
+ if hasattr(tracker, "coasting_tracks")
1233
+ else []
1234
+ )
1235
+ # Preserve all raw detections, Pass-1 track boxes & coasting boxes so
1236
+ # Pass-2 privacy masking covers every box even after smoothing shifts.
1237
+ raw_track_masks = [
1238
+ Track(tr.track_id, tr.bbox, tr.confidence, tr.class_id, tr.class_name)
1239
+ for tr in tracks
1240
+ ]
1241
+ pp_privacy_masks[frame_idx] = (
1242
+ [
1243
+ Detection(
1244
+ bbox=d.bbox,
1245
+ confidence=d.confidence,
1246
+ class_id=d.class_id,
1247
+ class_name=d.class_name,
1248
+ )
1249
+ for d in dets
1250
+ ],
1251
+ [*coasting, *raw_track_masks],
1252
+ )
1253
+
1254
+ if (save_video and not defer_video) or display:
1255
+ # Anonymize every box that may hold a person, not just confirmed tracks.
1256
+ coasting = (
1257
+ tracker.coasting_tracks(3)
1258
+ if hasattr(tracker, "coasting_tracks")
1259
+ else []
1260
+ )
1261
+ for c in coasting:
1262
+ cid = (
1263
+ mask_resolver.resolve_id(frame_idx, c.track_id)
1264
+ if mask_resolver is not None
1265
+ else c.track_id
1266
+ )
1267
+ c.track_id = card_index.canonical_id(cid)
1268
+ if async_writer is not None:
1269
+ trails_snap = {
1270
+ tr.track_id: trails[tr.track_id][-32:] for tr in tracks
1271
+ }
1272
+ line_counts_snap = (
1273
+ {k: dict(v) for k, v in counter.counts.items()}
1274
+ if counter
1275
+ else None
1276
+ )
1277
+ async_writer.submit(
1278
+ frame_bgr,
1279
+ tracks,
1280
+ dets,
1281
+ coasting,
1282
+ trails_snap,
1283
+ live_fps,
1284
+ line_counts_snap,
1285
+ )
1286
+ else:
1287
+ rendered = _render_frame(
1288
+ frame_bgr,
1289
+ tracks,
1290
+ dets,
1291
+ coasting,
1292
+ trails,
1293
+ live_fps,
1294
+ counter.counts if counter else None,
1295
+ )
1296
+ if video_writer is not None:
1297
+ video_writer.write(rendered)
1298
+ if display:
1299
+ try:
1300
+ cv2.imshow("Trackflow", rendered)
1301
+ if cv2.waitKey(1) & 0xFF == ord("q"):
1302
+ break
1303
+ except cv2.error:
1304
+ display = False
1305
+
1306
+ if progress_callback is not None:
1307
+ progress_callback(processed, (total_frames + skip) // stride, live_fps)
1308
+ except BaseException:
1309
+ aborted = True
1310
+ raise
1311
+ finally:
1312
+ interrupted_pass1 = stop.is_set()
1313
+ try:
1314
+ if async_writer is not None:
1315
+ async_writer.close(abort=aborted)
1316
+ finally:
1317
+ capture_stack.close()
1318
+ if display:
1319
+ with contextlib.suppress(cv2.error):
1320
+ cv2.destroyAllWindows()
1321
+
1322
+ # Merges are decided a few frames into a returning person's new track; relabel the
1323
+ # observations recorded before that so exports use one ID per person.
1324
+ if processed == 0:
1325
+ if interrupted_pass1:
1326
+ raise KeyboardInterrupt
1327
+ raise RuntimeError(f"No readable frames in {source}")
1328
+
1329
+ if self.postprocess:
1330
+ if mask_resolver is not None:
1331
+ for rec in pp_records:
1332
+ raw_tid = rec.pop("_raw_track_id", rec["track_id"])
1333
+ rec["track_id"] = mask_resolver.resolve_id(rec["frame_idx"], raw_tid)
1334
+ (
1335
+ final_records,
1336
+ by_frame,
1337
+ all_events,
1338
+ line_counts_by_frame,
1339
+ gap_reset_frames,
1340
+ ) = self._finalize_postprocess(
1341
+ pp_records,
1342
+ pp_embs,
1343
+ pp_cmc_by_frame,
1344
+ pp_frame_indices,
1345
+ all_events,
1346
+ tracker=tracker,
1347
+ card_index=card_index,
1348
+ floorplan=floorplan,
1349
+ counter=counter,
1350
+ src_fps=src_fps,
1351
+ frame_dt_s=frame_dt_s,
1352
+ stride=stride,
1353
+ width=width,
1354
+ height=height,
1355
+ )
1356
+ observations = len(final_records)
1357
+ if paths:
1358
+ for rec in final_records:
1359
+ sink.append(rec)
1360
+ if "html" in export_set:
1361
+ counts = [len(by_frame.get(f_i, ())) for f_i in pp_frame_indices]
1362
+ if defer_video:
1363
+ self._replay_postprocess_video(
1364
+ source,
1365
+ video_path,
1366
+ by_frame,
1367
+ pp_privacy_masks,
1368
+ line_counts_by_frame,
1369
+ seen_frames=seen_frames,
1370
+ src_fps=src_fps,
1371
+ skip=skip,
1372
+ width=width,
1373
+ height=height,
1374
+ gap_reset_frames=gap_reset_frames,
1375
+ )
1376
+ elif spool is not None:
1377
+ spool.seek(0)
1378
+ for line in spool:
1379
+ rec = json.loads(line)
1380
+ raw_tid = rec.pop("_raw_track_id", rec["track_id"])
1381
+ tid = (
1382
+ mask_resolver.resolve_id(rec["frame_idx"], raw_tid)
1383
+ if mask_resolver is not None
1384
+ else rec["track_id"]
1385
+ )
1386
+ rec["track_id"] = card_index.canonical_id(tid)
1387
+ sink.append(rec)
1388
+ writer_stack.close()
1389
+
1390
+ elapsed_s = max(time.perf_counter() - t_start, 1e-6)
1391
+ avg_fps = processed / elapsed_s
1392
+ avg_inf = total_inf_ms / processed
1393
+ avg_trk = total_trk_ms / processed
1394
+
1395
+ device_label = getattr(self.detector, "active_provider", "custom")
1396
+ output_files = {fmt: str(path) for fmt, path in paths.items()}
1397
+ if save_video and video_path.is_file():
1398
+ output_files["video"] = str(video_path)
1399
+
1400
+ # Persist Track Cards & diagnostic events (always written for `trackflow inspect` / `search`)
1401
+ cards_path = out_dir / "track_cards.json"
1402
+ card_index.save_json(
1403
+ cards_path, reid_backend=self.reid_backend, vlm_backend=self.vlm_backend
1404
+ )
1405
+ output_files["track_cards"] = str(cards_path)
1406
+
1407
+ events_path = out_dir / "events.json"
1408
+ events_path.write_text(json.dumps(all_events, indent=2), encoding="utf-8")
1409
+ output_files["events"] = str(events_path)
1410
+
1411
+ if floorplan is not None:
1412
+ fp_png = floorplan.render_floorplan(out_dir / "floorplan.png")
1413
+ fp_json = out_dir / "homography.json"
1414
+ floorplan.save_json(fp_json)
1415
+ output_files["floorplan"] = str(fp_png)
1416
+ output_files["homography"] = str(fp_json)
1417
+
1418
+ summary = RunSummary(
1419
+ source=_source_label(source),
1420
+ model=self.model_name,
1421
+ model_revision=getattr(self.detector, "revision", None),
1422
+ precision=getattr(self.detector, "precision", None),
1423
+ tracking_threshold=self.threshold,
1424
+ tracker=getattr(tracker, "name", type(tracker).__name__)
1425
+ if self.tracker_factory
1426
+ else self.tracker_name,
1427
+ postprocessed=self.postprocess,
1428
+ device=device_label,
1429
+ total_frames=seen_frames,
1430
+ processed_frames=processed,
1431
+ source_fps=src_fps,
1432
+ avg_fps=avg_fps,
1433
+ avg_inference_ms=avg_inf,
1434
+ avg_tracking_ms=avg_trk,
1435
+ total_detections=total_dets,
1436
+ total_track_observations=observations,
1437
+ frame_stride=stride,
1438
+ unique_tracks=len(card_index.cards),
1439
+ recovered_tracks=recovered_count,
1440
+ reid_merges=card_index.reid_merges,
1441
+ elapsed_s=elapsed_s,
1442
+ frame_width=width,
1443
+ frame_height=height,
1444
+ classes=self.classes,
1445
+ query=self.query,
1446
+ anonymize_mode=self.anonymize_mode,
1447
+ output_files=output_files,
1448
+ zone_dwell_totals_s=(
1449
+ dict(floorplan.zone_dwell_totals_s) if floorplan is not None else {}
1450
+ ),
1451
+ line_counts=counter.counts if counter else {},
1452
+ mask_fallback=(
1453
+ {
1454
+ "backend": self.mask_fallback_backend,
1455
+ **mask_resolver.stats.to_dict(),
1456
+ }
1457
+ if mask_resolver is not None
1458
+ else None
1459
+ ),
1460
+ )
1461
+
1462
+ if "html" in export_set:
1463
+ html_path = write_run_report(
1464
+ summary, counts, all_events, card_index.sorted_cards(), out_dir / "report.html"
1465
+ )
1466
+ summary.output_files["html"] = str(html_path)
1467
+
1468
+ summary_path = out_dir / "summary.json"
1469
+ summary.output_files["summary"] = str(summary_path)
1470
+ tmp_summary = out_dir / ".summary.tmp"
1471
+ tmp_summary.write_text(json.dumps(summary.to_dict(), indent=2), encoding="utf-8")
1472
+ tmp_summary.replace(summary_path)
1473
+ return summary