forked from andrew/feedmill-recounter
fix: drive batch FSM with real crossing events (FCP predict.py:1064 parity)
This commit is contained in:
1 parent
acc74dcb62
commit
fc94189040
8 files changed
+510
-44
No files matched your search
@@ -27,7 +27,7 @@ from src.pipeline import ANALYSIS_SIZE
|
||||
from src.truck_roi import TruckROI
|
||||
from src.zone_config import (
|
||||
load_zone_config, list_zone_presets, build_static_roi, build_counting_polygon,
|
||||
get_active_zone,
|
||||
build_truck_polygon, get_active_zone,
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
@@ -156,22 +156,32 @@ def _static_polygon(zone: dict) -> Polygon | None:
|
||||
return build_counting_polygon(zone, *ANALYSIS_SIZE)
|
||||
|
||||
|
||||
def _static_truck_polygon(zone: dict) -> Polygon | None:
|
||||
"""Build the truck-area polygon in FCP's 1280x720 analysis frame.
|
||||
|
||||
Same arithmetic as FCP's hardcoded truck_polygon (predict.py:706-712):
|
||||
the zone's truck_area scaled by 1280/1920 x 720/1080, truncated.
|
||||
"""
|
||||
return build_truck_polygon(zone, *ANALYSIS_SIZE)
|
||||
|
||||
|
||||
def _resolve_zone(
|
||||
zone_mode: str, zone_preset: str
|
||||
) -> tuple[str, TruckROI | None, str, Polygon | None]:
|
||||
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
|
||||
"""Resolve the counting zone of a job.
|
||||
|
||||
Returns (zone_mode, fixed_zone, zone_preset, counting_polygon). "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).
|
||||
Returns (zone_mode, fixed_zone, zone_preset, counting_polygon,
|
||||
truck_polygon). "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, None
|
||||
return zone_mode, None, zone_preset, None, None
|
||||
zone = None
|
||||
reason = "no zone file"
|
||||
roi: TruckROI | None = None
|
||||
polygon: Polygon | None = None
|
||||
truck_polygon: Polygon | None = None
|
||||
built = False
|
||||
if os.path.isfile(ZONES_PATH):
|
||||
try:
|
||||
@@ -179,19 +189,20 @@ def _resolve_zone(
|
||||
if zone is None:
|
||||
reason = "no active preset"
|
||||
else:
|
||||
# ROI + counting polygon come from the same zone dict. A
|
||||
# structurally invalid calibration must degrade to dynamic,
|
||||
# not 500 — so the builds stay inside this guard.
|
||||
# ROI + counting polygon + truck polygon come from the same zone
|
||||
# dict. A structurally invalid calibration must degrade to
|
||||
# dynamic, not 500 — so the builds stay inside this guard.
|
||||
roi = _static_roi(zone)
|
||||
polygon = _static_polygon(zone)
|
||||
truck_polygon = _static_truck_polygon(zone)
|
||||
built = True
|
||||
except (OSError, ValueError, TypeError, AttributeError) 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:
|
||||
print(f"[ZONE] {reason} at {ZONES_PATH} — falling back to dynamic")
|
||||
return "dynamic", None, zone_preset, None
|
||||
return "fixed", roi, zone_preset or "default", polygon
|
||||
return "dynamic", None, zone_preset, None, None
|
||||
return "fixed", roi, zone_preset or "default", polygon, truck_polygon
|
||||
|
||||
|
||||
def _save_and_queue(video, model_configs, class_filters,
|
||||
@@ -212,7 +223,7 @@ def _save_and_queue(video, model_configs, class_filters,
|
||||
# Transcode to 720p max height to save storage and speed up processing
|
||||
video_path = resize_video_to_max_height(video_path, max_height=720)
|
||||
|
||||
zone_mode, fixed_zone, zone_preset, counting_polygon = _resolve_zone(
|
||||
zone_mode, fixed_zone, zone_preset, counting_polygon, truck_polygon = _resolve_zone(
|
||||
zone_mode, zone_preset
|
||||
)
|
||||
|
||||
@@ -224,6 +235,7 @@ def _save_and_queue(video, model_configs, class_filters,
|
||||
zone_mode=zone_mode,
|
||||
fixed_zone=fixed_zone,
|
||||
counting_polygon=counting_polygon,
|
||||
truck_polygon=truck_polygon,
|
||||
zone_preset=zone_preset,
|
||||
output_max_height=(int(output_height) if output_height else None),
|
||||
)
|
||||
@@ -342,7 +354,7 @@ def upload_reuse():
|
||||
|
||||
output_height = request.form.get("output_height", "")
|
||||
zone_mode = request.form.get("zone_mode", "fixed")
|
||||
zone_mode, fixed_zone, zone_preset, counting_polygon = _resolve_zone(
|
||||
zone_mode, fixed_zone, zone_preset, counting_polygon, truck_polygon = _resolve_zone(
|
||||
zone_mode, request.form.get("zone_preset", "")
|
||||
)
|
||||
|
||||
@@ -353,6 +365,7 @@ def upload_reuse():
|
||||
zone_mode=zone_mode,
|
||||
fixed_zone=fixed_zone,
|
||||
counting_polygon=counting_polygon,
|
||||
truck_polygon=truck_polygon,
|
||||
zone_preset=zone_preset,
|
||||
output_max_height=(int(output_height) if output_height else None),
|
||||
)
|
||||
|
||||
@@ -74,6 +74,7 @@ class Job:
|
||||
zone_mode: str = "fixed"
|
||||
fixed_zone: TruckROI | None = None
|
||||
counting_polygon: Polygon | None = None
|
||||
truck_polygon: Polygon | None = None
|
||||
zone_preset: str = ""
|
||||
output_max_height: int | None = None
|
||||
|
||||
@@ -125,6 +126,7 @@ class JobQueue:
|
||||
zone_mode: str = "fixed",
|
||||
fixed_zone: TruckROI | None = None,
|
||||
counting_polygon: Polygon | None = None,
|
||||
truck_polygon: Polygon | None = None,
|
||||
zone_preset: str = "",
|
||||
output_max_height: int | None = None,
|
||||
) -> Job:
|
||||
@@ -140,6 +142,7 @@ class JobQueue:
|
||||
zone_mode=zone_mode,
|
||||
fixed_zone=fixed_zone,
|
||||
counting_polygon=counting_polygon,
|
||||
truck_polygon=truck_polygon,
|
||||
zone_preset=zone_preset,
|
||||
output_max_height=output_max_height,
|
||||
)
|
||||
@@ -260,6 +263,7 @@ class JobQueue:
|
||||
truck_model_config=truck_model_config,
|
||||
fixed_zone=job.fixed_zone,
|
||||
counting_polygon=job.counting_polygon,
|
||||
truck_polygon=job.truck_polygon,
|
||||
freeze_roi=(job.zone_mode == "freeze"),
|
||||
preview_path=job.preview_path,
|
||||
preview_enabled=job.preview_enabled,
|
||||
@@ -315,6 +319,7 @@ class JobQueue:
|
||||
truck_model_config=truck_model_config,
|
||||
fixed_zone=job.fixed_zone,
|
||||
counting_polygon=job.counting_polygon,
|
||||
truck_polygon=job.truck_polygon,
|
||||
freeze_roi=(job.zone_mode == "freeze"),
|
||||
preview_path=job.preview_path,
|
||||
preview_enabled=job.preview_enabled,
|
||||
|
||||
+107
-20
@@ -163,6 +163,76 @@ def filter_by_counting_polygon(
|
||||
]
|
||||
|
||||
|
||||
def compute_sacks_in_truck_area(
|
||||
detections: list[Detection],
|
||||
truck_polygon: Polygon,
|
||||
cutoff_ratio: float = 0.15,
|
||||
) -> int:
|
||||
"""Count detections inside the bottom 85% of the truck area.
|
||||
|
||||
FCP parity: predict.py:950-958 — 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.
|
||||
|
||||
Generic: counts whatever detections it is handed (the caller decides
|
||||
which classes are in the truck area).
|
||||
"""
|
||||
min_y, max_y = truck_polygon.bounds[1], truck_polygon.bounds[3]
|
||||
cutoff_y = min_y + cutoff_ratio * (max_y - min_y)
|
||||
count = 0
|
||||
for d in detections:
|
||||
cx = (d.bbox[0] + d.bbox[2]) / 2.0
|
||||
cy = (d.bbox[1] + d.bbox[3]) / 2.0
|
||||
if truck_polygon.contains(Point(cx, cy)) and cy >= cutoff_y:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def update_batch_state(
|
||||
batch_mgr: BatchLifecycleManager,
|
||||
*,
|
||||
events: list[dict],
|
||||
tracked_sacks: list[Detection],
|
||||
truck_polygon: Polygon | None,
|
||||
timestamp: float,
|
||||
loading_count: int,
|
||||
unloading_count: int,
|
||||
truck_detected: bool = False,
|
||||
truck_centroid: tuple[float, float] | None = None,
|
||||
) -> None:
|
||||
"""Drive the batch FSM with the frame's real crossing events.
|
||||
|
||||
FCP parity: predict.py:1064-1085 — has_crossing is "an event happened
|
||||
this frame" and sacks_in_area is the real count of sacks inside the
|
||||
truck area, not the legacy "1 if a truck was seen" proxy.
|
||||
|
||||
Both manager methods are called every frame; each one ignores the states
|
||||
it does not handle, so the call is safe in every state.
|
||||
"""
|
||||
has_crossing = bool(events)
|
||||
# FCP counts sacks only — boxes live in a separate list (predict.py:930-942).
|
||||
sacks = [d for d in tracked_sacks if d.class_name == "sack"]
|
||||
sacks_in_area = (
|
||||
compute_sacks_in_truck_area(sacks, truck_polygon)
|
||||
if truck_polygon is not None
|
||||
else 0
|
||||
)
|
||||
batch_mgr.update_sacks(
|
||||
has_crossing_event=has_crossing,
|
||||
sacks_in_area_count=sacks_in_area,
|
||||
timestamp=timestamp,
|
||||
loading_count=loading_count,
|
||||
unloading_count=unloading_count,
|
||||
)
|
||||
if batch_mgr.state == "WAITING_FOR_ACTIVITY":
|
||||
# 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
|
||||
batch_mgr.update_truck(activity, None, timestamp)
|
||||
else:
|
||||
batch_mgr.update_truck(truck_detected, truck_centroid, timestamp)
|
||||
|
||||
|
||||
def run_pipeline(
|
||||
video_path: str,
|
||||
model_config: ModelConfig,
|
||||
@@ -171,6 +241,7 @@ def run_pipeline(
|
||||
truck_model_config: ModelConfig | None = None,
|
||||
fixed_zone: TruckROI | None = None,
|
||||
counting_polygon: Polygon | None = None,
|
||||
truck_polygon: Polygon | None = None,
|
||||
sack_conf: float | None = None,
|
||||
truck_conf: float | None = None,
|
||||
truck_det_interval: int | None = None,
|
||||
@@ -362,17 +433,9 @@ def run_pipeline(
|
||||
if truck_present:
|
||||
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
|
||||
|
||||
if frame_idx % truck_det_interval == 0:
|
||||
batch_mgr.update(
|
||||
truck_detected=truck_present,
|
||||
timestamp=timestamp,
|
||||
loading_count=counter.loading_count,
|
||||
unloading_count=counter.unloading_count,
|
||||
truck_centroid=truck_centroid,
|
||||
)
|
||||
|
||||
# Track → Stabilize → Count
|
||||
tracked_sacks: list[Detection] = []
|
||||
events: list[dict] = []
|
||||
if batch_mgr.is_active:
|
||||
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
|
||||
stable = stabilizer.update(raw_tracked)
|
||||
@@ -392,7 +455,21 @@ 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))
|
||||
counter.update(countable_detections(tracked_sacks))
|
||||
events = counter.update(countable_detections(tracked_sacks))
|
||||
|
||||
# Drive the batch FSM with this frame's real crossing events
|
||||
# (FCP predict.py:1064-1085 — events first, then the FSM).
|
||||
update_batch_state(
|
||||
batch_mgr,
|
||||
events=events,
|
||||
tracked_sacks=tracked_sacks,
|
||||
truck_polygon=truck_polygon,
|
||||
timestamp=timestamp,
|
||||
loading_count=counter.loading_count,
|
||||
unloading_count=counter.unloading_count,
|
||||
truck_detected=truck_present,
|
||||
truck_centroid=truck_centroid,
|
||||
)
|
||||
|
||||
# Annotate frame
|
||||
viz = dashboard.draw(
|
||||
@@ -574,6 +651,7 @@ def run_merged_pipeline(
|
||||
truck_model_config: ModelConfig | None = None,
|
||||
fixed_zone: TruckROI | None = None,
|
||||
counting_polygon: Polygon | None = None,
|
||||
truck_polygon: Polygon | None = None,
|
||||
sack_conf: float | None = None,
|
||||
truck_conf: float | None = None,
|
||||
truck_det_interval: int | None = None,
|
||||
@@ -755,17 +833,10 @@ def run_merged_pipeline(
|
||||
if truck_present:
|
||||
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
|
||||
|
||||
if frame_idx % truck_det_interval == 0:
|
||||
batch_mgr.update(
|
||||
truck_detected=truck_present,
|
||||
timestamp=timestamp,
|
||||
loading_count=counter.loading_count,
|
||||
unloading_count=counter.unloading_count,
|
||||
truck_centroid=truck_centroid,
|
||||
)
|
||||
|
||||
# Detection + tracking
|
||||
all_detections: list[Detection] = []
|
||||
tracked: list[Detection] = []
|
||||
events: list[dict] = []
|
||||
if batch_mgr.is_active:
|
||||
# Primary: tracker gives detections WITH track_id for counting
|
||||
primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
|
||||
@@ -806,11 +877,27 @@ def run_merged_pipeline(
|
||||
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
|
||||
|
||||
# Count using only detections with track_id (tracker results)
|
||||
counter.update(countable_detections([d for d in tracked if d.track_id is not None]))
|
||||
events = counter.update(
|
||||
countable_detections([d for d in tracked if d.track_id is not None])
|
||||
)
|
||||
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).
|
||||
update_batch_state(
|
||||
batch_mgr,
|
||||
events=events,
|
||||
tracked_sacks=tracked,
|
||||
truck_polygon=truck_polygon,
|
||||
timestamp=timestamp,
|
||||
loading_count=counter.loading_count,
|
||||
unloading_count=counter.unloading_count,
|
||||
truck_detected=truck_present,
|
||||
truck_centroid=truck_centroid,
|
||||
)
|
||||
|
||||
# Annotate
|
||||
viz = dashboard.draw(
|
||||
frame=frame,
|
||||
|
||||
@@ -97,6 +97,30 @@ def build_counting_polygon(
|
||||
return Polygon([(int(p[0] * sx), int(p[1] * sy)) for p in pts])
|
||||
|
||||
|
||||
def build_truck_polygon(
|
||||
zone: dict[str, Any], video_w: int, video_h: int
|
||||
) -> Polygon | None:
|
||||
"""Build the truck-area polygon of a zone, scaled to the video frame.
|
||||
|
||||
zone["truck_area"] holds FCP's truck_poly_pts (predict.py:706-712) at
|
||||
zone["reference_resolution"]. The arithmetic is identical to
|
||||
build_static_roi's, so the polygon matches FCP's truck_polygon exactly.
|
||||
|
||||
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
|
||||
|
||||
|
||||
def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any] | None:
|
||||
"""Get the active preset dict. Falls back to active_preset field if name not given."""
|
||||
config = load_zone_config(path)
|
||||
|
||||
@@ -432,6 +432,7 @@ def test_analyze_defaults_to_fixed_zone_mode(client, buf, analyze_env, tmp_path,
|
||||
assert job.fixed_zone is not None
|
||||
assert job.fixed_zone.fixed is True
|
||||
assert job.counting_polygon is not None
|
||||
assert job.truck_polygon is not None
|
||||
_wait_job_done(job)
|
||||
|
||||
|
||||
@@ -476,6 +477,7 @@ def test_analyze_falls_back_to_dynamic_without_zone_file(client, buf, analyze_en
|
||||
assert job.zone_mode == "dynamic"
|
||||
assert job.fixed_zone is None
|
||||
assert job.counting_polygon is None
|
||||
assert job.truck_polygon is None
|
||||
_wait_job_done(job)
|
||||
|
||||
|
||||
@@ -526,6 +528,7 @@ def test_analyze_falls_back_to_dynamic_with_malformed_counting_area(client, buf,
|
||||
assert job.zone_mode == "dynamic"
|
||||
assert job.fixed_zone is None
|
||||
assert job.counting_polygon is None
|
||||
assert job.truck_polygon is None
|
||||
_wait_job_done(job)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Batch lifecycle tests — FCP batch-FSM parity."""
|
||||
|
||||
from src.batch import BatchLifecycleManager
|
||||
from src.interfaces import Detection
|
||||
from src.pipeline import compute_sacks_in_truck_area, update_batch_state
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
|
||||
def _counting_manager() -> BatchLifecycleManager:
|
||||
"""Manager already in COUNTING_SACKS (stabilize_seconds=0 to skip the ramp)."""
|
||||
m = BatchLifecycleManager(stabilize_seconds=0.0)
|
||||
m.update_truck(True, (100.0, 100.0), 1000.0)
|
||||
assert m.state == "COUNTING_SACKS"
|
||||
return m
|
||||
|
||||
|
||||
class _RecordingManager(BatchLifecycleManager):
|
||||
"""Batch manager that records the arguments it was driven with."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(stabilize_seconds=0.0)
|
||||
self.sacks_calls: list[dict] = []
|
||||
|
||||
def update_sacks(self, has_crossing_event, sacks_in_area_count, timestamp,
|
||||
loading_count=0, unloading_count=0):
|
||||
self.sacks_calls.append({
|
||||
"has_crossing_event": has_crossing_event,
|
||||
"sacks_in_area_count": sacks_in_area_count,
|
||||
"loading_count": loading_count,
|
||||
"unloading_count": unloading_count,
|
||||
})
|
||||
super().update_sacks(has_crossing_event, sacks_in_area_count, timestamp,
|
||||
loading_count, unloading_count)
|
||||
|
||||
|
||||
def test_update_batch_state_passes_real_crossing_flag():
|
||||
"""A crossing event reaches the manager as has_crossing_event=True."""
|
||||
m = _RecordingManager()
|
||||
update_batch_state(m, events=[{"direction": "loading"}], tracked_sacks=[],
|
||||
truck_polygon=None, timestamp=1000.0,
|
||||
loading_count=1, unloading_count=0)
|
||||
assert m.sacks_calls[-1]["has_crossing_event"] is True
|
||||
|
||||
|
||||
def test_update_batch_state_counts_sacks_in_truck_area():
|
||||
"""sacks_in_area_count comes from the truck polygon, not from truck presence."""
|
||||
poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)])
|
||||
dets = [Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9,
|
||||
class_id=0, class_name="sack", track_id=1)]
|
||||
m = _RecordingManager()
|
||||
update_batch_state(m, events=[], tracked_sacks=dets, truck_polygon=poly,
|
||||
timestamp=1000.0, loading_count=0, unloading_count=0)
|
||||
assert m.sacks_calls[-1]["sacks_in_area_count"] == 1
|
||||
|
||||
|
||||
def test_compute_sacks_in_truck_area_applies_bottom_cutoff():
|
||||
"""Only the bottom 85% of the truck area counts (FCP predict.py:950-958)."""
|
||||
poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)])
|
||||
top = [Detection(bbox=(10.0, 5.0, 20.0, 20.0), confidence=0.9,
|
||||
class_id=0, class_name="sack", track_id=1)]
|
||||
bottom = [Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9,
|
||||
class_id=0, class_name="sack", track_id=2)]
|
||||
assert compute_sacks_in_truck_area(top, poly) == 0
|
||||
assert compute_sacks_in_truck_area(bottom, poly) == 1
|
||||
|
||||
|
||||
def test_idle_timeout_without_activity_enters_waiting():
|
||||
"""No crossing and no sack in area for sack_idle_timeout -> WAITING."""
|
||||
m = _counting_manager()
|
||||
m.update_sacks(False, 0, 1001.0, 1, 0)
|
||||
m.update_sacks(False, 0, 1045.0, 1, 0) # 45s after batch start
|
||||
assert m.state == "WAITING_FOR_ACTIVITY"
|
||||
|
||||
|
||||
def test_pending_counts_follow_latest_crossing():
|
||||
"""_pending_loading tracks the newest count, not a frozen snapshot."""
|
||||
m = _counting_manager()
|
||||
m.update_sacks(True, 1, 1001.0, 7, 2)
|
||||
assert m._pending_loading == 7
|
||||
assert m._pending_unloading == 2
|
||||
|
||||
|
||||
def test_update_batch_state_counts_sacks_only_in_truck_area():
|
||||
"""Boxes in the truck area are not sacks (FCP keeps them in a separate list)."""
|
||||
poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)])
|
||||
box = Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9,
|
||||
class_id=1, class_name="box", track_id=1)
|
||||
m = _RecordingManager()
|
||||
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
|
||||
+201
-10
@@ -395,6 +395,9 @@ FCP_ZONE = {
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
|
||||
# FCP's truck_poly_pts at reference resolution (predict.py:706-712).
|
||||
FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
||||
|
||||
# centroid (620, 320) — inside FCP's polygon in the 1280x720 analysis frame.
|
||||
INSIDE_SACK = Detection(
|
||||
bbox=(590.0, 290.0, 650.0, 350.0),
|
||||
@@ -416,7 +419,7 @@ 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):
|
||||
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0, events=None):
|
||||
self.line_y = line_y
|
||||
self.line_x_start = line_x_start
|
||||
self.line_x_end = line_x_end
|
||||
@@ -426,10 +429,11 @@ class _RecordingCounter:
|
||||
self.box_loading_count = 0
|
||||
self.box_unloading_count = 0
|
||||
self.seen: list[Detection] = []
|
||||
self.events = list(events or [])
|
||||
|
||||
def update(self, detections):
|
||||
self.seen.extend(detections)
|
||||
return []
|
||||
return list(self.events)
|
||||
|
||||
|
||||
class _AlwaysCountingBatch:
|
||||
@@ -444,7 +448,7 @@ class _AlwaysCountingBatch:
|
||||
is_active = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
self.sacks_calls: list[dict] = []
|
||||
|
||||
def on_batch_end(self, callback):
|
||||
pass
|
||||
@@ -452,8 +456,18 @@ class _AlwaysCountingBatch:
|
||||
def update(self, **kwargs):
|
||||
pass
|
||||
|
||||
def update_sacks(self, has_crossing_event, sacks_in_area_count, timestamp,
|
||||
loading_count=0, unloading_count=0):
|
||||
self.sacks_calls.append({
|
||||
"has_crossing_event": has_crossing_event,
|
||||
"sacks_in_area_count": sacks_in_area_count,
|
||||
})
|
||||
|
||||
def _patch_counting_fakes(monkeypatch, detections):
|
||||
def update_truck(self, truck_detected, truck_centroid, timestamp):
|
||||
pass
|
||||
|
||||
|
||||
def _patch_counting_fakes(monkeypatch, detections, events=None):
|
||||
"""Stub tracker/batch/counter so the pipeline runs offline."""
|
||||
from src import pipeline as pipe_mod
|
||||
|
||||
@@ -466,11 +480,12 @@ def _patch_counting_fakes(monkeypatch, detections):
|
||||
def update(self, frame, dets):
|
||||
return list(detections)
|
||||
|
||||
counter = _RecordingCounter()
|
||||
counter = _RecordingCounter(events=events)
|
||||
batch = _AlwaysCountingBatch()
|
||||
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker)
|
||||
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", _AlwaysCountingBatch)
|
||||
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
|
||||
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
|
||||
return counter
|
||||
return counter, batch
|
||||
|
||||
|
||||
def _fcp_polygon():
|
||||
@@ -479,9 +494,20 @@ def _fcp_polygon():
|
||||
return build_counting_polygon(FCP_ZONE, 1280, 720)
|
||||
|
||||
|
||||
def _fcp_truck_polygon():
|
||||
"""FCP's truck area scaled to the 1280x720 analysis frame."""
|
||||
from src.zone_config import build_truck_polygon
|
||||
|
||||
return build_truck_polygon(
|
||||
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
||||
1280,
|
||||
720,
|
||||
)
|
||||
|
||||
|
||||
def test_run_pipeline_drops_detection_outside_counting_polygon(tmp_path, monkeypatch):
|
||||
"""A centroid outside FCP's detection polygon never reaches the counter."""
|
||||
counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=2)
|
||||
|
||||
@@ -522,7 +548,7 @@ def test_polygon_filter_keeps_non_countable_classes():
|
||||
|
||||
def test_run_pipeline_without_polygon_keeps_all_detections(tmp_path, monkeypatch):
|
||||
"""Control: without a polygon every detection reaches the counter."""
|
||||
counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=2)
|
||||
|
||||
@@ -545,7 +571,7 @@ def test_run_merged_pipeline_drops_detection_outside_counting_polygon(tmp_path,
|
||||
"""The merged pipeline applies the same polygon filter."""
|
||||
from src.pipeline import run_merged_pipeline
|
||||
|
||||
counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=2)
|
||||
|
||||
@@ -630,6 +656,171 @@ def test_job_forwards_counting_polygon_to_both_pipelines(tmp_path, monkeypatch):
|
||||
assert seen.get("counting_polygon") is polygon
|
||||
|
||||
|
||||
def test_job_forwards_truck_polygon_to_both_pipelines(tmp_path, monkeypatch):
|
||||
"""Job.truck_polygon reaches run_pipeline and run_merged_pipeline."""
|
||||
import src.job as job_mod
|
||||
from src.job import Job, JobQueue
|
||||
from src.pipeline import MergedPipelineResult, PipelineResult
|
||||
|
||||
polygon = _fcp_truck_polygon()
|
||||
seen: dict = {}
|
||||
|
||||
def fake_run_pipeline(**kwargs):
|
||||
seen.update(kwargs)
|
||||
return PipelineResult(
|
||||
output_path="out.mp4", frame_count=1, loading_count=0, unloading_count=0,
|
||||
batch_count=0, duration_seconds=0.0, model_name="a.pt", class_filter=None,
|
||||
)
|
||||
|
||||
def fake_run_merged(**kwargs):
|
||||
seen.update(kwargs)
|
||||
return MergedPipelineResult(
|
||||
output_path="merged.mp4", frame_count=1, loading_count=0, unloading_count=0,
|
||||
batch_count=0, duration_seconds=0.0, model_names=["a.pt"], class_filter=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline)
|
||||
monkeypatch.setattr(job_mod, "run_merged_pipeline", fake_run_merged)
|
||||
|
||||
q = JobQueue(output_dir=str(tmp_path))
|
||||
models = [
|
||||
ModelConfig(
|
||||
filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
|
||||
known_classes=["sack", "truck"],
|
||||
)
|
||||
]
|
||||
|
||||
single = Job(
|
||||
job_id="job-truck-single",
|
||||
video_path="/tmp/test.mp4",
|
||||
model_configs=models,
|
||||
output_dir=str(tmp_path / "job-truck-single"),
|
||||
truck_polygon=polygon,
|
||||
)
|
||||
q._jobs[single.job_id] = single
|
||||
q._run_job(single.job_id)
|
||||
assert seen.get("truck_polygon") is polygon
|
||||
|
||||
merged = Job(
|
||||
job_id="job-truck-merged",
|
||||
video_path="/tmp/test.mp4",
|
||||
model_configs=models + [
|
||||
ModelConfig(
|
||||
filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
|
||||
known_classes=["sack"],
|
||||
)
|
||||
],
|
||||
output_dir=str(tmp_path / "job-truck-merged"),
|
||||
truck_polygon=polygon,
|
||||
)
|
||||
q._jobs[merged.job_id] = merged
|
||||
q._run_job(merged.job_id)
|
||||
assert seen.get("truck_polygon") is polygon
|
||||
|
||||
|
||||
# ── Batch FSM driven by real crossing events (FCP predict.py:1064 parity) ──
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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"}]
|
||||
)
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=12)
|
||||
|
||||
result = run_pipeline(
|
||||
video_path=video_path,
|
||||
model_config=ModelConfig(
|
||||
filename="test.pt",
|
||||
path=str(tmp_path / "test.pt"),
|
||||
stem="test",
|
||||
known_classes=["sack"],
|
||||
),
|
||||
output_path=str(tmp_path / "out.mp4"),
|
||||
preview_enabled=False,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def test_run_merged_pipeline_drives_batch_fsm_every_frame_with_real_events(tmp_path, monkeypatch):
|
||||
"""The merged runner drives the seam the same way."""
|
||||
from src.pipeline import run_merged_pipeline
|
||||
|
||||
_counter, batch = _patch_counting_fakes(
|
||||
monkeypatch, [INSIDE_SACK], events=[{"direction": "loading"}]
|
||||
)
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=12)
|
||||
|
||||
result = run_merged_pipeline(
|
||||
video_path=video_path,
|
||||
model_configs=[
|
||||
ModelConfig(
|
||||
filename="a.pt",
|
||||
path=str(tmp_path / "a.pt"),
|
||||
stem="a",
|
||||
known_classes=["sack"],
|
||||
)
|
||||
],
|
||||
output_path=str(tmp_path / "merged.mp4"),
|
||||
preview_enabled=False,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def test_run_pipeline_counts_sacks_in_truck_area_for_the_fsm(tmp_path, monkeypatch):
|
||||
"""sacks_in_area_count comes from the truck polygon, not from truck presence."""
|
||||
_counter, batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK])
|
||||
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"],
|
||||
),
|
||||
output_path=str(tmp_path / "out.mp4"),
|
||||
preview_enabled=False,
|
||||
truck_polygon=_fcp_truck_polygon(),
|
||||
)
|
||||
|
||||
assert batch.sacks_calls[-1]["sacks_in_area_count"] == 1
|
||||
|
||||
|
||||
def test_run_pipeline_without_truck_polygon_reports_no_sacks_in_area(tmp_path, monkeypatch):
|
||||
"""No calibrated truck area -> no truck-area count (dynamic zone)."""
|
||||
_counter, batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK])
|
||||
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"],
|
||||
),
|
||||
output_path=str(tmp_path / "out.mp4"),
|
||||
preview_enabled=False,
|
||||
)
|
||||
|
||||
assert batch.sacks_calls[-1]["sacks_in_area_count"] == 0
|
||||
|
||||
|
||||
# ── Perf/output tuning params (signature contracts) ────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from shapely.geometry import Point
|
||||
from src.zone_config import (
|
||||
build_counting_polygon,
|
||||
build_static_roi,
|
||||
build_truck_polygon,
|
||||
list_zone_presets,
|
||||
load_zone_config,
|
||||
)
|
||||
@@ -120,3 +121,54 @@ def test_list_zone_presets(tmp_path):
|
||||
names = [p["name"] for p in presets]
|
||||
assert "p1" in names
|
||||
assert "p2" in names
|
||||
|
||||
|
||||
# ── Truck-area polygon (FCP predict.py:706-712) ──────────────────────────
|
||||
|
||||
# FCP's truck_poly_pts at reference resolution (predict.py:706-712).
|
||||
FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
||||
|
||||
|
||||
def test_build_truck_polygon_matches_fcp_reference_polygon():
|
||||
"""The truck polygon is FCP's, scaled to the analysis frame."""
|
||||
poly = build_truck_polygon(
|
||||
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
||||
1280,
|
||||
720,
|
||||
)
|
||||
assert list(poly.exterior.coords) == [
|
||||
(400.0, 256.0), (406.0, 717.0), (936.0, 718.0), (920.0, 228.0), (400.0, 256.0)
|
||||
]
|
||||
|
||||
|
||||
def test_build_truck_polygon_at_reference_resolution_is_unscaled():
|
||||
poly = build_truck_polygon(
|
||||
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
||||
1920,
|
||||
1080,
|
||||
)
|
||||
assert list(poly.exterior.coords)[:4] == [
|
||||
(600.0, 385.0), (609.0, 1076.0), (1404.0, 1078.0), (1381.0, 343.0)
|
||||
]
|
||||
|
||||
|
||||
def test_build_truck_polygon_defaults_to_1920x1080_reference():
|
||||
poly = build_truck_polygon({"truck_area": FCP_TRUCK_AREA}, 1280, 720)
|
||||
assert list(poly.exterior.coords)[0] == (400.0, 256.0)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_build_truck_polygon_none_with_too_few_points():
|
||||
assert build_truck_polygon({"truck_area": [[0, 0], [10, 10]]}, 1280, 720) is None
|
||||
|
||||
|
||||
def test_build_truck_polygon_none_on_malformed_truck_area():
|
||||
"""A malformed calibration degrades to "no truck area", never raises."""
|
||||
assert build_truck_polygon({"truck_area": [["a", "b"], [1, 2], [3, 4]]}, 1280, 720) is None
|
||||
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
|
||||
Reference in new issue
Block a user