diff --git a/app.py b/app.py index 3e6c5a9..b05fdd8 100644 --- a/app.py +++ b/app.py @@ -21,6 +21,7 @@ from pathlib import Path from shapely.errors import GEOSException from shapely.geometry import Polygon +from src.compress import compress_in_place from src.job import JobQueue from src.model_registry import scan_models, scan_model_groups, ModelConfig from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height @@ -401,12 +402,6 @@ def jobs_list(): return render_template("jobs.html", jobs=jobs) -# Serializes compression encodes: encodes are rare, one global lock is enough. -_COMPRESS_LOCK = threading.Lock() -_AUDIO_BITRATE = 64_000 -_MIN_VIDEO_BITRATE = 100_000 - - def _remove_quiet(path: str) -> None: try: os.remove(path) @@ -414,64 +409,6 @@ def _remove_quiet(path: str) -> None: pass -def _compressed_cache_valid(out_path: str, file_path: str) -> bool: - """Cache hit only if the compressed file exists and is newer than source.""" - try: - return ( - os.path.isfile(out_path) - and os.path.getmtime(out_path) >= os.path.getmtime(file_path) - ) - except OSError: - return False - - -def _compress_for_download(file_path: str, max_bytes: int = 250 * 1024 * 1024) -> str | None: - """Compress file_path with ffmpeg if larger than max_bytes. - - Returns path to `_compressed.mp4` next to the input, or None to - fall back to the original file (small file, ffmpeg missing/failed, or - result still over the limit). - """ - if not os.path.isfile(file_path): - return None - if os.path.getsize(file_path) <= max_bytes: - return None - out_path = os.path.splitext(file_path)[0] + "_compressed.mp4" - if _compressed_cache_valid(out_path, file_path): - return out_path - with _COMPRESS_LOCK: - if _compressed_cache_valid(out_path, file_path): - return out_path - try: - duration = float(probe_video(file_path).get("duration") or 0) - except Exception: - return None - if duration <= 0: - return None - video_bitrate = max( - int((max_bytes * 8 * 0.92) / duration) - _AUDIO_BITRATE, - _MIN_VIDEO_BITRATE, - ) - tmp_path = out_path + ".tmp" - try: - subprocess.run( - ["ffmpeg", "-y", "-i", file_path, "-c:v", "libx264", - "-preset", "veryfast", "-b:v", str(video_bitrate), - "-c:a", "aac", "-b:a", str(_AUDIO_BITRATE), "-f", "mp4", - tmp_path], - capture_output=True, timeout=3600, check=True, - stdin=subprocess.DEVNULL, - ) - except (OSError, subprocess.SubprocessError): - _remove_quiet(tmp_path) - return None - if not os.path.isfile(tmp_path) or os.path.getsize(tmp_path) > max_bytes: - _remove_quiet(tmp_path) - return None - os.replace(tmp_path, out_path) - return out_path - - @app.route("/download//") def download(job_id, filename): job = job_queue.get_job(job_id) @@ -486,7 +423,7 @@ def download(job_id, filename): return "File not found", 404 if not os.path.isfile(file_path): return "File not found", 404 - send_path = _compress_for_download(file_path) or file_path + send_path = compress_in_place(file_path) or file_path resp = send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path)) resp.headers["Content-Length"] = str(os.path.getsize(send_path)) return resp diff --git a/scripts/purge_expired_outputs.py b/scripts/purge_expired_outputs.py new file mode 100755 index 0000000..d499818 --- /dev/null +++ b/scripts/purge_expired_outputs.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Delete expired job videos from the output directory. + +A finished job leaves exactly one video behind (the compressed one). This +script sweeps the videos that are older than the retention period, so the +disk does not fill up with jobs nobody will ever download again. + + python scripts/purge_expired_outputs.py --output-dir output --max-age-days 5 + +The job directory, the thumbnail and the sample frames stay - the jobs list +in the web UI still renders. +""" + +from __future__ import annotations + +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from src.compress import RETENTION_DAYS, purge_expired_media # noqa: E402 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", default="output", + help="the job output root (default: output)") + parser.add_argument("--max-age-days", type=float, default=RETENTION_DAYS, + help=f"delete videos older than this (default: {RETENTION_DAYS})") + args = parser.parse_args(argv) + + deleted = purge_expired_media(args.output_dir, max_age_days=args.max_age_days) + for path in deleted: + print(f"deleted {path}") + print(f"purged {len(deleted)} file(s) older than {args.max_age_days} days " + f"from {args.output_dir}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/compress.py b/src/compress.py new file mode 100644 index 0000000..2bc3bd6 --- /dev/null +++ b/src/compress.py @@ -0,0 +1,126 @@ +"""Annotated-output lifecycle: compress in place, expire. + +A finished job must leave exactly ONE video behind: the compressed one, +under the original file name. The uncompressed source is replaced with +`os.replace` (atomic on the same filesystem), so there is never a moment +without a file, and a failed encode leaves the original untouched. +""" + +from __future__ import annotations + +import os +import subprocess +import threading +import time + +from src.preview import probe_video + +# A download above this size is compressed. The cap is the point of the +# exercise: a 724 MB annotated video becomes a 218 MB one. +MAX_BYTES = 250 * 1024 * 1024 + +_AUDIO_BITRATE = 64_000 +_MIN_VIDEO_BITRATE = 100_000 + +# Suffix of the encode target. The container is forced with "-f mp4", so the +# odd extension is safe. +_TMP_SUFFIX = ".compress.tmp" + +# Serializes the encodes: two downloads of the same file must not run two +# ffmpeg processes on one target path. +_COMPRESS_LOCK = threading.Lock() + +# Job videos are swept after this many days; the job dir, the thumbnail and +# the sample frames stay (small - the jobs list still renders). +RETENTION_DAYS = 5.0 + + +def _remove_quiet(path: str) -> None: + try: + os.remove(path) + except OSError: + pass + + +def compress_in_place(file_path: str, max_bytes: int = MAX_BYTES) -> str | None: + """Shrink file_path to max_bytes, replacing it under the same name. + + Returns file_path when the file was replaced, None when nothing changed + (already within the cap, ffmpeg missing/failed, or the encode still + overshoots the cap - the original then stays untouched). + """ + if not os.path.isfile(file_path): + return None + with _COMPRESS_LOCK: + if not os.path.isfile(file_path): + return None + if os.path.getsize(file_path) <= max_bytes: + return None + try: + duration = float(probe_video(file_path).get("duration") or 0) + except Exception: + return None + if duration <= 0: + return None + video_bitrate = max( + int((max_bytes * 8 * 0.92) / duration) - _AUDIO_BITRATE, + _MIN_VIDEO_BITRATE, + ) + tmp_path = file_path + _TMP_SUFFIX + try: + subprocess.run( + ["ffmpeg", "-y", "-i", file_path, "-c:v", "libx264", + "-preset", "veryfast", "-b:v", str(video_bitrate), + "-c:a", "aac", "-b:a", str(_AUDIO_BITRATE), "-f", "mp4", + tmp_path], + capture_output=True, timeout=3600, check=True, + stdin=subprocess.DEVNULL, + ) + except (OSError, subprocess.SubprocessError): + _remove_quiet(tmp_path) + return None + if not os.path.isfile(tmp_path) or os.path.getsize(tmp_path) > max_bytes: + _remove_quiet(tmp_path) + return None + # Atomic: the compressed video takes the original's name, the source + # is gone, and there is never a moment without a file. + os.replace(tmp_path, file_path) + return file_path + + +def purge_expired_media( + output_dir: str, + max_age_days: float = RETENTION_DAYS, + now: float | None = None, +) -> list[str]: + """Delete the job videos under output_dir/job-*/ older than max_age_days. + + Age comes from the file mtime - jobs live in memory only, so the file + timestamp is the only restart-proof clock. Stale '*.compress.tmp' + leftovers of a killed encode go too; a fresh one (an encode in flight) + stays. + """ + now = time.time() if now is None else now + cutoff = now - max_age_days * 86400 + deleted: list[str] = [] + root = os.path.abspath(output_dir) + if not os.path.isdir(root): + return deleted + for job_dir in sorted(os.listdir(root)): + if not job_dir.startswith("job-"): + continue + d = os.path.join(root, job_dir) + if not os.path.isdir(d): + continue + for name in sorted(os.listdir(d)): + if not (name.endswith(".mp4") or name.endswith(_TMP_SUFFIX)): + continue + p = os.path.join(d, name) + try: + if os.path.getmtime(p) >= cutoff: + continue + os.remove(p) + except OSError: + continue + deleted.append(p) + return deleted diff --git a/src/job.py b/src/job.py index 7a37614..4bb306e 100644 --- a/src/job.py +++ b/src/job.py @@ -13,6 +13,7 @@ from pathlib import Path from shapely.geometry import Polygon +from src.compress import compress_in_place from src.model_registry import ModelConfig, find_truck_detector from src.naming import annotated_output_name from src.pipeline import run_pipeline, run_merged_pipeline, PipelineResult, MergedPipelineResult @@ -218,6 +219,26 @@ class JobQueue: counts[job.status.name.lower()] += 1 return counts + def _compress_outputs(self, job: Job) -> None: + """Compress the finished job's videos in place. + + One video per job, under its original name: the compressed copy + replaces the uncompressed source (atomically). A file that cannot be + compressed is left as it is - the job still succeeded. + """ + for r in job.results: + path = r.output_path + if not path: + continue + if not os.path.isabs(path): + path = os.path.join(os.path.abspath(job.output_dir), os.path.basename(path)) + if not os.path.isfile(path): + continue + try: + compress_in_place(path) + except Exception: + continue + def _run_job(self, job_id: str) -> None: """Worker: process each model config sequentially.""" with self._lock: @@ -354,6 +375,11 @@ class JobQueue: truncated=result.truncated, )) + # The job is done: shrink the annotated video in place. One video + # per job, under its original name - the uncompressed source is + # replaced by the compressed copy. + self._compress_outputs(job) + with self._lock: if job.status != JobStatus.CANCELLED: job.status = JobStatus.COMPLETED diff --git a/tests/test_app.py b/tests/test_app.py index 2db0bd9..318c67f 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -212,12 +212,12 @@ def test_download_route_sets_content_length(client): """GET /download// sets Content-Length equal to file size.""" import os - from app import _compress_for_download + from src.compress import compress_in_place job, path = _completed_job_with_output() expected = os.path.getsize(path) - # Small file: helper returns None, route serves the original. - assert _compress_for_download(path) is None + # Small file: the compressor leaves it alone, the route serves the original. + assert compress_in_place(path) is None resp = client.get(f"/download/{job.job_id}/out.mp4") assert resp.status_code == 200 assert resp.headers["Content-Length"] == str(expected) diff --git a/tests/test_compress.py b/tests/test_compress.py new file mode 100644 index 0000000..0e7e1e8 --- /dev/null +++ b/tests/test_compress.py @@ -0,0 +1,206 @@ +"""Tests for the annotated-output lifecycle: compress in place, expire. + +A finished job must leave exactly ONE video behind: the compressed one, +under the original file name. The uncompressed source is gone. +""" + +import os +import subprocess +from unittest import mock + +import src.compress as compress_module +from src.compress import compress_in_place, purge_expired_media + + +def _fake_run(payload=b"compressed"): + def run(cmd, **kwargs): + with open(cmd[-1], "wb") as fh: + fh.write(payload) + return subprocess.CompletedProcess(cmd, 0) + return run + + +# ── compress_in_place ───────────────────────────────────────────────────── + + +def test_small_file_is_left_alone(tmp_path): + """A file within the cap is not touched.""" + f = tmp_path / "small.mp4" + f.write_bytes(b"tiny") + + assert compress_in_place(str(f)) is None + assert f.read_bytes() == b"tiny" + + +def test_missing_file_returns_none(tmp_path): + assert compress_in_place(str(tmp_path / "nope.mp4")) is None + + +def test_oversized_file_is_replaced_in_place(tmp_path): + """The compressed video replaces the original under the SAME name.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")): + out = compress_in_place(str(f), max_bytes=1024) + + assert out == str(f) + assert f.read_bytes() == b"c" + # exactly one file in the directory - no _compressed sibling + assert [p.name for p in tmp_path.iterdir()] == ["big.mp4"] + + +def test_encode_targets_a_temp_file_and_leaves_the_original_intact(tmp_path): + """The original must survive the whole encode until the atomic replace.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + seen = {} + + def fake_run(cmd, **kwargs): + seen["target"] = cmd[-1] + seen["original_during_encode"] = f.read_bytes() + with open(cmd[-1], "wb") as fh: + fh.write(b"c") + return subprocess.CompletedProcess(cmd, 0) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=fake_run): + compress_in_place(str(f), max_bytes=1024) + + assert seen["target"] != str(f) + assert seen["original_during_encode"] == b"x" * 300_000 + + +def test_failed_encode_keeps_the_original(tmp_path): + """ffmpeg missing or failing must not lose the video.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=OSError("no ffmpeg")): + assert compress_in_place(str(f), max_bytes=1024) is None + + assert f.read_bytes() == b"x" * 300_000 + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_oversized_result_is_discarded(tmp_path): + """An encode that still overshoots the cap is thrown away.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"y" * 5000)): + assert compress_in_place(str(f), max_bytes=1024) is None + + assert f.read_bytes() == b"x" * 300_000 + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_probe_failure_keeps_the_original(tmp_path): + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + + with mock.patch.object(compress_module, "probe_video", side_effect=FileNotFoundError): + assert compress_in_place(str(f), max_bytes=1024) is None + + assert f.exists() + + +def test_video_bitrate_leaves_room_for_the_audio_track(tmp_path): + """The audio budget is subtracted from the video bitrate.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 100.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=_fake_run(b"c")) as run: + compress_in_place(str(f), max_bytes=1024) + + cmd = run.call_args[0][0] + assert int(cmd[cmd.index("-b:v") + 1]) == 100_000 + + +# ── purge_expired_media ────────────────────────────────────────────────── + + +def test_purge_deletes_videos_older_than_the_retention(tmp_path): + """Videos older than the retention are removed; everything else stays.""" + job_dir = tmp_path / "job-1" + job_dir.mkdir() + old = job_dir / "annotated.mp4" + old.write_bytes(b"old") + os.utime(old, (1000, 1000)) + fresh = job_dir / "fresh.mp4" + fresh.write_bytes(b"new") + thumb = job_dir / "thumbnail.jpg" + thumb.write_bytes(b"jpg") + samples = job_dir / "samples" + samples.mkdir() + (samples / "f1.jpg").write_bytes(b"j") + stale_tmp = job_dir / "annotated.mp4.compress.tmp" + stale_tmp.write_bytes(b"t") + os.utime(stale_tmp, (1000, 1000)) + + deleted = purge_expired_media(str(tmp_path), max_age_days=5) + + assert not old.exists() + assert fresh.exists() + assert thumb.exists() + assert (samples / "f1.jpg").exists() + assert not stale_tmp.exists() + assert str(old) in deleted + + +def test_purge_keeps_a_recent_temp_file(tmp_path): + """An encode in flight must not be swept away.""" + job_dir = tmp_path / "job-2" + job_dir.mkdir() + tmp_file = job_dir / "annotated.mp4.compress.tmp" + tmp_file.write_bytes(b"t") + + purge_expired_media(str(tmp_path), max_age_days=5) + + assert tmp_file.exists() + + +def test_purge_ignores_files_outside_job_dirs(tmp_path): + """Only job output dirs are swept.""" + stray = tmp_path / "stray.mp4" + stray.write_bytes(b"s") + os.utime(stray, (1000, 1000)) + + purge_expired_media(str(tmp_path), max_age_days=5) + + assert stray.exists() + + +def test_purge_on_a_missing_output_dir_is_harmless(tmp_path): + assert purge_expired_media(str(tmp_path / "nope"), max_age_days=5) == [] + + +# ── the purge CLI ──────────────────────────────────────────────────────── + + +def test_purge_script_deletes_expired_videos(tmp_path): + """The CLI does the same as the function.""" + import subprocess as sp + import sys + + job_dir = tmp_path / "job-cli" + job_dir.mkdir() + old = job_dir / "annotated.mp4" + old.write_bytes(b"old") + os.utime(old, (1000, 1000)) + fresh = job_dir / "fresh.mp4" + fresh.write_bytes(b"new") + + res = sp.run( + [sys.executable, "scripts/purge_expired_outputs.py", + "--output-dir", str(tmp_path), "--max-age-days", "5"], + capture_output=True, text=True, timeout=120, + ) + + assert res.returncode == 0, res.stderr + assert not old.exists() + assert fresh.exists() diff --git a/tests/test_download_compress.py b/tests/test_download_compress.py index 48ea5da..6e28736 100644 --- a/tests/test_download_compress.py +++ b/tests/test_download_compress.py @@ -1,6 +1,5 @@ -"""Tests for download compression to max 250MB (Task 3).""" +"""Tests for the download route and the in-place compression it triggers.""" -import inspect import os import shutil import subprocess @@ -11,255 +10,12 @@ import pytest from unittest import mock import app as app_module -from app import _compress_for_download +import src.compress as compress_module +from src.compress import compress_in_place -def test_helper_exists_with_max_bytes_default(): - """_compress_for_download accepts max_bytes, defaults to 250MB.""" - sig = inspect.signature(_compress_for_download) - assert "max_bytes" in sig.parameters - assert sig.parameters["max_bytes"].default == 250 * 1024 * 1024 -def test_small_file_returns_none(tmp_path): - """Files under the limit are served untouched (no compression).""" - f = tmp_path / "small.mp4" - f.write_bytes(b"tiny") - assert _compress_for_download(str(f)) is None +# ── the route ───────────────────────────────────────────────────────────── -def test_file_exactly_at_limit_returns_none(tmp_path): - """Size == max_bytes means no compression.""" - f = tmp_path / "edge.mp4" - f.write_bytes(b"x" * 100) - assert _compress_for_download(str(f), max_bytes=100) is None - -def test_missing_file_returns_none(tmp_path): - assert _compress_for_download(str(tmp_path / "nope.mp4")) is None - -def test_compression_runs_ffmpeg_with_target_bitrate(tmp_path): - """Oversized file triggers ffmpeg at video bitrate net of audio budget.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 300_000) - - def fake_run(cmd, **kwargs): - open(cmd[-1], "wb").write(b"compressed") - return subprocess.CompletedProcess(cmd, 0) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run) as run: - out = _compress_for_download(str(f), max_bytes=200_000) - - assert out == str(tmp_path / "big_compressed.mp4") - assert os.path.isfile(out) - cmd = run.call_args[0][0] - assert cmd[0] == "ffmpeg" - # bitrate = int((200_000 * 8 * 0.92) / 2.0) - 64_000 = 672000 - assert "-b:v" in cmd - assert cmd[cmd.index("-b:v") + 1] == "672000" - assert cmd[cmd.index("-i") + 1] == str(f) - # audio stays budgeted - assert cmd[cmd.index("-b:a") + 1] == "64000" - # Jetson: fast preset, explicit container (output is a .tmp path) - assert cmd[cmd.index("-preset") + 1] == "veryfast" - assert cmd[cmd.index("-f") + 1] == "mp4" - # encode goes to a temp path, never the final path directly - assert cmd[-1] == str(tmp_path / "big_compressed.mp4.tmp") - assert run.call_args[1]["stdin"] is subprocess.DEVNULL - -def test_minimum_video_bitrate_floor(tmp_path): - """Tiny budget still gets a usable floor bitrate.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - - def fake_run(cmd, **kwargs): - open(cmd[-1], "wb").write(b"c") - return subprocess.CompletedProcess(cmd, 0) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 100.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run) as run: - _compress_for_download(str(f), max_bytes=1024) - - cmd = run.call_args[0][0] - assert int(cmd[cmd.index("-b:v") + 1]) == 100_000 - -def test_partial_encode_never_cached(tmp_path): - """ffmpeg writes only to .tmp; final path appears only after success.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 300_000) - final = str(tmp_path / "big_compressed.mp4") - seen = {} - - def fake_run(cmd, **kwargs): - seen["final_during_encode"] = os.path.isfile(final) - seen["tmp"] = cmd[-1] - open(cmd[-1], "wb").write(b"compressed") - return subprocess.CompletedProcess(cmd, 0) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run): - out = _compress_for_download(str(f), max_bytes=200_000) - - assert out == final - assert seen["final_during_encode"] is False - assert seen["tmp"] == final + ".tmp" - assert os.path.isfile(final) - assert not os.path.exists(final + ".tmp") - -def test_failed_encode_leaves_no_partial_file(tmp_path): - """Interrupted/killed encode must not leave a servable artifact.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - final = str(tmp_path / "big_compressed.mp4") - - def fake_run(cmd, **kwargs): - open(cmd[-1], "wb").write(b"partial") - raise subprocess.CalledProcessError(1, cmd) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run): - assert _compress_for_download(str(f), max_bytes=200_000) is None - - assert not os.path.exists(final) - assert not os.path.exists(final + ".tmp") - -def test_oversized_result_discarded(tmp_path): - """If the encode still exceeds max_bytes, drop it and fall back.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - final = str(tmp_path / "big_compressed.mp4") - - def fake_run(cmd, **kwargs): - open(cmd[-1], "wb").write(b"y" * 4096) - return subprocess.CompletedProcess(cmd, 0) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run): - assert _compress_for_download(str(f), max_bytes=1024) is None - - assert not os.path.exists(final) - assert not os.path.exists(final + ".tmp") - -def test_existing_compressed_file_reused(tmp_path): - """Cache: fresh _compressed.mp4 next to input is served as-is.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - cached = tmp_path / "big_compressed.mp4" - cached.write_bytes(b"cached") - os.utime(cached, (f.stat().st_mtime + 10, f.stat().st_mtime + 10)) - - with mock.patch.object(app_module, "probe_video") as probe, \ - mock.patch.object(app_module.subprocess, "run") as run: - out = _compress_for_download(str(f), max_bytes=1024) - - assert out == str(cached) - probe.assert_not_called() - run.assert_not_called() - -def test_stale_cache_reencoded(tmp_path): - """Cache older than the source video is invalid and gets re-encoded.""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 300_000) - cached = tmp_path / "big_compressed.mp4" - cached.write_bytes(b"old") - os.utime(cached, (1000, 1000)) # far older than source - - def fake_run(cmd, **kwargs): - open(cmd[-1], "wb").write(b"fresh") - return subprocess.CompletedProcess(cmd, 0) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=fake_run) as run: - out = _compress_for_download(str(f), max_bytes=200_000) - - assert out == str(cached) - run.assert_called_once() - assert cached.read_bytes() == b"fresh" - -def test_probe_failure_returns_none(tmp_path): - """probe failure falls back to the original file (no compression).""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - - with mock.patch.object(app_module, "probe_video", side_effect=FileNotFoundError): - assert _compress_for_download(str(f), max_bytes=1024) is None - -def test_nonpositive_duration_returns_none(tmp_path): - """duration <= 0 means no compression (nothing to budget against).""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - - for duration in (0, 0.0, -1.0, None): - with mock.patch.object(app_module, "probe_video", return_value={"duration": duration}): - assert _compress_for_download(str(f), max_bytes=1024) is None - -def test_ffmpeg_missing_binary_returns_none(tmp_path): - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=FileNotFoundError): - assert _compress_for_download(str(f), max_bytes=1024) is None - -def test_ffmpeg_failure_returns_none(tmp_path): - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 5000) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", - side_effect=subprocess.CalledProcessError(1, "ffmpeg")): - assert _compress_for_download(str(f), max_bytes=1024) is None - -def test_concurrent_downloads_encode_once(tmp_path): - """Threaded requests for the same file share one encode (global lock).""" - f = tmp_path / "big.mp4" - f.write_bytes(b"x" * 300_000) - calls = [] - - def slow_run(cmd, **kwargs): - calls.append(cmd) - time.sleep(0.3) - open(cmd[-1], "wb").write(b"compressed") - return subprocess.CompletedProcess(cmd, 0) - - results = [] - - def worker(): - results.append(_compress_for_download(str(f), max_bytes=200_000)) - - with mock.patch.object(app_module, "probe_video", return_value={"duration": 2.0}), \ - mock.patch.object(app_module.subprocess, "run", side_effect=slow_run): - threads = [threading.Thread(target=worker) for _ in range(2)] - for t in threads: - t.start() - for t in threads: - t.join(timeout=30) - - assert len(calls) == 1 - assert results == [str(tmp_path / "big_compressed.mp4")] * 2 - -# ── real ffmpeg smoke test ───────────────────────────────────────────── - -@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed") -def test_real_ffmpeg_smoke(tmp_path): - """Real encode of a tiny video+audio file lands under the byte cap.""" - src = tmp_path / "tiny.mp4" - # lossless source so it is genuinely larger than max_bytes - subprocess.run( - ["ffmpeg", "-y", - "-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=10", - "-f", "lavfi", "-i", "sine=frequency=440:duration=2", - "-c:v", "libx264", "-qp", "0", "-preset", "veryfast", - "-c:a", "aac", "-b:a", "128k", "-shortest", str(src)], - check=True, capture_output=True, stdin=subprocess.DEVNULL, - ) - max_bytes = 60_000 - assert os.path.getsize(src) > max_bytes, "source must exceed cap to compress" - - out = _compress_for_download(str(src), max_bytes=max_bytes) - - assert out is not None - assert os.path.getsize(out) <= max_bytes - assert not os.path.exists(out + ".tmp") - -# ── download route ────────────────────────────────────────────────────── @pytest.fixture def client(): @@ -268,6 +24,7 @@ def client(): with app.test_client() as c: yield c + def _job_with_file(status="COMPLETED", name="out.mp4", content=b"video-bytes"): from app import job_queue from src.job import JobStatus @@ -281,35 +38,133 @@ def _job_with_file(status="COMPLETED", name="out.mp4", content=b"video-bytes"): fh.write(content) return job, path + def _completed_job_with_file(name="out.mp4", content=b"video-bytes"): return _job_with_file("COMPLETED", name, content) -def test_download_route_uses_compressed_file(client): - """Route sends the compressed path when helper returns one.""" - job, path = _completed_job_with_file() - with mock.patch.object(app_module, "_compress_for_download", return_value=path) as m: - resp = client.get(f"/download/{job.job_id}/out.mp4") + +def test_download_route_serves_the_video(client): + job, _path = _completed_job_with_file() + resp = client.get(f"/download/{job.job_id}/out.mp4") assert resp.status_code == 200 - m.assert_called_once_with(path) assert resp.data == b"video-bytes" -def test_download_route_falls_back_to_original(client): - """Route serves original file when helper returns None.""" - job, path = _completed_job_with_file() - with mock.patch.object(app_module, "_compress_for_download", return_value=None): - resp = client.get(f"/download/{job.job_id}/out.mp4") + +def test_download_route_serves_the_plain_name(client): + """The client never sees a '_compressed' file name.""" + job, _path = _completed_job_with_file() + resp = client.get(f"/download/{job.job_id}/out.mp4") assert resp.status_code == 200 - assert resp.data == b"video-bytes" + disposition = resp.headers.get("Content-Disposition", "") + assert "_compressed" not in disposition + assert "out.mp4" in disposition + + +def test_download_route_compresses_a_big_file_in_place(client): + """An oversized download is shrunk and served under its own name.""" + job, path = _completed_job_with_file(content=b"x" * 300_000) + + def fake_run(cmd, **kwargs): + with open(cmd[-1], "wb") as fh: + fh.write(b"compressed") + return subprocess.CompletedProcess(cmd, 0) + + # the route calls the real compressor; only the cap is lowered so the + # test file counts as oversized + real_compress = compress_module.compress_in_place + + def small_cap(file_path): + return real_compress(file_path, max_bytes=1024) + + with mock.patch.object(app_module, "compress_in_place", small_cap), \ + mock.patch.object(compress_module, "probe_video", return_value={"duration": 2.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=fake_run): + resp = client.get(f"/download/{job.job_id}/out.mp4") + + assert resp.status_code == 200 + assert resp.data == b"compressed" + # one file in the job dir, the compressed one + assert sorted(os.listdir(job.output_dir)) == ["out.mp4"] + def test_download_route_409_when_job_running(client): """No downloads while the job is still writing its output.""" job, _path = _job_with_file("RUNNING") - with mock.patch.object(app_module, "_compress_for_download") as m: + with mock.patch.object(app_module, "compress_in_place") as m: resp = client.get(f"/download/{job.job_id}/out.mp4") assert resp.status_code == 409 m.assert_not_called() + def test_download_route_409_when_job_pending(client): job, _path = _job_with_file("PENDING") resp = client.get(f"/download/{job.job_id}/out.mp4") assert resp.status_code == 409 + + +def test_download_route_404_when_the_file_is_gone(client): + job, path = _completed_job_with_file() + os.remove(path) + resp = client.get(f"/download/{job.job_id}/out.mp4") + assert resp.status_code == 404 + + +# ── one encode for concurrent downloads ────────────────────────────────── + + +def test_concurrent_downloads_encode_once(tmp_path): + """Two threads on the same file share one encode.""" + f = tmp_path / "big.mp4" + f.write_bytes(b"x" * 300_000) + calls = [] + + def slow_run(cmd, **kwargs): + calls.append(cmd) + time.sleep(0.3) + with open(cmd[-1], "wb") as fh: + fh.write(b"compressed") + return subprocess.CompletedProcess(cmd, 0) + + results = [] + + def worker(): + results.append(compress_in_place(str(f), max_bytes=200_000)) + + with mock.patch.object(compress_module, "probe_video", return_value={"duration": 2.0}), \ + mock.patch.object(compress_module.subprocess, "run", side_effect=slow_run): + threads = [threading.Thread(target=worker) for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join(timeout=30) + + assert len(calls) == 1 + assert f.read_bytes() == b"compressed" + assert results[0] == str(f) + + +# ── real ffmpeg smoke test ─────────────────────────────────────────────── + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed") +def test_real_ffmpeg_smoke(tmp_path): + """A real encode lands under the byte cap and replaces the source.""" + src = tmp_path / "tiny.mp4" + # lossless source so it is genuinely larger than max_bytes + subprocess.run( + ["ffmpeg", "-y", + "-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=10", + "-f", "lavfi", "-i", "sine=frequency=440:duration=2", + "-c:v", "libx264", "-qp", "0", "-preset", "veryfast", + "-c:a", "aac", "-b:a", "128k", "-shortest", str(src)], + check=True, capture_output=True, stdin=subprocess.DEVNULL, + ) + max_bytes = 60_000 + assert os.path.getsize(src) > max_bytes, "source must exceed cap to compress" + + out = compress_in_place(str(src), max_bytes=max_bytes) + + assert out == str(src) + assert os.path.getsize(out) <= max_bytes + assert not os.path.exists(out + ".compress.tmp") + assert [p.name for p in tmp_path.iterdir()] == ["tiny.mp4"] diff --git a/tests/test_job.py b/tests/test_job.py index df2f725..cc37012 100644 --- a/tests/test_job.py +++ b/tests/test_job.py @@ -569,3 +569,53 @@ def test_run_job_propagates_truncation(tmp_path, monkeypatch, merged): r = job.results[0] assert r.truncated is True assert r.frames_expected == 100 + + +def test_run_job_compresses_the_output_when_the_job_finishes(tmp_path, monkeypatch): + """A finished job leaves ONE video: the compressed one, under its name.""" + import src.job as job_mod + from src.job import Job, JobQueue, JobStatus + from src.model_registry import ModelConfig + from src.pipeline import PipelineResult + + out_dir = tmp_path / "job-compress" + out_dir.mkdir() + out_path = out_dir / "a_annotated_clip.mp4" + out_path.write_bytes(b"x" * 300_000) + + fake = PipelineResult( + output_path=str(out_path), + frame_count=10, + loading_count=5, + unloading_count=2, + batch_count=1, + duration_seconds=1.0, + model_name="a.pt", + class_filter=None, + ) + monkeypatch.setattr(job_mod, "run_pipeline", lambda **kwargs: fake) + + def fake_compress(path, **kwargs): + with open(path, "wb") as fh: + fh.write(b"compressed") + return path + + monkeypatch.setattr(job_mod, "compress_in_place", fake_compress, raising=False) + + q = JobQueue(output_dir=str(tmp_path)) + job = Job( + job_id="job-compress", + video_path="/tmp/test.mp4", + model_configs=[ + ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a", + known_classes=["sack", "box", "truck"]) + ], + output_dir=str(out_dir), + ) + q._jobs[job.job_id] = job + q._run_job(job.job_id) + + assert job.status == JobStatus.COMPLETED + # the compressed video replaced the source, under the same name + assert out_path.read_bytes() == b"compressed" + assert [p.name for p in out_dir.iterdir()] == ["a_annotated_clip.mp4"]