fix: degrade a broken zone calibration instead of publishing a wrong count

The whole-branch review found three ways a broken zones.json could reach a
published count:

- build_static_roi indexed the truck_area points directly, so a 1-element
  point (IndexError) or an infinite coordinate (OverflowError) escaped the
  app's guard and became a 500. It now reuses _scaled_points and raises
  ValueError, which the guard already handles.
- A missing or short truck_area fell back to an invented heuristic box that
  was still published as a calibrated "fixed" zone. It now degrades to
  dynamic mode instead.
- A degenerate (zero-area) counting polygon was built successfully and
  filtered out every detection, silently publishing zero counts. It is
  now rejected like any other malformed calibration.

Also: the app guard catches IndexError/KeyError/OverflowError, the zone
preset comment no longer claims 1920x1080 coordinates are authored for
1280x720, and two FCP citations are corrected.
This commit is contained in:
jetson committed 2026-10-28 09:45:25 +07:00
1 parent 23ede68f28
commit 2ca4cb6c3d
6 files changed
+80 -19

No files matched your search

+1 -1
View File
@@ -139,7 +139,7 @@ Models without "truck" class: `best`, `karung-dimuat`, `yolo11n-bbox` (auto-load
The web upload form offers three zone modes:
- **Auto-detect Truck**: truck detector finds the main truck each ~15 frames, ROI + counting line follow it (EMA-smoothed with 10px deadband, sticky truck pick)
- **Auto-detect Truck**: truck detector finds the main truck every 5th frame (FCP parity, `predict.py:882`), ROI + counting line follow it (EMA-smoothed with 10px deadband, sticky truck pick)
- **Fixed Zone** (default): static zone from `zones.json` presets, built in the fixed 1280×720 analysis frame; never moves; presets editable via `tools/calibrate_zone.py`
- **Auto-detect + Freeze**: auto-detects the truck then locks the ROI permanently after 3 consecutive detections (geometry fixed, truck-presence still tracked for batch state machine)
+6 -3
View File
@@ -143,8 +143,10 @@ def upload():
def _static_roi(zone: dict) -> TruckROI:
"""Build the fixed zone ROI in FCP's 1280x720 analysis frame.
The zone preset is authored for 1280x720 (FCP predict.py:685-711), so it
must not be scaled to the uploaded clip's native size.
The zone preset is authored for 1920x1080 (zones.json reference_resolution)
and scaled down to the analysis frame exactly like FCP does
(predict.py:687-689) — it must not be scaled to the uploaded clip's
native size.
"""
return build_static_roi(zone, *ANALYSIS_SIZE)
@@ -204,7 +206,8 @@ def _resolve_zone(
reason = "malformed counting_area"
else:
built = True
except (OSError, ValueError, TypeError, AttributeError, GEOSException) as exc:
except (OSError, ValueError, TypeError, AttributeError, IndexError,
KeyError, OverflowError, GEOSException) as exc:
# A corrupt/unreadable calibration must degrade to dynamic, not 500.
reason = f"unreadable calibration — could not be read/applied ({exc})"
if not built:
+2 -2
View File
@@ -201,7 +201,7 @@ def compute_sacks_in_truck_area(
) -> int:
"""Count detections inside the bottom 85% of the truck area.
FCP parity: predict.py:950-958 — a detection counts when its bbox centre
FCP parity: predict.py:951-961 — a detection counts when its bbox centre
is inside the truck polygon AND its centre Y is at or below the 15% mark
from the top of the polygon.
@@ -256,7 +256,7 @@ def update_batch_state(
unloading_count=unloading_count,
)
if batch_mgr.state == BatchState.WAITING_FOR_ACTIVITY.name:
# FCP predict.py:1076-1078 — in WAITING the batch stays alive while
# FCP predict.py:1084-1086 — in WAITING the batch stays alive while
# there is activity, and closes when there is none.
activity = has_crossing or sacks_in_area > 0 or truck_detected
batch_mgr.update_truck(activity, None, timestamp)
+22 -13
View File
@@ -39,8 +39,12 @@ def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckR
The zone's count_line also yields the calibrated x-window
(line_x_start / line_x_end) the counter counts inside; a zone without a
count_line leaves both None.
Raises ValueError when the truck_area is missing or malformed — an
invented ROI would be published as if it were the calibration, so a
broken preset must degrade (the caller falls back to dynamic mode)
instead.
"""
truck_pts = zone.get("truck_area", [])
count_line = zone.get("count_line") or {}
ref_w, ref_h = zone.get("reference_resolution", [1920, 1080])
@@ -48,17 +52,17 @@ def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckR
sx = video_w / ref_w if ref_w else 1.0
sy = video_h / ref_h if ref_h else 1.0
# Compute bounding box of truck_area polygon (scaled)
if truck_pts and len(truck_pts) >= 4:
xs = [int(p[0] * sx) for p in truck_pts]
ys = [int(p[1] * sy) for p in truck_pts]
x1 = max(0, min(xs))
y1 = max(0, min(ys))
x2 = min(video_w, max(xs))
y2 = min(video_h, max(ys))
else:
x1, y1 = int(video_w * 0.3), int(video_h * 0.1)
x2, y2 = int(video_w * 0.75), int(video_h * 0.95)
# Bounding box of the truck_area polygon (scaled). _scaled_points rejects
# malformed points instead of letting them raise.
pts = _scaled_points(zone, "truck_area", video_w, video_h)
if pts is None or len(pts) < 4:
raise ValueError("truck_area must be a 4-point polygon")
xs = [p[0] for p in pts]
ys = [p[1] for p in pts]
x1 = max(0, min(xs))
y1 = max(0, min(ys))
x2 = min(video_w, max(xs))
y2 = min(video_h, max(ys))
# Calibrated count-line (FCP predict.py:702-703). The counter counts inside
# the x-window, not inside the truck-ROI bounds. The fallbacks are already
@@ -134,9 +138,14 @@ def _build_polygon(
if pts is None:
return None
try:
return Polygon(pts)
poly = Polygon(pts)
except GEOSException:
return None
if poly.area <= 0:
# A degenerate (zero-area) polygon contains nothing — it would filter
# out every detection and silently publish zero counts.
return None
return poly
def build_counting_polygon(
+26
View File
@@ -507,6 +507,32 @@ def test_analyze_falls_back_to_dynamic_with_corrupt_zone_file(client, buf, analy
assert "dynamic" in out
def test_analyze_falls_back_to_dynamic_with_a_malformed_truck_area(client, buf, analyze_env, tmp_path, monkeypatch, capsys):
"""A calibration the ROI builder rejects degrades to dynamic instead of 500."""
app_module = analyze_env
zones = tmp_path / "zones.json"
zones.write_text(json.dumps({
"active_preset": "default",
"presets": {"default": {**FCP_ZONE, "truck_area": [[600, 385]]}},
}))
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 == "dynamic"
assert job.fixed_zone is None
assert job.counting_polygon is None
_wait_job_done(job)
out = capsys.readouterr().out
assert "dynamic" in out
def test_analyze_falls_back_to_dynamic_with_malformed_counting_area(client, buf, analyze_env, tmp_path, monkeypatch, capsys):
"""A structurally invalid counting_area degrades to dynamic instead of 500."""
app_module = analyze_env
+23
View File
@@ -178,6 +178,29 @@ def test_build_truck_polygon_defaults_to_1920x1080_reference():
assert list(poly.exterior.coords)[0] == (400.0, 256.0)
def test_build_counting_polygon_none_on_a_degenerate_polygon():
"""Three collinear points have no interior — the filter would zero every count."""
assert build_counting_polygon(
{"counting_area": [[0, 0], [10, 0], [20, 0]]}, 1280, 720
) is None
def test_build_static_roi_rejects_a_missing_or_malformed_truck_area():
"""No calibration -> ValueError. An invented ROI must not pass as calibrated."""
import pytest
with pytest.raises(ValueError):
build_static_roi({"count_line": {"x_start": 577, "x_end": 1401, "y": 330}},
1280, 720)
with pytest.raises(ValueError):
build_static_roi({"truck_area": [[0, 0]]}, 1280, 720)
with pytest.raises(ValueError):
build_static_roi({"truck_area": [[0, 0], [1, 1], [2, 2]]}, 1280, 720)
with pytest.raises(ValueError):
build_static_roi({"truck_area": [["a", "b"], [1, 1], [2, 2], [3, 3]]},
1280, 720)
def test_build_truck_polygon_none_without_truck_area():
assert build_truck_polygon({}, 1280, 720) is None
assert build_truck_polygon({"truck_area": []}, 1280, 720) is None