Files
alex b976489f9b
CI / gates (push) Successful in 1m17s
ci: fix the two run #1 findings
Run #1 (6302e0b) failed at the tests gate for two reasons local runs
masked:

- The act image lacks OpenCV's runtime libs, so every
  scenedetect-importing media test died on `ImportError: libGL.so.1`.
  The workflow now installs libgl1/libglib2.0-0 with ffmpeg, and the
  README documents the headless-Linux runtime libs for users.
- Rich rendered `va transcribe --help` at 80 columns and wrapped
  `openai-transcriptions` mid-token: GITHUB_ACTIONS makes typer force a
  terminal, and TERM=dumb then picks rich's 80-column fallback. Tests
  now pin COLUMNS=120 before any Console is constructed and keep typer
  in auto-detect mode, so help and doctor output are width-independent
  of the runner.

Gates 4/4: 449 passed, 2 skipped; also green under
GITHUB_ACTIONS=true COLUMNS=80.
2026-11-24 13:24:08 +00:00

41 KiB
Raw Permalink Blame History

video-analyse

CI

Local-first, agent-friendly video analysis: give it a video file or URL and get a word-level transcript, speaker labels, per-shot visual descriptions and a structured report — as a Python library, a va CLI, and an MCP server that agents such as pi can call directly.

Everything is a typed pydantic model, every stage is content-cached, and every model stage (speech-to-text, vision, synthesis) can run locally or against a hosted provider.

  • Local by default — Parakeet TDT 0.6B v3 (ONNX, CPU) + Qwen3-VL-4B via llama-server; zero API keys, nothing leaves the machine except model downloads.
  • Hosted optional — Groq Whisper for STT and DeepSeek V4.1-Flash for vision and synthesis behind VA_PROFILE=hosted, or mix stages freely.
  • Cache-resumable — every stage writes ~/.cache/video-analyse/<sha256[:16]>/stage-*.json; re-running is incremental and --force re-runs only the requested stage and its downstream consumers.
  • Agent-first — one va command per stage, JSON on stdout, and six focused MCP tools.

Status: v1 feature-complete (see PLAN.md for the research and design). Real-model smoke covers ffmpeg, shot detection, faster-whisper, Parakeet and sherpa-onnx diarization on this machine; the vision/synthesis stages are covered by offline model mocks and a TestModel-backed full-pipeline run, not yet by a live llama-server run. See Current limitations.


Install

1. System dependencies

Tool Why Notes
ffmpeg / ffprobe probing, audio extraction, keyframes, hosted-STT FLAC conversion sudo pacman -S ffmpeg (Arch), sudo apt install ffmpeg (Debian/Ubuntu), or brew install ffmpeg
Python 3.13 project targets >=3.13,<3.14 (pinned in .python-version) uv python install 3.13
uv environment and dependency management any recent version

On headless Linux (servers, containers, CI) the OpenCV build behind shot detection also needs its runtime libs: sudo apt install libgl1 libglib2.0-0. Desktop installs normally have both already.

va doctor verifies ffmpeg, ffprobe, yt-dlp, the Python version, the llama-server, API-key presence, diarization assets, the cache and free disk space.

2. Python environment

git clone <repo> video-analyse
cd video-analyse
uv sync                 # creates .venv with Python 3.13 and all runtime + dev deps
uv run va --help        # or: .venv/bin/va --help

uv sync installs the console script va from the project. First runs of the model stages download weights into their normal caches (Hugging Face for Parakeet/Whisper/Silero VAD, GitHub releases for the sherpa-onnx diarization assets); see Privacy.

3. Optional extras

uv sync --extra pyannote      # optional pyannote.audio diarization backend (gated model)

The pyannote extra replaces the default sherpa-onnx diarizer when requested with VA_DIARIZE_BACKEND=pyannote or va diarize --backend pyannote. It needs a Hugging Face account, acceptance of the pyannote/speaker-diarization-community-1 model terms, and HF_TOKEN; it is torch-based and much heavier than sherpa-onnx.

For local vision and synthesis you also need llama-server from llama.cpp (see Local llama-server). Nothing else is required for transcription, diarization, shot detection or probing.


Quickstart

Generate a 10-second sample (the same synthetic clip the test suite uses) if you want to follow along:

ffmpeg -y -f lavfi -i testsrc2=duration=10:size=640x360:rate=12 \
  -f lavfi -i sine=frequency=440:duration=10 \
  -c:v libx264 -preset veryfast -c:a aac -shortest /tmp/va-sample.mp4

All commands accept a local path or an http(s) URL, print a rich table by default, and emit exactly one JSON document on stdout with --json (also accepted globally as va --json <command>). Progress lines go to stderr.

Probe

uv run va probe /tmp/va-sample.mp4
uv run va probe /tmp/va-sample.mp4 --json

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

uv run va fetch "https://example.com/talk.mp4" --quality 1080
uv run va fetch "https://example.com/talk.mp4" --json

fetch downloads through yt-dlp (any site it supports, or a direct HTTP media URL) into the cache and reports the local path and title. Later commands accept either the URL or the returned path.

