fix: match FCP's batch lifecycle (count every frame, predict.py:739-745)

This commit is contained in:
jetson committed 2026-10-28 09:57:26 +07:00
1 parent 2ca4cb6c3d
commit 1c313d97d8
5 files changed
+446 -105

No files matched your search

+8
View File
@@ -30,6 +30,14 @@ stabilizer:
ema_alpha: 0.35
max_hold: 10 # FCP parity: predict.py:668 (max_hold_frames=10)
# Batch lifecycle (FCP config.yaml:123-124 — the values the batch FSM is
# built with, karung_counter_semarang/predict.py:739-745).
batch:
timeout_seconds: 20.0 # sack-idle: N s with no crossing AND no sack
# in the truck area -> batch pauses (WAITING)
truck_gone_tolerance_seconds: 30.0 # truck-gone: in WAITING, N s with no sack and
# no truck signal -> batch ends
pipeline:
detect_interval: 1 # detection+tracking every N frames (1 = every frame, most accurate)
sup_det_interval: 5 # supplementary models every N frames
+6
View File
@@ -44,6 +44,12 @@ DEFAULTS: dict = {
"ema_alpha": 0.35,
"max_hold": 10,
},
"batch": {
# FCP config.yaml:123-124 — the batch FSM arguments
# (karung_counter_semarang/predict.py:739-745).
"timeout_seconds": 20.0,
"truck_gone_tolerance_seconds": 30.0,
},
"pipeline": {
"detect_interval": 1,
"sup_det_interval": 5,
+158 -105
View File
@@ -219,6 +219,38 @@ def compute_sacks_in_truck_area(
return count
def build_batch_manager(cfg: dict) -> BatchLifecycleManager:
"""Build FCP's batch lifecycle manager (predict.py:739-745).
FCP starts a batch the moment a truck triggers it (stabilize_seconds 0.0)
and never rejects a moving truck (stabilize_threshold_px 9999.0); the idle
and truck-gone timeouts come from the config (FCP config.yaml:123-124).
"""
return BatchLifecycleManager(
stabilize_seconds=0.0,
stabilize_threshold_px=9999.0,
sack_idle_timeout=cfg["batch"]["timeout_seconds"],
min_batch_duration=5.0,
truck_gone_tolerance=cfg["batch"]["truck_gone_tolerance_seconds"],
)
def truck_detection_centroid(
truck_detections: list[Detection],
) -> tuple[float, float] | None:
"""Centroid of the first truck detection, or None when no truck is there.
The FSM only leaves IDLE when a truck is detected AND a centroid is known
(src/batch.py:133-134), so the centroid must follow the detection.
"""
for det in truck_detections:
if det.class_name != "truck":
continue
x1, y1, x2, y2 = det.bbox
return ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
return None
def update_batch_state(
batch_mgr: BatchLifecycleManager,
*,
@@ -372,18 +404,18 @@ def run_pipeline(
shared_model, conf=effective_detector_conf, class_filter=effective_filter
)
# Truck detector — skip if fixed zone
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
truck_detector = None
if fixed_zone is None:
if truck_model_config is not None:
# Load a separate truck detection model
truck_shared = YOLO(truck_model_config.path)
truck_detector = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
elif "truck" in (model_config.known_classes or []):
# Use the same model for truck detection
truck_detector = BaseDetector(
shared_model, conf=truck_conf, class_filter=("truck",)
)
if truck_model_config is not None:
# Load a separate truck detection model
truck_shared = YOLO(truck_model_config.path)
truck_detector = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
elif "truck" in (model_config.known_classes or []):
# Use the same model for truck detection
truck_detector = BaseDetector(
shared_model, conf=truck_conf, class_filter=("truck",)
)
tracker = ByteTrackTracker(shared_model, conf=effective_detector_conf)
stabilizer = BboxStabilizer(
@@ -404,7 +436,7 @@ def run_pipeline(
line_x_end=int(w * 0.72),
margin=20,
)
batch_mgr = BatchLifecycleManager()
batch_mgr = build_batch_manager(cfg)
dashboard = DashboardOverlay()
writer: _AsyncWriter | None = None
@@ -412,6 +444,9 @@ def run_pipeline(
start_time = time.time()
frame_idx = 0
completed_batches = 0
# Last truck detections — kept between detection frames (FCP caches
# last_detected_trucks, predict.py:882-886).
last_trucks: list[Detection] = []
def on_batch_end(record):
nonlocal completed_batches
@@ -455,16 +490,27 @@ def run_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
if truck_detector is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_detector.detect(frame)
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
# not that a truck is there. The FSM's truck signal is the
# real detection (FCP predict.py:964).
truck_centroid = truck_detection_centroid(last_trucks)
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_detector is not None and frame_idx % truck_det_interval == 0:
trucks = truck_detector.detect(frame)
roi = roi_tracker.update(trucks)
truck_present = roi is not None and roi.confidence > 0
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
if truck_present:
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
if roi is not None:
counter.line_y = roi.line_y
@@ -477,36 +523,33 @@ def run_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
# Batch lifecycle
truck_centroid = None
if truck_present:
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
# Track → Stabilize → Count
# Track → Stabilize → Count — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
tracked_sacks: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
if batch_mgr.is_active:
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
stable = stabilizer.update(raw_tracked)
stable = apply_class_filter(stable, effective_filter)
stable = filter_by_counting_polygon(stable, counting_polygon)
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
stable = stabilizer.update(raw_tracked)
stable = apply_class_filter(stable, effective_filter)
stable = filter_by_counting_polygon(stable, counting_polygon)
if roi is not None:
tracked_sacks = [
d for d in stable
if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)
]
else:
tracked_sacks = stable
if roi is not None:
tracked_sacks = [
d for d in stable
if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)
]
else:
tracked_sacks = stable
tracked_sacks = _suppress_sacks_under_boxes(
tracked_sacks, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
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_input = countable_detections(tracked_sacks)
events = counter.update(counter_input)
tracked_sacks = _suppress_sacks_under_boxes(
tracked_sacks, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
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_input = countable_detections(tracked_sacks)
events = counter.update(counter_input)
# Drive the batch FSM with this frame's real crossing events
# (FCP predict.py:1064-1085 — events first, then the FSM).
@@ -783,18 +826,18 @@ def run_merged_pipeline(
)
detectors.append(BaseDetector(model, conf=det_conf, class_filter=eff_filter))
# Truck detector — skip if fixed zone
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
truck_det = None
if fixed_zone is None:
if truck_model_config is not None:
truck_shared = YOLO(truck_model_config.path)
truck_det = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
# ponytail: first-match truck detector; could prefer dedicated truck model over sack model w/ truck class
else:
for i, mcfg in enumerate(model_configs):
if "truck" in (mcfg.known_classes or []):
truck_det = detectors[i]
break
if truck_model_config is not None:
truck_shared = YOLO(truck_model_config.path)
truck_det = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
# ponytail: first-match truck detector; could prefer dedicated truck model over sack model w/ truck class
else:
for i, mcfg in enumerate(model_configs):
if "truck" in (mcfg.known_classes or []):
truck_det = detectors[i]
break
# Single tracker using first model's weights
tracker_model = YOLO(model_configs[0].path)
@@ -829,7 +872,7 @@ def run_merged_pipeline(
line_x_end=int(w * 0.72),
margin=20,
)
batch_mgr = BatchLifecycleManager()
batch_mgr = build_batch_manager(cfg)
dashboard = DashboardOverlay()
writer = _AsyncWriter(
AnnotatedVideoWriter(output_path, fps=fps, frame_size=(w, h), max_height=output_max_height)
@@ -839,6 +882,9 @@ def run_merged_pipeline(
frame_idx = 0
completed_batches = 0
_frame_times: list[float] = []
# Last truck detections — kept between detection frames (FCP caches
# last_detected_trucks, predict.py:882-886).
last_trucks: list[Detection] = []
# Primary model's class filter (mirrors eff_filter above) — applied to
# ByteTrack output so UI class checkboxes apply to the primary model too.
primary_filter = (
@@ -882,16 +928,28 @@ def run_merged_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
if truck_det is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_det.detect(frame)
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
# not that a truck is there. The FSM's truck signal is the
# real detection (FCP predict.py:964).
truck_centroid = truck_detection_centroid(last_trucks)
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_det is not None and frame_idx % truck_det_interval == 0:
trucks = truck_det.detect(frame)
roi = roi_tracker.update(trucks)
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
if truck_present:
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
truck_present = roi is not None and roi.confidence > 0
if roi is not None:
counter.line_y = roi.line_y
# FCP counts inside the calibrated count-line x-window
@@ -903,62 +961,57 @@ def run_merged_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
truck_centroid = None
if truck_present:
truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0)
# Detection + tracking
# Detection + tracking — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
all_detections: list[Detection] = []
tracked: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
if batch_mgr.is_active:
# Primary: tracker gives detections WITH track_id for counting
primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
primary = apply_class_filter(primary, primary_filter)
all_detections.extend(primary)
# Primary: tracker gives detections WITH track_id for counting
primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
primary = apply_class_filter(primary, primary_filter)
all_detections.extend(primary)
# Supplementary: run extra models every N frames for richer annotations
if len(detectors) > 1 and frame_idx % sup_det_interval == 0:
with ThreadPoolExecutor(max_workers=len(detectors) - 1) as pool:
extras = [d for i, d in enumerate(detectors) if i != 0]
futures = {pool.submit(d.detect, frame): d for d in extras}
for future in as_completed(futures):
try:
all_detections.extend(future.result())
except Exception:
pass
# Supplementary: run extra models every N frames for richer annotations
if len(detectors) > 1 and frame_idx % sup_det_interval == 0:
with ThreadPoolExecutor(max_workers=len(detectors) - 1) as pool:
extras = [d for i, d in enumerate(detectors) if i != 0]
futures = {pool.submit(d.detect, frame): d for d in extras}
for future in as_completed(futures):
try:
all_detections.extend(future.result())
except Exception:
pass
# Deduplicate
merged = _deduplicate_detections(
all_detections, iou_threshold=cfg["iou"]["dedup"]
)
# Deduplicate
merged = _deduplicate_detections(
all_detections, iou_threshold=cfg["iou"]["dedup"]
)
# Give supplementary (track_id=None) dets stable negative ids
assigned = synthetic.assign(merged)
# Give supplementary (track_id=None) dets stable negative ids
assigned = synthetic.assign(merged)
# Stabilize and filter to ROI
stable = stabilizer.update(assigned)
stable = filter_by_counting_polygon(stable, counting_polygon)
if roi is not None:
tracked = [d for d in stable if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)]
else:
tracked = stable
tracked = _suppress_sacks_under_boxes(
tracked, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked = _apply_class_confs(tracked, sack_conf, box_conf)
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
# Count using only detections with track_id (tracker results)
counter_input = countable_detections(
[d for d in tracked if d.track_id is not None]
)
events = counter.update(counter_input)
# Stabilize and filter to ROI
stable = stabilizer.update(assigned)
stable = filter_by_counting_polygon(stable, counting_polygon)
if roi is not None:
tracked = [d for d in stable if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)]
else:
tracked = []
synthetic.clear()
tracked = stable
tracked = _suppress_sacks_under_boxes(
tracked, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked = _apply_class_confs(tracked, sack_conf, box_conf)
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
# Count using only detections with track_id (tracker results)
counter_input = countable_detections(
[d for d in tracked if d.track_id is not None]
)
events = counter.update(counter_input)
# Drive the batch FSM with this frame's real crossing events
# (FCP predict.py:1064-1085 — events first, then the FSM).
+7
View File
@@ -186,3 +186,10 @@ def test_stabilizer_hold_matches_fcp():
def test_truck_det_interval_matches_fcp():
assert load_config()["pipeline"]["truck_det_interval"] == 5
def test_batch_section_matches_fcp():
"""The batch FSM arguments come from the config (FCP config.yaml:123-124)."""
cfg = load_config()
assert cfg["batch"]["timeout_seconds"] == 20.0
assert cfg["batch"]["truck_gone_tolerance_seconds"] == 30.0
assert DEFAULTS["batch"] == cfg["batch"]
+267
View File
@@ -271,10 +271,20 @@ def _patch_pipeline_fakes(monkeypatch):
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:
@@ -1301,3 +1311,260 @@ def test_pipeline_falls_back_to_the_roi_bounds_without_a_count_line(tmp_path, mo
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).
SACK_ABOVE = Detection(
bbox=(600.0, 200.0, 640.0, 240.0), confidence=0.9, class_id=0,
class_name="sack", track_id=1,
)
SACK_BELOW = Detection(
bbox=(600.0, 500.0, 640.0, 540.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,
)
@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)