trackflow-python-tensorrt 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/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """Trackflow — Modern real-time people & object tracking toolkit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from trackflow.boosttrack import BoostTracker
6
+ from trackflow.detector import Detector, OnnxDetrDetector, create_detector
7
+ from trackflow.homography import DwellZone, FloorplanHomography
8
+ from trackflow.lines import CountingLine
9
+ from trackflow.models import MODEL_REGISTRY, REID_REGISTRY, VLM_REGISTRY, ModelSpec
10
+ from trackflow.ocsort import OcSortTracker
11
+ from trackflow.pipeline import TrackflowPipeline
12
+ from trackflow.privacy import PrivacyAnonymizer
13
+ from trackflow.reid import ReidEmbedder, TrackCardIndex, VlmEmbedder
14
+ from trackflow.tracker import (
15
+ TRACKER_NAMES,
16
+ BotSortTracker,
17
+ ByteTracker,
18
+ Tracker,
19
+ create_tracker,
20
+ )
21
+ from trackflow.types import (
22
+ Detection,
23
+ FrameResult,
24
+ HomographyPoint,
25
+ RunSummary,
26
+ Track,
27
+ TrackCard,
28
+ )
29
+
30
+ __version__ = "0.6.1"
31
+
32
+ __all__ = [
33
+ "__version__",
34
+ "BoostTracker",
35
+ "BotSortTracker",
36
+ "ByteTracker",
37
+ "CountingLine",
38
+ "Detection",
39
+ "Detector",
40
+ "DwellZone",
41
+ "FloorplanHomography",
42
+ "FrameResult",
43
+ "HomographyPoint",
44
+ "MODEL_REGISTRY",
45
+ "ModelSpec",
46
+ "OcSortTracker",
47
+ "OnnxDetrDetector",
48
+ "PrivacyAnonymizer",
49
+ "REID_REGISTRY",
50
+ "ReidEmbedder",
51
+ "RunSummary",
52
+ "Track",
53
+ "TrackCard",
54
+ "TRACKER_NAMES",
55
+ "TrackCardIndex",
56
+ "TrackflowPipeline",
57
+ "Tracker",
58
+ "VLM_REGISTRY",
59
+ "VlmEmbedder",
60
+ "create_detector",
61
+ "create_tracker",
62
+ ]
trackflow/benchmark.py ADDED
@@ -0,0 +1,266 @@
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
+ from urllib.parse import quote
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ from trackflow.pipeline import TrackflowPipeline, fresh_run_dir
16
+ from trackflow.types import RunSummary
17
+
18
+ # Historical baseline recorded in the original July 2017 README (preserved on `legacy-2017`)
19
+ LEGACY_2017_BASELINE: dict[str, Any] = {
20
+ "era": "2017 (Tracking-with-darkflow)",
21
+ "detector": "YOLOv2 (darkflow / TF 1.0)",
22
+ "tracker": "DeepSORT (manual TF frozen graph)",
23
+ "hardware": "NVIDIA GTX 1080 (1024x1280)",
24
+ "avg_fps": 14.0,
25
+ "avg_fps_with_mog2": 10.5,
26
+ "setup_steps": 6,
27
+ "license": "GPL-3.0",
28
+ "features": "Boxes + IDs + CSV only",
29
+ }
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class BenchmarkRow:
34
+ model: str
35
+ tracker: str
36
+ device: str
37
+ avg_fps: float
38
+ avg_inference_ms: float
39
+ avg_tracking_ms: float
40
+ unique_tracks: int
41
+ processed_frames: int
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ return {
45
+ "model": self.model,
46
+ "tracker": self.tracker,
47
+ "device": self.device,
48
+ "avg_fps": round(self.avg_fps, 2),
49
+ "avg_inference_ms": round(self.avg_inference_ms, 2),
50
+ "avg_tracking_ms": round(self.avg_tracking_ms, 2),
51
+ "unique_tracks": self.unique_tracks,
52
+ "processed_frames": self.processed_frames,
53
+ }
54
+
55
+
56
+ def generate_synthetic_crowd_video(
57
+ out_path: str | Path,
58
+ *,
59
+ width: int = 640,
60
+ height: int = 360,
61
+ num_frames: int = 90,
62
+ fps: float = 30.0,
63
+ ) -> Path:
64
+ """Create a deterministic synthetic multi-pedestrian test video for offline/CI benchmarks."""
65
+ path = Path(out_path)
66
+ path.parent.mkdir(parents=True, exist_ok=True)
67
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
68
+ writer = cv2.VideoWriter(str(path), fourcc, fps, (width, height))
69
+
70
+ if not writer.isOpened():
71
+ raise RuntimeError(f"Could not open video writer at {path}")
72
+
73
+ actors = [
74
+ {"x": 60.0, "y": 140.0, "vx": 4.2, "vy": 0.4, "color": (60, 60, 220)},
75
+ {"x": 540.0, "y": 150.0, "vx": -3.8, "vy": 0.3, "color": (220, 140, 50)},
76
+ {"x": 180.0, "y": 120.0, "vx": 2.1, "vy": 0.8, "color": (70, 200, 110)},
77
+ {"x": 420.0, "y": 180.0, "vx": -2.5, "vy": -0.3, "color": (200, 90, 200)},
78
+ ]
79
+
80
+ try:
81
+ for _ in range(num_frames):
82
+ frame = np.full((height, width, 3), (38, 42, 52), dtype=np.uint8)
83
+ cv2.rectangle(frame, (0, int(height * 0.52)), (width, height), (54, 58, 68), -1)
84
+ for a in actors:
85
+ cx, cy = int(a["x"]), int(a["y"])
86
+ # Simple stylized pedestrian silhouette
87
+ cv2.circle(frame, (cx, cy - 36), 11, (205, 185, 170), -1)
88
+ cv2.rectangle(frame, (cx - 14, cy - 24), (cx + 14, cy + 20), a["color"], -1)
89
+ cv2.rectangle(frame, (cx - 12, cy + 20), (cx - 2, cy + 56), (40, 45, 60), -1)
90
+ cv2.rectangle(frame, (cx + 2, cy + 20), (cx + 12, cy + 56), (40, 45, 60), -1)
91
+ a["x"] = 20 + (a["x"] - 20 + a["vx"]) % (width - 40)
92
+ a["y"] = float(np.clip(a["y"] + a["vy"], 90, height - 80))
93
+ writer.write(frame)
94
+ finally:
95
+ writer.release()
96
+
97
+ return path
98
+
99
+
100
+ def render_split_screen_2017_vs_2026(
101
+ modern_video_path: str | Path,
102
+ out_path: str | Path,
103
+ *,
104
+ modern_summary: RunSummary,
105
+ ) -> Path:
106
+ """Create a side-by-side comparison video against the 2017 baseline."""
107
+ src = Path(modern_video_path)
108
+ out = Path(out_path)
109
+ cap = cv2.VideoCapture(str(src))
110
+ if not cap.isOpened():
111
+ raise RuntimeError(f"Could not open annotated video: {src}")
112
+
113
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
114
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
115
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
116
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
117
+ writer = cv2.VideoWriter(str(out), fourcc, fps, (w * 2, h))
118
+
119
+ if not writer.isOpened():
120
+ cap.release()
121
+ raise RuntimeError(f"Could not open video writer at {out}")
122
+
123
+ # The 2017 README supplies a measurement, not frame-level predictions for this input.
124
+ left_frame = np.full((h, w, 3), (24, 24, 30), dtype=np.uint8)
125
+ lines = [
126
+ "2017 historical measurement",
127
+ "YOLOv2 + DeepSORT",
128
+ "14 FPS on NVIDIA GTX 1080",
129
+ "1280 x 1024, original README",
130
+ ]
131
+ scale = max(0.2, min(w / 600, h / 400, 1.0))
132
+ for i, line in enumerate(lines):
133
+ cv2.putText(
134
+ left_frame,
135
+ line,
136
+ (int(12 * scale), int((40 + i * 38) * scale)),
137
+ cv2.FONT_HERSHEY_SIMPLEX,
138
+ 0.78 * scale,
139
+ (220, 220, 225),
140
+ 1,
141
+ cv2.LINE_AA,
142
+ )
143
+ try:
144
+ while True:
145
+ ok, right_frame = cap.read()
146
+ if not ok:
147
+ break
148
+
149
+ cv2.rectangle(right_frame, (0, 0), (w, 42), (10, 38, 32), -1)
150
+ cv2.putText(
151
+ right_frame,
152
+ f"2026: Trackflow ({modern_summary.model} + {modern_summary.tracker} · {modern_summary.avg_fps:.1f} FPS · 1 cmd)",
153
+ (10, 27),
154
+ cv2.FONT_HERSHEY_SIMPLEX,
155
+ 0.45,
156
+ (140, 255, 200),
157
+ 1,
158
+ cv2.LINE_AA,
159
+ )
160
+
161
+ combined = np.hstack([left_frame, right_frame])
162
+ cv2.line(combined, (w, 0), (w, h), (56, 189, 248), 2)
163
+ writer.write(combined)
164
+ finally:
165
+ cap.release()
166
+ writer.release()
167
+
168
+ return out
169
+
170
+
171
+ def run_benchmark_suite(
172
+ video_path: str | Path,
173
+ *,
174
+ output_dir: str | Path | None = None,
175
+ models: Sequence[str] = ("rtdetr-v2-r18",),
176
+ trackers: Sequence[str] = ("bytetrack", "botsort"),
177
+ device: str = "auto",
178
+ max_frames: int | None = 120,
179
+ split_screen: bool = False,
180
+ detector_factory: Any | None = None,
181
+ ) -> dict[str, Any]:
182
+ """Run reproducible Trackflow benchmarks and write JSON + Markdown 2017 vs. 2026 report.
183
+
184
+ Without ``output_dir``, results go to a fresh ``runs/benchmark-N`` directory.
185
+ """
186
+ out_dir = fresh_run_dir("benchmark") if output_dir is None else Path(output_dir)
187
+ out_dir.mkdir(parents=True, exist_ok=True)
188
+
189
+ rows: list[BenchmarkRow] = []
190
+ summaries: list[RunSummary] = []
191
+
192
+ for model_name in models:
193
+ for tracker_name in trackers:
194
+ sub_dir = out_dir / f"{quote(str(model_name), safe='')}_{quote(tracker_name, safe='')}"
195
+ det = detector_factory(model_name) if detector_factory is not None else None
196
+ pipe = TrackflowPipeline(
197
+ model=model_name,
198
+ tracker=tracker_name,
199
+ device=device,
200
+ detector=det,
201
+ )
202
+ summary = pipe.run(
203
+ str(video_path),
204
+ output_dir=sub_dir,
205
+ max_frames=max_frames,
206
+ save_video=split_screen,
207
+ exports=("parquet", "jsonl"),
208
+ )
209
+ summaries.append(summary)
210
+ rows.append(
211
+ BenchmarkRow(
212
+ model=model_name,
213
+ tracker=tracker_name,
214
+ device=summary.device,
215
+ avg_fps=summary.avg_fps,
216
+ avg_inference_ms=summary.avg_inference_ms,
217
+ avg_tracking_ms=summary.avg_tracking_ms,
218
+ unique_tracks=summary.unique_tracks,
219
+ processed_frames=summary.processed_frames,
220
+ )
221
+ )
222
+
223
+ split_path: str | None = None
224
+ if split_screen and summaries and "video" in summaries[0].output_files:
225
+ split_file = render_split_screen_2017_vs_2026(
226
+ summaries[0].output_files["video"],
227
+ out_dir / "split_2017_vs_2026.mp4",
228
+ modern_summary=summaries[0],
229
+ )
230
+ split_path = str(split_file)
231
+
232
+ md_lines = [
233
+ "# Trackflow Benchmark Report — 2017 vs. 2026",
234
+ "",
235
+ "## Historical 2017 Baseline (`legacy-2017`)",
236
+ f"- **Stack:** {LEGACY_2017_BASELINE['detector']} + {LEGACY_2017_BASELINE['tracker']}",
237
+ f"- **Recorded Speed:** {LEGACY_2017_BASELINE['avg_fps']} FPS on {LEGACY_2017_BASELINE['hardware']} ({LEGACY_2017_BASELINE['avg_fps_with_mog2']} FPS w/ MOG2)",
238
+ f"- **Setup Friction:** {LEGACY_2017_BASELINE['setup_steps']} manual steps (3 git submodules, Cython build, Google Drive weights)",
239
+ "",
240
+ "## 2026 Trackflow Results",
241
+ "",
242
+ "| Model | Tracker | Provider | Avg FPS | Inference (ms) | Tracking (ms) | Unique Tracks | Frames |",
243
+ "| :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: |",
244
+ ]
245
+ for r in rows:
246
+ md_lines.append(
247
+ f"| `{r.model}` | `{r.tracker}` | `{r.device}` | **{r.avg_fps:.1f}** | "
248
+ f"{r.avg_inference_ms:.1f} | {r.avg_tracking_ms:.2f} | {r.unique_tracks} | {r.processed_frames} |"
249
+ )
250
+ if split_path:
251
+ md_lines.extend(["", f"- **Split-screen video:** `{split_path}`"])
252
+
253
+ report_md = out_dir / "benchmark_report.md"
254
+ report_md.write_text("\n".join(md_lines) + "\n", encoding="utf-8")
255
+
256
+ payload = {
257
+ "video": str(video_path),
258
+ "legacy_2017": LEGACY_2017_BASELINE,
259
+ "results": [r.to_dict() for r in rows],
260
+ "report_md": str(report_md),
261
+ "split_screen_video": split_path,
262
+ }
263
+ report_json = out_dir / "benchmark_results.json"
264
+ report_json.write_text(json.dumps(payload, indent=2), encoding="utf-8")
265
+ payload["report_json"] = str(report_json)
266
+ return payload