Shots and keyframes

uv run va shots /tmp/va-sample.mp4 --max-shots 8
uv run va shots /tmp/va-sample.mp4 --max-shots 64 --json

Adaptive scene detection (PySceneDetect) + one keyframe per shot + perceptual-hash dedup (imagehash) + merging of very short adjacent shots. Adaptive sampling: long shots (talks, lectures, paper walkthroughs with overlays and no hard cuts) are subdivided by a cheap frame-difference activity curve — segments get an equal share of the video's total visual change, so busy stretches are sampled densely and quiet ones sparsely — and each segment's keyframe sits at its calmest (settled) frame, which keeps slides and figures clean and OCR-able. Each described shot also carries a relative activity level the vision model sees in its prompt. Configure with VA_SHOT_SAMPLING=adaptive|uniform|scene, VA_SAMPLING_INTERVAL_SECONDS (target seconds per extra keyframe, default 15) and VA_SUBDIVIDE_AFTER_SECONDS (default 20). Dedup keeps the first occurrence of a visual and drops the later duplicate shot with its frame, so repeated visuals can leave gaps in the shot timeline (the transcript still covers all audio). Keyframes live in <cache>/<source-hash>/keyframes/; JSON carries the absolute paths.

Transcribe

# local default: Parakeet TDT v3 (multilingual, int8 ONNX, VAD-chunked)
uv run va transcribe /tmp/va-sample.mp4

# English-only Parakeet v2 (slightly better English WER)
uv run va transcribe /tmp/va-sample.mp4 --lang en

# faster-whisper backend (naming a checkpoint selects it; see VA_WHISPER_MODEL)
VA_WHISPER_MODEL=tiny uv run va transcribe /tmp/va-sample.mp4

# diarization follows VA_DIARIZE (on by default), like MCP transcribe_video;
# pass --no-diarize to skip the second model pass
uv run va transcribe /tmp/va-sample.mp4
uv run va transcribe /tmp/va-sample.mp4 --no-diarize

# subtitles on stdout
uv run va transcribe /tmp/va-sample.mp4 --format srt

# machine-readable
uv run va transcribe /tmp/va-sample.mp4 --json

The transcript is a Transcript with optional word timings (Word.text/start/end/ probability), language, backend and model name. Parakeet token timings are converted to word timings via the SentencePiece word-boundary marker; VAD chunk offsets are applied so all times are absolute. Omitting --diarize / --no-diarize follows VA_DIARIZE (on by default), the same rule MCP transcribe_video uses; an explicit flag overrides it for that run.

Diarize

uv run va diarize /tmp/va-sample.mp4
uv run va diarize /tmp/va-sample.mp4 --backend sherpa --json
uv run va diarize /tmp/va-sample.mp4 --backend pyannote   # needs the extra + HF_TOKEN

Runs transcription (cached when already done), detects speaker turns and attributes every word/segment to a speaker by word-midpoint overlap (segment labels use the majority of its words). Default backend is sherpa-onnx offline diarization: CPU-only ONNX, no HF gating, ≈46 MB of models downloaded once and checksum-verified into <cache>/models/. Speaker labels are best-effort.

Describe shots (vision)

# local default: Qwen3-VL-4B-Instruct served by llama-server at 127.0.0.1:8080
uv run va describe /tmp/va-sample.mp4
uv run va describe /tmp/va-sample.mp4 --model local:Qwen3-VL-4B-Instruct --json

# hosted: one key covers vision + synthesis
VA_VLM_MODEL=deepseek:deepseek-flash uv run va describe /tmp/va-sample.mp4

# any pydantic-ai model string pydantic-ai knows
VA_VLM_MODEL=openrouter:deepseek/deepseek-v4.1-flash-1017 uv run va describe /tmp/va-sample.mp4

One agent call per shot, output_type=ShotDescription (summary, verbatim on-screen text, shot type, people, notable objects, setting). When the configured model targets the local server and it is down, va describe fails immediately with the exact llama-server startup command. Re-run after starting the server; described shots are cached.

Full analysis

uv run va analyse /tmp/va-sample.mp4                    # writes report.md/.json/.srt
uv run va analyse /tmp/va-sample.mp4 --out talk.md --force
uv run va analyse /tmp/va-sample.mp4 --no-diarize --json
uv run va analyse /tmp/va-sample.mp4 --no-describe --max-shots 32

analyse runs probe → audio → transcribe → diarize → shots → describe → report, caches every stage, and writes the PLAN §4 artifact set next to --out: a deterministic Markdown report (report.md), the validated VideoReport JSON (report.json) and the speaker-labelled transcript (transcript.srt, omitted only when there is no transcript). --json also prints the validated VideoReport to stdout. --no-diarize skips speaker labels, --no-describe skips the per-shot VLM calls, --max-shots caps shot detection, and --force re-runs the requested stages and their downstream consumers.

