feat: count against calibrated static zone by default (FCP parity)

This commit is contained in:
jetson committed 2026-10-27 13:51:08 +07:00
1 parent 354b1b3148
commit f4e7b5da49
4 files changed
+131 -20

No files matched your search

+25 -17
View File
@@ -127,7 +127,7 @@ def upload():
job = _save_and_queue( job = _save_and_queue(
video, model_configs, class_filters, video, model_configs, class_filters,
request.form.get("output_height", ""), request.form.get("output_height", ""),
request.form.get("zone_mode", "dynamic"), request.form.get("zone_mode", "fixed"),
request.form.get("zone_preset", ""), request.form.get("zone_preset", ""),
) )
return redirect(url_for("status", job_id=job.job_id)) return redirect(url_for("status", job_id=job.job_id))
@@ -142,6 +142,24 @@ def _static_roi(zone: dict) -> TruckROI:
return build_static_roi(zone, *ANALYSIS_SIZE) return build_static_roi(zone, *ANALYSIS_SIZE)
def _resolve_zone(zone_mode: str, zone_preset: str) -> tuple[str, TruckROI | None, str]:
"""Resolve the counting zone of a job.
Returns (zone_mode, fixed_zone, zone_preset). "fixed" needs a calibrated
preset on disk; without one the job falls back to "dynamic" so an
uncalibrated deployment still runs (FCP always counts on its calibrated
line, so "fixed" is the default).
"""
if zone_mode != "fixed":
return zone_mode, None, zone_preset
zone = None
if os.path.isfile(ZONES_PATH):
zone = get_active_zone(ZONES_PATH, zone_preset or None)
if zone is None:
return "dynamic", None, zone_preset
return "fixed", _static_roi(zone), zone_preset or "default"
def _save_and_queue(video, model_configs, class_filters, def _save_and_queue(video, model_configs, class_filters,
output_height, zone_mode, zone_preset): output_height, zone_mode, zone_preset):
"""Save upload (collision-safe), transcode to 720p, resolve fixed zone, """Save upload (collision-safe), transcode to 720p, resolve fixed zone,
@@ -160,12 +178,7 @@ def _save_and_queue(video, model_configs, class_filters,
# Transcode to 720p max height to save storage and speed up processing # Transcode to 720p max height to save storage and speed up processing
video_path = resize_video_to_max_height(video_path, max_height=720) video_path = resize_video_to_max_height(video_path, max_height=720)
fixed_zone = None zone_mode, fixed_zone, zone_preset = _resolve_zone(zone_mode, zone_preset)
if zone_mode == "fixed" and os.path.isfile(ZONES_PATH):
zone = get_active_zone(ZONES_PATH, zone_preset or None)
if zone:
fixed_zone = _static_roi(zone)
zone_preset = zone_preset or "default"
return job_queue.add_job( return job_queue.add_job(
video_path=video_path, video_path=video_path,
@@ -267,7 +280,7 @@ def api_analyze():
job = _save_and_queue( job = _save_and_queue(
video, model_configs, class_filters, video, model_configs, class_filters,
request.form.get("output_height", ""), request.form.get("output_height", ""),
request.form.get("zone_mode", "dynamic"), request.form.get("zone_mode", "fixed"),
request.form.get("zone_preset", ""), request.form.get("zone_preset", ""),
) )
return jsonify({"job_id": job.job_id, return jsonify({"job_id": job.job_id,
@@ -291,15 +304,10 @@ def upload_reuse():
return "No models selected", 400 return "No models selected", 400
output_height = request.form.get("output_height", "") output_height = request.form.get("output_height", "")
zone_mode = request.form.get("zone_mode", "dynamic") zone_mode = request.form.get("zone_mode", "fixed")
fixed_zone = None zone_mode, fixed_zone, zone_preset = _resolve_zone(
zone_preset = "" zone_mode, request.form.get("zone_preset", "")
if zone_mode == "fixed" and os.path.isfile(ZONES_PATH): )
preset_name = request.form.get("zone_preset", "")
zone = get_active_zone(ZONES_PATH, preset_name or None)
if zone:
fixed_zone = _static_roi(zone)
zone_preset = preset_name or "default"
job = job_queue.add_job( job = job_queue.add_job(
video_path=video_path, video_path=video_path,
+2 -2
View File
@@ -69,7 +69,7 @@ class Job:
live_box_unloading: int = 0 live_box_unloading: int = 0
live_frame: int = 0 live_frame: int = 0
preview_enabled: bool = True preview_enabled: bool = True
zone_mode: str = "dynamic" zone_mode: str = "fixed"
fixed_zone: TruckROI | None = None fixed_zone: TruckROI | None = None
zone_preset: str = "" zone_preset: str = ""
output_max_height: int | None = None output_max_height: int | None = None
@@ -119,7 +119,7 @@ class JobQueue:
model_configs: list[ModelConfig], model_configs: list[ModelConfig],
class_filters: dict[str, list[str] | None] | None = None, class_filters: dict[str, list[str] | None] | None = None,
source_stem: str = "", source_stem: str = "",
zone_mode: str = "dynamic", zone_mode: str = "fixed",
fixed_zone: TruckROI | None = None, fixed_zone: TruckROI | None = None,
zone_preset: str = "", zone_preset: str = "",
output_max_height: int | None = None, output_max_height: int | None = None,
+1 -1
View File
@@ -104,7 +104,7 @@ def test_analyze_fcp_mode_c_resolves_stems_and_returns_202(client, stub_queue):
"v4-best", "v4-best",
"yolo11n-bbox-100ep-sack+box-20260909-best", "yolo11n-bbox-100ep-sack+box-20260909-best",
] ]
assert stub_queue[0]["zone_mode"] == "dynamic" assert stub_queue[0]["zone_mode"] == "fixed"
def test_analyze_fcp_mode_a_single_model(client, stub_queue): def test_analyze_fcp_mode_a_single_model(client, stub_queue):
+103
View File
@@ -1,6 +1,7 @@
"""Integration tests for Flask web app.""" """Integration tests for Flask web app."""
import io import io
import json
import pytest import pytest
from app import app from app import app
@@ -347,3 +348,105 @@ def test_zone_roi_is_built_at_1280x720():
assert roi.line_y == 220 assert roi.line_y == 220
assert (roi.x1, roi.x2) == (400, 936) assert (roi.x1, roi.x2) == (400, 936)
# ── Zone mode default: calibrated static zone (FCP parity) ───────────────
ZONE_JSON = {
"active_preset": "default",
"presets": {"default": FCP_ZONE},
}
@pytest.fixture
def buf(tmp_path):
"""A tiny valid mp4 as an in-memory upload stream."""
import cv2
import numpy as np
path = tmp_path / "tiny.mp4"
writer = cv2.VideoWriter(
str(path), cv2.VideoWriter_fourcc(*"mp4v"), 5.0, (64, 64)
)
for i in range(5):
writer.write(np.full((64, 64, 3), i * 20, dtype=np.uint8))
writer.release()
return io.BytesIO(path.read_bytes())
@pytest.fixture
def analyze_env(tmp_path, monkeypatch):
"""Isolate /api/analyze: uploads land in tmp_path, no real model runs."""
import os
import app as app_module
import src.job as job_mod
uploads = tmp_path / "uploads"
os.makedirs(uploads, exist_ok=True)
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(uploads))
class _Result:
output_path = "annotated.mp4"
loading_count = 0
unloading_count = 0
net_count = 0
batch_count = 0
frame_count = 0
duration_seconds = 0.0
box_loading_count = 0
box_unloading_count = 0
box_net_count = 0
monkeypatch.setattr(job_mod, "run_pipeline", lambda **kw: _Result())
monkeypatch.setattr(job_mod, "run_merged_pipeline", lambda **kw: _Result())
return app_module
def _wait_job_done(job, timeout=10.0):
"""Block until the job leaves PENDING/RUNNING (keeps the stub in place)."""
import time
from src.job import JobStatus
deadline = time.time() + timeout
while job.status in (JobStatus.PENDING, JobStatus.RUNNING):
assert time.time() < deadline, "job never finished"
time.sleep(0.01)
def test_analyze_defaults_to_fixed_zone_mode(client, buf, analyze_env, tmp_path, monkeypatch):
"""POST /api/analyze without zone_mode uses the calibrated static zone."""
app_module = analyze_env
zones = tmp_path / "zones.json"
zones.write_text(json.dumps(ZONE_JSON))
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post(
"/api/analyze",
data={"fcp_mode": "C", "video": (buf, "clip.mp4")},
content_type="multipart/form-data",
)
assert resp.status_code == 202
job = app_module.job_queue.get_job(resp.get_json()["job_id"])
assert job.zone_mode == "fixed"
assert job.fixed_zone is not None
assert job.fixed_zone.fixed is True
_wait_job_done(job)
def test_analyze_falls_back_to_dynamic_without_zone_file(client, buf, analyze_env, tmp_path, monkeypatch):
"""No calibration on disk -> dynamic zone, job still accepted."""
app_module = analyze_env
monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json"))
resp = client.post(
"/api/analyze",
data={"fcp_mode": "C", "video": (buf, "clip.mp4")},
content_type="multipart/form-data",
)
assert resp.status_code == 202
job = app_module.job_queue.get_job(resp.get_json()["job_id"])
assert job.zone_mode == "dynamic"
assert job.fixed_zone is None
_wait_job_done(job)