feat: POST /api/analyze machine endpoint (fcp_mode, 202/409/401)
- /api/analyze: multipart video + fcp_mode letter (A-D) or explicit
model_stems; 202 {job_id,status_url}; 409 busy guard (one GPU);
optional X-API-Key auth iff env RECOUNTER_API_KEY set
- config.yaml fcp.mode_models: FCP mode -> recounter stems (mirrors
platform models.modes; C = current active_mode)
- extract _save_and_queue from /upload (save/transcode/zone/job);
/upload behavior unchanged
- fix src/job.py: single-model class_filter looked up by filename,
stem-keyed filters were silently dropped
This commit is contained in:
1 parent
97507f8bf8
commit
540e1b5dcd
5 files changed
+372
-10
No files matched your search
@@ -122,7 +122,20 @@ def upload():
|
||||
if not model_configs:
|
||||
return "No models selected", 400
|
||||
|
||||
video_path = os.path.join(UPLOAD_DIR, safe_name)
|
||||
job = _save_and_queue(
|
||||
video, model_configs, class_filters,
|
||||
request.form.get("output_height", ""),
|
||||
request.form.get("zone_mode", "dynamic"),
|
||||
request.form.get("zone_preset", ""),
|
||||
)
|
||||
return redirect(url_for("status", job_id=job.job_id))
|
||||
|
||||
|
||||
def _save_and_queue(video, model_configs, class_filters,
|
||||
output_height, zone_mode, zone_preset):
|
||||
"""Save upload (collision-safe), transcode to 720p, resolve fixed zone,
|
||||
enqueue job. Shared by /upload and /api/analyze."""
|
||||
video_path = os.path.join(UPLOAD_DIR, secure_filename(video.filename))
|
||||
base, ext = os.path.splitext(video_path)
|
||||
n = 1
|
||||
while os.path.exists(video_path):
|
||||
@@ -133,13 +146,9 @@ def upload():
|
||||
# Transcode to 720p max height to save storage and speed up processing
|
||||
video_path = resize_video_to_max_height(video_path, max_height=720)
|
||||
|
||||
output_height = request.form.get("output_height", "")
|
||||
zone_mode = request.form.get("zone_mode", "dynamic")
|
||||
fixed_zone = None
|
||||
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)
|
||||
zone = get_active_zone(ZONES_PATH, zone_preset or None)
|
||||
if zone:
|
||||
import cv2
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
@@ -147,9 +156,9 @@ def upload():
|
||||
vh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
cap.release()
|
||||
fixed_zone = build_static_roi(zone, vw, vh)
|
||||
zone_preset = preset_name or "default"
|
||||
zone_preset = zone_preset or "default"
|
||||
|
||||
job = job_queue.add_job(
|
||||
return job_queue.add_job(
|
||||
video_path=video_path,
|
||||
model_configs=model_configs,
|
||||
class_filters=class_filters,
|
||||
@@ -158,7 +167,84 @@ def upload():
|
||||
zone_preset=zone_preset,
|
||||
output_max_height=(int(output_height) if output_height else None),
|
||||
)
|
||||
return redirect(url_for("status", job_id=job.job_id))
|
||||
|
||||
|
||||
def _resolve_fcp_mode(mode: str):
|
||||
"""Map an FCP model-mode letter to ModelConfigs via config.yaml fcp.mode_models.
|
||||
|
||||
Returns (model_configs, error). error is None on success; model_configs
|
||||
is None when the letter is unknown or a mapped stem is missing on disk.
|
||||
"""
|
||||
from src.config import load_config
|
||||
|
||||
mode = (mode or "").strip().upper()
|
||||
mapping = (load_config().get("fcp") or {}).get("mode_models") or {}
|
||||
stems = mapping.get(mode)
|
||||
if not stems:
|
||||
return None, f"unknown fcp_mode: {mode!r} (valid: {', '.join(sorted(mapping))})"
|
||||
groups = {g.stem: g for g in scan_model_groups(MODELS_DIR)}
|
||||
configs = []
|
||||
for stem in stems:
|
||||
group = groups.get(stem)
|
||||
if group is None:
|
||||
return None, f"fcp_mode {mode!r} maps to stem {stem!r} not found under {MODELS_DIR}"
|
||||
configs.append(ModelConfig(
|
||||
filename=os.path.basename(group.format_paths[group.default_format]),
|
||||
path=group.format_paths[group.default_format],
|
||||
stem=stem,
|
||||
known_classes=list(group.known_classes),
|
||||
))
|
||||
return configs, None
|
||||
|
||||
|
||||
@app.route("/api/analyze", methods=["POST"])
|
||||
def api_analyze():
|
||||
"""Machine-facing analyze: multipart video + fcp_mode (or model_stems).
|
||||
|
||||
Optional auth: X-API-Key header required iff env RECOUNTER_API_KEY set.
|
||||
202 on accept, 400 validation, 401 bad key, 409 when another job is
|
||||
pending/running (one GPU — serializes external callers).
|
||||
"""
|
||||
key = os.getenv("RECOUNTER_API_KEY")
|
||||
if key and request.headers.get("X-API-Key") != key:
|
||||
return jsonify({"error": "unauthorized"}), 401
|
||||
|
||||
video = request.files.get("video")
|
||||
if not video or not video.filename:
|
||||
return jsonify({"error": "No video uploaded"}), 400
|
||||
safe_name = secure_filename(video.filename)
|
||||
if not safe_name or not safe_name.lower().endswith(VIDEO_EXTENSIONS):
|
||||
return jsonify({"error": "Invalid video file type"}), 400
|
||||
|
||||
active = [
|
||||
{"job_id": j.job_id, "status": j.status.name}
|
||||
for j in job_queue.list_jobs()
|
||||
if j.status.name in ("PENDING", "RUNNING")
|
||||
]
|
||||
if active:
|
||||
return jsonify({"error": "busy", "active": active}), 409
|
||||
|
||||
fcp_mode = request.form.get("fcp_mode", "")
|
||||
if fcp_mode:
|
||||
model_configs, err = _resolve_fcp_mode(fcp_mode)
|
||||
if err:
|
||||
return jsonify({"error": err}), 400
|
||||
class_filters: dict = {}
|
||||
else:
|
||||
model_configs, class_filters = _parse_model_configs(request.form)
|
||||
if not model_configs:
|
||||
return jsonify({
|
||||
"error": "No models selected (send fcp_mode or model_stems)",
|
||||
}), 400
|
||||
|
||||
job = _save_and_queue(
|
||||
video, model_configs, class_filters,
|
||||
request.form.get("output_height", ""),
|
||||
request.form.get("zone_mode", "dynamic"),
|
||||
request.form.get("zone_preset", ""),
|
||||
)
|
||||
return jsonify({"job_id": job.job_id,
|
||||
"status_url": f"/api/jobs/{job.job_id}"}), 202
|
||||
|
||||
|
||||
@app.route("/upload/reuse", methods=["POST"])
|
||||
|
||||
+10
@@ -35,3 +35,13 @@ pipeline:
|
||||
sup_det_interval: 5 # supplementary models every N frames
|
||||
truck_det_interval: 15 # truck ROI detection every N frames
|
||||
preview_every_n: 5 # preview JPEG every N frames
|
||||
|
||||
fcp:
|
||||
# FCP model-mode letter -> recounter model stems, for POST /api/analyze
|
||||
# (mirrors karung_counter_semarang config.yaml models.modes semantics;
|
||||
# C = platform's current active_mode).
|
||||
mode_models:
|
||||
A: [v4-best]
|
||||
B: [truck-detector, "yolo11n-bbox-100ep-sack+box-20260909-best"]
|
||||
C: [v4-best, "yolo11n-bbox-100ep-sack+box-20260909-best"]
|
||||
D: [truck-detector, best, "yolo11n-bbox-100ep-sack+box-20260909-best"]
|
||||
@@ -46,6 +46,16 @@ DEFAULTS: dict = {
|
||||
"truck_det_interval": 15,
|
||||
"preview_every_n": 5,
|
||||
},
|
||||
"fcp": {
|
||||
# FCP model-mode letter -> recounter model stems (mirrors
|
||||
# karung_counter_semarang config.yaml models.modes semantics).
|
||||
"mode_models": {
|
||||
"A": ["v4-best"],
|
||||
"B": ["truck-detector", "yolo11n-bbox-100ep-sack+box-20260909-best"],
|
||||
"C": ["v4-best", "yolo11n-bbox-100ep-sack+box-20260909-best"],
|
||||
"D": ["truck-detector", "best", "yolo11n-bbox-100ep-sack+box-20260909-best"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
+4
-1
@@ -221,7 +221,10 @@ class JobQueue:
|
||||
if total_models == 1:
|
||||
# Single model: use existing run_pipeline
|
||||
model_cfg = job.model_configs[0]
|
||||
class_filter = job.class_filters.get(model_cfg.filename)
|
||||
# stem is the UI/API key; filename kept for legacy callers
|
||||
class_filter = job.class_filters.get(
|
||||
model_cfg.stem, job.class_filters.get(model_cfg.filename)
|
||||
)
|
||||
truck_model_config = None
|
||||
if "truck" not in (model_cfg.known_classes or []):
|
||||
truck_model_config = find_truck_detector("./models")
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Tests for POST /api/analyze — machine-facing upload endpoint.
|
||||
|
||||
Route logic (auth, busy guard, fcp_mode → stems, 202 shape) is tested with
|
||||
_save_and_queue stubbed; the shared save/transcode path is /upload's, covered
|
||||
by manual smoke tests (real ffmpeg on real video).
|
||||
"""
|
||||
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from app import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app.config["TESTING"] = True
|
||||
with app.test_client() as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stub_queue(monkeypatch):
|
||||
"""Replace _save_and_queue; record calls, return fake job."""
|
||||
import app as app_module
|
||||
|
||||
calls = []
|
||||
|
||||
class _FakeJob:
|
||||
job_id = "job-deadbeef"
|
||||
|
||||
def fake_save_and_queue(video, model_configs, class_filters,
|
||||
output_height, zone_mode, zone_preset):
|
||||
calls.append({
|
||||
"model_configs": model_configs,
|
||||
"class_filters": class_filters,
|
||||
"output_height": output_height,
|
||||
"zone_mode": zone_mode,
|
||||
"zone_preset": zone_preset,
|
||||
})
|
||||
return _FakeJob()
|
||||
|
||||
monkeypatch.setattr(app_module, "_save_and_queue", fake_save_and_queue)
|
||||
return calls
|
||||
|
||||
|
||||
def _post(client, data=None, headers=None):
|
||||
return client.post(
|
||||
"/api/analyze",
|
||||
data=data or {},
|
||||
content_type="multipart/form-data",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
# ── validation (JSON 400s, never HTML) ─────────────────────────────────
|
||||
|
||||
|
||||
def test_analyze_no_video_returns_json_400(client, stub_queue):
|
||||
resp = _post(client, data={"fcp_mode": "C"})
|
||||
assert resp.status_code == 400
|
||||
assert resp.get_json()["error"] == "No video uploaded"
|
||||
|
||||
|
||||
def test_analyze_bad_extension_rejected(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "notes.txt"),
|
||||
"fcp_mode": "C",
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "Invalid" in resp.get_json()["error"]
|
||||
|
||||
|
||||
def test_analyze_unknown_fcp_mode_rejected(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "Z",
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "fcp_mode" in resp.get_json()["error"]
|
||||
|
||||
|
||||
def test_analyze_requires_model_selection(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "model" in resp.get_json()["error"].lower()
|
||||
|
||||
|
||||
# ── happy path: fcp_mode resolution + 202 shape ────────────────────────
|
||||
|
||||
|
||||
def test_analyze_fcp_mode_c_resolves_stems_and_returns_202(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
})
|
||||
assert resp.status_code == 202
|
||||
body = resp.get_json()
|
||||
assert body["job_id"] == "job-deadbeef"
|
||||
assert body["status_url"] == "/api/jobs/job-deadbeef"
|
||||
stems = [c.stem for c in stub_queue[0]["model_configs"]]
|
||||
assert stems == [
|
||||
"v4-best",
|
||||
"yolo11n-bbox-100ep-sack+box-20260909-best",
|
||||
]
|
||||
assert stub_queue[0]["zone_mode"] == "dynamic"
|
||||
|
||||
|
||||
def test_analyze_fcp_mode_a_single_model(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "A",
|
||||
})
|
||||
assert resp.status_code == 202
|
||||
stems = [c.stem for c in stub_queue[0]["model_configs"]]
|
||||
assert stems == ["v4-best"]
|
||||
|
||||
|
||||
def test_analyze_explicit_stems_override_mode(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"model_stems": ["best"],
|
||||
})
|
||||
assert resp.status_code == 202
|
||||
stems = [c.stem for c in stub_queue[0]["model_configs"]]
|
||||
assert stems == ["best"]
|
||||
|
||||
|
||||
def test_analyze_zone_mode_fixed_passthrough(client, stub_queue):
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
"zone_mode": "freeze",
|
||||
"output_height": "720",
|
||||
})
|
||||
assert resp.status_code == 202
|
||||
assert stub_queue[0]["zone_mode"] == "freeze"
|
||||
assert stub_queue[0]["output_height"] == "720"
|
||||
|
||||
|
||||
# ── busy guard (GPU OOM protection) ────────────────────────────────────
|
||||
|
||||
|
||||
def test_analyze_busy_returns_409(client, stub_queue):
|
||||
import app as app_module
|
||||
from src.job import JobStatus
|
||||
|
||||
job = app_module.job_queue.add_job(
|
||||
video_path="/tmp/x.mp4", model_configs=[]
|
||||
)
|
||||
import time
|
||||
time.sleep(0.1)
|
||||
with app_module.job_queue._lock:
|
||||
job.status = JobStatus.RUNNING
|
||||
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
})
|
||||
assert resp.status_code == 409
|
||||
body = resp.get_json()
|
||||
assert body["error"] == "busy"
|
||||
assert any(j["job_id"] == job.job_id for j in body["active"])
|
||||
|
||||
|
||||
# ── optional API-key auth ──────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_analyze_open_when_key_env_unset(client, stub_queue, monkeypatch):
|
||||
monkeypatch.delenv("RECOUNTER_API_KEY", raising=False)
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
})
|
||||
assert resp.status_code == 202
|
||||
|
||||
|
||||
def test_analyze_401_when_key_required_and_header_missing(
|
||||
client, stub_queue, monkeypatch
|
||||
):
|
||||
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
})
|
||||
assert resp.status_code == 401
|
||||
assert resp.get_json()["error"] == "unauthorized"
|
||||
|
||||
|
||||
def test_analyze_401_on_wrong_key(client, stub_queue, monkeypatch):
|
||||
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
}, headers={"X-API-Key": "wrong"})
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_analyze_202_on_correct_key(client, stub_queue, monkeypatch):
|
||||
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
|
||||
resp = _post(client, data={
|
||||
"video": (io.BytesIO(b"x"), "clip.mp4"),
|
||||
"fcp_mode": "C",
|
||||
}, headers={"X-API-Key": "sekret"})
|
||||
assert resp.status_code == 202
|
||||
|
||||
|
||||
# ── single-model class-filter fix (src/job.py stem key) ───────────────
|
||||
|
||||
|
||||
def test_single_model_job_filter_looked_up_by_stem(monkeypatch):
|
||||
"""job._run_job passes filter by stem, not filename (regression)."""
|
||||
import app as app_module
|
||||
from src.job import JobStatus
|
||||
from src.model_registry import ModelConfig
|
||||
|
||||
captured = {}
|
||||
|
||||
def fake_run_pipeline(**kwargs):
|
||||
captured.update(kwargs)
|
||||
|
||||
class _R:
|
||||
output_path = "x.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
|
||||
return _R()
|
||||
|
||||
import src.job as job_mod
|
||||
monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline)
|
||||
|
||||
cfg = ModelConfig(
|
||||
filename="fake-stem.pt", path="/tmp/fake-stem.pt",
|
||||
stem="fake-stem", known_classes=["sack"],
|
||||
)
|
||||
job = app_module.job_queue.add_job(
|
||||
video_path="/tmp/x.mp4",
|
||||
model_configs=[cfg],
|
||||
class_filters={"fake-stem": ["sack", "box"]},
|
||||
)
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
with app_module.job_queue._lock:
|
||||
job.status = JobStatus.CANCELLED # keep worker from re-running
|
||||
|
||||
assert captured["class_filter"] == ["sack", "box"]
|
||||
Reference in new issue
Block a user