Long transcripts are summarised chunk-wise (map step) before the final report (reduce step), so an hour-long video is not silently reduced to a prompt prefix. The report's metadata.synthesis records chunked, chunks and truncated; local prompts that would exceed the documented llama-server -c 8192 context raise an actionable error instead of being sent.

Ask a question

uv run va ask /tmp/va-sample.mp4 "What is shown and what is said?"
uv run va ask /tmp/va-sample.mp4 "Summarise the first 30 seconds" --json

Answers are grounded in the cached report (transcript is included when the prompt budget allows) and cite moments as [MM:SS]. Run va analyse first; va ask is cache-only, like MCP ask_video without allow_analysis. Identical questions are served from the local answer cache (keyed by report content, normalised question and synthesis model); pass --no-cache to force a fresh model call.

Moment

uv run va moment /tmp/va-sample.mp4 --start 0.5 --end 4 --out frames/
uv run va moment /tmp/va-sample.mp4 --start 0.5 --end 4 --describe --json

Zooms into one window: up to four JPEG frames (--max-frames, --width), the cached speaker-labelled transcript slice and the cached descriptions of overlapping shots. --out DIR writes the frames as frame-00.jpg, ...; --describe sends those frames to the VLM in one request. No stage runs unless the probe facts are missing, and the context is read at the current option keys, so a cached shot list from a different --max-shots is never served. MCP analyze_moment calls the same analysis operation.

Doctor

uv run va doctor
uv run va doctor --json

Read-only checks: Python version, resolved profile/models, ffmpeg/ffprobe versions, yt-dlp importability, llama-server health (GET /models, localhost only) and whether it serves the configured local model, hosted API-key presence and provider SDK availability (values are never printed), cached Parakeet/Whisper and sherpa/pyannote assets, cache size and free disk. fail checks (missing ffmpeg/ffprobe) exit non-zero; warnings such as "llama-server not reachable" do not.

Serve MCP

uv run va serve-mcp                     # stdio (default) — blocks until the host closes stdin
uv run va serve-mcp --transport http --port 8000

Configuration

Configuration comes from VA_* environment variables (pydantic-settings, case-insensitive) and from an optional ~/.config/video-analyse/config.toml (or $XDG_CONFIG_HOME). The precedence is constructor kwargs → environment → TOML; env always wins over the file.

