Files
alex 83a4785524 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
2026-11-24 00:04:10 +00:00

35 KiB
Raw Permalink Blame History

video-analyse — Research & Plan

Status: v1 implemented (2026-10-30) — all stages, CLI, MCP server built; 316 tests green; STT/diarization verified with real models, vision/synthesis verified offline (TestModel) — see README “Limitations” · Date: 2026-10-30 Goal of this document: record the research findings and the agreed plan for building the toolkit.


1. What we're building

A local-first, agent-friendly video analysis toolkit: give it a video file or URL, get back a word-level transcript, per-shot visual descriptions, and a combined structured report (JSON/Markdown) — with every model running locally, no API keys.

Guiding principles:

  1. Agent-first: everything is usable three ways — Python library, CLI (va), and an MCP server so agents (e.g. pi) can call the tools directly. Structured pydantic outputs everywhere, never free-text blobs.
  2. Local by default, hosted optional: every model stage (STT, vision, synthesis) can run locally or hosted — fully-local (zero API keys), fully-hosted, and mixed setups are all supported (§3.3.1). Defaults stay fully local; all local inference runs on this machine (CPU-only today; §2).
  3. Pipeline with cacheable stages: transcription and vision are expensive on CPU, so every stage writes a hashed artifact and is skipped when inputs haven't changed. Long videos are processed chunk-wise.
  4. Pluggable models: STT and VLM are behind small protocols; backends can be swapped via config without touching pipeline code.

Non-goals for v1: GPU-cluster scale-out, video generation/editing, real-time/streaming analysis. Speaker diarization is in scope for v1 (changed from the original post-v1 plan): sherpa-onnx default backend — see §3.1 and M3.


2. Environment (verified on this machine)

Item Value
OS / CPU Arch Linux x86_64, kernel 7.2.11 · Intel Core Ultra X7 358H, 16 cores
GPU None discrete; integrated Intel Arc B390 (Panther Lake, Vulkan-capable, shared RAM)
RAM / disk 30 GB · ~789 GB free
Python / uv 3.14.8 system · uv 0.12.23
ffmpeg n9.0.2 installed (yt-dlp, llama.cpp, Ollama: not installed)
Existing STT Pi Voice dictation runs transcribe-cpp (whisper.cpp-family) with cached parakeet-unified-en-0.6b Q8_0 GGUF (~700 MB, English)

Implication: inference is CPU-only initially. The plan selects models for the CPU sweet spot (≤4B VLM quantized, Parakeet 0.6B STT) and treats the iGPU as a later llama.cpp-Vulkan upgrade.


3. Research findings

Research was done via parallel agents with web access (2026-10-30), then load-bearing claims were spot-checked against primary sources (docs pages / GitHub releases / PyPI). Sources are listed inline and in §9.

3.1 Speech-to-text

