MediaInfo conflated content facts with a run-time handle, so byte-identical aliases could not share a probe artifact and every cache read needed a path-rebasing sweep. - models: replace MediaInfo in one sweep with content-only MediaFacts and run-time MediaRef; Artifacts gains ref; MediaFacts.extra drops local filename/path keys on construction - media.probe returns MediaFacts with no path/source and no ffprobe filename - pipeline: probe params are the content hash only; attach MediaRef on every run; delete _rebase_media/_rebase_report; keep yt-dlp title/metadata as sanitized run-time facts for reports - synthesis: prompts and metadata consume facts only; report assembly takes the run-time source; report metadata carries no local path - cli/mcp: compose facts + ref where a local path or source display is needed - CONTRACTS sections 3-4, README and PLAN reference the new shapes; tests cover the alias cache hit, facts round-trip and path-free report metadata Cache migration: dropping source from the probe params changes probe keys, so existing probe entries are a one-time invalidation (one cheap ffprobe call per source). Closes #7
615 lines
23 KiB
Python
615 lines
23 KiB
Python
"""Tests for ffprobe/ffmpeg/PySceneDetect helpers in ``video_analyse.media``.
|
|
|
|
Everything here runs locally against the synthetic ``sample_video`` fixture or
|
|
generated still images; no network access and no model downloads.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import itertools
|
|
import json
|
|
import random
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from PIL import Image, ImageDraw
|
|
|
|
from video_analyse.media import (
|
|
ShotOptions,
|
|
_activity_quantile_bounds,
|
|
_apply_shot_budget,
|
|
_merge_short_segments,
|
|
_representative_sample,
|
|
activity_curve,
|
|
dedup_keyframes,
|
|
detect_shots,
|
|
extract_audio,
|
|
extract_keyframes,
|
|
plan_shots,
|
|
probe,
|
|
)
|
|
from video_analyse.models import MediaFacts, Shot
|
|
|
|
FFPROBE = shutil.which("ffprobe")
|
|
FFMPEG = shutil.which("ffmpeg")
|
|
|
|
|
|
def _assert_shot_coverage(shots: list[Shot], duration: float) -> None:
|
|
"""Assert the shot list covers ``[0, duration]`` exactly once, in order."""
|
|
assert shots
|
|
assert [shot.index for shot in shots] == list(range(len(shots)))
|
|
assert shots[0].start == 0.0
|
|
assert shots[-1].end == duration
|
|
for shot in shots:
|
|
assert 0.0 <= shot.start < shot.end <= duration
|
|
for previous, following in itertools.pairwise(shots):
|
|
assert previous.end == following.start
|
|
|
|
|
|
def _ffprobe_json(path: Path) -> dict:
|
|
"""Run ffprobe -of json on a local file (test helper, no network)."""
|
|
if FFPROBE is None:
|
|
pytest.skip("ffprobe not found on PATH")
|
|
result = subprocess.run(
|
|
[
|
|
FFPROBE,
|
|
"-v",
|
|
"quiet",
|
|
"-show_format",
|
|
"-show_streams",
|
|
"-of",
|
|
"json",
|
|
str(path),
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=60,
|
|
)
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
async def test_probe_reads_container_and_stream_fields(sample_video: Path) -> None:
|
|
info = await probe(sample_video)
|
|
|
|
assert isinstance(info, MediaFacts)
|
|
assert "path" not in MediaFacts.model_fields
|
|
assert "source" not in MediaFacts.model_fields
|
|
assert info.duration == pytest.approx(10.0, abs=0.2)
|
|
assert info.width == 640
|
|
assert info.height == 360
|
|
assert info.fps == pytest.approx(12.0, abs=0.01)
|
|
assert info.has_audio is True
|
|
assert info.size_bytes == sample_video.stat().st_size > 0
|
|
assert info.format is not None
|
|
assert "mp4" in info.format
|
|
assert info.video_codec == "h264"
|
|
assert info.audio_codec == "aac"
|
|
# the raw ffprobe payload is kept for reports/telemetry, minus local filenames
|
|
assert info.extra["ffprobe"]["format"]["format_name"] == info.format
|
|
assert "filename" not in info.extra["ffprobe"]["format"]
|
|
assert str(sample_video) not in json.dumps(info.extra)
|
|
|
|
|
|
async def test_probe_missing_file_raises_value_error(tmp_path: Path) -> None:
|
|
with pytest.raises(ValueError, match="not found"):
|
|
await probe(tmp_path / "does-not-exist.mp4")
|
|
|
|
|
|
async def test_probe_directory_raises_value_error(tmp_path: Path) -> None:
|
|
with pytest.raises(ValueError, match="Not a regular file"):
|
|
await probe(tmp_path)
|
|
|
|
|
|
async def test_extract_audio_writes_16k_mono_s16_wav(sample_video: Path, tmp_path: Path) -> None:
|
|
wav = await extract_audio(sample_video, tmp_path)
|
|
|
|
assert wav == tmp_path / "audio.wav"
|
|
assert wav.is_file() and wav.stat().st_size > 44
|
|
|
|
streams = _ffprobe_json(wav)["streams"]
|
|
audio = next(stream for stream in streams if stream["codec_type"] == "audio")
|
|
assert audio["codec_name"] == "pcm_s16le"
|
|
assert int(audio["sample_rate"]) == 16_000
|
|
assert int(audio["channels"]) == 1
|
|
assert int(audio["bits_per_sample"]) == 16
|
|
assert audio["sample_fmt"] == "s16"
|
|
assert float(audio["duration"]) == pytest.approx(10.0, abs=0.2)
|
|
|
|
# probe() handles audio-only files: no video fields, still readable metadata
|
|
info = await probe(wav)
|
|
assert info.has_audio is True
|
|
assert info.audio_codec == "pcm_s16le"
|
|
assert info.width is None and info.height is None and info.fps is None
|
|
|
|
|
|
async def test_extract_audio_overwrites_existing_file(sample_video: Path, tmp_path: Path) -> None:
|
|
stale = tmp_path / "audio.wav"
|
|
stale.write_bytes(b"stale")
|
|
wav = await extract_audio(sample_video, tmp_path)
|
|
assert wav == stale
|
|
assert stale.stat().st_size > len(b"stale")
|
|
|
|
|
|
async def test_detect_shots_covers_duration_in_order(sample_video: Path) -> None:
|
|
info = await probe(sample_video)
|
|
shots = await detect_shots(
|
|
sample_video,
|
|
duration_hint=info.duration,
|
|
options=ShotOptions(max_shots=2, min_scene_len=0.6),
|
|
)
|
|
|
|
assert 1 <= len(shots) <= 2
|
|
assert [shot.index for shot in shots] == list(range(len(shots)))
|
|
assert shots[0].start == 0.0
|
|
assert shots[-1].end == pytest.approx(info.duration, abs=0.01)
|
|
for shot in shots:
|
|
assert 0.0 <= shot.start < shot.end <= info.duration + 0.01
|
|
for previous, following in itertools.pairwise(shots):
|
|
assert previous.end == following.start
|
|
|
|
|
|
async def test_detect_shots_respects_shot_budget(sample_video: Path) -> None:
|
|
info = await probe(sample_video)
|
|
shots = await detect_shots(sample_video, options=ShotOptions(max_shots=1))
|
|
assert len(shots) == 1
|
|
assert shots[0].index == 0
|
|
assert shots[0].start == 0.0
|
|
assert shots[0].end == pytest.approx(info.duration, abs=0.01)
|
|
|
|
with pytest.raises(ValueError, match="max_shots"):
|
|
await detect_shots(sample_video, options=ShotOptions(max_shots=0))
|
|
|
|
|
|
async def test_detect_shots_requires_known_duration(sample_video: Path, tmp_path: Path) -> None:
|
|
# scenedetect still reports the duration from the container, so this succeeds ...
|
|
shots = await detect_shots(sample_video, duration_hint=0.0)
|
|
assert len(shots) >= 1
|
|
# ... while a file that is not a video is rejected
|
|
bad = tmp_path / "bad.mp4"
|
|
bad.write_bytes(b"not a video")
|
|
with pytest.raises((ValueError, RuntimeError)):
|
|
await detect_shots(bad, duration_hint=0.0)
|
|
|
|
|
|
def test_merge_short_segments_folds_into_closer_neighbour() -> None:
|
|
segments = [(0.0, 0.2), (0.2, 5.0), (5.0, 5.3), (5.3, 10.0)]
|
|
merged = _merge_short_segments(segments, 0.6)
|
|
assert merged == [(0.0, 5.0), (5.0, 10.0)]
|
|
|
|
# nothing shorter than the threshold -> untouched
|
|
assert _merge_short_segments(segments[1:], 0.3) == segments[1:]
|
|
# a single, unavoidable short segment is kept as-is
|
|
assert _merge_short_segments([(0.0, 0.2)], 0.6) == [(0.0, 0.2)]
|
|
|
|
|
|
def test_apply_shot_budget_merges_shortest_adjacent_pairs() -> None:
|
|
segments = [(0.0, 1.0), (1.0, 2.0), (2.0, 10.0)]
|
|
assert _apply_shot_budget(segments, 3) == segments
|
|
assert _apply_shot_budget(segments, 2) == [(0.0, 2.0), (2.0, 10.0)]
|
|
assert _apply_shot_budget(segments, 1) == [(0.0, 10.0)]
|
|
with pytest.raises(ValueError, match="max_shots"):
|
|
_apply_shot_budget(segments, 0)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# pure shot planner (no ffmpeg, no filesystem)
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def test_plan_shots_global_budget_not_per_long_segment() -> None:
|
|
"""Regression: N long segments used to yield up to N x max_shots shots."""
|
|
shots = plan_shots(
|
|
300.0,
|
|
[100.0, 200.0],
|
|
None,
|
|
options=ShotOptions(
|
|
max_shots=8,
|
|
sampling="uniform",
|
|
sampling_interval_seconds=10.0,
|
|
subdivide_after_seconds=20.0,
|
|
),
|
|
)
|
|
_assert_shot_coverage(shots, 300.0)
|
|
assert len(shots) == 8 # three 100 s segments would previously give 3 x 8 = 24
|
|
|
|
|
|
@pytest.mark.parametrize("max_shots", [1, 2, 5, 8, 64])
|
|
def test_plan_shots_global_budget_holds_after_subdivision(max_shots: int) -> None:
|
|
shots = plan_shots(
|
|
300.0,
|
|
[100.0, 200.0],
|
|
None,
|
|
options=ShotOptions(
|
|
max_shots=max_shots,
|
|
sampling="uniform",
|
|
sampling_interval_seconds=10.0,
|
|
subdivide_after_seconds=20.0,
|
|
),
|
|
)
|
|
_assert_shot_coverage(shots, 300.0)
|
|
assert len(shots) == min(max_shots, 30) # 3 segments x 10 subdivisions each
|
|
|
|
|
|
def test_plan_shots_empty_cuts_returns_one_full_length_shot() -> None:
|
|
shots = plan_shots(42.0, [], None, options=ShotOptions(sampling="scene"))
|
|
|
|
assert len(shots) == 1
|
|
assert shots[0].index == 0
|
|
assert shots[0].start == 0.0
|
|
assert shots[0].end == 42.0
|
|
assert shots[0].keyframe_time is None
|
|
assert shots[0].activity is None
|
|
|
|
|
|
def test_plan_shots_merges_short_scenes_before_subdividing() -> None:
|
|
shots = plan_shots(
|
|
30.0,
|
|
[0.3, 10.0, 20.0],
|
|
None,
|
|
options=ShotOptions(min_scene_len=1.0, sampling="scene"),
|
|
)
|
|
|
|
assert [(shot.start, shot.end) for shot in shots] == [
|
|
(0.0, 10.0),
|
|
(10.0, 20.0),
|
|
(20.0, 30.0),
|
|
]
|
|
|
|
|
|
def test_plan_shots_adaptive_uses_activity_quantiles_and_calmest_frames() -> None:
|
|
busy = [(0.5 * (index + 1), 1.0) for index in range(20)] # 0.5 .. 10.0 s
|
|
quiet = [(0.5 * (index + 1), 0.0) for index in range(20, 120)] # 10.5 .. 60.0 s
|
|
|
|
shots = plan_shots(
|
|
60.0,
|
|
[],
|
|
busy + quiet,
|
|
options=ShotOptions(
|
|
sampling="adaptive",
|
|
sampling_interval_seconds=20.0,
|
|
subdivide_after_seconds=20.0,
|
|
),
|
|
)
|
|
|
|
assert [shot.start for shot in shots] == pytest.approx([0.0, 3.5, 7.0])
|
|
assert [shot.end for shot in shots] == pytest.approx([3.5, 7.0, 60.0])
|
|
assert [shot.keyframe_time for shot in shots] == pytest.approx([0.5, 3.5, 10.5])
|
|
assert shots[0].activity == pytest.approx(1.0)
|
|
assert shots[-1].activity < 0.1 # mostly quiet, with the busy tail before 10 s
|
|
|
|
|
|
def test_plan_shots_coverage_property_over_synthetic_cut_lists() -> None:
|
|
rng = random.Random(20261123)
|
|
for _ in range(120):
|
|
duration = rng.choice([1.0, 10.0, 37.5, 120.0, 300.0])
|
|
cuts = sorted(rng.uniform(-2.0, duration + 2.0) for _ in range(rng.randint(0, 20)))
|
|
sampling = rng.choice(["adaptive", "uniform", "scene"])
|
|
curve = None
|
|
if sampling == "adaptive" and rng.random() < 0.5:
|
|
curve = [(tick / 2.0, rng.random()) for tick in range(1, int(duration * 2) + 1)]
|
|
options = ShotOptions(
|
|
max_shots=rng.randint(1, 12),
|
|
min_scene_len=rng.choice([0.0, 0.2, 0.6, 2.0]),
|
|
sampling=sampling,
|
|
sampling_interval_seconds=rng.choice([5.0, 15.0]),
|
|
subdivide_after_seconds=rng.choice([1.0, 20.0]),
|
|
)
|
|
|
|
shots = plan_shots(duration, cuts, curve, options=options)
|
|
|
|
_assert_shot_coverage(shots, duration)
|
|
assert 1 <= len(shots) <= options.max_shots
|
|
assert sum(shot.end - shot.start for shot in shots) == pytest.approx(duration)
|
|
|
|
|
|
def test_plan_shots_is_deterministic() -> None:
|
|
args = (120.0, [30.0, 31.0, 90.0])
|
|
curve = [(tick / 2.0, float(tick % 5)) for tick in range(1, 240)]
|
|
options = ShotOptions(max_shots=7, sampling="adaptive")
|
|
|
|
first = plan_shots(*args, curve, options=options)
|
|
second = plan_shots(*args, curve, options=options)
|
|
|
|
assert [shot.model_dump() for shot in first] == [shot.model_dump() for shot in second]
|
|
|
|
|
|
async def test_extract_keyframes_writes_jpeg_per_shot(sample_video: Path, tmp_path: Path) -> None:
|
|
info = await probe(sample_video)
|
|
shots = await detect_shots(
|
|
sample_video, duration_hint=info.duration, options=ShotOptions(max_shots=3)
|
|
)
|
|
extracted = await extract_keyframes(sample_video, shots, tmp_path)
|
|
|
|
assert len(extracted) == len(shots)
|
|
for shot in extracted:
|
|
assert shot.keyframe is not None
|
|
assert shot.keyframe == tmp_path / "keyframes" / f"shot-{shot.index}.jpg"
|
|
assert shot.keyframe.is_file() and shot.keyframe.stat().st_size > 0
|
|
assert shot.keyframe.read_bytes().startswith(b"\xff\xd8\xff") # JPEG SOI marker
|
|
with Image.open(shot.keyframe) as image:
|
|
width, height = image.size
|
|
assert 0 < width <= 768
|
|
assert height > 0
|
|
|
|
|
|
async def test_extract_keyframes_validates_arguments(sample_video: Path, tmp_path: Path) -> None:
|
|
shots = [Shot(index=0, start=0.0, end=1.0)]
|
|
with pytest.raises(ValueError, match="width"):
|
|
await extract_keyframes(sample_video, shots, tmp_path, width=0)
|
|
with pytest.raises(ValueError, match="quality"):
|
|
await extract_keyframes(sample_video, shots, tmp_path, quality=101)
|
|
with pytest.raises(ValueError, match="namespace"):
|
|
await extract_keyframes(sample_video, shots, tmp_path, namespace="../escape")
|
|
|
|
|
|
async def test_extract_keyframes_namespaces_frames_per_shots_key(
|
|
sample_video: Path, tmp_path: Path
|
|
) -> None:
|
|
"""Different shot-detection runs must not overwrite each other's keyframe JPEGs."""
|
|
shots = [Shot(index=0, start=0.0, end=5.0)]
|
|
first = await extract_keyframes(sample_video, shots, tmp_path, namespace="a" * 12)
|
|
first_bytes = first[0].keyframe.read_bytes() if first[0].keyframe else b""
|
|
|
|
other = [Shot(index=0, start=5.0, end=10.0)]
|
|
second = await extract_keyframes(sample_video, other, tmp_path, namespace="b" * 12)
|
|
|
|
assert first[0].keyframe == tmp_path / "keyframes" / ("a" * 12) / "shot-0.jpg"
|
|
assert second[0].keyframe == tmp_path / "keyframes" / ("b" * 12) / "shot-0.jpg"
|
|
assert first[0].keyframe.read_bytes() == first_bytes
|
|
assert first[0].keyframe.read_bytes() != second[0].keyframe.read_bytes()
|
|
|
|
|
|
def _pattern_image(path: Path, boxes: list[tuple[int, int, int, int]]) -> Path:
|
|
"""Write a small high-contrast JPEG so perceptual hashes are meaningful."""
|
|
image = Image.new("RGB", (96, 96), "white")
|
|
draw = ImageDraw.Draw(image)
|
|
for box in boxes:
|
|
draw.rectangle(box, fill="black")
|
|
image.save(path, format="JPEG", quality=90)
|
|
return path
|
|
|
|
|
|
def test_dedup_keyframes_drops_duplicate_content(tmp_path: Path) -> None:
|
|
original = _pattern_image(tmp_path / "a.jpg", [(0, 0, 30, 30), (30, 30, 96, 60)])
|
|
copy = _pattern_image(tmp_path / "a-copy.jpg", [(0, 0, 30, 30), (30, 30, 96, 60)])
|
|
different = _pattern_image(tmp_path / "b.jpg", [(60, 60, 96, 96), (0, 60, 40, 96)])
|
|
|
|
def fresh_shots() -> list[Shot]:
|
|
return [
|
|
Shot(index=0, start=0.0, end=1.0, keyframe=original),
|
|
Shot(index=1, start=1.0, end=2.0, keyframe=copy),
|
|
Shot(index=2, start=2.0, end=3.0, keyframe=different),
|
|
Shot(index=3, start=3.0, end=4.0, keyframe=None),
|
|
]
|
|
|
|
kept = dedup_keyframes(fresh_shots())
|
|
assert len(kept) == 3
|
|
# indices are preserved (the duplicate left a gap) so keyframe names keep matching
|
|
assert [shot.index for shot in kept] == [0, 2, 3]
|
|
assert kept[0].keyframe == original
|
|
assert kept[1].keyframe == different
|
|
assert kept[2].keyframe is None
|
|
assert kept[0].phash is not None and len(kept[0].phash) == 16
|
|
assert kept[1].phash is not None and len(kept[1].phash) == 16
|
|
assert kept[0].phash != kept[1].phash
|
|
assert kept[2].phash is None
|
|
|
|
# threshold 0 still drops exact duplicates ...
|
|
assert len(dedup_keyframes(fresh_shots(), threshold=0)) == 3
|
|
# ... while a large threshold also swallows the visibly different frame
|
|
assert len(dedup_keyframes(fresh_shots(), threshold=100)) == 2
|
|
with pytest.raises(ValueError, match="threshold"):
|
|
dedup_keyframes(fresh_shots(), threshold=-1)
|
|
|
|
|
|
def test_dedup_keyframes_keeps_unreadable_keyframes(tmp_path: Path) -> None:
|
|
broken = tmp_path / "broken.jpg"
|
|
broken.write_bytes(b"definitely not a jpeg")
|
|
shots = [
|
|
Shot(index=0, start=0.0, end=1.0, keyframe=broken),
|
|
Shot(index=1, start=1.0, end=2.0, keyframe=tmp_path / "missing.jpg"),
|
|
]
|
|
kept = dedup_keyframes(shots)
|
|
assert len(kept) == 2
|
|
assert all(shot.phash is None for shot in kept)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# shot sampling modes (scene cuts / uniform / activity-adaptive)
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def sparse_cuts_video(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
|
"""45 s unchanging colour clip: zero scene cuts, one 45 s shot."""
|
|
if FFMPEG is None:
|
|
pytest.skip("ffmpeg not found on PATH")
|
|
out = tmp_path_factory.mktemp("media") / "plain-color.mp4"
|
|
subprocess.run(
|
|
[
|
|
FFMPEG,
|
|
"-y",
|
|
"-f",
|
|
"lavfi",
|
|
"-i",
|
|
"color=c=0x224488:s=320x180:d=45:r=5",
|
|
"-pix_fmt",
|
|
"yuv420p",
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"veryfast",
|
|
str(out),
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
)
|
|
assert out.is_file() and out.stat().st_size > 0
|
|
return out
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def busy_quiet_video(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
|
"""60 s clip: 40 s of continuously animating content, then 20 s of flat colour."""
|
|
if FFMPEG is None:
|
|
pytest.skip("ffmpeg not found on PATH")
|
|
out = tmp_path_factory.mktemp("media") / "busy-quiet.mp4"
|
|
subprocess.run(
|
|
[
|
|
FFMPEG,
|
|
"-y",
|
|
"-f",
|
|
"lavfi",
|
|
"-i",
|
|
"mandelbrot=s=320x180:r=10",
|
|
"-f",
|
|
"lavfi",
|
|
"-i",
|
|
"color=c=0x224488:s=320x180:r=10:d=20",
|
|
"-filter_complex",
|
|
"[0:v]trim=duration=40,setpts=PTS-STARTPTS[v0];[v0][1:v]concat=n=2:v=1:a=0",
|
|
"-pix_fmt",
|
|
"yuv420p",
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"veryfast",
|
|
str(out),
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
)
|
|
assert out.is_file() and out.stat().st_size > 0
|
|
return out
|
|
|
|
|
|
async def test_activity_curve_reports_change(sample_video: Path) -> None:
|
|
curve = await activity_curve(sample_video)
|
|
assert 15 <= len(curve) <= 20 # 10 s at 2 fps minus the undiffable first frame
|
|
assert all(time > 0 for time, _ in curve)
|
|
assert max(score for _, score in curve) > 0 # testsrc2 visibly changes
|
|
|
|
|
|
def test_activity_quantile_bounds_concentrate_on_activity() -> None:
|
|
"""Equal cumulative activity: 10 s of motion gets 2 boundaries, 50 s of stillness 1."""
|
|
busy = [(0.5 * (i + 1), 1.0) for i in range(20)] # 0.5 .. 10.0 s
|
|
quiet = [(0.5 * (i + 1), 0.0) for i in range(20, 120)] # 10.5 .. 60.0 s
|
|
bounds = _activity_quantile_bounds(busy + quiet, 0.0, 60.0, 3)
|
|
assert bounds[0] == pytest.approx(0.0)
|
|
assert bounds[1] == pytest.approx(3.5) # one third of the total activity
|
|
assert bounds[2] == pytest.approx(7.0) # two thirds of the total activity
|
|
assert bounds[3] == pytest.approx(60.0)
|
|
|
|
|
|
def test_activity_quantile_bounds_degenerate_cases() -> None:
|
|
# zero activity everywhere -> uniform grid
|
|
flat = [(0.5 * (i + 1), 0.0) for i in range(120)]
|
|
assert _activity_quantile_bounds(flat, 0.0, 60.0, 4) == pytest.approx(
|
|
[0.0, 15.0, 30.0, 45.0, 60.0]
|
|
)
|
|
# no samples inside the range -> uniform grid
|
|
assert _activity_quantile_bounds([], 0.0, 60.0, 3) == pytest.approx([0.0, 20.0, 40.0, 60.0])
|
|
|
|
|
|
def test_representative_sample_picks_calmest() -> None:
|
|
curve = [(1.0, 0.9), (2.0, 0.1), (3.0, 0.4), (4.0, 0.1)]
|
|
time, activity = _representative_sample(curve, 0.0, 5.0, global_max=1.0)
|
|
assert time == pytest.approx(2.0) # earliest of the calmest samples
|
|
assert activity == pytest.approx(0.375) # mean score 1.5/4
|
|
|
|
|
|
async def test_detect_shots_adaptive_subdivides_long_shots(sparse_cuts_video: Path) -> None:
|
|
"""45 s single shot with zero activity: 3 equal segments, calmest keyframes."""
|
|
info = await probe(sparse_cuts_video)
|
|
shots = await detect_shots(sparse_cuts_video, duration_hint=info.duration)
|
|
assert len(shots) == 3
|
|
assert shots[0].start == pytest.approx(0.0)
|
|
assert shots[-1].end == pytest.approx(info.duration)
|
|
for prev, shot in itertools.pairwise(shots):
|
|
assert shot.start == pytest.approx(prev.start + 15.0, abs=0.5)
|
|
for shot in shots:
|
|
assert shot.keyframe_time is not None # calmest sample; ties -> earliest
|
|
assert shot.start <= shot.keyframe_time < shot.end
|
|
assert shot.activity == 0.0
|
|
|
|
|
|
async def test_detect_shots_uniform_mode_uses_equal_intervals(sparse_cuts_video: Path) -> None:
|
|
info = await probe(sparse_cuts_video)
|
|
shots = await detect_shots(
|
|
sparse_cuts_video,
|
|
duration_hint=info.duration,
|
|
options=ShotOptions(sampling="uniform"),
|
|
)
|
|
assert len(shots) == 3
|
|
for prev, shot in itertools.pairwise(shots):
|
|
assert shot.start == pytest.approx(prev.start + 15.0, abs=0.5)
|
|
assert all(shot.keyframe_time is None for shot in shots) # midpoint keyframes
|
|
|
|
|
|
async def test_detect_shots_scene_mode_never_subdivides(sparse_cuts_video: Path) -> None:
|
|
info = await probe(sparse_cuts_video)
|
|
shots = await detect_shots(
|
|
sparse_cuts_video,
|
|
duration_hint=info.duration,
|
|
options=ShotOptions(sampling="scene"),
|
|
)
|
|
assert len(shots) == 1
|
|
assert shots[0].start == pytest.approx(0.0)
|
|
assert shots[0].end == pytest.approx(info.duration)
|
|
|
|
|
|
async def test_detect_shots_adaptive_concentrates_on_busy_regions(busy_quiet_video: Path) -> None:
|
|
"""min_scene_len=25 merges everything: one 60 s shot subdivided by activity mass.
|
|
|
|
All visual activity lives in the animated first half (0-40 s, roughly constant
|
|
frame-to-frame change); the equal-activity split therefore places three dense
|
|
segments inside it and covers the quiet remainder with a single long segment.
|
|
"""
|
|
info = await probe(busy_quiet_video)
|
|
shots = await detect_shots(
|
|
busy_quiet_video, duration_hint=info.duration, options=ShotOptions(min_scene_len=25)
|
|
)
|
|
assert len(shots) == 4 # round(60 / 15)
|
|
dense, tail = shots[:3], shots[3]
|
|
assert all(shot.end <= 41.0 for shot in dense) # boundaries sit inside the busy half
|
|
assert tail.start <= 41.0
|
|
assert tail.end == pytest.approx(info.duration, abs=1.0)
|
|
# the quiet remainder is covered by one segment much longer than the dense ones
|
|
assert (tail.end - tail.start) > 2 * max(shot.end - shot.start for shot in dense)
|
|
assert all(shot.keyframe_time is not None and shot.activity > 0 for shot in dense)
|
|
|
|
|
|
async def test_detect_shots_short_shots_are_not_subdivided(sample_video: Path) -> None:
|
|
"""The 10 s fixture stays a single shot (below the 20 s threshold)."""
|
|
info = await probe(sample_video)
|
|
shots = await detect_shots(sample_video, duration_hint=info.duration)
|
|
assert len(shots) == 1
|
|
assert shots[0].end == pytest.approx(info.duration)
|
|
assert shots[0].keyframe_time is None
|
|
|
|
|
|
async def test_detect_shots_long_sparse_video_respects_global_budget(
|
|
sparse_cuts_video: Path,
|
|
) -> None:
|
|
"""A 45 s shot naturally subdivides into 3; the global budget caps it at 2."""
|
|
info = await probe(sparse_cuts_video)
|
|
shots = await detect_shots(
|
|
sparse_cuts_video,
|
|
duration_hint=info.duration,
|
|
options=ShotOptions(max_shots=2),
|
|
)
|
|
_assert_shot_coverage(shots, info.duration)
|
|
assert len(shots) == 2
|
|
|
|
|
|
async def test_detect_shots_sampling_args_are_validated(sample_video: Path) -> None:
|
|
with pytest.raises(ValueError, match="sampling"):
|
|
ShotOptions(sampling="bogus")
|
|
with pytest.raises(ValueError, match="sampling_interval_seconds"):
|
|
await detect_shots(sample_video, options=ShotOptions(sampling_interval_seconds=0))
|
|
with pytest.raises(ValueError, match="subdivide_after_seconds"):
|
|
await detect_shots(sample_video, options=ShotOptions(subdivide_after_seconds=-1))
|