Variable Default Meaning
VA_PROFILE local local or hosted; selects coherent per-stage defaults (below). Per-stage VA_* settings always win.
VA_CACHE_DIR ~/.cache/video-analyse Stage-artifact, keyframe, audio and model-asset root. ~ is expanded.
VA_LANGUAGE unset (= auto) en selects Parakeet v2; any other code keeps Parakeet v3 (multilingual auto-detect). --lang overrides per command.
VA_STT_BACKEND unset parakeet | whisper | openai-transcriptions. Unset → parakeet in the local profile, openai-transcriptions in the hosted profile.
VA_STT_API_BASE_URL https://api.groq.com/openai/v1 Any OpenAI-compatible /audio/transcriptions endpoint (Groq, OpenAI, Mistral Voxtral, …).
VA_STT_API_MODEL whisper-large-v3-turbo Model name sent to that endpoint.
VA_STT_MAX_UPLOAD_BYTES unset Override the hosted-STT per-request upload cap (24 MB for api.openai.com, 90 MB otherwise).
VA_WHISPER_MODEL large-v3-turbo faster-whisper checkpoint. A non-default checkpoint also selects the whisper backend when VA_STT_BACKEND is unset (so VA_WHISPER_MODEL=tiny va transcribe works as expected); use VA_STT_BACKEND=whisper to run Whisper with this default checkpoint, or VA_STT_BACKEND=parakeet to keep Parakeet.
VA_SHOT_SAMPLING adaptive How long shots get extra keyframes: adaptive (subdivide shots longer than VA_SUBDIVIDE_AFTER_SECONDS at equal visual-activity boundaries from a frame-difference curve, keyframe at each segment's calmest frame — dense sampling where the video changes, sparse where it is static), uniform (equal time intervals), scene (never subdivide).
VA_SAMPLING_INTERVAL_SECONDS 15 Target seconds per extra keyframe inside subdivided long shots.
VA_SUBDIVIDE_AFTER_SECONDS 20 Shots longer than this get subdivided (adaptive/uniform modes).
VA_DIARIZE_CLUSTER_THRESHOLD 0.7 Speaker clustering threshold (smaller → more speakers). 0.7 keeps a dynamic narrator as one speaker; lower it (e.g. 0.5) only if real speakers are being merged.
VA_DIARIZE_MIN_DURATION_ON 0.3 Drop diarization segments shorter than this many seconds (sherpa backend).
VA_DIARIZE_MIN_DURATION_OFF 0.5 Merge diarization segments separated by gaps shorter than this many seconds (sherpa backend).
VA_DIARIZE true Run diarization in va analyse/va transcribe/va diarize (and MCP transcribe_video); false or --no-diarize skips the stage, --diarize forces it for one run.
VA_DIARIZE_BACKEND sherpa sherpa (default, ungated ONNX) | pyannote (optional extra, gated).
VA_VLM_MODEL unset Vision model spec: local:<name>/bare name → llama-server; deepseek:…, openrouter:…, ollama:… → that provider. Unset → local:Qwen3-VL-4B-Instruct (local profile) or deepseek:deepseek-flash (hosted).
VA_LLAMA_SERVER_URL http://127.0.0.1:8080/v1 OpenAI-compatible base URL of the local llama-server.
VA_SYNTHESIS_MODEL unset Model spec for report synthesis and va ask; same resolution rules and profile defaults as VA_VLM_MODEL.

Environment variables read directly by stages (not part of Settings):

Variable Used by Meaning
GROQ_API_KEY, VA_STT_API_KEY, OPENAI_API_KEY hosted STT First present key authenticates /audio/transcriptions; GROQ_API_KEY is the documented hosted-profile choice.
DEEPSEEK_API_KEY deepseek: models Hosted vision + synthesis through the DeepSeek API.
OPENROUTER_API_KEY openrouter: models Dated snapshots such as deepseek/deepseek-v4.1-flash-1017.
OLLAMA_API_KEY ollama: models Ollama (cloud) auth; also pair with OLLAMA_BASE_URL (required by pydantic-ai's Ollama provider).
HF_TOKEN pyannote only Gated-model download token; not needed by sherpa-onnx.

Profiles

VA_PROFILE only chooses defaults; every stage remains individually overridable.

Stage VA_PROFILE=local (default) VA_PROFILE=hosted Override
STT Parakeet TDT 0.6B v3 int8 via onnx-asr on CPU (v2 with VA_LANGUAGE=en) Groq whisper-large-v3-turbo via the OpenAI-transcriptions client VA_STT_BACKEND, VA_STT_API_*, VA_WHISPER_MODEL, VA_LANGUAGE
Diarization sherpa-onnx (local CPU, ungated) stays local (sherpa-onnx) VA_DIARIZE_BACKEND=sherpa|pyannote, VA_DIARIZE
Vision Qwen3-VL-4B-Instruct via llama-server DeepSeek V4.1-Flash (deepseek:deepseek-flash) VA_VLM_MODEL
Synthesis / Q&A Qwen3-VL-4B-Instruct via llama-server DeepSeek V4.1-Flash VA_SYNTHESIS_MODEL
API keys needed none GROQ_API_KEY + DEEPSEEK_API_KEY —

Mixed setups work, e.g. local STT + hosted vision:

VA_PROFILE=local \
VA_VLM_MODEL=deepseek:deepseek-flash \
VA_SYNTHESIS_MODEL=deepseek:deepseek-flash \
DEEPSEEK_API_KEY=... uv run va analyse /tmp/va-sample.mp4

or hosted STT with a local VLM:

VA_PROFILE=hosted \
VA_VLM_MODEL=local:Qwen3-VL-4B-Instruct \
VA_SYNTHESIS_MODEL=local:Qwen3-VL-4B-Instruct \
GROQ_API_KEY=... uv run va analyse /tmp/fa.mp4

Local vision + synthesis (llama-server)

Download/build llama.cpp and start a server with Qwen3-VL-4B and the multimodal projector. The exact command used by the project (PLAN.md §5):

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
  • --jinja + a tool-capable chat template are required because pydantic-ai's structured output is a tool call by default.
  • --image-max-tokens 448 is the most important CPU-affordability flag; frames are sent as base64 JPEG (BinaryImage) at ≤768 px.
  • -t 14 matches this machine's 16 cores (leave a couple for the OS). Qwen3-VL-4B Q4_K_M is ≈2.5 GB + mmproj ≈0.3–0.8 GB.
  • Expect roughly 10–20 s per 448–576 px frame on CPU; the 2B model is the speed fallback (VA_VLM_MODEL=local:Qwen3-VL-2B-Instruct).
  • va doctor shows the same command when the server is unreachable; va describe prints it in the error message.

The server must report the model name you configure (Qwen3-VL-4B-Instruct above). Any OpenAI-compatible server can replace it via VA_LLAMA_SERVER_URL.


Hosted profile

Fully hosted (audio leaves the machine, diarization stays local):

export VA_PROFILE=hosted
export GROQ_API_KEY=...        # hosted STT: whisper-large-v3-turbo
export DEEPSEEK_API_KEY=...    # vision + synthesis: deepseek:deepseek-flash
uv run va analyse video.mp4

Alternate LLM routes (same client shape, no code changes):

Route Model string Key / extra env
DeepSeek API deepseek:deepseek-flash (alias tracks latest flash) DEEPSEEK_API_KEY
OpenRouter openrouter:deepseek/deepseek-v4.1-flash-1017 (dated snapshot) OPENROUTER_API_KEY
Ollama cloud ollama:deepseek-v4.1-flash:1017 ollama_api_key in config.toml (or OLLAMA_API_KEY); endpoint defaults to https://ollama.com/v1

(Hosted STT is a plain OpenAI-compatible HTTP client, so Groq needs only GROQ_API_KEY; the groq: pydantic-ai provider prefix is not part of this install.)

Hosted STT points at Groq by default; any OpenAI-transcriptions endpoint works:

export VA_STT_API_BASE_URL=https://api.groq.com/openai/v1
export VA_STT_API_MODEL=whisper-large-v3-turbo
export GROQ_API_KEY=...

Rough hosted cost for an hour of video (from PLAN.md): STT ≈ $0.04, ~64 low-detail frames a few cents, synthesis ≈ 3–5 cents → ≈ $0.10–0.15, with repeated questions hitting the cache.

Mixed setup: local Parakeet STT + DeepSeek via Ollama Cloud

The recommended hosted configuration for this machine — audio transcription stays local (Parakeet, no key, no upload), DeepSeek handles vision and report/QA through Ollama Cloud. Put this in ~/.config/video-analyse/config.toml:

profile = "local"
stt_backend = "parakeet"                             # local STT: no key, no upload
vlm_model = "ollama:deepseek-v4.1-flash:1017"        # vision via Ollama Cloud
synthesis_model = "ollama:deepseek-v4.1-flash:1017"  # report + Q&A via Ollama Cloud
ollama_api_key = ""   # <- paste your key from https://ollama.com here

ollama: specs resolve their endpoint and key from ollama_base_url / ollama_api_key (config.toml or VA_OLLAMA_* env vars), falling back to the OLLAMA_BASE_URL / OLLAMA_API_KEY environment variables, with https://ollama.com/v1 as the endpoint default. A remote endpoint without a key fails fast with these instructions; a local Ollama daemon needs ollama_base_url = "http://localhost:11434/v1" and no key.


MCP server and pi integration

va serve-mcp runs FastMCP 4.1.4 over stdio by default (HTTP is opt-in with --transport http --port 8000). Six tools:

Tool Parameters Returns
transcribe_video source, diarize=None Transcript (segments, words, speaker labels when diarized). diarize follows VA_DIARIZE; pass false to skip the extra model pass.
extract_keyframes source, max_shots=64, max_images=16 Shot list + up to 16 keyframe JPEGs as image content blocks
analyze_video source, max_shots=64, diarize=None, describe=True, force=False, include_words=False, transcript_max_chars=20000 Validated VideoReport with a bounded transcript (the expensive tool)
analyze_moment source, t_start, t_end, describe=False, max_frames=4, width=768 Up to 8 frames + transcript slice + cached shot descriptions; describe=true adds one VLM request
get_frame_at source, t, width=768 Text summary + one JPEG frame block + structured timestamp/size (no model, near-free)
ask_video source, question, allow_analysis=False, no_cache=False Cached-only AnswerResult with [MM:SS] citations; set allow_analysis=true to run the full pipeline when no report exists, no_cache=true to bypass the answer cache

All tools share the same stage cache as the CLI, so the cheapest tool for the job is also the cheapest call: get_frame_at and analyze_moment never run a model by default; extract_keyframes never runs STT or a VLM; transcribe_video is the cheapest model call; analyze_video pays for everything once and later calls are cache hits. ask_video does not silently escalate to a full analysis unless allow_analysis=true, and repeated questions are answered from the answer cache.

Register the server with pi as a project-level MCP server:

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

Notes for agent hosts:

  • The server blocks on stdio and logs on stderr; it is safe to spawn per session.
  • analyze_video can run for many minutes on CPU (STT + one VLM call per shot). Raise pi's per-request MCP timeout accordingly, or steer the agent to transcribe_video, extract_keyframes, analyze_moment and get_frame_at first.
  • The first call of each local model downloads its weights (see below); pre-warm with the CLI if that latency matters, e.g. uv run va transcribe sample.mp4.
  • VA_*/provider environment variables are read by the server process; configure them in the environment pi spawns it with.

A quick manual check (also exercises the real stdio handshake):

import asyncio
from fastmcp import Client
from fastmcp.client.transports import StdioTransport


async def main():
    transport = StdioTransport(command=".venv/bin/va", args=["serve-mcp"])
    async with Client(transport) as client:
        print([t.name for t in await client.list_tools()])
        result = await client.call_tool("get_frame_at", {"source": "/tmp/va-sample.mp4", "t": 3.5})
        print(result.content[0].type, len(result.content[0].data))


asyncio.run(main())

Privacy

VA_PROFILE=local (default) — no audio, frames, transcripts or reports are uploaded:

  • All STT, diarization, vision and synthesis run on this machine. llama-server is addressed at 127.0.0.1 by default, and va doctor only probes that local URL.
  • First runs download model weights: Parakeet/Whisper/Silero VAD from Hugging Face, sherpa-onnx diarization assets from pinned GitHub release URLs (size + SHA-256 verified in model_assets.py). Downloads are one-time and need network access.
  • va fetch <url> (or any command given an http(s) URL) downloads that media from the remote host — obviously required for URL ingest, and the only network traffic in a local run besides model downloads.
  • va doctor reads only environment-variable presence, never values.

VA_PROFILE=hosted — opt-in, and per-stage:

  • Audio leaves the machine for hosted STT: the extracted 16 kHz mono audio is transcoded to FLAC (chunked if >90 MB) and POSTed to the configured /audio/transcriptions endpoint (Groq by default) with GROQ_API_KEY / VA_STT_API_KEY / OPENAI_API_KEY.
  • Keyframes and derived text leave the machine for hosted vision/synthesis: JPEG frames are sent as base64 image_url data URLs, together with the transcript/shot text in the prompt, to DeepSeek (or OpenRouter/Ollama-cloud/OpenAI, according to VA_VLM_MODEL/VA_SYNTHESIS_MODEL).
  • Diarization still runs locally (sherpa-onnx) in the hosted profile; only the transcript labels derived from it are sent along with the other prompt text.
  • Hosted Q&A sends the cached report (and its transcript when it fits the prompt budget) to the synthesis provider for every va ask; the answer is then cached locally.
  • API keys are read from the environment and are never written to the cache, logs or report. Prompts/responses are not retained beyond the provider's own policies.
  • The local cache (~/.cache/video-analyse) is not encrypted; it can contain audio, keyframes, transcripts and reports. Delete the directory to purge it.

Mixed profiles: whichever stage is pointed at a hosted model spec sends its own inputs (hosted STT → audio; hosted VLM/synthesis → frames + prompt text); the other stages stay local.


Architecture

Both front doors — the va CLI and the MCP server — are thin adapters over analysis.py: they map argv or tool arguments to AnalysisOptions, call one outcome-named operation, and shape the result. The pipeline and stage cache remain the implementation behind that interface.

source file / URL
      │
      ▼
 ingest (yt-dlp for URLs) ──► probe (ffprobe → MediaFacts)
      │                              │
      ├──► audio.wav (16 kHz mono) ──┼──► shots (PySceneDetect adaptive)
      │        │                     │         │
      │        ▼                     │         ▼
      │   transcribe (Parakeet |    │   keyframes (ffmpeg midpoint,
      │   faster-whisper |           │   ≤768 px JPEG) + phash dedup
      │   hosted OpenAI-transcriptions)        │
      │        │                     │         ▼
      │        ▼                     │   describe (pydantic-ai Agent →
      │   diarize (sherpa-onnx,      │   llama-server Qwen3-VL-4B or hosted VLM,
      │   optional pyannote)         │   one ShotDescription per shot)
      │        │                     │         │
      └────────┴──────────┬──────────┴─────────┘
                          ▼
              report (pydantic-ai Agent → ReportCore,
              assembled with code-owned facts into VideoReport)
                          │
                          ▼
              report.md · report.json · transcript.srt
              + cached stage-report-<key>.json · artifacts.json

Every stage is a pure-ish function inputs → pydantic model cached by content hash:

~/.cache/video-analyse/
  <sha256(source bytes)[:16]>/
    audio.wav
    keyframes/shot-<index>.jpg
    stage-probe-<key>.json
    stage-audio-<key>.json
    stage-transcribe-<key>.json
    stage-diarize-<key>.json
    stage-shots-<key>.json
    stage-describe-<key>.json
    stage-report-<key>.json
    artifacts.json
  models/                     # checksum-verified sherpa-onnx assets

Stage keys hash the stage name plus canonical JSON of its inputs (upstream artifact key, model spec, language, options), so changing a model or a flag invalidates exactly the affected stages. Writes are atomic; a corrupt artifact is treated as a cache miss.

One-time invalidation (architecture deepening, 2026-11). Probe keys used to include the source string; they now hash the content hash only, so two names for identical bytes share one probe entry (CONTRACTS.md §4). Probe artifacts written before that change are orphaned and simply ignored: the first run after upgrading recomputes them with one cheap ffprobe call per source. No other stage or model changed shape, so nothing else needs recomputing; the leftover stage-probe-*.json files are harmless and can be deleted.

Module Responsibility
models.py All pydantic data models (Word, Segment, Transcript, Shot, ShotDescription, VideoReport, Artifacts, …)
config.py pydantic-settings Settings (VA_*) and per-profile model/back-end resolution
ingest.py file/URL → local path (yt-dlp), info JSON
media.py ffprobe, audio extraction, adaptive shot detection, keyframe extraction, phash dedup
transcribe/ Transcriber protocol + Parakeet ONNX, faster-whisper, hosted OpenAI-transcriptions backends and the registry
diarize.py sherpa-onnx (default) / optional pyannote speaker turns, word-level speaker attribution
model_assets.py Pinned, checksum-verified downloads of the sherpa-onnx diarization models
llm.py pydantic-ai model factory (local:, bare names, provider strings) + llama-server health check
vision.py Shot describer agent (ShotDescription), frame prompts, actionable server-down error
synthesis.py Report synthesis (ReportCore → VideoReport) and grounded Q&A agents, prompt budgeting
report.py Deterministic Markdown rendering
srt.py SRT rendering (word-derived cues, optional speaker labels)
cache.py Content-addressed StageCache (sha256 keys, atomic writes, corruption = miss)
pipeline.py Stage descriptor table, dependency-aware scheduling, content cache, --force invalidation, URL ingest, injectable stages for tests
analysis.py Deep analysis interface: AnalysisOptions, outcome operations (analyse, transcript, shots, describe, probe, ask, moment, frame, cached), want-set policy, structured progress, error diagnosis
cli.py Typer app va (all stages + moment, JSON mode, rich rendering, exit-code mapping); adapter over analysis.py
mcp_server.py FastMCP server with the six agent tools (stdio default, HTTP opt-in); adapter over analysis.py
doctor.py Environment/profile/model/key/cache diagnostics

Library use is supported directly:

import asyncio
from video_analyse import analysis
from video_analyse.analysis import AnalysisOptions
from video_analyse.config import Settings


async def main() -> None:
    options = AnalysisOptions()
    artifacts = await analysis.analyse("/tmp/va-sample.mp4", options, settings=Settings())
    print(len(artifacts.shots), artifacts.transcript.duration)


asyncio.run(main())

The analysis operations are the normal library entry point: they compute the want-set, apply AnalysisOptions to Settings, read cached context at the current option keys and return models or raise an actionable error. probe, analyse, shots and describe return the run's assembled Artifacts (artifacts.shots, artifacts.media, ...), so one call is one scheduler run and both front doors render from the same value. Pipeline remains available for callers that need the raw scheduler, and individual stage functions (probe, extract_audio, detect_shots, extract_keyframes, diarize_audio, describe_shots, synthesise_report, answer_question, render_markdown, render_srt) are importable on their own.


Benchmarks

Accuracy and throughput benchmarks have not been measured yet; the table below is the template to fill in on a quiet machine (hyperfine for wall time, a known transcript for WER). The synthetic tone fixture cannot produce a meaningful WER (it has no speech), so the second table only records smoke-test wall times.

Date Backend Model (quant) Hardware Audio (min) Wall (s) RTF WER / notes
— parakeet nemo-parakeet-tdt-0.6b-v3 (int8 ONNX) Intel Core Ultra X7 358H, CPU TBD TBD TBD TBD
— parakeet nemo-parakeet-tdt-0.6b-v2 (int8 ONNX) same TBD TBD TBD English-only; TBD
— whisper large-v3-turbo (int8, faster-whisper) same TBD TBD TBD TBD
— whisper tiny (int8, faster-whisper) same TBD TBD TBD TBD
— vlm Qwen3-VL-4B-Instruct Q4_K_M (llama-server) same n/a TBD s/frame — quality review TBD
— vlm DeepSeek V4.1-Flash (hosted) network n/a TBD — quality/cost review TBD

Smoke timings observed while integrating (10 s synthetic clip unless a row says otherwise; no WER claim — the tone has no speech):

Command Wall time Notes
va probe < 1 s ffprobe only
va shots --max-shots 8 ≈ 0.8 s cold, < 0.3 s cached 1 shot on the degenerate fixture (0 cuts detected → full-length shot)
va transcribe (VA_WHISPER_MODEL=tiny) ≈ 1.2 s cold, ≈ 0.3 s cached int8 CPU; VAD removes the sine tone → 0 segments
va transcribe (Parakeet v3) ≈ 13.6 s first run including the 640 MB int8 download; ≈ 4.5 s cached-model speech run; sub-second cached empty transcript on the tone
va transcribe (VA_WHISPER_MODEL=tiny, 11 s JFK speech) ≈ 1.5 s 1 segment, 22 words, correct word timings
va diarize (sherpa) ≈ 3.1 s cold including ≈ 46 MB asset download; ≈ 0.4 s cached (tone) / ≈ 1.6 s on the 11 s speech clip 0 turns on a pure tone; 4×S1 turns + speaker-labelled segments on the one-speaker speech clip
va serve-mcp starts in ~1 s and blocks on stdio six tools listed over a real stdio handshake; get_frame_at returned a 29 KB JPEG

Testing

uv sync
uv run pytest tests/ -q                  # full suite; offline by default
uv run ruff check .
uv run ruff format --check src tests

Current state: 431 passed, 2 skipped (the two skips are the opt-in real-model smoke tests). The suite never downloads weights and never opens a network socket: local backends are exercised through their pure mapping functions and injected fakes, hosted STT through httpx.MockTransport, vision/synthesis through pydantic-ai FunctionModel/TestModel, and the MCP server through FastMCP's in-memory client. The sample_video fixture (10 s, 640×360 @ 12 fps, 440 Hz tone) is generated with ffmpeg and skipped cleanly if ffmpeg is missing.

Opt-in tests that load real models (they download weights and are slow):

VA_HEAVY_TESTS=1 uv run pytest tests/test_transcribe.py -q
VA_HEAVY_TESTS=1 VA_HEAVY_WHISPER_MODEL=tiny uv run pytest tests/test_transcribe.py -q

Manual smoke (no pytest), as used for the integration run:

ffmpeg -y -f lavfi -i testsrc2=duration=10:size=640x360:rate=12 \
  -f lavfi -i sine=frequency=440:duration=10 \
  -c:v libx264 -preset veryfast -c:a aac -shortest /tmp/va-sample.mp4

uv run va probe /tmp/va-sample.mp4
uv run va shots /tmp/va-sample.mp4 --max-shots 8
uv run va doctor
VA_WHISPER_MODEL=tiny uv run va transcribe /tmp/va-sample.mp4   # empty-but-valid transcript
uv run va diarize /tmp/va-sample.mp4                              # downloads sherpa assets once
timeout 3 uv run va serve-mcp < <(sleep 6); echo "exit=$? (124 = still running)"

A pure sine tone contains no speech, so an empty transcript/zero speaker turns is the correct result for /tmp/va-sample.mp4; the checks are that the JSON validates against the Transcript model and that a second run is a fast cache hit.

Optional real-speech sanity check (needs network):

curl -sSLo /tmp/jfk.wav \
  https://github.com/ggerganov/whisper.cpp/raw/master/samples/jfk.wav
VA_WHISPER_MODEL=tiny uv run va transcribe /tmp/jfk.wav --json   # 1 segment, 22 words
uv run va transcribe /tmp/jfk.wav --json                          # Parakeet v3: 4 segments, 22 words
uv run va diarize /tmp/jfk.wav --json                             # 4×S1 turns, segments labelled S1

Current limitations & untested paths

These are known, deliberate v1 boundaries — the README claims nothing more than what was verified. Milestones M5-M7 are partially verified: the STT backends, diarization, caching, CLI and MCP surfaces are exercised by the offline suite and smoke runs, while the WER/speed benchmark, a real 5-minute-video analysis and a live pi ask_video session still need a quiet machine and/or a running model server:

  • Vision, synthesis and the full va analyse / va ask / analyze_video chain were tested only against offline pydantic-ai mocks, not against a real llama-server with Qwen3-VL-4B. Unit tests use FunctionModel; a full va analyse and va ask run over the real pipeline was smoke-tested with pydantic-ai's TestModel (VA_VLM_MODEL=test VA_SYNTHESIS_MODEL=test) and wrote a valid report.md, but no real frame has been described and no real report has been synthesised end-to-end on this machine (llama-server was not installed during integration). va describe was smoke-tested only for its server-down error path.
  • Hosted paths are unexercised: no live calls were made to Groq STT, DeepSeek, OpenRouter, Ollama cloud or OpenAI (no API keys). The OpenAI-transcriptions client is covered by httpx.MockTransport, and provider model construction is unit-tested with dummy keys.
  • Parakeet v3 was smoke-tested on the sine-tone fixture (empty transcript, as expected) and on an 11 s English speech clip (JFK sample: 4 segments, 22 words with plausible word timings). Parakeet v2 (--lang en) was not run at all. No WER or rigorous speed benchmark exists yet (see Benchmarks).
  • Diarization quality is unmeasured: the tone produced zero turns; the real 11 s JFK clip produced four S1 turns and labelled every segment S1 (single-speaker case). Multi-speaker attribution and clustering quality have only been verified with synthetic SpeakerTurns in unit tests. The optional pyannote backend is implemented but its extra was not installed or run.
  • URL ingest (va fetch, URL sources, yt-dlp) was smoke-tested with a real direct MP4 URL (va fetch downloaded and returned a local path/title) and is unit-tested with fakes; site-specific extractors and blocked sites remain a risk.
  • MCP stdio transport was verified with a real subprocess (tool list + get_frame_at returning a JPEG). The HTTP transport was not smoke-tested, and analyze_video was not called against a live model server through MCP.
  • va analyse/va ask on the local profile fail with the provider's raw Connection error. when llama-server is down; only va describe and va doctor preflight the server and print the exact startup command. Start the server first.
  • CPU only: no Vulkan/iGPU or CUDA offload; long videos are processed by chunked STT and a capped number of shots, and long transcripts by a map-reduce summariser. Hosted runs can still hit provider rate limits.
  • va shots implements only the adaptive detector; vision sends one 448-576 px-class frame per request with hosted detail: low (grouping 2-3 short shots per request remains future work), and --format srt prints to stdout (while va analyse also writes transcript.srt). Keyframe dedup drops the whole later duplicate shot, so the shot timeline can have gaps when the same visual recurs (the transcript is unaffected).
  • PyAV 19 incompatibility workaround: faster-whisper 1.2.1 calls av.open(..., metadata_errors=...), which PyAV 19 removed. The whisper backend therefore decodes the 16 kHz mono WAV with the stdlib wave module and passes a float32 array to faster-whisper (see transcribe/faster_whisper.py); path/stream inputs other than 16-bit 16 kHz WAV are rejected with an actionable error.
  • The local cache is unencrypted and grows with every analysed source; there is no TTL or cache-pruning command yet (delete VA_CACHE_DIR to purge).
  • PLAN.md and CONTRACTS.md were reformatted by the repository-wide ruff format . during integration (code fences only; no content changes intended).

License

MIT (see pyproject.toml).