File size: 14,851 Bytes
091ea0d
 
 
 
 
 
162e31e
 
091ea0d
162e31e
 
 
 
 
 
 
 
f048b9a
 
 
 
162e31e
 
 
 
 
 
 
 
 
 
091ea0d
 
162e31e
 
 
 
 
 
 
 
 
091ea0d
4d20521
 
091ea0d
4d20521
 
091ea0d
4d20521
162e31e
 
091ea0d
162e31e
 
 
 
091ea0d
162e31e
4d20521
f048b9a
 
162e31e
 
 
 
091ea0d
 
 
 
162e31e
f048b9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162e31e
4d20521
162e31e
091ea0d
f048b9a
 
 
 
 
091ea0d
f048b9a
 
 
091ea0d
 
f048b9a
 
 
 
 
 
 
091ea0d
f048b9a
 
 
 
 
091ea0d
 
 
162e31e
 
f048b9a
 
5cd1866
 
 
 
162e31e
 
 
e3ec5d6
f048b9a
162e31e
 
f048b9a
162e31e
 
f048b9a
 
 
162e31e
 
091ea0d
 
f048b9a
 
 
 
 
 
162e31e
 
091ea0d
162e31e
f048b9a
 
162e31e
e3ec5d6
f048b9a
162e31e
f048b9a
091ea0d
162e31e
4d20521
f048b9a
 
 
5cd1866
 
 
 
f048b9a
091ea0d
f048b9a
 
 
 
162e31e
f048b9a
 
 
 
 
 
 
 
 
162e31e
4d20521
162e31e
 
 
091ea0d
 
 
 
162e31e
4d20521
 
 
162e31e
f048b9a
 
162e31e
f048b9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459069b
f048b9a
 
162e31e
 
 
f048b9a
091ea0d
 
 
 
162e31e
 
 
 
091ea0d
f048b9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ea0d
 
f048b9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ea0d
 
 
 
 
 
 
 
 
 
 
 
 
 
f048b9a
 
 
091ea0d
 
 
162e31e
 
091ea0d
 
162e31e
 
 
091ea0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162e31e
091ea0d
162e31e
091ea0d
4d20521
162e31e
 
4d20521
162e31e
 
 
f048b9a
 
162e31e
f048b9a
 
162e31e
4d20521
162e31e
 
 
 
 
4d20521
091ea0d
162e31e
 
 
 
f048b9a
 
 
 
 
 
162e31e
 
 
4d20521
 
162e31e
091ea0d
5cd1866
f048b9a
5cd1866
 
 
 
f048b9a
 
162e31e
 
091ea0d
4d20521
091ea0d
162e31e
4d20521
091ea0d
 
 
 
 
 
 
 
162e31e
 
 
 
4d20521
162e31e
091ea0d
162e31e
4d20521
162e31e
091ea0d
 
162e31e
 
a14a412
4d20521
091ea0d
a14a412
 
 
 
091ea0d
 
 
a14a412
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// =============================================
// UrbanFlow β€” initial.js (Mobile-First)
// Added: touch events, mobile upload UX
// =============================================

let videoId  = null;
let runConfig = {};

// ---- Step navigation ----
function showStep(name) {
    ['modules', 'upload', 'draw'].forEach(s => {
        const el = document.getElementById('step-' + s);
        if (el) el.classList.add('hidden');
    });
    const target = document.getElementById('step-' + name);
    if (target) target.classList.remove('hidden');

    // The canvas has no measurable size while its step is hidden, so it can
    // only be sized once the step is actually on screen.
    if (name === 'draw') initCanvas();

    if (name === 'upload') {
        document.getElementById('upload-progress-container').classList.add('hidden');
        document.getElementById('dropzone').classList.remove('hidden');
        document.getElementById('upload-bar').style.width = '0%';
        document.getElementById('upload-percentage').innerText = '0%';
        document.getElementById('upload-text').innerText = 'Uploading...';
        document.getElementById('upload-text').classList.remove('text-red-500');
    }
}

// ---- File input / dropzone ----
const dropzone  = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');

if (fileInput) {
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length) uploadFile(fileInput.files[0]);
    });
}

