trackflow-python-cuda 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/pipeline.py ADDED
@@ -0,0 +1,910 @@
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.models import Precision
28
+ from trackflow.privacy import AnonymizeMode, PrivacyAnonymizer
29
+ from trackflow.reid import (
30
+ QUERY_THRESHOLDS,
31
+ ReidBackend,
32
+ ReidEmbedder,
33
+ TrackCardIndex,
34
+ VlmBackend,
35
+ VlmEmbedder,
36
+ create_vlm_embedder,
37
+ )
38
+ from trackflow.sinks import ObservationWriter, draw_tracks, write_run_report
39
+ from trackflow.tracker import Tracker, create_tracker, iou_buffer_for_interval
40
+ from trackflow.types import Detection, FrameResult, RunSummary
41
+
42
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
43
+
44
+
45
+ def fresh_run_dir(stem: str = "run", parent: str | Path = "runs") -> Path:
46
+ """Create and return the first unused ``<parent>/<stem>-N`` directory."""
47
+ for number in count(1):
48
+ path = Path(parent) / f"{stem}-{number}"
49
+ try:
50
+ path.mkdir(parents=True)
51
+ except FileExistsError:
52
+ continue
53
+ return path
54
+ raise AssertionError("unreachable")
55
+
56
+
57
+ @contextlib.contextmanager
58
+ def _stop_on_interrupt() -> Iterator[threading.Event]:
59
+ """Turn the first Ctrl-C into a stop request that ``run`` checks between frames.
60
+
61
+ After that first Ctrl-C the previous handler is back, so a second one interrupts as usual.
62
+ Signal handlers can only be set from the main thread; elsewhere Ctrl-C keeps its default.
63
+ """
64
+ stop = threading.Event()
65
+ previous = signal.getsignal(signal.SIGINT)
66
+ if threading.current_thread() is not threading.main_thread() or previous is None:
67
+ yield stop
68
+ return
69
+
70
+ def request_stop(signum: int, frame: Any) -> None:
71
+ stop.set()
72
+ signal.signal(signal.SIGINT, previous)
73
+
74
+ signal.signal(signal.SIGINT, request_stop)
75
+ try:
76
+ yield stop
77
+ finally:
78
+ signal.signal(signal.SIGINT, previous)
79
+
80
+
81
+ @contextlib.contextmanager
82
+ def _run_directory(output_dir: str | Path | None) -> Iterator[Path]:
83
+ if output_dir is None:
84
+ path = fresh_run_dir()
85
+ created = True
86
+ else:
87
+ path = Path(output_dir)
88
+ created = not path.exists()
89
+ path.mkdir(parents=True, exist_ok=True)
90
+
91
+ # Two callers can arrive at an existing empty directory simultaneously.
92
+ lock = path / ".trackflow-running"
93
+ try:
94
+ lock.touch(exist_ok=False)
95
+ except FileExistsError as exc:
96
+ raise FileExistsError(f"Output {path} is in use. Choose a fresh output directory.") from exc
97
+ try:
98
+ if any(p != lock for p in path.iterdir()):
99
+ raise FileExistsError(
100
+ f"Output {path} is not empty. Choose a fresh output directory (-o)."
101
+ )
102
+ yield path
103
+ except BaseException:
104
+ # A run that fails before writing anything leaves no empty folder behind.
105
+ lock.unlink(missing_ok=True)
106
+ if created and not any(path.iterdir()):
107
+ path.rmdir()
108
+ raise
109
+ finally:
110
+ lock.unlink(missing_ok=True)
111
+
112
+
113
+ def _is_stream_url(source: str | Path | int) -> bool:
114
+ return isinstance(source, str) and source.lower().startswith(
115
+ ("rtsp://", "rtsps://", "http://", "https://")
116
+ )
117
+
118
+
119
+ def _is_camera_source(source: str | Path | int) -> bool:
120
+ return isinstance(source, int) or (
121
+ isinstance(source, str)
122
+ and (source.isdigit() or source.lower() == "camera")
123
+ and not Path(source).exists()
124
+ )
125
+
126
+
127
+ def _is_live_source(source: str | Path | int) -> bool:
128
+ return _is_camera_source(source) or _is_stream_url(source)
129
+
130
+
131
+ _WRITER_STOP = object()
132
+
133
+
134
+ @contextlib.contextmanager
135
+ def _prefetch_frames(
136
+ frame_iter: Generator[tuple[int, float, np.ndarray], None, None],
137
+ *,
138
+ maxsize: int = 2,
139
+ ) -> Iterator[Iterator[tuple[int, float, np.ndarray]]]:
140
+ """Decode frames one step ahead on a worker thread so file I/O overlaps inference."""
141
+ q: queue.Queue[tuple[str, Any]] = queue.Queue(maxsize=maxsize)
142
+ cancel = threading.Event()
143
+
144
+ def _put(item: tuple[str, Any]) -> bool:
145
+ while not cancel.is_set():
146
+ try:
147
+ q.put(item, timeout=0.05)
148
+ return True
149
+ except queue.Full:
150
+ continue
151
+ return False
152
+
153
+ def _reader() -> None:
154
+ try:
155
+ for item in frame_iter:
156
+ if not _put(("frame", item)):
157
+ return
158
+ _put(("eof", None))
159
+ except BaseException as exc:
160
+ _put(("error", exc))
161
+ finally:
162
+ frame_iter.close()
163
+
164
+ thread = threading.Thread(target=_reader, name="trackflow-frame-reader", daemon=True)
165
+ thread.start()
166
+
167
+ def _consume() -> Iterator[tuple[int, float, np.ndarray]]:
168
+ while True:
169
+ kind, payload = q.get()
170
+ if kind == "frame":
171
+ yield payload
172
+ elif kind == "eof":
173
+ return
174
+ else:
175
+ raise payload
176
+
177
+ try:
178
+ yield _consume()
179
+ finally:
180
+ cancel.set()
181
+ while True:
182
+ try:
183
+ q.get_nowait()
184
+ except queue.Empty:
185
+ break
186
+ thread.join()
187
+
188
+
189
+ class _AsyncVideoWriter:
190
+ """Render annotations and encode video frames on a worker thread with bounded backpressure."""
191
+
192
+ def __init__(
193
+ self,
194
+ video_writer: cv2.VideoWriter,
195
+ render_fn: Callable[..., np.ndarray],
196
+ *,
197
+ maxsize: int = 2,
198
+ ) -> None:
199
+ self._video_writer = video_writer
200
+ self._render_fn = render_fn
201
+ self._queue: queue.Queue[Any] = queue.Queue(maxsize=maxsize)
202
+ self._abort = threading.Event()
203
+ self._error: BaseException | None = None
204
+ self._closed = False
205
+ self._thread = threading.Thread(
206
+ target=self._worker, name="trackflow-video-writer", daemon=True
207
+ )
208
+ self._thread.start()
209
+
210
+ def _worker(self) -> None:
211
+ try:
212
+ while True:
213
+ item = self._queue.get()
214
+ if item is _WRITER_STOP:
215
+ return
216
+ if self._abort.is_set():
217
+ continue
218
+ rendered = self._render_fn(*item)
219
+ self._video_writer.write(rendered)
220
+ except BaseException as exc:
221
+ self._error = exc
222
+ self._abort.set()
223
+
224
+ def submit(self, *args: Any) -> None:
225
+ while True:
226
+ if self._error is not None:
227
+ raise self._error
228
+ try:
229
+ self._queue.put(args, timeout=0.05)
230
+ return
231
+ except queue.Full:
232
+ continue
233
+
234
+ def close(self, *, abort: bool = False) -> None:
235
+ if self._closed:
236
+ return
237
+ self._closed = True
238
+ if abort:
239
+ self._abort.set()
240
+ while True:
241
+ try:
242
+ self._queue.get_nowait()
243
+ except queue.Empty:
244
+ break
245
+ while self._thread.is_alive():
246
+ try:
247
+ self._queue.put(_WRITER_STOP, timeout=0.05)
248
+ break
249
+ except queue.Full:
250
+ continue
251
+ self._thread.join()
252
+ if not abort and self._error is not None:
253
+ raise self._error
254
+
255
+
256
+ def _source_label(source: str | Path | int) -> str:
257
+ if not _is_stream_url(source):
258
+ return str(source)
259
+ url = urlsplit(str(source))
260
+ return urlunsplit((url.scheme, url.netloc.rsplit("@", 1)[-1], url.path, "", ""))
261
+
262
+
263
+ def _iter_frames(
264
+ source: str | Path | int,
265
+ *,
266
+ max_frames: int | None = None,
267
+ fps: float | None = None,
268
+ ) -> tuple[Generator[tuple[int, float, np.ndarray], None, None], float, int, int, int]:
269
+ """Open files, image sequences, OpenCV network streams or cameras."""
270
+ if fps is not None and (not np.isfinite(fps) or fps <= 0):
271
+ raise ValueError("fps must be positive and finite.")
272
+ is_camera = _is_camera_source(source)
273
+ if is_camera:
274
+ capture_source = 0 if str(source).lower() == "camera" else int(source)
275
+ elif _is_stream_url(source):
276
+ capture_source = str(source)
277
+ else:
278
+ path = Path(source)
279
+ if path.is_dir():
280
+
281
+ def natural_order(p: Path) -> list[int | str]:
282
+ return [
283
+ int(part) if part.isdecimal() else part
284
+ for part in re.split(r"(\d+)", p.name.casefold())
285
+ ]
286
+
287
+ images = sorted(
288
+ (p for p in path.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXTS),
289
+ key=natural_order,
290
+ )
291
+ if not images:
292
+ raise FileNotFoundError(f"No images found in directory: {path}")
293
+ first = cv2.imread(str(images[0]))
294
+ if first is None:
295
+ raise RuntimeError(f"Failed to read image: {images[0]}")
296
+ h, w = first.shape[:2]
297
+ rate = fps or 25.0
298
+ total = min(len(images), max_frames) if max_frames is not None else len(images)
299
+
300
+ def images_iter() -> Generator[tuple[int, float, np.ndarray], None, None]:
301
+ for idx, p in enumerate(images[:total]):
302
+ frame = first if idx == 0 else cv2.imread(str(p))
303
+ if frame is None or frame.shape[:2] != (h, w):
304
+ raise ValueError(f"Expected a readable {w}x{h} image at {p}")
305
+ yield idx, idx / rate, frame
306
+
307
+ return images_iter(), rate, w, h, total
308
+ if not path.is_file():
309
+ raise FileNotFoundError(f"Video source not found: {path}")
310
+ capture_source = str(path)
311
+
312
+ cap = cv2.VideoCapture(capture_source)
313
+ ok, first = cap.read()
314
+ if not ok or first is None:
315
+ cap.release()
316
+ raise RuntimeError(f"Could not read video source: {_source_label(source)}")
317
+ h, w = first.shape[:2]
318
+ rate = fps or cap.get(cv2.CAP_PROP_FPS)
319
+ if not np.isfinite(rate) or rate <= 0:
320
+ rate = 30.0
321
+ reported = cap.get(cv2.CAP_PROP_FRAME_COUNT)
322
+ total = int(reported) if np.isfinite(reported) and reported > 0 else 0
323
+ if max_frames is not None:
324
+ total = min(total, max_frames) if total else max_frames
325
+
326
+ def capture_iter() -> Generator[tuple[int, float, np.ndarray], None, None]:
327
+ try:
328
+ idx, frame = 0, first
329
+ while True:
330
+ if frame.shape[:2] != (h, w):
331
+ raise ValueError("Video dimensions changed during tracking.")
332
+ yield idx, idx / rate, frame
333
+ idx += 1
334
+ if max_frames is not None and idx >= max_frames:
335
+ break
336
+ ok, frame = cap.read()
337
+ if not ok:
338
+ break
339
+ finally:
340
+ cap.release()
341
+
342
+ return capture_iter(), rate, w, h, total
343
+
344
+
345
+ def _crop(frame_bgr: np.ndarray, bbox: tuple[float, float, float, float]) -> np.ndarray | None:
346
+ h, w = frame_bgr.shape[:2]
347
+ x1, y1 = max(0, int(round(bbox[0]))), max(0, int(round(bbox[1])))
348
+ x2, y2 = min(w, int(round(bbox[2]))), min(h, int(round(bbox[3])))
349
+ if x2 - x1 < 4 or y2 - y1 < 4:
350
+ return None
351
+ return frame_bgr[y1:y2, x1:x2]
352
+
353
+
354
+ class TrackflowPipeline:
355
+ """Unified real-time tracking pipeline combining detection, MOT, Re-ID/NL query, privacy & floorplan."""
356
+
357
+ def __init__(
358
+ self,
359
+ *,
360
+ model: str | Path | None = None,
361
+ precision: Precision = "fp32",
362
+ tracker: str = "bytetrack",
363
+ device: str = "auto",
364
+ threshold: float = 0.45,
365
+ classes: Sequence[str] | None = ("person",),
366
+ reid: ReidBackend = "none",
367
+ vlm: VlmBackend | None = None,
368
+ reid_merge: bool = False,
369
+ query: str | None = None,
370
+ query_threshold: float | None = None,
371
+ anonymize: AnonymizeMode = "none",
372
+ homography: FloorplanHomography | str | Path | None = None,
373
+ lines: Sequence[CountingLine] = (),
374
+ detector: Detector | None = None,
375
+ tracker_factory: Callable[[], Tracker] | None = None,
376
+ reid_embedder: ReidEmbedder | None = None,
377
+ vlm_embedder: VlmEmbedder | None = None,
378
+ cache_dir: str | Path | None = None,
379
+ ) -> None:
380
+ self.model_name = (
381
+ str(model)
382
+ if model is not None
383
+ else (
384
+ getattr(detector, "model_name", type(detector).__name__)
385
+ if detector is not None
386
+ else "rtdetr-v2-r18"
387
+ )
388
+ )
389
+ self.tracker_name = tracker
390
+ self.tracker_factory = tracker_factory
391
+ if tracker_factory is None:
392
+ create_tracker(tracker) # reject an unknown name before any model loads
393
+ self.threshold = float(threshold)
394
+ if not 0 <= self.threshold <= 1:
395
+ raise ValueError("threshold must be between 0 and 1.")
396
+ self._allowed = _allowed_classes(classes)
397
+ self.classes = sorted(self._allowed) if self._allowed is not None else ["all"]
398
+ self.query = query.strip() if query else None
399
+ self.anonymize_mode: AnonymizeMode = anonymize
400
+
401
+ if reid in ("clip", "siglip"):
402
+ # Pre-0.1 runs used `--reid clip` for queries. CLIP can't tell people apart, so it is
403
+ # now only a vision-language model for --query / search, never an identity model.
404
+ warnings.warn(
405
+ f"--reid {reid} is now `--vlm {reid}` (text queries & search only). Use "
406
+ "`--reid osnet` for person re-identification.",
407
+ stacklevel=2,
408
+ )
409
+ vlm = vlm if vlm not in (None, "none") else reid # type: ignore[assignment]
410
+ reid = "none"
411
+ if vlm is None:
412
+ vlm = "clip" if self.query else "none"
413
+ if reid_merge and reid == "none" and reid_embedder is None:
414
+ raise ValueError("--reid-merge needs a person Re-ID model: add `--reid osnet`.")
415
+
416
+ self.reid_backend: ReidBackend = reid_embedder.backend if reid_embedder else reid
417
+ self.vlm_backend: VlmBackend = vlm_embedder.backend if vlm_embedder else vlm
418
+ self.query_threshold = float(
419
+ QUERY_THRESHOLDS.get(self.vlm_backend, 0.22)
420
+ if query_threshold is None
421
+ else query_threshold
422
+ )
423
+ self.reid_merge = bool(reid_merge)
424
+ if self.query and self.vlm_backend == "none":
425
+ raise ValueError(
426
+ "A text query needs a vision-language model. Choose clip, siglip, siglip2 or embeddinggemma."
427
+ )
428
+
429
+ detect_classes = self._allowed
430
+ if detect_classes is not None and anonymize in ("blur", "pixelate", "face-blur"):
431
+ detect_classes = detect_classes | {"person"}
432
+ self.detector = (
433
+ detector
434
+ if detector is not None
435
+ else create_detector(
436
+ model=self.model_name,
437
+ precision=precision,
438
+ device=device,
439
+ threshold=min(0.15, threshold, max(0.10, threshold * 0.35)),
440
+ classes=sorted(detect_classes) if detect_classes else None,
441
+ cache_dir=cache_dir,
442
+ )
443
+ )
444
+ self.reid_embedder = reid_embedder or (
445
+ ReidEmbedder(
446
+ backend=self.reid_backend,
447
+ device=device,
448
+ cache_dir=cache_dir,
449
+ )
450
+ if self.reid_backend != "none"
451
+ else None
452
+ )
453
+ self.vlm_embedder = vlm_embedder or (
454
+ create_vlm_embedder(self.vlm_backend, device=device, cache_dir=cache_dir)
455
+ if self.vlm_backend != "none"
456
+ else None
457
+ )
458
+ self.anonymizer = PrivacyAnonymizer(mode=anonymize)
459
+ if isinstance(homography, (str, Path)):
460
+ self.homography: FloorplanHomography | None = FloorplanHomography.from_json(homography)
461
+ else:
462
+ self.homography = homography
463
+ self.lines = list(lines)
464
+ LineCounter(self.lines) # reject duplicate names before any frame is read
465
+
466
+ def _new_counter(self) -> LineCounter | None:
467
+ return LineCounter(self.lines) if self.lines else None
468
+
469
+ def _new_tracker(self, frame_dt: float) -> Tracker:
470
+ if self.tracker_factory is not None:
471
+ return self.tracker_factory()
472
+ return create_tracker(
473
+ self.tracker_name,
474
+ track_high_thresh=self.threshold,
475
+ track_low_thresh=min(self.threshold, max(0.10, self.threshold * 0.35)),
476
+ new_track_thresh=max(self.threshold, min(0.95, self.threshold + 0.05)),
477
+ iou_buffer=iou_buffer_for_interval(frame_dt),
478
+ )
479
+
480
+ def _new_cards(
481
+ self,
482
+ tracker: Tracker,
483
+ stride: int,
484
+ crops_dir: Path | None = None,
485
+ ) -> TrackCardIndex:
486
+ buffer = getattr(tracker, "track_buffer", None)
487
+ if self.reid_merge and buffer is None:
488
+ raise ValueError(
489
+ "A custom tracker using reid_merge must expose its track_buffer in processed frames."
490
+ )
491
+ return TrackCardIndex(
492
+ vlm=self.vlm_embedder,
493
+ reid=self.reid_embedder,
494
+ query=self.query,
495
+ query_threshold=self.query_threshold,
496
+ reid_merge=self.reid_merge,
497
+ # A lost raw ID can still be recovered during the track buffer. Merging a
498
+ # different raw ID into it during that window can give two objects the same ID.
499
+ min_exit_gap_frames=max(8, ((buffer or 0) + 1) * stride),
500
+ crops_dir=crops_dir,
501
+ )
502
+
503
+ def _process_frame(
504
+ self,
505
+ frame: np.ndarray,
506
+ idx: int,
507
+ timestamp: float,
508
+ dt: float,
509
+ tracker: Tracker,
510
+ cards: TrackCardIndex | None,
511
+ floorplan: FloorplanHomography | None,
512
+ counter: LineCounter | None = None,
513
+ *,
514
+ record_floorplan: bool = False,
515
+ ) -> tuple[FrameResult, list[Detection]]:
516
+ start = time.perf_counter()
517
+ raw = self.detector.detect(frame)
518
+ detected = time.perf_counter()
519
+ targets = (
520
+ raw
521
+ if self._allowed is None
522
+ else [d for d in raw if _class_key(d.class_name) in self._allowed]
523
+ )
524
+ min_conf = getattr(tracker, "embedding_min_confidence", None)
525
+ if min_conf is not None and self.reid_embedder is not None:
526
+ people = [
527
+ d for d in targets if d.confidence >= min_conf and d.class_name.lower() == "person"
528
+ ]
529
+ for det, emb in zip(
530
+ people,
531
+ self.reid_embedder.encode_images([_crop(frame, d.bbox) for d in people]),
532
+ strict=True,
533
+ ):
534
+ det.embedding = emb
535
+ tracks = tracker.update(targets, frame_bgr=frame)
536
+ tracked = time.perf_counter()
537
+ if floorplan is not None:
538
+ for tr in tracks:
539
+ if record_floorplan:
540
+ tr.world_xy, tr.zone = floorplan.observe(tr.track_id, tr.foot_point, dt_s=dt)
541
+ else:
542
+ tr.world_xy = floorplan.project(tr.foot_point)
543
+ tr.zone = floorplan.locate_zone(tr.world_xy)
544
+ events = list(getattr(tracker, "last_events", ()))
545
+ if counter is not None:
546
+ # Raw tracker IDs: a Re-ID merge would join a track to a point from before it left.
547
+ events.extend(counter.update(tracks, timestamp))
548
+ if cards is not None:
549
+ events.extend(cards.update(idx, timestamp, frame, tracks, frame_dt_s=dt))
550
+ return FrameResult(
551
+ frame_idx=idx,
552
+ timestamp_s=timestamp,
553
+ tracks=tracks,
554
+ num_detections=len(targets),
555
+ inference_ms=(detected - start) * 1000,
556
+ tracking_ms=(tracked - detected) * 1000,
557
+ events=events,
558
+ ), raw
559
+
560
+ def stream(self, frames: Iterable[np.ndarray], *, fps: float = 30.0) -> Iterator[FrameResult]:
561
+ """Yield observations for consecutive BGR uint8 frames without writing any files.
562
+
563
+ Each call starts a fresh tracker. With re-entry merging enabled, a merge event
564
+ reports the new canonical ID; observations already yielded keep their original ID.
565
+ """
566
+ if not np.isfinite(fps) or fps <= 0:
567
+ raise ValueError("fps must be positive and finite.")
568
+ dt = 1.0 / fps
569
+ tracker = self._new_tracker(dt)
570
+ cards = self._new_cards(tracker, 1) if self.vlm_embedder or self.reid_merge else None
571
+ counter = self._new_counter()
572
+ shape = None
573
+ for idx, frame in enumerate(frames):
574
+ if (
575
+ not isinstance(frame, np.ndarray)
576
+ or frame.ndim != 3
577
+ or frame.shape[2] != 3
578
+ or frame.dtype != np.uint8
579
+ or not frame.size
580
+ ):
581
+ raise ValueError(f"Frame {idx} must be a nonempty H×W×3 uint8 BGR array.")
582
+ if shape is not None and frame.shape != shape:
583
+ raise ValueError(
584
+ f"Frame {idx} changed size. Start a new stream when geometry changes."
585
+ )
586
+ shape = frame.shape
587
+ result, _ = self._process_frame(
588
+ frame, idx, idx / fps, dt, tracker, cards, self.homography, counter
589
+ )
590
+ yield result
591
+
592
+ def run(
593
+ self,
594
+ source: str | Path | int,
595
+ *,
596
+ output_dir: str | Path | None = None,
597
+ skip: int = 0,
598
+ fps: float | None = None,
599
+ max_frames: int | None = None,
600
+ save_video: bool = True,
601
+ exports: Sequence[str] = ("parquet", "jsonl", "html"),
602
+ display: bool = False,
603
+ progress_callback: Callable[[int, int, float], None] | None = None,
604
+ ) -> RunSummary:
605
+ """Execute tracking on ``source`` and write requested artifacts into ``output_dir``.
606
+
607
+ Ctrl-C stops reading frames and still writes every artifact for the frames processed so
608
+ far, which is how a camera or stream run ends. A second Ctrl-C aborts.
609
+ """
610
+ if skip < 0 or (max_frames is not None and max_frames < 1):
611
+ raise ValueError("skip must be nonnegative and max_frames must be positive.")
612
+ if isinstance(exports, str):
613
+ exports = exports.split(",")
614
+ export_set = {e.lower().strip() for e in exports}
615
+ unknown = export_set - {"parquet", "jsonl", "csv", "mot", "html"}
616
+ if unknown:
617
+ raise ValueError(f"Unknown export format(s): {', '.join(sorted(unknown))}")
618
+ stride = skip + 1
619
+ with contextlib.ExitStack() as stack:
620
+ out_dir = stack.enter_context(_run_directory(output_dir))
621
+ frame_iter, src_fps, width, height, total_frames = _iter_frames(
622
+ source, max_frames=max_frames, fps=fps
623
+ )
624
+
625
+ capture_stack = stack.enter_context(contextlib.ExitStack())
626
+ capture_stack.callback(frame_iter.close)
627
+ frame_dt_s = stride / src_fps
628
+ tracker = self._new_tracker(frame_dt_s)
629
+ card_index = self._new_cards(
630
+ tracker,
631
+ stride,
632
+ out_dir / "crops" if self.anonymize_mode == "none" else None,
633
+ )
634
+ floorplan = self.homography.fresh() if self.homography else None
635
+ counter = self._new_counter()
636
+
637
+ video_writer: cv2.VideoWriter | None = None
638
+ video_path = out_dir / "annotated.mp4"
639
+ if save_video:
640
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
641
+ out_fps = src_fps / max(1, skip + 1)
642
+ video_writer = cv2.VideoWriter(str(video_path), fourcc, out_fps, (width, height))
643
+ if not video_writer.isOpened():
644
+ video_writer.release()
645
+ raise RuntimeError(f"Could not open MP4 video writer at {video_path}")
646
+ capture_stack.callback(video_writer.release)
647
+
648
+ counts: list[int] = []
649
+ extensions = {"parquet": "parquet", "jsonl": "jsonl", "csv": "csv", "mot": "txt"}
650
+ paths = {
651
+ fmt: out_dir / f"tracks.{ext}"
652
+ for fmt, ext in extensions.items()
653
+ if fmt in export_set
654
+ }
655
+ writer_stack = stack.enter_context(contextlib.ExitStack())
656
+ sink = ObservationWriter(paths, writer_stack)
657
+ # Re-entry IDs can change retrospectively. Only that mode needs a disk spool.
658
+ spool = (
659
+ stack.enter_context(
660
+ tempfile.TemporaryFile(mode="w+", encoding="utf-8", dir=out_dir)
661
+ )
662
+ if self.reid_merge and paths
663
+ else None
664
+ )
665
+ trails: dict[int, list[tuple[int, int]]] = defaultdict(list)
666
+ all_events: list[dict[str, Any]] = []
667
+
668
+ total_dets = 0
669
+ recovered_count = 0
670
+ total_inf_ms = total_trk_ms = 0.0
671
+ observations = 0
672
+
673
+ t_start = time.perf_counter()
674
+ processed = 0
675
+ seen_frames = 0
676
+
677
+ def _render_frame(
678
+ frame_bgr: np.ndarray,
679
+ tracks: list[Any],
680
+ dets: list[Detection],
681
+ coasting: list[Any],
682
+ trails_snap: dict[int, list[tuple[int, int]]],
683
+ live_fps: float,
684
+ line_counts_snap: dict[str, dict[str, int]] | None,
685
+ ) -> np.ndarray:
686
+ anon_frame = self.anonymizer.apply(
687
+ frame_bgr, tracks, detections=dets, coasting=coasting
688
+ )
689
+ return draw_tracks(
690
+ anon_frame,
691
+ tracks,
692
+ coasting=coasting,
693
+ trails=trails_snap,
694
+ fps=live_fps,
695
+ query=self.query,
696
+ anonymize_mode=self.anonymize_mode,
697
+ lines=self.lines,
698
+ line_counts=line_counts_snap,
699
+ )
700
+
701
+ frames: Iterator[tuple[int, float, np.ndarray]] = (
702
+ capture_stack.enter_context(_prefetch_frames(frame_iter))
703
+ if not _is_live_source(source) and total_frames != 1
704
+ else frame_iter
705
+ )
706
+ async_writer = (
707
+ _AsyncVideoWriter(video_writer, _render_frame)
708
+ if video_writer is not None and not display
709
+ else None
710
+ )
711
+
712
+ stop = stack.enter_context(_stop_on_interrupt())
713
+ aborted = False
714
+ try:
715
+ for frame_idx, timestamp_s, frame_bgr in frames:
716
+ if stop.is_set():
717
+ break
718
+ seen_frames += 1
719
+ if skip > 0 and (frame_idx % (skip + 1) != 0):
720
+ continue
721
+
722
+ fr, dets = self._process_frame(
723
+ frame_bgr,
724
+ frame_idx,
725
+ timestamp_s,
726
+ frame_dt_s,
727
+ tracker,
728
+ card_index,
729
+ floorplan,
730
+ counter,
731
+ record_floorplan=True,
732
+ )
733
+ tracks = fr.tracks
734
+ observations += len(tracks)
735
+ total_dets += fr.num_detections
736
+ total_inf_ms += fr.inference_ms
737
+ total_trk_ms += fr.tracking_ms
738
+ for ev in fr.events:
739
+ all_events.append(
740
+ {"frame_idx": frame_idx, "timestamp_s": round(timestamp_s, 3), **ev}
741
+ )
742
+
743
+ for tr in tracks:
744
+ if tr.recovered:
745
+ recovered_count += 1
746
+ if paths:
747
+ record = tr.to_record(frame_idx, timestamp_s)
748
+ if spool is None:
749
+ sink.append(record)
750
+ else:
751
+ spool.write(json.dumps(record) + "\n")
752
+ if save_video or display:
753
+ fx, fy = tr.foot_point
754
+ trail = trails[tr.track_id]
755
+ trail.append((int(round(fx)), int(round(fy))))
756
+ del trail[:-48]
757
+ if "html" in export_set:
758
+ counts.append(len(tracks))
759
+ processed += 1
760
+
761
+ elapsed_now = max(time.perf_counter() - t_start, 1e-6)
762
+ live_fps = processed / elapsed_now
763
+
764
+ if save_video or display:
765
+ # Anonymize every box that may hold a person, not just confirmed tracks.
766
+ coasting = (
767
+ tracker.coasting_tracks(3)
768
+ if hasattr(tracker, "coasting_tracks")
769
+ else []
770
+ )
771
+ for c in coasting:
772
+ c.track_id = card_index.canonical_id(c.track_id)
773
+ if async_writer is not None:
774
+ trails_snap = {tr.track_id: trails[tr.track_id][-32:] for tr in tracks}
775
+ line_counts_snap = (
776
+ {k: dict(v) for k, v in counter.counts.items()} if counter else None
777
+ )
778
+ async_writer.submit(
779
+ frame_bgr,
780
+ tracks,
781
+ dets,
782
+ coasting,
783
+ trails_snap,
784
+ live_fps,
785
+ line_counts_snap,
786
+ )
787
+ else:
788
+ rendered = _render_frame(
789
+ frame_bgr,
790
+ tracks,
791
+ dets,
792
+ coasting,
793
+ trails,
794
+ live_fps,
795
+ counter.counts if counter else None,
796
+ )
797
+ if video_writer is not None:
798
+ video_writer.write(rendered)
799
+ if display:
800
+ try:
801
+ cv2.imshow("Trackflow", rendered)
802
+ if cv2.waitKey(1) & 0xFF == ord("q"):
803
+ break
804
+ except cv2.error:
805
+ display = False
806
+
807
+ if progress_callback is not None:
808
+ progress_callback(processed, (total_frames + skip) // stride, live_fps)
809
+ except BaseException:
810
+ aborted = True
811
+ raise
812
+ finally:
813
+ try:
814
+ if async_writer is not None:
815
+ async_writer.close(abort=aborted)
816
+ finally:
817
+ capture_stack.close()
818
+ if display:
819
+ with contextlib.suppress(cv2.error):
820
+ cv2.destroyAllWindows()
821
+
822
+ # Merges are decided a few frames into a returning person's new track; relabel the
823
+ # observations recorded before that so exports use one ID per person.
824
+ if processed == 0:
825
+ if stop.is_set():
826
+ raise KeyboardInterrupt
827
+ raise RuntimeError(f"No readable frames in {source}")
828
+ if spool is not None:
829
+ spool.seek(0)
830
+ for line in spool:
831
+ rec = json.loads(line)
832
+ rec["track_id"] = card_index.canonical_id(rec["track_id"])
833
+ sink.append(rec)
834
+ writer_stack.close()
835
+
836
+ elapsed_s = max(time.perf_counter() - t_start, 1e-6)
837
+ avg_fps = processed / elapsed_s
838
+ avg_inf = total_inf_ms / processed
839
+ avg_trk = total_trk_ms / processed
840
+
841
+ device_label = getattr(self.detector, "active_provider", "custom")
842
+ output_files = {fmt: str(path) for fmt, path in paths.items()}
843
+ if save_video and video_path.is_file():
844
+ output_files["video"] = str(video_path)
845
+
846
+ # Persist Track Cards & diagnostic events (always written for `trackflow inspect` / `search`)
847
+ cards_path = out_dir / "track_cards.json"
848
+ card_index.save_json(
849
+ cards_path, reid_backend=self.reid_backend, vlm_backend=self.vlm_backend
850
+ )
851
+ output_files["track_cards"] = str(cards_path)
852
+
853
+ events_path = out_dir / "events.json"
854
+ events_path.write_text(json.dumps(all_events, indent=2), encoding="utf-8")
855
+ output_files["events"] = str(events_path)
856
+
857
+ if floorplan is not None:
858
+ fp_png = floorplan.render_floorplan(out_dir / "floorplan.png")
859
+ fp_json = out_dir / "homography.json"
860
+ floorplan.save_json(fp_json)
861
+ output_files["floorplan"] = str(fp_png)
862
+ output_files["homography"] = str(fp_json)
863
+
864
+ summary = RunSummary(
865
+ source=_source_label(source),
866
+ model=self.model_name,
867
+ model_revision=getattr(self.detector, "revision", None),
868
+ precision=getattr(self.detector, "precision", None),
869
+ tracking_threshold=self.threshold,
870
+ tracker=getattr(tracker, "name", type(tracker).__name__)
871
+ if self.tracker_factory
872
+ else self.tracker_name,
873
+ device=device_label,
874
+ total_frames=seen_frames,
875
+ processed_frames=processed,
876
+ source_fps=src_fps,
877
+ avg_fps=avg_fps,
878
+ avg_inference_ms=avg_inf,
879
+ avg_tracking_ms=avg_trk,
880
+ total_detections=total_dets,
881
+ total_track_observations=observations,
882
+ frame_stride=stride,
883
+ unique_tracks=len(card_index.cards),
884
+ recovered_tracks=recovered_count,
885
+ reid_merges=card_index.reid_merges,
886
+ elapsed_s=elapsed_s,
887
+ frame_width=width,
888
+ frame_height=height,
889
+ classes=self.classes,
890
+ query=self.query,
891
+ anonymize_mode=self.anonymize_mode,
892
+ output_files=output_files,
893
+ zone_dwell_totals_s=(
894
+ dict(floorplan.zone_dwell_totals_s) if floorplan is not None else {}
895
+ ),
896
+ line_counts=counter.counts if counter else {},
897
+ )
898
+
899
+ if "html" in export_set:
900
+ html_path = write_run_report(
901
+ summary, counts, all_events, card_index.sorted_cards(), out_dir / "report.html"
902
+ )
903
+ summary.output_files["html"] = str(html_path)
904
+
905
+ summary_path = out_dir / "summary.json"
906
+ summary.output_files["summary"] = str(summary_path)
907
+ tmp_summary = out_dir / ".summary.tmp"
908
+ tmp_summary.write_text(json.dumps(summary.to_dict(), indent=2), encoding="utf-8")
909
+ tmp_summary.replace(summary_path)
910
+ return summary