models+pipeline: split MediaFacts from the run-time MediaRef

MediaInfo conflated content facts with a run-time handle, so byte-identical aliases could not share a probe artifact and every cache read needed a path-rebasing sweep.

- models: replace MediaInfo in one sweep with content-only MediaFacts and run-time MediaRef; Artifacts gains ref; MediaFacts.extra drops local filename/path keys on construction
- media.probe returns MediaFacts with no path/source and no ffprobe filename
- pipeline: probe params are the content hash only; attach MediaRef on every run; delete _rebase_media/_rebase_report; keep yt-dlp title/metadata as sanitized run-time facts for reports
- synthesis: prompts and metadata consume facts only; report assembly takes the run-time source; report metadata carries no local path
- cli/mcp: compose facts + ref where a local path or source display is needed
- CONTRACTS sections 3-4, README and PLAN reference the new shapes; tests cover the alias cache hit, facts round-trip and path-free report metadata

Cache migration: dropping source from the probe params changes probe keys, so existing probe entries are a one-time invalidation (one cheap ffprobe call per source).

Closes #7
This commit is contained in:
alex committed 2026-11-24 00:04:10 +00:00
1 parent c58c0e4f42
commit 83a4785524
15 files changed
+409 -282

No files matched your search

+18 -9
View File
@@ -91,7 +91,7 @@ ordering in the `Pipeline`). Keyframe JPEGs go to `workdir/keyframes/`, audio to
```
ingest.py: async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestResult
IngestResult(BaseModel): path: Path; info: dict[str, Any] = {}; downloaded: bool; title: str | None = None
media.py: async def probe(path: Path) -> MediaInfo
media.py: async def probe(path: Path) -> MediaFacts
media.py: async def extract_audio(path: Path, workdir: Path) -> Path # 16 kHz mono s16le WAV at workdir/audio.wav
media.py: class ShotOptions(BaseModel) # frozen value: max_shots=64, min_scene_len=0.6, sampling="adaptive", sampling_interval_seconds=15.0, subdivide_after_seconds=20.0
media.py: def plan_shots(duration: float, cuts: list[float], curve: list[tuple[float, float]] | None, *, options: ShotOptions) -> list[Shot] # pure: no Path/I/O; global budget applied after subdivision
@@ -113,7 +113,7 @@ vision.py: class DescribeOptions(BaseModel) # frozen value: vlm_model, llama_se
vision.py: async def describe_shots(shots: list[Shot], transcript: Transcript | None, *, options: DescribeOptions) -> list[Shot] # pydantic-ai agent, output_type=ShotDescription, one call per shot, fills .description
vision.py: async def llama_server_up(settings: Settings) -> bool
synthesis.py: class ReportOptions(BaseModel) # frozen value: synthesis_model, llama_server_url, ollama_base_url, ollama_api_key
synthesis.py: async def synthesise_report(shots: list[Shot], transcript: Transcript | None, info: MediaInfo, *, options: ReportOptions) -> VideoReport # agent outputs ReportCore, code assembles VideoReport
synthesis.py: async def synthesise_report(shots: list[Shot], transcript: Transcript | None, info: MediaFacts, *, source: str, options: ReportOptions) -> VideoReport # agent outputs ReportCore; code assembles VideoReport from content facts + run-time source
synthesis.py: async def answer_question(report: VideoReport, question: str, *, settings: Settings) -> str
report.py: def render_markdown(report: VideoReport, *, keyframes_relpath: Path | None = None) -> str
cache.py: class StageCache # sha256 file hash; stage_key(stage, params) sha256 of canonical params JSON; paths cache_dir/<sha[:16]>/stage-<name>-<key>.json; load/save pydantic or raw JSON; exists()
@@ -129,10 +129,11 @@ mcp_server.py: FastMCP("video-analyse") with exactly 6 tools: transcribe_video,
## 4. `models.py` — field-by-field contract (implemented, frozen)
```python
MediaInfo(path: Path, source: str, duration: float, width: int | None = None,
height: int | None = None, fps: float | None = None, has_audio: bool,
size_bytes: int, format: str | None = None, video_codec: str | None = None,
audio_codec: str | None = None, extra: dict[str, Any] = {})
MediaFacts(duration: float, width: int | None = None, height: int | None = None,
fps: float | None = None, has_audio: bool, size_bytes: int,
format: str | None = None, video_codec: str | None = None,
audio_codec: str | None = None, extra: dict[str, Any] = {})
MediaRef(source: str, local_path: Path)
Word(text: str, start: float, end: float, probability: float | None = None)
SpeakerTurn(start: float, end: float, speaker: str) # "S1", "S2", ...
Segment(start: float, end: float, text: str, words: list[Word] = [], speaker: str | None = None)
@@ -153,9 +154,9 @@ VideoReport(source: str, title: str | None = None, duration: float, summary: str
topics: list[str], people: list[str], highlights: list[Highlight],
shots: list[Shot], transcript: Transcript | None = None,
metadata: dict[str, Any] = {})
Artifacts(source: str, workdir: Path, media: MediaInfo | None = None,
transcript: Transcript | None = None, shots: list[Shot] = [],
report: VideoReport | None = None)
Artifacts(source: str, workdir: Path, media: MediaFacts | None = None,
ref: MediaRef | None = None, transcript: Transcript | None = None,
shots: list[Shot] = [], report: VideoReport | None = None)
```
Decision (deviation from the literal signature block): **every nullable field defaults to
@@ -165,6 +166,14 @@ therefore safe to use from `vision.py`. Mutable defaults (`[]`, `{}`) are safe:
them per instance. Round-trips: `Model.model_validate_json(m.model_dump_json()) == m`, and `Path`
fields come back as `Path` (tested in `tests/test_models.py`).
`MediaFacts` is the probe stage artifact: content only, cached under the source content hash
and independent of the source string, so two aliases of identical bytes share one entry. Its
`extra` carries content metadata only; local filename/path keys are dropped on construction.
`MediaRef` is run-time state (`source` string plus resolved `local_path`), attached when
`Pipeline.run` assembles `Artifacts` and never cached. `synthesis.metadata_from_info` flattens
`MediaFacts` only, so report metadata contains no local path; front doors compose facts with the
ref when they need to display or open the local file.
---
## 5. `config.py` (implemented, frozen)
+2 -2
View File
@@ -153,7 +153,7 @@ Our niche: **fully local/offline, CPU-viable, structured pydantic outputs, cache
```
┌────────────────────────────────────────────────┐
src (file or URL) │ ingest: yt-dlp download (if URL) → local file │
─────────────────► │ probe: ffprobe → MediaInfo │
─────────────────► │ probe: ffprobe → MediaFacts │
└───────────────┬────────────────────────────────┘
│
┌─────────────────────┴─────────────────────┐
@@ -297,7 +297,7 @@ Provider keys: `GROQ_API_KEY`, `DEEPSEEK_API_KEY`, `OPENROUTER_API_KEY`, `OLLAMA
```
va fetch <url> [--quality 1080] # URL → local file + metadata
va probe <src> # MediaInfo JSON
va probe <src> # MediaFacts + MediaRef JSON
va transcribe <src> [--backend parakeet|whisper|openai-transcriptions] [--lang en|auto] [--diarize] [--format json|srt]
va diarize <src> [--backend sherpa|pyannote] # SpeakerTurns → speaker-attributed transcript
va shots <src> [--detector adaptive] [--max-shots 64] # ShotList + keyframes
+4 -3
View File
@@ -91,8 +91,9 @@ uv run va probe /tmp/va-sample.mp4
uv run va probe /tmp/va-sample.mp4 --json
```
Returns a `MediaInfo`: duration, resolution, frame rate, codecs, size, format and the raw
ffprobe streams under `extra.ffprobe`.
Returns the probe facts (`MediaFacts`) together with the run-time source/path (`MediaRef`):
duration, resolution, frame rate, codecs, size, format and the raw ffprobe streams under
`extra.ffprobe` (local filenames stripped).
### Download a URL
@@ -499,7 +500,7 @@ local.
source file / URL
│
▼
ingest (yt-dlp for URLs) ──► probe (ffprobe → MediaInfo)
ingest (yt-dlp for URLs) ──► probe (ffprobe → MediaFacts)
│ │
├──► audio.wav (16 kHz mono) ──┼──► shots (PySceneDetect adaptive)
│ │ │ │
+26 -17
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
import asyncio
import importlib
import json
import os
from collections.abc import Callable, Collection, Iterator
from contextlib import contextmanager
@@ -34,7 +35,7 @@ from . import __version__
from .cache import StageCache
from .config import Settings
from .ingest import IngestResult
from .models import Artifacts, MediaInfo, Shot, Transcript, VideoReport
from .models import Artifacts, MediaFacts, MediaRef, Shot, Transcript, VideoReport
from .pipeline import DEFAULT_MAX_SHOTS, STAGE_ORDER, Pipeline
from .report import format_timestamp, render_markdown
from .srt import render_srt
@@ -146,9 +147,17 @@ def _json_mode(ctx: typer.Context, explicit: bool) -> bool:
return explicit or bool(getattr(root, "json_output", False))
def _emit_json(payload: BaseModel) -> None:
def _emit_json(payload: BaseModel | dict[str, Any]) -> None:
"""Write exactly one JSON document to stdout, with no rich wrapping or markup."""
typer.echo(payload.model_dump_json(indent=2))
if isinstance(payload, BaseModel):
typer.echo(payload.model_dump_json(indent=2))
else:
typer.echo(json.dumps(payload, indent=2, default=str))
def _probe_payload(facts: MediaFacts, ref: MediaRef) -> dict[str, Any]:
"""Compose probe facts with the run-time ref for ``va probe --json``."""
return {"source": ref.source, "path": ref.local_path, **facts.model_dump(mode="json")}
def _progress(json_mode: bool) -> Callable[[str], None] | None:
@@ -253,20 +262,20 @@ def _write_report_artifacts(
# --------------------------------------------------------------------------- #
# human-readable rendering
# --------------------------------------------------------------------------- #
def _render_media(media: MediaInfo) -> None:
"""Print a media-information table."""
resolution = f"{media.width}x{media.height}" if media.width and media.height else "unknown"
fps = f"{media.fps:.3g} fps" if media.fps else "unknown"
def _render_media(facts: MediaFacts, ref: MediaRef) -> None:
"""Print a media-information table composed from content facts and the run-time ref."""
resolution = f"{facts.width}x{facts.height}" if facts.width and facts.height else "unknown"
fps = f"{facts.fps:.3g} fps" if facts.fps else "unknown"
rows = [
("Source", media.source),
("Path", str(media.path)),
("Duration", f"{format_timestamp(media.duration)} ({media.duration:.1f} s)"),
("Source", ref.source),
("Path", str(ref.local_path)),
("Duration", f"{format_timestamp(facts.duration)} ({facts.duration:.1f} s)"),
("Resolution", resolution),
("Frame rate", fps),
("Video codec", media.video_codec or "none"),
("Audio codec", media.audio_codec or "none"),
("Size", _human_bytes(media.size_bytes)),
("Format", media.format or "unknown"),
("Video codec", facts.video_codec or "none"),
("Audio codec", facts.audio_codec or "none"),
("Size", _human_bytes(facts.size_bytes)),
("Format", facts.format or "unknown"),
]
table = Table(title="Media info", show_header=True, header_style="bold")
table.add_column("Field", style="bold", no_wrap=True)
@@ -508,12 +517,12 @@ def probe(
artifacts = asyncio.run(
_run_pipeline(_settings(), src, {"probe"}, progress=_progress(json_mode))
)
if artifacts.media is None:
if artifacts.media is None or artifacts.ref is None:
raise RuntimeError("the probe stage returned no media information")
if json_mode:
_emit_json(artifacts.media)
_emit_json(_probe_payload(artifacts.media, artifacts.ref))
return
_render_media(artifacts.media)
_render_media(artifacts.media, artifacts.ref)
@app.command()
+17 -6
View File
@@ -45,7 +45,8 @@ from .cache import StageCache
from .config import Settings
from .models import (
Artifacts,
MediaInfo,
MediaFacts,
MediaRef,
Shot,
SpeakerTurn,
Transcript,
@@ -303,8 +304,8 @@ def _validate_window(t_start: float, t_end: float) -> tuple[float, float]:
return start, end
def _require_video(artifacts: Artifacts, tool: str) -> MediaInfo:
"""Return the source's media info, or raise when it has no video stream."""
def _require_video(artifacts: Artifacts, tool: str) -> MediaFacts:
"""Return the source's content facts, or raise when it has no video stream."""
media = artifacts.media
if media is None:
raise RuntimeError(f"{tool}: the pipeline returned no media information")
@@ -315,6 +316,14 @@ def _require_video(artifacts: Artifacts, tool: str) -> MediaInfo:
return media
def _require_ref(artifacts: Artifacts, tool: str) -> MediaRef:
"""Return the run-time source ref (the local path media tools extract from)."""
ref = artifacts.ref
if ref is None:
raise RuntimeError(f"{tool}: the pipeline returned no local media reference")
return ref
def _require_report(artifacts: Artifacts, tool: str) -> VideoReport:
"""Return the pipeline's report, or raise an actionable error when it is missing."""
if artifacts.report is not None:
@@ -860,6 +869,7 @@ async def analyze_moment(
settings = _settings()
artifacts = await _run_pipeline(text, want={"probe"}, settings=settings)
media = _require_video(artifacts, "analyze_moment")
ref = _require_ref(artifacts, "analyze_moment")
duration = media.duration
notes: list[str] = []
@@ -873,7 +883,7 @@ async def analyze_moment(
notes.append(f"t_end was clamped to the video duration ({duration:.3f}s).")
cache = StageCache(settings.cache_dir)
source_sha = await asyncio.to_thread(cache.source_hash, media.path)
source_sha = await asyncio.to_thread(cache.source_hash, ref.local_path)
transcript = _cached_transcript(cache, source_sha)
if transcript is not None:
turns = _cached_turns(cache, source_sha)
@@ -905,7 +915,7 @@ async def analyze_moment(
)
timestamps = _frame_timestamps(start, end, duration, count=max_frames)
frames = await _extract_frames(media.path, timestamps, width=width)
frames = await _extract_frames(ref.local_path, timestamps, width=width)
moment_description: MomentDescription | None = None
if describe:
from .vision import describe_moment
@@ -969,13 +979,14 @@ async def get_frame_at(source: str, t: float, width: int = FRAME_WIDTH) -> ToolR
raise ValueError(f"width must be an integer between 64 and 2048, got {width!r}")
artifacts = await _run_pipeline(text, want={"probe"})
media = _require_video(artifacts, "get_frame_at")
ref = _require_ref(artifacts, "get_frame_at")
if media.duration > 0 and timestamp > media.duration:
raise ValueError(
f"t={timestamp:.3f}s is beyond the end of {source!r} (duration "
f"{media.duration:.3f}s); pass a timestamp inside the video"
)
seek = min(timestamp, max(media.duration - MOMENT_END_EPSILON, 0.0))
frames = await _extract_frames(media.path, [seek], width=width)
frames = await _extract_frames(ref.local_path, [seek], width=width)
payload = {
"source": artifacts.source,
"t": seek,
+7 -9
View File
@@ -25,7 +25,7 @@ from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict
from .models import MediaInfo, Shot
from .models import MediaFacts, Shot
logger = logging.getLogger(__name__)
@@ -155,8 +155,8 @@ def _is_cover_art(stream: dict[str, Any]) -> bool:
return isinstance(disposition, dict) and bool(disposition.get("attached_pic"))
def _media_info_from_probe(path: Path, payload: dict[str, Any]) -> MediaInfo:
"""Build a :class:`MediaInfo` from an ffprobe ``-of json`` payload."""
def _media_facts_from_probe(path: Path, payload: dict[str, Any]) -> MediaFacts:
"""Build content-only :class:`MediaFacts` from an ffprobe ``-of json`` payload."""
format_info = payload.get("format")
if not isinstance(format_info, dict):
format_info = {}
@@ -196,9 +196,7 @@ def _media_info_from_probe(path: Path, payload: dict[str, Any]) -> MediaInfo:
fps = _parse_rate(video_stream.get("avg_frame_rate"))
format_name = format_info.get("format_name")
return MediaInfo(
path=path,
source=str(path),
return MediaFacts(
duration=float(duration),
width=_as_int(video_stream.get("width")) if video_stream is not None else None,
height=_as_int(video_stream.get("height")) if video_stream is not None else None,
@@ -216,8 +214,8 @@ def _media_info_from_probe(path: Path, payload: dict[str, Any]) -> MediaInfo:
)
async def probe(path: Path) -> MediaInfo:
"""Probe a media file with ffprobe and return its technical metadata.
async def probe(path: Path) -> MediaFacts:
"""Probe a media file with ffprobe and return its content-only technical facts.
Raises:
ValueError: ``path`` does not exist or is not a regular file.
@@ -245,7 +243,7 @@ async def probe(path: Path) -> MediaInfo:
raise RuntimeError(f"ffprobe returned invalid JSON for {media_path}: {exc}") from exc
if not isinstance(payload, dict):
raise RuntimeError(f"ffprobe returned an unexpected payload for {media_path}")
return _media_info_from_probe(media_path, payload)
return _media_facts_from_probe(media_path, payload)
# --------------------------------------------------------------------------- #
+38 -7
View File
@@ -10,12 +10,13 @@ from __future__ import annotations
from pathlib import Path
from typing import Any, Literal
from pydantic import BaseModel
from pydantic import BaseModel, field_validator
__all__ = [
"Artifacts",
"Highlight",
"MediaInfo",
"MediaFacts",
"MediaRef",
"ReportCore",
"Segment",
"Shot",
@@ -27,11 +28,24 @@ __all__ = [
]
class MediaInfo(BaseModel):
"""Technical metadata about a media file (ffprobe + source metadata)."""
#: Nested keys that identify a local file rather than the media's content.
_LOCAL_PATH_KEYS = frozenset({"filename", "filepath", "_filename", "path", "local_path"})
def _content_only(value: Any) -> Any:
"""Recursively drop local-path fields from probe/ingest metadata."""
if isinstance(value, dict):
return {
key: _content_only(item) for key, item in value.items() if key not in _LOCAL_PATH_KEYS
}
if isinstance(value, list):
return [_content_only(item) for item in value]
return value
class MediaFacts(BaseModel):
"""Content facts produced by probing a media file (never run-time paths)."""
path: Path
source: str
duration: float
width: int | None = None
height: int | None = None
@@ -41,8 +55,24 @@ class MediaInfo(BaseModel):
format: str | None = None
video_codec: str | None = None
audio_codec: str | None = None
#: Content metadata only (ffprobe tags, bit rate, ...); local filenames are dropped.
extra: dict[str, Any] = {}
@field_validator("extra")
@classmethod
def _drop_local_paths(cls, value: dict[str, Any]) -> dict[str, Any]:
"""Keep the content-only invariant even when a caller passes raw metadata."""
cleaned = _content_only(value)
assert isinstance(cleaned, dict) # a dict input can only clean to a dict
return cleaned
class MediaRef(BaseModel):
"""Run-time location of a source; attached when facts are read, never cached."""
source: str
local_path: Path
class Word(BaseModel):
"""A single transcribed word with timings in seconds."""
@@ -151,7 +181,8 @@ class Artifacts(BaseModel):
source: str
workdir: Path
media: MediaInfo | None = None
media: MediaFacts | None = None
ref: MediaRef | None = None
transcript: Transcript | None = None
shots: list[Shot] = []
report: VideoReport | None = None
+52 -69
View File
@@ -20,13 +20,13 @@ it wraps:
================ ==============================================================
``ingest`` ``async (source, *, cache_dir: Path, quality: int) -> IngestResult``
``probe`` ``async (path: Path) -> MediaInfo``
``probe`` ``async (path: Path) -> MediaFacts``
``audio`` ``async (path: Path, workdir: Path) -> Path``
``transcribe`` ``async (wav: Path, *, options: SttOptions) -> Transcript``
``diarize`` ``async (wav: Path, *, options: DiarizeOptions) -> list[SpeakerTurn]``
``shots`` ``async (path, info, *, workdir: Path, options: ShotOptions) -> list[Shot]``
``shots`` ``async (path, facts, *, workdir: Path, options: ShotOptions) -> list[Shot]``
``describe`` ``async (shots, transcript, *, options: DescribeOptions) -> list[Shot]``
``report`` ``async (shots, transcript, info, *, options: ReportOptions) -> VideoReport``
``report`` ``async (shots, transcript, facts, *, source, options) -> VideoReport``
================ ==============================================================
Option values come from ``Settings.options_for(stage)``; stages never receive the
@@ -63,7 +63,8 @@ from .cache import StageCache
from .config import Settings
from .models import (
Artifacts,
MediaInfo,
MediaFacts,
MediaRef,
Shot,
SpeakerTurn,
Transcript,
@@ -159,14 +160,14 @@ class _TurnsArtifact(BaseModel):
# --------------------------------------------------------------------------- #
# stage input parameters (the cache keys hash exactly these)
# --------------------------------------------------------------------------- #
def _probe_params(video_sha: str, source: str) -> dict[str, Any]:
"""Inputs of the probe stage: the content hash and the original source string.
def _probe_params(video_sha: str) -> dict[str, Any]:
"""Inputs of the probe stage: only the content hash.
``MediaInfo.path``/``source`` are run-time values, so including ``source`` keeps
byte-identical copies under different names from sharing a cached artifact that
points at the first path (MCP frame tools read ``media.path``).
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, "source": source}
return {"video_sha256": video_sha}
def _audio_params(video_sha: str) -> dict[str, Any]:
@@ -258,8 +259,8 @@ def _report_params(
``applied`` flags record whether speaker labels and shot descriptions are part of
the material, so a run without (or with) diarization/description never hits the
other variant's cached report. ``source`` keeps two aliases of the same bytes from
sharing a report whose ``source``/``metadata['path']`` point at the other file.
other variant's cached report. ``source`` is the report's run-time identity, so
two aliases of the same bytes keep distinct reports.
"""
return {
"source": source,
@@ -381,20 +382,21 @@ class Pipeline:
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, original))
probed, _ = await self._execute_stage(
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=MediaInfo,
model_type=MediaFacts,
runner=lambda: self._stage("probe")(local_path),
notify=notify,
forced=self._forced("probe", wanted, force),
)
# ``path``/``source`` are run-time values, not content: always re-inject the
# current ones, and fold in yt-dlp's title/metadata for URL sources (PLAN §4).
media = self._rebase_media(probed, original, local_path, ingested)
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)
@@ -629,16 +631,18 @@ class Pipeline:
source_sha=video_sha,
key=report_key,
model_type=VideoReport,
runner=lambda: self._run_report(shots, transcript, media, options=report_options),
runner=lambda: self._run_report(
shots, transcript, media, ref.source, options=report_options
),
notify=notify,
forced=self._forced("report", wanted, force),
)
report = self._rebase_report(report, original, local_path)
artifacts = Artifacts(
source=original,
workdir=workdir,
media=media,
ref=ref,
transcript=transcript,
shots=shots,
report=report,
@@ -692,48 +696,25 @@ class Pipeline:
shot.transcript_slice = transcript_slice_for(shot, transcript)
@staticmethod
def _rebase_media(
probed: MediaInfo, original: str, local_path: Path, ingested: Any | None
) -> MediaInfo:
"""Re-inject run-time path/source and merge yt-dlp metadata into ``extra``."""
extra = dict(probed.extra)
if ingested is not None:
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()
ffprobe = extra.get("ffprobe")
if isinstance(ffprobe, dict):
ffprobe = dict(ffprobe)
format_info = ffprobe.get("format")
if isinstance(format_info, dict):
format_info = dict(format_info)
format_info["filename"] = str(local_path)
ffprobe["format"] = format_info
extra["ffprobe"] = ffprobe
return probed.model_copy(update={"source": original, "path": local_path, "extra": extra})
def _facts_with_ingest_metadata(facts: MediaFacts, ingested: Any | None) -> MediaFacts:
"""Merge URL provenance (yt-dlp title/metadata) into this run's facts.
@staticmethod
def _rebase_report(report: VideoReport, original: str, local_path: Path) -> VideoReport:
"""Keep a cached report's source/path fields in sync with the current run."""
metadata = dict(report.metadata)
metadata["path"] = str(local_path)
extra = metadata.get("extra")
if isinstance(extra, dict):
extra = dict(extra)
ffprobe = extra.get("ffprobe")
if isinstance(ffprobe, dict):
ffprobe = dict(ffprobe)
format_info = ffprobe.get("format")
if isinstance(format_info, dict):
format_info = dict(format_info)
format_info["filename"] = str(local_path)
ffprobe["format"] = format_info
extra["ffprobe"] = ffprobe
metadata["extra"] = extra
return report.model_copy(update={"source": original, "metadata": metadata})
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
@@ -873,7 +854,7 @@ class Pipeline:
async def _run_shots(
self,
path: Path,
info: MediaInfo,
info: MediaFacts,
workdir: Path,
shots_key: str | None,
*,
@@ -903,12 +884,13 @@ class Pipeline:
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
source: str,
*,
options: ReportOptions,
) -> VideoReport:
"""Run the report stage for the available material."""
return await self._stage("report")(shots, transcript, info, options=options)
"""Run the report stage for the available material and run-time source."""
return await self._stage("report")(shots, transcript, info, source=source, options=options)
# ------------------------------------------------------------------ #
# real stage implementations (heavy imports stay inside the methods)
@@ -919,7 +901,7 @@ class Pipeline:
return await fetch(source, cache_dir=cache_dir, quality=quality)
async def _real_probe(self, path: Path) -> MediaInfo:
async def _real_probe(self, path: Path) -> MediaFacts:
"""Probe the media file with ffprobe (``video_analyse.media.probe``)."""
from .media import probe
@@ -946,7 +928,7 @@ class Pipeline:
async def _real_shots(
self,
path: Path,
info: MediaInfo,
info: MediaFacts,
*,
workdir: Path,
options: ShotOptions,
@@ -982,11 +964,12 @@ class Pipeline:
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
source: str,
options: ReportOptions,
) -> VideoReport:
"""Synthesise the validated report with the configured model."""
from .synthesis import synthesise_report
return await synthesise_report(shots, transcript, info, options=options)
return await synthesise_report(shots, transcript, info, source=source, options=options)
+25 -20
View File
@@ -32,7 +32,7 @@ from .cache import StageCache
from .config import Settings
from .models import (
Highlight,
MediaInfo,
MediaFacts,
ReportCore,
Shot,
Transcript,
@@ -276,11 +276,10 @@ def _yes_no(value: bool) -> str:
return "yes" if value else "no"
def format_media_metadata(info: MediaInfo) -> str:
"""Render media facts as compact, one-fact-per-line text."""
def format_media_metadata(info: MediaFacts) -> str:
"""Render media facts as compact, one-fact-per-line text (never a source path)."""
lines = [
"VIDEO METADATA:",
f"- source: {info.source}",
f"- duration: {format_timestamp(info.duration)} ({info.duration:.2f} s)",
]
if info.width and info.height:
@@ -466,7 +465,7 @@ def _compact_chunk_notes(cores: list[ChunkCore], *, max_chars: int) -> tuple[str
return f"{body}\n{note}"[:max_chars], True
def _chunk_prompt(info: MediaInfo, chunk: str, index: int, total: int, *, max_chars: int) -> str:
def _chunk_prompt(info: MediaFacts, chunk: str, index: int, total: int, *, max_chars: int) -> str:
"""Build the map-step prompt for one transcript chunk."""
fixed = "\n\n".join(
[CHUNK_TASK, format_media_metadata(info), f"TRANSCRIPT CHUNK {index}/{total}:"]
@@ -477,7 +476,7 @@ def _chunk_prompt(info: MediaInfo, chunk: str, index: int, total: int, *, max_ch
def build_synthesis_prompt(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
max_chars: int,
chunk_notes: str | None = None,
@@ -631,10 +630,9 @@ def build_question_prompt(report: VideoReport, question: str, *, max_chars: int)
# --- report assembly and agents -------------------------------------------
def metadata_from_info(info: MediaInfo) -> dict[str, Any]:
"""Flatten a :class:`MediaInfo` into the report's free-form metadata dict."""
def metadata_from_info(info: MediaFacts) -> dict[str, Any]:
"""Flatten :class:`MediaFacts` into the report's content-only metadata dict."""
metadata: dict[str, Any] = {
"path": str(info.path),
"format": info.format,
"video_codec": info.video_codec,
"audio_codec": info.audio_codec,
@@ -649,7 +647,7 @@ def metadata_from_info(info: MediaInfo) -> dict[str, Any]:
return metadata
def _metadata_title(info: MediaInfo) -> str | None:
def _metadata_title(info: MediaFacts) -> str | None:
"""Best grounded title from the source metadata, if it carries one."""
title = info.extra.get("title")
if isinstance(title, str) and title.strip():
@@ -680,21 +678,24 @@ def assemble_report(
core: ReportCore,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
source: str,
prompt_info: dict[str, Any] | None = None,
) -> VideoReport:
"""Combine the LLM-authored core with the facts the code owns.
"""Combine the LLM-authored core with the facts and run-time source.
``prompt_info`` records whether the prompt was chunked/truncated so a partial
report is visible as such in ``metadata['synthesis']`` instead of looking complete.
``info`` contributes content metadata only; ``source`` is the run-time identity
from :class:`~video_analyse.models.MediaRef`. ``prompt_info`` records whether the
prompt was chunked/truncated so a partial report is visible as such in
``metadata['synthesis']`` instead of looking complete.
"""
title = core.title if core.title and core.title.strip() else _metadata_title(info)
metadata = metadata_from_info(info)
if prompt_info:
metadata["synthesis"] = dict(prompt_info)
return VideoReport(
source=info.source,
source=source,
title=title,
duration=info.duration,
summary=core.summary,
@@ -730,8 +731,9 @@ class ReportOptions(BaseModel):
async def synthesise_report(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
source: str,
options: ReportOptions,
) -> VideoReport:
"""Ask the synthesis model for a report core and assemble the full report.
@@ -744,7 +746,8 @@ async def synthesise_report(
Args:
shots: detected shots (with descriptions when the vision stage ran).
transcript: speaker-labelled transcript, or ``None`` when unavailable.
info: media metadata for the source.
info: content facts for the source (never a run-time path).
source: original source string (run-time, from the ``MediaRef``).
options: frozen ``ReportOptions`` value; ``options.synthesis_model`` picks the model.
Returns:
@@ -788,7 +791,7 @@ async def synthesise_report(
"synthesis map step %d/%d for %s (%d chars)",
index,
len(chunks),
info.source,
source,
len(prompt),
)
result = await map_agent.run(prompt)
@@ -817,7 +820,7 @@ async def synthesise_report(
}
logger.info(
"synthesising report for %s with %s (%d shots, %d chars, ~%d tokens, chunked=%s)",
info.source,
source,
spec,
len(shots),
len(prompt),
@@ -837,7 +840,9 @@ async def synthesise_report(
)
result = await agent.run(prompt)
core = result.output
return assemble_report(core, shots, transcript, info, prompt_info=synthesis_metadata)
return assemble_report(
core, shots, transcript, info, source=source, prompt_info=synthesis_metadata
)
class _AnswerArtifact(BaseModel):
+35 -38
View File
@@ -15,7 +15,7 @@ import pytest
from video_analyse import cache as cache_module
from video_analyse.cache import StageCache
from video_analyse.models import MediaInfo, Segment, Transcript, Word
from video_analyse.models import MediaFacts, Segment, Transcript, Word
@pytest.fixture
@@ -25,11 +25,9 @@ def cache(tmp_path: Path) -> StageCache:
@pytest.fixture
def sample_media(sample_video: Path) -> MediaInfo:
"""A MediaInfo for the conftest sample video (the fixture skips without ffmpeg)."""
return MediaInfo(
path=sample_video,
source=str(sample_video),
def sample_media(sample_video: Path) -> MediaFacts:
"""Content facts for the conftest sample video (the fixture skips without ffmpeg)."""
return MediaFacts(
duration=10.0,
width=640,
height=360,
@@ -199,7 +197,7 @@ def test_cache_dir_expands_the_home_directory(
# model / JSON round-trips
# --------------------------------------------------------------------------- #
def test_save_and_load_model_round_trip(
cache: StageCache, sample_video: Path, sample_media: MediaInfo
cache: StageCache, sample_video: Path, sample_media: MediaFacts
) -> None:
digest = cache.source_hash(sample_video)
key = cache.stage_key("probe", {"video_sha256": digest})
@@ -210,9 +208,8 @@ def test_save_and_load_model_round_trip(
assert path.is_file()
assert path.read_text(encoding="utf-8").endswith("\n")
assert json.loads(path.read_text(encoding="utf-8"))["duration"] == 10.0
loaded = cache.load_model(path, MediaInfo)
loaded = cache.load_model(path, MediaFacts)
assert loaded == sample_media
assert loaded is not None and isinstance(loaded.path, Path)
def test_save_and_load_nested_models(cache: StageCache, tmp_path: Path) -> None:
@@ -246,17 +243,17 @@ def test_load_model_handles_missing_and_corrupt_artifacts(
cache: StageCache, tmp_path: Path
) -> None:
missing = tmp_path / "missing.json"
assert cache.load_model(missing, MediaInfo) is None
assert cache.load_model(missing, MediaFacts) is None
corrupt = tmp_path / "corrupt.json"
corrupt.write_text("{not json", encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaInfo"):
cache.load_model(corrupt, MediaInfo)
with pytest.raises(ValueError, match="does not match MediaFacts"):
cache.load_model(corrupt, MediaFacts)
wrong_shape = tmp_path / "wrong.json"
wrong_shape.write_text('{"duration": 1.0}', encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaInfo"):
cache.load_model(wrong_shape, MediaInfo)
with pytest.raises(ValueError, match="does not match MediaFacts"):
cache.load_model(wrong_shape, MediaFacts)
with pytest.raises(TypeError, match="model_type must be a pydantic BaseModel"):
cache.load_model(missing, dict) # type: ignore[arg-type]
@@ -292,7 +289,7 @@ def test_exists_only_true_for_regular_files(cache: StageCache, tmp_path: Path) -
def test_clear_stage_removes_only_that_stage(
cache: StageCache, sample_video: Path, sample_media: MediaInfo
cache: StageCache, sample_video: Path, sample_media: MediaFacts
) -> None:
digest = cache.source_hash(sample_video)
keep = cache.stage_path(digest, "probe", cache.stage_key("probe", {"video_sha256": digest}))
@@ -308,7 +305,7 @@ def test_clear_stage_removes_only_that_stage(
def test_writes_are_atomic_and_leave_no_temporary_files(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
@@ -320,33 +317,33 @@ def test_writes_are_atomic_and_leave_no_temporary_files(
# cached_run: the single load -> miss -> run -> save policy
# --------------------------------------------------------------------------- #
async def test_cached_run_returns_a_hit_without_running(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
hits: list[str] = []
async def runner() -> MediaInfo: # pragma: no cover - must not run
async def runner() -> MediaFacts: # pragma: no cover - must not run
raise AssertionError("runner must not run on a cache hit")
loaded = await cache.cached_run(path, MediaInfo, runner, on_hit=lambda: hits.append("hit"))
loaded = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert loaded == sample_media
assert hits == ["hit"]
async def test_cached_run_runs_saves_and_then_hits(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "nested" / "artifact.json"
calls: list[str] = []
hits: list[str] = []
async def runner() -> MediaInfo:
async def runner() -> MediaFacts:
calls.append("run")
return sample_media
first = await cache.cached_run(path, MediaInfo, runner, on_hit=lambda: hits.append("hit"))
first = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert first == sample_media
assert calls == ["run"]
@@ -354,7 +351,7 @@ async def test_cached_run_runs_saves_and_then_hits(
assert path.is_file()
assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"]
second = await cache.cached_run(path, MediaInfo, runner, on_hit=lambda: hits.append("hit"))
second = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert second == sample_media
assert calls == ["run"] # the second call was a hit
@@ -367,68 +364,68 @@ async def test_cached_run_runs_saves_and_then_hits(
ids=["not-json", "missing-fields", "wrong-types"],
)
async def test_cached_run_treats_a_corrupt_artifact_as_a_miss(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo, payload: str
cache: StageCache, tmp_path: Path, sample_media: MediaFacts, payload: str
) -> None:
path = tmp_path / "artifact.json"
path.write_text(payload, encoding="utf-8")
calls: list[str] = []
async def runner() -> MediaInfo:
async def runner() -> MediaFacts:
calls.append("run")
return sample_media
loaded = await cache.cached_run(path, MediaInfo, runner)
loaded = await cache.cached_run(path, MediaFacts, runner)
assert loaded == sample_media
assert calls == ["run"]
assert cache.load_model(path, MediaInfo) == sample_media # corrupt file rewritten
assert cache.load_model(path, MediaFacts) == sample_media # corrupt file rewritten
assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"]
async def test_cached_run_reruns_when_validation_rejects_the_cached_model(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
calls: list[str] = []
replacement = sample_media.model_copy(update={"duration": 12.0})
async def runner() -> MediaInfo:
async def runner() -> MediaFacts:
calls.append("run")
return replacement
loaded = await cache.cached_run(
path, MediaInfo, runner, validate=lambda item: item.duration != 10.0
path, MediaFacts, runner, validate=lambda item: item.duration != 10.0
)
assert loaded == replacement
assert calls == ["run"]
assert cache.load_model(path, MediaInfo) == replacement
assert cache.load_model(path, MediaFacts) == replacement
async def test_cached_run_force_bypasses_an_existing_artifact(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
replacement = sample_media.model_copy(update={"duration": 12.0})
calls: list[str] = []
async def runner() -> MediaInfo:
async def runner() -> MediaFacts:
calls.append("run")
return replacement
loaded = await cache.cached_run(path, MediaInfo, runner, force=True)
loaded = await cache.cached_run(path, MediaFacts, runner, force=True)
assert loaded == replacement
assert calls == ["run"]
assert cache.load_model(path, MediaInfo) == replacement
assert cache.load_model(path, MediaFacts) == replacement
async def test_cached_run_keeps_the_value_when_saving_fails(
cache: StageCache,
tmp_path: Path,
sample_media: MediaInfo,
sample_media: MediaFacts,
monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "artifact.json"
@@ -438,7 +435,7 @@ async def test_cached_run_keeps_the_value_when_saving_fails(
monkeypatch.setattr(cache, "save_model", explode)
async def runner() -> MediaInfo:
async def runner() -> MediaFacts:
return sample_media
assert await cache.cached_run(path, MediaInfo, runner) == sample_media
assert await cache.cached_run(path, MediaFacts, runner) == sample_media
+7 -7
View File
@@ -28,7 +28,8 @@ from video_analyse.config import Settings
from video_analyse.models import (
Artifacts,
Highlight,
MediaInfo,
MediaFacts,
MediaRef,
Segment,
Shot,
ShotDescription,
@@ -194,12 +195,10 @@ def _shots(frames_dir: Path, *, described: bool = True) -> list[Shot]:
]
def _media(path: Path, *, has_audio: bool = True, has_video: bool = True) -> MediaInfo:
"""Synthetic media facts for ``path`` (the file is never opened)."""
def _media(path: Path, *, has_audio: bool = True, has_video: bool = True) -> MediaFacts:
"""Synthetic content facts for ``path`` (the file is never opened)."""
size = path.stat().st_size if path.is_file() else 0
return MediaInfo(
path=path,
source=str(path),
return MediaFacts(
duration=10.0,
width=640 if has_video else None,
height=360 if has_video else None,
@@ -226,6 +225,7 @@ def _artifacts(
source=str(path),
workdir=path.parent,
media=_media(path, has_audio=has_audio, has_video=has_video),
ref=MediaRef(source=str(path), local_path=path),
transcript=transcript,
shots=shots or [],
report=report,
@@ -246,7 +246,7 @@ def _report(path: Path, transcript: Transcript, shots: list[Shot]) -> VideoRepor
],
shots=shots,
transcript=transcript,
metadata={"path": str(path), "width": 640, "height": 360},
metadata={"width": 640, "height": 360},
)
+7 -4
View File
@@ -30,7 +30,7 @@ from video_analyse.media import (
plan_shots,
probe,
)
from video_analyse.models import Shot
from video_analyse.models import MediaFacts, Shot
FFPROBE = shutil.which("ffprobe")
FFMPEG = shutil.which("ffmpeg")
@@ -74,8 +74,9 @@ def _ffprobe_json(path: Path) -> dict:
async def test_probe_reads_container_and_stream_fields(sample_video: Path) -> None:
info = await probe(sample_video)
assert info.path == sample_video
assert info.source == str(sample_video)
assert isinstance(info, MediaFacts)
assert "path" not in MediaFacts.model_fields
assert "source" not in MediaFacts.model_fields
assert info.duration == pytest.approx(10.0, abs=0.2)
assert info.width == 640
assert info.height == 360
@@ -86,8 +87,10 @@ async def test_probe_reads_container_and_stream_fields(sample_video: Path) -> No
assert "mp4" in info.format
assert info.video_codec == "h264"
assert info.audio_codec == "aac"
# the raw ffprobe payload is kept for reports/telemetry
# the raw ffprobe payload is kept for reports/telemetry, minus local filenames
assert info.extra["ffprobe"]["format"]["format_name"] == info.format
assert "filename" not in info.extra["ffprobe"]["format"]
assert str(sample_video) not in json.dumps(info.extra)
async def test_probe_missing_file_raises_value_error(tmp_path: Path) -> None:
+50 -12
View File
@@ -7,7 +7,8 @@ from pathlib import Path
from video_analyse.models import (
Artifacts,
Highlight,
MediaInfo,
MediaFacts,
MediaRef,
ReportCore,
Segment,
Shot,
@@ -57,10 +58,8 @@ def _shot(tmp_path: Path) -> Shot:
)
def test_media_info_roundtrip(tmp_path: Path) -> None:
media = MediaInfo(
path=tmp_path / "video.mp4",
source="video.mp4",
def test_media_facts_roundtrip() -> None:
media = MediaFacts(
duration=10.0,
width=640,
height=360,
@@ -72,19 +71,46 @@ def test_media_info_roundtrip(tmp_path: Path) -> None:
audio_codec="aac",
extra={"bit_rate": "48k"},
)
assert isinstance(media.path, Path)
assert "path" not in MediaFacts.model_fields
assert "source" not in MediaFacts.model_fields
dumped = media.model_dump_json()
restored = MediaInfo.model_validate_json(dumped)
restored = MediaFacts.model_validate_json(dumped)
assert restored == media
assert isinstance(restored.path, Path)
assert restored.extra["bit_rate"] == "48k"
def test_nullable_media_info_fields_default_to_none(tmp_path: Path) -> None:
media = MediaInfo(
path=tmp_path / "audio_only.m4a",
source="audio_only.m4a",
def test_media_facts_extra_drops_local_paths() -> None:
media = MediaFacts(
duration=1.0,
has_audio=True,
size_bytes=10,
extra={
"ffprobe": {
"format": {"filename": "/tmp/private/video.mp4", "format_name": "mp4"},
"streams": [{"codec_type": "video", "filename": "/tmp/private/video.mp4"}],
},
"title": "Safe title",
},
)
assert media.extra == {
"ffprobe": {"format": {"format_name": "mp4"}, "streams": [{"codec_type": "video"}]},
"title": "Safe title",
}
def test_media_ref_roundtrip(tmp_path: Path) -> None:
ref = MediaRef(source="https://example.com/clip.mp4", local_path=tmp_path / "clip.mp4")
restored = MediaRef.model_validate_json(ref.model_dump_json())
assert restored == ref
assert isinstance(restored.local_path, Path)
def test_nullable_media_facts_fields_default_to_none() -> None:
media = MediaFacts(
duration=3.0,
has_audio=True,
size_bytes=1,
@@ -177,6 +203,7 @@ def test_video_report_roundtrip(tmp_path: Path) -> None:
def test_artifacts_defaults_and_roundtrip(tmp_path: Path) -> None:
artifacts = Artifacts(source="video.mp4", workdir=tmp_path)
assert artifacts.media is None
assert artifacts.ref is None
assert artifacts.transcript is None
assert artifacts.shots == []
assert artifacts.report is None
@@ -184,3 +211,14 @@ def test_artifacts_defaults_and_roundtrip(tmp_path: Path) -> None:
restored = Artifacts.model_validate_json(artifacts.model_dump_json())
assert restored == artifacts
assert isinstance(restored.workdir, Path)
with_ref = Artifacts(
source="video.mp4",
workdir=tmp_path,
media=MediaFacts(duration=10.0, has_audio=True, size_bytes=123),
ref=MediaRef(source="video.mp4", local_path=tmp_path / "video.mp4"),
)
restored = Artifacts.model_validate_json(with_ref.model_dump_json())
assert restored == with_ref
assert restored.ref is not None
assert isinstance(restored.ref.local_path, Path)
+48 -44
View File
@@ -9,6 +9,7 @@ content hash matters to the pipeline.
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
@@ -21,7 +22,8 @@ from video_analyse.ingest import IngestResult
from video_analyse.media import ShotOptions
from video_analyse.models import (
Artifacts,
MediaInfo,
MediaFacts,
MediaRef,
Segment,
Shot,
ShotDescription,
@@ -141,16 +143,22 @@ class FakeStages:
self.calls.append("ingest")
self.ingest_calls.append((source, cache_dir, quality))
return IngestResult(
path=self.source, info={"title": "Fake video"}, downloaded=True, title="Fake video"
path=self.source,
info={
"title": "Fake video",
"filepath": str(self.source),
"_filename": str(self.source),
"requested_downloads": [{"filepath": str(self.source)}],
},
downloaded=True,
title="Fake video",
)
async def probe(self, path: Path) -> MediaInfo:
"""Return synthetic media facts for ``path``."""
async def probe(self, path: Path) -> MediaFacts:
"""Return synthetic content facts for ``path``."""
self.calls.append("probe")
self.probe_calls.append(path)
return MediaInfo(
path=path,
source=str(path),
return MediaFacts(
duration=10.0,
width=640 if self.has_video else None,
height=360 if self.has_video else None,
@@ -204,7 +212,7 @@ class FakeStages:
return [turn.model_copy(deep=True) for turn in self.turn_template]
async def shots(
self, path: Path, info: MediaInfo, *, workdir: Path, options: ShotOptions
self, path: Path, info: MediaFacts, *, workdir: Path, options: ShotOptions
) -> list[Shot]:
"""Return the canned shot list."""
self.calls.append("shots")
@@ -229,8 +237,9 @@ class FakeStages:
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
source: str,
options: ReportOptions,
) -> VideoReport:
"""Assemble a report from exactly the material that was handed in."""
@@ -238,7 +247,7 @@ class FakeStages:
self.report_calls.append(transcript is not None)
self.report_options.append(options)
return VideoReport(
source=info.source,
source=source,
title="Fake video",
duration=info.duration,
summary="fake report",
@@ -247,7 +256,7 @@ class FakeStages:
highlights=[],
shots=[shot.model_copy(deep=True) for shot in shots],
transcript=transcript,
metadata={"has_audio": info.has_audio},
metadata={"has_audio": info.has_audio, "extra": dict(info.extra)},
)
@@ -276,8 +285,7 @@ async def test_full_run_orders_stages_and_assembles_artifacts(tmp_path: Path) ->
assert artifacts.source == str(source)
assert artifacts.workdir == cache.source_dir(cache.source_hash(source))
assert artifacts.media is not None
assert artifacts.media.source == str(source)
assert artifacts.media.path == source.resolve()
assert artifacts.ref == MediaRef(source=str(source), local_path=source.resolve())
assert artifacts.transcript is not None
assert [segment.speaker for segment in artifacts.transcript.segments] == ["S1", "S2"]
@@ -647,8 +655,7 @@ async def test_url_source_runs_the_ingest_stage_first(tmp_path: Path) -> None:
assert "ingest: ready (clip.mp4)" in messages
assert artifacts.source == url
assert artifacts.media is not None
assert artifacts.media.source == url
assert artifacts.media.path == local
assert artifacts.ref == MediaRef(source=url, local_path=local)
async def test_local_source_never_calls_the_ingest_stage(tmp_path: Path) -> None:
@@ -711,48 +718,45 @@ async def test_transcript_slice_is_populated_for_every_shot(tmp_path: Path) -> N
assert artifacts.report.shots[1].transcript_slice == "[00:05] S2: second"
async def test_probe_and_report_use_the_current_source_path(tmp_path: Path) -> None:
"""Byte-identical copies under different names must not share a stale path."""
async def test_probe_facts_are_shared_by_aliases_and_ref_tracks_the_alias(
tmp_path: Path,
) -> None:
"""Two aliases of identical bytes share one probe artifact; the ref is per run."""
first = _make_source(tmp_path, name="one.mp4")
settings = _settings(tmp_path)
await Pipeline(settings, FakeStages(first).mapping()).run(str(first), want={"probe"})
first_artifacts = await Pipeline(settings, FakeStages(first).mapping()).run(
str(first), want={"probe"}
)
first.unlink()
second = _make_source(tmp_path, name="two.mp4")
fakes = FakeStages(second)
messages: list[str] = []
artifacts = await Pipeline(settings, FakeStages(second).mapping()).run(
artifacts = await Pipeline(settings, fakes.mapping()).run(
str(second), want={"probe"}, progress=messages.append
)
assert artifacts.media is not None
assert artifacts.media.path == second.resolve()
assert artifacts.media.source == str(second)
assert "probe: running" in messages
assert fakes.probe_calls == [] # the probe entry is shared by content, not by name
assert "probe: cached" in messages
assert artifacts.media == first_artifacts.media
assert artifacts.ref == MediaRef(source=str(second), local_path=second.resolve())
assert len(list(artifacts.workdir.glob("stage-probe-*.json"))) == 1
def test_rebase_media_merges_yt_dlp_metadata_and_title(tmp_path: Path) -> None:
"""PLAN §4: URL reports carry ffprobe + yt-dlp metadata, including the title."""
async def test_url_facts_and_report_carry_no_local_paths(tmp_path: Path) -> None:
"""yt-dlp metadata is kept, but the download path never enters the artifacts."""
url = "https://example.invalid/watch?v=abc"
local = _make_source(tmp_path)
probed = MediaInfo(
path=local,
source=str(local),
duration=10.0,
has_audio=True,
size_bytes=local.stat().st_size,
extra={"ffprobe": {"format": {"filename": str(local)}}},
)
ingested = IngestResult(
path=local,
info={"title": "Real title", "id": "abc"},
downloaded=True,
title="Real title",
)
media = Pipeline._rebase_media(probed, "https://example.invalid/watch?v=abc", local, ingested)
fakes = FakeStages(local)
artifacts = await Pipeline(_settings(tmp_path), fakes.mapping()).run(url)
assert media.source == "https://example.invalid/watch?v=abc"
assert media.path == local
assert media.extra["title"] == "Real title"
assert media.extra["yt_dlp"]["id"] == "abc"
assert artifacts.media is not None
assert artifacts.media.extra["title"] == "Fake video"
assert artifacts.media.extra["yt_dlp"]["title"] == "Fake video"
assert str(local) not in json.dumps(artifacts.media.extra)
assert artifacts.report is not None
assert artifacts.report.source == url
assert str(local) not in artifacts.report.model_dump_json()
async def test_describe_cache_key_tracks_diarization_context(tmp_path: Path) -> None:
+73 -35
View File
@@ -21,7 +21,7 @@ from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.models import (
Highlight,
MediaInfo,
MediaFacts,
ReportCore,
Segment,
Shot,
@@ -54,12 +54,11 @@ from video_analyse.synthesis import (
LOCAL_SETTINGS = Settings(profile="local", synthesis_model=None)
HOSTED_SETTINGS = Settings(profile="hosted", synthesis_model="deepseek:deepseek-flash")
SOURCE = "/media/sample.mp4"
def _info(**overrides: object) -> MediaInfo:
def _facts(**overrides: object) -> MediaFacts:
data: dict[str, object] = {
"path": Path("/media/sample.mp4"),
"source": "/media/sample.mp4",
"duration": 95.0,
"width": 640,
"height": 360,
@@ -72,7 +71,7 @@ def _info(**overrides: object) -> MediaInfo:
"extra": {"title": "Metadata title"},
}
data.update(overrides)
return MediaInfo(**data) # type: ignore[arg-type]
return MediaFacts(**data) # type: ignore[arg-type]
def _transcript() -> Transcript:
@@ -127,7 +126,7 @@ def _report() -> VideoReport:
people=["Alice"],
highlights=[Highlight(start=65.25, end=70.0, description="[01:05] Results are shown.")],
)
return assemble_report(core, _shots(), _transcript(), _info())
return assemble_report(core, _shots(), _transcript(), _facts(), source=SOURCE)
def _prompt_text(messages: list[ModelMessage]) -> str:
@@ -334,11 +333,11 @@ def test_prompt_text_is_pinned_byte_for_byte() -> None:
def test_build_synthesis_prompt_contains_metadata_shots_and_transcript() -> None:
prompt, _info_value = build_synthesis_prompt(
_shots(), _transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS
_shots(), _transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
)
assert "TASK: write the core of a report about this video" in prompt
assert "VIDEO METADATA:" in prompt
assert "- source: /media/sample.mp4" in prompt
assert "- source:" not in prompt
assert "- duration: 01:35 (95.00 s)" in prompt
assert "- resolution: 640x360 at 12 fps" in prompt
assert "[0] [00:00-00:15]: Title slide on a blue background." in prompt
@@ -350,7 +349,7 @@ def test_build_synthesis_prompt_contains_metadata_shots_and_transcript() -> None
def test_build_synthesis_prompt_without_transcript_says_so() -> None:
prompt, _info_value = build_synthesis_prompt(
_shots(), None, _info(), max_chars=LOCAL_PROMPT_CHARS
_shots(), None, _facts(), max_chars=LOCAL_PROMPT_CHARS
)
assert "(no transcript available)" in prompt
assert "transcript truncated" not in prompt
@@ -358,11 +357,11 @@ def test_build_synthesis_prompt_without_transcript_says_so() -> None:
def test_build_synthesis_prompt_truncates_long_transcripts_and_keeps_shots() -> None:
prompt, _info_value = build_synthesis_prompt(
_shots(), _long_transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS
_shots(), _long_transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
)
assert "transcript truncated for the prompt budget" in prompt
assert "[0] [00:00-00:15]: Title slide on a blue background." in prompt
assert "- source: /media/sample.mp4" in prompt
assert "- source:" not in prompt
assert len(prompt) <= LOCAL_PROMPT_CHARS
@@ -404,8 +403,8 @@ def test_assemble_report_uses_the_code_owned_facts() -> None:
people=["Alice"],
highlights=[Highlight(start=1.0, end=2.5, description="[00:01] Something happens.")],
)
info = _info()
report = assemble_report(core, _shots(), _transcript(), info)
info = _facts()
report = assemble_report(core, _shots(), _transcript(), info, source=SOURCE)
assert report.source == "/media/sample.mp4"
assert report.duration == 95.0
assert report.summary == "Grounded summary."
@@ -414,7 +413,7 @@ def test_assemble_report_uses_the_code_owned_facts() -> None:
assert report.highlights == core.highlights
assert report.shots == _shots()
assert report.transcript == _transcript()
assert report.metadata["path"] == str(info.path)
assert "path" not in report.metadata
assert report.metadata["format"] == "mp4"
assert report.metadata["has_audio"] is True
assert report.metadata["extra"] == {"title": "Metadata title"}
@@ -422,37 +421,41 @@ def test_assemble_report_uses_the_code_owned_facts() -> None:
def test_assemble_report_prefers_the_core_title_and_falls_back_to_metadata() -> None:
core = ReportCore(title="Model title", summary="Summary.")
assert assemble_report(core, _shots(), None, _info()).title == "Model title"
assert assemble_report(core, _shots(), None, _facts(), source=SOURCE).title == "Model title"
untitled = ReportCore(title=None, summary="Summary.")
assert assemble_report(untitled, _shots(), None, _info()).title == "Metadata title"
plain = _info(extra={})
assert assemble_report(untitled, _shots(), None, plain).title is None
assert (
assemble_report(untitled, _shots(), None, _facts(), source=SOURCE).title == "Metadata title"
)
plain = _facts(extra={})
assert assemble_report(untitled, _shots(), None, plain, source=SOURCE).title is None
def test_assemble_report_reads_yt_dlp_and_ffprobe_titles() -> None:
core = ReportCore(title=None, summary="Summary.")
from_yt_dlp = assemble_report(core, [], None, _info(extra={"yt_dlp": {"title": "YT title"}}))
from_yt_dlp = assemble_report(
core, [], None, _facts(extra={"yt_dlp": {"title": "YT title"}}), source=SOURCE
)
assert from_yt_dlp.title == "YT title"
from_ffprobe = assemble_report(
core,
[],
None,
_info(extra={"ffprobe": {"format": {"tags": {"title": "Container title"}}}}),
_facts(extra={"ffprobe": {"format": {"tags": {"title": "Container title"}}}}),
source=SOURCE,
)
assert from_ffprobe.title == "Container title"
def test_assemble_report_copies_lists_instead_of_aliasing_the_core() -> None:
core = ReportCore(summary="Summary.", topics=["one"])
report = assemble_report(core, _shots(), None, _info())
report = assemble_report(core, _shots(), None, _facts(), source=SOURCE)
core.topics.append("two")
assert report.topics == ["one"]
def test_metadata_from_info_flattens_the_media_fields() -> None:
metadata = metadata_from_info(_info(extra={}))
metadata = metadata_from_info(_facts(extra={}))
assert metadata == {
"path": "/media/sample.mp4",
"format": "mp4",
"video_codec": "h264",
"audio_codec": "aac",
@@ -464,6 +467,17 @@ def test_metadata_from_info_flattens_the_media_fields() -> None:
}
def test_metadata_from_info_omits_local_filenames() -> None:
facts = _facts(
extra={"ffprobe": {"format": {"filename": "/media/sample.mp4", "format_name": "mp4"}}}
)
metadata = metadata_from_info(facts)
assert "path" not in metadata
assert metadata["extra"] == {"ffprobe": {"format": {"format_name": "mp4"}}}
# --- agents (FunctionModel, no network) -----------------------------------
@@ -480,7 +494,11 @@ async def test_synthesise_report_assembles_a_video_report(
captured = _patch_model(monkeypatch, _canned_responder(canned))
report = await synthesise_report(
_shots(), _transcript(), _info(), options=LOCAL_SETTINGS.options_for("report")
_shots(),
_transcript(),
_facts(),
source=SOURCE,
options=LOCAL_SETTINGS.options_for("report"),
)
assert isinstance(report, VideoReport)
@@ -507,7 +525,11 @@ async def test_synthesise_report_truncates_a_long_transcript(
captured = _patch_model(monkeypatch, _canned_responder(canned))
await synthesise_report(
_shots(), _long_transcript(), _info(), options=LOCAL_SETTINGS.options_for("report")
_shots(),
_long_transcript(),
_facts(),
source=SOURCE,
options=LOCAL_SETTINGS.options_for("report"),
)
# A long transcript is map-reduced: one prompt per chunk, then a final reduce prompt
@@ -528,7 +550,7 @@ async def test_synthesise_report_uses_the_provider_budget_for_hosted_models(
def spy(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
info: MediaFacts,
*,
max_chars: int,
chunk_notes: str | None = None,
@@ -548,7 +570,11 @@ async def test_synthesise_report_uses_the_provider_budget_for_hosted_models(
captured = _patch_model(monkeypatch, _canned_responder(ReportCore(summary="Summary.")))
await synthesise_report(
_shots(), _transcript(), _info(), options=HOSTED_SETTINGS.options_for("report")
_shots(),
_transcript(),
_facts(),
source=SOURCE,
options=HOSTED_SETTINGS.options_for("report"),
)
assert seen["max_chars"] == PROVIDER_PROMPT_CHARS
@@ -563,12 +589,15 @@ async def test_synthesise_report_requires_grounding_material(
monkeypatch.setattr(llm, "build_model", explode)
with pytest.raises(ValueError, match="no shots and no transcript"):
await synthesise_report([], None, _info(), options=LOCAL_SETTINGS.options_for("report"))
await synthesise_report(
[], None, _facts(), source=SOURCE, options=LOCAL_SETTINGS.options_for("report")
)
with pytest.raises(ValueError, match="no shots and no transcript"):
await synthesise_report(
[],
Transcript(duration=1.0, segments=[]),
_info(),
_facts(),
source=SOURCE,
options=LOCAL_SETTINGS.options_for("report"),
)
@@ -649,7 +678,7 @@ async def test_prompt_budget_holds_for_an_oversized_fixed_part() -> None:
def test_build_synthesis_prompt_reports_prompt_info_as_a_value() -> None:
prompt, info = build_synthesis_prompt(
_shots(), _transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS
_shots(), _transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
)
assert info == synthesis.PromptInfo(
@@ -661,7 +690,7 @@ def test_build_synthesis_prompt_reports_prompt_info_as_a_value() -> None:
def test_build_synthesis_prompt_reports_transcript_truncation_as_a_value() -> None:
prompt, info = build_synthesis_prompt(
_shots(), _long_transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS
_shots(), _long_transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
)
assert info.truncated is True
@@ -683,7 +712,7 @@ def test_build_synthesis_prompt_counts_only_the_shots_that_fit() -> None:
for index in range(20)
]
prompt, info = build_synthesis_prompt(shots, _transcript(), _info(), max_chars=900)
prompt, info = build_synthesis_prompt(shots, _transcript(), _facts(), max_chars=900)
assert info.truncated is True
assert info.char_budget == 900
@@ -700,7 +729,8 @@ def test_assemble_report_exposes_prompt_info_truncation_without_an_agent_run() -
ReportCore(summary="Summary."),
_shots(),
None,
_info(),
_facts(),
source=SOURCE,
prompt_info={"prompt_info": prompt_info},
)
@@ -714,7 +744,11 @@ async def test_synthesise_report_records_prompt_info_in_metadata(
_patch_model(monkeypatch, _canned_responder(ReportCore(summary="Canned summary.")))
report = await synthesise_report(
_shots(), _transcript(), _info(), options=LOCAL_SETTINGS.options_for("report")
_shots(),
_transcript(),
_facts(),
source=SOURCE,
options=LOCAL_SETTINGS.options_for("report"),
)
prompt_info = report.metadata["synthesis"]["prompt_info"]
@@ -741,7 +775,11 @@ async def test_synthesise_report_records_a_truncated_prompt_in_metadata(
]
report = await synthesise_report(
shots, _transcript(), _info(), options=LOCAL_SETTINGS.options_for("report")
shots,
_transcript(),
_facts(),
source=SOURCE,
options=LOCAL_SETTINGS.options_for("report"),
)
assert report.metadata["synthesis"]["prompt_info"]["truncated"] is True