diff --git a/src/video_analyse/ingest.py b/src/video_analyse/ingest.py index b3b4c19..33f13cf 100644 --- a/src/video_analyse/ingest.py +++ b/src/video_analyse/ingest.py @@ -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 -into a deterministic per-URL directory under ``/downloads/`` so that a -second run reuses the same files. Anything else (other URL schemes) is rejected -with a ``ValueError``. +Local files are validated in place by :func:`validate_local_source`. ``http(s)`` +URLs are downloaded into the content-addressed source directory of the ingest stage +(``//``), so the media file lives next to its +: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 unless an ``http(s)`` URL is passed in. @@ -13,20 +14,19 @@ from __future__ import annotations import asyncio import contextlib -import hashlib -import json import logging import re +from importlib import metadata from pathlib import Path from typing import Any from urllib.parse import urlparse from pydantic import BaseModel, Field +from .cache import StageCache + logger = logging.getLogger(__name__) -DOWNLOAD_DIR_NAME = "downloads" -INGEST_INFO_FILE_NAME = "ingest-info.json" DIRECT_DOWNLOAD_TIMEOUT_S = 900.0 VIDEO_EXTENSIONS = frozenset( @@ -58,7 +58,13 @@ VIDEO_EXTENSIONS = frozenset( AUDIO_EXTENSIONS = frozenset({".aac", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".wma"}) MEDIA_EXTENSIONS = VIDEO_EXTENSIONS | AUDIO_EXTENSIONS -__all__ = ["IngestResult", "fetch"] +__all__ = [ + "IngestResult", + "fetch", + "ingest_key_params", + "validate_local_source", + "yt_dlp_version", +] class IngestResult(BaseModel): @@ -88,26 +94,6 @@ def _redacted_url(url: str) -> str: return redacted or "" -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: """True for ``http(s)`` URLs that name a media file directly (no site extractor).""" 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: - """Return the newest media file already present in ``target_dir``, if any.""" +def _newest_media_file(target_dir: Path) -> Path | None: + """Return the newest completed media file in ``target_dir``, if any.""" if not target_dir.is_dir(): return None media_files = [ @@ -195,17 +181,10 @@ def _resolve_downloaded_path(ydl: Any, info: dict[str, Any], target_dir: Path) - return candidate.resolve() # Remuxing/merging may change the extension, so fall back to the newest media file. - media_files = [ - entry - 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) + newest = _newest_media_file(target_dir) + if newest is not None: logger.debug("Resolved download via directory scan: %s", newest) - return newest.resolve() + return newest raise RuntimeError( 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 -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]]: """Fetch a direct media URL with ffmpeg (no yt-dlp, argument list, no shell).""" parsed = urlparse(url) @@ -335,19 +282,112 @@ async def _download_direct(url: str, target_dir: Path, quality: int) -> tuple[Pa "url": _redacted_url(url), } logger.info("Downloaded direct media URL %s to %s", _redacted_url(url), target) - _save_ingest_info(target_dir, target, info) return target.resolve(), info -async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestResult: - """Resolve ``source`` to a local media file, downloading http(s) URLs via yt-dlp. +def yt_dlp_version() -> str: + """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: - ValueError: empty source, other URL schemes, missing/empty local file, an - unknown extension, or a non-positive ``quality``. + ValueError: the path is missing, not a file, empty or has an unknown extension. + """ + 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 "" + 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. """ 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 not parsed.netloc: raise ValueError(f"Malformed URL (missing host): {_redacted_url(source)!r}") - target_dir = ( - Path(cache_dir).expanduser() / DOWNLOAD_DIR_NAME / _download_dir_name(source, quality) - ) - cached = _load_cached_download(target_dir) - if cached is not None: - path, info = cached - logger.info("Reusing cached download %s", _redacted_url(source)) - return IngestResult( - path=path, info=info, downloaded=False, title=_title_from_info(info) - ) - 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) - else: - existing = _find_media_file(target_dir) - path, info = await asyncio.to_thread(_download_sync, source, target_dir, quality) - 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), + cache = StageCache(cache_dir) + key = cache.stage_key("ingest", ingest_key_params(source, quality)) + artifact_path = cache.stage_path(key, "ingest", key) + executed = False + + async def run() -> IngestResult: + nonlocal executed + executed = True + return await _download_media(source, cache.source_dir(key), quality, force=force) + + result = await cache.cached_run( + artifact_path, + IngestResult, + run, + force=force, + validate=_ingest_artifact_usable, ) + if not executed: + return result.model_copy(update={"downloaded": False}) + return result if scheme: raise ValueError( f"Unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file path " "or an http(s) URL" ) - 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}") - suffix = local.suffix.lower() - if suffix not in MEDIA_EXTENSIONS: - supported = ", ".join(sorted(MEDIA_EXTENSIONS)) - shown = suffix if suffix else "" - 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) + local = validate_local_source(source) + return IngestResult(path=local, info={}, downloaded=False, title=None) diff --git a/src/video_analyse/pipeline.py b/src/video_analyse/pipeline.py index 0dfa106..1f7e257 100644 --- a/src/video_analyse/pipeline.py +++ b/src/video_analyse/pipeline.py @@ -1,14 +1,20 @@ -"""Stage orchestration: ordering, caching and artifact assembly. +"""Stage orchestration: one descriptor table, one scheduler loop. -The pipeline runs up to seven stages per source, in this fixed order:: +The stage graph is encoded exactly once in :data:`STAGES_TABLE`. Each +:class:`StageSpec` records a stage's prerequisites, source applicability, cache-key +params, artifact model, optional context artifacts and runner. :class:`Pipeline` +resolves the want closure from that table, iterates in stage order and delegates the +load -> miss -> run -> save policy to :meth:`~video_analyse.cache.StageCache.cached_run`. - probe -> audio -> transcribe -> diarize -> shots -> describe -> report +Stages:: -Every stage reads/writes a content-addressed artifact through -:class:`video_analyse.cache.StageCache`, so a second run over unchanged inputs only -reads JSON files. ``force=True`` re-runs the stages the caller asked for and drops -their downstream cache entries, so stale report/description data never survives a -deliberate refresh. + ingest -> probe -> audio -> transcribe -> diarize -> shots -> describe -> report + +``ingest`` is a real cached stage for ``http(s)`` sources; local sources are validated +by the shared ``ingest.validate_local_source`` policy and never run it. ``want`` names +stage *results*: prerequisites run as needed, while ``load_context`` lists cached +artifacts a stage may reuse without re-running the expensive upstream stage. A forced +stage re-runs and drops every downstream cache entry, all derived from the same table. Stage callables --------------- @@ -31,21 +37,6 @@ it wraps: Option values come from ``Settings.options_for(stage)``; stages never receive the whole settings bag. - -``want`` semantics ------------------- -``want`` names the stages whose *results* the caller needs. Stages required to -produce them run as well (``transcribe`` needs ``audio``, which needs ``probe``; -``diarize`` needs a transcript; ``describe`` needs shots). When only ``describe`` or -``report`` is wanted, already cached transcript, speaker-turn, shot and description -artifacts are loaded as context without re-running the expensive upstream stages, so a -cached report is reproduced from the cache instead of being synthesised again. -``probe`` always runs (it is a single cheap ffprobe call) because it supplies the media -metadata every artifact and report is built from. - -Diarization runs only when ``settings.diarize`` is true *and* ``"diarize"`` is in -``want``; the speaker-attributed transcript then replaces the plain one in the -returned :class:`~video_analyse.models.Artifacts`. """ from __future__ import annotations @@ -53,6 +44,7 @@ from __future__ import annotations import asyncio import logging from collections.abc import Awaitable, Callable, Collection, Mapping +from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, TypeVar from urllib.parse import urlparse @@ -61,6 +53,7 @@ from pydantic import BaseModel from .cache import StageCache from .config import Settings +from .ingest import IngestResult, ingest_key_params, validate_local_source from .models import ( Artifacts, MediaFacts, @@ -72,11 +65,10 @@ from .models import ( ) if TYPE_CHECKING: - from .diarize import DiarizeOptions, Diarizer + from .diarize import DiarizeOptions from .media import ShotOptions from .synthesis import ReportOptions - from .transcribe import SttOptions, Transcriber - from .transcribe.base import ModelIdentity + from .transcribe import SttOptions from .vision import DescribeOptions logger = logging.getLogger(__name__) @@ -87,11 +79,14 @@ __all__ = [ "DEFAULT_MIN_SCENE_LEN", "DETECTOR_NAME", "STAGES", + "STAGES_TABLE", "STAGE_ORDER", "Pipeline", + "RunContext", + "StageSpec", ] -#: Stages in execution order; the report always closes the run. +#: Analysis stages in execution order; the report always closes the run. STAGE_ORDER: tuple[str, ...] = ( "probe", "audio", @@ -101,8 +96,8 @@ STAGE_ORDER: tuple[str, ...] = ( "describe", "report", ) -#: Every name accepted in ``want`` and in the injectable ``stages`` mapping. -STAGES: frozenset[str] = frozenset({"ingest", *STAGE_ORDER}) +#: Full execution order, including the ingest stage that precedes probe. +_ALL_STAGE_ORDER: tuple[str, ...] = ("ingest", *STAGE_ORDER) DEFAULT_MAX_SHOTS = 64 DEFAULT_MIN_SCENE_LEN = 0.6 @@ -114,17 +109,6 @@ KEYFRAME_WIDTH = 768 KEYFRAME_QUALITY = 85 DEDUP_THRESHOLD = 8 -#: Cache entries to drop when a stage is re-run with ``force=True``. -_DOWNSTREAM: dict[str, tuple[str, ...]] = { - "probe": ("audio", "transcribe", "diarize", "shots", "describe", "report"), - "audio": ("transcribe", "diarize", "describe", "report"), - "transcribe": ("diarize", "describe", "report"), - "diarize": ("describe", "report"), - "shots": ("describe", "report"), - "describe": ("report",), - "report": (), -} - ModelT = TypeVar("ModelT", bound=BaseModel) StageCallable = Callable[..., Awaitable[Any]] ProgressCallback = Callable[[str], None] @@ -158,27 +142,95 @@ class _TurnsArtifact(BaseModel): turns: list[SpeakerTurn] = [] +@dataclass +class RunContext: + """Everything a stage's key-params, runner and apply callable may read. + + The scheduler fills this in stage order; fields that a stage has not produced yet + are ``None`` (or empty). ``keys`` holds each stage's cache key as soon as it has + been composed, so downstream key params never rebuild upstream keys themselves. + """ + + pipeline: Pipeline + source: str + settings: Settings + cache: StageCache + notify: ProgressCallback + wanted: frozenset[str] + force: bool + ingest_quality: int + max_shots: int + min_scene_len: float + local_path: Path | None = None + video_sha: str | None = None + workdir: Path | None = None + ingest: IngestResult | None = None + media: MediaFacts | None = None + wav: Path | None = None + audio_sha: str | None = None + transcript: Transcript | None = None + turns_applied: bool = False + shots: list[Shot] = field(default_factory=list) + report: VideoReport | None = None + descriptions_applied: bool = False + keys: dict[str, str | None] = field(default_factory=dict) + + def namespace(self, stage: str, key: str) -> str: + """Return the cache source namespace for ``stage``'s artifact.""" + if stage == "ingest": + return key + if self.video_sha is None: + raise ValueError(f"stage {stage!r} needs a resolved source hash") + return self.video_sha + + +@dataclass(frozen=True) +class StageSpec: + """One stage's complete descriptor; the graph lives only in ``STAGES_TABLE``.""" + + name: str + prereqs: tuple[str, ...] + key_params: Callable[[RunContext], dict[str, Any] | None] + model: type[BaseModel] + runner: Callable[[RunContext], Awaitable[BaseModel]] + applies: Callable[[str], bool] | None = None + load_context: tuple[str, ...] = () + apply: Callable[[RunContext, BaseModel], Awaitable[None]] | None = None + validate: Callable[[Any], bool] | None = None + skip_reason: Callable[[RunContext], str | None] | None = None + #: False when the stage's artifact is not read as context (its payload is enough). + context_cache: bool = True + + # --------------------------------------------------------------------------- # # stage input parameters (the cache keys hash exactly these) # --------------------------------------------------------------------------- # -def _probe_params(video_sha: str) -> dict[str, Any]: +def _is_url_source(source: str) -> bool: + """True for ``http(s)`` sources; only those need the ingest stage.""" + return urlparse(source).scheme.lower() in {"http", "https"} + + +def _ingest_params(ctx: RunContext) -> dict[str, Any]: + """Inputs of the ingest stage: URL, requested quality and yt-dlp version.""" + return ingest_key_params(ctx.source, ctx.ingest_quality) + + +def _probe_params(ctx: RunContext) -> dict[str, Any]: """Inputs of the probe stage: only the content hash. Probe artifacts are :class:`MediaFacts` (content only), so byte-identical copies under different names share one entry; the run-time location lives in :class:`MediaRef` and is attached after the cache read. """ - return {"video_sha256": video_sha} + return {"video_sha256": ctx.video_sha} -def _audio_params(video_sha: str) -> dict[str, Any]: +def _audio_params(ctx: RunContext) -> dict[str, Any]: """Inputs of the audio stage: the content hash of the video file.""" - return {"video_sha256": video_sha} + return {"video_sha256": ctx.video_sha} -def _transcribe_params( - audio_sha: str, options: SttOptions, identity: ModelIdentity -) -> dict[str, Any]: +def _transcribe_params(ctx: RunContext) -> dict[str, Any] | None: """Inputs of the transcribe stage: audio hash, adapter identity and language. ``identity.endpoint`` participates so repointing ``VA_STT_API_BASE_URL`` at another @@ -186,8 +238,14 @@ def _transcribe_params( model come from the adapter, never from a caller-side if/else, so a newly registered backend cannot alias another backend's checkpoint. """ + if ctx.audio_sha is None: + return None + options = ctx.settings.options_for("stt") + from .transcribe import get_transcriber + + identity = get_transcriber(options).identity() return { - "audio_sha256": audio_sha, + "audio_sha256": ctx.audio_sha, "backend": identity.backend, "model": identity.model, "endpoint": identity.endpoint, @@ -195,15 +253,27 @@ def _transcribe_params( } -def _diarize_params(audio_sha: str, cache_params: Mapping[str, Any]) -> dict[str, Any]: +def _diarize_params(ctx: RunContext) -> dict[str, Any] | None: """Inputs of the diarize stage: the audio hash plus the adapter's applicable options.""" - return {"audio_sha256": audio_sha, **cache_params} + if ctx.audio_sha is None: + return None + options = ctx.settings.options_for("diarize") + from .diarize import get_diarizer + + return {"audio_sha256": ctx.audio_sha, **get_diarizer(options).cache_params()} -def _shots_params(video_sha: str, options: ShotOptions) -> dict[str, Any]: +def _shots_params(ctx: RunContext) -> dict[str, Any] | None: """Inputs of the shots stage: the video hash plus detector and keyframe options.""" + if ctx.video_sha is None: + return None + if ctx.media is not None and ctx.media.width is None and ctx.media.height is None: + return None + options = ctx.settings.options_for("shots").model_copy( + update={"max_shots": ctx.max_shots, "min_scene_len": ctx.min_scene_len} + ) return { - "video_sha256": video_sha, + "video_sha256": ctx.video_sha, "detector": DETECTOR_NAME, "max_shots": options.max_shots, "min_scene_len": options.min_scene_len, @@ -216,14 +286,7 @@ def _shots_params(video_sha: str, options: ShotOptions) -> dict[str, Any]: } -def _describe_params( - shots_key: str | None, - options: DescribeOptions, - *, - transcript_key: str | None, - diarize_key: str | None, - diarize_applied: bool, -) -> dict[str, Any]: +def _describe_params(ctx: RunContext) -> dict[str, Any]: """Inputs of the describe stage: shots, transcript/speaker context and the VLM. The per-shot prompt embeds the speaker-labelled transcript slice, so changing the @@ -231,28 +294,17 @@ def _describe_params( endpoint participates too: the same bare model name can be served by different llama-server instances. """ + options = ctx.settings.options_for("describe") return { - "shots_key": shots_key, + "shots_key": ctx.keys.get("shots"), "vlm": options.vlm_model, - "transcript_key": transcript_key, - "diarize": {"key": diarize_key, "applied": diarize_applied}, + "transcript_key": ctx.keys.get("transcribe"), + "diarize": {"key": ctx.keys.get("diarize"), "applied": ctx.turns_applied}, "llama_server_url": options.llama_server_url, } -def _report_params( - *, - source: str, - probe_key: str, - audio_key: str | None, - transcribe_key: str | None, - diarize_key: str | None, - diarize_applied: bool, - shots_key: str | None, - describe_key: str | None, - describe_applied: bool, - options: ReportOptions, -) -> dict[str, Any]: +def _report_params(ctx: RunContext) -> dict[str, Any]: """Inputs of the report stage: every upstream key plus the synthesis value. ``applied`` flags record whether speaker labels and shot descriptions are part of @@ -260,19 +312,211 @@ def _report_params( other variant's cached report. ``source`` is the report's run-time identity, so two aliases of the same bytes keep distinct reports. """ + options = ctx.settings.options_for("report") return { - "source": source, - "probe": probe_key, - "audio": audio_key, - "transcribe": transcribe_key, - "diarize": {"key": diarize_key, "applied": diarize_applied}, - "shots": shots_key, - "describe": {"key": describe_key, "applied": describe_applied}, + "source": ctx.source, + "probe": ctx.keys.get("probe"), + "audio": ctx.keys.get("audio"), + "transcribe": ctx.keys.get("transcribe"), + "diarize": {"key": ctx.keys.get("diarize"), "applied": ctx.turns_applied}, + "shots": ctx.keys.get("shots"), + "describe": {"key": ctx.keys.get("describe"), "applied": ctx.descriptions_applied}, "synthesis": options.synthesis_model, "llama_server_url": options.llama_server_url, } +# --------------------------------------------------------------------------- # +# per-stage skip policy, validation and artifact application +# --------------------------------------------------------------------------- # +def _audio_skip_reason(ctx: RunContext) -> str | None: + if ctx.media is None or not ctx.media.has_audio: + return "source has no audio" + return None + + +def _transcribe_skip_reason(ctx: RunContext) -> str | None: + if ctx.media is None or not ctx.media.has_audio: + return "no audio" + if ctx.wav is None or not ctx.wav.is_file(): + return "no audio" + return None + + +def _diarize_skip_reason(ctx: RunContext) -> str | None: + if not ctx.settings.diarize: + return "disabled in settings" + if ctx.transcript is None or ctx.wav is None or not ctx.wav.is_file(): + return "no transcript" + return None + + +def _shots_skip_reason(ctx: RunContext) -> str | None: + if ctx.media is None or (ctx.media.width is None and ctx.media.height is None): + return "source has no video" + return None + + +def _describe_skip_reason(ctx: RunContext) -> str | None: + return None if ctx.shots else "no shots" + + +def _report_skip_reason(ctx: RunContext) -> str | None: + return None if ctx.transcript is not None or ctx.shots else "no transcript or shots" + + +def _audio_usable(artifact: _AudioArtifact) -> bool: + """True when the cached WAV path still points at a readable file.""" + return Path(artifact.path).is_file() + + +def _shots_usable(artifact: _ShotsArtifact) -> bool: + """True when every cached keyframe path still points at a readable file.""" + return all(shot.keyframe is None or Path(shot.keyframe).is_file() for shot in artifact.shots) + + +def _ingest_usable(artifact: IngestResult) -> bool: + """True when the cached download still passes the shared local-source policy.""" + try: + validate_local_source(artifact.path) + except (OSError, ValueError): + return False + return True + + +def _expect[ModelT: BaseModel](model: BaseModel, expected: type[ModelT]) -> ModelT: + """Narrow a cached artifact to its declared model type.""" + if not isinstance(model, expected): + raise TypeError(f"expected {expected.__name__}, got {type(model).__name__}") + return model + + +async def _refresh_audio_sha(ctx: RunContext) -> None: + """Hash an already extracted WAV so context stages can build their keys.""" + if ctx.audio_sha is not None: + return + wav = ctx.wav + if wav is None and ctx.video_sha is not None: + candidate = ctx.cache.audio_path(ctx.video_sha) + if candidate.is_file(): + wav = candidate + if wav is not None and wav.is_file(): + ctx.wav = wav + ctx.audio_sha = await asyncio.to_thread(ctx.cache.source_hash, wav) + + +def _facts_with_ingest_metadata(facts: MediaFacts, ingested: Any | None) -> MediaFacts: + """Merge URL provenance (yt-dlp title/metadata) into this run's facts. + + The probe artifact stays content-only and cached; the merged value is only + passed through this run. Re-validating the facts makes the model's content-only + validator drop any local paths carried by yt-dlp metadata. + """ + if ingested is None: + return facts + extra = dict(facts.extra) + info = getattr(ingested, "info", None) + if isinstance(info, dict) and info: + extra["yt_dlp"] = dict(info) + title = getattr(ingested, "title", None) + if isinstance(title, str) and title.strip(): + extra["title"] = title.strip() + if extra == facts.extra: + return facts + return MediaFacts.model_validate({**facts.model_dump(), "extra": extra}) + + +async def _apply_ingest(ctx: RunContext, artifact: BaseModel) -> None: + result = _expect(artifact, IngestResult) + local_path = Path(result.path).expanduser() + ctx.ingest = result + ctx.local_path = local_path + ctx.video_sha = await asyncio.to_thread(ctx.cache.source_hash, local_path) + ctx.workdir = ctx.cache.source_dir(ctx.video_sha) + await _refresh_audio_sha(ctx) + ctx.notify(f"ingest: ready ({local_path.name})") + + +async def _apply_probe(ctx: RunContext, artifact: BaseModel) -> None: + facts = _expect(artifact, MediaFacts) + ctx.media = _facts_with_ingest_metadata(facts, ctx.ingest) + + +async def _apply_audio(ctx: RunContext, artifact: BaseModel) -> None: + audio = _expect(artifact, _AudioArtifact) + ctx.wav = Path(audio.path) + if ctx.wav.is_file(): + ctx.audio_sha = await asyncio.to_thread(ctx.cache.source_hash, ctx.wav) + + +async def _apply_transcribe(ctx: RunContext, artifact: BaseModel) -> None: + ctx.transcript = _expect(artifact, Transcript) + + +async def _apply_diarize(ctx: RunContext, artifact: BaseModel) -> None: + turns_artifact = _expect(artifact, _TurnsArtifact) + turns = turns_artifact.turns + ctx.turns_applied = bool(turns) + if turns and ctx.transcript is not None: + ctx.transcript = ctx.pipeline._apply_speakers(ctx.transcript, turns) + + +async def _apply_shots(ctx: RunContext, artifact: BaseModel) -> None: + ctx.shots = list(_expect(artifact, _ShotsArtifact).shots) + + +async def _apply_describe(ctx: RunContext, artifact: BaseModel) -> None: + described = _expect(artifact, _ShotsArtifact) + ctx.shots = list(described.shots) + ctx.descriptions_applied = any(shot.description is not None for shot in described.shots) + + +async def _apply_report(ctx: RunContext, artifact: BaseModel) -> None: + ctx.report = _expect(artifact, VideoReport) + + +# --------------------------------------------------------------------------- # +# want-closure resolution (pure: the graph comes from STAGES_TABLE) +# --------------------------------------------------------------------------- # +def _source_applies(name: str, source: str) -> bool: + applies = STAGES_TABLE[name].applies + return applies is None or applies(source) + + +def _resolve_want(wanted: Collection[str], source: str) -> tuple[frozenset[str], frozenset[str]]: + """Resolve wanted stage names into ``(hard, context)`` sets. + + ``hard`` stages run (or hit their cache); ``context`` stages are only loaded from + cache because a needed stage lists them in ``load_context``. Prerequisites of + context stages are deliberately not pulled in: loading an artifact must not start + an expensive upstream stage. + """ + hard = {name for name in wanted if _source_applies(name, source)} + context: set[str] = set() + while True: + previous = set(context) + for name in tuple(hard) + tuple(context): + for dependency in STAGES_TABLE[name].load_context: + if _source_applies(dependency, source): + context.add(dependency) + + expanded = False + for name in tuple(hard): + for prereq in STAGES_TABLE[name].prereqs: + if not _source_applies(prereq, source): + continue + if prereq in context and prereq not in wanted: + continue + if prereq not in hard: + hard.add(prereq) + expanded = True + if not expanded and context == previous: + break + + context -= hard + return frozenset(hard), frozenset(context) + + class Pipeline: """Run the analysis stages for one source, reusing cached artifacts. @@ -343,13 +587,13 @@ class Pipeline: force: bool = False, progress: ProgressCallback | None = None, ) -> Artifacts: - """Run the pipeline for ``source`` and return the assembled artifacts. + """Run the wanted stage closure for ``source`` and return the artifacts. Args: source: local media path or ``http(s)`` URL. - want: stages whose results are needed; defaults to every stage in - :data:`STAGE_ORDER`. Prerequisites run as needed, so a bare - ``{"transcribe"}`` still probes and extracts audio. + want: stages whose results are needed; defaults to :data:`STAGE_ORDER`. + Prerequisites run as needed, so a bare ``{"transcribe"}`` still probes + and extracts audio. force: re-run the *wanted* stages even when their cache entry exists and drop the cache entries of every downstream stage. progress: called with a short ``": "`` message before each @@ -369,299 +613,130 @@ class Pipeline: original = source.strip() if not original: raise ValueError("source must not be empty") - wanted = self._normalise_want(want) + wanted = self._normalise_want(want) or frozenset({"probe"}) notify = progress if progress is not None else _ignore_progress cache = StageCache(self.settings.cache_dir) - - # --- ingest (URL sources only) --------------------------------- - local_path, ingested = await self._resolve_source(original, cache=cache, notify=notify) - video_sha = await asyncio.to_thread(cache.source_hash, local_path) - workdir = cache.source_dir(video_sha) - logger.info("pipeline source=%s sha256=%s workdir=%s", original, video_sha[:16], workdir) - - # --- probe ------------------------------------------------------ - probe_key = cache.stage_key("probe", _probe_params(video_sha)) - media, _ = await self._execute_stage( - "probe", - cache=cache, - source_sha=video_sha, - key=probe_key, - model_type=MediaFacts, - runner=lambda: self._stage("probe")(local_path), - notify=notify, - forced=self._forced("probe", wanted, force), - ) - ref = MediaRef(source=original, local_path=local_path) - # URL provenance (yt-dlp title/metadata) is run-time input, not probe content; - # fold it into this run's facts without touching the cached probe artifact. - media = self._facts_with_ingest_metadata(media, ingested) - - # --- audio ------------------------------------------------------ - wav = cache.audio_path(video_sha) - audio_key = cache.stage_key("audio", _audio_params(video_sha)) - audio_wanted = bool(wanted & {"audio", "transcribe", "diarize"}) - audio_ready = False - if not media.has_audio: - notify("audio: skipped (source has no audio)") - elif audio_wanted: - audio, _ = await self._execute_stage( - "audio", - cache=cache, - source_sha=video_sha, - key=audio_key, - model_type=_AudioArtifact, - runner=lambda: self._run_audio(local_path, workdir), - notify=notify, - forced=self._forced("audio", wanted, force), - validate=lambda item: item.path.is_file(), - ) - wav = audio.path - audio_ready = True - else: - notify("audio: skipped (not requested)") - audio_ready = wav.is_file() - - # --- transcribe ------------------------------------------------- - transcribe_wanted = "transcribe" in wanted or "diarize" in wanted - context_wanted = bool(wanted & {"describe", "report"}) - audio_sha: str | None = None - transcribe_key: str | None = None - transcript: Transcript | None = None - if not audio_ready: - reason = "no audio" if not media.has_audio else "not requested" - notify(f"transcribe: skipped ({reason})") - else: - audio_sha = await asyncio.to_thread(cache.source_hash, wav) - stt_options = self.settings.options_for("stt") - from .transcribe import get_transcriber - - transcriber = get_transcriber(stt_options) - transcribe_key = cache.stage_key( - "transcribe", - _transcribe_params(audio_sha, stt_options, transcriber.identity()), - ) - if transcribe_wanted: - transcript, _ = await self._execute_stage( - "transcribe", - cache=cache, - source_sha=video_sha, - key=transcribe_key, - model_type=Transcript, - runner=lambda: self._run_transcribe( - wav, options=stt_options, transcriber=transcriber - ), - notify=notify, - forced=self._forced("transcribe", wanted, force), - ) - elif context_wanted: - cached_transcript = self._load_cached( - cache, video_sha, "transcribe", transcribe_key, Transcript - ) - if cached_transcript is not None: - transcript = cached_transcript - notify("transcribe: cached (context)") - else: - notify("transcribe: skipped (not requested)") - else: - notify("transcribe: skipped (not requested)") - - # --- diarize (speaker turns applied to the transcript) ---------- - diarize_key: str | None = None - diarizer: Diarizer | None = None - diarize_options = self.settings.options_for("diarize") - if audio_sha is not None: - from .diarize import get_diarizer - - diarizer = get_diarizer(diarize_options) - diarize_key = cache.stage_key( - "diarize", - _diarize_params(audio_sha, diarizer.cache_params()), - ) - diarize_applied = False - if "diarize" in wanted: - if not self.settings.diarize: - notify("diarize: skipped (disabled in settings)") - elif transcript is None or audio_sha is None or not wav.is_file(): - notify("diarize: skipped (no transcript)") - else: - turns_artifact, _ = await self._execute_stage( - "diarize", - cache=cache, - source_sha=video_sha, - key=diarize_key, - model_type=_TurnsArtifact, - runner=lambda: self._run_diarize( - wav, options=diarize_options, diarizer=diarizer - ), - notify=notify, - forced=self._forced("diarize", wanted, force), - ) - transcript = self._apply_speakers(transcript, turns_artifact.turns) - diarize_applied = bool(turns_artifact.turns) - else: - # A report/description run can reuse already cached turns for free; the - # diarization backend itself only ever runs when explicitly requested. - cached_turns = None - reuse_turns = ( - self.settings.diarize - and transcript is not None - and diarize_key is not None - and bool(wanted & {"describe", "report"}) - ) - if reuse_turns: - cached_turns = self._load_cached( - cache, video_sha, "diarize", diarize_key, _TurnsArtifact - ) - if cached_turns is not None and cached_turns.turns and transcript is not None: - transcript = self._apply_speakers(transcript, cached_turns.turns) - diarize_applied = True - notify("diarize: cached (context)") - else: - notify("diarize: skipped (not requested)") - - # --- shots ------------------------------------------------------ - has_video = media.width is not None or media.height is not None - shots_key: str | None = None - shots_options = self.settings.options_for("shots").model_copy( - update={"max_shots": self.max_shots, "min_scene_len": self.min_scene_len} - ) - if has_video: - shots_key = cache.stage_key( - "shots", - _shots_params(video_sha, shots_options), - ) - shots_wanted = "shots" in wanted or "describe" in wanted - shots: list[Shot] = [] - if not has_video: - notify("shots: skipped (source has no video)") - elif shots_wanted: - shots_artifact, _ = await self._execute_stage( - "shots", - cache=cache, - source_sha=video_sha, - key=shots_key, - model_type=_ShotsArtifact, - runner=lambda: self._run_shots( - local_path, media, workdir, shots_key, options=shots_options - ), - notify=notify, - forced=self._forced("shots", wanted, force), - validate=self._shots_usable, - ) - shots = shots_artifact.shots - elif "report" in wanted: - cached_shots = self._load_cached(cache, video_sha, "shots", shots_key, _ShotsArtifact) - if cached_shots is not None and self._shots_usable(cached_shots): - shots = cached_shots.shots - notify("shots: cached (context)") - else: - notify("shots: skipped (not requested)") - else: - notify("shots: skipped (not requested)") - - # --- describe --------------------------------------------------- - describe_options = self.settings.options_for("describe") - describe_key = cache.stage_key( - "describe", - _describe_params( - shots_key, - describe_options, - transcript_key=transcribe_key, - diarize_key=diarize_key, - diarize_applied=diarize_applied, - ), - ) - describe_applied = False - if "describe" in wanted: - if not shots: - notify("describe: skipped (no shots)") - else: - described, _ = await self._execute_stage( - "describe", - cache=cache, - source_sha=video_sha, - key=describe_key, - model_type=_ShotsArtifact, - runner=lambda: self._run_describe(shots, transcript, options=describe_options), - notify=notify, - forced=self._forced("describe", wanted, force), - validate=self._shots_usable, - ) - shots = described.shots - describe_applied = any(shot.description is not None for shot in shots) - else: - # Reuse cached descriptions as report material without re-running the VLM. - described = None - if shots and "report" in wanted: - described = self._load_cached( - cache, video_sha, "describe", describe_key, _ShotsArtifact - ) - if described is not None and not self._shots_usable(described): - logger.warning("cached descriptions point at missing keyframes; ignoring them") - described = None - if described is None: - notify("describe: skipped (not requested)") - else: - shots = described.shots - describe_applied = any(shot.description is not None for shot in shots) - notify("describe: cached (context)") - - # PLAN ยง4: every shot carries the words spoken during it. Fill it here (the - # first point where shots and the speaker-attributed transcript coexist) and - # again inside describe_shots for callers of the vision stage directly. - self._populate_transcript_slices(shots, transcript) - - # --- report ----------------------------------------------------- - report_options = self.settings.options_for("report") - report_key = cache.stage_key( - "report", - _report_params( - source=original, - probe_key=probe_key, - audio_key=audio_key, - transcribe_key=transcribe_key, - diarize_key=diarize_key, - diarize_applied=diarize_applied, - shots_key=shots_key, - describe_key=describe_key, - describe_applied=describe_applied, - options=report_options, - ), - ) - report: VideoReport | None = None - if "report" not in wanted: - notify("report: skipped (not requested)") - elif transcript is None and not shots: - notify("report: skipped (no transcript or shots)") - else: - report, _ = await self._execute_stage( - "report", - cache=cache, - source_sha=video_sha, - key=report_key, - model_type=VideoReport, - runner=lambda: self._run_report( - shots, transcript, media, ref.source, options=report_options - ), - notify=notify, - forced=self._forced("report", wanted, force), - ) - - artifacts = Artifacts( + ctx = RunContext( + pipeline=self, source=original, - workdir=workdir, - media=media, - ref=ref, - transcript=transcript, - shots=shots, - report=report, + settings=self.settings, + cache=cache, + notify=notify, + wanted=wanted, + force=force, + ingest_quality=self.ingest_quality, + max_shots=self.max_shots, + min_scene_len=self.min_scene_len, ) - self._persist_artifacts(cache, video_sha, artifacts) + + await self._prepare_context(ctx) + + hard, context = _resolve_want(wanted, original) + for name in _ALL_STAGE_ORDER: + spec = STAGES_TABLE[name] + if name not in hard and name not in context: + if not (name == "ingest" and ctx.local_path is not None): + notify(f"{name}: skipped (not requested)") + continue + params = spec.key_params(ctx) + key = None if params is None else ctx.cache.stage_key(name, params) + ctx.keys[name] = key + reason = spec.skip_reason(ctx) if spec.skip_reason is not None else None + if reason is not None: + notify(f"{name}: skipped ({reason})") + elif name in hard: + await self._execute_spec(spec, ctx, key) + else: + await self._load_context_spec(spec, ctx, key) + + return self._assemble_artifacts(ctx) + + # ------------------------------------------------------------------ # + # scheduler helpers + # ------------------------------------------------------------------ # + async def _prepare_context(self, ctx: RunContext) -> None: + """Validate the source and resolve local content state before scheduling.""" + scheme = urlparse(ctx.source).scheme.lower() + if scheme in {"http", "https"}: + return + if scheme: + raise ValueError( + f"unsupported URL scheme {scheme + ':'!r} in {ctx.source!r}; pass a local " + "file path or an http(s) URL" + ) + if ctx.wanted == {"ingest"}: + raise ValueError( + "ingest only applies to http(s) URL sources; local paths are used directly" + ) + ctx.local_path = validate_local_source(ctx.source) + ctx.notify("ingest: local file") + ctx.video_sha = await asyncio.to_thread(ctx.cache.source_hash, ctx.local_path) + ctx.workdir = ctx.cache.source_dir(ctx.video_sha) + await _refresh_audio_sha(ctx) + + def _assemble_artifacts(self, ctx: RunContext) -> Artifacts: + """Attach run-time context and persist the final artifact mirror.""" + self._populate_transcript_slices(ctx.shots, ctx.transcript) + if ctx.video_sha is None or ctx.local_path is None or ctx.workdir is None: + raise ValueError(f"source {ctx.source!r} did not resolve to a local media file") + artifacts = Artifacts( + source=ctx.source, + workdir=ctx.workdir, + media=ctx.media, + ref=MediaRef(source=ctx.source, local_path=ctx.local_path), + transcript=ctx.transcript, + shots=ctx.shots, + report=ctx.report, + ) + self._persist_artifacts(ctx.cache, ctx.video_sha, artifacts) return artifacts - # ------------------------------------------------------------------ # - # orchestration helpers - # ------------------------------------------------------------------ # + async def _execute_spec(self, spec: StageSpec, ctx: RunContext, key: str | None) -> None: + """Run one hard stage through the shared load -> miss -> run -> save policy.""" + if key is None: + raise ValueError(f"stage {spec.name!r} has no cache key; its inputs are unavailable") + forced = self._forced(spec.name, ctx.wanted, ctx.force) + start = f"ingest: fetching {ctx.source}" if spec.name == "ingest" else None + value, executed = await self._execute_stage( + spec.name, + cache=ctx.cache, + source_sha=ctx.namespace(spec.name, key), + key=key, + model_type=spec.model, + runner=lambda: spec.runner(ctx), + notify=ctx.notify, + forced=forced, + validate=spec.validate, + start_message=start, + ) + if spec.name == "ingest" and not executed and isinstance(value, IngestResult): + value = value.model_copy(update={"downloaded": False}) + if spec.apply is not None: + await spec.apply(ctx, value) + if spec.name == "ingest" and forced and ctx.video_sha is not None: + # The ingest artifact lives under the URL/quality key; downstream artifacts + # live under the resolved content hash, so invalidate that namespace too. + self._invalidate_downstream(ctx.cache, ctx.video_sha, spec.name) + + async def _load_context_spec(self, spec: StageSpec, ctx: RunContext, key: str | None) -> None: + """Load a cached context artifact without ever running the stage.""" + if not spec.context_cache or key is None: + ctx.notify(f"{spec.name}: skipped (not requested)") + return + value = self._load_cached( + ctx.cache, + ctx.namespace(spec.name, key), + spec.name, + key, + spec.model, + ) + if value is None or (spec.validate is not None and not spec.validate(value)): + ctx.notify(f"{spec.name}: skipped (not requested)") + return + if spec.apply is not None: + await spec.apply(ctx, value) + ctx.notify(f"{spec.name}: cached (context)") + @staticmethod def _normalise_want(want: Collection[str] | None) -> frozenset[str]: """Validate ``want`` and return it as a frozenset of stage names.""" @@ -687,13 +762,6 @@ class Pipeline: """Return the injected callable for ``name``, else the real implementation.""" return self._injected.get(name) or self._real[name] - @staticmethod - def _shots_usable(artifact: _ShotsArtifact) -> bool: - """True when every cached keyframe path still points at a readable file.""" - return all( - shot.keyframe is None or Path(shot.keyframe).is_file() for shot in artifact.shots - ) - @staticmethod def _populate_transcript_slices(shots: list[Shot], transcript: Transcript | None) -> None: """Fill ``Shot.transcript_slice`` with the words spoken during each shot.""" @@ -705,55 +773,11 @@ class Pipeline: shot.transcript_slice = transcript_slice_for(shot, transcript) @staticmethod - def _facts_with_ingest_metadata(facts: MediaFacts, ingested: Any | None) -> MediaFacts: - """Merge URL provenance (yt-dlp title/metadata) into this run's facts. + def _apply_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript: + """Attribute ``transcript`` words/segments to ``turns`` (pure, cheap).""" + from .diarize import attribute_speakers - The probe artifact stays content-only and cached; the merged value is only - passed through this run. Re-validating the facts makes the model's - content-only validator drop any local paths carried by yt-dlp metadata. - """ - if ingested is None: - return facts - extra = dict(facts.extra) - info = getattr(ingested, "info", None) - if isinstance(info, dict) and info: - extra["yt_dlp"] = dict(info) - title = getattr(ingested, "title", None) - if isinstance(title, str) and title.strip(): - extra["title"] = title.strip() - if extra == facts.extra: - return facts - return MediaFacts.model_validate({**facts.model_dump(), "extra": extra}) - - async def _resolve_source( - self, source: str, *, cache: StageCache, notify: ProgressCallback - ) -> tuple[Path, Any | None]: - """Return the local media file for ``source`` plus its ingest result (URLs only).""" - scheme = urlparse(source).scheme.lower() - if scheme in {"http", "https"}: - notify(f"ingest: fetching {source}") - ingested = await self._stage("ingest")( - source, cache_dir=cache.cache_dir, quality=self.ingest_quality - ) - local_path = Path(ingested.path).expanduser() - if not local_path.is_file(): - raise RuntimeError( - f"ingest stage reported {local_path} for {source} but no such file exists" - ) - notify(f"ingest: ready ({local_path.name})") - return local_path, ingested - if scheme: - raise ValueError( - f"unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file " - "path or an http(s) URL" - ) - notify("ingest: local file") - local_path = Path(source).expanduser() - if not local_path.exists(): - raise ValueError(f"Local media file not found: {local_path}") - if not local_path.is_file(): - raise ValueError(f"Local path is not a regular file: {local_path}") - return local_path.resolve(), None + return attribute_speakers(transcript, turns) async def _execute_stage( self, @@ -767,6 +791,7 @@ class Pipeline: notify: ProgressCallback, forced: bool, validate: Callable[[ModelT], bool] | None = None, + start_message: str | None = None, ) -> tuple[ModelT, bool]: """Load a stage artifact from the cache, or run the stage and store it. @@ -785,7 +810,7 @@ class Pipeline: async def run_stage() -> ModelT: nonlocal executed executed = True - notify(f"{stage}: running") + notify(start_message or f"{stage}: running") return await runner() value = await cache.cached_run( @@ -836,98 +861,107 @@ class Pipeline: except OSError as exc: logger.warning("could not write %s: %s", path, exc) - @staticmethod - def _apply_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript: - """Attribute ``transcript`` words/segments to ``turns`` (pure, cheap).""" - from .diarize import attribute_speakers - - return attribute_speakers(transcript, turns) - # ------------------------------------------------------------------ # # stage runners (wrap an injected or real callable into a cache artifact) # ------------------------------------------------------------------ # - async def _run_audio(self, path: Path, workdir: Path) -> _AudioArtifact: + async def _run_ingest(self, ctx: RunContext) -> IngestResult: + """Resolve/download the source through the injectable ingest stage.""" + if "ingest" in self._injected: + return await self._stage("ingest")( + ctx.source, cache_dir=ctx.cache.cache_dir, quality=ctx.ingest_quality + ) + from .ingest import fetch + + return await fetch( + ctx.source, + cache_dir=ctx.cache.cache_dir, + quality=ctx.ingest_quality, + force=self._forced("ingest", ctx.wanted, ctx.force), + ) + + async def _run_probe(self, ctx: RunContext) -> MediaFacts: + """Probe the resolved local file.""" + if ctx.local_path is None: # pragma: no cover - guarded by the ingest stage + raise RuntimeError("probe stage has no local media path") + return await self._stage("probe")(ctx.local_path) + + async def _run_audio(self, ctx: RunContext) -> _AudioArtifact: """Run the audio stage and wrap the returned WAV path in a cache artifact.""" - wav = await self._stage("audio")(path, workdir) + if ctx.local_path is None or ctx.workdir is None: # pragma: no cover + raise RuntimeError("audio stage has no resolved source") + wav = await self._stage("audio")(ctx.local_path, ctx.workdir) return _AudioArtifact(path=Path(wav)) - async def _run_transcribe( - self, - wav: Path, - *, - options: SttOptions, - transcriber: Transcriber | None = None, - ) -> Transcript: - """Run the transcribe stage for ``wav`` with its frozen option value.""" + async def _run_transcribe(self, ctx: RunContext) -> Transcript: + """Run the transcribe stage for the extracted WAV with its frozen options.""" + if ctx.wav is None: + raise RuntimeError("transcribe stage has no audio file") + options = ctx.settings.options_for("stt") if "transcribe" in self._injected: - return await self._stage("transcribe")(wav, options=options) + return await self._stage("transcribe")(ctx.wav, options=options) from .transcribe import get_transcriber - active = transcriber or get_transcriber(options) - return await active.transcribe(wav, language=options.language) + return await get_transcriber(options).transcribe(ctx.wav, language=options.language) - async def _run_diarize( - self, - wav: Path, - *, - options: DiarizeOptions, - diarizer: Diarizer | None = None, - ) -> _TurnsArtifact: + async def _run_diarize(self, ctx: RunContext) -> _TurnsArtifact: """Run the diarize stage and wrap the speaker turns in a cache artifact.""" + if ctx.wav is None: + raise RuntimeError("diarize stage has no audio file") + options = ctx.settings.options_for("diarize") if "diarize" in self._injected: - turns = await self._stage("diarize")(wav, options=options) + turns = await self._stage("diarize")(ctx.wav, options=options) else: from .diarize import get_diarizer - active = diarizer or get_diarizer(options) - turns = await active.diarize(wav, options) + turns = await get_diarizer(options).diarize(ctx.wav, options) return _TurnsArtifact(turns=list(turns)) - async def _run_shots( - self, - path: Path, - info: MediaFacts, - workdir: Path, - shots_key: str | None, - *, - options: ShotOptions, - ) -> _ShotsArtifact: + async def _run_shots(self, ctx: RunContext) -> _ShotsArtifact: """Run the shots stage and wrap the shot list in a cache artifact. Real keyframes are namespaced by the shots cache key so runs with different ``--max-shots``/dedup options can never overwrite each other's JPEGs. """ + if ctx.local_path is None or ctx.workdir is None or ctx.media is None: # pragma: no cover + raise RuntimeError("shots stage has no resolved source") + options = ctx.settings.options_for("shots").model_copy( + update={"max_shots": ctx.max_shots, "min_scene_len": ctx.min_scene_len} + ) + namespace = ctx.keys.get("shots") if "shots" in self._injected: - shots = await self._stage("shots")(path, info, workdir=workdir, options=options) + shots = await self._stage("shots")( + ctx.local_path, ctx.media, workdir=ctx.workdir, options=options + ) else: shots = await self._real_shots( - path, info, workdir=workdir, options=options, namespace=shots_key + ctx.local_path, + ctx.media, + workdir=ctx.workdir, + options=options, + namespace=namespace, ) return _ShotsArtifact(shots=list(shots)) - async def _run_describe( - self, shots: list[Shot], transcript: Transcript | None, *, options: DescribeOptions - ) -> _ShotsArtifact: + async def _run_describe(self, ctx: RunContext) -> _ShotsArtifact: """Run the describe stage and wrap the described shots in a cache artifact.""" - described = await self._stage("describe")(shots, transcript, options=options) + options = ctx.settings.options_for("describe") + described = await self._stage("describe")(ctx.shots, ctx.transcript, options=options) return _ShotsArtifact(shots=list(described)) - async def _run_report( - self, - shots: list[Shot], - transcript: Transcript | None, - info: MediaFacts, - source: str, - *, - options: ReportOptions, - ) -> VideoReport: + async def _run_report(self, ctx: RunContext) -> VideoReport: """Run the report stage for the available material and run-time source.""" - return await self._stage("report")(shots, transcript, info, source=source, options=options) + if ctx.media is None: # pragma: no cover - probe is a hard prerequisite + raise RuntimeError("report stage has no media facts") + self._populate_transcript_slices(ctx.shots, ctx.transcript) + options = ctx.settings.options_for("report") + return await self._stage("report")( + ctx.shots, ctx.transcript, ctx.media, source=ctx.source, options=options + ) # ------------------------------------------------------------------ # # real stage implementations (heavy imports stay inside the methods) # ------------------------------------------------------------------ # - async def _real_ingest(self, source: str, *, cache_dir: Path, quality: int) -> Any: + async def _real_ingest(self, source: str, *, cache_dir: Path, quality: int) -> IngestResult: """Download ``source`` with yt-dlp (``video_analyse.ingest.fetch``).""" from .ingest import fetch @@ -1005,3 +1039,122 @@ class Pipeline: from .synthesis import synthesise_report return await synthesise_report(shots, transcript, info, source=source, options=options) + + +# --------------------------------------------------------------------------- # +# the single encoding of the stage graph +# --------------------------------------------------------------------------- # +STAGES_TABLE: dict[str, StageSpec] = { + "ingest": StageSpec( + name="ingest", + prereqs=(), + applies=_is_url_source, + key_params=_ingest_params, + model=IngestResult, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_ingest(ctx), + apply=_apply_ingest, + validate=_ingest_usable, + ), + "probe": StageSpec( + name="probe", + prereqs=("ingest",), + key_params=_probe_params, + model=MediaFacts, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_probe(ctx), + apply=_apply_probe, + ), + "audio": StageSpec( + name="audio", + prereqs=("probe",), + key_params=_audio_params, + model=_AudioArtifact, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_audio(ctx), + apply=_apply_audio, + validate=_audio_usable, + skip_reason=_audio_skip_reason, + context_cache=False, + ), + "transcribe": StageSpec( + name="transcribe", + prereqs=("audio",), + key_params=_transcribe_params, + model=Transcript, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_transcribe(ctx), + apply=_apply_transcribe, + skip_reason=_transcribe_skip_reason, + ), + "diarize": StageSpec( + name="diarize", + prereqs=("transcribe",), + key_params=_diarize_params, + model=_TurnsArtifact, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_diarize(ctx), + apply=_apply_diarize, + skip_reason=_diarize_skip_reason, + ), + "shots": StageSpec( + name="shots", + prereqs=("probe",), + key_params=_shots_params, + model=_ShotsArtifact, + load_context=(), + runner=lambda ctx: ctx.pipeline._run_shots(ctx), + apply=_apply_shots, + validate=_shots_usable, + skip_reason=_shots_skip_reason, + ), + "describe": StageSpec( + name="describe", + prereqs=("probe", "shots", "transcribe", "diarize"), + key_params=_describe_params, + model=_ShotsArtifact, + load_context=("transcribe", "diarize"), + runner=lambda ctx: ctx.pipeline._run_describe(ctx), + apply=_apply_describe, + validate=_shots_usable, + skip_reason=_describe_skip_reason, + ), + "report": StageSpec( + name="report", + prereqs=("probe", "audio", "transcribe", "diarize", "shots", "describe"), + key_params=_report_params, + model=VideoReport, + load_context=("audio", "transcribe", "diarize", "shots", "describe"), + runner=lambda ctx: ctx.pipeline._run_report(ctx), + apply=_apply_report, + skip_reason=_report_skip_reason, + ), +} + +#: Every name accepted in ``want`` and in the injectable ``stages`` mapping. +STAGES: frozenset[str] = frozenset(STAGES_TABLE) + + +def _derive_downstream() -> dict[str, tuple[str, ...]]: + """Transitive closure of the reversed prerequisite graph, computed once.""" + direct: dict[str, set[str]] = {name: set() for name in STAGES_TABLE} + for name, spec in STAGES_TABLE.items(): + for prereq in spec.prereqs: + direct[prereq].add(name) + + downstream: dict[str, tuple[str, ...]] = {} + for name in STAGES_TABLE: + seen: set[str] = set() + stack = list(direct[name]) + while stack: + dependent = stack.pop() + if dependent in seen: + continue + seen.add(dependent) + stack.extend(direct[dependent]) + downstream[name] = tuple(stage for stage in _ALL_STAGE_ORDER if stage in seen) + return downstream + + +#: Cache entries to drop when a stage is re-run with ``force=True`` (derived, never edited). +_DOWNSTREAM: dict[str, tuple[str, ...]] = _derive_downstream() diff --git a/tests/test_cache.py b/tests/test_cache.py index 8342f8b..07024fe 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -15,6 +15,7 @@ import pytest from video_analyse import cache as cache_module from video_analyse.cache import StageCache +from video_analyse.ingest import IngestResult 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"] +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( cache: StageCache, tmp_path: Path, sample_media: MediaFacts ) -> None: diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 875e264..9bc28c3 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -6,14 +6,14 @@ tests never open a socket and never download anything. from __future__ import annotations -import re from pathlib import Path from typing import Any, ClassVar import pytest 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" 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) - slug = f"{_safe_dir_name(URL)}-q720" - expected_dir = (cache_dir / "downloads" / slug).resolve() + cache = StageCache(cache_dir) + key = cache.stage_key("ingest", ingest_key_params(URL, 720)) + expected_dir = cache.source_dir(key).resolve() assert result.downloaded is True assert result.title == "My Clip" 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.name == DOWNLOAD_FILE_NAME 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 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} assert len(home_dirs) == 1 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 first.path == second.path 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( fake_ydl: type[_FakeYoutubeDL], tmp_path: Path ) -> None: @@ -199,19 +217,13 @@ async def test_fetch_maps_download_errors_to_actionable_runtime_error( assert excinfo.value.__cause__ is not None -def test_safe_dir_name_is_stable_filesystem_safe_and_url_specific() -> None: - slug = _safe_dir_name(URL) - assert slug == _safe_dir_name(URL) - assert re.fullmatch(r"[A-Za-z0-9._-]+", slug) - assert "/" not in slug and "?" not in slug and "&" not in slug - assert len(slug) <= 75 - 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/")) +async def test_fetch_never_puts_url_credentials_in_the_cache_path( + fake_ydl: type[_FakeYoutubeDL], tmp_path: Path +) -> None: + result = await fetch( + "https://alice:s3cr3t@example.invalid/watch?v=abc", + cache_dir=tmp_path / "cache", + ) - -def test_safe_dir_name_never_contains_url_credentials() -> None: - 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") + assert "s3cr3t" not in str(result.path) + assert "alice" not in str(result.path) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 2954842..272ff26 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -18,7 +18,7 @@ import pytest from video_analyse.cache import StageCache from video_analyse.config import Settings 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.models import ( Artifacts, @@ -32,7 +32,15 @@ from video_analyse.models import ( VideoReport, 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.transcribe import SttOptions 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() await Pipeline(_settings(tmp_path, diarize=False), fakes.mapping()).run(str(source)) 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) diff --git a/tests/test_transcribe.py b/tests/test_transcribe.py index d9ca4b5..f2a8ee1 100644 --- a/tests/test_transcribe.py +++ b/tests/test_transcribe.py @@ -343,11 +343,22 @@ def test_local_readiness_follows_the_huggingface_cache_without_downloading( 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: options = _stt_options(stt_backend="whisper", whisper_model="tiny") identity = get_transcriber(options).identity() - params = _transcribe_params("a" * 64, options, identity) + params = _transcribe_cache_params(options) assert params["backend"] == identity.backend 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 cache = StageCache(tmp_path) - parakeet_key = cache.stage_key( - "transcribe", _transcribe_params("a" * 64, parakeet_options, parakeet.identity()) - ) - stub_key = cache.stage_key( - "transcribe", _transcribe_params("a" * 64, stub_options, stub.identity()) - ) + parakeet_key = cache.stage_key("transcribe", _transcribe_cache_params(parakeet_options)) + stub_key = cache.stage_key("transcribe", _transcribe_cache_params(stub_options)) assert stub_key != parakeet_key