if (dropzone) {
    // Desktop drag-and-drop
    dropzone.addEventListener('dragover', e => {
        e.preventDefault();
        dropzone.classList.add('dz-active');
    });
    dropzone.addEventListener('dragleave', () => {
        dropzone.classList.remove('dz-active');
    });
    dropzone.addEventListener('drop', e => {
        e.preventDefault();
        dropzone.classList.remove('dz-active');
        if (e.dataTransfer.files.length) uploadFile(e.dataTransfer.files[0]);
    });
}

// ---- Upload ----
let currentXHR = null;

const MAX_UPLOAD_BYTES = 500 * 1024 * 1024;

function uploadFile(file) {
    if (currentXHR) currentXHR.abort();

    const dropzoneEl = document.getElementById('dropzone');
    const prog       = document.getElementById('upload-progress-container');
    const bar        = document.getElementById('upload-bar');
    const pct        = document.getElementById('upload-percentage');
    const txt        = document.getElementById('upload-text');

    const fail = (msg) => {
        txt.innerText = msg;
        txt.classList.add('text-red-500');
        if (fileInput) fileInput.value = '';
        // Give the dropzone back so the user can retry without a page reload.
        setTimeout(() => { if (!videoId) showStep('upload'); }, 2600);
    };

    if (file.size > MAX_UPLOAD_BYTES) {
        if (dropzoneEl) dropzoneEl.classList.add('hidden');
        if (prog)       prog.classList.remove('hidden');
        fail('File too large β€” 500MB maximum');
        return;
    }

    if (dropzoneEl) dropzoneEl.classList.add('hidden');
    if (prog)       prog.classList.remove('hidden');

    // ---- Simulated progress (proxy-buffer-safe) ----
    // The HF proxy buffers the body, so upload.onprogress usually reports 100%
    // long before the server has actually stored the file. Simulate up to 90%,
    // then hand the remaining band to the real post-upload stages so the bar
    // only ever moves forward.
    const fileMB        = file.size / (1024 * 1024);
    const estDurationMs = Math.min(Math.max(fileMB * 1000, 3000), 60000);
    const targetPct     = 90;
    const tickMs        = 200;
    const stepPerTick   = targetPct / (estDurationMs / tickMs);

    let simPct = 0;
    const setPct = (v) => {
        simPct = Math.max(simPct, v);          // never move backwards
        bar.style.width = simPct.toFixed(1) + '%';
        pct.innerText   = Math.floor(simPct) + '%';
    };

    const simInterval = setInterval(() => {
        if (simPct < targetPct) {
            setPct(simPct + stepPerTick);
        } else {
            // Plateau reached: the bytes are sent, the server is still working.
            // Say so instead of leaving a frozen bar with no explanation.
            txt.innerText = 'Processing on server...';
        }
    }, tickMs);

    const form = new FormData();
    form.append('file', file);

    fetch('api/event', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event: 'UPLOAD_STARTED', meta: { size: fileMB.toFixed(2) } })
    }).catch(()=>{});

    const xhr = new XMLHttpRequest();
    currentXHR = xhr;
    xhr.open('POST', 'upload');
    xhr.timeout = 10 * 60 * 1000;   // large files on a cold Space are slow

    xhr.upload.onprogress = e => {
        if (e.lengthComputable) setPct(Math.min(e.loaded / e.total * targetPct, targetPct));
    };

    xhr.onerror   = () => { clearInterval(simInterval); fail('Network error β€” check your connection and retry'); };
    xhr.ontimeout = () => { clearInterval(simInterval); fail('Upload timed out β€” try a shorter clip'); };
    xhr.onabort   = () => { clearInterval(simInterval); };

    xhr.onload = () => {
        clearInterval(simInterval);

        let res = null;
        try { res = JSON.parse(xhr.responseText); } catch (e) { /* non-JSON error page */ }

        if (xhr.status !== 200 || !res || !res.video_id) {
            // Surface the server's own message (rate limit, too large, bad type).
            fail((res && res.error) || `Upload failed (${xhr.status || 'no response'})`);
            return;
        }

        videoId = res.video_id;
        setPct(94);
        txt.innerText = 'Extracting metadata...';

        fetch('config/' + videoId)
            .then(r => r.ok ? r.json() : Promise.reject(new Error('config')))
            .then(cfg => {
                setPct(97);
                runConfig      = cfg;
                runConfig.conf = 0.12;
                runConfig.iou  = 0.60;
                txt.innerText  = 'Loading preview frame...';

                fetch('api/event', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ event: 'UPLOAD_SUCCESS', meta: { video_id: videoId } })
                }).catch(()=>{});

                if (fileInput) fileInput.value = '';

                // Only hit 100% and switch screens once the frame is decoded and
                // on screen β€” otherwise the user gets a blank step after "100%".
                return loadFirstFrame();
            })
            .then(ok => {
                // Without a decoded frame there is nothing to draw the counting
                // line on, and taps would map to meaningless coordinates.
                if (!ok) { videoId = null; fail('Could not read this video β€” try another file'); return; }
                setPct(100);
                txt.innerText = 'Ready';
                setTimeout(() => showStep('draw'), 400);
            })
            .catch(() => { videoId = null; fail('Could not read this video β€” try another file'); });
    };

    xhr.send(form);
}

