trackflow-python 0.1.0__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/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """Trackflow — Modern real-time people & object tracking toolkit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from trackflow.detector import OnnxDetrDetector
6
+ from trackflow.homography import DwellZone, FloorplanHomography
7
+ from trackflow.models import MODEL_REGISTRY, REID_REGISTRY, ModelSpec
8
+ from trackflow.pipeline import TrackflowPipeline
9
+ from trackflow.privacy import PrivacyAnonymizer
10
+ from trackflow.reid import AppearanceEmbedder, TrackCardIndex
11
+ from trackflow.tracker import BotSortTracker, ByteTracker, create_tracker
12
+ from trackflow.types import (
13
+ Detection,
14
+ FrameResult,
15
+ HomographyPoint,
16
+ RunSummary,
17
+ Track,
18
+ TrackCard,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ __all__ = [
24
+ "__version__",
25
+ "AppearanceEmbedder",
26
+ "BotSortTracker",
27
+ "ByteTracker",
28
+ "Detection",
29
+ "DwellZone",
30
+ "FloorplanHomography",
31
+ "FrameResult",
32
+ "HomographyPoint",
33
+ "MODEL_REGISTRY",
34
+ "ModelSpec",
35
+ "OnnxDetrDetector",
36
+ "PrivacyAnonymizer",
37
+ "REID_REGISTRY",
38
+ "RunSummary",
39
+ "Track",
40
+ "TrackCard",
41
+ "TrackCardIndex",
42
+ "TrackflowPipeline",
43
+ "create_tracker",
44
+ ]
trackflow/benchmark.py ADDED
@@ -0,0 +1,253 @@
1
+ """Reproducible benchmark harness & 2017 vs. 2026 split-screen comparison generator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import cv2
12
+ import numpy as np
13
+
14
+ from trackflow.pipeline import TrackflowPipeline
15
+ from trackflow.types import RunSummary
16
+
17
+ # Historical baseline recorded in the original July 2017 README (preserved on `legacy-2017`)
18
+ LEGACY_2017_BASELINE: dict[str, Any] = {
19
+ "era": "2017 (Tracking-with-darkflow)",
20
+ "detector": "YOLOv2 (darkflow / TF 1.0)",
21
+ "tracker": "DeepSORT (manual TF frozen graph)",
22
+ "hardware": "NVIDIA GTX 1080 (1024x1280)",
23
+ "avg_fps": 14.0,
24
+ "avg_fps_with_mog2": 10.5,
25
+ "setup_steps": 6,
26
+ "license": "GPL-3.0",
27
+ "features": "Boxes + IDs + CSV only",
28
+ }
29
+
30
+
31
+ @dataclass(slots=True)
32
+ class BenchmarkRow:
33
+ model: str
34
+ tracker: str
35
+ device: str
36
+ avg_fps: float
37
+ avg_inference_ms: float
38
+ avg_tracking_ms: float
39
+ unique_tracks: int
40
+ processed_frames: int
41
+
42
+ def to_dict(self) -> dict[str, Any]:
43
+ return {
44
+ "model": self.model,
45
+ "tracker": self.tracker,
46
+ "device": self.device,
47
+ "avg_fps": round(self.avg_fps, 2),
48
+ "avg_inference_ms": round(self.avg_inference_ms, 2),
49
+ "avg_tracking_ms": round(self.avg_tracking_ms, 2),
50
+ "unique_tracks": self.unique_tracks,
51
+ "processed_frames": self.processed_frames,
52
+ }
53
+
54
+
55
+ def generate_synthetic_crowd_video(
56
+ out_path: str | Path,
57
+ *,
58
+ width: int = 640,
59
+ height: int = 360,
60
+ num_frames: int = 90,
61
+ fps: float = 30.0,
62
+ ) -> Path:
63
+ """Create a deterministic synthetic multi-pedestrian test video for offline/CI benchmarks."""
64
+ path = Path(out_path)
65
+ path.parent.mkdir(parents=True, exist_ok=True)
66
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
67
+ writer = cv2.VideoWriter(str(path), fourcc, fps, (width, height))
68
+
69
+ actors = [
70
+ {"x": 60.0, "y": 140.0, "vx": 4.2, "vy": 0.4, "color": (60, 60, 220)},
71
+ {"x": 540.0, "y": 150.0, "vx": -3.8, "vy": 0.3, "color": (220, 140, 50)},
72
+ {"x": 180.0, "y": 120.0, "vx": 2.1, "vy": 0.8, "color": (70, 200, 110)},
73
+ {"x": 420.0, "y": 180.0, "vx": -2.5, "vy": -0.3, "color": (200, 90, 200)},
74
+ ]
75
+
76
+ try:
77
+ for _ in range(num_frames):
78
+ frame = np.full((height, width, 3), (38, 42, 52), dtype=np.uint8)
79
+ cv2.rectangle(frame, (0, int(height * 0.52)), (width, height), (54, 58, 68), -1)
80
+ for a in actors:
81
+ cx, cy = int(a["x"]), int(a["y"])
82
+ # Simple stylized pedestrian silhouette
83
+ cv2.circle(frame, (cx, cy - 36), 11, (205, 185, 170), -1)
84
+ cv2.rectangle(frame, (cx - 14, cy - 24), (cx + 14, cy + 20), a["color"], -1)
85
+ cv2.rectangle(frame, (cx - 12, cy + 20), (cx - 2, cy + 56), (40, 45, 60), -1)
86
+ cv2.rectangle(frame, (cx + 2, cy + 20), (cx + 12, cy + 56), (40, 45, 60), -1)
87
+ a["x"] = (a["x"] + a["vx"]) % (width - 40) + 20
88
+ a["y"] = float(np.clip(a["y"] + a["vy"], 90, height - 80))
89
+ writer.write(frame)
90
+ finally:
91
+ writer.release()
92
+
93
+ return path
94
+
95
+
96
+ def render_split_screen_2017_vs_2026(
97
+ modern_video_path: str | Path,
98
+ out_path: str | Path,
99
+ *,
100
+ modern_summary: RunSummary,
101
+ ) -> Path:
102
+ """Create a 2017 vs. 2026 side-by-side showcase video illustrating 9 years of progress."""
103
+ src = Path(modern_video_path)
104
+ out = Path(out_path)
105
+ cap = cv2.VideoCapture(str(src))
106
+ if not cap.isOpened():
107
+ raise RuntimeError(f"Could not open annotated video: {src}")
108
+
109
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
110
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
111
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
112
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
113
+ writer = cv2.VideoWriter(str(out), fourcc, fps, (w * 2, h))
114
+
115
+ frame_i = 0
116
+ try:
117
+ while True:
118
+ ok, right_frame = cap.read()
119
+ if not ok:
120
+ break
121
+
122
+ # Stylized 2017 panel: lower effective cadence + retro YOLOv2/DeepSORT HUD banner
123
+ if frame_i % 2 == 0 or frame_i == 0:
124
+ left_frame = cv2.GaussianBlur(right_frame, (5, 5), 0)
125
+ left_frame = cv2.convertScaleAbs(left_frame, alpha=0.82, beta=-10)
126
+ cv2.rectangle(left_frame, (0, 0), (w, 42), (24, 24, 30), -1)
127
+ cv2.putText(
128
+ left_frame,
129
+ "2017: YOLOv2 + DeepSORT (TF 1.0, Cython, 14 FPS GTX 1080, 6 setup steps)",
130
+ (10, 27),
131
+ cv2.FONT_HERSHEY_SIMPLEX,
132
+ 0.45,
133
+ (190, 190, 210),
134
+ 1,
135
+ cv2.LINE_AA,
136
+ )
137
+
138
+ cv2.rectangle(right_frame, (0, 0), (w, 42), (10, 38, 32), -1)
139
+ cv2.putText(
140
+ right_frame,
141
+ f"2026: Trackflow ({modern_summary.model} + {modern_summary.tracker} · {modern_summary.avg_fps:.1f} FPS · 1 cmd)",
142
+ (10, 27),
143
+ cv2.FONT_HERSHEY_SIMPLEX,
144
+ 0.45,
145
+ (140, 255, 200),
146
+ 1,
147
+ cv2.LINE_AA,
148
+ )
149
+
150
+ combined = np.hstack([left_frame, right_frame])
151
+ cv2.line(combined, (w, 0), (w, h), (56, 189, 248), 2)
152
+ writer.write(combined)
153
+ frame_i += 1
154
+ finally:
155
+ cap.release()
156
+ writer.release()
157
+
158
+ return out
159
+
160
+
161
+ def run_benchmark_suite(
162
+ video_path: str | Path,
163
+ *,
164
+ output_dir: str | Path = "runs/benchmark",
165
+ models: Sequence[str] = ("rtdetr-v2-r18",),
166
+ trackers: Sequence[str] = ("bytetrack", "botsort"),
167
+ device: str = "auto",
168
+ max_frames: int | None = 120,
169
+ split_screen: bool = False,
170
+ detector_factory: Any | None = None,
171
+ ) -> dict[str, Any]:
172
+ """Run reproducible Trackflow benchmarks and write JSON + Markdown 2017 vs. 2026 report."""
173
+ out_dir = Path(output_dir)
174
+ out_dir.mkdir(parents=True, exist_ok=True)
175
+
176
+ rows: list[BenchmarkRow] = []
177
+ summaries: list[RunSummary] = []
178
+
179
+ for model_name in models:
180
+ for tracker_name in trackers:
181
+ sub_dir = out_dir / f"{model_name}_{tracker_name}"
182
+ det = detector_factory(model_name) if detector_factory is not None else None
183
+ pipe = TrackflowPipeline(
184
+ model=model_name,
185
+ tracker=tracker_name,
186
+ device=device,
187
+ detector=det,
188
+ )
189
+ summary = pipe.run(
190
+ str(video_path),
191
+ output_dir=sub_dir,
192
+ max_frames=max_frames,
193
+ save_video=split_screen and len(summaries) == 0,
194
+ exports=("parquet", "jsonl"),
195
+ )
196
+ summaries.append(summary)
197
+ rows.append(
198
+ BenchmarkRow(
199
+ model=model_name,
200
+ tracker=tracker_name,
201
+ device=summary.device,
202
+ avg_fps=summary.avg_fps,
203
+ avg_inference_ms=summary.avg_inference_ms,
204
+ avg_tracking_ms=summary.avg_tracking_ms,
205
+ unique_tracks=summary.unique_tracks,
206
+ processed_frames=summary.processed_frames,
207
+ )
208
+ )
209
+
210
+ split_path: str | None = None
211
+ if split_screen and summaries and "video" in summaries[0].output_files:
212
+ split_file = render_split_screen_2017_vs_2026(
213
+ summaries[0].output_files["video"],
214
+ out_dir / "split_2017_vs_2026.mp4",
215
+ modern_summary=summaries[0],
216
+ )
217
+ split_path = str(split_file)
218
+
219
+ md_lines = [
220
+ "# Trackflow Benchmark Report — 2017 vs. 2026",
221
+ "",
222
+ "## Historical 2017 Baseline (`legacy-2017`)",
223
+ f"- **Stack:** {LEGACY_2017_BASELINE['detector']} + {LEGACY_2017_BASELINE['tracker']}",
224
+ f"- **Recorded Speed:** {LEGACY_2017_BASELINE['avg_fps']} FPS on {LEGACY_2017_BASELINE['hardware']} ({LEGACY_2017_BASELINE['avg_fps_with_mog2']} FPS w/ MOG2)",
225
+ f"- **Setup Friction:** {LEGACY_2017_BASELINE['setup_steps']} manual steps (3 git submodules, Cython build, Google Drive weights)",
226
+ "",
227
+ "## 2026 Trackflow Results",
228
+ "",
229
+ "| Model | Tracker | Provider | Avg FPS | Inference (ms) | Tracking (ms) | Unique Tracks | Frames |",
230
+ "| :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: |",
231
+ ]
232
+ for r in rows:
233
+ md_lines.append(
234
+ f"| `{r.model}` | `{r.tracker}` | `{r.device}` | **{r.avg_fps:.1f}** | "
235
+ f"{r.avg_inference_ms:.1f} | {r.avg_tracking_ms:.2f} | {r.unique_tracks} | {r.processed_frames} |"
236
+ )
237
+ if split_path:
238
+ md_lines.extend(["", f"- **Split-screen video:** `{split_path}`"])
239
+
240
+ report_md = out_dir / "benchmark_report.md"
241
+ report_md.write_text("\n".join(md_lines) + "\n", encoding="utf-8")
242
+
243
+ payload = {
244
+ "video": str(video_path),
245
+ "legacy_2017": LEGACY_2017_BASELINE,
246
+ "results": [r.to_dict() for r in rows],
247
+ "report_md": str(report_md),
248
+ "split_screen_video": split_path,
249
+ }
250
+ report_json = out_dir / "benchmark_results.json"
251
+ report_json.write_text(json.dumps(payload, indent=2), encoding="utf-8")
252
+ payload["report_json"] = str(report_json)
253
+ return payload
trackflow/cli.py ADDED
@@ -0,0 +1,395 @@
1
+ """Trackflow command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import onnxruntime as ort
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
13
+ from rich.table import Table
14
+
15
+ from trackflow import __version__
16
+ from trackflow.benchmark import (
17
+ LEGACY_2017_BASELINE,
18
+ generate_synthetic_crowd_video,
19
+ run_benchmark_suite,
20
+ )
21
+ from trackflow.inspector import serve_inspector
22
+ from trackflow.models import MODEL_REGISTRY, REID_REGISTRY
23
+ from trackflow.pipeline import TrackflowPipeline
24
+ from trackflow.reid import search_track_cards
25
+
26
+ app = typer.Typer(
27
+ name="trackflow",
28
+ help="Modern real-time people & object tracking — queryable, debuggable, privacy-first.",
29
+ no_args_is_help=True,
30
+ rich_markup_mode="rich",
31
+ )
32
+ console = Console()
33
+
34
+
35
+ @app.command()
36
+ def run(
37
+ source: Annotated[
38
+ str, typer.Argument(help="Video path, image directory, or 'camera' / webcam index.")
39
+ ],
40
+ model: Annotated[
41
+ str, typer.Option("--model", "-m", help="Detector preset, HF repo, or local .onnx path.")
42
+ ] = "rtdetr-v2-r18",
43
+ precision: Annotated[
44
+ str, typer.Option("--precision", help="Model precision: fp32, fp16, or int8.")
45
+ ] = "fp32",
46
+ tracker: Annotated[
47
+ str, typer.Option("--tracker", "-t", help="Tracker: bytetrack or botsort.")
48
+ ] = "bytetrack",
49
+ device: Annotated[
50
+ str, typer.Option("--device", "-d", help="Execution device: auto, coreml, cuda, cpu.")
51
+ ] = "auto",
52
+ threshold: Annotated[
53
+ float, typer.Option("--threshold", help="Detection confidence threshold.")
54
+ ] = 0.45,
55
+ classes: Annotated[
56
+ str, typer.Option("--classes", "-c", help="Comma-separated class names, or 'all'.")
57
+ ] = "person",
58
+ reid: Annotated[
59
+ str, typer.Option("--reid", help="Appearance/VLM backend: none, color, clip, siglip.")
60
+ ] = "none",
61
+ query: Annotated[
62
+ str | None,
63
+ typer.Option(
64
+ "--query", "-q", help='Natural-language prompt-to-track, e.g. "person in red jacket".'
65
+ ),
66
+ ] = None,
67
+ query_threshold: Annotated[
68
+ float,
69
+ typer.Option("--query-threshold", help="Cosine similarity threshold for --query matches."),
70
+ ] = 0.22,
71
+ anonymize: Annotated[
72
+ str,
73
+ typer.Option(
74
+ "--anonymize", help="Privacy mode: none, blur, pixelate, face-blur, skeleton."
75
+ ),
76
+ ] = "none",
77
+ homography: Annotated[
78
+ Path | None, typer.Option("--homography", help="4-point floorplan calibration JSON file.")
79
+ ] = None,
80
+ skip: Annotated[int, typer.Option("--skip", help="Skip N frames between detections.")] = 0,
81
+ max_frames: Annotated[
82
+ int | None, typer.Option("--max-frames", help="Stop after N frames.")
83
+ ] = None,
84
+ output: Annotated[
85
+ Path, typer.Option("--output", "-o", help="Output directory for run artifacts.")
86
+ ] = Path("runs/latest"),
87
+ save_video: Annotated[
88
+ bool, typer.Option("--save-video/--no-video", help="Save annotated MP4 video.")
89
+ ] = True,
90
+ export: Annotated[
91
+ str, typer.Option("--export", help="Comma-separated exports: parquet,jsonl,csv,html.")
92
+ ] = "parquet,jsonl,html",
93
+ display: Annotated[
94
+ bool, typer.Option("--display", help="Show live preview window if OpenCV GUI is available.")
95
+ ] = False,
96
+ ) -> None:
97
+ """Run real-time detection, tracking, optional NL querying, privacy anonymization, and exports."""
98
+ class_list = [c.strip() for c in classes.split(",") if c.strip()]
99
+ export_list = [e.strip() for e in export.split(",") if e.strip()]
100
+
101
+ console.print(
102
+ f"[bold cyan]Trackflow v{__version__}[/] · model=[bold]{model}[/] ({precision}) · "
103
+ f"tracker=[bold]{tracker}[/] · privacy=[bold]{anonymize}[/]"
104
+ )
105
+
106
+ pipeline = TrackflowPipeline(
107
+ model=model,
108
+ precision=precision, # type: ignore[arg-type]
109
+ tracker=tracker,
110
+ device=device,
111
+ threshold=threshold,
112
+ classes=class_list,
113
+ reid=reid, # type: ignore[arg-type]
114
+ query=query,
115
+ query_threshold=query_threshold,
116
+ anonymize=anonymize, # type: ignore[arg-type]
117
+ homography=homography,
118
+ )
119
+
120
+ with Progress(
121
+ SpinnerColumn(),
122
+ TextColumn("[progress.description]{task.description}"),
123
+ BarColumn(),
124
+ TextColumn("{task.completed}/{task.total or '?'} frames"),
125
+ TimeElapsedColumn(),
126
+ console=console,
127
+ ) as progress:
128
+ task_id = progress.add_task("Tracking…", total=None)
129
+
130
+ def _on_progress(done: int, total: int, fps: float) -> None:
131
+ if total > 0:
132
+ progress.update(task_id, total=total)
133
+ progress.update(task_id, completed=done, description=f"Tracking ({fps:.1f} FPS)")
134
+
135
+ summary = pipeline.run(
136
+ source,
137
+ output_dir=output,
138
+ skip=skip,
139
+ max_frames=max_frames,
140
+ save_video=save_video,
141
+ exports=export_list,
142
+ display=display,
143
+ progress_callback=_on_progress,
144
+ )
145
+
146
+ table = Table(title="Run Summary", show_header=False, box=None)
147
+ table.add_row("Provider", f"[cyan]{summary.device}[/]")
148
+ table.add_row(
149
+ "Speed",
150
+ f"[bold green]{summary.avg_fps:.1f} FPS[/] (inf {summary.avg_inference_ms:.1f} ms · trk {summary.avg_tracking_ms:.2f} ms)",
151
+ )
152
+ table.add_row(
153
+ "Unique Tracks",
154
+ f"[bold]{summary.unique_tracks}[/] (recovered: {summary.recovered_tracks}, Re-ID merges: {summary.reid_merges})",
155
+ )
156
+ table.add_row("Frames", f"{summary.processed_frames} processed / {summary.total_frames} read")
157
+ for k, v in summary.output_files.items():
158
+ table.add_row(f"Output ({k})", f"[dim]{v}[/]")
159
+ console.print(table)
160
+
161
+
162
+ @app.command()
163
+ def search(
164
+ run_dir: Annotated[
165
+ Path, typer.Argument(help="Completed Trackflow run directory (or track_cards.json).")
166
+ ],
167
+ query: Annotated[
168
+ str,
169
+ typer.Argument(help='Natural-language search query, e.g. "person wearing blue backpack".'),
170
+ ],
171
+ top_k: Annotated[
172
+ int, typer.Option("--top-k", "-k", help="Maximum Track Cards to return.")
173
+ ] = 10,
174
+ min_score: Annotated[
175
+ float, typer.Option("--min-score", help="Minimum cosine similarity score.")
176
+ ] = -1.0,
177
+ ) -> None:
178
+ """Search saved Track Cards in a completed run using natural language."""
179
+ hits = search_track_cards(run_dir, query, top_k=top_k, min_score=min_score)
180
+ table = Table(title=f'Track Card Search: "{query}"')
181
+ table.add_column("Track ID", style="bold cyan")
182
+ table.add_column("Score", justify="right", style="bold green")
183
+ table.add_column("Class")
184
+ table.add_column("Frames")
185
+ table.add_column("Duration", justify="right")
186
+ table.add_column("Thumbnail", style="dim")
187
+
188
+ for h in hits:
189
+ table.add_row(
190
+ f"#{h['track_id']}",
191
+ f"{h['search_score']:.4f}",
192
+ str(h["class_name"]),
193
+ f"{h['first_frame']}–{h['last_frame']}",
194
+ f"{h['duration_s']:.1f}s",
195
+ str(h.get("thumbnail") or "-"),
196
+ )
197
+ console.print(table)
198
+
199
+
200
+ @app.command()
201
+ def inspect(
202
+ run_dir: Annotated[Path, typer.Argument(help="Completed Trackflow run directory to inspect.")],
203
+ compare: Annotated[
204
+ Path | None,
205
+ typer.Option(
206
+ "--compare", help="Optional second run directory for side-by-side tracker diff."
207
+ ),
208
+ ] = None,
209
+ host: Annotated[str, typer.Option("--host", help="Bind host.")] = "127.0.0.1",
210
+ port: Annotated[int, typer.Option("--port", "-p", help="Local HTTP port.")] = 8765,
211
+ no_browser: Annotated[
212
+ bool, typer.Option("--no-browser", help="Do not automatically open the browser.")
213
+ ] = False,
214
+ ) -> None:
215
+ """Launch the interactive Visual Track Debugger & 4-Point Floorplan Studio."""
216
+ console.print(
217
+ f"[bold green]Trackflow Inspector[/] running at [link=http://{host}:{port}]http://{host}:{port}[/]"
218
+ )
219
+ if compare is not None:
220
+ console.print(f"Comparing [cyan]{run_dir}[/] vs [magenta]{compare}[/]")
221
+ console.print("Press Ctrl+C to stop.")
222
+ serve_inspector(
223
+ run_dir,
224
+ compare_dir=compare,
225
+ host=host,
226
+ port=port,
227
+ open_browser=not no_browser,
228
+ )
229
+
230
+
231
+ @app.command()
232
+ def compare(
233
+ source: Annotated[str, typer.Argument(help="Video path to compare trackers on.")],
234
+ trackers: Annotated[
235
+ str,
236
+ typer.Option("--trackers", help="Two comma-separated trackers, e.g. bytetrack,botsort."),
237
+ ] = "bytetrack,botsort",
238
+ model: Annotated[str, typer.Option("--model", "-m", help="Detector preset.")] = "rtdetr-v2-r18",
239
+ max_frames: Annotated[
240
+ int | None, typer.Option("--max-frames", help="Limit frames for quick comparison.")
241
+ ] = None,
242
+ output: Annotated[
243
+ Path, typer.Option("--output", "-o", help="Parent directory for both runs.")
244
+ ] = Path("runs/compare"),
245
+ open_inspector: Annotated[
246
+ bool, typer.Option("--inspect", help="Open Visual Track Debugger after comparing.")
247
+ ] = False,
248
+ ) -> None:
249
+ """Run two trackers on the same video and compare FPS, track counts, and ID switches side-by-side."""
250
+ names = [t.strip() for t in trackers.split(",") if t.strip()]
251
+ if len(names) < 2:
252
+ raise typer.BadParameter(
253
+ "Provide at least two comma-separated trackers (e.g. bytetrack,botsort)."
254
+ )
255
+
256
+ runs: list[tuple[str, Path, object]] = []
257
+ for tname in names[:2]:
258
+ sub = output / tname
259
+ pipe = TrackflowPipeline(model=model, tracker=tname)
260
+ summary = pipe.run(source, output_dir=sub, max_frames=max_frames, save_video=False)
261
+ runs.append((tname, sub, summary))
262
+
263
+ table = Table(title=f"Tracker Comparison ({model})")
264
+ table.add_column("Metric", style="bold")
265
+ for tname, _, _ in runs:
266
+ table.add_column(tname, justify="right")
267
+
268
+ s0, s1 = runs[0][2], runs[1][2]
269
+ table.add_row("Avg FPS", f"{s0.avg_fps:.1f}", f"{s1.avg_fps:.1f}") # type: ignore[attr-defined]
270
+ table.add_row("Unique Tracks", str(s0.unique_tracks), str(s1.unique_tracks)) # type: ignore[attr-defined]
271
+ table.add_row("Track Recoveries", str(s0.recovered_tracks), str(s1.recovered_tracks)) # type: ignore[attr-defined]
272
+ table.add_row(
273
+ "Observations", str(s0.total_track_observations), str(s1.total_track_observations)
274
+ ) # type: ignore[attr-defined]
275
+ console.print(table)
276
+
277
+ if open_inspector:
278
+ serve_inspector(runs[0][1], compare_dir=runs[1][1])
279
+
280
+
281
+ @app.command()
282
+ def benchmark(
283
+ video: Annotated[
284
+ Path | None,
285
+ typer.Argument(help="Optional video file (generates synthetic crowd video if omitted)."),
286
+ ] = None,
287
+ models: Annotated[
288
+ str, typer.Option("--models", help="Comma-separated models to benchmark.")
289
+ ] = "rtdetr-v2-r18",
290
+ trackers: Annotated[
291
+ str, typer.Option("--trackers", help="Comma-separated trackers to benchmark.")
292
+ ] = "bytetrack,botsort",
293
+ device: Annotated[
294
+ str, typer.Option("--device", help="Device: auto, coreml, cuda, cpu.")
295
+ ] = "auto",
296
+ max_frames: Annotated[int, typer.Option("--max-frames", help="Max frames per run.")] = 90,
297
+ output: Annotated[
298
+ Path, typer.Option("--output", "-o", help="Benchmark output directory.")
299
+ ] = Path("runs/benchmark"),
300
+ split_screen: Annotated[
301
+ bool, typer.Option("--split-screen", help="Generate a 2017 vs. 2026 split-screen MP4.")
302
+ ] = False,
303
+ ) -> None:
304
+ """Run the reproducible 2017 vs. 2026 benchmark suite."""
305
+ output.mkdir(parents=True, exist_ok=True)
306
+ target_video = (
307
+ video
308
+ if video is not None
309
+ else generate_synthetic_crowd_video(output / "synthetic_crowd.mp4")
310
+ )
311
+
312
+ res = run_benchmark_suite(
313
+ target_video,
314
+ output_dir=output,
315
+ models=[m.strip() for m in models.split(",") if m.strip()],
316
+ trackers=[t.strip() for t in trackers.split(",") if t.strip()],
317
+ device=device,
318
+ max_frames=max_frames,
319
+ split_screen=split_screen,
320
+ )
321
+
322
+ table = Table(title="2017 vs. 2026 Benchmark Results")
323
+ table.add_column("Config")
324
+ table.add_column("Provider")
325
+ table.add_column("Avg FPS", justify="right", style="bold green")
326
+ table.add_column("Inf (ms)", justify="right")
327
+ table.add_column("Tracks", justify="right")
328
+
329
+ table.add_row(
330
+ f"[dim]2017 {LEGACY_2017_BASELINE['detector']} + DeepSORT[/]",
331
+ f"[dim]{LEGACY_2017_BASELINE['hardware']}[/]",
332
+ f"[dim]{LEGACY_2017_BASELINE['avg_fps']:.1f}[/]",
333
+ "[dim]~71.4[/]",
334
+ "[dim]—[/]",
335
+ )
336
+ for row in res["results"]:
337
+ table.add_row(
338
+ f"{row['model']} + {row['tracker']}",
339
+ row["device"],
340
+ f"{row['avg_fps']:.1f}",
341
+ f"{row['avg_inference_ms']:.1f}",
342
+ str(row["unique_tracks"]),
343
+ )
344
+ console.print(table)
345
+ console.print(f"Markdown report written to [cyan]{res['report_md']}[/]")
346
+
347
+
348
+ @app.command()
349
+ def models() -> None:
350
+ """List built-in Apache-2.0 detectors and vision-language Re-ID models."""
351
+ det_table = Table(title="Built-in ONNX Object Detectors (Auto-Downloaded from Hugging Face)")
352
+ det_table.add_column("Preset", style="bold cyan")
353
+ det_table.add_column("Architecture")
354
+ det_table.add_column("Size", justify="right")
355
+ det_table.add_column("License", style="green")
356
+ det_table.add_column("Hugging Face Repo", style="dim")
357
+
358
+ for spec in MODEL_REGISTRY.values():
359
+ det_table.add_row(
360
+ spec.name,
361
+ spec.architecture,
362
+ f"{spec.approx_size_mb:.1f} MB",
363
+ spec.license,
364
+ spec.repo_id,
365
+ )
366
+ console.print(det_table)
367
+
368
+ reid_table = Table(title="Built-in Vision-Language Re-ID & Query Models (--reid / --query)")
369
+ reid_table.add_column("Backend", style="bold magenta")
370
+ reid_table.add_column("INT8 Size", justify="right")
371
+ reid_table.add_column("License", style="green")
372
+ reid_table.add_column("Hugging Face Repo", style="dim")
373
+ for rspec in REID_REGISTRY.values():
374
+ reid_table.add_row(
375
+ rspec.name, f"{rspec.approx_size_mb:.0f} MB", rspec.license, rspec.repo_id
376
+ )
377
+ console.print(reid_table)
378
+
379
+
380
+ @app.command()
381
+ def info() -> None:
382
+ """Display system environment, Python version, and ONNX Runtime acceleration providers."""
383
+ table = Table(title="Trackflow Environment Info", show_header=False)
384
+ table.add_row("Trackflow Version", f"[bold cyan]{__version__}[/]")
385
+ table.add_row("Python", platform.python_version())
386
+ table.add_row("Platform", f"{platform.system()} {platform.machine()}")
387
+ table.add_row("ONNX Runtime", ort.__version__)
388
+ table.add_row("Available EPs", ", ".join(ort.get_available_providers()))
389
+ console.print(table)
390
+
391
+
392
+ @app.command()
393
+ def version() -> None:
394
+ """Print the Trackflow version."""
395
+ console.print(__version__)