diff --git a/app.py b/app.py index 1afddcf..5645af4 100644 --- a/app.py +++ b/app.py @@ -30,7 +30,10 @@ from src.model_conversion import ( MODEL_UPLOAD_EXTENSIONS, conversion_status_dict, ) -from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height +from src.preview import ( + extract_thumbnail, extract_sample_frames, probe_video, + resize_video_to_max_height, extract_frame_jpeg, +) from src.pipeline import ANALYSIS_SIZE from src.truck_roi import TruckROI from src.validation import ValidationError @@ -437,6 +440,32 @@ def download(job_id, filename): return send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path)) +@app.route("/calibrate") +def calibrate_page(): + """Interactive zone calibration page.""" + return render_template("calibrate.html") + + +@app.route("/api/frame") +def api_frame(): + """One JPEG frame of an uploaded video, resized to the analysis size.""" + safe = secure_filename(request.args.get("video", "")) + if not safe or not safe.lower().endswith(VIDEO_EXTENSIONS): + return jsonify({"error": "invalid filename"}), 400 + path = os.path.join(UPLOAD_DIR, safe) + if not os.path.isfile(path): + return jsonify({"error": "not found"}), 404 + try: + t = float(request.args.get("t", "0")) + except ValueError: + return jsonify({"error": "invalid t"}), 400 + try: + jpeg = extract_frame_jpeg(path, t, ANALYSIS_SIZE) + except (FileNotFoundError, RuntimeError, OSError) as exc: + return jsonify({"error": str(exc)}), 500 + return Response(jpeg, mimetype="image/jpeg") + + @app.route("/api/videos") def api_videos(): """List previously uploaded videos.""" diff --git a/src/preview.py b/src/preview.py index 1dbafe7..fb6fc0e 100644 --- a/src/preview.py +++ b/src/preview.py @@ -126,6 +126,33 @@ def extract_thumbnail( cap.release() +def extract_frame_jpeg( + video_path: str, time_sec: float = 0.0, size: tuple[int, int] = (1280, 720) +) -> bytes: + """Return one frame of the video as JPEG bytes, resized to `size`. + + `size` is the analysis frame size (1280x720) so the calibration overlay + maps 1:1 onto the pixels the pipeline counts on. + """ + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + raise FileNotFoundError(f"Cannot open video: {video_path}") + try: + fps = cap.get(cv2.CAP_PROP_FPS) + frame_idx = int(max(0.0, time_sec) * fps) if fps and fps > 0 else 0 + cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) + ret, frame = cap.read() + if not ret: + raise RuntimeError(f"Could not read frame at {time_sec}s") + frame = cv2.resize(frame, size) + ok, buf = cv2.imencode(".jpg", frame) + if not ok: + raise RuntimeError("Could not encode frame as JPEG") + return buf.tobytes() + finally: + cap.release() + + def extract_sample_frames( video_path: str, output_dir: str, count: int = 6 ) -> list[str]: diff --git a/static/calibrate.js b/static/calibrate.js new file mode 100644 index 0000000..48f2a63 --- /dev/null +++ b/static/calibrate.js @@ -0,0 +1,427 @@ +/* Interactive zone editor. + * + * The backdrop is a frame already resized to the 1280x720 analysis space and + * the SVG overlay uses the same viewBox, so a page pixel maps to an analysis + * pixel with one uniform scale (plus the letterbox offset of "xMidYMid meet"). + */ +(function () { + 'use strict'; + + const ZONE_SOURCE_W = 1280; + const ZONE_SOURCE_H = 720; + const ZONE_LINE_MARGIN = 20; // the counter's trigger band (margin=20) + + const SVG_NS = 'http://www.w3.org/2000/svg'; + + // Area key -> visibility toggle key and colour. + const AREAS = [ + { key: 'counting_area', vis: 'counting', color: '#2563eb' }, + { key: 'truck_area', vis: 'truck', color: '#d97706' } + ]; + + let zonesData = null; + let zoneEditMode = false; + let zoneDrag = null; + const zoneVisibility = { counting: false, truck: false, counting_line: false }; + + let currentPreset = ''; + let frameTimer = null; + + const $ = function (id) { return document.getElementById(id); }; + + function setStatus(text) { + $('zone-status').textContent = text; + } + + function sourcePoint(ev) { + const svg = document.getElementById('zoneOverlay'); + const r = svg.getBoundingClientRect(); + const scale = Math.min(r.width / ZONE_SOURCE_W, r.height / ZONE_SOURCE_H); + const offsetX = (r.width - ZONE_SOURCE_W * scale) / 2; + const offsetY = (r.height - ZONE_SOURCE_H * scale) / 2; + const x = Math.round((ev.clientX - r.left - offsetX) / scale); + const y = Math.round((ev.clientY - r.top - offsetY) / scale); + return { + x: Math.max(0, Math.min(ZONE_SOURCE_W, x)), + y: Math.max(0, Math.min(ZONE_SOURCE_H, y)) + }; + } + + function svgEl(name, attrs) { + const node = document.createElementNS(SVG_NS, name); + Object.keys(attrs).forEach(function (key) { + node.setAttribute(key, attrs[key]); + }); + return node; + } + + function areaByKey(key) { + for (let i = 0; i < AREAS.length; i++) { + if (AREAS[i].key === key) return AREAS[i]; + } + return null; + } + + function makeHandle(id, color, cx, cy, radius, onDown) { + const node = svgEl('circle', { + id: id, cx: cx, cy: cy, r: radius, + fill: color, stroke: '#ffffff', 'stroke-width': '2', + 'vector-effect': 'non-scaling-stroke' + }); + node.classList.add('zone-handle'); + node.style.display = zoneEditMode ? '' : 'none'; + node.style.pointerEvents = zoneEditMode ? 'all' : 'none'; + node.addEventListener('mousedown', onDown); + return node; + } + + function renderZones() { + const layer = $('zoneLayer'); + layer.innerHTML = ''; + syncVisibilityUI(); + if (!zonesData) return; + + AREAS.forEach(function (area) { + const pts = zonesData[area.key]; + if (!zoneVisibility[area.vis] || !Array.isArray(pts) || pts.length < 3) return; + layer.appendChild(svgEl('polygon', { + id: 'zp-' + area.vis, + points: pts.map(function (p) { return p[0] + ',' + p[1]; }).join(' '), + fill: area.color + '22', + stroke: area.color, + 'stroke-width': '3', + 'vector-effect': 'non-scaling-stroke' + })); + pts.forEach(function (pt, i) { + layer.appendChild(makeHandle( + 'zh-' + area.vis + '-' + i, area.color, pt[0], pt[1], 8, + function (ev) { startZoneDrag(ev, area.key, 'poly', i); } + )); + }); + }); + + const line = zonesData.counting_line; + if (zoneVisibility.counting_line && Array.isArray(line) && line.length === 2) { + const lineY = Math.round((line[0][1] + line[1][1]) / 2); + line[0][1] = lineY; + line[1][1] = lineY; + const xMin = Math.min(line[0][0], line[1][0]); + const xMax = Math.max(line[0][0], line[1][0]); + const bandTop = Math.max(0, lineY - ZONE_LINE_MARGIN); + const bandBottom = Math.min(ZONE_SOURCE_H, lineY + ZONE_LINE_MARGIN); + + const band = svgEl('rect', { + id: 'zb-counting', x: xMin, y: bandTop, + width: Math.max(1, xMax - xMin), height: Math.max(1, bandBottom - bandTop), + fill: 'rgba(22, 163, 74, 0.16)', stroke: '#16a34a', + 'stroke-width': '1.5', 'stroke-dasharray': '6,4', + 'vector-effect': 'non-scaling-stroke' + }); + band.style.pointerEvents = 'none'; + layer.appendChild(band); + + const stroke = svgEl('line', { + id: 'zl-counting', x1: line[0][0], y1: lineY, x2: line[1][0], y2: lineY, + stroke: '#16a34a', 'stroke-width': '4', 'vector-effect': 'non-scaling-stroke' + }); + stroke.style.pointerEvents = 'none'; + layer.appendChild(stroke); + + line.forEach(function (pt, i) { + layer.appendChild(makeHandle( + 'zh-line-' + i, '#16a34a', pt[0], lineY, 9, + function (ev) { startZoneDrag(ev, 'counting_line', 'line', i); } + )); + }); + } + } + + function startZoneDrag(ev, key, kind, index) { + if (!zoneEditMode) return; + ev.preventDefault(); + ev.stopPropagation(); + zoneDrag = { key: key, kind: kind, index: index }; + document.addEventListener('mousemove', onZoneDrag); + document.addEventListener('mouseup', endZoneDrag); + } + + function onZoneDrag(ev) { + if (!zoneDrag) return; + const pt = sourcePoint(ev); + const info = zoneDrag; + if (info.kind === 'poly') { + zonesData[info.key][info.index] = [pt.x, pt.y]; + const area = areaByKey(info.key); + const poly = document.getElementById('zp-' + area.vis); + if (poly) { + poly.setAttribute('points', zonesData[info.key].map(function (p) { + return p[0] + ',' + p[1]; + }).join(' ')); + } + const handle = document.getElementById('zh-' + area.vis + '-' + info.index); + if (handle) { + handle.setAttribute('cx', pt.x); + handle.setAttribute('cy', pt.y); + } + return; + } + + // The count line stays horizontal: the dragged endpoint sets x, and + // both endpoints take the dragged y. + const line = zonesData.counting_line; + line[info.index][0] = pt.x; + line[0][1] = pt.y; + line[1][1] = pt.y; + const x0 = line[0][0]; + const x1 = line[1][0]; + const bandTop = Math.max(0, pt.y - ZONE_LINE_MARGIN); + const bandBottom = Math.min(ZONE_SOURCE_H, pt.y + ZONE_LINE_MARGIN); + const band = document.getElementById('zb-counting'); + if (band) { + band.setAttribute('x', Math.min(x0, x1)); + band.setAttribute('y', bandTop); + band.setAttribute('width', Math.max(1, Math.abs(x1 - x0))); + band.setAttribute('height', Math.max(1, bandBottom - bandTop)); + } + const stroke = document.getElementById('zl-counting'); + if (stroke) { + stroke.setAttribute('x1', x0); + stroke.setAttribute('y1', pt.y); + stroke.setAttribute('x2', x1); + stroke.setAttribute('y2', pt.y); + } + ['zh-line-0', 'zh-line-1'].forEach(function (id, i) { + const handle = document.getElementById(id); + if (!handle) return; + handle.setAttribute('cx', i === 0 ? x0 : x1); + handle.setAttribute('cy', pt.y); + }); + } + + function endZoneDrag() { + zoneDrag = null; + document.removeEventListener('mousemove', onZoneDrag); + document.removeEventListener('mouseup', endZoneDrag); + } + + function syncVisibilityUI() { + const buttons = { + counting: 'zone-vis-counting', + truck: 'zone-vis-truck', + counting_line: 'zone-vis-line' + }; + Object.keys(buttons).forEach(function (key) { + const btn = $(buttons[key]); + if (!btn) return; + const visible = Boolean(zoneVisibility[key]); + btn.setAttribute('aria-pressed', visible ? 'true' : 'false'); + }); + const all = Object.keys(buttons).every(function (key) { return zoneVisibility[key]; }); + const global = $('zone-vis-all-btn'); + if (global) { + global.setAttribute('aria-pressed', all ? 'true' : 'false'); + global.textContent = all ? 'Hide All ROIs' : 'Show All ROIs'; + } + } + + function toggleZoneEdit() { + zoneEditMode = !zoneEditMode; + if (zoneEditMode && !zoneVisibility.counting && !zoneVisibility.truck + && !zoneVisibility.counting_line) { + zoneVisibility.counting = true; + zoneVisibility.truck = true; + zoneVisibility.counting_line = true; + } + $('zone-edit-btn').textContent = zoneEditMode ? 'Lock Edit' : 'Unlock Edit'; + setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked'); + renderZones(); + } + + function toggleZoneItemVisibility(key) { + if (!(key in zoneVisibility)) return; + zoneVisibility[key] = !zoneVisibility[key]; + renderZones(); + } + + function toggleAllZoneVisibility() { + const all = Object.keys(zoneVisibility).every(function (key) { return zoneVisibility[key]; }); + Object.keys(zoneVisibility).forEach(function (key) { + zoneVisibility[key] = !all; + }); + renderZones(); + } + + function applyPreset(preset) { + const line = (preset && preset.count_line) || {}; + zonesData = { + truck_area: (preset && preset.truck_area) || [], + counting_area: (preset && preset.counting_area) || [], + counting_line: [ + [Number(line.x_start) || 0, Number(line.y) || 0], + [Number(line.x_end) || 0, Number(line.y) || 0] + ] + }; + renderZones(); + } + + async function loadPreset(name) { + currentPreset = name; + try { + const res = await fetch('/api/zones/' + encodeURIComponent(name)); + const data = await res.json(); + if (!res.ok) { + setStatus('Load failed: ' + (data.error || res.status)); + return; + } + applyPreset(data.preset || {}); + setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked'); + } catch (err) { + setStatus('Load failed'); + } + } + + async function saveZones() { + if (!zonesData || !currentPreset) { + setStatus('Nothing to save'); + return; + } + const xs = zonesData.counting_line.map(function (p) { return p[0]; }); + const ys = zonesData.counting_line.map(function (p) { return p[1]; }); + const payload = { + preset: { + truck_area: zonesData.truck_area, + counting_area: zonesData.counting_area, + count_line: { + x_start: Math.min.apply(null, xs), + x_end: Math.max.apply(null, xs), + y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length) + }, + reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H] + } + }; + try { + const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + const data = await res.json().catch(function () { return {}; }); + if (!res.ok) { + setStatus('Save failed: ' + (data.error || res.status)); + return; + } + await loadPreset(currentPreset); + setStatus('Saved to zones.json'); + } catch (err) { + setStatus('Save failed'); + } + } + + async function resetZones() { + if (!currentPreset) return; + try { + const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset) + '/reset', { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }); + const data = await res.json().catch(function () { return {}; }); + if (!res.ok) { + setStatus('Reset failed: ' + (data.error || res.status)); + return; + } + applyPreset(data.preset || {}); + setStatus('Reset to the shipped default'); + } catch (err) { + setStatus('Reset failed'); + } + } + + function loadFrame() { + const video = $('video-select').value; + if (!video) return; + const t = parseFloat($('time-slider').value) || 0; + $('zone-backdrop').src = '/api/frame?video=' + encodeURIComponent(video) + '&t=' + t; + } + + async function loadVideos() { + const select = $('video-select'); + try { + const res = await fetch('/api/videos'); + const videos = await res.json(); + select.innerHTML = ''; + videos.forEach(function (video) { + const option = document.createElement('option'); + option.value = video.filename; + option.textContent = video.filename; + select.appendChild(option); + }); + if (!videos.length) { + setStatus('No videos uploaded yet'); + return; + } + loadFrame(); + } catch (err) { + setStatus('Could not load the video list'); + } + } + + async function loadPresets() { + const select = $('preset-select'); + try { + const res = await fetch('/api/zones'); + const presets = await res.json(); + select.innerHTML = ''; + presets.forEach(function (preset) { + const option = document.createElement('option'); + option.value = preset.name; + option.textContent = preset.name; + select.appendChild(option); + }); + if (!presets.length) { + setStatus('No zone presets found'); + return; + } + await loadPreset(presets[0].name); + } catch (err) { + setStatus('Could not load the zone presets'); + } + } + + function init() { + $('zone-edit-btn').addEventListener('click', toggleZoneEdit); + $('zone-save-btn').addEventListener('click', saveZones); + $('zone-reload-btn').addEventListener('click', function () { + if (currentPreset) loadPreset(currentPreset); + }); + $('zone-reset-btn').addEventListener('click', resetZones); + $('zone-vis-all-btn').addEventListener('click', toggleAllZoneVisibility); + $('zone-vis-counting').addEventListener('click', function () { + toggleZoneItemVisibility('counting'); + }); + $('zone-vis-truck').addEventListener('click', function () { + toggleZoneItemVisibility('truck'); + }); + $('zone-vis-line').addEventListener('click', function () { + toggleZoneItemVisibility('counting_line'); + }); + $('preset-select').addEventListener('change', function () { + loadPreset(this.value); + }); + $('video-select').addEventListener('change', loadFrame); + $('time-slider').addEventListener('input', function () { + $('time-label').textContent = (parseFloat(this.value) || 0).toFixed(1) + ' s'; + if (frameTimer) clearTimeout(frameTimer); + frameTimer = setTimeout(loadFrame, 150); + }); + + renderZones(); + loadPresets(); + loadVideos(); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init); + } else { + init(); + } +})(); diff --git a/static/style.css b/static/style.css index d7d8c8c..7ae249e 100644 --- a/static/style.css +++ b/static/style.css @@ -1205,3 +1205,100 @@ main { max-width: 1024px; } } + +/* ---------- Zone calibration page ---------- */ +.calibrate-heading { + margin-bottom: var(--space-4); +} + +.calibrate-heading h2 { + margin-bottom: var(--space-1); +} + +.calibrate-heading p { + color: var(--color-neutral-500); + font-size: var(--text-sm); +} + +.calibrate-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + padding: var(--space-4); + margin-bottom: var(--space-3); + background: #fff; + border: 1px solid var(--color-neutral-200); + border-radius: var(--radius-lg); +} + +.calibrate-toolbar label { + font-size: var(--text-sm); + font-weight: var(--font-semibold); + color: var(--color-neutral-600); +} + +.calibrate-toolbar select { + max-width: 200px; +} + +.calibrate-toolbar input[type="range"] { + width: 170px; +} + +#time-label { + min-width: 3.5rem; + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; + color: var(--color-neutral-600); +} + +.calibrate-status { + margin-left: auto; + font-size: var(--text-sm); + color: var(--color-neutral-600); +} + +#zone-legend { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + margin-bottom: var(--space-3); +} + +#zone-legend .btn[aria-pressed="true"], +#zone-vis-all-btn[aria-pressed="true"] { + background: var(--color-primary); + color: #fff; + border-color: var(--color-primary); +} + +.calibrate-stage { + position: relative; + width: 100%; + aspect-ratio: 16 / 9; + overflow: hidden; + background: var(--color-neutral-900); + border: 1px solid var(--color-neutral-200); + border-radius: var(--radius-lg); +} + +#zone-backdrop { + position: relative; + display: block; + width: 100%; + height: 100%; + object-fit: contain; +} + +#zoneOverlay { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + pointer-events: none; +} + +#zoneOverlay .zone-handle { + cursor: grab; +} diff --git a/templates/calibrate.html b/templates/calibrate.html new file mode 100644 index 0000000..3ee83ba --- /dev/null +++ b/templates/calibrate.html @@ -0,0 +1,47 @@ +{% extends "base.html" %} +{% block title %}Calibrate Zones - Feedmill Recounter{% endblock %} + +{% block content %} +
Drag the counting area, truck area and count line over a frame of an uploaded video, then save. + Every coordinate is in the 1280×720 analysis space.
+