// =============================================
// CANVAS β€” Spatial Boundary Drawing
// Supports both mouse (desktop) and touch (mobile)
// =============================================
const canvas = document.getElementById('drawing-canvas');
const ctx    = canvas ? canvas.getContext('2d') : null;
let points   = [];
let imgNatW  = 0, imgNatH = 0;

// Resolves true once the frame is decoded and painted, false if it failed.
// Never rejects β€” a missing preview should not abort the whole flow.
function loadFirstFrame() {
    return new Promise(resolve => {
        const img         = document.getElementById('frame-img');
        const placeholder = document.getElementById('frame-placeholder');
        if (!img) { resolve(false); return; }

        img.onload = () => {
            imgNatW = img.naturalWidth;
            imgNatH = img.naturalHeight;
            img.style.display = 'block';
            if (placeholder) placeholder.style.display = 'none';
            initCanvas();
            resolve(true);
        };

        img.onerror = () => {
            console.error('Failed to load first frame');
            img.style.display = 'none';
            if (placeholder) {
                placeholder.style.display = 'flex';
                placeholder.innerHTML =
                    '<i class="fa-solid fa-circle-exclamation text-4xl mb-3 opacity-50" style="color:#c89a6c"></i>' +
                    '<span class="font-bold text-[10px] uppercase tracking-widest opacity-50 block mt-2">Frame Load Error</span>';
            }
            resolve(false);
        };

        img.src = 'first-frame/' + videoId;
    });
}

function initCanvas() {
    if (!canvas || !canvas.offsetWidth) return;   // hidden step has no size yet
    canvas.width  = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    // Redraw existing points after resize
    redrawCanvas();
}

window.addEventListener('resize', initCanvas);

// ---- Coordinate helpers ----
// The frame uses object-contain, so it is letterboxed whenever the canvas
// aspect ratio differs from the video's (it always does on mobile, where CSS
// forces 4/3). Mapping canvas pixels straight to image pixels therefore put
// the counting line in the wrong place. Everything below goes through the
// displayed image rect instead.
function getImageRect() {
    if (!imgNatW || !imgNatH) {
        return { x: 0, y: 0, w: canvas.width, h: canvas.height };
    }
    const scale = Math.min(canvas.width / imgNatW, canvas.height / imgNatH);
    const w = imgNatW * scale;
    const h = imgNatH * scale;
    return { x: (canvas.width - w) / 2, y: (canvas.height - h) / 2, w, h };
}

function getCanvasCoords(clientX, clientY) {
    const rect = canvas.getBoundingClientRect();
    const box  = getImageRect();
    // Clamp into the visible frame so taps on the letterbox bars still land.
    const cx = Math.min(Math.max(clientX - rect.left, box.x), box.x + box.w);
    const cy = Math.min(Math.max(clientY - rect.top, box.y), box.y + box.h);
    return {
        rx: Math.round((cx - box.x) / box.w * imgNatW),
        ry: Math.round((cy - box.y) / box.h * imgNatH),
    };
}

// Image coords -> canvas coords, recomputed on every draw so the line stays
// correct after a resize or an orientation change.
function toCanvasPoint(p) {
    const box = getImageRect();
    return {
        x: box.x + (p.rx / (imgNatW || 1)) * box.w,
        y: box.y + (p.ry / (imgNatH || 1)) * box.h,
    };
}