Recommendation (decided): Parakeet TDT 0.6B v3 (multilingual default) via onnx-asr as primary + faster-whisper large-v3-turbo as fallback, behind one Transcriber protocol.

  • onnx-asr (istupakov, active — 0.12.0 2026-07, ~10k downloads/day): torch-free ONNX runtime for Parakeet TDT v2 (En) / v3 (25 European languages) and Canary. Pure-Python deps (numpy + onnxruntime + huggingface-hub), Python 3.10–3.14 supported, int8 quantization ≈ WER-neutral, token-level timestamps (with_timestamps()), Silero VAD for long audio (with_vad(), models hard-capped at 20–30 s per pass, so VAD chunking + offset bookkeeping is mandatory — that's our integration work). Parakeet 0.6B beats Whisper large-v3-turbo on the HF Open ASR leaderboard (~6.4 vs ~8.4 avg WER) and runs many× real time on laptop CPUs (36× RTFx on a Ryzen 9800X3D; 14× RTF measured for the 0.6B GGUF on a Ryzen 4750U) — i.e. minutes per hour of video on this machine.
    • v3 is the default backend (decided) — 25 European languages, auto-detect; --lang en switches to v2 (slightly better English WER). Both work through the same package.
  • faster-whisper 1.2.1 (SYSTRAN, 2025-10-31): the mature Whisper runtime — reliable word-level timestamps (word_timestamps=True), Silero VAD v6, int8 CPU, BatchedInferencePipeline for ~2–3× more throughput. large-v3-turbo int8 is the fallback for languages outside Parakeet v3's set and as a quality cross-check. Note: faster-whisper 1.2.1 is only CI-tested to Python 3.13 (3.14 support merged to master but unreleased) — either pin the venv to 3.13 or install from git; its deps (ctranslate2 ≥4.7.1, av, onnxruntime, tokenizers) do ship cp314 wheels.
  • whisper.cpp — rejected as the main backend: word timestamps are officially experimental with acknowledged poor accuracy; Python bindings lag (pywhispercpp wraps an older snapshot); Parakeet support exists but only for ggml-org's own conversions. (It's healthy though: v1.9.5, 2026-10-06, and Pi Voice already uses the transcribe-cpp variant for dictation.)
  • Cached parakeet-unified-en-0.6b GGUF: reusable via the transcribe-cpp Python bindings (ctypes, "in development" 0.4.x) — English-only, very fast (~14× real time on a laptop CPU, LibriSpeech clean WER ~1.6%). Keep as an optional fast-path backend behind a feature flag, not a load-bearing dependency.
  • Hosted STT (optional, decided): one generic OpenAI-transcriptions client covers Groq whisper-large-v3-turbo ($0.04/hour, 216× real time, word timestamps), Mistral Voxtral, OpenAI whisper/gpt-4o-transcribe — details in §3.3.1. Local stays the default (no keys, no audio upload).
  • Diarization — in scope for v1 (decided): sherpa-onnx offline diarization is the default backend — pure CPU ONNX, no HF account/gating/token (models are plain GitHub-release downloads), ~0.3 RTF single-threaded (~18 min per hour of audio; faster with threads), tens of MB of models, low RAM. It emits speaker turns (start/end/speaker); we attribute words/segments by overlapping each word's midpoint with the containing turn. pyannote community-1 is the opt-in quality alternative (better clustering/counting, but gated: HF account + terms acceptance, torch-heavy) — installable as an optional extra. Diarization runs locally in both profiles by default; Deepgram/AssemblyAI bundle diarization into their hosted STT (accuracy-first, own SDKs) and remain a possible later addition for a fully-hosted-with-diarization route.

3.2 Vision-language model

Recommendation (local default): Qwen3-VL-4B-Instruct Q4_K_M served by llama.cpp llama-server (OpenAI-compatible), images sent as base64 JPEG; Qwen3-VL-2B-Instruct as the speed fallback. Hosted alternative (decided): DeepSeek V4.1-Flash — native vision, one key covers vision + synthesis — via VA_VLM_MODEL (§3.3.1).

  • Qwen3-VL-4B-Instruct (Apache-2.0, 256K context): best small-model OCR/document reading in this class (OCRBench ~88, DocVQA ~94.8), solid captioning — key for videos of screens/talks/UIs. Q4_K_M ≈ 2.5 GB + mmproj ≈ 0.3–0.8 GB; ~4–5 GB RSS at 8K context (30 GB RAM is ample). On CPU expect ~10–20 s per 448–576 px frame on this class of CPU; 2B model ≈ 4–8 s.
  • llama.cpp (confirmed from current docs/multimodal.md): supports image, audio, and video input for Qwen3-VL (image since 2025-10; native video input merged 2026-06). Serve with -hf <gguf-repo>:Q4_K_M or -m model.gguf --mmproj mmproj.gguf. llama-server exposes OpenAI-compatible /v1/chat/completions and accepts image_url with data:image/jpeg;base64,.... --image-max-tokens caps per-image tokens — the single most important flag for CPU affordability.
  • Video-native input (input_video/video_url, --video-fps default 4) exists but is token-explosive for anything but short clips; we'll do our own frame selection (§3.4) instead.
  • Ollama — usable (official qwen3-vl:2b/4b/8b-instruct tags) but not the default: it launches Qwen3-VL with --image-min-tokens 1024 and 4 threads by default and doesn't expose the image-token cap — 3–5× slower on CPU than a tuned llama-server.
  • Later upgrades: llama.cpp Vulkan build for the Arc iGPU (big prefill/vision-encoder gains on Xe2/Xe3-class iGPUs, decode roughly at parity); start with mmproj-only offload. Qwen3.5-4B is the quality alternative (higher general VQA, but thinking-by-default, weaker on dense small text).
  • Frame budgeting (Qwen3-VL: 32×32 px per visual token): 448×448 ≈ 196 tokens, 768×768 ≈ 576. With an 8K context keep ≤2–3K visual tokens per request → 2–3 frames per request at 448–576 px, one shot per request for long videos. Text below ~16–20 px is misread; for text-heavy frames spend more tokens on that frame rather than trusting a 4B model's small-text OCR. Hosted vision removes the CPU/context constraint — image tokens are billed instead, so detail: "low" plus the same modest frame budgets keep it cheap (§3.3.1).

