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/cli.py ADDED
@@ -0,0 +1,631 @@
1
+ """Trackflow command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import platform
8
+ from collections.abc import Iterator
9
+ from contextlib import contextmanager
10
+ from dataclasses import asdict
11
+ from pathlib import Path
12
+ from typing import Annotated, Any
13
+
14
+ import onnxruntime as ort
15
+ import typer
16
+ from rich.console import Console
17
+ from rich.progress import (
18
+ BarColumn,
19
+ MofNCompleteColumn,
20
+ Progress,
21
+ SpinnerColumn,
22
+ TextColumn,
23
+ TimeElapsedColumn,
24
+ )
25
+ from rich.table import Table
26
+
27
+ from trackflow import __version__
28
+ from trackflow.benchmark import (
29
+ LEGACY_2017_BASELINE,
30
+ generate_synthetic_crowd_video,
31
+ run_benchmark_suite,
32
+ )
33
+ from trackflow.detector import (
34
+ _apple_p_cores,
35
+ detect_nvidia_gpu,
36
+ preload_gpu_libraries,
37
+ )
38
+ from trackflow.inspector import serve_inspector
39
+ from trackflow.lines import CountingLine
40
+ from trackflow.models import MODEL_REGISTRY, REID_REGISTRY, VLM_REGISTRY
41
+ from trackflow.pipeline import TrackflowPipeline, fresh_run_dir
42
+ from trackflow.reid import export_search_prompts, search_track_cards
43
+
44
+ app = typer.Typer(
45
+ name="trackflow",
46
+ help="Real-time people and object tracking with ONNX detectors, ByteTrack, BoT-SORT, OC-SORT or BoostTrack, text search, and a local inspector.",
47
+ no_args_is_help=True,
48
+ pretty_exceptions_show_locals=False,
49
+ rich_markup_mode="rich",
50
+ )
51
+ console = Console()
52
+
53
+
54
+ @contextmanager
55
+ def _user_errors() -> Iterator[None]:
56
+ try:
57
+ yield
58
+ except (ValueError, FileExistsError, FileNotFoundError, ImportError, RuntimeError) as exc:
59
+ raise typer.BadParameter(str(exc)) from exc
60
+
61
+
62
+ def _default_device() -> str:
63
+ return os.environ.get("TRACKFLOW_DEFAULT_DEVICE", "").strip() or "auto"
64
+
65
+
66
+ def app_tensorrt() -> None:
67
+ """Entrypoint for the ``trackflow-python-tensorrt`` package (defaults --device to tensorrt)."""
68
+ os.environ.setdefault("TRACKFLOW_DEFAULT_DEVICE", "tensorrt")
69
+ app()
70
+
71
+
72
+ @app.command()
73
+ def run(
74
+ source: Annotated[
75
+ str, typer.Argument(help="Video path, image directory, RTSP/HTTP URL, or camera index.")
76
+ ],
77
+ model: Annotated[
78
+ str,
79
+ typer.Option(
80
+ "--model", "-m", help="Preset, ONNX repo/file, or hf:owner/repo Transformers detector."
81
+ ),
82
+ ] = "rtdetr-v2-r18",
83
+ precision: Annotated[
84
+ str, typer.Option("--precision", help="Model precision: fp32, fp16, or int8.")
85
+ ] = "fp32",
86
+ tracker: Annotated[
87
+ str,
88
+ typer.Option("--tracker", "-t", help="Tracker: bytetrack, botsort, ocsort, or boosttrack."),
89
+ ] = "bytetrack",
90
+ device: Annotated[
91
+ str | None,
92
+ typer.Option(
93
+ "--device",
94
+ "-d",
95
+ help="ONNX: auto, cpu, cuda, coreml, tensorrt. Transformers: auto, cpu, cuda, mps.",
96
+ ),
97
+ ] = None,
98
+ threshold: Annotated[
99
+ float,
100
+ typer.Option("--threshold", min=0.0, max=1.0, help="High-confidence tracking threshold."),
101
+ ] = 0.45,
102
+ classes: Annotated[
103
+ str, typer.Option("--classes", "-c", help="Comma-separated class names, or 'all'.")
104
+ ] = "person",
105
+ reid: Annotated[
106
+ str,
107
+ typer.Option(
108
+ "--reid",
109
+ help="Person Re-ID model for BoT-SORT/BoostTrack appearance and --reid-merge: none, osnet, color.",
110
+ ),
111
+ ] = "none",
112
+ vlm: Annotated[
113
+ str | None,
114
+ typer.Option(
115
+ "--vlm",
116
+ help="Vision-language model for --query and `trackflow search`: none, clip, siglip, "
117
+ "siglip2, embeddinggemma (needs the [transformers] extra) (default: clip when --query "
118
+ "is set, else none).",
119
+ ),
120
+ ] = None,
121
+ reid_merge: Annotated[
122
+ bool,
123
+ typer.Option(
124
+ "--reid-merge/--no-reid-merge",
125
+ help="Give a person who leaves and comes back their earlier ID (needs --reid osnet). "
126
+ "Off by default: look-alikes are left unmerged, but mistakes are still possible.",
127
+ ),
128
+ ] = False,
129
+ query: Annotated[
130
+ str | None,
131
+ typer.Option(
132
+ "--query",
133
+ "-q",
134
+ help='Highlight tracks matching a text description, e.g. "person in red jacket".',
135
+ ),
136
+ ] = None,
137
+ query_threshold: Annotated[
138
+ float | None,
139
+ typer.Option(
140
+ "--query-threshold",
141
+ help="Cosine similarity threshold for --query matches "
142
+ "(default: 0.27 for clip, 0.08 for siglip, 0.09 for siglip2, 0.71 for embeddinggemma).",
143
+ ),
144
+ ] = None,
145
+ anonymize: Annotated[
146
+ str,
147
+ typer.Option(
148
+ "--anonymize",
149
+ help="Privacy mode: none, blur, pixelate, face-blur (top 30% of each person box), skeleton.",
150
+ ),
151
+ ] = "none",
152
+ homography: Annotated[
153
+ Path | None, typer.Option("--homography", help="4-point floorplan calibration JSON file.")
154
+ ] = None,
155
+ line: Annotated[
156
+ list[str] | None,
157
+ typer.Option(
158
+ "--line",
159
+ help="Count tracks crossing a line in image pixels: [name=]x1,y1,x2,y2. "
160
+ "Crossings to the right of the direction from the first point to the second count "
161
+ "as in. Repeat for more lines.",
162
+ ),
163
+ ] = None,
164
+ skip: Annotated[
165
+ int, typer.Option("--skip", min=0, help="Skip N frames between detections.")
166
+ ] = 0,
167
+ max_frames: Annotated[
168
+ int | None, typer.Option("--max-frames", min=1, help="Stop after N source frames.")
169
+ ] = None,
170
+ fps: Annotated[
171
+ float | None,
172
+ typer.Option("--fps", help="Override source frame rate (image sequences default to 25)."),
173
+ ] = None,
174
+ output: Annotated[
175
+ Path | None,
176
+ typer.Option(
177
+ "--output",
178
+ "-o",
179
+ help="Empty output directory. By default a fresh directory under runs/.",
180
+ ),
181
+ ] = None,
182
+ save_video: Annotated[
183
+ bool, typer.Option("--save-video/--no-video", help="Save annotated MP4 video.")
184
+ ] = True,
185
+ export: Annotated[
186
+ str, typer.Option("--export", help="Comma-separated exports: parquet,jsonl,csv,mot,html.")
187
+ ] = "parquet,jsonl,html",
188
+ display: Annotated[
189
+ bool, typer.Option("--display", help="Show live preview window if OpenCV GUI is available.")
190
+ ] = False,
191
+ ) -> None:
192
+ """Run detection and tracking on a video, image directory, or webcam."""
193
+ class_list = [c.strip() for c in classes.split(",") if c.strip()]
194
+ export_list = [e.strip() for e in export.split(",") if e.strip()]
195
+
196
+ console.print(
197
+ f"[bold cyan]Trackflow v{__version__}[/] · model=[bold]{model}[/] ({precision}) · "
198
+ f"tracker=[bold]{tracker}[/] · privacy=[bold]{anonymize}[/]"
199
+ )
200
+
201
+ with _user_errors():
202
+ lines = [CountingLine.parse(spec, f"line-{i}") for i, spec in enumerate(line or [], 1)]
203
+ pipeline = TrackflowPipeline(
204
+ model=model,
205
+ precision=precision, # type: ignore[arg-type]
206
+ tracker=tracker,
207
+ device=device or _default_device(),
208
+ threshold=threshold,
209
+ classes=class_list,
210
+ reid=reid, # type: ignore[arg-type]
211
+ vlm=vlm, # type: ignore[arg-type]
212
+ reid_merge=reid_merge,
213
+ query=query,
214
+ query_threshold=query_threshold,
215
+ anonymize=anonymize, # type: ignore[arg-type]
216
+ homography=homography,
217
+ lines=lines,
218
+ )
219
+
220
+ with Progress(
221
+ SpinnerColumn(),
222
+ TextColumn("[progress.description]{task.description}"),
223
+ BarColumn(),
224
+ MofNCompleteColumn(),
225
+ TimeElapsedColumn(),
226
+ console=console,
227
+ ) as progress:
228
+ task_id = progress.add_task("Tracking…", total=None)
229
+
230
+ def _on_progress(done: int, total: int, fps: float) -> None:
231
+ if total > 0:
232
+ progress.update(task_id, total=total)
233
+ progress.update(task_id, completed=done, description=f"Tracking ({fps:.1f} FPS)")
234
+
235
+ summary = pipeline.run(
236
+ source,
237
+ output_dir=output,
238
+ skip=skip,
239
+ fps=fps,
240
+ max_frames=max_frames,
241
+ save_video=save_video,
242
+ exports=export_list,
243
+ display=display,
244
+ progress_callback=_on_progress,
245
+ )
246
+
247
+ table = Table(title="Run Summary", show_header=False, box=None)
248
+ table.add_row("Provider", f"[cyan]{summary.device}[/]")
249
+ table.add_row(
250
+ "Speed",
251
+ f"[bold green]{summary.avg_fps:.1f} FPS[/] (inf {summary.avg_inference_ms:.1f} ms · trk {summary.avg_tracking_ms:.2f} ms)",
252
+ )
253
+ table.add_row(
254
+ "Unique Tracks",
255
+ f"[bold]{summary.unique_tracks}[/] (recovered: {summary.recovered_tracks}, Re-ID merges: {summary.reid_merges})",
256
+ )
257
+ table.add_row("Frames", f"{summary.processed_frames} processed / {summary.total_frames} read")
258
+ for name, counts in summary.line_counts.items():
259
+ table.add_row(f"Line {name}", f"[bold]{counts['in']}[/] in · [bold]{counts['out']}[/] out")
260
+ for k, v in summary.output_files.items():
261
+ table.add_row(f"Output ({k})", f"[dim]{v}[/]")
262
+ console.print(table)
263
+
264
+
265
+ @app.command()
266
+ def search(
267
+ run_dir: Annotated[
268
+ Path, typer.Argument(help="Completed Trackflow run directory (or track_cards.json).")
269
+ ],
270
+ query: Annotated[
271
+ str,
272
+ typer.Argument(help='Natural-language search query, e.g. "person wearing blue backpack".'),
273
+ ],
274
+ top_k: Annotated[
275
+ int, typer.Option("--top-k", "-k", help="Maximum Track Cards to return.")
276
+ ] = 10,
277
+ min_score: Annotated[
278
+ float, typer.Option("--min-score", help="Minimum cosine similarity score.")
279
+ ] = -1.0,
280
+ export_prompts: Annotated[
281
+ Path | None,
282
+ typer.Option(
283
+ "--export-prompts",
284
+ help="Write top hits as a JSON prompt manifest (time windows + pixel/normalized boxes for SAM 3 or VLMs).",
285
+ ),
286
+ ] = None,
287
+ pad_s: Annotated[
288
+ float,
289
+ typer.Option(
290
+ "--pad-s",
291
+ min=0.0,
292
+ help="Seconds of context to pad before/after each hit window in --export-prompts.",
293
+ ),
294
+ ] = 0.0,
295
+ as_json: Annotated[
296
+ bool, typer.Option("--json", help="Print search results as JSON.")
297
+ ] = False,
298
+ ) -> None:
299
+ """Search saved Track Cards in a completed run using natural language."""
300
+ with _user_errors():
301
+ hits = search_track_cards(run_dir, query, top_k=top_k, min_score=min_score)
302
+ out_path: Path | None = None
303
+ if export_prompts is not None:
304
+ out_path = export_search_prompts(run_dir, query, hits, export_prompts, pad_s=pad_s)
305
+ if as_json:
306
+ payload: dict[str, Any] = {"query": query, "results": hits}
307
+ if out_path is not None:
308
+ payload["exported_prompts"] = str(out_path)
309
+ typer.echo(json.dumps(payload, indent=2))
310
+ return
311
+ table = Table(title=f'Track Card Search: "{query}"')
312
+ table.add_column("Track ID", style="bold cyan")
313
+ table.add_column("Score", justify="right", style="bold green")
314
+ table.add_column("Class")
315
+ table.add_column("Frames")
316
+ table.add_column("Duration", justify="right")
317
+ table.add_column("Thumbnail", style="dim")
318
+
319
+ for h in hits:
320
+ table.add_row(
321
+ f"#{h['track_id']}",
322
+ f"{h['search_score']:.4f}",
323
+ str(h["class_name"]),
324
+ f"{h['first_frame']}–{h['last_frame']}",
325
+ f"{h['duration_s']:.1f}s",
326
+ str(h.get("thumbnail") or "-"),
327
+ )
328
+ console.print(table)
329
+ if export_prompts is not None:
330
+ console.print(f"[dim]Exported {len(hits)} prompt(s) to {out_path}[/]")
331
+
332
+
333
+ @app.command()
334
+ def inspect(
335
+ run_dir: Annotated[
336
+ Path | None,
337
+ typer.Argument(help="Completed run. Defaults to the most recent run under runs/."),
338
+ ] = None,
339
+ compare: Annotated[
340
+ Path | None,
341
+ typer.Option(
342
+ "--compare", help="Optional second run directory for side-by-side tracker diff."
343
+ ),
344
+ ] = None,
345
+ host: Annotated[str, typer.Option("--host", help="Bind host.")] = "127.0.0.1",
346
+ port: Annotated[int, typer.Option("--port", "-p", help="Local HTTP port.")] = 8765,
347
+ no_browser: Annotated[
348
+ bool, typer.Option("--no-browser", help="Do not automatically open the browser.")
349
+ ] = False,
350
+ ) -> None:
351
+ """Open the local web inspector for a completed run (timeline, track cards, floorplan, compare)."""
352
+ if run_dir is None:
353
+ latest = max(
354
+ Path("runs").glob("*/summary.json"), key=lambda p: p.stat().st_mtime_ns, default=None
355
+ )
356
+ if latest is None:
357
+ raise typer.BadParameter("No completed runs under runs/. Supply a run directory.")
358
+ run_dir = latest.parent
359
+ console.print(
360
+ f"[bold green]Trackflow Inspector[/] running at [link=http://{host}:{port}]http://{host}:{port}[/]"
361
+ )
362
+ if compare is not None:
363
+ console.print(f"Comparing [cyan]{run_dir}[/] vs [magenta]{compare}[/]")
364
+ console.print("Press Ctrl+C to stop.")
365
+ serve_inspector(
366
+ run_dir,
367
+ compare_dir=compare,
368
+ host=host,
369
+ port=port,
370
+ open_browser=not no_browser,
371
+ )
372
+
373
+
374
+ @app.command()
375
+ def compare(
376
+ source: Annotated[str, typer.Argument(help="Video path to compare trackers on.")],
377
+ trackers: Annotated[
378
+ str,
379
+ typer.Option("--trackers", help="Two comma-separated trackers, e.g. bytetrack,botsort."),
380
+ ] = "bytetrack,botsort",
381
+ model: Annotated[str, typer.Option("--model", "-m", help="Detector preset.")] = "rtdetr-v2-r18",
382
+ device: Annotated[
383
+ str | None,
384
+ typer.Option("--device", "-d", help="Device: auto, cpu, coreml, cuda, tensorrt."),
385
+ ] = None,
386
+ max_frames: Annotated[
387
+ int | None, typer.Option("--max-frames", help="Limit frames for quick comparison.")
388
+ ] = None,
389
+ output: Annotated[
390
+ Path | None,
391
+ typer.Option(
392
+ "--output",
393
+ "-o",
394
+ help="Parent directory for both runs. By default a fresh directory under runs/.",
395
+ ),
396
+ ] = None,
397
+ open_inspector: Annotated[
398
+ bool, typer.Option("--inspect", help="Open the local inspector after comparing.")
399
+ ] = False,
400
+ ) -> None:
401
+ """Run two trackers on the same video and compare FPS, track counts, and recoveries."""
402
+ names = [t.strip() for t in trackers.split(",") if t.strip()]
403
+ if len(names) < 2:
404
+ raise typer.BadParameter(
405
+ "Provide at least two comma-separated trackers (e.g. bytetrack,botsort)."
406
+ )
407
+
408
+ runs: list[tuple[str, Path, object]] = []
409
+ resolved_device = device or _default_device()
410
+ with _user_errors():
411
+ parent = output if output is not None else fresh_run_dir("compare")
412
+ for tname in names[:2]:
413
+ sub = parent / tname
414
+ pipe = TrackflowPipeline(model=model, tracker=tname, device=resolved_device)
415
+ summary = pipe.run(source, output_dir=sub, max_frames=max_frames, save_video=False)
416
+ runs.append((tname, sub, summary))
417
+
418
+ table = Table(title=f"Tracker Comparison ({model})")
419
+ table.add_column("Metric", style="bold")
420
+ for tname, _, _ in runs:
421
+ table.add_column(tname, justify="right")
422
+
423
+ s0, s1 = runs[0][2], runs[1][2]
424
+ table.add_row("Avg FPS", f"{s0.avg_fps:.1f}", f"{s1.avg_fps:.1f}") # type: ignore[attr-defined]
425
+ table.add_row("Unique Tracks", str(s0.unique_tracks), str(s1.unique_tracks)) # type: ignore[attr-defined]
426
+ table.add_row("Track Recoveries", str(s0.recovered_tracks), str(s1.recovered_tracks)) # type: ignore[attr-defined]
427
+ table.add_row(
428
+ "Observations", str(s0.total_track_observations), str(s1.total_track_observations)
429
+ ) # type: ignore[attr-defined]
430
+ console.print(table)
431
+
432
+ if open_inspector:
433
+ serve_inspector(runs[0][1], compare_dir=runs[1][1])
434
+
435
+
436
+ @app.command()
437
+ def benchmark(
438
+ video: Annotated[
439
+ Path | None,
440
+ typer.Argument(help="Optional video file (generates synthetic crowd video if omitted)."),
441
+ ] = None,
442
+ models: Annotated[
443
+ str, typer.Option("--models", help="Comma-separated models to benchmark.")
444
+ ] = "rtdetr-v2-r18",
445
+ trackers: Annotated[
446
+ str, typer.Option("--trackers", help="Comma-separated trackers to benchmark.")
447
+ ] = "bytetrack,botsort",
448
+ device: Annotated[
449
+ str | None, typer.Option("--device", help="Device: auto, coreml, cuda, tensorrt, cpu.")
450
+ ] = None,
451
+ max_frames: Annotated[int, typer.Option("--max-frames", help="Max frames per run.")] = 90,
452
+ output: Annotated[
453
+ Path | None,
454
+ typer.Option(
455
+ "--output",
456
+ "-o",
457
+ help="Benchmark output directory. By default a fresh directory under runs/.",
458
+ ),
459
+ ] = None,
460
+ split_screen: Annotated[
461
+ bool, typer.Option("--split-screen", help="Generate a 2017 vs. 2026 split-screen MP4.")
462
+ ] = False,
463
+ ) -> None:
464
+ """Benchmark detector and tracker combinations on a video."""
465
+ with _user_errors():
466
+ output = output if output is not None else fresh_run_dir("benchmark")
467
+ output.mkdir(parents=True, exist_ok=True)
468
+ target_video = (
469
+ video
470
+ if video is not None
471
+ else generate_synthetic_crowd_video(output / "synthetic_crowd.mp4")
472
+ )
473
+
474
+ res = run_benchmark_suite(
475
+ target_video,
476
+ output_dir=output,
477
+ models=[m.strip() for m in models.split(",") if m.strip()],
478
+ trackers=[t.strip() for t in trackers.split(",") if t.strip()],
479
+ device=device or _default_device(),
480
+ max_frames=max_frames,
481
+ split_screen=split_screen,
482
+ )
483
+
484
+ table = Table(title="2017 vs. 2026 Benchmark Results")
485
+ table.add_column("Config")
486
+ table.add_column("Provider")
487
+ table.add_column("Avg FPS", justify="right", style="bold green")
488
+ table.add_column("Inf (ms)", justify="right")
489
+ table.add_column("Tracks", justify="right")
490
+
491
+ table.add_row(
492
+ f"[dim]2017 {LEGACY_2017_BASELINE['detector']} + DeepSORT[/]",
493
+ f"[dim]{LEGACY_2017_BASELINE['hardware']}[/]",
494
+ f"[dim]{LEGACY_2017_BASELINE['avg_fps']:.1f}[/]",
495
+ "[dim]—[/]",
496
+ "[dim]—[/]",
497
+ )
498
+ for row in res["results"]:
499
+ table.add_row(
500
+ f"{row['model']} + {row['tracker']}",
501
+ row["device"],
502
+ f"{row['avg_fps']:.1f}",
503
+ f"{row['avg_inference_ms']:.1f}",
504
+ str(row["unique_tracks"]),
505
+ )
506
+ console.print(table)
507
+ console.print(f"Markdown report written to [cyan]{res['report_md']}[/]")
508
+
509
+
510
+ @app.command()
511
+ def models(
512
+ as_json: Annotated[
513
+ bool, typer.Option("--json", help="Print the model catalog as JSON.")
514
+ ] = False,
515
+ ) -> None:
516
+ """List built-in detectors, person Re-ID models, and vision-language models."""
517
+ if as_json:
518
+ typer.echo(
519
+ json.dumps(
520
+ {
521
+ "detectors": [
522
+ {**asdict(s), "precisions": s.precisions} for s in MODEL_REGISTRY.values()
523
+ ],
524
+ "reid": [asdict(s) for s in REID_REGISTRY.values()],
525
+ "vlm": [asdict(s) for s in VLM_REGISTRY.values()],
526
+ },
527
+ indent=2,
528
+ )
529
+ )
530
+ return
531
+ det_table = Table(title="Object Detectors")
532
+ det_table.add_column("Preset", style="bold cyan")
533
+ det_table.add_column("Architecture")
534
+ det_table.add_column("Runtime")
535
+ det_table.add_column("Size", justify="right")
536
+ det_table.add_column("License", style="green")
537
+ det_table.add_column("Hugging Face Repo", style="dim")
538
+
539
+ for spec in MODEL_REGISTRY.values():
540
+ det_table.add_row(
541
+ spec.name,
542
+ spec.architecture,
543
+ spec.backend,
544
+ f"{spec.approx_size_mb:.1f} MB",
545
+ spec.license,
546
+ spec.repo_id,
547
+ )
548
+ console.print(det_table)
549
+
550
+ reid_table = Table(
551
+ title="Person Re-ID Models (--reid: BoT-SORT/BoostTrack appearance, --reid-merge)"
552
+ )
553
+ reid_table.add_column("Backend", style="bold magenta")
554
+ reid_table.add_column("Size", justify="right")
555
+ reid_table.add_column("License", style="green")
556
+ reid_table.add_column("Hugging Face Repo", style="dim")
557
+ for rspec in REID_REGISTRY.values():
558
+ reid_table.add_row(
559
+ rspec.name, f"{rspec.approx_size_mb:.1f} MB", rspec.license, rspec.repo_id
560
+ )
561
+ reid_table.add_row("color", "0 MB", "-", "built-in HSV histogram (weak, no download)")
562
+ console.print(reid_table)
563
+
564
+ vlm_table = Table(title="Vision-Language Models (--vlm: --query scoring & `trackflow search`)")
565
+ vlm_table.add_column("Backend", style="bold magenta")
566
+ vlm_table.add_column("Download", justify="right")
567
+ vlm_table.add_column("License", style="green")
568
+ vlm_table.add_column("Hugging Face Repo", style="dim")
569
+ for vspec in VLM_REGISTRY.values():
570
+ vlm_table.add_row(
571
+ vspec.name, f"{vspec.approx_size_mb:.0f} MB", vspec.license, vspec.repo_id
572
+ )
573
+ console.print(vlm_table)
574
+
575
+
576
+ @app.command()
577
+ def info(
578
+ as_json: Annotated[
579
+ bool, typer.Option("--json", help="Print environment details as JSON.")
580
+ ] = False,
581
+ ) -> None:
582
+ """Display system environment, Python version, and ONNX Runtime acceleration providers."""
583
+ providers = ort.get_available_providers()
584
+ trt_libs = list(preload_gpu_libraries())
585
+ nvidia_gpu = detect_nvidia_gpu()
586
+ apple_p_cores = _apple_p_cores()
587
+ recommended_command: str | None = None
588
+ if nvidia_gpu and "CUDAExecutionProvider" not in providers:
589
+ recommended_command = (
590
+ "uvx trackflow-python-cuda run <video> # or uvx trackflow-python-tensorrt run <video>"
591
+ )
592
+ if as_json:
593
+ typer.echo(
594
+ json.dumps(
595
+ {
596
+ "version": __version__,
597
+ "python": platform.python_version(),
598
+ "platform": f"{platform.system()} {platform.machine()}",
599
+ "onnxruntime": ort.__version__,
600
+ "available_providers": providers,
601
+ "nvidia_gpu": nvidia_gpu,
602
+ "apple_p_cores": apple_p_cores,
603
+ "tensorrt_libs": trt_libs,
604
+ "default_device": _default_device(),
605
+ "recommended_command": recommended_command,
606
+ },
607
+ indent=2,
608
+ )
609
+ )
610
+ return
611
+ table = Table(title="Trackflow Environment Info", show_header=False)
612
+ table.add_row("Trackflow Version", f"[bold cyan]{__version__}[/]")
613
+ table.add_row("Python", platform.python_version())
614
+ table.add_row("Platform", f"{platform.system()} {platform.machine()}")
615
+ if apple_p_cores is not None:
616
+ table.add_row("Apple Silicon P-cores", str(apple_p_cores))
617
+ if nvidia_gpu is not None:
618
+ table.add_row("NVIDIA GPU", nvidia_gpu)
619
+ table.add_row("ONNX Runtime", ort.__version__)
620
+ table.add_row("Available EPs", ", ".join(providers))
621
+ if trt_libs:
622
+ table.add_row("TensorRT Libs", ", ".join(trt_libs))
623
+ if recommended_command is not None:
624
+ table.add_row("GPU Acceleration", f"[bold yellow]{recommended_command}[/]")
625
+ console.print(table)
626
+
627
+
628
+ @app.command()
629
+ def version() -> None:
630
+ """Print the Trackflow version."""
631
+ console.print(__version__)