Files

2234 lines
78 KiB
Python

"""Tests for pipeline runner (src/pipeline.py)."""
import os
import cv2
import numpy as np
import pytest
from shapely.geometry import Polygon
from src.counting import MultiClassLineCounter
from src.pipeline import apply_class_filter, run_pipeline, PipelineResult
from src.interfaces import Detection
from src.model_registry import ModelConfig
def test_pipeline_result_dataclass():
"""PipelineResult has correct fields."""
r = PipelineResult(
output_path="/tmp/out.mp4",
frame_count=100,
loading_count=5,
unloading_count=2,
batch_count=1,
duration_seconds=10.0,
model_name="v4-best.pt",
class_filter=None,
)
assert r.loading_count == 5
assert r.unloading_count == 2
assert r.net_count == 3
def test_run_pipeline_processes_video(tmp_path):
"""run_pipeline processes a 3-frame video and writes output."""
# Create a test video
video_path = str(tmp_path / "test.mp4")
writer = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*"mp4v"), 25.0, (320, 240))
for _ in range(3):
writer.write(np.zeros((240, 320, 3), dtype=np.uint8))
writer.release()
# Strengthened (controller ruling): verify the fixture video is valid.
assert os.path.exists(video_path)
cap = cv2.VideoCapture(video_path)
assert cap.isOpened()
assert int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) == 3
cap.release()
# Create a minimal .pt file placeholder (YOLO will fail to load, but we test the pipeline structure)
# For unit testing without real models, we test PipelineResult directly
pass # See integration test below for end-to-end with real models
def test_apply_class_filter_keeps_only_selected():
"""apply_class_filter keeps only classes in the filter; None/[] keep all."""
dets = [
Detection(bbox=(0, 0, 1, 1), confidence=0.9, class_id=0, class_name="sack"),
Detection(bbox=(0, 0, 1, 1), confidence=0.9, class_id=1, class_name="box"),
Detection(bbox=(0, 0, 1, 1), confidence=0.9, class_id=0, class_name="sack"),
]
filtered = apply_class_filter(dets, ["sack"])
assert [d.class_name for d in filtered] == ["sack", "sack"]
assert apply_class_filter(dets, None) == dets
assert apply_class_filter(dets, []) == dets
def test_run_pipeline_no_model_raises(tmp_path):
"""run_pipeline raises RuntimeError if video can't be opened."""
with pytest.raises(RuntimeError, match="Cannot open video"):
run_pipeline(
video_path=str(tmp_path / "nonexistent.mp4"),
model_config=ModelConfig(filename="test.pt", path="/nonexistent.pt", stem="test", known_classes=["sack"]),
output_path=str(tmp_path / "out.mp4"),
)
def test_run_pipeline_accepts_frame_callback(tmp_path):
"""run_pipeline signature accepts frame_callback parameter."""
import inspect
sig = inspect.signature(run_pipeline)
assert "frame_callback" in sig.parameters
param = sig.parameters["frame_callback"]
assert param.default is None
def test_run_pipeline_accepts_cancel_check(tmp_path):
"""run_pipeline signature accepts cancel_check parameter."""
import inspect
sig = inspect.signature(run_pipeline)
assert "cancel_check" in sig.parameters
param = sig.parameters["cancel_check"]
assert param.default is None
def test_cancel_check_breaks_pipeline(tmp_path):
"""run_pipeline stops early when cancel_check returns True."""
# Create a test video with many frames
video_path = str(tmp_path / "test_cancel.mp4")
writer = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*"mp4v"), 25.0, (320, 240))
for _ in range(120):
writer.write(np.zeros((240, 320, 3), dtype=np.uint8))
writer.release()
cancel_called = [0]
def fake_cancel_check():
cancel_called[0] += 1
return True # cancel immediately
# Without a real model this will fail at YOLO load, but we verify cancel_check is called
# by checking the function accepts it and the loop would break
import inspect
sig = inspect.signature(run_pipeline)
assert "cancel_check" in sig.parameters
# ── Truck class must never be counted ────────────────────────────────────
def _cross_det(class_name: str, track_id: int, y1: float, x: float) -> Detection:
"""Detection whose top edge (y1) sits above/below a line at y=100."""
return Detection(
bbox=(x, y1, x + 40, y1 + 40),
confidence=0.9,
class_id=0,
class_name=class_name,
track_id=track_id,
)
def test_countable_detections_excludes_truck():
"""Pipeline's count filter keeps sack/box, drops truck."""
from src.pipeline import countable_detections
dets = [
_cross_det("sack", 1, 50.0, 100.0),
_cross_det("truck", 2, 50.0, 200.0),
_cross_det("box", 3, 50.0, 150.0),
]
assert [d.class_name for d in countable_detections(dets)] == ["sack", "box"]
def test_truck_crossing_not_counted_after_filter():
"""Sack + truck both cross the line; only the sack increments the counter."""
from src.pipeline import countable_detections
counter = MultiClassLineCounter(line_y=100, line_x_start=0, line_x_end=320, margin=20)
# frame 1: both above the line
counter.update(countable_detections([
_cross_det("sack", 1, 50.0, 100.0),
_cross_det("truck", 2, 50.0, 200.0),
]))
# frame 2: both below the line (crossing)
events = counter.update(countable_detections([
_cross_det("sack", 1, 150.0, 100.0),
_cross_det("truck", 2, 150.0, 200.0),
]))
assert counter.loading_count == 1
assert counter.unloading_count == 0
assert [ev["track_id"] for ev in events] == [1]
assert all(ev["track_id"] != 2 for ev in events)
def test_multiclass_line_counter_ignores_truck_class():
"""MultiClassLineCounter drops truck detections entirely (defense in depth)."""
counter = MultiClassLineCounter(line_y=100, line_x_start=0, line_x_end=320, margin=20)
counter.update([_cross_det("truck", 9, 50.0, 100.0)])
events = counter.update([_cross_det("truck", 9, 150.0, 100.0)])
assert events == []
assert counter.loading_count == 0
assert counter.unloading_count == 0
assert counter.box_loading_count == 0
assert counter.box_unloading_count == 0
assert counter.net_count == 0
def test_dashboard_label_uses_class_name(monkeypatch):
"""_draw_detections renders det.class_name, not hardcoded 'sack'."""
from src import dashboard as dash_mod
drawn: list[str] = []
monkeypatch.setattr(
dash_mod.cv2, "putText",
lambda frame, text, *args, **kwargs: drawn.append(text),
)
frame = np.zeros((240, 320, 3), dtype=np.uint8)
dash_mod.DashboardOverlay()._draw_detections(
frame, [_cross_det("truck", 7, 50.0, 100.0)]
)
assert any(t.startswith("truck") for t in drawn), drawn
# ── Box count propagation to results (Task 2) ───────────────────────────
def _box_result_kwargs() -> dict:
return dict(
output_path="/tmp/out.mp4",
frame_count=100,
loading_count=5,
unloading_count=2,
batch_count=1,
duration_seconds=10.0,
class_filter=None,
)
def test_pipeline_result_box_fields_default_zero():
"""PipelineResult box fields default to 0, box_net_count derives."""
r = PipelineResult(model_name="v4-best.pt", **_box_result_kwargs())
assert r.box_loading_count == 0
assert r.box_unloading_count == 0
assert r.box_net_count == 0
def test_pipeline_result_box_fields_accept_values():
"""PipelineResult accepts box counts, box_net_count = in - out."""
r = PipelineResult(
model_name="v4-best.pt",
**_box_result_kwargs(),
box_loading_count=4,
box_unloading_count=1,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (4, 1, 3)
def test_merged_pipeline_result_box_fields():
"""MergedPipelineResult has same box fields with defaults."""
from src.pipeline import MergedPipelineResult
kwargs = _box_result_kwargs()
r = MergedPipelineResult(
model_names=["a.pt", "b.pt"],
**kwargs,
box_loading_count=2,
box_unloading_count=5,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (2, 5, -3)
r0 = MergedPipelineResult(model_names=["a.pt"], **kwargs)
assert (r0.box_loading_count, r0.box_unloading_count, r0.box_net_count) == (0, 0, 0)
class _FakeCounter:
"""Stands in for MultiClassLineCounter with fixed counts."""
def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0, **kwargs):
self.line_y = line_y
self.line_x_start = line_x_start
self.line_x_end = line_x_end
self.margin = margin
self.loading_count = 7
self.unloading_count = 3
self.box_loading_count = 4
self.box_unloading_count = 1
def update(self, detections):
return []
def reset_state(self):
pass
class _FakeYOLO:
def __init__(self, path="fake.pt"):
self.names = {0: "sack", 1: "box", 2: "truck"}
self.ckpt_path = path
def _patch_pipeline_fakes(monkeypatch):
from src import detection as det_mod
from src import pipeline as pipe_mod
from src import tracking as trk_mod
class _FakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
pass
def update(self, frame, dets):
return []
monkeypatch.setattr(pipe_mod, "YOLO", _FakeYOLO)
monkeypatch.setattr(det_mod, "YOLO", _FakeYOLO)
monkeypatch.setattr(trk_mod, "YOLO", _FakeYOLO)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", _FakeCounter)
# The runners track on every frame now (FCP predict.py:1066-1067), so the
# tracker needs a stub even for the tests that only check the plumbing.
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker)
def _write_video(path: str, frames: int = 3) -> None:
writer = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"mp4v"), 25.0, (320, 240))
for _ in range(frames):
writer.write(np.zeros((240, 320, 3), dtype=np.uint8))
writer.release()
def test_run_pipeline_propagates_box_counts(tmp_path, monkeypatch):
"""run_pipeline passes counter box counts into PipelineResult."""
_patch_pipeline_fakes(monkeypatch)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path)
result = run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert result.loading_count == 7
assert result.unloading_count == 3
assert result.box_loading_count == 4
assert result.box_unloading_count == 1
assert result.box_net_count == 3
def test_run_merged_pipeline_propagates_box_counts(tmp_path, monkeypatch):
"""run_merged_pipeline passes counter box counts into MergedPipelineResult."""
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path)
cfgs = [
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a", known_classes=["sack", "box"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b", known_classes=["sack", "box"]),
]
result = run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert result.loading_count == 7
assert result.box_loading_count == 4
assert result.box_unloading_count == 1
assert result.box_net_count == 3
# ── Per-class conf gating (platform-aligned detection tuning) ─────────────
def test_apply_class_confs_per_class_thresholds():
"""box keeps >=0.35, sack keeps >=0.40, truck untouched."""
from src.pipeline import _apply_class_confs
dets = [
Detection(bbox=(0, 0, 10, 10), confidence=0.36, class_id=1, class_name="box"),
Detection(bbox=(0, 0, 10, 10), confidence=0.34, class_id=1, class_name="box"),
Detection(bbox=(0, 0, 10, 10), confidence=0.39, class_id=0, class_name="sack"),
Detection(bbox=(0, 0, 10, 10), confidence=0.40, class_id=0, class_name="sack"),
Detection(bbox=(0, 0, 10, 10), confidence=0.10, class_id=2, class_name="truck"),
]
out = _apply_class_confs(dets, sack_conf=0.4, box_conf=0.35)
assert [(d.class_name, d.confidence) for d in out] == [
("box", 0.36),
("sack", 0.40),
("truck", 0.10),
]
def test_apply_min_area_per_class_thresholds():
"""Areas below per-class min drop; unknown class kept."""
from src.pipeline import _apply_min_area
areas = {"sack": 1500, "box": 1500, "truck": 5000}
dets = [
Detection(bbox=(0, 0, 30, 30), confidence=0.9, class_id=0, class_name="sack"), # 900 drop
Detection(bbox=(0, 0, 50, 50), confidence=0.9, class_id=0, class_name="sack"), # 2500 keep
Detection(bbox=(0, 0, 100, 40), confidence=0.9, class_id=2, class_name="truck"), # 4000 drop
Detection(bbox=(0, 0, 100, 60), confidence=0.9, class_id=2, class_name="truck"), # 6000 keep
Detection(bbox=(0, 0, 10, 10), confidence=0.9, class_id=9, class_name="unknown"), # min 0 keep
]
out = _apply_min_area(dets, areas)
assert [(d.class_name, (d.bbox[2] - d.bbox[0]) * (d.bbox[3] - d.bbox[1])) for d in out] == [
("sack", 2500),
("truck", 6000),
("unknown", 100),
]
def test_scaled_min_areas_platform_parity():
"""1080p frames scale thresholds 2.25x; 720p stays at platform reference."""
from src.pipeline import _scaled_min_areas
cfg = {"min_bbox_area": {"sack": 1500, "box": 1500, "truck": 5000}}
# Native 720p == platform's reference resolution → unchanged
at_720p = _scaled_min_areas(cfg, 1280, 720)
assert at_720p == {"sack": 1500, "box": 1500, "truck": 5000}
# 1080p: area ratio 2.25 → 1500 -> 3375, 5000 -> 11250
at_1080p = _scaled_min_areas(cfg, 1920, 1080)
assert at_1080p["sack"] == 3375
assert at_1080p["truck"] == 11250
# ── Counting polygon filter (FCP detection_polygon parity) ──────────────
# FCP's detection_poly_pts at reference resolution (predict.py:692-697).
FCP_ZONE = {
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"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]]
# 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),
confidence=0.9,
class_id=0,
class_name="sack",
track_id=1,
)
# centroid (70, 320) — left of FCP's polygon.
OUTSIDE_SACK = Detection(
bbox=(40.0, 290.0, 100.0, 350.0),
confidence=0.9,
class_id=0,
class_name="sack",
track_id=2,
)
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,
emit_every=1):
self.line_y = line_y
self.line_x_start = line_x_start
self.line_x_end = line_x_end
self.margin = margin
self.loading_count = 0
self.unloading_count = 0
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
self.reset_state_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)
def reset_state(self):
self.reset_state_calls += 1
class _AlwaysCountingBatch:
"""Batch manager stub: the batch is open, so the counter is always fed."""
current_batch_id = 1
history: list = []
state = "COUNTING_SACKS"
batch_duration = 0.0
stabilize_progress = 1.0
waiting_duration = 0.0
is_active = True
def __init__(self, *args, **kwargs):
self.sacks_calls: list[dict] = []
self.start_callbacks: list = []
def on_batch_start(self, callback):
self.start_callbacks.append(callback)
def on_batch_end(self, callback):
pass
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 update_truck(self, truck_detected, truck_centroid, timestamp):
pass
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
_patch_pipeline_fakes(monkeypatch)
class _FakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
pass
def update(self, frame, dets):
return list(detections)
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)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
return counter, batch
def _fcp_polygon():
from src.zone_config import build_counting_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, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_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,
counting_polygon=_fcp_polygon(),
)
assert counter.seen, "counter never received a detection"
assert {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox}
def test_polygon_filter_keeps_non_countable_classes():
"""FCP filters sacks/boxes only — a truck outside the polygon keeps its box."""
from src.pipeline import filter_by_counting_polygon
truck = Detection(
bbox=(40.0, 290.0, 100.0, 350.0),
confidence=0.9,
class_id=2,
class_name="truck",
track_id=3,
)
poly = _fcp_polygon()
assert filter_by_counting_polygon([truck], poly) == [truck]
assert filter_by_counting_polygon([OUTSIDE_SACK], poly) == []
assert filter_by_counting_polygon([INSIDE_SACK], poly) == [INSIDE_SACK]
def test_run_pipeline_without_polygon_keeps_all_detections(tmp_path, monkeypatch):
"""Control: without a polygon every detection reaches the counter."""
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_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 {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox, OUTSIDE_SACK.bbox}
def test_run_merged_pipeline_drops_detection_outside_counting_polygon(tmp_path, monkeypatch):
"""The merged pipeline applies the same polygon filter."""
from src.pipeline import run_merged_pipeline
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK])
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"],
)
],
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
counting_polygon=_fcp_polygon(),
)
assert counter.seen, "counter never received a detection"
assert {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox}
def test_job_forwards_counting_polygon_to_both_pipelines(tmp_path, monkeypatch):
"""Job.counting_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_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-poly-single",
video_path="/tmp/test.mp4",
model_configs=models,
output_dir=str(tmp_path / "job-poly-single"),
counting_polygon=polygon,
)
q._jobs[single.job_id] = single
q._run_job(single.job_id)
assert seen.get("counting_polygon") is polygon
merged = Job(
job_id="job-poly-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-poly-merged"),
counting_polygon=polygon,
)
q._jobs[merged.job_id] = merged
q._run_job(merged.job_id)
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 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"}], emit_every=2
)
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 [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):
"""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"}], emit_every=2
)
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 [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):
"""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) ────────────────────
@pytest.mark.parametrize(
"fn_name", ["run_pipeline", "run_merged_pipeline"]
)
def test_pipeline_perf_params_signature(fn_name):
"""Both runners expose detect_interval=None, output_max_height=None, preview_every_n=None."""
import inspect
from src import pipeline as pipe_mod
sig = inspect.signature(getattr(pipe_mod, fn_name))
assert sig.parameters["detect_interval"].default is None
assert sig.parameters["output_max_height"].default is None
assert sig.parameters["preview_every_n"].default is None
# ── _AsyncWriter (encode off main loop) ─────────────────────────────────
class _RecordingWriter:
"""Fake underlying writer: records frames, counts finish() calls."""
def __init__(self):
self.frames = []
self.finish_calls = 0
def write_frame(self, frame):
self.frames.append(frame)
def finish(self):
self.finish_calls += 1
def test_async_writer_preserves_order_and_finishes():
"""_AsyncWriter writes frames 1..20 in order, then finish() exactly once."""
from src.pipeline import _AsyncWriter
fake = _RecordingWriter()
aw = _AsyncWriter(fake)
for i in range(1, 21):
aw.put(i)
aw.close()
assert fake.frames == list(range(1, 21))
assert fake.finish_calls == 1
# ── Batch start resets the per-track counting state (Task 7) ─────────────
class _BatchStartFiringBatch(_AlwaysCountingBatch):
"""Batch manager stub: fires the batch-start callback when the batch opens."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fired = False
def update_sacks(self, has_crossing_event, sacks_in_area_count, timestamp,
loading_count=0, unloading_count=0):
super().update_sacks(has_crossing_event, sacks_in_area_count, timestamp,
loading_count, unloading_count)
if not self.fired:
self.fired = True
for cb in self.start_callbacks:
cb(1, timestamp)
class _RecordingStabilizer:
"""Stabilizer stub that records reset() calls."""
def __init__(self, *args, **kwargs):
self.reset_calls = 0
def update(self, detections):
return list(detections)
def reset(self):
self.reset_calls += 1
def _patch_batch_start_fakes(monkeypatch):
"""Stub tracker/batch/counter/stabilizer so the pipeline runs offline."""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
class _FakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
pass
def update(self, frame, dets):
return [INSIDE_SACK]
counter = _RecordingCounter()
batch = _BatchStartFiringBatch()
stabilizer = _RecordingStabilizer()
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
monkeypatch.setattr(pipe_mod, "BboxStabilizer", lambda *a, **kw: stabilizer)
return counter, batch, stabilizer
@pytest.mark.parametrize("fn_name", ["run_pipeline", "run_merged_pipeline"])
def test_batch_start_resets_per_track_state(tmp_path, monkeypatch, fn_name):
"""The batch-start hook reaches the counter and the stabilizer."""
from src import pipeline as pipe_mod
counter, batch, stabilizer = _patch_batch_start_fakes(monkeypatch)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=3)
if fn_name == "run_pipeline":
pipe_mod.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,
)
else:
pipe_mod.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.start_callbacks, "no batch-start callback registered"
assert counter.reset_state_calls == 1
assert stabilizer.reset_calls == 1
# ── Truncated clip flag (Task 10) ───────────────────────────────────────
def test_is_truncated_detects_short_decode():
from src.pipeline import is_truncated
assert is_truncated(100, 100) is False
assert is_truncated(100, 99) is False
assert is_truncated(100, 40) is True
assert is_truncated(0, 10) is False # unknown length -> not truncated
@pytest.mark.parametrize("raw,expected", [
(100.0, 100),
(0.0, 0),
(-1.0, 0),
(float("nan"), 0),
])
def test_expected_frames_reads_container_count_defensively(raw, expected):
"""A broken container length (0/NaN/negative) reads as 0, never a crash."""
from src.pipeline import _expected_frames
class _Cap:
def get(self, prop):
return raw
assert _expected_frames(_Cap()) == expected
class _StubCapture:
"""Capture stub: claims a frame count it does not deliver."""
def __init__(self, expected_frames: int, frames_yielded: int):
self._expected = expected_frames
self._remaining = frames_yielded
def isOpened(self):
return True
def get(self, prop):
return {
cv2.CAP_PROP_FPS: 25.0,
cv2.CAP_PROP_FRAME_COUNT: float(self._expected),
cv2.CAP_PROP_FRAME_WIDTH: 320.0,
cv2.CAP_PROP_FRAME_HEIGHT: 240.0,
}.get(prop, 0.0)
def read(self):
if self._remaining <= 0:
return False, None
self._remaining -= 1
return True, np.zeros((240, 320, 3), dtype=np.uint8)
def release(self):
pass
def _run_runner(runner_name, tmp_path):
"""Run one of the two pipeline runners against the fake model/detector fakes."""
from src import pipeline as pipe_mod
from src.model_registry import ModelConfig
if runner_name == "run_pipeline":
return pipe_mod.run_pipeline(
video_path=str(tmp_path / "in.mp4"),
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,
)
return pipe_mod.run_merged_pipeline(
video_path=str(tmp_path / "in.mp4"),
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,
)
@pytest.mark.parametrize("runner_name", ["run_pipeline", "run_merged_pipeline"])
def test_runner_flags_truncated_clip(tmp_path, monkeypatch, runner_name):
"""A clip decoding fewer frames than the container claims is flagged."""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
capture = _StubCapture(expected_frames=100, frames_yielded=40)
monkeypatch.setattr(pipe_mod.cv2, "VideoCapture", lambda *a, **kw: capture)
result = _run_runner(runner_name, tmp_path)
assert result.frame_count == 40
assert result.frames_expected == 100
assert result.truncated is True
@pytest.mark.parametrize("runner_name", ["run_pipeline", "run_merged_pipeline"])
def test_runner_does_not_flag_complete_clip(tmp_path, monkeypatch, runner_name):
"""A clip that decodes every declared frame is not flagged."""
_patch_pipeline_fakes(monkeypatch)
_write_video(str(tmp_path / "in.mp4"), frames=3)
result = _run_runner(runner_name, tmp_path)
assert result.frame_count == 3
assert result.frames_expected == 3
assert result.truncated is False
def test_async_writer_surfaces_first_write_error():
"""Writer failing on frame 3 raises that error from close(); queue still drains."""
from src.pipeline import _AsyncWriter
class BoomWriter(_RecordingWriter):
def write_frame(self, frame):
if frame == 3:
raise RuntimeError("encode boom")
super().write_frame(frame)
fake = BoomWriter()
aw = _AsyncWriter(fake)
with pytest.raises(RuntimeError, match="encode boom"):
for i in range(1, 7):
aw.put(i)
aw.close()
# No partial-finish: error surfaced before finish().
assert fake.finish_calls == 0
# Worker keeps draining after the failure (frames 4..6 still written).
assert fake.frames == [1, 2, 4, 5, 6]
# ── Count-line x-window (FCP predict.py:701-703 parity) ──────────────────
def _count_line_zone():
"""A fixed zone whose calibrated count-line window differs from the ROI bounds."""
from src.truck_roi import TruckROI
return TruckROI(
x1=400, y1=256, x2=936, y2=718, # truck-ROI bounds
line_y=220,
confidence=1.0,
fixed=True,
line_x_start=384, # FCP's calibrated count-line window
line_x_end=934,
)
def _model_config(tmp_path):
return ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack"],
)
def test_pipeline_uses_the_count_line_x_window_for_the_counter(tmp_path, monkeypatch):
"""The counter counts inside the calibrated window, not the truck-ROI bounds."""
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=_model_config(tmp_path),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
fixed_zone=_count_line_zone(),
)
assert counter.line_x_start == 384
assert counter.line_x_end == 934
def test_merged_pipeline_uses_the_count_line_x_window_for_the_counter(tmp_path, monkeypatch):
"""The merged runner counts inside the calibrated window too."""
from src.pipeline import run_merged_pipeline
counter, _batch = _patch_counting_fakes(monkeypatch, [INSIDE_SACK])
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"],
)
],
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
fixed_zone=_count_line_zone(),
)
assert counter.line_x_start == 384
assert counter.line_x_end == 934
def test_pipeline_falls_back_to_the_roi_bounds_without_a_count_line(tmp_path, monkeypatch):
"""An auto-detected ROI has no calibrated line -> the ROI bounds are the window."""
from src.truck_roi import TruckROI
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=_model_config(tmp_path),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
fixed_zone=TruckROI(
x1=400, y1=256, x2=936, y2=718, line_y=220, confidence=1.0, fixed=True
),
)
assert counter.line_x_start == 400
assert counter.line_x_end == 936
# ── Batch lifecycle parity (FCP predict.py:739-745, :1066-1067) ────────
class _IdleBatch:
"""Batch manager stub for a batch that is NOT open.
Records how the manager was constructed (FCP's arguments) and how the
FSM was driven (the truck signal).
"""
is_active = False
current_batch_id = None
history: list = []
state = "IDLE"
batch_duration = 0.0
stabilize_progress = 0.0
waiting_duration = 0.0
def __init__(self, *args, **kwargs):
self.init_args = args
self.init_kwargs = kwargs
self.sacks_calls: list[dict] = []
self.truck_calls: list[tuple] = []
def on_batch_start(self, callback):
pass
def on_batch_end(self, callback):
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 update_truck(self, truck_detected, truck_centroid, timestamp):
self.truck_calls.append((truck_detected, truck_centroid))
def _patch_tracker(monkeypatch, pipe_mod, frame_dets):
"""Tracker stub: frame N yields frame_dets[N] (the last one repeats)."""
class _FakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.calls = 0
def update(self, frame, dets):
dets_for_frame = frame_dets[min(self.calls, len(frame_dets) - 1)]
self.calls += 1
return list(dets_for_frame)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker)
def _patch_stabilizer(monkeypatch, pipe_mod):
"""Stabilizer stub: passes detections through (no EMA lag in the test)."""
class _PassThroughStabilizer:
def __init__(self, *args, **kwargs):
pass
def update(self, detections):
return list(detections)
def reset(self):
pass
monkeypatch.setattr(pipe_mod, "BboxStabilizer", _PassThroughStabilizer)
def _patch_real_counter(monkeypatch, pipe_mod):
"""Use the real line counter, but record what it was fed."""
counters: list = []
class _RecordingRealCounter(MultiClassLineCounter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.seen: list[Detection] = []
counters.append(self)
def update(self, detections):
self.seen.extend(detections)
return super().update(detections)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", _RecordingRealCounter)
return counters
# A sack that crosses the count line (y=360 in the 1280x720 analysis frame).
# The y1 jump stays inside the FCP gates: <= max_step_dy (160 px) per frame and
# below the corridor bound (line_y + capture_below = 460 px).
SACK_ABOVE = Detection(
bbox=(600.0, 280.0, 640.0, 320.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
SACK_BELOW = Detection(
bbox=(600.0, 400.0, 640.0, 440.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
def _run_with_runner(runner_name, tmp_path, **kwargs):
"""Drive one of the two runners with the offline fakes in place."""
from src import pipeline as pipe_mod
if runner_name == "run_pipeline":
return pipe_mod.run_pipeline(
video_path=str(tmp_path / "in.mp4"),
model_config=_model_config(tmp_path),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
**kwargs,
)
return pipe_mod.run_merged_pipeline(
video_path=str(tmp_path / "in.mp4"),
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,
**kwargs,
)
def test_truck_signal_needs_the_truck_inside_the_counting_polygon():
"""FCP keeps a truck only when >=50% of its bbox is inside the polygon (predict.py:893-902)."""
from src.pipeline import truck_detection_centroid
from src.zone_config import build_counting_polygon
poly = build_counting_polygon(FCP_ZONE, 1280, 720)
inside = Detection(bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.9, class_id=2,
class_name="truck", track_id=9)
outside = Detection(bbox=(0.0, 0.0, 100.0, 100.0), confidence=0.9, class_id=2,
class_name="truck", track_id=9)
mostly_outside = Detection(bbox=(200.0, 100.0, 400.0, 200.0), confidence=0.9,
class_id=2, class_name="truck", track_id=9)
assert truck_detection_centroid([outside], poly) is None
assert truck_detection_centroid([mostly_outside], poly) is None
assert truck_detection_centroid([inside], poly) == (650.0, 150.0)
# Without a polygon every truck counts.
assert truck_detection_centroid([outside], None) == (50.0, 50.0)
@pytest.mark.parametrize("runner_name", ["run_pipeline", "run_merged_pipeline"])
def test_runner_counts_while_no_batch_is_open(tmp_path, monkeypatch, runner_name):
"""A crossing before the batch opens is still counted (FCP predict.py:1066-1067).
FCP runs the line-crossing counter on every frame; the recounter used to
feed it only while a batch was open, so the first crossings of a clip
were lost.
"""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
counters = _patch_real_counter(monkeypatch, pipe_mod)
_patch_stabilizer(monkeypatch, pipe_mod)
_patch_tracker(monkeypatch, pipe_mod, [[SACK_ABOVE], [SACK_BELOW]])
batch = _IdleBatch()
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
video_path = str(tmp_path / "in.mp4")
_write_video(video_path, frames=3)
result = _run_with_runner(runner_name, tmp_path)
assert counters, "the runner built no counter"
assert counters[0].seen, "counter never received a detection"
assert result.loading_count == 1, "the crossing was not counted"
@pytest.mark.parametrize("runner_name", ["run_pipeline", "run_merged_pipeline"])
def test_runner_builds_the_batch_manager_with_fcp_arguments(tmp_path, monkeypatch, runner_name):
"""The FSM is constructed with FCP's arguments (predict.py:739-745)."""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
_patch_tracker(monkeypatch, pipe_mod, [[]])
created: list = []
def factory(*args, **kwargs):
mgr = _IdleBatch(*args, **kwargs)
created.append(mgr)
return mgr
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", factory)
video_path = str(tmp_path / "in.mp4")
_write_video(video_path, frames=2)
_run_with_runner(runner_name, tmp_path)
assert len(created) == 1
assert created[0].init_args == (), "FCP passes the arguments by keyword"
assert created[0].init_kwargs == {
"stabilize_seconds": 0.0,
"stabilize_threshold_px": 9999.0,
"sack_idle_timeout": 20.0,
"min_batch_duration": 5.0,
"truck_gone_tolerance": 30.0,
}
@pytest.mark.parametrize("runner_name", ["run_pipeline", "run_merged_pipeline"])
def test_fixed_mode_uses_the_truck_detector_for_the_batch_signal(tmp_path, monkeypatch, runner_name):
"""In fixed mode the FSM's truck signal is the real detection, not the static ROI.
The calibrated zone is a fixed AREA — it says where to count, not that a
truck is there. FCP always runs the truck model (predict.py:882) and uses
the real detections (predict.py:964).
"""
from src import pipeline as pipe_mod
from src.truck_roi import TruckROI
truck_dets: list[Detection] = []
detector_calls: list[int] = []
class _StubDetector:
def __init__(self, model, conf=0.0, class_filter=None):
self.class_filter = class_filter
def detect(self, frame):
if self.class_filter == ("truck",):
detector_calls.append(1)
return list(truck_dets)
return []
_patch_pipeline_fakes(monkeypatch)
monkeypatch.setattr(pipe_mod, "BaseDetector", _StubDetector)
_patch_tracker(monkeypatch, pipe_mod, [[]])
counters: list = []
class _RecordingFakeCounter(_FakeCounter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
counters.append(self)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", _RecordingFakeCounter)
batch = _IdleBatch()
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
video_path = str(tmp_path / "in.mp4")
_write_video(video_path, frames=12)
fixed = TruckROI(
x1=400, y1=256, x2=936, y2=718,
line_y=220,
confidence=1.0,
fixed=True,
line_x_start=384,
line_x_end=934,
)
truck_model = ModelConfig(
filename="truck.pt",
path=str(tmp_path / "truck.pt"),
stem="truck",
known_classes=["truck"],
)
# No truck in the scene -> the FSM must see "no truck", not the zone's
# constant confidence=1.0.
_run_with_runner(runner_name, tmp_path, fixed_zone=fixed, truck_model_config=truck_model)
assert batch.truck_calls
assert [detected for detected, _ in batch.truck_calls] == [False] * 12
assert all(centroid is None for _, centroid in batch.truck_calls)
# The calibrated zone still provides the counting geometry.
assert counters[0].line_y == 220
assert counters[0].line_x_start == 384
assert counters[0].line_x_end == 934
# A truck in the scene -> the FSM sees it, on FCP's every-5-frames
# cadence with the detection cached in between (predict.py:882).
truck_dets.append(
Detection(
bbox=(600.0, 100.0, 800.0, 300.0), confidence=0.9, class_id=2,
class_name="truck", track_id=9,
)
)
batch.truck_calls.clear()
detector_calls.clear()
_run_with_runner(runner_name, tmp_path, fixed_zone=fixed, truck_model_config=truck_model)
assert len(detector_calls) == 2, "truck detection must run every 5th frame"
assert [detected for detected, _ in batch.truck_calls] == [False] * 4 + [True] * 8
assert batch.truck_calls[-1][1] == (700.0, 200.0)
# ── Cross-model dedup only (FCP predict.py:891) ──────────────────────────
# Two sacks of the SAME model overlapping by IoU 0.56 (a stack on the truck).
_OVERLAP_A = Detection(
bbox=(600.0, 300.0, 700.0, 400.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
_OVERLAP_B = Detection(
bbox=(620.0, 310.0, 720.0, 410.0), confidence=0.8, class_id=0,
class_name="sack", track_id=2,
)
# The same object seen by ANOTHER model (no track id yet).
_OVERLAP_DUPE = Detection(
bbox=(605.0, 302.0, 705.0, 402.0), confidence=0.7, class_id=0,
class_name="sack", track_id=None,
)
def test_deduplicate_detections_only_merges_across_models():
"""FCP keeps every tracked detection (predict.py:891).
Two detections of the SAME model are two objects (sacks stacked on the
truck overlap) — dropping the lower-confidence one loses a crossing.
A detection that duplicates an object from ANOTHER model is one object.
"""
from src.pipeline import _deduplicate_detections
kept = _deduplicate_detections(
[_OVERLAP_A, _OVERLAP_B], [_OVERLAP_DUPE], iou_threshold=0.5
)
assert [d.bbox for d in kept] == [_OVERLAP_A.bbox, _OVERLAP_B.bbox]
def test_deduplicate_detections_keeps_an_extra_that_is_not_a_duplicate():
"""An extra detection of another object stays."""
from src.pipeline import _deduplicate_detections
far_away = Detection(
bbox=(100.0, 100.0, 200.0, 200.0), confidence=0.7, class_id=0,
class_name="sack", track_id=None,
)
kept = _deduplicate_detections([_OVERLAP_A], [far_away], iou_threshold=0.5)
assert [d.bbox for d in kept] == [_OVERLAP_A.bbox, far_away.bbox]
def test_the_merged_runner_keeps_overlapping_sacks_of_one_model(tmp_path, monkeypatch):
"""The merged runner must not drop a sack that overlaps another sack."""
from src.pipeline import run_merged_pipeline
counter, _batch = _patch_counting_fakes(monkeypatch, [_OVERLAP_A, _OVERLAP_B])
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"],
)
],
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert {d.bbox for d in counter.seen} == {_OVERLAP_A.bbox, _OVERLAP_B.bbox}
# ── Zone polygons in the annotated output ───────────────────────────────
def test_dashboard_draws_zone_polygons():
"""The overlay draws the calibrated polygons, not just the ROI box."""
from src.dashboard import DashboardOverlay
counting = Polygon([(383, 33), (391, 718), (945, 717), (931, 33)])
truck = Polygon([(400, 257), (406, 717), (936, 719), (921, 229)])
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], None, 0, 0, None, None,
counting_polygon=counting, truck_polygon=truck,
)
assert out.shape == frame.shape
# A pixel on the truck polygon edge must be lit in the truck colour.
assert out[257, 400].tolist() == [0, 165, 255]
# Same for the counting polygon edge.
assert out[33, 383].tolist() == [235, 99, 37]
def test_dashboard_count_band_spans_calibrated_window():
"""The count band follows roi.line_x_start/line_x_end, not the ROI bounds."""
from src.dashboard import DashboardOverlay
from src.truck_roi import TruckROI
# ROI bounds are wide; the calibrated count window is a narrow slice
# inside them — the counter only counts in that slice.
roi = TruckROI(
x1=100, y1=100, x2=1000, y2=600, line_y=300, confidence=1.0,
fixed=False, line_x_start=400, line_x_end=800,
)
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], roi, 0, 0, None, None,
)
# Inside the calibrated window → magenta band.
assert out[310, 500].tolist() == [38, 0, 38]
# Inside the ROI bounds but outside the calibrated window → no band.
assert out[310, 200].tolist() == [0, 0, 0]
assert out[310, 900].tolist() == [0, 0, 0]
def test_dashboard_draws_no_band_for_inverted_calibrated_window():
"""An inverted calibrated window counts nothing, so no band is drawn."""
from src.dashboard import DashboardOverlay
from src.truck_roi import TruckROI
roi = TruckROI(
x1=100, y1=100, x2=1000, y2=600, line_y=300, confidence=1.0,
fixed=False, line_x_start=800, line_x_end=400,
)
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
out = DashboardOverlay().draw(
frame, [], roi, 0, 0, None, None,
)
# No band anywhere — not over the ROI bounds either.
assert out[310, 200].tolist() == [0, 0, 0]
assert out[310, 500].tolist() == [0, 0, 0]
def test_dashboard_draws_polygons_behind_detection_boxes():
"""Polygons go down first, so the detection boxes stay readable."""
from src.dashboard import DashboardOverlay
# A polygon edge that runs right along a detection box edge.
counting = Polygon([(383, 33), (383, 200), (500, 200), (500, 33)])
frame = np.zeros((720, 1280, 3), dtype=np.uint8)
det = Detection(
bbox=(383, 33, 500, 200), confidence=0.9, class_id=0, class_name="sack",
)
out = DashboardOverlay().draw(
frame, [det], None, 0, 0, None, None, counting_polygon=counting,
)
# The box edge (green top line) sits on top of the polygon edge.
assert out[33, 400].tolist() == [0, 200, 0]
def test_pipeline_forwards_zone_polygons_to_dashboard(tmp_path, monkeypatch):
"""run_pipeline hands the zone polygons to the dashboard overlay."""
from src import pipeline as pipe_mod
_patch_pipeline_fakes(monkeypatch)
seen: list[dict] = []
class _RecordingDashboard:
def draw(self, frame, **kwargs):
seen.append(kwargs)
return frame
monkeypatch.setattr(pipe_mod, "DashboardOverlay", _RecordingDashboard)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path)
counting = Polygon([(383, 33), (391, 718), (945, 717), (931, 33)])
truck = Polygon([(400, 257), (406, 717), (936, 719), (921, 229)])
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
counting_polygon=counting,
truck_polygon=truck,
)
assert seen, "dashboard.draw() was never called"
assert all(call["counting_polygon"] is counting for call in seen)
assert all(call["truck_polygon"] is truck for call in seen)
# ── FCP full pipeline parity (pre-stabilizer filter, suppression, Mode D) ──
def test_truck_detection_centroid_picks_largest_valid_truck():
"""FCP picks the largest valid truck inside the counting polygon (predict.py:1088-1093)."""
from src.pipeline import truck_detection_centroid
poly = _fcp_polygon()
small = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.95, class_id=2,
class_name="truck", track_id=1,
) # area 10_000, centroid (650, 150)
large = Detection(
bbox=(700.0, 200.0, 900.0, 400.0), confidence=0.70, class_id=2,
class_name="truck", track_id=2,
) # area 40_000, centroid (800, 300)
assert truck_detection_centroid([small, large], poly) == (800.0, 300.0)
# Equal-area tie-breaker picks higher confidence
eq_low = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.60, class_id=2,
class_name="truck", track_id=3,
)
eq_high = Detection(
bbox=(700.0, 100.0, 800.0, 200.0), confidence=0.90, class_id=2,
class_name="truck", track_id=4,
)
assert truck_detection_centroid([eq_low, eq_high], poly) == (750.0, 150.0)
def test_subthreshold_box_does_not_suppress_valid_sack(tmp_path, monkeypatch):
"""Boxes below box_conf or min_bbox_area.box are dropped before suppression."""
from src import pipeline as pipe_mod
low_conf_box = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.31, class_id=1,
class_name="box", track_id=2,
)
valid_sack_a = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
)
tiny_box = Detection(
bbox=(700.0, 290.0, 720.0, 330.0), confidence=0.90, class_id=1,
class_name="box", track_id=4,
) # area 800 < 1000
valid_sack_b = Detection(
bbox=(700.0, 290.0, 740.0, 330.0), confidence=0.90, class_id=0,
class_name="sack", track_id=3,
) # area 1600 >= 1500, IoU with tiny_box = 0.50
counter, _batch = _patch_counting_fakes(
monkeypatch, [valid_sack_a, low_conf_box, valid_sack_b, tiny_box]
)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert {d.track_id for d in counter.seen} == {1, 3}
def test_occluded_sack_held_by_stabilizer_survives_confidence_decay(tmp_path, monkeypatch):
"""Conf filtering runs before BboxStabilizer so 0.85x decay does not drop held sacks."""
from src import pipeline as pipe_mod
borderline_sack = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.36, class_id=0,
class_name="sack", track_id=1,
) # >= 0.35 on frame 1; held frame 2 decays to 0.306 < 0.35
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
_patch_pipeline_fakes(monkeypatch)
_patch_tracker(monkeypatch, pipe_mod, [[borderline_sack], []])
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
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 len(counter.calls_seen) == 2
assert [d.track_id for d in counter.calls_seen[0]] == [1]
assert [d.track_id for d in counter.calls_seen[1]] == [1]
def test_merged_pipeline_selects_first_sack_model_as_primary_and_runs_dedicated_box_tracker(
tmp_path, monkeypatch
):
"""Mode D (truck, sack, box) runs ByteTrack on sack (iou=0.45) and box (iou=0.7) every frame."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
class _ModeFakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
self.calls = 0
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs, "inst": self})
def update(self, frame, dets):
self.calls += 1
if "best.pt" in self.path:
return [
Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
]
if "yolo11n" in self.path:
return [
Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeFakeTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
filters = {
"v4-best": ["truck"],
"best": ["sack"],
"yolo11n": ["box"],
}
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters=filters,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 2
assert created_trackers[0]["path"].endswith("best.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert created_trackers[0]["inst"].calls == 2
assert created_trackers[1]["path"].endswith("yolo11n.pt")
assert created_trackers[1]["kwargs"].get("iou") == 0.7
assert created_trackers[1]["inst"].calls == 2
# Frame 1 (despite sup_det_interval=5) receives both tracked sack and tracked box
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_c_does_not_share_yolo_between_tracker_and_truck_det(
tmp_path, monkeypatch
):
"""Mode C extracts trucks from primary tracker rather than sharing YOLO with BaseDetector."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
from src.truck_roi import TruckROI
_patch_pipeline_fakes(monkeypatch)
base_detector_paths: list[str] = []
class _RecordingDetector:
def __init__(self, model, conf=0.0, class_filter=None):
base_detector_paths.append(getattr(model, "ckpt_path", ""))
def detect(self, frame):
return []
truck_det = Detection(
bbox=(600.0, 100.0, 800.0, 300.0), confidence=0.8,
class_id=2, class_name="truck", track_id=99,
)
sack_det = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
box_det = Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
class _ModeCTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "v4-best" in self.path:
return [truck_det, sack_det]
if "yolo11n" in self.path:
return [box_det]
return []
batch = _IdleBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BaseDetector", _RecordingDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeCTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck", "sack"], "yolo11n": ["box"]},
fixed_zone=TruckROI(x1=400, y1=150, x2=950, y2=720, line_y=182, confidence=1.0, fixed=True),
counting_polygon=_fcp_polygon(),
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert not any("v4-best" in p for p in base_detector_paths)
assert batch.truck_calls[0] == (True, (700.0, 200.0))
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_b_uses_single_sack_box_tracker_and_separate_truck_det(
tmp_path, monkeypatch
):
"""Mode B runs one ByteTrackTracker on yolo11n (sack+box) and separate truck_det on v4-best."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
detector_filters: list[tuple] = []
class _ModeBDetector:
def __init__(self, model, conf=0.0, class_filter=None):
detector_filters.append((getattr(model, "ckpt_path", ""), class_filter))
def detect(self, frame):
return []
class _ModeBTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs})
def update(self, frame, dets):
return [
Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=1),
Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=2),
]
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ModeBDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeBTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck"], "yolo11n": ["sack", "box"]},
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 1
assert created_trackers[0]["path"].endswith("yolo11n.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert any("v4-best" in p and cf == ("truck",) for p, cf in detector_filters)
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 1), ("box", 2)}
def test_merged_pipeline_deduplicates_extra_boxes_against_box_tracker(tmp_path, monkeypatch):
"""Extra supplementary model boxes overlapping box_tracker must not double-count."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
class _ExtraDetector:
def __init__(self, model, conf=0.0, class_filter=None):
self.path = getattr(model, "ckpt_path", "")
def detect(self, frame):
if "unified" in self.path:
return [
Detection(
bbox=(705.0, 292.0, 765.0, 352.0), confidence=0.85,
class_id=1, class_name="box", track_id=None,
)
]
return []
class _DualTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "best.pt" in self.path:
return [Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=10)]
if "yolo11n" in self.path:
return [Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=20)]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ExtraDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _DualTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
ModelConfig(filename="unified.pt", path=str(tmp_path / "unified.pt"), stem="unified", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
frame5_boxes = [d for d in counter.calls_seen[4] if d.class_name == "box"]
assert [d.track_id for d in frame5_boxes] == [20]
def test_merged_pipeline_batch_start_resets_box_stabilizer(tmp_path, monkeypatch):
"""on_batch_start resets both primary stabilizer and dedicated box_stabilizer."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
stabilizers: list = []
class _TrackingStabilizer(_RecordingStabilizer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
stabilizers.append(self)
batch = _BatchStartFiringBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BboxStabilizer", _TrackingStabilizer)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(stabilizers) == 2
assert all(s.reset_calls == 1 for s in stabilizers)
def test_box_outside_roi_x_but_inside_counting_polygon_still_suppresses_sack(tmp_path, monkeypatch):
"""Cross-class suppression runs before roi.contains_x (FCP predict.py:1137->1227)."""
from src import pipeline as pipe_mod
from src.truck_roi import TruckROI
edge_box = Detection(
bbox=(355.0, 290.0, 425.0, 350.0), confidence=0.90, class_id=1,
class_name="box", track_id=2,
) # cx=390 (inside counting_poly, left of roi.x1=400)
mislabeled_sack = Detection(
bbox=(375.0, 290.0, 445.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
) # cx=410 (inside roi.x1=400), IoU = 50/90 = 0.556 >= 0.4
counter, _batch = _patch_counting_fakes(monkeypatch, [edge_box, mislabeled_sack])
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
poly = Polygon([(300, 100), (300, 700), (950, 700), (950, 100)])
fixed = TruckROI(x1=400, y1=200, x2=900, y2=700, line_y=220, confidence=1.0, fixed=True)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
fixed_zone=fixed,
counting_polygon=poly,
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert counter.seen == []