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.
@@ -0,0 +1,451 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Trackflow Inspector — Visual Track Debugger & Floorplan Studio</title>
7
+ <style>
8
+ :root {
9
+ --bg: #090d1a; --panel: #11182c; --panel-2: #16203a; --border: #253358;
10
+ --text: #e8effc; --muted: #8ea1c4; --accent: #34d399; --sky: #38bdf8;
11
+ --warn: #fbbf24; --danger: #f87171;
12
+ }
13
+ * { box-sizing: border-box; }
14
+ body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); }
15
+ header { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; background: var(--panel); border-bottom: 1px solid var(--border); }
16
+ .brand { font-weight: 700; font-size: 17px; display: flex; align-items: center; gap: 10px; }
17
+ .brand span.pill { font-size: 11px; background: #0d3b2e; color: var(--accent); padding: 2px 8px; border-radius: 999px; font-weight: 600; }
18
+ nav { display: flex; gap: 8px; }
19
+ nav button { background: transparent; border: 1px solid var(--border); color: var(--muted); padding: 7px 14px; border-radius: 8px; cursor: pointer; font-weight: 600; }
20
+ nav button.active { background: var(--panel-2); color: var(--text); border-color: var(--sky); }
21
+ main { max-width: 1280px; margin: 0 auto; padding: 18px 22px 40px; }
22
+ .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 18px; }
23
+ .kpi { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; }
24
+ .kpi .lbl { font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
25
+ .kpi .val { font-size: 22px; font-weight: 700; margin-top: 3px; color: var(--accent); }
26
+ .grid-2 { display: grid; grid-template-columns: 1.45fr 1fr; gap: 16px; }
27
+ @media (max-width: 960px) { .grid-2 { grid-template-columns: 1fr; } }
28
+ .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px; margin-bottom: 16px; }
29
+ .panel h2 { margin: 0 0 12px; font-size: 15px; display: flex; justify-content: space-between; align-items: center; }
30
+ canvas { width: 100%; background: #060912; border-radius: 8px; border: 1px solid var(--border); display: block; }
31
+ .controls { display: flex; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
32
+ .controls input[type=range] { flex: 1; min-width: 180px; }
33
+ button.btn { background: #1c2c52; border: 1px solid #30477d; color: var(--text); padding: 7px 12px; border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 600; }
34
+ button.btn.primary { background: #059669; border-color: #10b981; color: #fff; }
35
+ input[type=text], input[type=number] { background: #0c1222; border: 1px solid var(--border); color: var(--text); padding: 8px 10px; border-radius: 8px; font-size: 13px; }
36
+ .markers { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px; max-height: 70px; overflow-y: auto; }
37
+ .marker { font-size: 11px; padding: 2px 7px; border-radius: 6px; cursor: pointer; border: 1px solid transparent; }
38
+ .marker.switch { background: rgba(248,113,113,.15); color: var(--danger); border-color: rgba(248,113,113,.4); }
39
+ .marker.merge { background: rgba(52,211,153,.15); color: var(--accent); border-color: rgba(52,211,153,.4); }
40
+ .marker.rec { background: rgba(251,191,36,.15); color: var(--warn); border-color: rgba(251,191,36,.4); }
41
+ .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(195px, 1fr)); gap: 10px; max-height: 540px; overflow-y: auto; }
42
+ .card { background: #0c1324; border: 1px solid var(--border); border-radius: 9px; padding: 8px; display: flex; gap: 9px; cursor: pointer; transition: border-color .15s; }
43
+ .card:hover, .card.selected { border-color: var(--sky); }
44
+ .card img { width: 52px; height: 68px; object-fit: cover; border-radius: 6px; background: #17223d; flex-shrink: 0; }
45
+ .card .meta { font-size: 11px; color: var(--muted); line-height: 1.4; }
46
+ .tab { display: none; }
47
+ .tab.active { display: block; }
48
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
49
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); }
50
+ th { color: var(--muted); }
51
+ .hint { font-size: 12px; color: var(--muted); }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <header>
56
+ <div class="brand">
57
+ Trackflow Inspector
58
+ <span class="pill" id="metaPill">Loading…</span>
59
+ </div>
60
+ <nav>
61
+ <button class="active" data-tab="debugger">Track Debugger</button>
62
+ <button data-tab="floorplan">4-Point Floorplan</button>
63
+ <button data-tab="compare">Tracker Compare</button>
64
+ </nav>
65
+ </header>
66
+
67
+ <main>
68
+ <div class="kpis" id="kpis"></div>
69
+
70
+ <!-- TAB 1: VISUAL TRACK DEBUGGER -->
71
+ <section id="tab-debugger" class="tab active">
72
+ <div class="grid-2">
73
+ <div class="panel">
74
+ <h2>
75
+ <span>Frame Canvas & Timeline Scrubber</span>
76
+ <span class="hint" id="frameInfo">Frame 0</span>
77
+ </h2>
78
+ <canvas id="trackCanvas" width="800" height="450"></canvas>
79
+ <div class="controls">
80
+ <button class="btn primary" id="playBtn">Play</button>
81
+ <input type="range" id="scrubber" min="0" max="0" value="0" />
82
+ <label class="hint"><input type="checkbox" id="showTrails" checked /> Trails</label>
83
+ </div>
84
+ <div class="hint" style="margin-top:10px;">Diagnostic Event Markers (click to jump):</div>
85
+ <div class="markers" id="eventMarkers"></div>
86
+ </div>
87
+
88
+ <div class="panel">
89
+ <h2>
90
+ <span>Track Cards & Natural-Language Search</span>
91
+ <span class="hint" id="cardCount"></span>
92
+ </h2>
93
+ <div class="controls" style="margin-top:0; margin-bottom:12px;">
94
+ <input type="text" id="nlQuery" placeholder='e.g. "person in red jacket"' style="flex:1;" />
95
+ <button class="btn primary" id="nlSearchBtn">Search</button>
96
+ <button class="btn" id="nlResetBtn">Reset</button>
97
+ </div>
98
+ <div id="searchStatus" class="hint" style="margin-bottom:8px;"></div>
99
+ <div class="cards" id="cardGrid"></div>
100
+ </div>
101
+ </div>
102
+ </section>
103
+
104
+ <!-- TAB 2: 4-POINT FLOORPLAN HOMOGRAPHY -->
105
+ <section id="tab-floorplan" class="tab">
106
+ <div class="grid-2">
107
+ <div class="panel">
108
+ <h2>
109
+ <span>1. Click 4 Ground Corners (TL → TR → BR → BL)</span>
110
+ <button class="btn" id="resetPtsBtn">Clear Points</button>
111
+ </h2>
112
+ <canvas id="calibCanvas" width="760" height="430" style="cursor:crosshair;"></canvas>
113
+ <div class="controls">
114
+ <label class="hint">Width (m): <input type="number" id="worldW" value="10" step="0.5" style="width:74px;" /></label>
115
+ <label class="hint">Height (m): <input type="number" id="worldH" value="8" step="0.5" style="width:74px;" /></label>
116
+ <button class="btn primary" id="projectBtn">Project to Bird's-Eye</button>
117
+ </div>
118
+ <div id="calibStatus" class="hint" style="margin-top:8px;">Click 4 ground-plane points to calibrate perspective homography.</div>
119
+ </div>
120
+ <div class="panel">
121
+ <h2><span>2. Bird's-Eye Trajectories & Heatmap</span></h2>
122
+ <canvas id="floorCanvas" width="600" height="480"></canvas>
123
+ <div id="zoneSummary" class="hint" style="margin-top:10px;"></div>
124
+ </div>
125
+ </div>
126
+ </section>
127
+
128
+ <!-- TAB 3: SIDE-BY-SIDE TRACKER COMPARISON -->
129
+ <section id="tab-compare" class="tab">
130
+ <div class="panel">
131
+ <h2>Side-by-Side Tracker Comparison</h2>
132
+ <div id="compareContent" class="hint">Launch with <code>trackflow inspect run_a --compare run_b</code> to compare trackers side-by-side.</div>
133
+ </div>
134
+ </section>
135
+ </main>
136
+
137
+ <script>
138
+ const PALETTE = ['#34d399','#38bdf8','#a78bfa','#fbbf24','#f472b6','#60a5fa','#4ade80','#fb7185'];
139
+ let DATA = null;
140
+ let frameIdxPos = 0;
141
+ let playing = false;
142
+ let playTimer = null;
143
+ let selectedTrackId = null;
144
+ let calibPoints = [];
145
+
146
+ function colorFor(id) { return PALETTE[id % PALETTE.length]; }
147
+
148
+ document.querySelectorAll('nav button').forEach(btn => {
149
+ btn.addEventListener('click', () => {
150
+ document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));
151
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
152
+ btn.classList.add('active');
153
+ document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
154
+ if (btn.dataset.tab === 'floorplan') drawCalibCanvas();
155
+ });
156
+ });
157
+
158
+ async function init() {
159
+ const res = await fetch('/api/run');
160
+ DATA = await res.json();
161
+ const s = DATA.summary;
162
+ document.getElementById('metaPill').textContent = `${s.model || 'model'} · ${s.tracker || 'tracker'} · ${s.device || 'cpu'}`;
163
+ renderKpis();
164
+ renderMarkers();
165
+ renderCards(DATA.cards);
166
+ renderCompare();
167
+
168
+ const scrubber = document.getElementById('scrubber');
169
+ scrubber.max = Math.max(0, DATA.frames.length - 1);
170
+ scrubber.addEventListener('input', e => { frameIdxPos = Number(e.target.value); drawFrame(); });
171
+ document.getElementById('showTrails').addEventListener('change', drawFrame);
172
+
173
+ if (DATA.homography && DATA.homography.image_points) {
174
+ calibPoints = DATA.homography.image_points.map(p => [...p]);
175
+ document.getElementById('worldW').value = DATA.homography.width_m || 10;
176
+ document.getElementById('worldH').value = DATA.homography.height_m || 8;
177
+ }
178
+ drawFrame();
179
+ drawCalibCanvas();
180
+ }
181
+
182
+ function renderKpis() {
183
+ const s = DATA.summary, d = DATA.diagnostics;
184
+ const items = [
185
+ ['Unique Tracks', s.unique_tracks ?? DATA.cards.length],
186
+ ['Avg FPS', (s.avg_fps ?? 0).toFixed(1)],
187
+ ['Frames', s.processed_frames ?? DATA.frames.length],
188
+ ['Possible ID Switches', d.possible_id_switches],
189
+ ['Recoveries / Re-ID', `${d.recoveries} / ${d.reid_merges}`],
190
+ ['Re-ID Backend', DATA.reid_backend || 'none'],
191
+ ];
192
+ document.getElementById('kpis').innerHTML = items.map(([l,v]) =>
193
+ `<div class="kpi"><div class="lbl">${l}</div><div class="val">${v}</div></div>`
194
+ ).join('');
195
+ }
196
+
197
+ function renderMarkers() {
198
+ const wrap = document.getElementById('eventMarkers');
199
+ const interesting = DATA.events.filter(e =>
200
+ ['possible_id_switch','reid_cross_exit_merge','track_recovered'].includes(e.type)
201
+ );
202
+ if (!interesting.length) { wrap.innerHTML = '<span class="hint">No ID switches or merges flagged.</span>'; return; }
203
+ wrap.innerHTML = interesting.slice(0, 80).map(e => {
204
+ const cls = e.type === 'possible_id_switch' ? 'switch' : (e.type === 'reid_cross_exit_merge' ? 'merge' : 'rec');
205
+ const lbl = e.type === 'possible_id_switch'
206
+ ? `F${e.frame_idx} Switch #${e.previous_track_id}→#${e.new_track_id}`
207
+ : e.type === 'reid_cross_exit_merge'
208
+ ? `F${e.frame_idx} Re-ID #${e.raw_track_id}→#${e.canonical_track_id}`
209
+ : `F${e.frame_idx} Recovered #${e.track_id}`;
210
+ return `<span class="marker ${cls}" onclick="jumpToFrame(${e.frame_idx})">${lbl}</span>`;
211
+ }).join('');
212
+ }
213
+
214
+ function jumpToFrame(targetFrameIdx) {
215
+ const pos = DATA.frames.findIndex(f => f.frame_idx >= targetFrameIdx);
216
+ if (pos >= 0) {
217
+ frameIdxPos = pos;
218
+ document.getElementById('scrubber').value = pos;
219
+ drawFrame();
220
+ }
221
+ }
222
+
223
+ function renderCards(cards) {
224
+ document.getElementById('cardCount').textContent = `${cards.length} cards`;
225
+ const grid = document.getElementById('cardGrid');
226
+ grid.innerHTML = cards.map(c => {
227
+ const score = c.search_score !== undefined ? `<div>Match: <b>${c.search_score.toFixed(3)}</b></div>`
228
+ : (c.query_score !== null && c.query_score !== undefined ? `<div>Query: <b>${c.query_score.toFixed(3)}</b></div>` : '');
229
+ const thumb = c.thumbnail ? `<img src="/${c.thumbnail}" alt="Track #${c.track_id}" />` : '';
230
+ return `<div class="card ${selectedTrackId === c.track_id ? 'selected' : ''}" onclick="selectTrack(${c.track_id}, ${c.best_frame})">
231
+ ${thumb}
232
+ <div class="meta">
233
+ <div style="color:#fff;font-weight:700;">#${c.track_id} · ${c.class_name}</div>
234
+ <div>F${c.first_frame}–F${c.last_frame} (${c.duration_s}s)</div>
235
+ <div>Conf ${c.best_confidence}</div>
236
+ ${score}
237
+ </div>
238
+ </div>`;
239
+ }).join('');
240
+ }
241
+
242
+ function selectTrack(tid, bestFrame) {
243
+ selectedTrackId = selectedTrackId === tid ? null : tid;
244
+ jumpToFrame(bestFrame);
245
+ renderCards(DATA.cards);
246
+ }
247
+
248
+ function drawFrame() {
249
+ const canvas = document.getElementById('trackCanvas');
250
+ const ctx = canvas.getContext('2d');
251
+ const fw = DATA.summary.frame_width || 800;
252
+ const fh = DATA.summary.frame_height || 450;
253
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
254
+
255
+ // Subtle coordinate grid
256
+ ctx.strokeStyle = '#141d36';
257
+ ctx.lineWidth = 1;
258
+ for (let x = 0; x < canvas.width; x += 64) { ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,canvas.height); ctx.stroke(); }
259
+ for (let y = 0; y < canvas.height; y += 64) { ctx.beginPath(); ctx.moveTo(0,y); ctx.lineTo(canvas.width,y); ctx.stroke(); }
260
+
261
+ if (!DATA.frames.length) return;
262
+ const frame = DATA.frames[frameIdxPos];
263
+ document.getElementById('frameInfo').textContent = `Frame ${frame.frame_idx} · ${frame.tracks.length} tracks`;
264
+
265
+ const sx = canvas.width / fw;
266
+ const sy = canvas.height / fh;
267
+
268
+ if (document.getElementById('showTrails').checked) {
269
+ const start = Math.max(0, frameIdxPos - 30);
270
+ const paths = {};
271
+ for (let i = start; i <= frameIdxPos; i++) {
272
+ for (const tr of DATA.frames[i].tracks) {
273
+ (paths[tr.track_id] ||= []).push([(tr.x1 + tr.x2) * 0.5 * sx, tr.y2 * sy]);
274
+ }
275
+ }
276
+ for (const [tid, pts] of Object.entries(paths)) {
277
+ if (pts.length < 2) continue;
278
+ ctx.strokeStyle = colorFor(Number(tid));
279
+ ctx.globalAlpha = selectedTrackId && Number(tid) !== selectedTrackId ? 0.2 : 0.75;
280
+ ctx.lineWidth = 2;
281
+ ctx.beginPath();
282
+ pts.forEach(([x,y], idx) => idx ? ctx.lineTo(x,y) : ctx.moveTo(x,y));
283
+ ctx.stroke();
284
+ }
285
+ ctx.globalAlpha = 1;
286
+ }
287
+
288
+ for (const tr of frame.tracks) {
289
+ const dim = selectedTrackId && tr.track_id !== selectedTrackId;
290
+ const col = colorFor(tr.track_id);
291
+ ctx.globalAlpha = dim ? 0.22 : 1;
292
+ ctx.strokeStyle = col;
293
+ ctx.lineWidth = tr.track_id === selectedTrackId ? 3.5 : 2;
294
+ const x = tr.x1 * sx, y = tr.y1 * sy, w = tr.width * sx, h = tr.height * sy;
295
+ ctx.strokeRect(x, y, w, h);
296
+ ctx.fillStyle = col;
297
+ const lbl = `#${tr.track_id} ${tr.class_name} ${(tr.confidence).toFixed(2)}`;
298
+ ctx.font = '12px ui-monospace, monospace';
299
+ const tw = ctx.measureText(lbl).width + 8;
300
+ ctx.fillRect(x, Math.max(0, y - 18), tw, 18);
301
+ ctx.fillStyle = '#090d1a';
302
+ ctx.fillText(lbl, x + 4, Math.max(13, y - 5));
303
+ }
304
+ ctx.globalAlpha = 1;
305
+ }
306
+
307
+ document.getElementById('playBtn').addEventListener('click', () => {
308
+ playing = !playing;
309
+ document.getElementById('playBtn').textContent = playing ? 'Pause' : 'Play';
310
+ if (playing) {
311
+ playTimer = setInterval(() => {
312
+ frameIdxPos = (frameIdxPos + 1) % Math.max(1, DATA.frames.length);
313
+ document.getElementById('scrubber').value = frameIdxPos;
314
+ drawFrame();
315
+ }, 66);
316
+ } else {
317
+ clearInterval(playTimer);
318
+ }
319
+ });
320
+
321
+ document.getElementById('nlSearchBtn').addEventListener('click', async () => {
322
+ const q = document.getElementById('nlQuery').value.trim();
323
+ if (!q) return;
324
+ const st = document.getElementById('searchStatus');
325
+ st.textContent = `Searching Track Cards for "${q}"…`;
326
+ const res = await fetch('/api/search', {
327
+ method: 'POST', headers: {'Content-Type': 'application/json'},
328
+ body: JSON.stringify({ query: q, top_k: 20 })
329
+ });
330
+ const body = await res.json();
331
+ if (!res.ok) { st.textContent = `Error: ${body.error}`; return; }
332
+ st.textContent = `Ranked ${body.results.length} Track Cards for "${q}".`;
333
+ renderCards(body.results);
334
+ });
335
+ document.getElementById('nlResetBtn').addEventListener('click', () => {
336
+ document.getElementById('nlQuery').value = '';
337
+ document.getElementById('searchStatus').textContent = '';
338
+ renderCards(DATA.cards);
339
+ });
340
+
341
+ // 4-Point Homography Calibration Studio
342
+ const calibCanvas = document.getElementById('calibCanvas');
343
+ calibCanvas.addEventListener('click', e => {
344
+ if (!DATA || calibPoints.length >= 4) return;
345
+ const rect = calibCanvas.getBoundingClientRect();
346
+ const fw = DATA.summary.frame_width || 800;
347
+ const fh = DATA.summary.frame_height || 450;
348
+ const x = ((e.clientX - rect.left) / rect.width) * fw;
349
+ const y = ((e.clientY - rect.top) / rect.height) * fh;
350
+ calibPoints.push([x, y]);
351
+ drawCalibCanvas();
352
+ });
353
+ document.getElementById('resetPtsBtn').addEventListener('click', () => { calibPoints = []; drawCalibCanvas(); });
354
+
355
+ function drawCalibCanvas() {
356
+ if (!DATA) return;
357
+ const ctx = calibCanvas.getContext('2d');
358
+ const fw = DATA.summary.frame_width || 800;
359
+ const fh = DATA.summary.frame_height || 450;
360
+ const sx = calibCanvas.width / fw, sy = calibCanvas.height / fh;
361
+ ctx.clearRect(0, 0, calibCanvas.width, calibCanvas.height);
362
+
363
+ // Draw all foot points in image space as spatial reference
364
+ ctx.fillStyle = 'rgba(56, 189, 248, 0.28)';
365
+ for (const f of DATA.frames) {
366
+ for (const tr of f.tracks) {
367
+ ctx.fillRect(((tr.x1 + tr.x2) * 0.5) * sx - 1.5, tr.y2 * sy - 1.5, 3, 3);
368
+ }
369
+ }
370
+
371
+ if (calibPoints.length) {
372
+ ctx.strokeStyle = '#34d399'; ctx.lineWidth = 2;
373
+ ctx.beginPath();
374
+ calibPoints.forEach(([x,y], i) => i ? ctx.lineTo(x*sx, y*sy) : ctx.moveTo(x*sx, y*sy));
375
+ if (calibPoints.length === 4) ctx.closePath();
376
+ ctx.stroke();
377
+ calibPoints.forEach(([x,y], i) => {
378
+ ctx.fillStyle = '#fbbf24';
379
+ ctx.beginPath(); ctx.arc(x*sx, y*sy, 6, 0, Math.PI*2); ctx.fill();
380
+ ctx.fillStyle = '#090d1a'; ctx.font = 'bold 11px sans-serif';
381
+ ctx.fillText(String(i+1), x*sx - 3, y*sy + 4);
382
+ });
383
+ }
384
+ document.getElementById('calibStatus').textContent = `${calibPoints.length}/4 corners selected.`;
385
+ }
386
+
387
+ document.getElementById('projectBtn').addEventListener('click', async () => {
388
+ if (calibPoints.length !== 4) {
389
+ document.getElementById('calibStatus').textContent = 'Please click exactly 4 ground points first.';
390
+ return;
391
+ }
392
+ const width_m = Number(document.getElementById('worldW').value) || 10;
393
+ const height_m = Number(document.getElementById('worldH').value) || 8;
394
+ const res = await fetch('/api/homography', {
395
+ method: 'POST', headers: {'Content-Type': 'application/json'},
396
+ body: JSON.stringify({ image_points: calibPoints, width_m, height_m })
397
+ });
398
+ const out = await res.json();
399
+ if (!res.ok) { document.getElementById('calibStatus').textContent = out.error; return; }
400
+ drawFloorplan(out.trajectories, width_m, height_m);
401
+ document.getElementById('calibStatus').textContent = 'Projected & saved homography.json + floorplan.png.';
402
+ });
403
+
404
+ function drawFloorplan(trajectories, wm, hm) {
405
+ const c = document.getElementById('floorCanvas');
406
+ const ctx = c.getContext('2d');
407
+ ctx.clearRect(0, 0, c.width, c.height);
408
+ ctx.strokeStyle = '#192440'; ctx.lineWidth = 1;
409
+ for (let i = 0; i <= Math.ceil(wm); i++) {
410
+ const x = (i / wm) * c.width; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, c.height); ctx.stroke();
411
+ }
412
+ for (let j = 0; j <= Math.ceil(hm); j++) {
413
+ const y = (j / hm) * c.height; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(c.width, y); ctx.stroke();
414
+ }
415
+ for (const [tid, pts] of Object.entries(trajectories)) {
416
+ if (pts.length < 2) continue;
417
+ ctx.strokeStyle = colorFor(Number(tid));
418
+ ctx.lineWidth = 2;
419
+ ctx.beginPath();
420
+ pts.forEach(([wx, wy], idx) => {
421
+ const px = (wx / wm) * c.width, py = (wy / hm) * c.height;
422
+ idx ? ctx.lineTo(px, py) : ctx.moveTo(px, py);
423
+ });
424
+ ctx.stroke();
425
+ }
426
+ }
427
+
428
+ function renderCompare() {
429
+ if (!DATA.compare) return;
430
+ const a = DATA, b = DATA.compare;
431
+ const rows = [
432
+ ['Tracker', a.summary.tracker, b.summary.tracker],
433
+ ['Model', a.summary.model, b.summary.model],
434
+ ['Avg FPS', a.summary.avg_fps?.toFixed(1), b.summary.avg_fps?.toFixed(1)],
435
+ ['Unique Tracks (lower = less fragmentation)', a.summary.unique_tracks, b.summary.unique_tracks],
436
+ ['Possible ID Switches', a.diagnostics.possible_id_switches, b.diagnostics.possible_id_switches],
437
+ ['Track Recoveries', a.diagnostics.recoveries, b.diagnostics.recoveries],
438
+ ['Cross-Exit Re-ID Merges', a.diagnostics.reid_merges, b.diagnostics.reid_merges],
439
+ ['Total Observations', a.diagnostics.total_observations, b.diagnostics.total_observations],
440
+ ];
441
+ document.getElementById('compareContent').innerHTML = `
442
+ <table>
443
+ <thead><tr><th>Metric</th><th>Run A (${a.summary.tracker})</th><th>Run B (${b.summary.tracker})</th></tr></thead>
444
+ <tbody>${rows.map(([m,va,vb]) => `<tr><td>${m}</td><td><b>${va}</b></td><td><b>${vb}</b></td></tr>`).join('')}</tbody>
445
+ </table>`;
446
+ }
447
+
448
+ init();
449
+ </script>
450
+ </body>
451
+ </html>
trackflow/models.py ADDED
@@ -0,0 +1,184 @@
1
+ """Model registry and automatic Hugging Face ONNX weight downloading."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ from huggingface_hub import hf_hub_download
10
+
11
+ Precision = Literal["fp32", "fp16", "int8"]
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class ModelSpec:
16
+ """Descriptor for a built-in Hugging Face ONNX detector model."""
17
+
18
+ name: str
19
+ repo_id: str
20
+ architecture: str
21
+ license: str
22
+ approx_size_mb: float
23
+ default_input_size: tuple[int, int]
24
+ description: str
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class ReidModelSpec:
29
+ """Descriptor for a built-in vision-language Re-ID / query model."""
30
+
31
+ name: str
32
+ repo_id: str
33
+ license: str
34
+ approx_size_mb: float
35
+ vision_files: dict[str, str]
36
+ text_files: dict[str, str]
37
+ description: str
38
+
39
+
40
+ MODEL_REGISTRY: dict[str, ModelSpec] = {
41
+ "dfine-n": ModelSpec(
42
+ name="dfine-n",
43
+ repo_id="onnx-community/dfine_n_coco-ONNX",
44
+ architecture="D-FINE Nano",
45
+ license="Apache-2.0",
46
+ approx_size_mb=15.3,
47
+ default_input_size=(640, 640),
48
+ description="Ultra-fast 15 MB end-to-end transformer detector (default for laptops & real-time).",
49
+ ),
50
+ "rtdetr-v2-r18": ModelSpec(
51
+ name="rtdetr-v2-r18",
52
+ repo_id="onnx-community/rtdetr_v2_r18vd-ONNX",
53
+ architecture="RT-DETRv2 ResNet-18",
54
+ license="Apache-2.0",
55
+ approx_size_mb=81.1,
56
+ default_input_size=(640, 640),
57
+ description="Balanced accuracy and speed for crowded scenes.",
58
+ ),
59
+ "rfdetr-base": ModelSpec(
60
+ name="rfdetr-base",
61
+ repo_id="onnx-community/rfdetr_base-ONNX",
62
+ architecture="RF-DETR Base",
63
+ license="Apache-2.0",
64
+ approx_size_mb=107.8,
65
+ default_input_size=(560, 560),
66
+ description="High-accuracy Apache-2.0 detection transformer for dense people tracking.",
67
+ ),
68
+ }
69
+
70
+ REID_REGISTRY: dict[str, ReidModelSpec] = {
71
+ "clip": ReidModelSpec(
72
+ name="clip",
73
+ repo_id="Xenova/clip-vit-base-patch32",
74
+ license="MIT",
75
+ approx_size_mb=153.0,
76
+ vision_files={
77
+ "int8": "onnx/vision_model_int8.onnx",
78
+ "fp16": "onnx/vision_model_fp16.onnx",
79
+ "fp32": "onnx/vision_model.onnx",
80
+ },
81
+ text_files={
82
+ "int8": "onnx/text_model_int8.onnx",
83
+ "fp16": "onnx/text_model_fp16.onnx",
84
+ "fp32": "onnx/text_model.onnx",
85
+ },
86
+ description="Fast MIT-licensed CLIP ViT-B/32 vision+text ONNX for NL prompt-to-track and Re-ID.",
87
+ ),
88
+ "siglip": ReidModelSpec(
89
+ name="siglip",
90
+ repo_id="Xenova/siglip-base-patch16-224",
91
+ license="Apache-2.0",
92
+ approx_size_mb=205.0,
93
+ vision_files={
94
+ "int8": "onnx/vision_model_int8.onnx",
95
+ "fp16": "onnx/vision_model_fp16.onnx",
96
+ "fp32": "onnx/vision_model.onnx",
97
+ },
98
+ text_files={
99
+ "int8": "onnx/text_model_int8.onnx",
100
+ "fp16": "onnx/text_model_fp16.onnx",
101
+ "fp32": "onnx/text_model.onnx",
102
+ },
103
+ description="High-precision Apache-2.0 SigLIP Base vision+text ONNX for fine-grained clothing/attribute queries.",
104
+ ),
105
+ }
106
+
107
+ PRECISION_TO_FILENAME: dict[str, str] = {
108
+ "fp32": "onnx/model.onnx",
109
+ "fp16": "onnx/model_fp16.onnx",
110
+ "int8": "onnx/model_int8.onnx",
111
+ }
112
+
113
+
114
+ def resolve_detector_artifacts(
115
+ model: str,
116
+ precision: Precision = "fp32",
117
+ cache_dir: str | Path | None = None,
118
+ ) -> tuple[Path, Path | None, Path | None]:
119
+ """Resolve a model preset, HF repo id, or local ONNX path into local file paths.
120
+
121
+ Returns ``(onnx_path, config_path, preprocessor_config_path)``.
122
+ """
123
+ local_path = Path(model)
124
+ if local_path.is_file():
125
+ parent = local_path.parent
126
+ cfg = parent / "config.json"
127
+ if not cfg.is_file():
128
+ cfg = parent.parent / "config.json"
129
+ prep = parent / "preprocessor_config.json"
130
+ if not prep.is_file():
131
+ prep = parent.parent / "preprocessor_config.json"
132
+ return (
133
+ local_path,
134
+ cfg if cfg.is_file() else None,
135
+ prep if prep.is_file() else None,
136
+ )
137
+
138
+ repo_id = MODEL_REGISTRY[model].repo_id if model in MODEL_REGISTRY else model
139
+ onnx_filename = PRECISION_TO_FILENAME.get(precision, "onnx/model.onnx")
140
+
141
+ kwargs = {"cache_dir": str(cache_dir)} if cache_dir is not None else {}
142
+ onnx_path = Path(hf_hub_download(repo_id=repo_id, filename=onnx_filename, **kwargs))
143
+
144
+ config_path: Path | None = None
145
+ prep_path: Path | None = None
146
+ try:
147
+ config_path = Path(hf_hub_download(repo_id=repo_id, filename="config.json", **kwargs))
148
+ except Exception:
149
+ config_path = None
150
+ try:
151
+ prep_path = Path(
152
+ hf_hub_download(repo_id=repo_id, filename="preprocessor_config.json", **kwargs)
153
+ )
154
+ except Exception:
155
+ prep_path = None
156
+
157
+ return onnx_path, config_path, prep_path
158
+
159
+
160
+ def resolve_reid_artifacts(
161
+ backend: str = "clip",
162
+ precision: Precision = "int8",
163
+ cache_dir: str | Path | None = None,
164
+ ) -> dict[str, Path]:
165
+ """Download and cache ONNX vision+text encoder and tokenizer files for Re-ID & NL search."""
166
+ if backend not in REID_REGISTRY:
167
+ raise ValueError(f"Unknown Re-ID model '{backend}'. Available: {list(REID_REGISTRY)}")
168
+
169
+ spec = REID_REGISTRY[backend]
170
+ vision_file = spec.vision_files.get(precision, spec.vision_files["int8"])
171
+ text_file = spec.text_files.get(precision, spec.text_files["int8"])
172
+ kwargs = {"cache_dir": str(cache_dir)} if cache_dir is not None else {}
173
+
174
+ return {
175
+ "vision_onnx": Path(hf_hub_download(repo_id=spec.repo_id, filename=vision_file, **kwargs)),
176
+ "text_onnx": Path(hf_hub_download(repo_id=spec.repo_id, filename=text_file, **kwargs)),
177
+ "tokenizer": Path(
178
+ hf_hub_download(repo_id=spec.repo_id, filename="tokenizer.json", **kwargs)
179
+ ),
180
+ "preprocessor": Path(
181
+ hf_hub_download(repo_id=spec.repo_id, filename="preprocessor_config.json", **kwargs)
182
+ ),
183
+ "config": Path(hf_hub_download(repo_id=spec.repo_id, filename="config.json", **kwargs)),
184
+ }