forked from andrew/feedmill-recounter
fix(ui): harden the frame API and align the OpenCV calibrator
This commit is contained in:
1 parent
c34ac85643
commit
3ede31b554
5 files changed
+136
-9
No files matched your search
@@ -4,6 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
@@ -452,15 +453,19 @@ def api_frame():
|
||||
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
|
||||
if not math.isfinite(t) or t < 0:
|
||||
return jsonify({"error": "invalid t"}), 400
|
||||
path = os.path.join(UPLOAD_DIR, safe)
|
||||
if not os.path.isfile(path):
|
||||
return jsonify({"error": "not found"}), 404
|
||||
try:
|
||||
jpeg = extract_frame_jpeg(path, t, ANALYSIS_SIZE)
|
||||
except ValueError:
|
||||
return jsonify({"error": "invalid t"}), 400
|
||||
except (FileNotFoundError, RuntimeError, OSError) as exc:
|
||||
return jsonify({"error": str(exc)}), 500
|
||||
return Response(jpeg, mimetype="image/jpeg")
|
||||
|
||||
+17
-5
@@ -3,6 +3,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
@@ -13,7 +14,7 @@ def probe_video(video_path: str) -> dict:
|
||||
"""Return video metadata: {width, height, fps, duration, frame_count}."""
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
||||
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
|
||||
try:
|
||||
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
@@ -108,7 +109,7 @@ def extract_thumbnail(
|
||||
"""Extract a single frame as JPEG. Returns the output_path."""
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
||||
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
|
||||
try:
|
||||
fps = cap.get(cv2.CAP_PROP_FPS)
|
||||
if fps > 0:
|
||||
@@ -133,13 +134,24 @@ def extract_frame_jpeg(
|
||||
|
||||
`size` is the analysis frame size (1280x720) so the calibration overlay
|
||||
maps 1:1 onto the pixels the pipeline counts on.
|
||||
|
||||
Raises ValueError when `time_sec` is not a usable seek position (not
|
||||
finite, negative, or so large that the frame index overflows) and
|
||||
FileNotFoundError when the video cannot be opened.
|
||||
"""
|
||||
if not math.isfinite(time_sec) or time_sec < 0:
|
||||
raise ValueError("time_sec must be a finite, non-negative number")
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
||||
raise FileNotFoundError(f"Cannot open video: {os.path.basename(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
|
||||
frame_idx = 0
|
||||
if fps and fps > 0:
|
||||
target = time_sec * fps
|
||||
if not math.isfinite(target):
|
||||
raise ValueError(f"time_sec {time_sec} is out of range for this video")
|
||||
frame_idx = int(target)
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
||||
ret, frame = cap.read()
|
||||
if not ret:
|
||||
@@ -159,7 +171,7 @@ def extract_sample_frames(
|
||||
"""Extract evenly-spaced frames as JPEGs. Returns list of paths."""
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Cannot open video: {video_path}")
|
||||
raise FileNotFoundError(f"Cannot open video: {os.path.basename(video_path)}")
|
||||
try:
|
||||
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
if frame_count <= 0:
|
||||
|
||||
@@ -408,6 +408,12 @@
|
||||
loadPreset(this.value);
|
||||
});
|
||||
$('video-select').addEventListener('change', loadFrame);
|
||||
$('zone-backdrop').addEventListener('error', function () {
|
||||
setStatus('Frame failed to load (corrupt video, or the time is past the end)');
|
||||
});
|
||||
$('zone-backdrop').addEventListener('load', function () {
|
||||
setStatus(zoneEditMode ? 'Editing: drag handles, then Save' : 'Locked');
|
||||
});
|
||||
$('time-slider').addEventListener('input', function () {
|
||||
$('time-label').textContent = (parseFloat(this.value) || 0).toFixed(1) + ' s';
|
||||
if (frameTimer) clearTimeout(frameTimer);
|
||||
|
||||
@@ -976,3 +976,93 @@ def test_api_frame_returns_a_1280x720_jpeg(client, tmp_path, monkeypatch):
|
||||
assert resp.mimetype == "image/jpeg"
|
||||
img = cv2.imdecode(np.frombuffer(resp.data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
assert img.shape[:2] == (720, 1280)
|
||||
|
||||
|
||||
def _write_clip(path):
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
|
||||
for _ in range(5):
|
||||
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
|
||||
writer.release()
|
||||
|
||||
|
||||
def test_api_frame_rejects_an_unusable_time(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
||||
_write_clip(tmp_path / "clip.mp4")
|
||||
|
||||
for bad in ("inf", "-inf", "nan", "1e999", "-1", "abc"):
|
||||
resp = client.get(f"/api/frame?video=clip.mp4&t={bad}")
|
||||
assert resp.status_code == 400, bad
|
||||
assert resp.mimetype == "application/json"
|
||||
assert resp.get_json() == {"error": "invalid t"}
|
||||
|
||||
|
||||
def test_api_frame_error_does_not_leak_the_server_path(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
||||
(tmp_path / "broken.mp4").write_bytes(b"not a video")
|
||||
|
||||
resp = client.get("/api/frame?video=broken.mp4&t=0")
|
||||
assert resp.status_code == 500
|
||||
assert resp.mimetype == "application/json"
|
||||
message = resp.get_json()["error"]
|
||||
assert str(tmp_path) not in message
|
||||
assert "broken.mp4" in message
|
||||
|
||||
|
||||
def test_extract_frame_jpeg_rejects_an_unusable_time(tmp_path):
|
||||
from src.preview import extract_frame_jpeg
|
||||
|
||||
clip = tmp_path / "clip.mp4"
|
||||
_write_clip(clip)
|
||||
|
||||
for bad in (float("inf"), float("-inf"), float("nan"), -1.0):
|
||||
with pytest.raises(ValueError):
|
||||
extract_frame_jpeg(str(clip), bad)
|
||||
|
||||
|
||||
def test_open_cv_calibrator_merges_geometry_and_keeps_tuning_keys():
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"calibrate_zone",
|
||||
Path(__file__).resolve().parents[1] / "tools" / "calibrate_zone.py",
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
stored = {
|
||||
"truck_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
|
||||
"counting_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
|
||||
"palet": [[9, 9], [8, 8], [7, 7], [6, 6]],
|
||||
"count_line": {"x_start": 1, "x_end": 2, "y": 3},
|
||||
"reference_resolution": [1280, 720],
|
||||
"left_limit": 0.27578,
|
||||
"min_valid_area": 15000,
|
||||
}
|
||||
config = {"active_preset": "default", "presets": {"default": dict(stored)}}
|
||||
measured = {
|
||||
"truck_area": [[10, 20], [30, 40], [50, 60], [70, 80]],
|
||||
"counting_area": [[11, 21], [31, 41], [51, 61], [71, 81]],
|
||||
"count_line": {"x_start": 100, "x_end": 200, "y": 150},
|
||||
"reference_resolution": [1280, 720],
|
||||
}
|
||||
|
||||
module.merge_preset(config, "default", measured)
|
||||
|
||||
preset = config["presets"]["default"]
|
||||
# the measured geometry wins ...
|
||||
assert preset["truck_area"] == measured["truck_area"]
|
||||
assert preset["counting_area"] == measured["counting_area"]
|
||||
assert preset["count_line"] == measured["count_line"]
|
||||
assert preset["reference_resolution"] == [1280, 720]
|
||||
# ... the tuning knobs survive
|
||||
assert preset["palet"] == stored["palet"]
|
||||
assert preset["left_limit"] == stored["left_limit"]
|
||||
assert preset["min_valid_area"] == stored["min_valid_area"]
|
||||
+15
-1
@@ -36,6 +36,20 @@ def save_zones(config: dict, path: str):
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def merge_preset(config: dict, preset_name: str, preset: dict) -> None:
|
||||
"""Merge the measured geometry into a preset, keeping its tuning keys.
|
||||
|
||||
Same contract as the web editor's server-side merge
|
||||
(src/zone_config.py save_zone_preset): only the geometry this tool
|
||||
measured is overwritten, so calibrating a shipped preset does not drop
|
||||
its palet or tuning knobs.
|
||||
"""
|
||||
presets = config.setdefault("presets", {})
|
||||
merged = dict(presets.get(preset_name, {}))
|
||||
merged.update(preset)
|
||||
presets[preset_name] = merged
|
||||
|
||||
|
||||
def draw_state(frame, points, current_zone, zone_idx, zone_sizes, zone_names):
|
||||
vis = frame.copy()
|
||||
colors = [(0, 255, 0), (255, 0, 0), (0, 0, 255)]
|
||||
@@ -166,7 +180,7 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
preset["reference_resolution"] = [1280, 720]
|
||||
|
||||
config = load_zones(zones_path)
|
||||
config.setdefault("presets", {})[preset_name] = preset
|
||||
merge_preset(config, preset_name, preset)
|
||||
save_zones(config, zones_path)
|
||||
print(f"Saved preset '{preset_name}' to {zones_path}")
|
||||
cv2.destroyAllWindows()
|
||||
|
||||
Reference in new issue
Block a user