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/inspector.py ADDED
@@ -0,0 +1,479 @@
1
+ """Local HTTP server and API for the Trackflow Visual Track Debugger & 4-Point Floorplan Studio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import mimetypes
7
+ import re
8
+ import shutil
9
+ import threading
10
+ import webbrowser
11
+ from collections import OrderedDict, defaultdict
12
+ from http import HTTPStatus
13
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
14
+ from pathlib import Path
15
+ from typing import Any
16
+ from urllib.parse import urlparse
17
+
18
+ import cv2
19
+ import pyarrow.csv as pcsv
20
+ import pyarrow.parquet as pq
21
+
22
+ from trackflow.homography import DwellZone, FloorplanHomography
23
+ from trackflow.reid import search_track_cards
24
+ from trackflow.sinks import PARQUET_SCHEMA
25
+
26
+ UI_HTML_PATH = Path(__file__).with_name("inspector_ui.html")
27
+ _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
28
+ _MAX_FRAME_WIDTH = 960
29
+ _FRAME_CACHE_SIZE = 64
30
+
31
+
32
+ def _natural_order(path: Path) -> list[int | str]:
33
+ return [
34
+ int(part) if part.isdecimal() else part for part in re.split(r"(\d+)", path.name.casefold())
35
+ ]
36
+
37
+
38
+ def _resolve_frame_source(
39
+ run_dir: Path, summary: dict[str, Any]
40
+ ) -> tuple[str, Path | list[Path], int] | None:
41
+ """Pick a safe local frame source for the inspector, respecting ``anonymize_mode``.
42
+
43
+ Anonymized runs never read the raw source file; they only serve frames from ``annotated.mp4``.
44
+ """
45
+ outputs = summary.get("output_files")
46
+ annotated = run_dir / "annotated.mp4"
47
+ has_annotated = (outputs is None or "video" in outputs) and annotated.is_file()
48
+ stride = max(1, int(summary.get("frame_stride") or 1))
49
+
50
+ if summary.get("anonymize_mode", "none") != "none":
51
+ return ("video", annotated, stride) if has_annotated else None
52
+
53
+ raw_source = summary.get("source")
54
+ if isinstance(raw_source, str) and not raw_source.lower().startswith(
55
+ ("rtsp://", "rtsps://", "http://", "https://")
56
+ ):
57
+ src_path = Path(raw_source)
58
+ if src_path.is_file():
59
+ return ("video", src_path, 1)
60
+ if src_path.is_dir():
61
+ images = sorted(
62
+ (p for p in src_path.iterdir() if p.is_file() and p.suffix.lower() in _IMAGE_EXTS),
63
+ key=_natural_order,
64
+ )
65
+ if images:
66
+ return ("images", images, 1)
67
+
68
+ return ("video", annotated, stride) if has_annotated else None
69
+
70
+
71
+ class _FrameStore:
72
+ """Thread-safe on-demand JPEG decoder for inspector video/image backgrounds."""
73
+
74
+ def __init__(self, run_dir: Path) -> None:
75
+ summary_path = run_dir / "summary.json"
76
+ summary = (
77
+ json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.is_file() else {}
78
+ )
79
+ resolved = _resolve_frame_source(run_dir, summary)
80
+ self._kind: str | None = resolved[0] if resolved else None
81
+ self._target: Path | list[Path] | None = resolved[1] if resolved else None
82
+ self._stride: int = resolved[2] if resolved else 1
83
+ self._cap: cv2.VideoCapture | None = None
84
+ self._next_pos: int | None = None
85
+ self._lock = threading.Lock()
86
+ self._cache: OrderedDict[int, bytes] = OrderedDict()
87
+
88
+ @property
89
+ def available(self) -> bool:
90
+ return self._kind is not None
91
+
92
+ def get_jpeg(self, frame_idx: int) -> bytes | None:
93
+ if not self.available or frame_idx < 0:
94
+ return None
95
+ with self._lock:
96
+ cached = self._cache.get(frame_idx)
97
+ if cached is not None:
98
+ self._cache.move_to_end(frame_idx)
99
+ return cached
100
+
101
+ frame = self._read_frame(frame_idx)
102
+ if frame is None:
103
+ return None
104
+
105
+ h, w = frame.shape[:2]
106
+ if w > _MAX_FRAME_WIDTH:
107
+ new_h = max(1, int(round(h * (_MAX_FRAME_WIDTH / w))))
108
+ frame = cv2.resize(frame, (_MAX_FRAME_WIDTH, new_h), interpolation=cv2.INTER_AREA)
109
+
110
+ ok, encoded = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 82])
111
+ if not ok:
112
+ return None
113
+ jpeg = encoded.tobytes()
114
+ self._cache[frame_idx] = jpeg
115
+ if len(self._cache) > _FRAME_CACHE_SIZE:
116
+ self._cache.popitem(last=False)
117
+ return jpeg
118
+
119
+ def _read_frame(self, frame_idx: int) -> Any:
120
+ if self._kind == "images" and isinstance(self._target, list):
121
+ if frame_idx >= len(self._target):
122
+ return None
123
+ return cv2.imread(str(self._target[frame_idx]))
124
+
125
+ if self._kind == "video" and isinstance(self._target, Path):
126
+ if self._cap is None:
127
+ cap = cv2.VideoCapture(str(self._target))
128
+ if not cap.isOpened():
129
+ return None
130
+ self._cap = cap
131
+ self._next_pos = 0
132
+ pos = frame_idx // self._stride
133
+ if self._next_pos != pos:
134
+ self._cap.set(cv2.CAP_PROP_POS_FRAMES, float(pos))
135
+ ok, frame = self._cap.read()
136
+ if not ok or frame is None:
137
+ self._next_pos = None
138
+ return None
139
+ self._next_pos = pos + 1
140
+ return frame
141
+
142
+ return None
143
+
144
+ def close(self) -> None:
145
+ with self._lock:
146
+ if self._cap is not None:
147
+ self._cap.release()
148
+ self._cap = None
149
+ self._next_pos = None
150
+ self._cache.clear()
151
+
152
+
153
+ def load_run_payload(run_dir: Path) -> dict[str, Any]:
154
+ """Load summary, track observations, Track Cards, diagnostic events, and homography from a run directory."""
155
+ summary_path = run_dir / "summary.json"
156
+ summary = (
157
+ json.loads(summary_path.read_text(encoding="utf-8"))
158
+ if summary_path.is_file()
159
+ else {"source": str(run_dir), "frame_width": 640, "frame_height": 480}
160
+ )
161
+
162
+ cards_path = run_dir / "track_cards.json"
163
+ cards_payload = (
164
+ json.loads(cards_path.read_text(encoding="utf-8"))
165
+ if cards_path.is_file()
166
+ else {"reid_backend": "none", "cards": []}
167
+ )
168
+ # Strip raw embeddings from browser payload to keep responses fast
169
+ cards = [
170
+ {k: v for k, v in c.items() if k != "embedding"} for c in cards_payload.get("cards", [])
171
+ ]
172
+
173
+ events_path = run_dir / "events.json"
174
+ events = json.loads(events_path.read_text(encoding="utf-8")) if events_path.is_file() else []
175
+
176
+ homography_path = run_dir / "homography.json"
177
+ homography = (
178
+ json.loads(homography_path.read_text(encoding="utf-8"))
179
+ if homography_path.is_file()
180
+ else None
181
+ )
182
+
183
+ records: list[dict[str, Any]] = []
184
+ jsonl_path = run_dir / "tracks.jsonl"
185
+ parquet_path = run_dir / "tracks.parquet"
186
+ outputs = summary.get("output_files")
187
+
188
+ def present(key: str, path: Path) -> bool:
189
+ return (outputs is None or key in outputs) and path.is_file()
190
+
191
+ csv_path = run_dir / "tracks.csv"
192
+ if present("jsonl", jsonl_path):
193
+ with jsonl_path.open(encoding="utf-8") as rows:
194
+ records = [json.loads(line) for line in rows if line.strip()]
195
+ elif present("parquet", parquet_path):
196
+ records = pq.read_table(str(parquet_path)).to_pylist()
197
+ elif present("csv", csv_path):
198
+ opts = pcsv.ConvertOptions(column_types=PARQUET_SCHEMA, strings_can_be_null=True)
199
+ records = pcsv.read_csv(csv_path, convert_options=opts).to_pylist()
200
+
201
+ frames_map: dict[int, list[dict[str, Any]]] = defaultdict(list)
202
+ for rec in records:
203
+ frames_map[int(rec["frame_idx"])].append(rec)
204
+ if "frame_stride" in summary and outputs and {"jsonl", "parquet", "csv"}.intersection(outputs):
205
+ for idx in range(0, summary["total_frames"], summary["frame_stride"]):
206
+ frames_map.setdefault(idx, [])
207
+
208
+ frames_sorted = [
209
+ {"frame_idx": idx, "tracks": frames_map[idx]} for idx in sorted(frames_map.keys())
210
+ ]
211
+
212
+ id_switches = [e for e in events if e.get("type") == "possible_id_switch"]
213
+ recoveries = [e for e in events if e.get("type") == "track_recovered"]
214
+ reid_merges = [e for e in events if e.get("type") == "reid_cross_exit_merge"]
215
+
216
+ return {
217
+ "run_dir": str(run_dir),
218
+ "summary": summary,
219
+ "reid_backend": cards_payload.get("reid_backend", "none"),
220
+ "cards": cards,
221
+ "events": events,
222
+ "diagnostics": {
223
+ "possible_id_switches": len(id_switches),
224
+ "recoveries": len(recoveries),
225
+ "reid_merges": len(reid_merges),
226
+ "total_observations": len(records),
227
+ },
228
+ "homography": homography,
229
+ "frames": frames_sorted,
230
+ "has_video": present("video", run_dir / "annotated.mp4"),
231
+ "has_frames": _resolve_frame_source(run_dir, summary) is not None,
232
+ "has_floorplan": (run_dir / "floorplan.png").is_file(),
233
+ }
234
+
235
+
236
+ def compute_homography_projection(
237
+ run_dir: Path,
238
+ image_points: list[list[float]],
239
+ width_m: float = 10.0,
240
+ height_m: float = 10.0,
241
+ zones_raw: list[dict[str, Any]] | None = None,
242
+ ) -> dict[str, Any]:
243
+ """Calibrate 4-point homography on a saved run and project all track foot points to bird's-eye."""
244
+ world_points = [
245
+ (0.0, 0.0),
246
+ (float(width_m), 0.0),
247
+ (float(width_m), float(height_m)),
248
+ (0.0, float(height_m)),
249
+ ]
250
+ zones = [
251
+ DwellZone(
252
+ name=str(z["name"]),
253
+ polygon=[(float(p[0]), float(p[1])) for p in z["polygon"]],
254
+ color=str(z.get("color", "#38bdf8")),
255
+ )
256
+ for z in (zones_raw or [])
257
+ ]
258
+ hom = FloorplanHomography(
259
+ image_points=[(float(p[0]), float(p[1])) for p in image_points],
260
+ world_points=world_points,
261
+ width_m=float(width_m),
262
+ height_m=float(height_m),
263
+ zones=zones,
264
+ )
265
+
266
+ run_data = load_run_payload(run_dir)
267
+ src_fps = float(run_data["summary"].get("source_fps", 30.0) or 30.0)
268
+ dt_s = run_data["summary"].get("frame_stride", 1) / max(src_fps, 1e-3)
269
+
270
+ trajectories: dict[str, list[list[float]]] = defaultdict(list)
271
+ for frame in run_data["frames"]:
272
+ for tr in frame["tracks"]:
273
+ fx = (float(tr["x1"]) + float(tr["x2"])) * 0.5
274
+ fy = float(tr["y2"])
275
+ (wx, wy), _ = hom.observe(int(tr["track_id"]), (fx, fy), dt_s=dt_s)
276
+ trajectories[str(tr["track_id"])].append([round(wx, 3), round(wy, 3)])
277
+
278
+ hom.save_json(run_dir / "homography.json")
279
+ hom.render_floorplan(run_dir / "floorplan.png")
280
+
281
+ return {
282
+ "homography": hom.to_dict(),
283
+ "trajectories": dict(trajectories),
284
+ "zone_dwell_totals_s": {k: round(v, 2) for k, v in hom.zone_dwell_totals_s.items()},
285
+ }
286
+
287
+
288
+ def make_inspector_handler(
289
+ run_dir: Path,
290
+ compare_dir: Path | None = None,
291
+ *,
292
+ frame_store: _FrameStore | None = None,
293
+ ) -> type[BaseHTTPRequestHandler]:
294
+ """Create an HTTP handler bound to ``run_dir`` (and optional ``compare_dir``)."""
295
+ root_dir = run_dir.resolve()
296
+ cmp_dir = compare_dir.resolve() if compare_dir is not None else None
297
+ frames = frame_store if frame_store is not None else _FrameStore(root_dir)
298
+
299
+ class InspectorHandler(BaseHTTPRequestHandler):
300
+ frame_store = frames
301
+
302
+ def log_message(self, format: str, *args: Any) -> None:
303
+ _ = (format, args)
304
+
305
+ def _send_json(self, data: Any, status: int = HTTPStatus.OK) -> None:
306
+ body = json.dumps(data).encode("utf-8")
307
+ self.send_response(status)
308
+ self.send_header("Content-Type", "application/json; charset=utf-8")
309
+ self.send_header("Content-Length", str(len(body)))
310
+ self.end_headers()
311
+ self.wfile.write(body)
312
+
313
+ def _send_file(self, path: Path) -> None:
314
+ resolved = path.resolve()
315
+ if not resolved.is_relative_to(root_dir) or not resolved.is_file():
316
+ self.send_error(HTTPStatus.NOT_FOUND)
317
+ return
318
+ mime, _ = mimetypes.guess_type(str(resolved))
319
+ self.send_response(HTTPStatus.OK)
320
+ self.send_header("Content-Type", mime or "application/octet-stream")
321
+ self.send_header("Content-Length", str(resolved.stat().st_size))
322
+ self.end_headers()
323
+ with resolved.open("rb") as stream:
324
+ shutil.copyfileobj(stream, self.wfile)
325
+
326
+ def do_GET(self) -> None:
327
+ parsed = urlparse(self.path)
328
+ route = parsed.path
329
+
330
+ if route in ("/", "/index.html"):
331
+ html_bytes = UI_HTML_PATH.read_bytes()
332
+ self.send_response(HTTPStatus.OK)
333
+ self.send_header("Content-Type", "text/html; charset=utf-8")
334
+ self.send_header("Content-Length", str(len(html_bytes)))
335
+ self.end_headers()
336
+ self.wfile.write(html_bytes)
337
+ return
338
+
339
+ if route == "/api/run":
340
+ payload = load_run_payload(root_dir)
341
+ if cmp_dir is not None and cmp_dir.is_dir():
342
+ payload["compare"] = load_run_payload(cmp_dir)
343
+ self._send_json(payload)
344
+ return
345
+
346
+ if route.startswith("/api/frame/"):
347
+ raw_idx = route.removeprefix("/api/frame/")
348
+ if not raw_idx.isdigit():
349
+ self.send_error(HTTPStatus.NOT_FOUND)
350
+ return
351
+ jpeg = frames.get_jpeg(int(raw_idx))
352
+ if jpeg is None:
353
+ self.send_error(HTTPStatus.NOT_FOUND)
354
+ return
355
+ self.send_response(HTTPStatus.OK)
356
+ self.send_header("Content-Type", "image/jpeg")
357
+ self.send_header("Cache-Control", "private, max-age=300")
358
+ self.send_header("Content-Length", str(len(jpeg)))
359
+ self.end_headers()
360
+ self.wfile.write(jpeg)
361
+ return
362
+
363
+ if route.startswith("/crops/"):
364
+ rel = route.removeprefix("/crops/")
365
+ summary_path = root_dir / "summary.json"
366
+ summary = (
367
+ json.loads(summary_path.read_text(encoding="utf-8"))
368
+ if summary_path.is_file()
369
+ else {}
370
+ )
371
+ if (
372
+ summary.get("anonymize_mode", "none") != "none"
373
+ or not Path(rel).match("track_*.jpg")
374
+ or Path(rel).name != rel
375
+ ):
376
+ self.send_error(HTTPStatus.NOT_FOUND)
377
+ else:
378
+ self._send_file(root_dir / "crops" / rel)
379
+ return
380
+
381
+ if route.startswith("/media/"):
382
+ rel = route.removeprefix("/media/")
383
+ if rel not in {"floorplan.png", "annotated.mp4"}:
384
+ self.send_error(HTTPStatus.NOT_FOUND)
385
+ return
386
+ if rel == "annotated.mp4":
387
+ summary_path = root_dir / "summary.json"
388
+ if summary_path.is_file():
389
+ outputs = json.loads(summary_path.read_text(encoding="utf-8")).get(
390
+ "output_files"
391
+ )
392
+ if outputs is not None and "video" not in outputs:
393
+ self.send_error(HTTPStatus.NOT_FOUND)
394
+ return
395
+ self._send_file(root_dir / rel)
396
+ return
397
+
398
+ self.send_error(HTTPStatus.NOT_FOUND)
399
+
400
+ def do_POST(self) -> None:
401
+ parsed = urlparse(self.path)
402
+ try:
403
+ length = int(self.headers.get("Content-Length", "0"))
404
+ if length <= 0 or length > 1024 * 1024:
405
+ raise ValueError("Invalid content length")
406
+ if self.headers.get_content_type() != "application/json":
407
+ self.send_error(HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
408
+ return
409
+ raw = self.rfile.read(length)
410
+ body = json.loads(raw.decode("utf-8"))
411
+ if not isinstance(body, dict):
412
+ raise ValueError("Expected a JSON object")
413
+ except (ValueError, UnicodeError):
414
+ self._send_json({"error": "Invalid JSON body"}, status=HTTPStatus.BAD_REQUEST)
415
+ return
416
+
417
+ if parsed.path == "/api/search":
418
+ query = str(body.get("query", "")).strip()
419
+ if not query:
420
+ self._send_json({"error": "Empty query"}, status=HTTPStatus.BAD_REQUEST)
421
+ return
422
+ try:
423
+ top_k = int(body.get("top_k", 10))
424
+ hits = search_track_cards(root_dir, query, top_k=top_k)
425
+ self._send_json({"query": query, "results": hits})
426
+ except Exception as exc:
427
+ self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
428
+ return
429
+
430
+ if parsed.path == "/api/homography":
431
+ pts = body.get("image_points")
432
+ if not isinstance(pts, list) or len(pts) != 4:
433
+ self._send_json(
434
+ {"error": "Provide exactly 4 image_points [[x,y], ...]"},
435
+ status=HTTPStatus.BAD_REQUEST,
436
+ )
437
+ return
438
+ try:
439
+ res = compute_homography_projection(
440
+ root_dir,
441
+ image_points=pts,
442
+ width_m=float(body.get("width_m", 10.0)),
443
+ height_m=float(body.get("height_m", 10.0)),
444
+ zones_raw=body.get("zones"),
445
+ )
446
+ self._send_json(res)
447
+ except Exception as exc:
448
+ self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
449
+ return
450
+
451
+ self.send_error(HTTPStatus.NOT_FOUND)
452
+
453
+ return InspectorHandler
454
+
455
+
456
+ def serve_inspector(
457
+ run_dir: str | Path,
458
+ *,
459
+ compare_dir: str | Path | None = None,
460
+ host: str = "127.0.0.1",
461
+ port: int = 8765,
462
+ open_browser: bool = True,
463
+ ) -> None:
464
+ """Start the Trackflow Visual Track Debugger HTTP server."""
465
+ root = Path(run_dir).resolve()
466
+ cmp_root = Path(compare_dir).resolve() if compare_dir is not None else None
467
+ store = _FrameStore(root)
468
+ handler = make_inspector_handler(root, cmp_root, frame_store=store)
469
+ server = ThreadingHTTPServer((host, port), handler)
470
+ url = f"http://{host}:{port}"
471
+ if open_browser:
472
+ webbrowser.open(url)
473
+ try:
474
+ server.serve_forever()
475
+ except KeyboardInterrupt:
476
+ pass
477
+ finally:
478
+ store.close()
479
+ server.server_close()