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/inspector.py ADDED
@@ -0,0 +1,282 @@
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 webbrowser
8
+ from collections import defaultdict
9
+ from http import HTTPStatus
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlparse
14
+
15
+ import pyarrow.parquet as pq
16
+
17
+ from trackflow.homography import DwellZone, FloorplanHomography
18
+ from trackflow.reid import search_track_cards
19
+
20
+ UI_HTML_PATH = Path(__file__).with_name("inspector_ui.html")
21
+
22
+
23
+ def load_run_payload(run_dir: Path) -> dict[str, Any]:
24
+ """Load summary, track observations, Track Cards, diagnostic events, and homography from a run directory."""
25
+ summary_path = run_dir / "summary.json"
26
+ summary = (
27
+ json.loads(summary_path.read_text(encoding="utf-8"))
28
+ if summary_path.is_file()
29
+ else {"source": str(run_dir), "frame_width": 640, "frame_height": 480}
30
+ )
31
+
32
+ cards_path = run_dir / "track_cards.json"
33
+ cards_payload = (
34
+ json.loads(cards_path.read_text(encoding="utf-8"))
35
+ if cards_path.is_file()
36
+ else {"reid_backend": "none", "cards": []}
37
+ )
38
+ # Strip raw embeddings from browser payload to keep responses fast
39
+ cards = [
40
+ {k: v for k, v in c.items() if k != "embedding"} for c in cards_payload.get("cards", [])
41
+ ]
42
+
43
+ events_path = run_dir / "events.json"
44
+ events = json.loads(events_path.read_text(encoding="utf-8")) if events_path.is_file() else []
45
+
46
+ homography_path = run_dir / "homography.json"
47
+ homography = (
48
+ json.loads(homography_path.read_text(encoding="utf-8"))
49
+ if homography_path.is_file()
50
+ else None
51
+ )
52
+
53
+ records: list[dict[str, Any]] = []
54
+ jsonl_path = run_dir / "tracks.jsonl"
55
+ parquet_path = run_dir / "tracks.parquet"
56
+ if jsonl_path.is_file():
57
+ for line in jsonl_path.read_text(encoding="utf-8").splitlines():
58
+ if line.strip():
59
+ records.append(json.loads(line))
60
+ elif parquet_path.is_file():
61
+ records = pq.read_table(str(parquet_path)).to_pylist()
62
+
63
+ frames_map: dict[int, list[dict[str, Any]]] = defaultdict(list)
64
+ for rec in records:
65
+ frames_map[int(rec["frame_idx"])].append(rec)
66
+
67
+ frames_sorted = [
68
+ {"frame_idx": idx, "tracks": frames_map[idx]} for idx in sorted(frames_map.keys())
69
+ ]
70
+
71
+ id_switches = [e for e in events if e.get("type") == "possible_id_switch"]
72
+ recoveries = [e for e in events if e.get("type") == "track_recovered"]
73
+ reid_merges = [e for e in events if e.get("type") == "reid_cross_exit_merge"]
74
+
75
+ return {
76
+ "run_dir": str(run_dir),
77
+ "summary": summary,
78
+ "reid_backend": cards_payload.get("reid_backend", "none"),
79
+ "cards": cards,
80
+ "events": events,
81
+ "diagnostics": {
82
+ "possible_id_switches": len(id_switches),
83
+ "recoveries": len(recoveries),
84
+ "reid_merges": len(reid_merges),
85
+ "total_observations": len(records),
86
+ },
87
+ "homography": homography,
88
+ "frames": frames_sorted,
89
+ "has_video": (run_dir / "annotated.mp4").is_file(),
90
+ "has_floorplan": (run_dir / "floorplan.png").is_file(),
91
+ }
92
+
93
+
94
+ def compute_homography_projection(
95
+ run_dir: Path,
96
+ image_points: list[list[float]],
97
+ width_m: float = 10.0,
98
+ height_m: float = 10.0,
99
+ zones_raw: list[dict[str, Any]] | None = None,
100
+ ) -> dict[str, Any]:
101
+ """Calibrate 4-point homography on a saved run and project all track foot points to bird's-eye."""
102
+ world_points = [
103
+ (0.0, 0.0),
104
+ (float(width_m), 0.0),
105
+ (float(width_m), float(height_m)),
106
+ (0.0, float(height_m)),
107
+ ]
108
+ zones = [
109
+ DwellZone(
110
+ name=str(z["name"]),
111
+ polygon=[(float(p[0]), float(p[1])) for p in z["polygon"]],
112
+ color=str(z.get("color", "#38bdf8")),
113
+ )
114
+ for z in (zones_raw or [])
115
+ ]
116
+ hom = FloorplanHomography(
117
+ image_points=[(float(p[0]), float(p[1])) for p in image_points],
118
+ world_points=world_points,
119
+ width_m=float(width_m),
120
+ height_m=float(height_m),
121
+ zones=zones,
122
+ )
123
+
124
+ run_data = load_run_payload(run_dir)
125
+ src_fps = float(run_data["summary"].get("source_fps", 30.0) or 30.0)
126
+ dt_s = 1.0 / max(src_fps, 1e-3)
127
+
128
+ trajectories: dict[str, list[list[float]]] = defaultdict(list)
129
+ for frame in run_data["frames"]:
130
+ for tr in frame["tracks"]:
131
+ fx = (float(tr["x1"]) + float(tr["x2"])) * 0.5
132
+ fy = float(tr["y2"])
133
+ (wx, wy), _ = hom.observe(int(tr["track_id"]), (fx, fy), dt_s=dt_s)
134
+ trajectories[str(tr["track_id"])].append([round(wx, 3), round(wy, 3)])
135
+
136
+ hom.save_json(run_dir / "homography.json")
137
+ hom.render_floorplan(run_dir / "floorplan.png")
138
+
139
+ return {
140
+ "homography": hom.to_dict(),
141
+ "trajectories": dict(trajectories),
142
+ "zone_dwell_totals_s": {k: round(v, 2) for k, v in hom.zone_dwell_totals_s.items()},
143
+ }
144
+
145
+
146
+ def make_inspector_handler(
147
+ run_dir: Path,
148
+ compare_dir: Path | None = None,
149
+ ) -> type[BaseHTTPRequestHandler]:
150
+ """Create an HTTP handler bound to ``run_dir`` (and optional ``compare_dir``)."""
151
+ root_dir = run_dir.resolve()
152
+ cmp_dir = compare_dir.resolve() if compare_dir is not None else None
153
+
154
+ class InspectorHandler(BaseHTTPRequestHandler):
155
+ def log_message(self, format: str, *args: Any) -> None:
156
+ _ = (format, args)
157
+
158
+ def _send_json(self, data: Any, status: int = HTTPStatus.OK) -> None:
159
+ body = json.dumps(data).encode("utf-8")
160
+ self.send_response(status)
161
+ self.send_header("Content-Type", "application/json; charset=utf-8")
162
+ self.send_header("Content-Length", str(len(body)))
163
+ self.end_headers()
164
+ self.wfile.write(body)
165
+
166
+ def _send_file(self, path: Path) -> None:
167
+ resolved = path.resolve()
168
+ if not str(resolved).startswith(str(root_dir)) or not resolved.is_file():
169
+ self.send_error(HTTPStatus.NOT_FOUND)
170
+ return
171
+ mime, _ = mimetypes.guess_type(str(resolved))
172
+ data = resolved.read_bytes()
173
+ self.send_response(HTTPStatus.OK)
174
+ self.send_header("Content-Type", mime or "application/octet-stream")
175
+ self.send_header("Content-Length", str(len(data)))
176
+ self.end_headers()
177
+ self.wfile.write(data)
178
+
179
+ def do_GET(self) -> None:
180
+ parsed = urlparse(self.path)
181
+ route = parsed.path
182
+
183
+ if route in ("/", "/index.html"):
184
+ html_bytes = UI_HTML_PATH.read_bytes()
185
+ self.send_response(HTTPStatus.OK)
186
+ self.send_header("Content-Type", "text/html; charset=utf-8")
187
+ self.send_header("Content-Length", str(len(html_bytes)))
188
+ self.end_headers()
189
+ self.wfile.write(html_bytes)
190
+ return
191
+
192
+ if route == "/api/run":
193
+ payload = load_run_payload(root_dir)
194
+ if cmp_dir is not None and cmp_dir.is_dir():
195
+ payload["compare"] = load_run_payload(cmp_dir)
196
+ self._send_json(payload)
197
+ return
198
+
199
+ if route.startswith("/crops/"):
200
+ rel = route.removeprefix("/crops/")
201
+ self._send_file(root_dir / "crops" / Path(rel).name)
202
+ return
203
+
204
+ if route.startswith("/media/"):
205
+ rel = route.removeprefix("/media/")
206
+ self._send_file(root_dir / Path(rel).name)
207
+ return
208
+
209
+ self.send_error(HTTPStatus.NOT_FOUND)
210
+
211
+ def do_POST(self) -> None:
212
+ parsed = urlparse(self.path)
213
+ length = int(self.headers.get("Content-Length", "0"))
214
+ raw = self.rfile.read(length) if length > 0 else b"{}"
215
+ try:
216
+ body = json.loads(raw.decode("utf-8"))
217
+ except json.JSONDecodeError:
218
+ self._send_json({"error": "Invalid JSON body"}, status=HTTPStatus.BAD_REQUEST)
219
+ return
220
+
221
+ if parsed.path == "/api/search":
222
+ query = str(body.get("query", "")).strip()
223
+ top_k = int(body.get("top_k", 10))
224
+ if not query:
225
+ self._send_json({"error": "Empty query"}, status=HTTPStatus.BAD_REQUEST)
226
+ return
227
+ try:
228
+ hits = search_track_cards(root_dir, query, top_k=top_k)
229
+ self._send_json({"query": query, "results": hits})
230
+ except Exception as exc:
231
+ self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
232
+ return
233
+
234
+ if parsed.path == "/api/homography":
235
+ pts = body.get("image_points")
236
+ if not isinstance(pts, list) or len(pts) != 4:
237
+ self._send_json(
238
+ {"error": "Provide exactly 4 image_points [[x,y], ...]"},
239
+ status=HTTPStatus.BAD_REQUEST,
240
+ )
241
+ return
242
+ try:
243
+ res = compute_homography_projection(
244
+ root_dir,
245
+ image_points=pts,
246
+ width_m=float(body.get("width_m", 10.0)),
247
+ height_m=float(body.get("height_m", 10.0)),
248
+ zones_raw=body.get("zones"),
249
+ )
250
+ self._send_json(res)
251
+ except Exception as exc:
252
+ self._send_json({"error": str(exc)}, status=HTTPStatus.BAD_REQUEST)
253
+ return
254
+
255
+ self.send_error(HTTPStatus.NOT_FOUND)
256
+
257
+ return InspectorHandler
258
+
259
+
260
+ def serve_inspector(
261
+ run_dir: str | Path,
262
+ *,
263
+ compare_dir: str | Path | None = None,
264
+ host: str = "127.0.0.1",
265
+ port: int = 8765,
266
+ open_browser: bool = True,
267
+ ) -> None:
268
+ """Start the Trackflow Visual Track Debugger HTTP server."""
269
+ handler = make_inspector_handler(
270
+ Path(run_dir),
271
+ Path(compare_dir) if compare_dir is not None else None,
272
+ )
273
+ server = ThreadingHTTPServer((host, port), handler)
274
+ url = f"http://{host}:{port}"
275
+ if open_browser:
276
+ webbrowser.open(url)
277
+ try:
278
+ server.serve_forever()
279
+ except KeyboardInterrupt:
280
+ pass
281
+ finally:
282
+ server.server_close()