Files
alex 08a4af9b86 CONTRACTS: sync the ownership map and signatures to the branch (code-review S1, S2)
The two-axis review found the binding contract contradicted by the diff it was
supposed to describe: section 2's map omitted analysis.py's report/synthesis imports
and mcp_server.py's synthesis import, and section 3 still documented pre-diff
signatures (it was edited in this very diff, so the drift was avoidable).

Section 2 rows now list what each owner actually imports (analysis gains report.py +
synthesis/vision; the front doors gain diarize/transcribe/synthesis; the stage rows
drop config.py, which no stage imports since #5), and the foundation bullet describes
route_model/ModelEndpoints/LLAMA_SERVER_COMMAND.

Section 3 now matches the code: fetch(force=), extract_keyframes(namespace=,
keyframe_time), Transcriber.identity/readiness, the SttBackend/DiarizeBackend enums,
Diarizer/get_diarizer (diarize(wav), constructor-owned options), StageCache.cached_run,
Pipeline.__init__'s keyword limits, analysis shots/describe -> Artifacts, cached()'s
None contract, checked_int, and the llm block (route_model/build_model/
llama_server_models/llama_server_up/LLAMA_SERVER_COMMAND). vision.llama_server_up is
gone from the contract because it is gone from the code.

Sections 4-6 follow: MediaFacts.has_video, ShotsPayload, the enum-typed Settings
fields plus load_settings, and the llm routing record/endpoint protocol/startup
command.
2026-11-24 12:57:22 +00:00

47 KiB
Raw Permalink Blame History

CONTRACTS — video-analyse

Binding contract for every agent that implements a phase-2 module. Read PLAN.md first for intent, then this file for the exact API surface. Everything here was executed against the installed packages in .venv (Python 3.13.16) on the day this file was written — the snippets are copied from working code, not from memory or from web docs.

Post-v1 note (2026-11-23): phase 2 is complete and shipped. The foundation-file freeze is reopened — see ADR-0001 (docs/adr/0001-reopen-foundation-freeze.md) and §1.10. The per-file contracts in sections 4–6 remain the reference for what exists today; deliberate changes land through reviewed issues (#5, #6, #7 are the first).

Environment: uv, venv pinned by .python-version = 3.13, uv sync installs the deps in pyproject.toml (dev group included). uv.lock is committed state.


1. Coding standards

  1. Python 3.13, from __future__ import annotations at the top of every module, full type hints on public functions, pathlib.Path (never bare strings) for filesystem paths.
  2. Pydantic v2 only. All data crossing a module boundary is a model from video_analyse.models (or a BaseModel defined next to the stage entry point, e.g. IngestResult). Never return dicts/blobs where a model is specified.
  3. Async first. I/O-bound work is async def + httpx.AsyncClient. CPU-bound model work (faster-whisper, onnxruntime, sherpa-onnx, OpenCV) must be wrapped in await asyncio.to_thread(...) — never block the event loop.
  4. No network and no model downloads in tests. Unit tests construct objects; they must not hit the network or download weights. Anything needing a model is either skipped or dependency-injected with a fake. tests/conftest.py provides the synthetic sample_video fixture (10 s, 640×360 @ 12 fps, 440 Hz tone) and skips cleanly when ffmpeg is missing.
  5. Lazy imports for heavy deps. Import faster_whisper, onnx_asr, sherpa_onnx, cv2, scenedetect, yt_dlp inside the function/method that uses them (or inside the class __init__), so import video_analyse stays fast and optional extras stay optional.
  6. Lint/type/format gates: uv run ruff check . must pass (config in pyproject.toml: line-length 100, E,W,F,I,UP,B,C4,SIM,RUF, B008 ignored). uv run mypy src/ must pass ([tool.mypy] in pyproject.toml; per-module ignore_missing_imports only for untyped third-parties). Run uv run ruff format src tests before finishing; do not reformat PLAN.md/CONTRACTS.md (ruff formats their code fences and would create noise).
  7. Tests: uv run pytest tests/ -q must stay green. Add tests/test_<module>.py for your module. asyncio_mode = "auto" is on, so async def test_* needs no marker.
  8. Errors: raise ValueError/RuntimeError with actionable messages; the CLI layer maps them to typer exits. Never sys.exit() outside cli.py. Log through logging.getLogger(__name__).
  9. Secrets: never hard-code or require API keys in the local profile. Hosted providers read the standard env vars (DEEPSEEK_API_KEY, OPENROUTER_API_KEY, GROQ_API_KEY, OPENAI_API_KEY, OLLAMA_BASE_URL).
  10. Foundation files (src/video_analyse/__init__.py, models.py, config.py, llm.py, transcribe/base.py, pyproject.toml, tests/conftest.py, this file) were frozen during phase-2 construction so build agents could not drift from the spec. As of 2026-11-23 the freeze is reopened (ADR-0001): deliberate changes to these files are fine when they land through a reviewed issue that records the motivation (see #5, #6, #7). Undocumented ad-hoc edits remain off-limits; additive test fixtures in your own test files are always fine.
  11. No git commit unless the orchestrator asks for it.

2. Module ownership map (phase 2)

Owner Files (create/replace) Depends on
A — ingest & media src/video_analyse/ingest.py, media.py, tests/test_ingest.py, tests/test_media.py models.py, cache.py (ingest caches downloads)
B — speech-to-text transcribe/__init__.py (registry), transcribe/faster_whisper.py, transcribe/parakeet_onnx.py, transcribe/openai_transcriptions.py, srt.py, tests/test_transcribe_*.py, tests/test_srt.py transcribe/base.py, models.py
C — diarization diarize.py, model_assets.py, tests/test_diarize.py, tests/test_model_assets.py models.py (and its own model_assets.py)
D — vision, synthesis, report vision.py, synthesis.py, report.py, tests/test_vision.py, tests/test_synthesis.py, tests/test_report.py models.py, llm.py, config.py, cache.py (Q&A answer cache), report.py (timestamps)
E — cache & pipeline cache.py, pipeline.py, tests/test_cache.py, tests/test_pipeline.py all stage modules, cache.py, models.py, config.py
F — CLI & MCP (front doors) cli.py (replaces the stub), mcp_server.py, tests/test_cli.py, tests/test_mcp.py analysis.py, config.py, models.py, diarize.py, ingest.py (fetch), report.py, srt.py, synthesis.py, transcribe.py
G — analysis module analysis.py, tests/test_analysis.py pipeline.py, cache.py, media.py, config.py, models.py, report.py, synthesis.py (Q&A), vision.py (moment)
Foundation (frozen during phase 2; reopened post-v1 — ADR-0001) pyproject.toml, .python-version, .gitignore, __init__.py, models.py, config.py, llm.py, transcribe/base.py, tests/conftest.py, CONTRACTS.md —

Already implemented by the foundation and usable as-is:

  • video_analyse.models — every data model (section 4).
  • video_analyse.config.Settings — VA_* env config + resolved_stt(), resolved_vlm(), resolved_synthesis() (section 5).
  • video_analyse.llm.build_model(spec, *, settings) — pydantic-ai model factory, plus llm.route_model(spec), llm.llama_server_models(settings) / llm.llama_server_up(settings) and llm.LLAMA_SERVER_COMMAND (section 6). settings is any llm.ModelEndpoints value: the Settings bag or a stage's own frozen option value.
  • video_analyse.transcribe.base.Transcriber — the protocol to implement.
  • video_analyse.cli: placeholder va typer app with a version command + main(); agent F replaces the body while keeping app and main() importable from video_analyse.cli.

Cross-agent rules: stage functions are pure-ish (path/workdir in → model out), never read env directly (take Settings), and never assume another stage already ran (except the documented ordering in the Pipeline). Keyframe JPEGs go to workdir/keyframes/, audio to workdir/audio.wav.


3. SIGNATURES (verbatim contract — implement exactly these)

ingest.py: async def fetch(source: str, *, cache_dir: Path, quality: int = 1080, force: bool = False) -> IngestResult
  IngestResult(BaseModel): path: Path; info: dict[str, Any] = {}; downloaded: bool; title: str | None = None
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
media.py: async def detect_shots(path: Path, *, duration_hint: float | None = None, options: ShotOptions | None = None) -> list[Shot]
media.py: async def extract_keyframes(path: Path, shots: list[Shot], workdir: Path, *, width: int = 768, quality: int = 85, namespace: str | None = None) -> list[Shot]  # fills Shot.keyframe (JPEG in workdir/keyframes/[<namespace[:12]>/]), frame at Shot.keyframe_time else the midpoint
media.py: def dedup_keyframes(shots: list[Shot], *, threshold: int = 8) -> list[Shot]  # imagehash phash Hamming <= threshold dedup, fills Shot.phash
transcribe/base.py: class Transcriber(Protocol)
  async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript
  def identity(self) -> ModelIdentity  # backend, model, endpoint; hashed into the transcribe cache key
  def readiness(self) -> Readiness  # weights_present, weights_location, requirements; offline, never raises
transcribe/__init__.py: class SttBackend(StrEnum)  # parakeet | whisper | openai-transcriptions; STT_BACKENDS = their values
transcribe/__init__.py: class SttOptions(BaseModel)  # frozen value: backend (SttBackend), language, whisper_model, api_base_url, api_model, max_upload_bytes
transcribe/__init__.py: def get_transcriber(options: SttOptions) -> Transcriber
transcribe/faster_whisper.py: class FasterWhisperTranscriber(Transcriber)   # WhisperModel(options.whisper_model, device="cpu", compute_type="int8"); word_timestamps=True, vad_filter=True; run via asyncio.to_thread
transcribe/parakeet_onnx.py: class ParakeetOnnxTranscriber(Transcriber)   # onnx-asr nemo-parakeet-tdt-0.6b-v3 (language None) else -v2; int8; with_vad + with_timestamps per installed API; token->word merge
transcribe/openai_transcriptions.py: class OpenAITranscriptionsTranscriber(Transcriber)  # httpx multipart POST {base}/audio/transcriptions; verbose_json + timestamp_granularities word,segment; WAV->FLAC upload, chunk if >90MB with offset stitching; injectable httpx.AsyncClient for tests
srt.py: def render_srt(transcript: Transcript, *, speaker_labels: bool = False) -> str
diarize.py: class DiarizeBackend(StrEnum)  # sherpa | pyannote; DIARIZE_BACKENDS = their values
diarize.py: class DiarizeOptions(BaseModel)  # frozen value: backend (DiarizeBackend), cluster_threshold (no independent default), min_duration_on, min_duration_off, cache_dir, num_speakers=-1
diarize.py: class Diarizer(Protocol): def cache_params(self) -> dict[str, Any]; async def diarize(self, wav: Path) -> list[SpeakerTurn]  # constructor owns the option value; cache_params lists only the options it applies
diarize.py: def get_diarizer(options: DiarizeOptions) -> Diarizer
diarize.py: async def diarize_audio(wav: Path, options: DiarizeOptions) -> list[SpeakerTurn]
diarize.py: def attribute_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript  # word-midpoint containment; segment.speaker = majority of word speakers; fills transcript.speaker_turns
model_assets.py: async def ensure_model(name: str, *, cache_dir: Path) -> Path  # pinned-download cache for sherpa-onnx diarization assets
vision.py: class DescribeOptions(BaseModel)  # frozen value: vlm_model, llama_server_url, ollama_base_url, ollama_api_key
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: class TranscriptWindow(NamedTuple); def window_segments(transcript: Transcript | None, start: float, end: float) -> list[TranscriptWindow]  # the half-open [start, end) word-midpoint clipper both the shot prompt and moment use
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: 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()
cache.py: async def cached_run(path, model_type, runner, *, validate=None, force=False, on_hit=None) -> ModelT  # the one load -> miss -> run -> save policy
pipeline.py: class Pipeline  # __init__(settings: Settings, stages: Mapping[str, Callable] | None = None, *, max_shots: int = 64, min_scene_len: float = 0.6, ingest_quality: int = 1080); async def run(source: str, *, want: set[str], force: bool = False, progress: Callable[[ProgressEvent], None] | None = None) -> Artifacts
  async def cached(source: str, *, want: set[str] | None = None) -> Artifacts | None  # cache-only, current option keys
  stage order: probe -> audio -> transcribe -> diarize(attribute) -> shots -> describe -> report; diarize only when settings.diarize and "diarize" in want; describe needs shots; report needs transcript or shots
  ProgressEvent(stage: str, state: "start" | "cached" | "skipped" | "done", index: int, total: int)
analysis.py: class AnalysisOptions  # diarize: bool | None = None; describe: bool = True; force: bool = False; max_shots: int = Field(64, ge=1); language: str | None = None; no_cache: bool = False; ingest_quality: int = 1080
analysis.py: async def analyse(source: str, options: AnalysisOptions, *, settings: Settings, progress: Callable[[ProgressEvent], None] | None = None) -> Artifacts
analysis.py: async def transcript(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Transcript
analysis.py: async def shots(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Artifacts  # the run's artifacts; the shot list is artifacts.shots
analysis.py: async def describe(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Artifacts  # descriptions on artifacts.shots
analysis.py: async def probe(source: str, *, settings: Settings, progress: ... = None) -> Artifacts  # MediaFacts + MediaRef
analysis.py: async def ask(source: str, question: str, options: AnalysisOptions, *, settings: Settings, allow_analysis: bool = False) -> AnswerResult
analysis.py: async def moment(source: str, t_start: float, t_end: float, options: AnalysisOptions, *, settings: Settings, max_frames: int = 4, width: int = 768) -> MomentResult
analysis.py: async def frame(source: str, timestamp: float, *, settings: Settings, width: int = 768) -> FrameResult
analysis.py: async def cached(source: str, *, settings: Settings, options: AnalysisOptions | None = None) -> Artifacts | None  # None when nothing is cached (an uncached URL has no resolved hash)
analysis.py: def checked_int(value: object, name: str, *, minimum: int, maximum: int | None = None) -> int  # the shared bounded-integer guard both doors use
  stage callables take option values (SttOptions, DiarizeOptions, ShotOptions, DescribeOptions, ReportOptions), never Settings; lazy-import real stages inside methods; injectable stages dict enables unit tests with fakes; per-stage caching + skip; force re-runs requested stages and downstream; URL source -> fetch first
llm.py: class ModelEndpoints(Protocol)  # llama_server_url; ollama_base_url | None; ollama_api_key | None (Settings or a stage's frozen options)
llm.py: def route_model(spec: str) -> ModelRoute  # spec, model, local, prefix, provider, credential_env: the one routing fact behind vision/synthesis/doctor
llm.py: def build_model(spec: str, *, settings: ModelEndpoints) -> Model
llm.py: async def llama_server_models(settings: ModelEndpoints) -> list[str] | None  # None when unreachable/malformed
llm.py: async def llama_server_up(settings: ModelEndpoints) -> bool
llm.py: LLAMA_SERVER_COMMAND: str  # the exact local llama-server startup command (vision hint, va doctor)
cli.py: typer app "va": fetch, probe, transcribe, diarize, shots, describe, analyse, moment, ask, doctor, serve-mcp (+ main() entry); argv -> AnalysisOptions, output shaping only
mcp_server.py: FastMCP("video-analyse") with exactly 6 tools: transcribe_video, extract_keyframes, analyze_video, analyze_moment, get_frame_at, ask_video; tool args -> AnalysisOptions, output shaping only; run() stdio default

4. models.py — field-by-field contract (implemented, frozen)

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] = {})
           # computed property: has_video (a width or height was probed)
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)
Transcript(language: str | None = None, duration: float, segments: list[Segment],
           speaker_turns: list[SpeakerTurn] = [], backend: str | None = None,
           model: str | None = None)
Shot(index: int, start: float, end: float, keyframe: Path | None = None,
     phash: str | None = None, transcript_slice: str = "",
     description: ShotDescription | None = None)
ShotDescription(summary: str, on_screen_text: str | None = None,
                shot_type: Literal["wide", "medium", "close-up", "screen", "other"],
                people: list[str] = [], notable_objects: list[str] = [],
                setting: str | None = None)
ShotsPayload(source: str, workdir: Path, shots: list[Shot] = [])   # the shots outcome as both doors render it
Highlight(start: float, end: float, description: str)
ReportCore(title: str | None = None, summary: str, topics: list[str] = [],
           people: list[str] = [], highlights: list[Highlight] = [])
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: 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 None, so only the semantically required fields must be passed. Shot.description is a forward reference resolved with Shot.model_rebuild() at module import; ShotDescription is therefore safe to use from vision.py. Mutable defaults ([], {}) are safe: pydantic copies 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)

from video_analyse.config import Settings

s = Settings()  # reads VA_* env vars, env_prefix="VA_", case-insensitive
s.profile  # "local" | "hosted"           (VA_PROFILE)
s.cache_dir  # Path, "~/..." expanded       (VA_CACHE_DIR)
s.language  # None => auto, "en" => Parakeet v2 (VA_LANGUAGE)
s.stt_backend  # None | SttBackend ("parakeet" | "whisper" | "openai-transcriptions")
s.stt_api_base_url  # https://api.groq.com/openai/v1
s.stt_api_model  # whisper-large-v3-turbo
s.whisper_model  # large-v3-turbo
s.diarize  # bool, True    (VA_DIARIZE=false works)
s.diarize_backend  # DiarizeBackend ("sherpa" | "pyannote")
s.diarize_cluster_threshold  # float, 0.7
s.diarize_min_duration_on  # float, 0.3 (sherpa)
s.diarize_min_duration_off  # float, 0.5 (sherpa)
s.vlm_model  # None or a model spec (see llm.build_model)
s.llama_server_url  # http://127.0.0.1:8080/v1
s.synthesis_model  # None or a model spec

s.resolved_stt()  # alias of s.options_for("stt").backend
s.resolved_vlm()  # explicit vlm_model, else "local:Qwen3-VL-4B-Instruct" / "deepseek:deepseek-flash"
s.resolved_synthesis()  # same rule as resolved_vlm

# config.py: the front doors' one construction path. Builds Settings once at a command/tool
# entry point; only the explicit (non-None) profile fields override VA_*/TOML. Behavioural flags
# (diarize, language, shot caps, cache policy) are AnalysisOptions fields, never settings.
load_settings(stt_backend=..., diarize_backend=..., vlm_model=...)

s.options_for("stt")       # SttOptions (backend rule: explicit stt_backend, else a non-default
                           # whisper_model selects "whisper", else the profile default)
s.options_for("diarize")   # DiarizeOptions; fills diarize_cluster_threshold (the single 0.7),
                           # diarize_min_duration_on/off and cache_dir
s.options_for("shots")     # media.ShotOptions from the shot_sampling block
s.options_for("describe")  # vision.DescribeOptions from resolved_vlm() + llama/ollama endpoints
s.options_for("report")    # synthesis.ReportOptions from resolved_synthesis() + endpoints

Settings(profile="hosted", ...) also works as keyword construction — use that in tests together with monkeypatch.delenv for any VA_* variable you care about (see tests/test_config.py). Module constants: LOCAL_VLM_MODEL, HOSTED_VLM_MODEL, DEFAULT_CACHE_DIR, DEFAULT_WHISPER_MODEL.


6. llm.py (implemented, frozen) + verified pydantic-ai facts

from video_analyse.config import Settings
from video_analyse.llm import (
    LLAMA_SERVER_COMMAND,
    ModelEndpoints,
    build_model,
    llama_server_models,
    llama_server_up,
    route_model,
)

settings = Settings()
route = route_model("deepseek:deepseek-flash")  # .spec/.model/.local/.prefix/.provider/.credential_env
route.credential_env  # "DEEPSEEK_API_KEY" - the one routing fact vision/synthesis/doctor share
model = build_model("local:Qwen3-VL-4B-Instruct", settings=settings)  # llama-server
model = build_model("Qwen3-VL-4B-Instruct", settings=settings)  # bare name -> llama-server
model = build_model("deepseek:deepseek-flash", settings=settings)  # needs DEEPSEEK_API_KEY
model = build_model("ollama:deepseek-v4.1-flash:1017", settings=settings)  # Ollama Cloud
model = build_model(settings.resolved_vlm(), settings=settings)
up = await llama_server_up(settings)  # GET {url}/models, 2 s; never raises
served = await llama_server_models(settings)  # list[str] | None when unreachable/malformed
LLAMA_SERVER_COMMAND  # exact startup command shown by the vision hint and `va doctor`

settings in every call above is any llm.ModelEndpoints value: the Settings bag from a front door, or the frozen DescribeOptions/ReportOptions a stage already holds.

Resolution rules: local:<name> → OpenAIChatModel(name, provider=OpenAICompatibleProvider( "llama-server", base_url=settings.llama_server_url, api_key="local")); a bare name (or an unknown vendor:name prefix, e.g. qwen3-vl:4b) → the same local model with the full spec as the model name; a prefix: that pydantic-ai knows → pydantic_ai.models.infer_model(spec); "test" → infer_model("test") (pydantic-ai TestModel). Provider detection uses pydantic_ai.providers.infer_provider_class(prefix) and treats ValueError as "not a provider". llama_server_up returns False for connection errors, timeouts and malformed URLs alike (httpx.HTTPError catch-all, verified).

6.1 pydantic-ai 2.63.0 — exact, verified import paths

from pydantic_ai import Agent, BinaryImage, BinaryContent, ImageUrl, ModelSettings
from pydantic_ai import NativeOutput, ToolOutput, PromptedOutput  # output modes
from pydantic_ai.models import Model, infer_model  # model factory / typing
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
from pydantic_ai.providers import infer_provider_class  # provider discovery
from pydantic_ai.models.test import TestModel  # NOT top-level
from pydantic_ai.models.function import FunctionModel, AgentInfo  # NOT top-level

TestModel and FunctionModel are not re-exported from pydantic_ai — importing them from the package root raises ImportError.

Construction (no network):

model = OpenAIChatModel(
    "qwen",
    provider=OpenAICompatibleProvider(
        "llama-server", base_url="http://127.0.0.1:8080/v1", api_key="local"
    ),
)
model.model_name  # 'qwen'
model.system  # 'llama-server'   (provider name)
model.base_url  # 'http://127.0.0.1:8080/v1'
model.client.base_url  # 'http://127.0.0.1:8080/v1/'  (AsyncOpenAI client, trailing slash)

Model-string inference (infer_model(model: Model | KnownModelName | str) -> Model):

spec result extra requirement
infer_model("deepseek:deepseek-flash") OpenAIChatModel, .system == "deepseek" DEEPSEEK_API_KEY
infer_model("openrouter:deepseek/deepseek-v4.1-flash-1017") OpenRouterModel, .system == "openrouter" OPENROUTER_API_KEY
infer_model("ollama:qwen3-vl:4b") OllamaModel, .system == "ollama" OLLAMA_BASE_URL
infer_model("test") TestModel —
infer_model("some-bare-name") raises UserError: Unknown model: ... —

Consequence: never pass a bare model name to infer_model; that is exactly why build_model routes bare names to llama-server. Missing provider keys raise pydantic_ai.UserError at construction time (no network request is made), so tests can monkeypatch.setenv("DEEPSEEK_API_KEY", "x").

ollama: specs are special-cased in build_model: it constructs OllamaModel(name, provider=OllamaProvider(base_url=..., api_key=...)) where the endpoint is Settings.ollama_base_url > OLLAMA_BASE_URL env > https://ollama.com/v1 (Ollama Cloud) and the key is Settings.ollama_api_key > OLLAMA_API_KEY env; a non-local endpoint without a key raises ValueError naming the config.toml option. Local daemons (localhost:11434) need no key. Cloud paths auto-disable supports_json_schema_output (verified in pydantic_ai/models/ollama.py), so structured output uses ToolOutput — the default in our agents.

Agent construction (verified, no request is made):

agent = Agent(
    model,
    output_type=ShotDescription,  # a pydantic BaseModel class
    model_settings={"temperature": 0.1, "max_tokens": 400, "max_retries": 0},
    retries={"output": 2},  # AgentRetries dict
    system_prompt="Describe only what is visible.",
)
agent.output_type  # <class 'ShotDescription'>
agent.model_settings["max_retries"]  # 0

ModelSettings keys seen in 2.63.0 include max_tokens, temperature, top_p, top_k, timeout, request_timeout, max_retries, parallel_tool_calls, tool_choice, seed, presence_penalty, frequency_penalty. Multimodal prompt (list of parts):

from pydantic_ai import BinaryImage

img = BinaryImage(data=jpeg_bytes, media_type="image/jpeg")  # dataclass: data, media_type
result = await agent.run(["Describe this frame.", img])
result.output  # validated ShotDescription

Verified offline: Agent(TestModel(), output_type=SomeBaseModel).run("...") returns a validated SomeBaseModel (structured output works with TestModel), and a BinaryImage part in a list prompt is accepted. Agent init parameters of interest: model, output_type, instructions, system_prompt, model_settings, retries, tools, deps_type. The one-time startup banner is silenced with PYDANTIC_AI_NO_BANNER=1 (set in tests/conftest.py).

Structured-output notes from PLAN §3.3 that still apply: default output_type=<BaseModel> is a ToolOutput → llama-server needs --jinja; alternatives are NativeOutput and PromptedOutput (top-level imports, verified). Keep schemas flat and set generous max_tokens.


7. Verified dependency snippets

Installed versions (.venv, Python 3.13.16): pydantic 2.14.2 · pydantic-ai 2.63.0 · pydantic-settings 2.16.2 · typer 0.27.3 · rich 15.0.0 · httpx 0.28.1 · faster-whisper 1.2.1 · onnx-asr 0.12.0 (onnxruntime 1.31.1) · sherpa-onnx 2.0.1 · scenedetect 0.7.2 · opencv-python-headless 5.0.0.93 · imagehash 4.3.2 · pillow 13.0.0 · yt-dlp 2026.10.26 · fastmcp 4.1.4 · numpy 2.5.4 · av 19.0.2 · pytest 9.2.0 · pytest-asyncio 1.4.1 · ruff 0.17.3.

7.1 fastmcp 4.1.4 — server, in-memory client, image content

from fastmcp import FastMCP, Client
from fastmcp.utilities.types import Image  # image content helper

mcp = FastMCP("video-analyse")


@mcp.tool
async def add(a: int, b: int) -> int:  # sync or async tools both work
    """Add two ints."""
    return a + b


@mcp.tool
def frame() -> Image:  # returning Image => ImageContent block
    return Image(data=jpeg_bytes, format="jpeg")  # or format="png"; kwargs: data=, format=


async def main() -> None:
    async with Client(mcp) as client:  # in-memory transport, fully offline
        tools = await client.list_tools()  # [Tool(name='add', ...), ...]
        res = await client.call_tool("add", {"a": 2, "b": 3})
        res.data  # 5 (Python value; pydantic models come back as dicts)
        res.structured_content  # {'result': 5}
        res.content  # [TextContent(...)] / [ImageContent(type='image', mime_type='image/png', ...)]


mcp.run()  # stdio is the default transport
mcp.run(transport="http", host="127.0.0.1", port=8000)  # opt-in HTTP

Verified offline: in-memory Client(mcp) lists tools, calls async and sync tools, returns dict payloads (structured_content mirrors them) and Image results as ImageContent. ImageContent exposes .mime_type (MCP SDK v2 name); .mimeType still works but is deprecated. Image ctor: Image(path=None, data=None, format=None, annotations=None) — pass data=<bytes> plus format="jpeg"|"png". mcp.get_tool(name) is a coroutine (await mcp.get_tool("f")), verified; there is no get_tools() on the server object.

7.2 scenedetect 0.7.2 (+ OpenCV backend)

from scenedetect import open_video, SceneManager, AdaptiveDetector, ContentDetector
from scenedetect import detect, FrameTimecode  # convenience helper / timecodes
from scenedetect.scene_manager import save_images

video = open_video(str(path))  # backend='opencv' default -> VideoStreamCv2
video.frame_rate, video.frame_size, video.duration.seconds, video.duration.frame_num
# fixture: 12.0, (640, 360), 10.0, 120

sm = SceneManager()
sm.add_detector(
    ContentDetector(threshold=10.0, min_scene_len=0.6)
)  # min_scene_len: frames or seconds
sm.detect_scenes(video, show_progress=False)
scenes = sm.get_scene_list()  # list[tuple[FrameTimecode, FrameTimecode]]
start_s, end_s = scenes[0][0].seconds, scenes[0][1].seconds

Verified facts that change how detect_shots must be written:

  • SceneManager.get_scene_list(start_in_scene: bool = False) returns only detected cuts and returns [] when nothing is detected — you must synthesise a single [0, duration] shot yourself (use start_in_scene=True or an explicit fallback).
  • On the synthetic testsrc2 fixture, AdaptiveDetector() (defaults) and ContentDetector() (threshold 27) find 0 cuts; ContentDetector(threshold=10.0) finds one at 7.5 s. So the fixture is a degenerate case: detect_shots must handle empty detection and tests must not assume ≥1 cut. detect(path, detector) returns the same (possibly empty) list.
  • The adaptive sampling (added after v1): shots longer than subdivide_after_seconds (default 20 s) are subdivided — ShotOptions.sampling="adaptive" (default) computes a frame-difference activity curve (media.activity_curve, one ffmpeg rawvideo pass at 2 fps, 64x36 gray) and places segment boundaries at equal cumulative activity quantiles, with each segment's keyframe at its calmest sample and a relative Shot.activity used in the vision prompt; "uniform" uses equal intervals (midpoint keyframes); "scene" never subdivides. Shot gained optional keyframe_time and activity fields. detect_shots is the I/O adapter (cuts + curve); the pure plan_shots owns segmentation, subdivision and the global max_shots budget, which is applied after subdivision. The pipeline passes the three Settings.shot_sampling-block values through and includes them in the shots stage cache key.
  • In 0.7.2 use the properties FrameTimecode.seconds, .frame_num, .frame_rate; the get_seconds()/get_frames() getters still work but emit DeprecationWarning.
  • save_images(scene_list, video, num_images=1, output_dir=..., width=..., image_extension='jpg', image_name_template=..., encoder_param=95, scale=..., threading=True) exists if you prefer it over calling ffmpeg per keyframe; note it returns dict[int, list[str]].
  • import cv2 works from opencv-python-headless 5.0.0.93 (cv2.__version__ == '5.0.0'); scenedetect.backends.AVAILABLE_BACKENDS / VideoStreamCv2 / VideoStreamAv are present.

7.3 ffmpeg / ffprobe commands (verified on the fixture)

ffmpeg -y -i in.mp4 -vn -ac 1 -ar 16000 -c:a pcm_s16le workdir/audio.wav   # 16000 Hz, 1 ch, 16 bit
ffmpeg -y -ss <midpoint> -i in.mp4 -frames:v 1 -vf scale=768:-2 -q:v 3 workdir/keyframes/000.jpg
ffprobe -v quiet -show_format -show_streams -of json in.mp4

ffprobe JSON: format.duration/.format_name/.size/.bit_rate/.tags, and per stream codec_type, codec_name, width/height, r_frame_rate (e.g. "12/1"), channels, duration. Audio-only streams have no width/height and r_frame_rate == "0/0" — never divide by it. ffmpeg is at /usr/bin/ffmpeg on this machine (n9.x).

7.4 imagehash 4.3.2 + Pillow 13.0.0

import imagehash
from PIL import Image

h = imagehash.phash(Image.open("frame.jpg"))  # phash(image, hash_size=8, highfreq_factor=4)
str(h)  # 16 hex chars, e.g. '8000000000000000'  -> Shot.phash
h - h2  # Hamming distance int (ImageHash.__sub__)

ImageHash has no public query methods beyond dunder ops (-, ==, hash, str); persist the hex string in Shot.phash and rebuild with imagehash.hex_to_hash(s) when comparing across runs.

7.5 faster-whisper 1.2.1 (do not load a model in tests)

from faster_whisper import WhisperModel

model = WhisperModel(settings.whisper_model, device="cpu", compute_type="int8")
# __init__(model_size_or_path: str, device='auto', device_index=0, compute_type='default',
#          cpu_threads=0, num_workers=1, download_root=None, local_files_only=False,
#          files=None, revision=None, use_auth_token=None, **model_kwargs)

segments, info = model.transcribe(
    str(wav),
    language=language,
    word_timestamps=True,
    vad_filter=True,
    beam_size=5,
    condition_on_previous_text=False,
)
# returns (Iterable[faster_whisper.transcribe.Segment], TranscriptionInfo) -- a *generator*:
# iterate it inside asyncio.to_thread and build the Transcript there.
# Segment: .start .end .text .words (list[Word]) ; each word: .word .start .end .probability
# info: .language .language_probability .duration

7.6 onnx-asr 0.12.0 (Parakeet TDT; no downloads)

import onnx_asr
from onnx_asr.adapters import TimestampedResultsAsrAdapter, TimestampedSegmentResultsAsrAdapter

wav_model = onnx_asr.load_model(
    "nemo-parakeet-tdt-0.6b-v3", quantization="int8"
)  # v2 when language == "en"
vad = onnx_asr.load_vad("silero")  # load_vad(model="silero", path=None, *, quantization=...)
rec = wav_model.with_vad(vad).with_timestamps()  # ORDER MATTERS: with_vad(...) first
for seg in rec.recognize(str(wav)):  # single input -> iterator of segments
    seg.start, seg.end, seg.text  # absolute seconds, absolute text
    seg.timestamps  # list[float] token times RELATIVE to seg.start
    seg.tokens, seg.logprobs  # list[str] tokens (SentencePiece, '▁' -> ' ')

Verified from the installed source (site-packages/onnx_asr/):

  • load_model(model, path=None, *, quantization=None, sess_options=None, providers=None, ...) -> onnx_asr.adapters.TextResultsAsrAdapter. quantization="int8" resolves the model.int8.onnx file (_get_model_files builds f"model?{quantization}.onnx").
  • Model IDs are fixed: "nemo-parakeet-tdt-0.6b-v2" (English) and "nemo-parakeet-tdt-0.6b-v3" (multilingual). They map to HF repos istupakov/parakeet-tdt-0.6b-v2-onnx / -v3-onnx in resolver.model_repos; the hub extra (huggingface-hub) performs the download on first use. Pass path= (a local model directory) to stay offline.
  • TextResultsAsrAdapter.with_timestamps() -> TimestampedResultsAsrAdapter; also with_vad(vad, **VadOptions) -> SegmentResultsAsrAdapter, which itself has .with_timestamps() -> TimestampedSegmentResultsAsrAdapter. Adapters.recognize(waveform, *, sample_rate=16_000, channel=None, language=None, ...) accepts a path, a np.float32 array ([-1, 1]) or a list of either.
  • Result dataclasses: onnx_asr.asr.TimestampedResult(text, timestamps, tokens, logprobs) and onnx_asr.vad.SegmentResult(start, end, text); TimestampedSegmentResult inherits both. Only VAD mode exposes absolute segment start/end — token timestamps are chunk-relative, so word times = seg.start + token_time (and you must split tokens on the '▁'/leading-space boundary to merge SentencePiece tokens into words).
  • Return shape of recognize: for a single waveform the adapter returns next(...), so a plain timestamped adapter yields one TimestampedResult while a VAD adapter yields an iterator of TimestampedSegmentResult (for a list input you get a list of those). Iterate it — do not index it or call len() on it.
  • VadOptions (TypedDict): batch_size, threshold, neg_threshold, min_speech_duration_ms, max_speech_duration_s, min_silence_duration_ms, speech_pad_ms. Use e.g. max_speech_duration_s=20.0 to respect the model's 20-30 s cap.
  • RecognizeOptions: language (Whisper/Canary only — ignored by Parakeet), target_language, pnc. For Parakeet, language=None means auto (v3); choose -v2 when language == "en".

7.7 sherpa-onnx 2.0.1 — offline speaker diarization

import sherpa_onnx
from sherpa_onnx import (
    FastClusteringConfig,
    OfflineSpeakerDiarization,
    OfflineSpeakerDiarizationConfig,
    OfflineSpeakerSegmentationModelConfig,
    OfflineSpeakerSegmentationPyannoteModelConfig,
    SpeakerEmbeddingExtractorConfig,
)

config = OfflineSpeakerDiarizationConfig(
    segmentation=OfflineSpeakerSegmentationModelConfig(
        pyannote=OfflineSpeakerSegmentationPyannoteModelConfig(
            model=str(seg_model),  # e.g. sherpa-onnx-pyannote-segmentation-3-0/model.onnx
            window_shift_ratio=0.1,  # default 0.1; (0,1]
        ),
        num_threads=4,
        debug=False,
        provider="cpu",
    ),
    embedding=SpeakerEmbeddingExtractorConfig(
        model=str(emb_model), num_threads=4, debug=False, provider="cpu"
    ),
    clustering=FastClusteringConfig(num_clusters=-1, threshold=0.5, compute_confidence=False),
    min_duration_on=0.3,  # drop segments shorter than this (s)
    min_duration_off=0.5,  # merge gaps shorter than this (s)
)
sd = OfflineSpeakerDiarization(config)  # ctor takes the config only
sd.sample_rate  # expected input rate (16000 for the pyannote model)
result = sd.process(
    samples
)  # samples: 1-D float32 Sequence in [-1, 1]; optional callback(processed, total)
for seg in result.sort_by_start_time():  # or result.sort_by_speaker()
    seg.start, seg.end, seg.speaker  # speaker is an int cluster id -> map to "S1", "S2", ...
    seg.confidence  # -2 when unavailable (compute_confidence=False)
result.num_speakers, result.num_segments
sd.set_config(config)  # re-tune clustering only

Verified: the config objects above construct and expose exactly those fields (validate() returns False and logs when a file path does not exist — construction itself does not load). FastClusteringConfig(num_clusters>0) bypasses the threshold. provider="cpu". Asset filenames referenced in the installed C header (c-api.h): segmentation ./sherpa-onnx-pyannote-segmentation-3-0/model.onnx, embedding ./3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx (also documented: 3dspeaker_speech_campplus_sv_zh-cn_16k-common.onnx). Pin whatever you download in model_assets.ensure_model and record the URL + sha256 there.

sherpa_onnx.write_wave(filename, samples, sample_rate) -> bool exists, but read_wave does not in the Python API of 2.0.1: read the 16 kHz WAV with the stdlib wave module and convert np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0.

7.8 yt-dlp 2026.10.26

import yt_dlp
from yt_dlp import YoutubeDL
from yt_dlp.utils import DownloadError

opts = {
    "format": "bv*[height<=1080]+ba/b",  # single analysis-friendly file
    "outtmpl": "%(title)s [%(id)s].%(ext)s",
    "noplaylist": True,
    "writeinfojson": True,  # sidecar .info.json -> IngestResult.info
    "paths": {"home": str(cache_dir)},
    "quiet": True,
    "no_warnings": True,
}
with YoutubeDL(opts) as ydl:  # ctor is offline; extract_info(download=True) is not
    info = ydl.extract_info(url, download=True)
    local_path = ydl.prepare_filename(info)  # use ydl.sanitize_info(info) before storing

Run the blocking extract_info via asyncio.to_thread. yt_dlp.version.__version__ gives the version string. YoutubeDL.__init__(params=None, auto_init=True); extract_info(url, download=True, ie_key=None, extra_info=None, process=True, force_generic_extractor=False).

7.9 typer 0.27.3 + rich 15.0.0

import typer
from typer.testing import CliRunner

app = typer.Typer(name="va", help="...")


@app.callback()
def _root() -> None:
    """Forces group mode so subcommands work even with few commands."""


@app.command()
def probe(src: str, json_out: bool = typer.Option(False, "--json")) -> None: ...


def main() -> None:  # [project.scripts] va = "video_analyse.cli:main"
    app()


result = CliRunner().invoke(app, ["probe", "x.mp4"])  # result.exit_code, result.stdout

va --help and va version are verified working against the installed console script. Note: with exactly one command and no callback typer collapses the app into a single command (va <args> instead of va <cmd> <args>); the existing @app.callback() keeps group mode — keep it when you replace cli.py. Use rich.console.Console for human output.

7.10 httpx 0.28.1 (hosted STT)

async with httpx.AsyncClient(timeout=120.0) as client:
    resp = await client.post(
        "https://api.groq.com/openai/v1/audio/transcriptions",
        headers={"Authorization": f"Bearer {api_key}"},
        files={"file": ("audio.flac", flac_bytes, "audio/flac")},
        data={
            "model": settings.stt_api_model,
            "response_format": "verbose_json",
            "timestamp_granularities[]": "word",
        },
    )
    resp.raise_for_status()
    payload = resp.json()  # .text, .language, .segments[{start,end,text}], .words[{word,start,end}]

timestamp_granularities must be sent as repeated timestamp_granularities[] form fields (httpx serialises the dict entries as-is; this field name comes from the OpenAI/Groq API docs, not from local verification). Inject the client (client: httpx.AsyncClient | None = None) so tests can use httpx.MockTransport. Convert WAV→FLAC for upload with ffmpeg -i audio.wav -c:a flac -ar 16000 -ac 1 out.flac.


8. Foundation state / verification log

  • uv python pin 3.13 → .python-version = 3.13; uv sync succeeded with zero version-pin changes (no deviation from the requested pins).
  • uv run va --help / va version → OK (placeholder CLI).
  • uv run pytest tests/ -q → 32 passed (models, config, llm; sample_video fixture verified to generate the 10 s MP4).
  • uv run ruff check . → clean.
  • Verified offline, no downloads, no sockets opened except the deliberate dead-port probes: pydantic-ai model/agent construction + TestModel structured run + BinaryImage prompt part; fastmcp in-memory client (text, dict and image tools); scenedetect detection on the fixture; imagehash on a generated PIL image and a real JPEG keyframe; faster-whisper import/signatures; onnx-asr source inspection; sherpa-onnx config construction; yt-dlp option dict; typer CliRunner; ffmpeg/ffprobe audio + frame extraction.

9. Deviations & decisions (recorded)

  1. Nullable model fields default to None (section 4) — the literal block lists some of them without defaults; adding = None only loosens the contract and keeps phase-2 construction ergonomic. All other names/types/defaults are exactly as specified.
  2. pyproject.toml additions beyond the requested keys: [tool.ruff.lint] select/ignore lists, [tool.ruff.lint.per-file-ignores] for tests/**, and asyncio_default_fixture_loop_scope = "function" in [tool.pytest.ini_options] (silences the pytest-asyncio 1.4 deprecation warning; behaviour unchanged with asyncio_mode = "auto"). readme = "PLAN.md", license, authors and [project.optional-dependencies] pyannote are set so the wheel builds.
  3. cli.py is not empty: an empty typer.Typer() makes va --help fail and va version ambiguous (typer collapses single-command apps). The stub has a root callback (group mode) and a version command so M0's acceptance criterion (uv run va --help works) holds. Agent F replaces the body; keep app, main() and the @app.callback().
  4. onnx-asr model IDs / quantization and the with_vad(...).with_timestamps() ordering were read from the installed source rather than the docs; onnx_asr 0.12.0 has no read_wave equivalent for diarization either (see 7.7).
  5. AdaptiveDetector yields 0 cuts on the synthetic fixture (see 7.2) — detect_shots must fall back to a single full-length shot, and media tests should assert on invariants (coverage of [0, duration], ordering, no overlap) instead of a cut count.
  6. Unpinned transitive deps resolved higher than the plan text assumed: scenedetect 0.7.2, sherpa-onnx 2.0.1, opencv-python-headless/opencv-python 5.0.0.93, pillow 13.0.0, yt-dlp 2026.10.26, fastmcp 4.1.4 — all satisfy the requested lower bounds; APIs above are the ones actually installed.
  7. Integration addition to Settings.resolved_stt() (behaviour, not signature): when stt_backend is unset and whisper_model was explicitly provided (env VA_WHISPER_MODEL or a constructor kwarg), the resolution is whisper rather than the profile default. This keeps VA_WHISPER_MODEL=tiny va transcribe meaningful; VA_STT_BACKEND=parakeet still overrides it. Documented in README.md; covered by tests/test_config.py.
  8. faster-whisper/PyAV 19 workaround: faster-whisper 1.2.1 calls av.open(..., metadata_errors=...), a keyword PyAV 19.0.2 removed (TypeError before any audio is decoded). transcribe/faster_whisper.py now decodes the stage's 16 kHz mono s16le WAV with the stdlib wave module and hands faster-whisper a float32 numpy array (load_wav_samples); non-conforming inputs raise an actionable ValueError.
  9. pyproject.toml readme moved from PLAN.md to README.md once the README existed.