function addPoint(coords) {
    if (points.length >= 2) return;
    points.push(coords);
    redrawCanvas();
    if (points.length === 2 && canvas) {
        canvas.style.cursor = 'default';
    }
}

function redrawCanvas() {
    if (!ctx) return;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    const pts = points.map(toCanvasPoint);
    pts.forEach(p => drawDot(p.x, p.y));
    if (pts.length === 2) drawLine(pts);
}

// ---- Mouse events (desktop) ----
if (canvas) {
    canvas.addEventListener('mousedown', e => {
        e.preventDefault();
        addPoint(getCanvasCoords(e.clientX, e.clientY));
    });
}

// ---- Touch events (mobile) ----
if (canvas) {
    canvas.addEventListener('touchstart', e => {
        e.preventDefault(); // prevent scroll while drawing
        if (e.touches.length === 0) return;
        const touch = e.touches[0];
        addPoint(getCanvasCoords(touch.clientX, touch.clientY));
    }, { passive: false });

    // touchmove: prevent page scroll when finger is on canvas
    canvas.addEventListener('touchmove', e => {
        e.preventDefault();
    }, { passive: false });
}

// ---- Drawing helpers ----
function drawDot(x, y) {
    if (!ctx) return;
    ctx.beginPath();
    ctx.arc(x, y, 6, 0, Math.PI * 2); // slightly larger dot for mobile visibility
    ctx.fillStyle   = '#c89a6c';
    ctx.fill();
    ctx.strokeStyle = '#f0ece6';
    ctx.lineWidth   = 2;
    ctx.stroke();
}

function drawLine(pts) {
    if (!ctx || !pts || pts.length < 2) return;
    ctx.beginPath();
    ctx.moveTo(pts[0].x, pts[0].y);
    ctx.lineTo(pts[1].x, pts[1].y);
    ctx.strokeStyle = '#c89a6c';
    ctx.lineWidth   = 3;
    ctx.stroke();
}

function resetCanvas() {
    points = [];
    if (ctx) ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (canvas) canvas.style.cursor = 'crosshair';
}

function startRun() {
    if (points.length < 2) return;
    // Two points in the same spot define no line β€” the backend would compute a
    // zero-length segment and silently count nothing.
    if (points[0].rx === points[1].rx && points[0].ry === points[1].ry) {
        resetCanvas();
        return;
    }
    const line = [[points[0].rx, points[0].ry], [points[1].rx, points[1].ry]];
    sessionStorage.setItem('funky_run', JSON.stringify({
        video_id: videoId,
        line:     line,
        config:   runConfig
    }));
    sessionStorage.setItem('uf_active_tab', 'settings');
    
    fetch('api/event', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event: 'DRAW_LINE_COMPLETED', meta: { video_id: videoId } })
    }).catch(()=>{});

    window.location.replace('/vehicles');
}

// =============================================
// Onboarding
// =============================================
let _obStep = 0;

function triggerIconPulse() {
    const activeStep = document.querySelector('.onboard-step.active i');
    if (activeStep) {
        activeStep.classList.add('pulse-once');
        setTimeout(() => activeStep.classList.remove('pulse-once'), 400);
    }
}

function nextOnboardStep() {
    _obStep++;
    if (_obStep >= 3) { closeOnboarding(); return; }
    document.querySelectorAll('.onboard-step').forEach((s, i) => s.classList.toggle('active', i === _obStep));
    document.querySelectorAll('.onboard-dot').forEach((d, i)  => d.classList.toggle('active', i === _obStep));
    if (_obStep === 2) document.getElementById('onboard-next').innerText = 'Get Started';
    triggerIconPulse();
}

function closeOnboarding() {
    const overlay = document.getElementById('onboard-overlay');
    if (overlay) overlay.style.display = 'none';
}

function openOnboarding() {
    const onboard = document.getElementById('onboard-overlay');
    if (onboard) {
        _obStep = 0;
        document.querySelectorAll('.onboard-step').forEach((s, i) => s.classList.toggle('active', i === _obStep));
        document.querySelectorAll('.onboard-dot').forEach((d, i)  => d.classList.toggle('active', i === _obStep));
        document.getElementById('onboard-next').innerText = 'Next';
        onboard.style.display = 'flex';
        triggerIconPulse();
    }
}