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/sinks.py ADDED
@@ -0,0 +1,308 @@
1
+ """Structured data sinks: Parquet, JSONL, CSV, Annotated MP4, and standalone HTML run report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import html
7
+ import json
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import cv2
13
+ import numpy as np
14
+ import pyarrow as pa
15
+ import pyarrow.parquet as pq
16
+
17
+ from trackflow.privacy import _track_color
18
+ from trackflow.types import FrameResult, RunSummary, Track, TrackCard
19
+
20
+ PARQUET_SCHEMA = pa.schema(
21
+ [
22
+ ("frame_idx", pa.int64()),
23
+ ("timestamp_s", pa.float64()),
24
+ ("track_id", pa.int64()),
25
+ ("class_id", pa.int64()),
26
+ ("class_name", pa.string()),
27
+ ("confidence", pa.float64()),
28
+ ("x1", pa.float64()),
29
+ ("y1", pa.float64()),
30
+ ("x2", pa.float64()),
31
+ ("y2", pa.float64()),
32
+ ("width", pa.float64()),
33
+ ("height", pa.float64()),
34
+ ("age", pa.int64()),
35
+ ("hits", pa.int64()),
36
+ ("recovered", pa.bool_()),
37
+ ("query_score", pa.float64()),
38
+ ("query_match", pa.bool_()),
39
+ ("world_x", pa.float64()),
40
+ ("world_y", pa.float64()),
41
+ ("zone", pa.string()),
42
+ ]
43
+ )
44
+
45
+
46
+ def write_parquet(records: list[dict[str, Any]], path: Path) -> Path:
47
+ """Write track observations to Apache Parquet (directly queryable by DuckDB / Polars / Pandas)."""
48
+ if records:
49
+ table = pa.Table.from_pylist(records, schema=PARQUET_SCHEMA)
50
+ else:
51
+ empty = {field.name: [] for field in PARQUET_SCHEMA}
52
+ table = pa.Table.from_pydict(empty, schema=PARQUET_SCHEMA)
53
+ pq.write_table(table, str(path), compression="snappy")
54
+ return path
55
+
56
+
57
+ def write_jsonl(records: list[dict[str, Any]], path: Path) -> Path:
58
+ """Write line-delimited JSON track observations."""
59
+ with path.open("w", encoding="utf-8") as fh:
60
+ for rec in records:
61
+ fh.write(json.dumps(rec) + "\n")
62
+ return path
63
+
64
+
65
+ def write_csv(records: list[dict[str, Any]], path: Path) -> Path:
66
+ """Write CSV track observations."""
67
+ fieldnames = [f.name for f in PARQUET_SCHEMA]
68
+ with path.open("w", newline="", encoding="utf-8") as fh:
69
+ writer = csv.DictWriter(fh, fieldnames=fieldnames)
70
+ writer.writeheader()
71
+ for rec in records:
72
+ writer.writerow(rec)
73
+ return path
74
+
75
+
76
+ def draw_tracks(
77
+ frame_bgr: np.ndarray,
78
+ tracks: list[Track],
79
+ *,
80
+ trails: dict[int, list[tuple[int, int]]],
81
+ fps: float | None = None,
82
+ query: str | None = None,
83
+ anonymize_mode: str = "none",
84
+ ) -> np.ndarray:
85
+ """Draw boxes, IDs, motion trails, query highlight badges, and HUD onto a frame."""
86
+ canvas = frame_bgr.copy()
87
+
88
+ for tr in tracks:
89
+ x1, y1, x2, y2 = [int(round(v)) for v in tr.bbox]
90
+ base_color = _track_color(tr.track_id)
91
+ is_match = tr.query_match
92
+
93
+ color = base_color if is_match else (100, 105, 115)
94
+ thickness = 3 if (query and is_match) else (2 if is_match else 1)
95
+
96
+ # Draw motion trail
97
+ trail = trails.get(tr.track_id, [])
98
+ if len(trail) >= 2:
99
+ pts = np.array(trail[-32:], dtype=np.int32)
100
+ cv2.polylines(canvas, [pts], False, color, 2 if is_match else 1, cv2.LINE_AA)
101
+
102
+ # Bounding box
103
+ cv2.rectangle(canvas, (x1, y1), (x2, y2), color, thickness, cv2.LINE_AA)
104
+
105
+ # Label pill
106
+ parts = [f"#{tr.track_id}", tr.class_name, f"{tr.confidence:.2f}"]
107
+ if tr.query_score is not None:
108
+ parts.append(f"q:{tr.query_score:.2f}")
109
+ if tr.zone:
110
+ parts.append(f"[{tr.zone}]")
111
+ label = " ".join(parts)
112
+
113
+ (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
114
+ ly = max(th + 8, y1)
115
+ cv2.rectangle(canvas, (x1, ly - th - 8), (x1 + tw + 10, ly), color, -1)
116
+ cv2.putText(
117
+ canvas,
118
+ label,
119
+ (x1 + 5, ly - 5),
120
+ cv2.FONT_HERSHEY_SIMPLEX,
121
+ 0.5,
122
+ (15, 18, 24),
123
+ 1,
124
+ cv2.LINE_AA,
125
+ )
126
+
127
+ # Top-left HUD
128
+ hud_items = [f"Trackflow | {len(tracks)} active"]
129
+ if fps is not None:
130
+ hud_items.append(f"{fps:.1f} FPS")
131
+ if query:
132
+ hud_items.append(f'query: "{query}"')
133
+ if anonymize_mode != "none":
134
+ hud_items.append(f"privacy: {anonymize_mode}")
135
+ hud_text = " • ".join(hud_items)
136
+ (hw, hh), _ = cv2.getTextSize(hud_text, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 1)
137
+ cv2.rectangle(canvas, (10, 10), (24 + hw, 24 + hh), (15, 18, 26), -1)
138
+ cv2.putText(
139
+ canvas,
140
+ hud_text,
141
+ (17, 17 + hh),
142
+ cv2.FONT_HERSHEY_SIMPLEX,
143
+ 0.55,
144
+ (235, 242, 250),
145
+ 1,
146
+ cv2.LINE_AA,
147
+ )
148
+ return canvas
149
+
150
+
151
+ def write_html_report(
152
+ summary: RunSummary,
153
+ frame_results: list[FrameResult],
154
+ cards: list[TrackCard],
155
+ path: Path,
156
+ ) -> Path:
157
+ """Generate a self-contained HTML run report with inline SVG charts & Track Card gallery."""
158
+ counts = [len(fr.tracks) for fr in frame_results]
159
+ max_count = max(counts, default=1) or 1
160
+
161
+ # Build inline SVG sparkline for active tracks per frame
162
+ svg_w, svg_h = 720, 150
163
+ if len(counts) >= 2:
164
+ pts = [
165
+ f"{(i / (len(counts) - 1)) * svg_w:.1f},{svg_h - 12 - (c / max_count) * (svg_h - 24):.1f}"
166
+ for i, c in enumerate(counts)
167
+ ]
168
+ polyline = " ".join(pts)
169
+ area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
170
+ else:
171
+ polyline = f"0,{svg_h - 12} {svg_w},{svg_h - 12}"
172
+ area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
173
+
174
+ # Diagnostic events summary
175
+ event_counts: dict[str, int] = defaultdict(int)
176
+ id_switch_rows: list[str] = []
177
+ for fr in frame_results:
178
+ for ev in fr.events:
179
+ et = ev.get("type", "event")
180
+ event_counts[et] += 1
181
+ if et in ("possible_id_switch", "reid_cross_exit_merge", "track_recovered"):
182
+ id_switch_rows.append(
183
+ f"<tr><td>{fr.frame_idx}</td><td>{fr.timestamp_s:.2f}s</td>"
184
+ f"<td><code>{html.escape(et)}</code></td>"
185
+ f"<td><code>{html.escape(json.dumps(ev))}</code></td></tr>"
186
+ )
187
+
188
+ card_html: list[str] = []
189
+ for c in cards[:60]:
190
+ q_badge = (
191
+ f'<span class="badge {"match" if c.query_match else "muted"}">query {c.query_score:.2f}</span>'
192
+ if c.query_score is not None
193
+ else ""
194
+ )
195
+ merged_badge = (
196
+ f'<span class="badge accent">Re-ID merged {len(c.merged_track_ids)}x</span>'
197
+ if c.merged_track_ids
198
+ else ""
199
+ )
200
+ thumb = (
201
+ f'<img src="{html.escape(c.thumbnail_relpath)}" alt="Track #{c.track_id}" />'
202
+ if c.thumbnail_relpath
203
+ else '<div class="thumb-placeholder">No Crop</div>'
204
+ )
205
+ card_html.append(
206
+ f"""
207
+ <div class="card">
208
+ <div class="thumb">{thumb}</div>
209
+ <div class="card-body">
210
+ <div class="card-head">
211
+ <strong>Track #{c.track_id}</strong>
212
+ <span class="badge">{html.escape(c.class_name)}</span>
213
+ {q_badge}{merged_badge}
214
+ </div>
215
+ <div class="meta">
216
+ Frames {c.first_frame}–{c.last_frame} ({c.duration_s:.1f}s · {c.frame_count} obs)<br/>
217
+ Peak conf: {c.best_confidence:.2f}
218
+ {f"<br/>Zones: {', '.join(c.zones_visited)}" if c.zones_visited else ""}
219
+ </div>
220
+ </div>
221
+ </div>
222
+ """
223
+ )
224
+
225
+ doc = f"""<!DOCTYPE html>
226
+ <html lang="en">
227
+ <head>
228
+ <meta charset="utf-8" />
229
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
230
+ <title>Trackflow Run Report — {html.escape(Path(summary.source).name)}</title>
231
+ <style>
232
+ :root {{
233
+ --bg: #0b1020; --surface: #131b31; --border: #24304f;
234
+ --text: #e6eefc; --muted: #93a4c7; --accent: #34d399; --sky: #38bdf8;
235
+ }}
236
+ * {{ box-sizing: border-box; }}
237
+ body {{ margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); padding: 28px; }}
238
+ .wrap {{ max-width: 1080px; margin: 0 auto; }}
239
+ h1 {{ margin: 0 0 6px; font-size: 24px; }}
240
+ .sub {{ color: var(--muted); font-size: 14px; margin-bottom: 22px; }}
241
+ .kpis {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 22px; }}
242
+ .kpi {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; }}
243
+ .kpi .label {{ font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }}
244
+ .kpi .val {{ font-size: 26px; font-weight: 700; margin-top: 4px; color: var(--accent); }}
245
+ .panel {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 18px; margin-bottom: 20px; }}
246
+ .panel h2 {{ margin: 0 0 12px; font-size: 16px; }}
247
+ .cards {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 12px; }}
248
+ .card {{ background: #0f1629; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; display: flex; gap: 10px; padding: 10px; }}
249
+ .thumb {{ width: 64px; height: 84px; flex: 0 0 64px; border-radius: 6px; overflow: hidden; background: #1a2440; display: flex; align-items: center; justify-content: center; }}
250
+ .thumb img {{ width: 100%; height: 100%; object-fit: cover; }}
251
+ .thumb-placeholder {{ font-size: 11px; color: var(--muted); }}
252
+ .card-head {{ display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 6px; }}
253
+ .badge {{ font-size: 11px; padding: 2px 7px; border-radius: 999px; background: #1d2b4f; color: var(--sky); }}
254
+ .badge.match, .badge.accent {{ background: #0d3b2e; color: var(--accent); }}
255
+ .badge.muted {{ background: #1e2433; color: var(--muted); }}
256
+ .meta {{ font-size: 12px; color: var(--muted); line-height: 1.45; }}
257
+ table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
258
+ th, td {{ text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); }}
259
+ th {{ color: var(--muted); font-weight: 600; }}
260
+ code {{ font-family: ui-monospace, SFMono-Regular, monospace; font-size: 12px; color: #bae6fd; }}
261
+ </style>
262
+ </head>
263
+ <body>
264
+ <div class="wrap">
265
+ <h1>Trackflow Run Report</h1>
266
+ <div class="sub">
267
+ Source: <code>{html.escape(summary.source)}</code> ·
268
+ Model: <code>{html.escape(summary.model)}</code> ·
269
+ Tracker: <code>{html.escape(summary.tracker)}</code> ·
270
+ Provider: <code>{html.escape(summary.device)}</code>
271
+ {f" · Query: <code>{html.escape(summary.query)}</code>" if summary.query else ""}
272
+ {f" · Privacy: <code>{html.escape(summary.anonymize_mode)}</code>" if summary.anonymize_mode != "none" else ""}
273
+ </div>
274
+
275
+ <div class="kpis">
276
+ <div class="kpi"><div class="label">Unique Tracks</div><div class="val">{summary.unique_tracks}</div></div>
277
+ <div class="kpi"><div class="label">Avg Speed</div><div class="val">{summary.avg_fps:.1f} FPS</div></div>
278
+ <div class="kpi"><div class="label">Frames</div><div class="val">{summary.processed_frames}</div></div>
279
+ <div class="kpi"><div class="label">Inference</div><div class="val">{summary.avg_inference_ms:.1f} ms</div></div>
280
+ <div class="kpi"><div class="label">Recovered / Re-ID</div><div class="val">{summary.recovered_tracks} / {summary.reid_merges}</div></div>
281
+ </div>
282
+
283
+ <div class="panel">
284
+ <h2>Active Tracked Objects Over Time (peak: {max_count})</h2>
285
+ <svg viewBox="0 0 {svg_w} {svg_h}" width="100%" height="150" preserveAspectRatio="none">
286
+ <polygon points="{area}" fill="rgba(56, 189, 248, 0.16)" />
287
+ <polyline points="{polyline}" fill="none" stroke="#38bdf8" stroke-width="2.2" />
288
+ </svg>
289
+ </div>
290
+
291
+ <div class="panel">
292
+ <h2>Track Cards ({len(cards)} total)</h2>
293
+ <div class="cards">{"".join(card_html) or '<div class="meta">No tracks recorded.</div>'}</div>
294
+ </div>
295
+
296
+ <div class="panel">
297
+ <h2>Tracker Diagnostics (Possible ID Switches, Recoveries & Re-ID Merges)</h2>
298
+ <table>
299
+ <thead><tr><th>Frame</th><th>Time</th><th>Event</th><th>Details</th></tr></thead>
300
+ <tbody>{"".join(id_switch_rows[:40]) or '<tr><td colspan="4" class="meta">No anomalies or switches detected.</td></tr>'}</tbody>
301
+ </table>
302
+ </div>
303
+ </div>
304
+ </body>
305
+ </html>
306
+ """
307
+ path.write_text(doc, encoding="utf-8")
308
+ return path