pipeline+ingest: one stage descriptor table and a real ingest stage

This commit is contained in:
alex committed 2026-11-24 10:51:54 +00:00
1 parent 799a810b60
commit 265b834858
6 files changed
+1120 -640

No files matched your search

+142 -125
View File
@@ -1,9 +1,10 @@
"""Source ingest: resolve local media paths and download remote videos. """Source ingest: validate local media paths and download remote videos.
Local files are validated in place. ``http(s)`` URLs are downloaded with yt-dlp Local files are validated in place by :func:`validate_local_source`. ``http(s)``
into a deterministic per-URL directory under ``<cache_dir>/downloads/`` so that a URLs are downloaded into the content-addressed source directory of the ingest stage
second run reuses the same files. Anything else (other URL schemes) is rejected (``<cache_dir>/<ingest_key[:16]>/``), so the media file lives next to its
with a ``ValueError``. :class:`IngestResult` artifact like ``audio.wav`` lives next to the audio artifact.
Anything else (other URL schemes) is rejected with a ``ValueError``.
The blocking yt-dlp call runs in a worker thread; nothing here touches the network The blocking yt-dlp call runs in a worker thread; nothing here touches the network
unless an ``http(s)`` URL is passed in. unless an ``http(s)`` URL is passed in.
@@ -13,20 +14,19 @@ from __future__ import annotations
import asyncio import asyncio
import contextlib import contextlib
import hashlib
import json
import logging import logging
import re import re
from importlib import metadata
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from urllib.parse import urlparse from urllib.parse import urlparse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from .cache import StageCache
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
DOWNLOAD_DIR_NAME = "downloads"
INGEST_INFO_FILE_NAME = "ingest-info.json"
DIRECT_DOWNLOAD_TIMEOUT_S = 900.0 DIRECT_DOWNLOAD_TIMEOUT_S = 900.0
VIDEO_EXTENSIONS = frozenset( VIDEO_EXTENSIONS = frozenset(
@@ -58,7 +58,13 @@ VIDEO_EXTENSIONS = frozenset(
AUDIO_EXTENSIONS = frozenset({".aac", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".wma"}) AUDIO_EXTENSIONS = frozenset({".aac", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".wma"})
MEDIA_EXTENSIONS = VIDEO_EXTENSIONS | AUDIO_EXTENSIONS MEDIA_EXTENSIONS = VIDEO_EXTENSIONS | AUDIO_EXTENSIONS
__all__ = ["IngestResult", "fetch"] __all__ = [
"IngestResult",
"fetch",
"ingest_key_params",
"validate_local_source",
"yt_dlp_version",
]
class IngestResult(BaseModel): class IngestResult(BaseModel):
@@ -88,26 +94,6 @@ def _redacted_url(url: str) -> str:
return redacted or "<url>" return redacted or "<url>"
def _safe_dir_name(url: str) -> str:
"""Deterministic, filesystem-safe directory name for a download URL.
Only the hostname (never userinfo) and path are used in the human-readable slug,
so credentials embedded in a URL never reach the cache path or a log line.
"""
parsed = urlparse(url)
raw = f"{_host_with_port(parsed)}{parsed.path}"
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", raw).strip("-._")
if not slug:
slug = "download"
digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:10]
return f"{slug[:64]}-{digest}"
def _download_dir_name(url: str, quality: int) -> str:
"""Download identity: URL *and* requested quality (PLAN section 3.4)."""
return f"{_safe_dir_name(url)}-q{int(quality)}"
def _is_direct_media_url(url: str) -> bool: def _is_direct_media_url(url: str) -> bool:
"""True for ``http(s)`` URLs that name a media file directly (no site extractor).""" """True for ``http(s)`` URLs that name a media file directly (no site extractor)."""
return Path(urlparse(url).path).suffix.lower() in MEDIA_EXTENSIONS return Path(urlparse(url).path).suffix.lower() in MEDIA_EXTENSIONS
@@ -172,8 +158,8 @@ def _candidate_paths(ydl: Any, info: dict[str, Any], target_dir: Path) -> list[P
] ]
def _find_media_file(target_dir: Path) -> Path | None: def _newest_media_file(target_dir: Path) -> Path | None:
"""Return the newest media file already present in ``target_dir``, if any.""" """Return the newest completed media file in ``target_dir``, if any."""
if not target_dir.is_dir(): if not target_dir.is_dir():
return None return None
media_files = [ media_files = [
@@ -195,17 +181,10 @@ def _resolve_downloaded_path(ydl: Any, info: dict[str, Any], target_dir: Path) -
return candidate.resolve() return candidate.resolve()
# Remuxing/merging may change the extension, so fall back to the newest media file. # Remuxing/merging may change the extension, so fall back to the newest media file.
media_files = [ newest = _newest_media_file(target_dir)
entry if newest is not None:
for entry in target_dir.iterdir()
if entry.is_file()
and entry.suffix.lower() in MEDIA_EXTENSIONS
and not entry.name.endswith(".part")
]
if media_files:
newest = max(media_files, key=lambda entry: entry.stat().st_mtime)
logger.debug("Resolved download via directory scan: %s", newest) logger.debug("Resolved download via directory scan: %s", newest)
return newest.resolve() return newest
raise RuntimeError( raise RuntimeError(
f"yt-dlp reported success for {info.get('webpage_url') or info.get('id') or 'the URL'} " f"yt-dlp reported success for {info.get('webpage_url') or info.get('id') or 'the URL'} "
@@ -240,38 +219,6 @@ def _download_sync(url: str, target_dir: Path, quality: int) -> tuple[Path, dict
return path, clean_info return path, clean_info
def _save_ingest_info(target_dir: Path, path: Path, info: dict[str, Any]) -> None:
"""Persist the resolved download path and metadata for later cache hits."""
payload = {"path": str(path), "info": info}
try:
(target_dir / INGEST_INFO_FILE_NAME).write_text(
json.dumps(payload, ensure_ascii=False, default=str) + "\n", encoding="utf-8"
)
except OSError as exc: # a read-only cache must not fail the download
logger.warning("could not write ingest metadata in %s: %s", target_dir, exc)
def _load_cached_download(target_dir: Path) -> tuple[Path, dict[str, Any]] | None:
"""Return a previously completed download for this URL+quality, if still present."""
payload_path = target_dir / INGEST_INFO_FILE_NAME
if not payload_path.is_file():
return None
try:
payload = json.loads(payload_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(payload, dict):
return None
raw_path = payload.get("path")
info = payload.get("info")
if not isinstance(raw_path, str) or not isinstance(info, dict):
return None
path = Path(raw_path)
if not path.is_file() or path.stat().st_size == 0:
return None
return path, info
async def _download_direct(url: str, target_dir: Path, quality: int) -> tuple[Path, dict[str, Any]]: async def _download_direct(url: str, target_dir: Path, quality: int) -> tuple[Path, dict[str, Any]]:
"""Fetch a direct media URL with ffmpeg (no yt-dlp, argument list, no shell).""" """Fetch a direct media URL with ffmpeg (no yt-dlp, argument list, no shell)."""
parsed = urlparse(url) parsed = urlparse(url)
@@ -335,19 +282,112 @@ async def _download_direct(url: str, target_dir: Path, quality: int) -> tuple[Pa
"url": _redacted_url(url), "url": _redacted_url(url),
} }
logger.info("Downloaded direct media URL %s to %s", _redacted_url(url), target) logger.info("Downloaded direct media URL %s to %s", _redacted_url(url), target)
_save_ingest_info(target_dir, target, info)
return target.resolve(), info return target.resolve(), info
async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestResult: def yt_dlp_version() -> str:
"""Resolve ``source`` to a local media file, downloading http(s) URLs via yt-dlp. """Return the installed yt-dlp version (part of the ingest cache key)."""
try:
return metadata.version("yt-dlp")
except metadata.PackageNotFoundError:
return "unknown"
``quality`` is the maximum video height in pixels for downloads. Local paths must
exist and carry a known media extension; URLs must be ``http``/``https``. def ingest_key_params(source: str, quality: int) -> dict[str, Any]:
"""Inputs of the ingest cache key: URL, requested quality and yt-dlp version."""
return {"url": source, "quality": int(quality), "yt_dlp": yt_dlp_version()}
def validate_local_source(source: str | Path) -> Path:
"""Validate a local media path and return its resolved form.
This is the one local-source policy: exists, is a regular file, is non-empty and
carries a known media extension. ``ingest.fetch`` and the pipeline both call it,
so an empty ``.mp4`` fails once with one message.
Raises: Raises:
ValueError: empty source, other URL schemes, missing/empty local file, an ValueError: the path is missing, not a file, empty or has an unknown extension.
unknown extension, or a non-positive ``quality``. """
local = Path(source).expanduser()
if not local.exists():
raise ValueError(f"Local media file not found: {local}")
if not local.is_file():
raise ValueError(f"Local path is not a regular file: {local}")
if local.stat().st_size == 0:
raise ValueError(f"Local media file is empty: {local}")
suffix = local.suffix.lower()
if suffix not in MEDIA_EXTENSIONS:
supported = ", ".join(sorted(MEDIA_EXTENSIONS))
shown = suffix if suffix else "<none>"
raise ValueError(
f"{local} does not look like a media file (extension {shown}); "
f"supported extensions: {supported}"
)
return local.resolve()
def _clear_downloaded_media(target_dir: Path) -> None:
"""Remove a previous download's payload so ``force`` really re-downloads."""
if not target_dir.is_dir():
return
for entry in target_dir.iterdir():
if not entry.is_file():
continue
if entry.suffix.lower() in MEDIA_EXTENSIONS or entry.name.endswith((".part", ".info.json")):
with contextlib.suppress(OSError):
entry.unlink()
def _ingest_artifact_usable(result: IngestResult) -> bool:
"""True when the artifact still points at a valid local media file."""
try:
validate_local_source(result.path)
except (OSError, ValueError):
return False
return True
async def _download_media(
source: str, target_dir: Path, quality: int, *, force: bool
) -> IngestResult:
"""Download ``source`` into ``target_dir`` and describe the resulting file."""
if force:
_clear_downloaded_media(target_dir)
existing = _newest_media_file(target_dir)
logger.info("Downloading %s into %s", _redacted_url(source), target_dir)
if _is_direct_media_url(source):
path, info = await _download_direct(source, target_dir, quality)
downloaded = True
else:
path, info = await asyncio.to_thread(_download_sync, source, target_dir, quality)
downloaded = existing is None or path != existing
if not downloaded:
logger.info("yt-dlp reused an existing file for %s", _redacted_url(source))
return IngestResult(
path=path,
info=info,
downloaded=downloaded,
title=_title_from_info(info),
)
async def fetch(
source: str,
*,
cache_dir: Path,
quality: int = 1080,
force: bool = False,
) -> IngestResult:
"""Resolve ``source`` to a local media file, downloading http(s) URLs via yt-dlp.
``quality`` is the maximum video height in pixels for downloads. Local paths are
validated by :func:`validate_local_source`; URLs must be ``http``/``https``.
``force`` bypasses the cached :class:`IngestResult` and removes the previous
download so yt-dlp fetches the media again.
Raises:
ValueError: empty source, other URL schemes, missing/empty/unknown local file,
or a non-positive ``quality``.
RuntimeError: yt-dlp failed, timed out, or produced no media file. RuntimeError: yt-dlp failed, timed out, or produced no media file.
""" """
if isinstance(quality, bool) or not isinstance(quality, int) or quality < 1: if isinstance(quality, bool) or not isinstance(quality, int) or quality < 1:
@@ -361,54 +401,31 @@ async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestR
if scheme in {"http", "https"}: if scheme in {"http", "https"}:
if not parsed.netloc: if not parsed.netloc:
raise ValueError(f"Malformed URL (missing host): {_redacted_url(source)!r}") raise ValueError(f"Malformed URL (missing host): {_redacted_url(source)!r}")
target_dir = ( cache = StageCache(cache_dir)
Path(cache_dir).expanduser() / DOWNLOAD_DIR_NAME / _download_dir_name(source, quality) key = cache.stage_key("ingest", ingest_key_params(source, quality))
) artifact_path = cache.stage_path(key, "ingest", key)
cached = _load_cached_download(target_dir) executed = False
if cached is not None:
path, info = cached async def run() -> IngestResult:
logger.info("Reusing cached download %s", _redacted_url(source)) nonlocal executed
return IngestResult( executed = True
path=path, info=info, downloaded=False, title=_title_from_info(info) return await _download_media(source, cache.source_dir(key), quality, force=force)
)
logger.info("Downloading %s into %s", _redacted_url(source), target_dir) result = await cache.cached_run(
if _is_direct_media_url(source): artifact_path,
path, info = await _download_direct(source, target_dir, quality) IngestResult,
else: run,
existing = _find_media_file(target_dir) force=force,
path, info = await asyncio.to_thread(_download_sync, source, target_dir, quality) validate=_ingest_artifact_usable,
if existing is not None and path == existing:
logger.info("yt-dlp reused an existing file for %s", _redacted_url(source))
_save_ingest_info(target_dir, path, info)
return IngestResult(
path=path, info=info, downloaded=False, title=_title_from_info(info)
)
_save_ingest_info(target_dir, path, info)
return IngestResult(
path=path,
info=info,
downloaded=True,
title=_title_from_info(info),
) )
if not executed:
return result.model_copy(update={"downloaded": False})
return result
if scheme: if scheme:
raise ValueError( raise ValueError(
f"Unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file path " f"Unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file path "
"or an http(s) URL" "or an http(s) URL"
) )
local = Path(source).expanduser() local = validate_local_source(source)
if not local.exists(): return IngestResult(path=local, info={}, downloaded=False, title=None)
raise ValueError(f"Local media file not found: {local}")
if not local.is_file():
raise ValueError(f"Local path is not a regular file: {local}")
suffix = local.suffix.lower()
if suffix not in MEDIA_EXTENSIONS:
supported = ", ".join(sorted(MEDIA_EXTENSIONS))
shown = suffix if suffix else "<none>"
raise ValueError(
f"{local} does not look like a media file (extension {shown}); "
f"supported extensions: {supported}"
)
if local.stat().st_size == 0:
raise ValueError(f"Local media file is empty: {local}")
return IngestResult(path=local.resolve(), info={}, downloaded=False, title=None)
File diff suppressed because it is too large. Load diff
+31
View File
@@ -15,6 +15,7 @@ import pytest
from video_analyse import cache as cache_module from video_analyse import cache as cache_module
from video_analyse.cache import StageCache from video_analyse.cache import StageCache
from video_analyse.ingest import IngestResult
from video_analyse.models import MediaFacts, Segment, Transcript, Word from video_analyse.models import MediaFacts, Segment, Transcript, Word
@@ -382,6 +383,36 @@ async def test_cached_run_treats_a_corrupt_artifact_as_a_miss(
assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"] assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"]
async def test_ingest_artifacts_share_the_atomic_corruption_safe_cache(
cache: StageCache, tmp_path: Path
) -> None:
"""The ingest artifact is a normal StageCache model: atomic writes, miss on corrupt."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"video bytes")
artifact = IngestResult(path=media, info={"id": "abc"}, downloaded=True, title="Clip")
digest = "a" * 64
key = cache.stage_key("ingest", {"url": "https://example.invalid/v", "quality": 720})
path = cache.stage_path(digest, "ingest", key)
cache.save_model(path, artifact)
assert [entry.name for entry in path.parent.iterdir()] == [path.name]
assert cache.load_model(path, IngestResult) == artifact
calls: list[str] = []
async def runner() -> IngestResult:
calls.append("run")
return artifact
for payload in ("{not json", '{"path": "x.mp4"}', '{"path": 1, "downloaded": true}'):
path.write_text(payload, encoding="utf-8")
calls.clear()
assert await cache.cached_run(path, IngestResult, runner) == artifact
assert calls == ["run"]
assert cache.load_model(path, IngestResult) == artifact
async def test_cached_run_reruns_when_validation_rejects_the_cached_model( async def test_cached_run_reruns_when_validation_rejects_the_cached_model(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None: ) -> None:
+32 -20
View File
@@ -6,14 +6,14 @@ tests never open a socket and never download anything.
from __future__ import annotations from __future__ import annotations
import re
from pathlib import Path from pathlib import Path
from typing import Any, ClassVar from typing import Any, ClassVar
import pytest import pytest
from yt_dlp.utils import DownloadError from yt_dlp.utils import DownloadError
from video_analyse.ingest import IngestResult, _safe_dir_name, fetch from video_analyse.cache import StageCache
from video_analyse.ingest import IngestResult, fetch, ingest_key_params
URL = "https://example.invalid/watch?v=abc123&list=PL123" URL = "https://example.invalid/watch?v=abc123&list=PL123"
DOWNLOAD_FILE_NAME = "My Clip [abc123].mp4" DOWNLOAD_FILE_NAME = "My Clip [abc123].mp4"
@@ -136,8 +136,9 @@ async def test_fetch_downloads_http_url_into_cache(
result = await fetch(URL, cache_dir=cache_dir, quality=720) result = await fetch(URL, cache_dir=cache_dir, quality=720)
slug = f"{_safe_dir_name(URL)}-q720" cache = StageCache(cache_dir)
expected_dir = (cache_dir / "downloads" / slug).resolve() key = cache.stage_key("ingest", ingest_key_params(URL, 720))
expected_dir = cache.source_dir(key).resolve()
assert result.downloaded is True assert result.downloaded is True
assert result.title == "My Clip" assert result.title == "My Clip"
assert result.info["id"] == "abc123" assert result.info["id"] == "abc123"
@@ -145,6 +146,8 @@ async def test_fetch_downloads_http_url_into_cache(
assert result.path.is_file() assert result.path.is_file()
assert result.path.name == DOWNLOAD_FILE_NAME assert result.path.name == DOWNLOAD_FILE_NAME
assert result.path.parent == expected_dir assert result.path.parent == expected_dir
# The old parallel manifest cache is gone: the StageCache artifact is the cache.
assert not (result.path.parent / "ingest-info.json").exists()
assert len(fake_ydl.calls) == 1 assert len(fake_ydl.calls) == 1
options = fake_ydl.calls[0] options = fake_ydl.calls[0]
@@ -165,12 +168,27 @@ async def test_fetch_uses_a_stable_directory_per_url(
home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls} home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls}
assert len(home_dirs) == 1 assert len(home_dirs) == 1
assert first.downloaded is True assert first.downloaded is True
assert second.downloaded is False # reused from the URL+quality cache directory assert second.downloaded is False # reused from the StageCache ingest artifact
assert len(fake_ydl.calls) == 1 assert len(fake_ydl.calls) == 1
assert first.path == second.path assert first.path == second.path
assert first.info == second.info assert first.info == second.info
async def test_fetch_force_bypasses_the_cached_result_and_redownloads(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
cache_dir = tmp_path / "cache"
first = await fetch(URL, cache_dir=cache_dir)
assert first.downloaded is True
assert len(fake_ydl.calls) == 1
forced = await fetch(URL, cache_dir=cache_dir, force=True)
assert forced.downloaded is True
assert len(fake_ydl.calls) == 2
assert forced.path.is_file()
async def test_fetch_keys_the_download_directory_by_quality( async def test_fetch_keys_the_download_directory_by_quality(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None: ) -> None:
@@ -199,19 +217,13 @@ async def test_fetch_maps_download_errors_to_actionable_runtime_error(
assert excinfo.value.__cause__ is not None assert excinfo.value.__cause__ is not None
def test_safe_dir_name_is_stable_filesystem_safe_and_url_specific() -> None: async def test_fetch_never_puts_url_credentials_in_the_cache_path(
slug = _safe_dir_name(URL) fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
assert slug == _safe_dir_name(URL) ) -> None:
assert re.fullmatch(r"[A-Za-z0-9._-]+", slug) result = await fetch(
assert "/" not in slug and "?" not in slug and "&" not in slug "https://alice:s3cr3t@example.invalid/watch?v=abc",
assert len(slug) <= 75 cache_dir=tmp_path / "cache",
assert slug != _safe_dir_name("https://example.invalid/other?v=abc123") )
# a URL with nothing usable still yields a directory name
assert re.fullmatch(r"[A-Za-z0-9._-]+", _safe_dir_name("https://example.invalid/"))
assert "s3cr3t" not in str(result.path)
def test_safe_dir_name_never_contains_url_credentials() -> None: assert "alice" not in str(result.path)
slug = _safe_dir_name("https://alice:s3cr3t@example.invalid/private/clip.mp4")
assert "s3cr3t" not in slug
assert "alice" not in slug
assert slug.startswith("example.invalid")
+262 -2
View File
@@ -18,7 +18,7 @@ import pytest
from video_analyse.cache import StageCache from video_analyse.cache import StageCache
from video_analyse.config import Settings from video_analyse.config import Settings
from video_analyse.diarize import DiarizeOptions from video_analyse.diarize import DiarizeOptions
from video_analyse.ingest import IngestResult from video_analyse.ingest import IngestResult, fetch, ingest_key_params
from video_analyse.media import ShotOptions from video_analyse.media import ShotOptions
from video_analyse.models import ( from video_analyse.models import (
Artifacts, Artifacts,
@@ -32,7 +32,15 @@ from video_analyse.models import (
VideoReport, VideoReport,
Word, Word,
) )
from video_analyse.pipeline import STAGE_ORDER, Pipeline from video_analyse.pipeline import (
_DOWNSTREAM,
STAGE_ORDER,
STAGES_TABLE,
Pipeline,
RunContext,
StageSpec,
_resolve_want,
)
from video_analyse.synthesis import ReportOptions from video_analyse.synthesis import ReportOptions
from video_analyse.transcribe import SttOptions from video_analyse.transcribe import SttOptions
from video_analyse.vision import DescribeOptions from video_analyse.vision import DescribeOptions
@@ -804,3 +812,255 @@ async def test_describe_cache_key_tracks_diarization_context(tmp_path: Path) ->
fakes.describe_calls.clear() fakes.describe_calls.clear()
await Pipeline(_settings(tmp_path, diarize=False), fakes.mapping()).run(str(source)) await Pipeline(_settings(tmp_path, diarize=False), fakes.mapping()).run(str(source))
assert fakes.describe_calls == [2] assert fakes.describe_calls == [2]
# --------------------------------------------------------------------------- #
# the stage descriptor table (issue #8)
# --------------------------------------------------------------------------- #
def test_stage_table_is_the_single_encoding_of_the_dependency_graph() -> None:
assert tuple(STAGES_TABLE) == ("ingest", *STAGE_ORDER)
assert all(isinstance(spec, StageSpec) for spec in STAGES_TABLE.values())
assert all(spec.name == name for name, spec in STAGES_TABLE.items())
assert STAGES_TABLE["ingest"].prereqs == ()
assert STAGES_TABLE["probe"].prereqs == ("ingest",)
assert STAGES_TABLE["report"].prereqs == (
"probe",
"audio",
"transcribe",
"diarize",
"shots",
"describe",
)
def test_downstream_is_derived_from_the_descriptor_prereqs() -> None:
assert _DOWNSTREAM["probe"] == (
"audio",
"transcribe",
"diarize",
"shots",
"describe",
"report",
)
assert _DOWNSTREAM["audio"] == ("transcribe", "diarize", "describe", "report")
assert _DOWNSTREAM["shots"] == ("describe", "report")
assert _DOWNSTREAM["report"] == ()
def test_want_closure_follows_prereqs_and_honours_source_applicability() -> None:
hard, context = _resolve_want({"report"}, "/media/clip.mp4")
assert hard == {"probe", "report"}
assert context == {"audio", "transcribe", "diarize", "shots", "describe"}
hard, context = _resolve_want({"describe"}, "/media/clip.mp4")
assert hard == {"probe", "shots", "describe"}
assert context == {"transcribe", "diarize"}
assert context == {"transcribe", "diarize"}
hard, context = _resolve_want({"probe"}, "https://example.invalid/clip.mp4")
assert hard == {"ingest", "probe"}
assert context == frozenset()
local_ingest, context = _resolve_want({"ingest"}, "/media/clip.mp4")
assert local_ingest == frozenset()
assert context == frozenset()
def _run_context(tmp_path: Path, **overrides: Any) -> RunContext:
"""A RunContext with every value a key-params callable may read."""
settings = _settings(tmp_path)
cache = StageCache(settings.cache_dir)
values: dict[str, Any] = {
"pipeline": Pipeline(settings),
"source": "https://example.invalid/watch?v=abc",
"settings": settings,
"cache": cache,
"notify": lambda _message: None,
"wanted": frozenset({"report"}),
"force": False,
"ingest_quality": 720,
"max_shots": 12,
"min_scene_len": 0.25,
"video_sha": "a" * 64,
"audio_sha": "b" * 64,
"turns_applied": True,
"descriptions_applied": True,
"keys": {
"probe": "1" * 64,
"audio": "2" * 64,
"transcribe": "3" * 64,
"diarize": "4" * 64,
"shots": "5" * 64,
"describe": "6" * 64,
},
}
values.update(overrides)
return RunContext(**values)
def test_ingest_key_params_include_url_quality_and_yt_dlp_version(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("video_analyse.ingest.yt_dlp_version", lambda: "2026.01.01")
ctx = _run_context(tmp_path)
params = STAGES_TABLE["ingest"].key_params(ctx)
assert params == ingest_key_params(ctx.source, 720)
assert params["url"] == ctx.source
assert params["quality"] == 720
assert params["yt_dlp"] == "2026.01.01"
def test_probe_and_audio_key_params_use_the_content_hash(tmp_path: Path) -> None:
ctx = _run_context(tmp_path)
assert STAGES_TABLE["probe"].key_params(ctx) == {"video_sha256": "a" * 64}
assert STAGES_TABLE["audio"].key_params(ctx) == {"video_sha256": "a" * 64}
def test_transcribe_key_params_carry_the_adapter_identity_and_language(
tmp_path: Path,
) -> None:
from video_analyse.transcribe import get_transcriber
ctx = _run_context(tmp_path, settings=_settings(tmp_path, language="en"))
options = ctx.settings.options_for("stt")
identity = get_transcriber(options).identity()
params = STAGES_TABLE["transcribe"].key_params(ctx)
assert params == {
"audio_sha256": "b" * 64,
"backend": identity.backend,
"model": identity.model,
"endpoint": identity.endpoint,
"language": "en",
}
def test_diarize_key_params_use_only_the_backends_applicable_options(tmp_path: Path) -> None:
from video_analyse.diarize import get_diarizer
ctx = _run_context(tmp_path, settings=_settings(tmp_path, diarize_backend="pyannote"))
options = ctx.settings.options_for("diarize")
params = STAGES_TABLE["diarize"].key_params(ctx)
assert params == {"audio_sha256": "b" * 64, **get_diarizer(options).cache_params()}
def test_shots_key_params_carry_detector_options_and_pipeline_overrides(tmp_path: Path) -> None:
ctx = _run_context(
tmp_path,
media=MediaFacts(duration=10.0, width=640, height=360, has_audio=True, size_bytes=1),
)
params = STAGES_TABLE["shots"].key_params(ctx)
assert params["video_sha256"] == "a" * 64
assert params["detector"] == "adaptive"
assert params["max_shots"] == 12
assert params["min_scene_len"] == 0.25
assert params["keyframe_width"] == 768
def test_describe_and_report_key_params_are_composed_from_upstream_keys(
tmp_path: Path,
) -> None:
ctx = _run_context(tmp_path)
describe = STAGES_TABLE["describe"].key_params(ctx)
assert describe["shots_key"] == "5" * 64
assert describe["transcript_key"] == "3" * 64
assert describe["diarize"] == {"key": "4" * 64, "applied": True}
report = STAGES_TABLE["report"].key_params(ctx)
assert report["source"] == ctx.source
assert report["probe"] == "1" * 64
assert report["audio"] == "2" * 64
assert report["transcribe"] == "3" * 64
assert report["diarize"] == {"key": "4" * 64, "applied": True}
assert report["shots"] == "5" * 64
assert report["describe"] == {"key": "6" * 64, "applied": True}
# --------------------------------------------------------------------------- #
# ingest as a real cached stage
# --------------------------------------------------------------------------- #
async def test_ingest_stage_artifact_is_cached_and_force_redownloads(tmp_path: Path) -> None:
url = "https://example.invalid/watch?v=8"
local = _make_source(tmp_path)
fakes = FakeStages(local)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping())
await pipeline.run(url, want={"ingest"})
assert fakes.ingest_calls == [(url, settings.cache_dir, 1080)]
ingest_artifacts = list(StageCache(settings.cache_dir).cache_dir.glob("*/stage-ingest-*.json"))
assert len(ingest_artifacts) == 1
fakes.ingest_calls.clear()
messages: list[str] = []
await pipeline.run(url, want={"ingest"}, progress=messages.append)
assert fakes.ingest_calls == []
assert "ingest: cached" in messages
await pipeline.run(url, want={"ingest"}, force=True)
assert fakes.ingest_calls == [(url, settings.cache_dir, 1080)]
def test_forced_invalidation_drops_the_derived_downstream_stages(tmp_path: Path) -> None:
cache = StageCache(tmp_path / "cache")
digest = "a" * 64
model = MediaFacts(duration=1.0, has_audio=True, size_bytes=1)
for stage in ("transcribe", "diarize", "shots", "describe", "report"):
key = cache.stage_key(stage, {"probe": digest})
cache.save_model(cache.stage_path(digest, stage, key), model)
Pipeline._invalidate_downstream(cache, digest, "transcribe")
remaining = {
path.name.removeprefix("stage-").split("-", 1)[0]
for path in cache.source_dir(digest).glob("stage-*.json")
}
assert remaining == {"transcribe", "shots"}
async def test_force_ingest_drops_every_downstream_artifact(tmp_path: Path) -> None:
url = "https://example.invalid/watch?v=9"
local = _make_source(tmp_path)
fakes = FakeStages(local)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
full = await pipeline.run(url)
assert list(full.workdir.glob("stage-probe-*.json"))
assert list(full.workdir.glob("stage-report-*.json"))
forced = await pipeline.run(url, want={"ingest"}, force=True)
assert not list(forced.workdir.glob("stage-probe-*.json"))
assert not list(forced.workdir.glob("stage-report-*.json"))
async def test_want_ingest_on_a_local_path_is_an_explicit_validation_error(
tmp_path: Path,
) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
with pytest.raises(ValueError, match=r"ingest.*http"):
await pipeline.run(str(source), want={"ingest"})
async def test_empty_local_source_fails_once_with_the_shared_message(tmp_path: Path) -> None:
empty = _make_source(tmp_path, name="empty.mp4", payload=b"")
pipeline = Pipeline(_settings(tmp_path), FakeStages(_make_source(tmp_path)).mapping())
with pytest.raises(ValueError) as via_pipeline:
await pipeline.run(str(empty), want={"probe"})
with pytest.raises(ValueError) as via_ingest:
await fetch(str(empty), cache_dir=tmp_path / "cache")
assert "empty" in str(via_pipeline.value)
assert str(via_pipeline.value) == str(via_ingest.value)
+14 -7
View File
@@ -343,11 +343,22 @@ def test_local_readiness_follows_the_huggingface_cache_without_downloading(
assert transcriber.readiness().weights_present is True assert transcriber.readiness().weights_present is True
def _transcribe_cache_params(options: SttOptions) -> dict[str, Any]:
"""Call the pipeline's key builder with the options the adapter was built from."""
ctx = SimpleNamespace(
audio_sha="a" * 64,
settings=SimpleNamespace(options_for=lambda _stage: options),
)
params = _transcribe_params(ctx) # type: ignore[arg-type]
assert params is not None
return params
def test_transcribe_cache_params_use_the_adapter_identity(tmp_path: Path) -> None: def test_transcribe_cache_params_use_the_adapter_identity(tmp_path: Path) -> None:
options = _stt_options(stt_backend="whisper", whisper_model="tiny") options = _stt_options(stt_backend="whisper", whisper_model="tiny")
identity = get_transcriber(options).identity() identity = get_transcriber(options).identity()
params = _transcribe_params("a" * 64, options, identity) params = _transcribe_cache_params(options)
assert params["backend"] == identity.backend assert params["backend"] == identity.backend
assert params["model"] == identity.model assert params["model"] == identity.model
@@ -381,12 +392,8 @@ def test_a_fourth_registered_backend_cannot_alias_another_cache_key(
assert stub.identity().model == parakeet.identity().model assert stub.identity().model == parakeet.identity().model
cache = StageCache(tmp_path) cache = StageCache(tmp_path)
parakeet_key = cache.stage_key( parakeet_key = cache.stage_key("transcribe", _transcribe_cache_params(parakeet_options))
"transcribe", _transcribe_params("a" * 64, parakeet_options, parakeet.identity()) stub_key = cache.stage_key("transcribe", _transcribe_cache_params(stub_options))
)
stub_key = cache.stage_key(
"transcribe", _transcribe_params("a" * 64, stub_options, stub.identity())
)
assert stub_key != parakeet_key assert stub_key != parakeet_key