feat: flag truncated clips in the job result

This commit is contained in:
jetson committed 2026-10-27 17:28:02 +07:00
1 parent fcafc98b17
commit 3d9cce2261
5 files changed
+232 -5

No files matched your search

+4
View File
@@ -552,6 +552,8 @@ def api_jobs():
"loading": r.loading_count,
"unloading": r.unloading_count,
"net": r.net_count,
"truncated": r.truncated,
"frames_expected": r.frames_expected,
}
for r in j.results
],
@@ -628,6 +630,8 @@ def api_job_detail(job_id):
"frame_count": r.frame_count,
"duration_seconds": r.duration_seconds,
"output_path": os.path.basename(r.output_path) if r.output_path else None,
"truncated": r.truncated,
"frames_expected": r.frames_expected,
}
for r in job.results
],
+6
View File
@@ -43,6 +43,8 @@ class JobResult:
box_loading_count: int = 0
box_unloading_count: int = 0
box_net_count: int = 0
frames_expected: int = 0
truncated: bool = False
@dataclass
@@ -286,6 +288,8 @@ class JobQueue:
box_loading_count=result.box_loading_count,
box_unloading_count=result.box_unloading_count,
box_net_count=result.box_net_count,
frames_expected=result.frames_expected,
truncated=result.truncated,
))
else:
# Multiple models: run merged pipeline
@@ -342,6 +346,8 @@ class JobQueue:
box_loading_count=result.box_loading_count,
box_unloading_count=result.box_unloading_count,
box_net_count=result.box_net_count,
frames_expected=result.frames_expected,
truncated=result.truncated,
))
with self._lock:
+40 -5
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import math
import os
import queue as queue_mod
import sys
@@ -43,6 +44,32 @@ def analysis_size(src_w: int, src_h: int) -> tuple[int, int]:
return ANALYSIS_SIZE
def _expected_frames(cap) -> int:
"""Container frame count as a non-negative int; 0 when the length is unknown.
CAP_PROP_FRAME_COUNT is 0.0 for some containers and NaN for others, and
int(NaN) raises — an unreadable length must never crash the run.
"""
try:
raw = float(cap.get(cv2.CAP_PROP_FRAME_COUNT))
except (TypeError, ValueError):
return 0
if not math.isfinite(raw) or raw < 0:
return 0
return int(raw)
def is_truncated(expected_frames: int, frames_read: int) -> bool:
"""True when the decoder produced fewer frames than the container claims.
A cut-short upload decodes only the first N% of the clip and its counts
look complete. An unknown length (expected_frames <= 0) is never flagged.
"""
if expected_frames <= 0:
return False
return frames_read < expected_frames * 0.98
class _AsyncWriter:
"""Writer worker: preserves frame order, surfaces first error at close()."""
@@ -89,6 +116,8 @@ class PipelineResult:
class_filter: list[str] | None
box_loading_count: int = 0
box_unloading_count: int = 0
frames_expected: int = 0
truncated: bool = False
@property
def net_count(self) -> int:
@@ -113,6 +142,8 @@ class MergedPipelineResult:
class_filter: list[str] | None
box_loading_count: int = 0
box_unloading_count: int = 0
frames_expected: int = 0
truncated: bool = False
@property
def net_count(self) -> int:
@@ -275,7 +306,7 @@ def run_pipeline(
detect_interval: Run detection+tracking every N frames (None =
config.yaml, default 1 = every frame; >1 throttles and can lose
counts via ByteTrack ID switches at crossings).
progress_callback: Optional fn(frame_idx, total_frames) called per frame.
progress_callback: Optional fn(frame_idx, expected_frames) called per frame.
frame_callback: Optional fn(jpeg_bytes) called every 10th frame (fallback).
cancel_check: Optional fn() returning True to abort processing.
preview_path: Optional file path for live preview frames (JPEG written atomically).
@@ -308,7 +339,7 @@ def run_pipeline(
raise RuntimeError(f"Cannot open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
expected_frames = _expected_frames(cap)
src_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
src_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Analysis space is always FCP's 1280x720, whatever the clip's native size.
@@ -546,7 +577,7 @@ def run_pipeline(
frame_callback(jpeg.tobytes())
if progress_callback:
progress_callback(frame_idx, total_frames)
progress_callback(frame_idx, expected_frames)
finally:
cap.release()
@@ -579,6 +610,8 @@ def run_pipeline(
duration_seconds=duration,
model_name=model_config.filename,
class_filter=effective_filter,
frames_expected=expected_frames,
truncated=is_truncated(expected_frames, frame_idx),
)
@@ -717,7 +750,7 @@ def run_merged_pipeline(
raise RuntimeError(f"Cannot open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
expected_frames = _expected_frames(cap)
src_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
src_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Analysis space is always FCP's 1280x720, whatever the clip's native size.
@@ -981,7 +1014,7 @@ def run_merged_pipeline(
os.replace(tmp_path, preview_path)
if progress_callback:
progress_callback(frame_idx, total_frames)
progress_callback(frame_idx, expected_frames)
finally:
cap.release()
@@ -1012,4 +1045,6 @@ def run_merged_pipeline(
duration_seconds=duration,
model_names=[c.filename for c in model_configs],
class_filter=None,
frames_expected=expected_frames,
truncated=is_truncated(expected_frames, frame_idx),
)
+65
View File
@@ -483,3 +483,68 @@ def test_merged_output_name_falls_back_to_stored_file_name(tmp_path, monkeypatch
q._run_job(job.job_id)
assert os.path.basename(seen["output_path"]) == "merged_annotated_clip_1.mp4"
# ── Truncated clip flag (Task 10) ───────────────────────────────────────
def test_job_result_exposes_truncation():
from src.job import JobResult
r = JobResult(model_name="m", output_path="", loading_count=1, unloading_count=0,
net_count=1, batch_count=1, frame_count=40, duration_seconds=1.0,
truncated=True, frames_expected=100)
assert r.truncated is True
assert r.frames_expected == 100
@pytest.mark.parametrize("merged", [False, True])
def test_run_job_propagates_truncation(tmp_path, monkeypatch, merged):
"""_run_job copies truncated/frames_expected from the pipeline result."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult, PipelineResult
common = dict(
output_path=str(tmp_path / "out.mp4"),
frame_count=40,
loading_count=1,
unloading_count=0,
batch_count=1,
duration_seconds=1.0,
class_filter=None,
frames_expected=100,
truncated=True,
)
models = [
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack"]),
]
if merged:
monkeypatch.setattr(
job_mod, "run_merged_pipeline",
lambda **kwargs: MergedPipelineResult(model_names=["a.pt"], **common),
)
models.append(ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]))
else:
monkeypatch.setattr(
job_mod, "run_pipeline",
lambda **kwargs: PipelineResult(model_name="a.pt", **common),
)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t10",
video_path="/tmp/test.mp4",
model_configs=models,
output_dir=str(tmp_path / "job-t10"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.truncated is True
assert r.frames_expected == 100
+117
View File
@@ -1071,6 +1071,123 @@ def test_batch_start_resets_per_track_state(tmp_path, monkeypatch, fn_name):
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