3.3 pydantic-ai

Confirmed current state: pydantic-ai v2 (2.63.0, 2026-10-27). V1.0 was 2025-09-04; V2.0 stable 2026-06-23. Docs live at pydantic.dev/docs/ai. Pin pydantic-ai>=2.63,<3 (no breaking changes within v2 minors). Python 3.11–3.15 supported.

Key facts for this project (verify exact imports against docs while implementing):

  • Model for a local server:
    from pydantic_ai import Agent, BinaryImage
    from pydantic_ai.models.openai import OpenAIChatModel
    from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
    
    model = OpenAIChatModel(
        "Qwen3-VL-4B-Instruct",  # must match the model name llama-server reports
        provider=OpenAICompatibleProvider(
            "llama-server",
            base_url="http://127.0.0.1:8080/v1",
            api_key="local",
        ),
    )
    
    OpenAIModel is gone (renamed OpenAIChatModel); a bare openai: model prefix now means the Responses API — don't use it for llama.cpp. OllamaModel still exists if we ever switch to Ollama.
  • Multimodal input: pass a list of parts, e.g. agent.run(["Describe this frame.", BinaryImage(data=jpeg_bytes, media_type="image/jpeg")]) — sent as base64 data-URL image_url content parts, which llama-server accepts (needs --mmproj). Prefer BinaryImage over ImageUrl so nothing fetches remotely.
  • Structured output: output_type=MyModel defaults to a ToolOutput (an output tool call) → llama-server must run with --jinja and a tool-capable chat template (Qwen3 has one). Alternatives: NativeOutput (json_schema → llama.cpp GBNF grammar; syntax-safe but llama.cpp silently drops unsupported schema keywords and does not inject the schema into the prompt) and PromptedOutput. Keep schemas flat, put semantics in Field(description=...) + instructions, set generous max_tokens, retries={'output': 2}.
  • Other V2 notes: MCPToolset replaces the old MCPServer* classes (pydantic-ai as MCP client); deps via RunContext; FallbackModel for failover; ModelSettings(temperature=..., max_tokens=..., max_retries=0) — set max_retries=0 for deterministic local runs.
  • Hosted providers are first-class: DeepSeek and OpenRouter have provider guides (e.g. Agent('deepseek:deepseek-flash') with DEEPSEEK_API_KEY, Agent('openrouter:deepseek/deepseek-v4.1-flash-1017') with OPENROUTER_API_KEY) — the hosted synthesis option (§3.3.1) needs no custom code.
  • pydantic-ai does not expose an MCP server — for that we use FastMCP 4 (4.1.4, Python ≥3.10, Apache-2.0): from fastmcp import FastMCP; mcp = FastMCP("video-analyse"), @mcp.tool on async functions, mcp.run() (stdio) or mcp.run(transport="http", host="127.0.0.1", port=8000).

3.3.1 Model hosting: per-stage local or hosted (decided)

Every model stage — STT, vision, synthesis — is provider-pluggable, supporting fully-local, fully-hosted, and mixed setups. VA_PROFILE picks coherent all-at-once defaults; each stage is individually overridable:

Stage VA_PROFILE=local (default — zero keys) VA_PROFILE=hosted Per-stage override
STT Parakeet v3 via onnx-asr (CPU) Groq whisper-large-v3-turbo — $0.04/h, word timestamps VA_STT_BACKEND=parakeet | whisper | openai-transcriptions + VA_STT_API_*
Diarization sherpa-onnx (local CPU, ungated) same — stays local in the hosted profile VA_DIARIZE_BACKEND=sherpa | pyannote (opt-in extra)
Vision (shot description) Qwen3-VL-4B via llama-server DeepSeek V4.1-Flash (native vision) VA_VLM_MODEL — local model name or pydantic-ai model string
Synthesis/QA Qwen3-VL-4B via llama-server DeepSeek V4.1-Flash VA_SYNTHESIS_MODEL — same

Hosted keys: GROQ_API_KEY (STT) + DEEPSEEK_API_KEY (LLM stages) — or the OpenRouter/Ollama-cloud equivalents below.

