fix: feed the batch seam the counter's own stream and harden the zone polygon builders

This commit is contained in:
jetson committed 2026-10-27 16:27:28 +07:00
1 parent fc94189040
commit f54521c1d8
6 files changed
+243 -34

No files matched your search

+9 -2
View File
@@ -18,6 +18,7 @@ from werkzeug.utils import secure_filename
from pathlib import Path
from shapely.errors import GEOSException
from shapely.geometry import Polygon
from src.job import JobQueue
@@ -195,8 +196,14 @@ def _resolve_zone(
roi = _static_roi(zone)
polygon = _static_polygon(zone)
truck_polygon = _static_truck_polygon(zone)
built = True
except (OSError, ValueError, TypeError, AttributeError) as exc:
if zone.get("counting_area") and polygon is None:
# A counting area that is present but could not be built
# means the calibration is broken. Counting without it
# would widen the counting area, so degrade the zone.
reason = "malformed counting_area"
else:
built = True
except (OSError, ValueError, TypeError, AttributeError, 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:
+15 -7
View File
@@ -16,7 +16,7 @@ import cv2
from shapely.geometry import Point, Polygon
from ultralytics import YOLO
from src.batch import BatchLifecycleManager
from src.batch import BatchLifecycleManager, BatchState
from src.config import load_config
from src.counting import MultiClassLineCounter
from src.dashboard import DashboardOverlay
@@ -224,7 +224,7 @@ def update_batch_state(
loading_count=loading_count,
unloading_count=unloading_count,
)
if batch_mgr.state == "WAITING_FOR_ACTIVITY":
if batch_mgr.state == BatchState.WAITING_FOR_ACTIVITY.name:
# FCP predict.py:1076-1078 — 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
@@ -435,6 +435,7 @@ def run_pipeline(
# Track → Stabilize → Count
tracked_sacks: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
if batch_mgr.is_active:
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
@@ -455,14 +456,17 @@ def run_pipeline(
)
tracked_sacks = _apply_class_confs(tracked_sacks, sack_conf, box_conf)
tracked_sacks = _apply_min_area(tracked_sacks, _scaled_min_areas(cfg, w, h))
events = counter.update(countable_detections(tracked_sacks))
counter_input = countable_detections(tracked_sacks)
events = counter.update(counter_input)
# Drive the batch FSM with this frame's real crossing events
# (FCP predict.py:1064-1085 — events first, then the FSM).
# The seam counts the very stream the counter consumed, so the
# truck-area count matches FCP's stable list.
update_batch_state(
batch_mgr,
events=events,
tracked_sacks=tracked_sacks,
tracked_sacks=counter_input,
truck_polygon=truck_polygon,
timestamp=timestamp,
loading_count=counter.loading_count,
@@ -836,6 +840,7 @@ def run_merged_pipeline(
# Detection + tracking
all_detections: list[Detection] = []
tracked: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
if batch_mgr.is_active:
# Primary: tracker gives detections WITH track_id for counting
@@ -877,19 +882,22 @@ def run_merged_pipeline(
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
# Count using only detections with track_id (tracker results)
events = counter.update(
countable_detections([d for d in tracked if d.track_id is not None])
counter_input = countable_detections(
[d for d in tracked if d.track_id is not None]
)
events = counter.update(counter_input)
else:
tracked = []
synthetic.clear()
# Drive the batch FSM with this frame's real crossing events
# (FCP predict.py:1064-1085 — events first, then the FSM).
# The seam counts the very stream the counter consumed — the
# primary tracker's detections, not the supplementary ones.
update_batch_state(
batch_mgr,
events=events,
tracked_sacks=tracked,
tracked_sacks=counter_input,
truck_polygon=truck_polygon,
timestamp=timestamp,
loading_count=counter.loading_count,
+53 -17
View File
@@ -4,8 +4,11 @@ from __future__ import annotations
import json
import os
from math import isfinite
from numbers import Real
from typing import Any
from shapely.errors import GEOSException
from shapely.geometry import Polygon
from src.truck_roi import TruckROI
@@ -75,6 +78,53 @@ def list_zone_presets(path: str) -> list[dict[str, Any]]:
]
def _scaled_points(
zone: Any, key: str, video_w: int, video_h: int
) -> list[tuple[int, int]] | None:
"""Scale a zone's point list to the video frame, or None if unusable.
A point must be a 2-number sequence — a 3-number point is rejected, not
silently truncated. Anything malformed (non-dict zone, short list, bad
reference resolution, non-numeric or non-finite coordinates) yields None
so a broken calibration degrades instead of raising.
"""
if not isinstance(zone, dict):
return None
try:
pts = zone.get(key) or []
if len(pts) < 3:
return None
ref_w, ref_h = zone.get("reference_resolution", [1920, 1080])
sx = video_w / ref_w if ref_w else 1.0
sy = video_h / ref_h if ref_h else 1.0
scaled: list[tuple[int, int]] = []
for p in pts:
if not isinstance(p, (list, tuple)) or len(p) != 2:
return None
x, y = p
if not isinstance(x, Real) or not isinstance(y, Real):
return None
if not (isfinite(x) and isfinite(y)):
return None
scaled.append((int(x * sx), int(y * sy)))
return scaled
except (TypeError, ValueError, IndexError, KeyError, OverflowError):
return None
def _build_polygon(
zone: Any, key: str, video_w: int, video_h: int
) -> Polygon | None:
"""Build a zone polygon in the video frame, or None if the zone is malformed."""
pts = _scaled_points(zone, key, video_w, video_h)
if pts is None:
return None
try:
return Polygon(pts)
except GEOSException:
return None
def build_counting_polygon(
zone: dict[str, Any], video_w: int, video_h: int
) -> Polygon | None:
@@ -87,14 +137,9 @@ def build_counting_polygon(
detection_polygon exactly.
Returns None when the zone has no usable counting_area (no polygon filter).
A malformed calibration degrades to None, it never raises.
"""
pts = zone.get("counting_area") or []
if len(pts) < 3:
return None
ref_w, ref_h = zone.get("reference_resolution", [1920, 1080])
sx = video_w / ref_w if ref_w else 1.0
sy = video_h / ref_h if ref_h else 1.0
return Polygon([(int(p[0] * sx), int(p[1] * sy)) for p in pts])
return _build_polygon(zone, "counting_area", video_w, video_h)
def build_truck_polygon(
@@ -109,16 +154,7 @@ def build_truck_polygon(
Returns None when the zone has no usable truck_area — a malformed
calibration must degrade to "no truck area", never raise.
"""
try:
pts = zone.get("truck_area") or []
if len(pts) < 3:
return None
ref_w, ref_h = zone.get("reference_resolution", [1920, 1080])
sx = video_w / ref_w if ref_w else 1.0
sy = video_h / ref_h if ref_h else 1.0
return Polygon([(int(p[0] * sx), int(p[1] * sy)) for p in pts])
except (TypeError, ValueError, IndexError, KeyError):
return None
return _build_polygon(zone, "truck_area", video_w, video_h)
def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any] | None:
+13
View File
@@ -89,3 +89,16 @@ def test_update_batch_state_counts_sacks_only_in_truck_area():
update_batch_state(m, events=[], tracked_sacks=[box], truck_polygon=poly,
timestamp=1000.0, loading_count=0, unloading_count=0)
assert m.sacks_calls[-1]["sacks_in_area_count"] == 0
def test_update_batch_state_counts_the_sack_next_to_a_box():
"""Positive control: a sack and a box in the same area count as one sack."""
poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)])
sack = Detection(bbox=(40.0, 80.0, 50.0, 95.0), confidence=0.9,
class_id=0, class_name="sack", track_id=1)
box = Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9,
class_id=1, class_name="box", track_id=2)
m = _RecordingManager()
update_batch_state(m, events=[], tracked_sacks=[sack, box], truck_polygon=poly,
timestamp=1000.0, loading_count=0, unloading_count=0)
assert m.sacks_calls[-1]["sacks_in_area_count"] == 1
+102 -8
View File
@@ -398,6 +398,15 @@ FCP_ZONE = {
# FCP's truck_poly_pts at reference resolution (predict.py:706-712).
FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
# A non-countable class: it survives the class filter but the counter drops it.
TRUCK_DET = Detection(
bbox=(900.0, 100.0, 1000.0, 200.0),
confidence=0.9,
class_id=2,
class_name="truck",
track_id=2,
)
# centroid (620, 320) — inside FCP's polygon in the 1280x720 analysis frame.
INSIDE_SACK = Detection(
bbox=(590.0, 290.0, 650.0, 350.0),
@@ -419,7 +428,8 @@ OUTSIDE_SACK = Detection(
class _RecordingCounter:
"""Counter stub that records every detection set it is handed."""
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0, events=None):
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0, events=None,
emit_every=1):
self.line_y = line_y
self.line_x_start = line_x_start
self.line_x_end = line_x_end
@@ -429,10 +439,19 @@ class _RecordingCounter:
self.box_loading_count = 0
self.box_unloading_count = 0
self.seen: list[Detection] = []
self.calls_seen: list[list[Detection]] = []
self.events = list(events or [])
self.emit_every = emit_every
self.calls = 0
def update(self, detections):
self.seen.extend(detections)
self.calls_seen.append(list(detections))
self.calls += 1
# emit_every=2 -> an event on calls 1, 3, 5 ... so a stale payload
# shows up as a constant pattern instead of the current frame's.
if self.emit_every > 1 and self.calls % self.emit_every != 1:
return []
return list(self.events)
@@ -467,7 +486,7 @@ class _AlwaysCountingBatch:
pass
def _patch_counting_fakes(monkeypatch, detections, events=None):
def _patch_counting_fakes(monkeypatch, detections, events=None, emit_every=1):
"""Stub tracker/batch/counter so the pipeline runs offline."""
from src import pipeline as pipe_mod
@@ -480,7 +499,7 @@ def _patch_counting_fakes(monkeypatch, detections, events=None):
def update(self, frame, dets):
return list(detections)
counter = _RecordingCounter(events=events)
counter = _RecordingCounter(events=events, emit_every=emit_every)
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
@@ -722,12 +741,14 @@ def test_job_forwards_truck_polygon_to_both_pipelines(tmp_path, monkeypatch):
def test_run_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_path, monkeypatch):
"""The seam runs every frame and carries the frame's real crossing events.
"""The seam runs every frame and carries THAT frame's crossing events.
The counter emits on every other call, so a stale payload would show up
as a constant True/False pattern instead of the alternating one.
truck_det_interval is 5 — a seam gated by it would fire on 3 of 12 frames.
"""
_counter, batch = _patch_counting_fakes(
monkeypatch, [INSIDE_SACK], events=[{"direction": "loading"}]
monkeypatch, [INSIDE_SACK], events=[{"direction": "loading"}], emit_every=2
)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=12)
@@ -746,7 +767,9 @@ def test_run_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_path, mo
assert batch.sacks_calls
assert len(batch.sacks_calls) == result.frame_count
assert all(c["has_crossing_event"] is True for c in batch.sacks_calls)
assert [c["has_crossing_event"] for c in batch.sacks_calls] == [
i % 2 == 0 for i in range(result.frame_count)
]
def test_run_merged_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_path, monkeypatch):
@@ -754,7 +777,7 @@ def test_run_merged_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_p
from src.pipeline import run_merged_pipeline
_counter, batch = _patch_counting_fakes(
monkeypatch, [INSIDE_SACK], events=[{"direction": "loading"}]
monkeypatch, [INSIDE_SACK], events=[{"direction": "loading"}], emit_every=2
)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=12)
@@ -775,7 +798,78 @@ def test_run_merged_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_p
assert batch.sacks_calls
assert len(batch.sacks_calls) == result.frame_count
assert all(c["has_crossing_event"] is True for c in batch.sacks_calls)
assert [c["has_crossing_event"] for c in batch.sacks_calls] == [
i % 2 == 0 for i in range(result.frame_count)
]
def test_run_pipeline_hands_the_seam_the_counter_stream(tmp_path, monkeypatch):
"""The seam counts exactly the detections the counter consumed."""
from src import pipeline as pipe_mod
seam_inputs: list[list[Detection]] = []
real_seam = pipe_mod.update_batch_state
def spy(batch_mgr, *, tracked_sacks, **kw):
seam_inputs.append(list(tracked_sacks))
return real_seam(batch_mgr, tracked_sacks=tracked_sacks, **kw)
monkeypatch.setattr(pipe_mod, "update_batch_state", spy)
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, TRUCK_DET])
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack"],
),
class_filter=["sack", "truck"],
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert seam_inputs
assert seam_inputs == counter.calls_seen
def test_run_merged_pipeline_hands_the_seam_the_counter_stream(tmp_path, monkeypatch):
"""The merged seam sees the primary stream, not the supplementary dets."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
seam_inputs: list[list[Detection]] = []
real_seam = pipe_mod.update_batch_state
def spy(batch_mgr, *, tracked_sacks, **kw):
seam_inputs.append(list(tracked_sacks))
return real_seam(batch_mgr, tracked_sacks=tracked_sacks, **kw)
monkeypatch.setattr(pipe_mod, "update_batch_state", spy)
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, TRUCK_DET])
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
run_merged_pipeline(
video_path=video_path,
model_configs=[
ModelConfig(
filename="a.pt",
path=str(tmp_path / "a.pt"),
stem="a",
known_classes=["sack"],
)
],
class_filters={"a": ["sack", "truck"]},
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert seam_inputs
assert seam_inputs == counter.calls_seen
def test_run_pipeline_counts_sacks_in_truck_area_for_the_fsm(tmp_path, monkeypatch):
+51
View File
@@ -172,3 +172,54 @@ def test_build_truck_polygon_none_on_malformed_truck_area():
assert build_truck_polygon({"truck_area": [1, 2, 3]}, 1280, 720) is None
assert build_truck_polygon({"truck_area": "nope"}, 1280, 720) is None
assert build_truck_polygon({"truck_area": 5}, 1280, 720) is None
def test_build_truck_polygon_none_on_a_three_number_point():
"""A 3-number point is rejected, not silently truncated to two."""
assert build_truck_polygon(
{"truck_area": [[0, 0, 0], [10, 10], [20, 0]]}, 1280, 720
) is None
def test_build_truck_polygon_none_on_a_non_dict_zone():
"""A non-dict zone must not raise."""
assert build_truck_polygon(None, 1280, 720) is None
assert build_truck_polygon(["not", "a", "dict"], 1280, 720) is None
def test_build_truck_polygon_none_on_non_finite_coordinates():
"""NaN/inf coordinates would make shapely raise — degrade instead."""
assert build_truck_polygon(
{"truck_area": [[float("nan"), 0], [10, 10], [20, 0]]}, 1280, 720
) is None
assert build_truck_polygon(
{"truck_area": [[float("inf"), 0], [10, 10], [20, 0]]}, 1280, 720
) is None
def test_build_counting_polygon_none_on_malformed_counting_area():
"""The counting polygon builder never raises either (same contract)."""
assert build_counting_polygon({"counting_area": [["a", "b"], [1, 2], [3, 4]]}, 1280, 720) is None
assert build_counting_polygon({"counting_area": [1, 2, 3]}, 1280, 720) is None
assert build_counting_polygon({"counting_area": "nope"}, 1280, 720) is None
assert build_counting_polygon({"counting_area": 5}, 1280, 720) is None
def test_build_counting_polygon_none_on_a_three_number_point():
assert build_counting_polygon(
{"counting_area": [[0, 0, 0], [10, 10], [20, 0]]}, 1280, 720
) is None
def test_build_counting_polygon_none_on_a_non_dict_zone():
assert build_counting_polygon(None, 1280, 720) is None
assert build_counting_polygon(["not", "a", "dict"], 1280, 720) is None
def test_build_counting_polygon_none_on_non_finite_coordinates():
assert build_counting_polygon(
{"counting_area": [[float("nan"), 0], [10, 10], [20, 0]]}, 1280, 720
) is None
assert build_counting_polygon(
{"counting_area": [[float("inf"), 0], [10, 10], [20, 0]]}, 1280, 720
) is None