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/sinks.py ADDED
@@ -0,0 +1,440 @@
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.abc import Iterable, Sequence
9
+ from contextlib import ExitStack
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import cv2
14
+ import numpy as np
15
+ import pyarrow as pa
16
+ import pyarrow.parquet as pq
17
+
18
+ from trackflow.lines import CountingLine
19
+ from trackflow.privacy import _track_color
20
+ from trackflow.types import FrameResult, RunSummary, Track, TrackCard
21
+
22
+ PARQUET_SCHEMA = pa.schema(
23
+ [
24
+ ("frame_idx", pa.int64()),
25
+ ("timestamp_s", pa.float64()),
26
+ ("track_id", pa.int64()),
27
+ ("class_id", pa.int64()),
28
+ ("class_name", pa.string()),
29
+ ("confidence", pa.float64()),
30
+ ("x1", pa.float64()),
31
+ ("y1", pa.float64()),
32
+ ("x2", pa.float64()),
33
+ ("y2", pa.float64()),
34
+ ("width", pa.float64()),
35
+ ("height", pa.float64()),
36
+ ("age", pa.int64()),
37
+ ("hits", pa.int64()),
38
+ ("recovered", pa.bool_()),
39
+ ("query_score", pa.float64()),
40
+ ("query_match", pa.bool_()),
41
+ ("world_x", pa.float64()),
42
+ ("world_y", pa.float64()),
43
+ ("zone", pa.string()),
44
+ ]
45
+ )
46
+
47
+
48
+ class ObservationWriter:
49
+ """Write each requested format in bounded batches, including schemas on empty runs."""
50
+
51
+ def __init__(self, paths: dict[str, Path], stack: ExitStack) -> None:
52
+ self._batch: list[dict[str, Any]] = []
53
+ self._parquet = None
54
+ self._jsonl = self._csv = self._mot = None
55
+ if "parquet" in paths:
56
+ self._parquet = stack.enter_context(
57
+ pq.ParquetWriter(paths["parquet"], PARQUET_SCHEMA, compression="snappy")
58
+ )
59
+ if "jsonl" in paths:
60
+ self._jsonl = stack.enter_context(paths["jsonl"].open("w", encoding="utf-8"))
61
+ if "csv" in paths:
62
+ fh = stack.enter_context(paths["csv"].open("w", encoding="utf-8", newline=""))
63
+ self._csv = csv.DictWriter(fh, fieldnames=PARQUET_SCHEMA.names)
64
+ self._csv.writeheader()
65
+ if "mot" in paths:
66
+ fh = stack.enter_context(paths["mot"].open("w", encoding="utf-8", newline=""))
67
+ self._mot = csv.writer(fh, lineterminator="\n")
68
+ stack.callback(self.flush)
69
+
70
+ def append(self, record: dict[str, Any]) -> None:
71
+ self._batch.append(record)
72
+ if len(self._batch) >= 1024:
73
+ self.flush()
74
+
75
+ def flush(self) -> None:
76
+ if not self._batch:
77
+ return
78
+ batch, self._batch = self._batch, []
79
+ if self._parquet is not None:
80
+ self._parquet.write_table(pa.Table.from_pylist(batch, schema=PARQUET_SCHEMA))
81
+ if self._csv is not None:
82
+ self._csv.writerows(batch)
83
+ if self._jsonl is not None:
84
+ self._jsonl.writelines(json.dumps(r) + "\n" for r in batch)
85
+ if self._mot is not None:
86
+ for r in batch:
87
+ self._mot.writerow(
88
+ (
89
+ r["frame_idx"] + 1,
90
+ r["track_id"],
91
+ round(r["x1"] + 1, 2),
92
+ round(r["y1"] + 1, 2),
93
+ r["width"],
94
+ r["height"],
95
+ r["confidence"],
96
+ -1,
97
+ -1,
98
+ -1,
99
+ )
100
+ )
101
+
102
+
103
+ def _write_records(records: Iterable[dict[str, Any]], path: Path, fmt: str) -> Path:
104
+ with ExitStack() as stack:
105
+ writer = ObservationWriter({fmt: path}, stack)
106
+ for rec in records:
107
+ writer.append(rec)
108
+ return path
109
+
110
+
111
+ def write_parquet(records: Iterable[dict[str, Any]], path: Path) -> Path:
112
+ """Write track observations to Parquet with the public Trackflow schema."""
113
+ return _write_records(records, path, "parquet")
114
+
115
+
116
+ def write_jsonl(records: Iterable[dict[str, Any]], path: Path) -> Path:
117
+ """Write line-delimited JSON observations."""
118
+ return _write_records(records, path, "jsonl")
119
+
120
+
121
+ def write_csv(records: Iterable[dict[str, Any]], path: Path) -> Path:
122
+ """Write CSV observations with a header."""
123
+ return _write_records(records, path, "csv")
124
+
125
+
126
+ def write_mot(records: Iterable[dict[str, Any]], path: Path) -> Path:
127
+ """Write MOTChallenge 2D results. Frame, ID, left and top are one-based."""
128
+ return _write_records(records, path, "mot")
129
+
130
+
131
+ def draw_tracks(
132
+ frame_bgr: np.ndarray,
133
+ tracks: list[Track],
134
+ *,
135
+ trails: dict[int, list[tuple[int, int]]],
136
+ coasting: list[Track] | None = None,
137
+ fps: float | None = None,
138
+ query: str | None = None,
139
+ anonymize_mode: str = "none",
140
+ lines: Sequence[CountingLine] = (),
141
+ line_counts: dict[str, dict[str, int]] | None = None,
142
+ ) -> np.ndarray:
143
+ """Draw boxes, IDs, motion trails, query highlight badges, counting lines, and HUD."""
144
+ canvas = frame_bgr.copy()
145
+
146
+ for line in lines:
147
+ start = tuple(int(round(v)) for v in line.start)
148
+ end = tuple(int(round(v)) for v in line.end)
149
+ cv2.line(canvas, start, end, (0, 215, 255), 2, cv2.LINE_AA)
150
+ # Arrow from the middle of the line toward its "in" side.
151
+ dx, dy = line.end[0] - line.start[0], line.end[1] - line.start[1]
152
+ norm = max((dx * dx + dy * dy) ** 0.5, 1e-6)
153
+ mid = ((line.start[0] + line.end[0]) / 2, (line.start[1] + line.end[1]) / 2)
154
+ tip = (mid[0] - dy / norm * 18, mid[1] + dx / norm * 18)
155
+ cv2.arrowedLine(
156
+ canvas,
157
+ (int(round(mid[0])), int(round(mid[1]))),
158
+ (int(round(tip[0])), int(round(tip[1]))),
159
+ (0, 215, 255),
160
+ 2,
161
+ cv2.LINE_AA,
162
+ tipLength=0.4,
163
+ )
164
+ counts = (line_counts or {}).get(line.name, {"in": 0, "out": 0})
165
+ cv2.putText(
166
+ canvas,
167
+ f"{line.name} in {counts['in']} out {counts['out']}",
168
+ (start[0] + 4, max(14, start[1] - 6)),
169
+ cv2.FONT_HERSHEY_SIMPLEX,
170
+ 0.5,
171
+ (0, 215, 255),
172
+ 1,
173
+ cv2.LINE_AA,
174
+ )
175
+
176
+ # Briefly-missed tracks at their predicted position: thin dimmed box + ID, so boxes don't blink.
177
+ for tr in coasting or []:
178
+ x1, y1, x2, y2 = [int(round(v)) for v in tr.bbox]
179
+ dim = tuple(int(c * 0.6) for c in _track_color(tr.track_id))
180
+ cv2.rectangle(canvas, (x1, y1), (x2, y2), dim, 1, cv2.LINE_AA)
181
+ cv2.putText(
182
+ canvas,
183
+ f"#{tr.track_id}",
184
+ (x1 + 2, max(12, y1 - 4)),
185
+ cv2.FONT_HERSHEY_SIMPLEX,
186
+ 0.45,
187
+ dim,
188
+ 1,
189
+ cv2.LINE_AA,
190
+ )
191
+
192
+ for tr in tracks:
193
+ x1, y1, x2, y2 = [int(round(v)) for v in tr.bbox]
194
+ base_color = _track_color(tr.track_id)
195
+ is_match = tr.query_match
196
+
197
+ color = base_color if is_match else (100, 105, 115)
198
+ thickness = 3 if (query and is_match) else (2 if is_match else 1)
199
+
200
+ # Draw motion trail
201
+ trail = trails.get(tr.track_id, [])
202
+ if len(trail) >= 2:
203
+ pts = np.array(trail[-32:], dtype=np.int32)
204
+ cv2.polylines(canvas, [pts], False, color, 2 if is_match else 1, cv2.LINE_AA)
205
+
206
+ # Bounding box
207
+ cv2.rectangle(canvas, (x1, y1), (x2, y2), color, thickness, cv2.LINE_AA)
208
+
209
+ # Label pill
210
+ parts = [f"#{tr.track_id}", tr.class_name, f"{tr.confidence:.2f}"]
211
+ if tr.query_score is not None:
212
+ parts.append(f"q:{tr.query_score:.2f}")
213
+ if tr.zone:
214
+ parts.append(f"[{tr.zone}]")
215
+ label = " ".join(parts)
216
+
217
+ (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
218
+ ly = max(th + 8, y1)
219
+ cv2.rectangle(canvas, (x1, ly - th - 8), (x1 + tw + 10, ly), color, -1)
220
+ cv2.putText(
221
+ canvas,
222
+ label,
223
+ (x1 + 5, ly - 5),
224
+ cv2.FONT_HERSHEY_SIMPLEX,
225
+ 0.5,
226
+ (15, 18, 24),
227
+ 1,
228
+ cv2.LINE_AA,
229
+ )
230
+
231
+ # Top-left HUD
232
+ hud_items = [f"Trackflow | {len(tracks)} active"]
233
+ if fps is not None:
234
+ hud_items.append(f"{fps:.1f} FPS")
235
+ if query:
236
+ hud_items.append(f'query: "{query}"')
237
+ if anonymize_mode != "none":
238
+ hud_items.append(f"privacy: {anonymize_mode}")
239
+ hud_text = " • ".join(hud_items)
240
+ (hw, hh), _ = cv2.getTextSize(hud_text, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 1)
241
+ cv2.rectangle(canvas, (10, 10), (24 + hw, 24 + hh), (15, 18, 26), -1)
242
+ cv2.putText(
243
+ canvas,
244
+ hud_text,
245
+ (17, 17 + hh),
246
+ cv2.FONT_HERSHEY_SIMPLEX,
247
+ 0.55,
248
+ (235, 242, 250),
249
+ 1,
250
+ cv2.LINE_AA,
251
+ )
252
+ return canvas
253
+
254
+
255
+ def write_html_report(
256
+ summary: RunSummary,
257
+ frame_results: list[FrameResult],
258
+ cards: list[TrackCard],
259
+ path: Path,
260
+ ) -> Path:
261
+ """Generate a self-contained HTML run report with inline SVG charts & Track Card gallery."""
262
+ counts = [len(fr.tracks) for fr in frame_results]
263
+ events = (
264
+ {"frame_idx": fr.frame_idx, "timestamp_s": fr.timestamp_s, **ev}
265
+ for fr in frame_results
266
+ for ev in fr.events
267
+ )
268
+ return write_run_report(summary, counts, events, cards, path)
269
+
270
+
271
+ def write_run_report(
272
+ summary: RunSummary,
273
+ counts: Sequence[int],
274
+ events: Iterable[dict[str, Any]],
275
+ cards: list[TrackCard],
276
+ path: Path,
277
+ ) -> Path:
278
+ """Render the report from frame counts and events without retaining track objects."""
279
+ max_count = max(counts, default=0)
280
+
281
+ # Build inline SVG sparkline for active tracks per frame
282
+ svg_w, svg_h = 720, 150
283
+ if len(counts) > svg_w:
284
+ # One peak per display column keeps the report usable for long recordings.
285
+ counts = [
286
+ max(counts[i * len(counts) // svg_w : (i + 1) * len(counts) // svg_w])
287
+ for i in range(svg_w)
288
+ ]
289
+ if len(counts) >= 2:
290
+ pts = [
291
+ f"{(i / (len(counts) - 1)) * svg_w:.1f},{svg_h - 12 - (c / max(1, max_count)) * (svg_h - 24):.1f}"
292
+ for i, c in enumerate(counts)
293
+ ]
294
+ polyline = " ".join(pts)
295
+ area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
296
+ else:
297
+ polyline = f"0,{svg_h - 12} {svg_w},{svg_h - 12}"
298
+ area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
299
+
300
+ # Diagnostic events summary
301
+ id_switch_rows: list[str] = []
302
+ for ev in events:
303
+ et = ev.get("type", "event")
304
+ if et in ("possible_id_switch", "reid_cross_exit_merge", "track_recovered"):
305
+ id_switch_rows.append(
306
+ f"<tr><td>{int(ev['frame_idx'])}</td><td>{ev['timestamp_s']:.2f}s</td>"
307
+ f"<td><code>{html.escape(et)}</code></td>"
308
+ f"<td><code>{html.escape(json.dumps(ev))}</code></td></tr>"
309
+ )
310
+ if len(id_switch_rows) == 40:
311
+ break
312
+
313
+ line_kpis = "".join(
314
+ f'<div class="kpi"><div class="label">Line {html.escape(name)} (in / out)</div>'
315
+ f'<div class="val">{c["in"]} / {c["out"]}</div></div>'
316
+ for name, c in summary.line_counts.items()
317
+ )
318
+
319
+ card_html: list[str] = []
320
+ for c in cards[:60]:
321
+ q_badge = (
322
+ f'<span class="badge {"match" if c.query_match else "muted"}">query {c.query_score:.2f}</span>'
323
+ if c.query_score is not None
324
+ else ""
325
+ )
326
+ merged_badge = (
327
+ f'<span class="badge accent">Re-ID merged {len(c.merged_track_ids)}x</span>'
328
+ if c.merged_track_ids
329
+ else ""
330
+ )
331
+ thumb = (
332
+ f'<img src="{html.escape(c.thumbnail_relpath)}" alt="Track #{c.track_id}" />'
333
+ if c.thumbnail_relpath
334
+ else '<div class="thumb-placeholder">No Crop</div>'
335
+ )
336
+ card_html.append(
337
+ f"""
338
+ <div class="card">
339
+ <div class="thumb">{thumb}</div>
340
+ <div class="card-body">
341
+ <div class="card-head">
342
+ <strong>Track #{c.track_id}</strong>
343
+ <span class="badge">{html.escape(c.class_name)}</span>
344
+ {q_badge}{merged_badge}
345
+ </div>
346
+ <div class="meta">
347
+ Frames {c.first_frame}–{c.last_frame} ({c.duration_s:.1f}s · {c.frame_count} obs)<br/>
348
+ Peak conf: {c.best_confidence:.2f}
349
+ {f"<br/>Zones: {html.escape(', '.join(c.zones_visited))}" if c.zones_visited else ""}
350
+ </div>
351
+ </div>
352
+ </div>
353
+ """
354
+ )
355
+
356
+ doc = f"""<!DOCTYPE html>
357
+ <html lang="en">
358
+ <head>
359
+ <meta charset="utf-8" />
360
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
361
+ <title>Trackflow Run Report — {html.escape(Path(summary.source).name)}</title>
362
+ <style>
363
+ :root {{
364
+ --bg: #0b1020; --surface: #131b31; --border: #24304f;
365
+ --text: #e6eefc; --muted: #93a4c7; --accent: #34d399; --sky: #38bdf8;
366
+ }}
367
+ * {{ box-sizing: border-box; }}
368
+ body {{ margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); padding: 28px; }}
369
+ .wrap {{ max-width: 1080px; margin: 0 auto; }}
370
+ h1 {{ margin: 0 0 6px; font-size: 24px; }}
371
+ .sub {{ color: var(--muted); font-size: 14px; margin-bottom: 22px; }}
372
+ .kpis {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 22px; }}
373
+ .kpi {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; }}
374
+ .kpi .label {{ font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }}
375
+ .kpi .val {{ font-size: 26px; font-weight: 700; margin-top: 4px; color: var(--accent); }}
376
+ .panel {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 18px; margin-bottom: 20px; }}
377
+ .panel h2 {{ margin: 0 0 12px; font-size: 16px; }}
378
+ .cards {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 12px; }}
379
+ .card {{ background: #0f1629; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; display: flex; gap: 10px; padding: 10px; }}
380
+ .thumb {{ width: 64px; height: 84px; flex: 0 0 64px; border-radius: 6px; overflow: hidden; background: #1a2440; display: flex; align-items: center; justify-content: center; }}
381
+ .thumb img {{ width: 100%; height: 100%; object-fit: cover; }}
382
+ .thumb-placeholder {{ font-size: 11px; color: var(--muted); }}
383
+ .card-head {{ display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 6px; }}
384
+ .badge {{ font-size: 11px; padding: 2px 7px; border-radius: 999px; background: #1d2b4f; color: var(--sky); }}
385
+ .badge.match, .badge.accent {{ background: #0d3b2e; color: var(--accent); }}
386
+ .badge.muted {{ background: #1e2433; color: var(--muted); }}
387
+ .meta {{ font-size: 12px; color: var(--muted); line-height: 1.45; }}
388
+ table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
389
+ th, td {{ text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); }}
390
+ th {{ color: var(--muted); font-weight: 600; }}
391
+ code {{ font-family: ui-monospace, SFMono-Regular, monospace; font-size: 12px; color: #bae6fd; }}
392
+ </style>
393
+ </head>
394
+ <body>
395
+ <div class="wrap">
396
+ <h1>Trackflow Run Report</h1>
397
+ <div class="sub">
398
+ Source: <code>{html.escape(summary.source)}</code> ·
399
+ Model: <code>{html.escape(summary.model)}</code> ·
400
+ Tracker: <code>{html.escape(summary.tracker)}</code> ·
401
+ Provider: <code>{html.escape(summary.device)}</code>
402
+ {f" · Query: <code>{html.escape(summary.query)}</code>" if summary.query else ""}
403
+ {f" · Privacy: <code>{html.escape(summary.anonymize_mode)}</code>" if summary.anonymize_mode != "none" else ""}
404
+ </div>
405
+
406
+ <div class="kpis">
407
+ <div class="kpi"><div class="label">Unique Tracks</div><div class="val">{summary.unique_tracks}</div></div>
408
+ <div class="kpi"><div class="label">Avg Speed</div><div class="val">{summary.avg_fps:.1f} FPS</div></div>
409
+ <div class="kpi"><div class="label">Frames</div><div class="val">{summary.processed_frames}</div></div>
410
+ <div class="kpi"><div class="label">Inference</div><div class="val">{summary.avg_inference_ms:.1f} ms</div></div>
411
+ <div class="kpi"><div class="label">Recovered / Re-ID</div><div class="val">{summary.recovered_tracks} / {summary.reid_merges}</div></div>
412
+ {line_kpis}
413
+ </div>
414
+
415
+ <div class="panel">
416
+ <h2>Active Tracked Objects Over Time (peak: {max_count})</h2>
417
+ <svg viewBox="0 0 {svg_w} {svg_h}" width="100%" height="150" preserveAspectRatio="none">
418
+ <polygon points="{area}" fill="rgba(56, 189, 248, 0.16)" />
419
+ <polyline points="{polyline}" fill="none" stroke="#38bdf8" stroke-width="2.2" />
420
+ </svg>
421
+ </div>
422
+
423
+ <div class="panel">
424
+ <h2>Track Cards ({len(cards)} total)</h2>
425
+ <div class="cards">{"".join(card_html) or '<div class="meta">No tracks recorded.</div>'}</div>
426
+ </div>
427
+
428
+ <div class="panel">
429
+ <h2>Tracker Diagnostics (Possible ID Switches, Recoveries & Re-ID Merges)</h2>
430
+ <table>
431
+ <thead><tr><th>Frame</th><th>Time</th><th>Event</th><th>Details</th></tr></thead>
432
+ <tbody>{"".join(id_switch_rows[:40]) or '<tr><td colspan="4" class="meta">No anomalies or switches detected.</td></tr>'}</tbody>
433
+ </table>
434
+ </div>
435
+ </div>
436
+ </body>
437
+ </html>
438
+ """
439
+ path.write_text(doc, encoding="utf-8")
440
+ return path