Hosted STT (researched 2026-10-30): a single generic OpenAI-transcriptions client (/v1/audio/transcriptions, response_format=verbose_json, timestamp_granularities=[word, segment]) covers the recommended providers:

  • Groq — recommended hosted default: whisper-large-v3-turbo, $0.04/hour of audio, 216× real time, 99 languages, word-level timestamps, OpenAI-compatible endpoint (api.groq.com/openai/v1). 100 MB/request cap — our 16 kHz mono FLAC (~60 MB/hour) fits without chunking.
  • Same client shape: Mistral Voxtral (~$0.18/h batch, strong WER), OpenAI whisper-1/gpt-4o-transcribe ($0.36/h, 25 MB → chunking needed).
  • Accuracy-first alternatives with their own SDKs (add only on request): Deepgram Nova-3, AssemblyAI Universal-3.5 Pro (WER ~5%, $0.15–0.26/h) — both bundle diarization, a possible later fully-hosted STT+diarization route.

Recommended hosted LLM (vision + synthesis): DeepSeek V4.1-Flash, :1017 snapshot (Oct 17, 2026) — researched 2026-10-30:

  • What it is: 552B-param MoE on DeepSeek's new Causal Encoder–Decoder architecture — asymmetric 8B active input / 16B active output params, 1M-token context, native joint vision+text (DocVQA 95.6, MMMU-Pro 56.5), controllable reasoning effort (1–100), compressed KV cache (¼ the HBM of the previous flash generation → very cheap prompt caching).

  • Quality: beats DeepSeek's own much larger V4-Pro (1.6T params) on most benchmarks (MMLU-Pro 74.1 vs 73.5 — V4-Pro is being phased out). The 1017 update added large agentic gains: Terminal-Bench 4.0 42.3 (vs 31.2), DeepSWE 77.0 (above GPT-5.6 Sol 73.0 and Opus 5 74.0), Agents' Last Exam 35.4. Tool calling is its core strength — ideal for pydantic-ai ToolOutput structured reports.

  • Vision mechanics (confirmed from DeepSeek API docs): standard OpenAI-compatible image_url content blocks — base64 data URLs (our default), external URLs, or Files API file_id for reuse; detail: "low" (512×512 downscale) for cheap frame processing; up to 600 images/request (max dimension drops to 4096 px at ≥15 images); JPEG/PNG/GIF/WebP; images in user messages only. Works through pydantic-ai's BinaryImage unchanged, so the describer agent is provider-agnostic.

  • Cost/speed (Ollama-cloud pricing): $0.30/$1.20 per 1M tokens peak, $0.15/$0.60 off-peak, $0.006 cached input. A full synthesis over an hour-long video (~100K in / ~3K out) costs ~3–5 cents; repeated va ask queries hit the cache for fractions of a cent.

  • Serving routes (all OpenAI-compatible, all reachable from pydantic-ai):

    Route Model string Key Pinning
    DeepSeek API deepseek:deepseek-flash DEEPSEEK_API_KEY alias tracks latest flash
    OpenRouter openrouter:deepseek/deepseek-v4.1-flash-1017 OPENROUTER_API_KEY dated snapshot pinned
    Ollama cloud ollama:deepseek-v4.1-flash:1017 ollama_api_key in config.toml (or OLLAMA_API_KEY env) dated snapshot pinned
  • Verdict: near-ideal hosted LLM for both perception and synthesis — one key covers both stages; 1M context swallows whole transcripts + shot lists; flash-tier latency. Rough fully-hosted cost for an hour of video: ~$0.10–0.15 (STT $0.04 + ~64 frames at detail: "low" a few cents + synthesis 3–5 cents); measure real image-token cost on the first hosted run. Caveats: raw audio (STT) and frames + derived text (LLM) leave the machine, so hosted stays opt-in behind VA_PROFILE/per-stage config; exact-snapshot reproducibility only via the dated OpenRouter/Ollama-cloud tags (DeepSeek's own deepseek-flash alias floats to the current release).

3.4 Video preprocessing & ingest

  • ffmpeg (n9.x, already installed):
    • audio for STT: ffmpeg -i in.mp4 -vn -ac 1 -ar 16000 -c:a pcm_s16le audio.wav
    • probing: ffprobe -v quiet -show_format -show_streams -of json input
    • keyframe at time t (used for shot midpoints): ffmpeg -ss <t> -i in.mp4 -frames:v 1 -vf scale=768:-2 -q:v 3 frame.jpg
    • scene cuts (fast fallback without PySceneDetect): ffmpeg -i in.mp4 -vf "select='gt(scene,0.3)',showinfo" -f null -
    • adaptive sampling (implemented): shots longer than 20 s are subdivided at equal cumulative-activity boundaries from a frame-difference curve (dense sampling where the video changes, sparse where static), keyframes at each segment's calmest frame, phash-dedup after
  • PySceneDetect 0.7 (current docs confirmed): ContentDetector (HSV content diff), AdaptiveDetector (two-pass, robust to fast motion — our default), HashDetector (perceptual-hash similarity — doubles as our dedup detector). OpenCV or PyAV backend; outputs scene list [(start, end)].
  • Frame dedup: dHash/pHash Hamming distance ≤ 8 (via imagehash, or PySceneDetect's HashDetector) to drop near-identical keyframes (talking heads, slides); keep a min-shot-merge so a 1-hour lecture doesn't produce 500 shots — cap at ~1 keyframe per shot, target ≤ 64 shots per video chunk.
  • URL ingest: yt-dlp (to be added as a dependency): -f "bv*[height<=1080]+ba/b" --write-info-json for an analysis-friendly local file plus metadata; direct HTTP mp4 URLs pass straight to ffmpeg. Cache downloads under the stage cache (§4) keyed by URL+format.

3.5 Prior art (and what we take from it)

  • pr1hm/FrameRead (2026): fully-local pipeline — faster-whisper + Qwen2-VL-2B frames + Ollama synthesis → validates our exact architecture on similar hardware. Take: dual audio/visual pipelines, Q&A mode, per-stage logging.
  • guimatheus92/mcp-video-analyzer: MCP server (yt-dlp platforms + OCR + timeline, 8 tools; cloud Whisper fallback). Take: the tool surface (analyze_video, get_transcript, get_frames, analyze_moment, get_frame_at) and the "cheapest tool for the job" principle.
  • thoughtpunch/claudetube: MCP server, 40+ tools, faster-whisper + on-demand frame extraction. Take: frame-on-demand at a timestamp (get_frame_at) — an agent-cheap way to "look" at a moment without full analysis.
  • Commercial references (Twelve Labs, Gemini video APIs): report schemas — timestamped highlights, topics, entities.

Our niche: fully local/offline, CPU-viable, structured pydantic outputs, cache-resumable pipeline, first-class Python lib + CLI + MCP.


4. Architecture

                    ┌────────────────────────────────────────────────┐
 src (file or URL)  │  ingest: yt-dlp download (if URL) → local file   │
 ─────────────────► │  probe:  ffprobe → MediaFacts                    │
                    └───────────────┬────────────────────────────────┘
                                    │
              ┌─────────────────────┴─────────────────────┐
              ▼                                           ▼
   audio.wav (16k mono)                     shot detection (PySceneDetect)
              │                                           │
              ▼                                           ▼
   STT (Transcriber protocol:                keyframes (ffmpeg + phash dedup
   parakeet-onnx | faster-whisper |           + resize ≤768px, JPEG q85)
   openai-transcriptions)                                 │
              │                                           ▼
              ▼                                           │
   diarization (sherpa-onnx →                VLM (pydantic-ai Agent → llama-server
   SpeakerTurns, merged into                 Qwen3-VL-4B or hosted DeepSeek;
   speaker-attributed segments)               2–3 frames/req, ShotDescription)
              │                                           │
              ▼                                           │
   Transcript (words + segments,                          │
   speaker labels)                                        │
              │                                           │
              └────────────────┬────────────────────────┘
                               ▼
               synthesis Agent (pydantic-ai, same server):
               transcript + shots → VideoReport (pydantic, validated)
                               │
                               ▼
               artifacts: report.json · report.md · transcript.srt
               + MCP server + CLI for agents to consume

Every stage (fetch → probe → audio → transcript → diarize → shots → descriptions → report) is cached under ~/.cache/video-analyse/<hash-of-source>/ with a content hash; re-running is incremental and resumable. Every model stage (STT, VLM, synthesis) is provider-pluggable — fully-local or fully-hosted profiles (§3.3.1).

Package layout (src/video_analyse/, uv-managed):

Module Responsibility
models.py All pydantic data models (below)
config.py pydantic-settings: model names, endpoints, cache dir (VA_* env)
ingest.py file/URL → local path (yt-dlp), info JSON
media.py ffprobe, audio extraction, PySceneDetect shots, keyframe extraction, phash dedup, resize
diarize.py sherpa-onnx speaker diarization (default; local, ungated) + optional pyannote backend; merge SpeakerTurns into the transcript via word-timestamp overlap
transcribe/base.py Transcriber protocol (async, returns Transcript)
transcribe/parakeet_onnx.py onnx-asr parakeet-tdt-0.6b(-v2/v3) int8, VAD chunking, token→word merging
transcribe/faster_whisper.py faster-whisper turbo int8, word_timestamps=True
transcribe/openai_transcriptions.py hosted STT via OpenAI-compatible /v1/audio/transcriptions (Groq-documented; word timestamps)
vision.py pydantic-ai ShotDescriber agent — provider-agnostic (local llama-server default, hosted via VA_VLM_MODEL); llama-server health check when local
synthesis.py pydantic-ai report/QA agents over Transcript+Shots (model via VA_SYNTHESIS_MODEL)
pipeline.py stage orchestration, caching, chunked processing for long videos
cli.py typer app (va ...), mirrors every pipeline stage
mcp_server.py FastMCP 4 server exposing the tools (stdio + HTTP)

Core data models (in models.py):

class Word(BaseModel):
    text: str
    start: float
    end: float
    probability: float | None = None


class SpeakerTurn(BaseModel):
    start: float
    end: float
    speaker: str  # "S1", "S2", …


class Segment(BaseModel):
    start: float
    end: float
    text: str
    words: list[Word] = []
    speaker: str | None = None  # set when diarization ran


class Transcript(BaseModel):
    language: str | None
    duration: float
    segments: list[Segment]
    speaker_turns: list[SpeakerTurn] = []  # present when diarization ran


class Shot(BaseModel):
    index: int
    start: float
    end: float
    keyframe: Path | None = None  # cached jpg
    phash: str | None = None
    transcript_slice: str = ""  # words spoken during this shot (speaker-prefixed when diarized)
    description: ShotDescription | None = None


class ShotDescription(BaseModel):
    summary: str
    on_screen_text: str | None = None  # verbatim captions/UI/OCR
    shot_type: Literal["wide", "medium", "close-up", "screen", "other"]
    people: list[str] = []
    notable_objects: list[str] = []
    setting: str | None = None


class Highlight(BaseModel):
    start: float
    end: float
    description: str


class VideoReport(BaseModel):
    source: str  # original path/URL
    title: str | None
    duration: float
    summary: str
    topics: list[str]
    people: list[str]
    highlights: list[Highlight]
    shots: list[Shot]
    transcript: Transcript
    metadata: dict[str, Any]  # ffprobe + yt-dlp info

5. Interfaces

Config (pydantic-settings; env VA_*, optional ~/.config/video-analyse/config.toml):

Setting Default Meaning
VA_PROFILE local local | hosted — coherent per-stage defaults (§3.3.1)
VA_STT_BACKEND parakeet (v3, multilingual) parakeet | whisper | openai-transcriptions; --lang en selects Parakeet v2
VA_STT_API_BASE_URL / VA_STT_API_MODEL Groq: https://api.groq.com/openai/v1 / whisper-large-v3-turbo any OpenAI-transcriptions endpoint
VA_DIARIZE on run diarization in va analyse (--no-diarize to skip)
VA_DIARIZE_BACKEND sherpa sherpa | pyannote (opt-in extra, gated model)
VA_VLM_MODEL Qwen3-VL-4B-Instruct (llama-server at 127.0.0.1:8080) local model name or pydantic-ai model string (e.g. deepseek:deepseek-flash)
VA_SYNTHESIS_MODEL local llama-server model any pydantic-ai model string (§3.3.1)
VA_CACHE_DIR ~/.cache/video-analyse stage artifact cache

Provider keys: GROQ_API_KEY, DEEPSEEK_API_KEY, OPENROUTER_API_KEY, OLLAMA_API_KEY.

CLI (typer; every stage runnable alone, va analyse runs the whole pipeline):

va fetch <url> [--quality 1080]        # URL → local file + metadata
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
va describe <src> [--model <name-or-model-string>]  # per-shot ShotDescription (local llama-server or hosted, §3.3.1)
va analyse <src> [--no-diarize] [--out report.md]  # full pipeline → VideoReport + markdown
va ask <src> "question"                 # Q&A grounded in the cached report
va serve-mcp [--transport stdio|http]   # run the MCP server

MCP server (FastMCP 4; stdio transport (decided) — HTTP stays behind a flag for other agent hosts; six focused tools — small enough to run direct in pi):

Tool Returns Notes
transcribe_video Transcript (segments/words, speaker labels when diarized) cheapest first; cached
extract_keyframes Shot list + frames (image content blocks) scene-based, deduped
analyze_video full VideoReport the expensive one
analyze_moment frames + transcript slice for a time range agent "zoom-in"
get_frame_at single frame at timestamp near-free "look here"
ask_video grounded answer to a question uses cached artifacts

pi integration (project-level, after implementation):

pi mcp add -l video-analyse -- uv run --directory /home/alex/projects/video-analyse va serve-mcp

Serving the VLM — llama-server is a separate process the user (or va describe) launches:

llama-server -hf bartowski/Qwen_Qwen3-VL-4B-Instruct-GGUF:Q4_K_M \
  --jinja -c 8192 -t 14 --image-max-tokens 448 --flash-attn auto \
  --host 127.0.0.1 --port 8080

va describe should detect the server is up and print this exact hint when it isn't.


6. Roadmap

Milestone Scope Acceptance criteria
M0 — scaffold uv project, venv pinned to Python 3.13 (uv python pin 3.13 — decided), pyproject + deps (pydantic-ai, typer, pydantic-settings, faster-whisper, onnx-asr, sherpa-onnx, scenedetect, imagehash, yt-dlp, fastmcp, av), ruff + pytest, config skeleton, CI-less uv run va --help works; test_model_wiring.py smoke test green (local model against a stub server + mocked deepseek:/openrouter: model strings); sample video fixture generator (ffmpeg testsrc)
M1 — ingest & media fetch, probe, audio extraction, shot detection, keyframe extraction + dedup va shots sample.mp4 → ≤N deduped JPEG keyframes + ShotList JSON on a synthetic fixture
M2 — transcription faster-whisper backend → Transcript JSON/SRT; stage cache 1-min sample transcribed with word timestamps; JSON round-trips through the pydantic model; SRT is valid
M3 — diarization sherpa-onnx diarization → SpeakerTurns; merge into transcript via word-timestamp overlap (va diarize, --diarize/--no-diarize); pyannote optional backend behind an extra two-speaker synthetic fixture gets correct word→speaker assignment; va analyse output carries speaker labels; --no-diarize skips the stage and the cache reflects it
M4 — vision pydantic-ai describer agent (va describe), provider-agnostic: llama-server local default or hosted VLM via VA_VLM_MODEL all shots described with validated ShotDescription output (retries on schema failure); works against local llama-server and a hosted model string with only config changes
M5 — STT backends parakeet-tdt-0.6b-v3 int8 (onnx-asr; VAD chunking, token→word) + hosted openai-transcriptions client (Groq-documented); benchmark parakeet vs whisper; pick default parakeet within ±5% WER sanity vs whisper backend, ≥3× faster; hosted client returns word timestamps from Groq on the same sample; --backend flag
M6 — synthesis synthesis agent → VideoReport (validated), markdown renderer, va analyse, va ask; synthesis model configurable (VA_SYNTHESIS_MODEL, local default; hosted DeepSeek V4.1-Flash documented — §3.3.1) full pipeline on a 5-min real video; report.md human-readable; pipeline fully cached on second run; VA_SYNTHESIS_MODEL=deepseek:deepseek-flash va analyse produces the same validated report shape with zero code changes
M7 — MCP + docs FastMCP server (6 tools, stdio), pi project config, README with architecture + benchmark table + privacy notes (hosted opt-in) pi can transcribe_video/ask_video on a local file end-to-end in a fresh session

Later (post-v1): CLIP-embedding search + semantic dedup, Vulkan/iGPU llama.cpp, video-native input for short clips, long-video map-reduce chunking (if > ~40 min), hosted combined STT+diarization providers (Deepgram/AssemblyAI, own SDKs).


7. Risks & mitigations

Risk Mitigation
CPU throughput (10–20 s/frame; hours for long videos) Parakeet STT (minutes/hour); ≤64 shots default; 2B fallback model; stage caching; chunked overnight-style runs; frame budget flags
llama.cpp grammar-constrained output: schema keywords silently dropped, no schema in prompt flat schemas, rich Field descriptions + instructions; ToolOutput with --jinja + retries; always model_validate before caching; generous max_tokens to avoid mid-JSON truncation
Small-VLM hallucination in descriptions temperature 0.1, "describe only what is visible" instructions, verbatim-OCR field separated from interpretation, optional per-shot notable_objects cap
parakeet onnx-asr VAD offset bookkeeping bugs (word timings off) unit test with synthetic tone/speech fixture with known word gaps; cross-check segment times vs faster-whisper on sample
Diarization quality/speaker-count on hard audio (sherpa-onnx below pyannote; threshold tuning) speaker labels are best-effort and flagged as such in output; tune cluster_threshold on the fixture; pyannote optional backend for quality-critical runs
yt-dlp breakage / sites blocking downloads pin yt-dlp, support direct URLs + local files first, clear error mapping
faster-whisper on Python 3.14 venv pinned to 3.13 in M0; onnx-asr path is 3.14-clean either way
Exact pydantic-ai v2 API names (OpenAICompatibleProvider, BinaryImage, MCPToolset) drift vs research one smoke test at M0 (test_model_wiring.py) that constructs the model + agent against a stub server, plus a mocked deepseek:/openrouter: provider test
Hosted profile: raw audio (STT), frames + derived text (LLM stages) leave the machine off by default (VA_PROFILE=local); privacy trade-off documented in README; pin dated snapshots (deepseek-v4.1-flash:1017 / deepseek/deepseek-v4.1-flash-1017) for reproducibility

8. Decisions (resolved 2026-10-30)

  1. Diarization: in scope for v1 (changed 2026-10-30, was post-v1): sherpa-onnx default backend (local, ungated), pyannote as opt-in quality extra; on by default in va analyse with --no-diarize to skip (M3).
  2. Languages: Parakeet v3 multilingual default; v2 English via --lang en.
  3. Python: venv pinned to 3.13 (uv python pin 3.13) for faster-whisper safety; the onnx-asr path is 3.14-ready if we ever bump.
  4. MCP transport: stdio (pi project-level server via pi mcp add -l ...); FastMCP's HTTP transport stays behind a flag for other agent hosts.
  5. Model hosting (supersedes the earlier synthesis-only decision): every stage pluggable — fully-local or fully-hosted profiles (VA_PROFILE=local\|hosted) with per-stage overrides. Local defaults: Parakeet v3 + Qwen3-VL-4B (llama-server), zero keys. Hosted defaults: Groq whisper-large-v3-turbo (STT) + DeepSeek V4.1-Flash :1017 (vision + synthesis). Research in §3.3.1.

9. Sources (key primary sources consulted, 2026-10-30)

STT: onnx-asr docs/PyPI (istupakov.github.io/onnx-asr, pypi.org/project/onnx-asr) · github.com/SYSTRAN/faster-whisper (+releases: 1.2.1, Silero VAD v6) · github.com/ggml-org/whisper.cpp (+releases v1.9.5, word-timestamp experimental note, parakeet-cli) · huggingface.co/handy-computer/parakeet-unified-en-0.6b-gguf · hf-audio open-asr-leaderboard results · github.com/k2-fsa/sherpa-onnx (offline speaker diarization, ungated models). VLM: huggingface.co/Qwen/Qwen3-VL-4B-Instruct · github.com/ggml-org/llama.cpp docs/multimodal.md (image/audio/video support, -hf/--mmproj, mmproj offload) · llama.cpp PRs #16780 (Qwen3-VL), #24269 (video input), #14001 (Vulkan Xe2 coopmat) · ollama.com/library/qwen3-vl · bartowski Qwen3-VL GGUF. pydantic-ai / MCP: github.com/pydantic/pydantic-ai/releases (v2.63.0, 2026-10-27) · pydantic.dev/docs/ai (models, input, MCP client, compatible APIs) · pypi.org/project/fastmcp (4.1.4) · py.sdk.modelcontextprotocol.io/migration. Preprocessing: scenedetect.com/docs/latest (0.7 detectors incl. AdaptiveDetector, HashDetector) · ffmpeg.org filters (select/thumbnail/fps). Prior art: github.com/pr1hm/FrameRead · github.com/guimatheus92/mcp-video-analyzer · github.com/thoughtpunch/claudetube. Hosted synthesis: deepseek.com/en/news/deepseek-v4-1-flash (announcement: CED architecture, pricing) · huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash and /DeepSeek-V4.1-Flash-1017 (model cards, benchmarks) · ollama.com/library/deepseek-v4.1-flash:1017-cloud (tag + pricing) · openrouter.ai/deepseek (snapshot pinning). Hosted STT/vision: console.groq.com/docs/speech-to-text (models, pricing, timestamp_granularities) · speechtotext.dev/pricing (2026 hosted STT price comparison) · api-docs.deepseek.com/guides/vision (image input formats, limits, detail levels).