Implement v1: local-first video analysis toolkit (library + va CLI + MCP server)

Per PLAN.md: ingest (yt-dlp) → probe/audio (ffmpeg) → STT (Parakeet v3 ONNX,
faster-whisper, OpenAI-transcriptions/Groq hosted) → diarization (sherpa-onnx,
optional pyannote) → shots (PySceneDetect + phash dedup) → vision (pydantic-ai
over llama-server Qwen3-VL-4B or hosted DeepSeek) → synthesis (map-reduce
VideoReport + grounded Q&A). Content-addressed per-stage cache, fully-local or
fully-hosted profiles (VA_PROFILE), typer CLI with doctor, FastMCP server with
six agent-facing tools, structured pydantic outputs throughout.

316 tests passed, 2 skipped (opt-in heavy tests); ruff clean.
STT/diarization/shot/media/MCP-stdio paths verified with real models and
fixtures; vision/synthesis covered by offline FunctionModel tests (no
llama-server available in-session). See README.md for usage and limitations.
This commit is contained in:
alex committed 2026-10-30 17:13:11 +00:00
commit 3ff45ffa78
44 files changed
+19681

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
.venv/
__pycache__/
.pytest_cache/
.ruff_cache/
*.egg-info/
dist/
build/
.coverage
+1
View File
@@ -0,0 +1 @@
3.13
+664
View File
@@ -0,0 +1,664 @@
# 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.
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/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). 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. **Do not modify foundation files** (`src/video_analyse/__init__.py`, `models.py`, `config.py`,
`llm.py`, `transcribe/base.py`, `pyproject.toml`, `tests/conftest.py`, this file). If a change
is genuinely required, note it in your final report instead of editing silently; 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`, `config.py` |
| **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`, `config.py` |
| **C — diarization** | `diarize.py`, `model_assets.py`, `tests/test_diarize.py`, `tests/test_model_assets.py` | `models.py`, `config.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`, `config.py`, `llm.py` |
| **E — cache & pipeline** | `cache.py`, `pipeline.py`, `tests/test_cache.py`, `tests/test_pipeline.py` | all stage modules, `models.py`, `config.py` |
| **F — CLI & MCP** | `cli.py` (replaces the stub), `mcp_server.py`, `tests/test_cli.py`, `tests/test_mcp.py` | stage modules, `pipeline.py`, `synthesis.py` |
| **Foundation (frozen)** | `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, and
`llm.llama_server_up(settings)`.
* `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) -> IngestResult
IngestResult(BaseModel): path: Path; info: dict[str, Any] = {}; downloaded: bool; title: str | None = None
media.py: async def probe(path: Path) -> MediaInfo
media.py: async def extract_audio(path: Path, workdir: Path) -> Path # 16 kHz mono s16le WAV at workdir/audio.wav
media.py: async def detect_shots(path: Path, info: MediaInfo, *, max_shots: int = 64, min_scene_len: float = 0.6) -> list[Shot]
media.py: async def extract_keyframes(path: Path, shots: list[Shot], workdir: Path, *, width: int = 768, quality: int = 85) -> list[Shot] # fills Shot.keyframe (JPEG in workdir/keyframes/), frame at shot 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
transcribe/__init__.py: def get_transcriber(settings: Settings) -> Transcriber
transcribe/faster_whisper.py: class FasterWhisperTranscriber(Transcriber) # WhisperModel(settings.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: async def diarize_audio(wav: Path, *, settings: Settings) -> 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: async def describe_shots(shots: list[Shot], transcript: Transcript | None, *, settings: Settings) -> list[Shot] # pydantic-ai agent, output_type=ShotDescription, one call per shot, fills .description
vision.py: async def llama_server_up(settings: Settings) -> bool
synthesis.py: async def synthesise_report(shots: list[Shot], transcript: Transcript | None, info: MediaInfo, *, settings: Settings) -> VideoReport # agent outputs ReportCore, code assembles VideoReport
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()
pipeline.py: class Pipeline # __init__(settings: Settings, stages: Mapping[str, Callable] | None = None); async def run(source: str, *, want: set[str], force: bool = False, progress: Callable[[str], None] | None = None) -> Artifacts
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
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
cli.py: typer app "va": fetch, probe, transcribe, diarize, shots, describe, analyse, ask, doctor, serve-mcp (+ main() entry); flags exactly per PLAN.md section 5
mcp_server.py: FastMCP("video-analyse") with exactly 6 tools: transcribe_video, extract_keyframes, analyze_video, analyze_moment, get_frame_at, ask_video; run() stdio default
```
---
## 4. `models.py` — field-by-field contract (implemented, frozen)
```python
MediaInfo(path: Path, source: str, duration: float, width: int | None = None,
height: int | None = None, fps: float | None = None, has_audio: bool,
size_bytes: int, format: str | None = None, video_codec: str | None = None,
audio_codec: str | None = None, extra: dict[str, Any] = {})
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)
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: MediaInfo | 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`).
---
## 5. `config.py` (implemented, frozen)
```python
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 | "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 # "sherpa" | "pyannote"
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() # explicit stt_backend, else "parakeet" (local) / "openai-transcriptions" (hosted)
s.resolved_vlm() # explicit vlm_model, else "local:Qwen3-VL-4B-Instruct" / "deepseek:deepseek-flash"
s.resolved_synthesis() # same rule as resolved_vlm
```
`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`.
---
## 6. `llm.py` (implemented, frozen) + verified pydantic-ai facts
```python
from video_analyse.config import Settings
from video_analyse.llm import build_model, llama_server_up
settings = Settings()
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(settings.resolved_vlm(), settings=settings)
up = await llama_server_up(settings) # GET {url}/models, 2 s
```
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
```python
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):
```python
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")`.
Agent construction (verified, no request is made):
```python
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):
```python
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
```python
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)
```python
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.
* 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)
```bash
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
```python
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)
```python
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)
```python
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
```python
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
```python
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
```python
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)
```python
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.
+390
View File
@@ -0,0 +1,390 @@
# 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:
```python
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 | `deepseek-v4.1-flash:1017` (via `OllamaModel` or Ollama's OpenAI-compatible endpoint) | `OLLAMA_API_KEY` | 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 -`
- uniform fallback sampling: `-vf fps=0.5,scale=768:-2`
- **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 → MediaInfo │
└───────────────┬────────────────────────────────┘
│
┌─────────────────────┴─────────────────────┐
▼ ▼
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 `SpeakerTurn`s 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`):
```python
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> # MediaInfo 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):
```bash
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:
```bash
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 → `SpeakerTurn`s; 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).
+705
View File
@@ -0,0 +1,705 @@
# video-analyse
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](https://github.com/badlogic/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](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](#current-limitations--untested-paths).
---
## 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](https://docs.astral.sh/uv/) | environment and dependency management | any recent version |
`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
```bash
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](#privacy).
### 3. Optional extras
```bash
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](#local-vision--synthesis-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:
```bash
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
```bash
uv run va probe /tmp/va-sample.mp4
uv run va probe /tmp/va-sample.mp4 --json
```
Returns a `MediaInfo`: duration, resolution, frame rate, codecs, size, format and the raw
ffprobe streams under `extra.ffprobe`.
### Download a URL
```bash
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
```bash
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 at the shot midpoint
(≤768 px JPEG) + perceptual-hash dedup (`imagehash`) + merging of very short adjacent
shots. 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
```bash
# 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
# transcript + speaker labels in one go
uv run va transcribe /tmp/va-sample.mp4 --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.
### Diarize
```bash
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)
```bash
# 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
```bash
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
```
`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; `--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
```bash
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; with a reachable model the
report stage can also be created on demand from cached transcript/shots. 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.
### Doctor
```bash
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
```bash
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. **Setting it explicitly also selects the `whisper` backend** when `VA_STT_BACKEND` is unset (so `VA_WHISPER_MODEL=tiny va transcribe` works as expected); set `VA_STT_BACKEND=parakeet` to keep Parakeet. |
| `VA_DIARIZE` | `true` | Run diarization in `va analyse`/`va diarize`; `false` or `--no-diarize` skips the stage. `va transcribe` defaults to off unless `--diarize` is passed. |
| `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:
```bash
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:
```bash
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):
```bash
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):
```bash
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` + `OLLAMA_BASE_URL` |
(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:
```bash
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.
---
## 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` | Cached-only `AnswerResult` with `[MM:SS]` citations; set `allow_analysis=true` to run the full pipeline when no report exists |
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:
```bash
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):
```python
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
```
source file / URL
│
▼
ingest (yt-dlp for URLs) ──► probe (ffprobe → MediaInfo)
│ │
├──► 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.
| 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 orchestration, dependency-aware caching, `--force` invalidation, URL ingest, injectable stages for tests |
| `cli.py` | Typer app `va` (all stages, JSON mode, rich rendering, error mapping) |
| `mcp_server.py` | FastMCP server with the six agent tools (stdio default, HTTP opt-in) |
| `doctor.py` | Environment/profile/model/key/cache diagnostics |
Library use is supported directly:
```python
import asyncio
from video_analyse.config import Settings
from video_analyse.pipeline import Pipeline
async def main() -> None:
artifacts = await Pipeline(Settings()).run(
"/tmp/va-sample.mp4", want={"probe", "shots", "transcribe"}
)
print(len(artifacts.shots), artifacts.transcript.duration)
asyncio.run(main())
```
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; `Pipeline` is the normal
entry point because it handles caching and ordering.
---
## 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
```bash
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: **296 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):
```bash
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:
```bash
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):
```bash
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](#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
`SpeakerTurn`s 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 (the `--detector` flag rejects other
names); 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`).
+72
View File
@@ -0,0 +1,72 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "video-analyse"
version = "0.1.0"
description = "Local-first, agent-friendly video analysis toolkit (transcript + shots + report)"
readme = "README.md"
requires-python = ">=3.13,<3.14"
license = { text = "MIT" }
authors = [{ name = "video-analyse" }]
dependencies = [
"pydantic>=2.11",
"pydantic-ai>=2.63,<3",
"pydantic-settings>=2.6",
"typer>=0.15",
"rich>=13",
"httpx>=0.27",
"faster-whisper>=1.2",
"onnx-asr[cpu,hub]>=0.12",
"sherpa-onnx>=1.10",
"scenedetect>=0.6.5",
"opencv-python-headless>=4.10",
"imagehash>=4.3",
"Pillow>=10.4",
"yt-dlp>=2025.10",
"fastmcp>=4.1",
]
[project.optional-dependencies]
pyannote = ["pyannote.audio>=4.0"]
[project.scripts]
va = "video_analyse.cli:main"
[dependency-groups]
dev = [
"pytest>=8",
"pytest-asyncio>=0.24",
"ruff>=0.8",
]
[tool.hatch.build.targets.wheel]
packages = ["src/video_analyse"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"UP", # pyupgrade
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"SIM", # flake8-simplify
"RUF", # ruff-specific rules
]
ignore = [
"B008", # function call in default argument (typer uses this pattern)
]
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]
+3
View File
@@ -0,0 +1,3 @@
"""video_analyse — local-first, agent-friendly video analysis toolkit."""
__version__ = "0.1.0"
+331
View File
@@ -0,0 +1,331 @@
"""Content-addressed cache for pipeline stage artifacts.
Layout under the configured cache directory::
<cache_dir>/
<source_sha256[:16]>/
audio.wav # media.extract_audio output
keyframes/shot-<index>.jpg # media.extract_keyframes output
stage-<stage>-<key>.json # one artifact per stage (pydantic or raw JSON)
artifacts.json # the pipeline's final Artifacts model
``<key>`` is :meth:`StageCache.stage_key` over the stage's *inputs* (upstream artifact
keys, model specs, options), so a stage is recomputed exactly when its inputs change.
Hashes are content hashes: editing or re-encoding a source file produces a new
``<source_sha16>`` directory and leaves the old artifacts untouched.
All writes go through a temporary file plus :func:`os.replace`, so an interrupted run
never leaves a half-written artifact behind (a corrupt artifact is treated as a cache
miss by the pipeline).
"""
from __future__ import annotations
import contextlib
import hashlib
import json
import logging
import os
import re
import tempfile
from collections.abc import Mapping
from pathlib import Path
from typing import Any, TypeVar
from pydantic import BaseModel, ValidationError
__all__ = [
"ARTIFACTS_FILE_NAME",
"AUDIO_FILE_NAME",
"HASH_CHUNK_SIZE",
"KEYFRAMES_DIR_NAME",
"SOURCE_HASH_PREFIX_LENGTH",
"StageCache",
]
logger = logging.getLogger(__name__)
#: Read size for streaming file hashes (1 MiB keeps memory flat on multi-GB videos).
HASH_CHUNK_SIZE = 1024 * 1024
#: Number of leading hex characters of a source hash used as the per-source directory.
SOURCE_HASH_PREFIX_LENGTH = 16
AUDIO_FILE_NAME = "audio.wav"
KEYFRAMES_DIR_NAME = "keyframes"
ARTIFACTS_FILE_NAME = "artifacts.json"
_HEX_DIGITS = frozenset("0123456789abcdef")
_STAGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*")
_KEY_RE = re.compile(r"[0-9a-f]{8,64}")
ModelT = TypeVar("ModelT", bound=BaseModel)
def _source_prefix(source_sha: str) -> str:
"""Validate a source sha256 and return the 16-character directory prefix.
Both a full 64-character digest (as returned by :meth:`StageCache.source_hash`)
and an already-shortened prefix of at least 16 hex characters are accepted.
Raises:
TypeError: ``source_sha`` is not a string.
ValueError: ``source_sha`` is not at least 16 lowercase hex characters.
"""
if not isinstance(source_sha, str):
raise TypeError(f"source_sha must be a string, got {type(source_sha).__name__}")
digest = source_sha.strip().lower()
if len(digest) < SOURCE_HASH_PREFIX_LENGTH or any(ch not in _HEX_DIGITS for ch in digest):
raise ValueError(
f"invalid source sha256 {source_sha!r}; expected at least "
f"{SOURCE_HASH_PREFIX_LENGTH} hex characters (use StageCache.source_hash)"
)
return digest[:SOURCE_HASH_PREFIX_LENGTH]
def _write_atomically(path: Path, text: str) -> Path:
"""Write ``text`` to ``path`` via a temporary file in the same directory."""
path.parent.mkdir(parents=True, exist_ok=True)
handle, temporary = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
try:
with os.fdopen(handle, "w", encoding="utf-8") as stream:
stream.write(text)
os.replace(temporary, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(temporary)
raise
return path
class StageCache:
"""Hashed artifact store for one cache directory.
The cache is not bound to a source: every path helper takes the source sha256
(or at least its 16-character prefix), which keeps the object reusable for
multi-source runs and trivial to test.
"""
def __init__(self, cache_dir: Path | str) -> None:
"""Bind the cache to ``cache_dir`` (``~`` is expanded, nothing is created)."""
self.cache_dir = Path(cache_dir).expanduser()
# ------------------------------------------------------------------ #
# hashing
# ------------------------------------------------------------------ #
def source_hash(self, path: Path | str) -> str:
"""Return the sha256 hex digest of a file's contents.
The file is streamed in :data:`HASH_CHUNK_SIZE` blocks, so hashing a
multi-gigabyte video does not load it into memory.
Raises:
ValueError: ``path`` does not exist or is not a regular file.
OSError: the file cannot be read.
"""
target = Path(path).expanduser()
if not target.exists():
raise ValueError(f"Cannot hash missing file: {target}")
if not target.is_file():
raise ValueError(f"Cannot hash non-file path: {target}")
digest = hashlib.sha256()
with target.open("rb") as stream:
for block in iter(lambda: stream.read(HASH_CHUNK_SIZE), b""):
digest.update(block)
return digest.hexdigest()
def stage_key(self, stage_name: str, params: Mapping[str, Any] | None = None) -> str:
"""Return the content key of a stage from its name and input parameters.
``params`` is serialised as canonical JSON -- sorted keys, no insignificant
whitespace -- and hashed with sha256 together with the stage name, so
``{"a": 1, "b": 2}`` and ``{"b": 2, "a": 1}`` share a key while any changed
value produces a different one. Values JSON cannot encode (``Path``, enums, ...)
are rendered with ``str``; dict keys must be strings.
Args:
stage_name: stage identifier (letters, digits, ``-``, ``_``).
params: JSON-like mapping of the stage's inputs; ``None`` means empty.
Returns:
A 64-character lowercase hex sha256 digest.
Raises:
ValueError: ``stage_name`` is not filename-safe.
TypeError: ``params`` is not a mapping.
"""
name = self._check_stage_name(stage_name)
if params is not None and not isinstance(params, Mapping):
raise TypeError(f"params must be a mapping, got {type(params).__name__}")
payload: dict[str, Any] = dict(params or {})
canonical = json.dumps(
{"stage": name, "params": payload},
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
default=str,
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
# ------------------------------------------------------------------ #
# path layout
# ------------------------------------------------------------------ #
def source_dir(self, source_sha: str) -> Path:
"""Per-source directory ``<cache_dir>/<source_sha16>/``."""
return self.cache_dir / _source_prefix(source_sha)
def asset_dir(self, source_sha: str) -> Path:
"""Alias of :meth:`source_dir`: where derived media assets live."""
return self.source_dir(source_sha)
def audio_path(self, source_sha: str) -> Path:
"""``<source dir>/audio.wav`` -- the 16 kHz mono WAV for speech-to-text."""
return self.source_dir(source_sha) / AUDIO_FILE_NAME
def keyframes_dir(self, source_sha: str) -> Path:
"""``<source dir>/keyframes/`` -- the shot keyframe JPEGs."""
return self.source_dir(source_sha) / KEYFRAMES_DIR_NAME
def keyframe_path(
self, source_sha: str, shot_index: int, *, namespace: str | None = None
) -> Path:
"""``<source dir>/keyframes/[<namespace>/]shot-<index>.jpg`` for one shot.
``namespace`` is the shots cache key (or its prefix) used by the pipeline, so
keyframes from different shot-detection options never collide.
Raises:
ValueError: ``shot_index`` is not a non-negative integer or ``namespace``
is not filename-safe.
"""
if isinstance(shot_index, bool) or not isinstance(shot_index, int) or shot_index < 0:
raise ValueError(f"shot_index must be a non-negative integer, got {shot_index!r}")
directory = self.keyframes_dir(source_sha)
if namespace is not None:
if not _KEY_RE.fullmatch(namespace):
raise ValueError(
f"invalid keyframe namespace {namespace!r}; expected 8-64 lowercase "
"hex characters"
)
directory = directory / namespace[:12]
return directory / f"shot-{shot_index}.jpg"
def artifacts_path(self, source_sha: str) -> Path:
"""``<source dir>/artifacts.json`` -- the pipeline's final ``Artifacts`` model."""
return self.source_dir(source_sha) / ARTIFACTS_FILE_NAME
def stage_path(self, source_sha: str, stage_name: str, key: str) -> Path:
"""``<source dir>/stage-<stage>-<key>.json`` for one cached stage artifact.
Raises:
ValueError: the stage name or key is not filename-safe.
"""
name = self._check_stage_name(stage_name)
return self.source_dir(source_sha) / f"stage-{name}-{self._check_key(key)}.json"
# ------------------------------------------------------------------ #
# I/O
# ------------------------------------------------------------------ #
def exists(self, path: Path | str) -> bool:
"""True when ``path`` is an existing regular file."""
return Path(path).expanduser().is_file()
def save_model(self, path: Path | str, model: BaseModel) -> Path:
"""Persist a pydantic model as indented JSON at ``path``.
Parent directories are created; the write is atomic.
Raises:
TypeError: ``model`` is not a pydantic ``BaseModel``.
"""
if not isinstance(model, BaseModel):
raise TypeError(f"save_model expects a pydantic BaseModel, got {type(model).__name__}")
return _write_atomically(Path(path).expanduser(), model.model_dump_json(indent=2) + "\n")
def load_model(self, path: Path | str, model_type: type[ModelT]) -> ModelT | None:
"""Load and validate a cached model, or ``None`` when the file is missing.
Args:
path: artifact path (typically from :meth:`stage_path`).
model_type: the pydantic class the payload must validate against.
Returns:
The validated model, or ``None`` if ``path`` does not exist.
Raises:
TypeError: ``model_type`` is not a pydantic model class.
ValueError: the cached payload is not valid JSON or does not match
``model_type`` (the pipeline treats this as a cache miss).
"""
if not (isinstance(model_type, type) and issubclass(model_type, BaseModel)):
raise TypeError(f"model_type must be a pydantic BaseModel subclass, got {model_type!r}")
target = Path(path).expanduser()
if not target.is_file():
return None
text = target.read_text(encoding="utf-8")
try:
return model_type.model_validate_json(text)
except ValidationError as exc:
raise ValueError(
f"cached artifact {target} does not match {model_type.__name__}: {exc}"
) from exc
def save_json(self, path: Path | str, payload: Any) -> Path:
"""Persist a raw JSON-able payload at ``path`` (parents created, atomic write).
Values JSON cannot encode are rendered with ``str``, mirroring
:meth:`stage_key`.
"""
text = json.dumps(payload, indent=2, ensure_ascii=False, default=str) + "\n"
return _write_atomically(Path(path).expanduser(), text)
def load_json(self, path: Path | str) -> Any | None:
"""Load a raw JSON payload, or ``None`` when the file is missing.
Raises:
ValueError: the file does not contain valid JSON.
"""
target = Path(path).expanduser()
if not target.is_file():
return None
try:
return json.loads(target.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"cached artifact {target} is not valid JSON: {exc}") from exc
def clear_stage(self, source_sha: str, stage_name: str) -> int:
"""Delete every cached artifact of one stage for one source.
Returns:
Number of artifact files removed.
"""
name = self._check_stage_name(stage_name)
removed = 0
for path in sorted(self.source_dir(source_sha).glob(f"stage-{name}-*.json")):
try:
path.unlink()
except FileNotFoundError: # another run removed it first
continue
removed += 1
if removed:
logger.debug("removed %d cached %s artifact(s)", removed, name)
return removed
# ------------------------------------------------------------------ #
# validation helpers
# ------------------------------------------------------------------ #
@staticmethod
def _check_stage_name(stage_name: str) -> str:
"""Validate a stage name against the filename-safe pattern."""
if not isinstance(stage_name, str) or not _STAGE_NAME_RE.fullmatch(stage_name):
raise ValueError(
f"invalid stage name {stage_name!r}; expected letters, digits, '-' or '_'"
)
return stage_name
@staticmethod
def _check_key(key: str) -> str:
"""Validate a stage key (lowercase hex, 8-64 characters)."""
if not isinstance(key, str) or not _KEY_RE.fullmatch(key):
raise ValueError(f"invalid stage key {key!r}; expected 8-64 lowercase hex characters")
return key
+846
View File
@@ -0,0 +1,846 @@
"""``va`` -- the video-analyse command-line interface.
Every pipeline stage is runnable on its own (``va probe``, ``va transcribe``,
``va shots``, ...), ``va analyse`` runs the whole chain and writes a Markdown report,
``va ask`` answers questions from the cached analysis and ``va serve-mcp`` starts the
MCP server for agent hosts. All asynchronous work is driven through
:func:`asyncio.run`.
Output conventions: rich tables/panels for humans, and a single clean JSON document on
stdout with ``--json`` (accepted both before the subcommand and per command) so the CLI
pipes into ``jq`` and friends. Progress and error messages go to stderr.
"""
from __future__ import annotations
import asyncio
import importlib
import os
from collections.abc import Callable, Collection, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
from typing import TYPE_CHECKING, Any
import typer
from pydantic import BaseModel
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from . import __version__
from .cache import StageCache
from .config import Settings
from .ingest import IngestResult
from .models import Artifacts, MediaInfo, Shot, Transcript, VideoReport
from .pipeline import DEFAULT_MAX_SHOTS, STAGE_ORDER, Pipeline
from .report import format_timestamp, render_markdown
from .srt import render_srt
if TYPE_CHECKING: # imported lazily in `_render_doctor` to keep `va --help` fast
from .doctor import DoctorReport
from .synthesis import AnswerResult
__all__ = ["app", "main"]
# Keep pydantic-ai's one-off telemetry banner off stderr; `--json` output must stay clean and
# the first model call of a run would otherwise print it after the progress lines.
os.environ.setdefault("PYDANTIC_AI_NO_BANNER", "1")
class STTBackend(StrEnum):
"""Speech-to-text backends accepted by ``va transcribe --backend``."""
PARAKEET = "parakeet"
WHISPER = "whisper"
OPENAI_TRANSCRIPTIONS = "openai-transcriptions"
class DiarizeBackend(StrEnum):
"""Diarization backends accepted by ``va diarize --backend``."""
SHERPA = "sherpa"
PYANNOTE = "pyannote"
class TranscriptFormat(StrEnum):
"""Output formats of ``va transcribe --format``."""
JSON = "json"
SRT = "srt"
class Transport(StrEnum):
"""MCP transports accepted by ``va serve-mcp --transport``."""
STDIO = "stdio"
HTTP = "http"
#: Values that mean "let the model detect the spoken language".
AUTO_LANGUAGES = frozenset({"", "auto", "none"})
#: Progress, tables and panels go through this console; stdout stays clean for JSON.
console = Console()
_SIZE_UNITS = ("B", "KiB", "MiB", "GiB", "TiB")
@dataclass(frozen=True, slots=True)
class _RootOptions:
"""Options parsed by the root callback and shared with every subcommand."""
json_output: bool = False
class _ShotsPayload(BaseModel):
"""JSON payload of ``va shots --json`` and ``va describe --json``."""
source: str
workdir: Path
shots: list[Shot] = []
class _AnswerPayload(BaseModel):
"""JSON payload of ``va ask --json``."""
source: str
question: str
answer: str
cached: bool = False
cache_key: str | None = None
citations: list[str] = []
# --------------------------------------------------------------------------- #
# small shared helpers
# --------------------------------------------------------------------------- #
def _human_bytes(size: int) -> str:
"""Render a byte count compactly (``1.1 MiB``)."""
value = float(max(int(size), 0))
for unit in _SIZE_UNITS[:-1]:
if value < 1024.0:
return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024.0
return f"{value:.1f} {_SIZE_UNITS[-1]}"
def _settings() -> Settings:
"""Build the runtime settings from the ``VA_*`` environment."""
return Settings()
def _normalise_language(value: str | None) -> str | None:
"""Map ``auto``/empty to ``None`` (model auto-detect) and keep explicit codes."""
if value is None:
return None
text = value.strip()
return None if text.lower() in AUTO_LANGUAGES else text
def _json_mode(ctx: typer.Context, explicit: bool) -> bool:
"""True when JSON output was requested per command or globally (``va --json``)."""
root = getattr(ctx, "obj", None)
return explicit or bool(getattr(root, "json_output", False))
def _emit_json(payload: BaseModel) -> None:
"""Write exactly one JSON document to stdout, with no rich wrapping or markup."""
typer.echo(payload.model_dump_json(indent=2))
def _progress(json_mode: bool) -> Callable[[str], None] | None:
"""Progress callback for the pipeline: stderr in human mode, silence for JSON."""
if json_mode:
return None
def _notify(message: str) -> None:
if message.endswith("skipped (not requested)"):
return # the six unrequested stages would drown the interesting lines
typer.echo(message, err=True)
return _notify
@contextmanager
def _error_boundary(action: str) -> Iterator[None]:
"""Turn expected stage/argument failures into one actionable message and exit code 1."""
try:
yield
except typer.Exit:
raise
except (ValueError, RuntimeError, ImportError, OSError) as exc:
typer.secho(f"error: {action} failed: {exc}", fg=typer.colors.RED, err=True)
raise typer.Exit(code=1) from exc
async def _run_pipeline(
settings: Settings,
source: str,
want: Collection[str],
*,
force: bool = False,
max_shots: int = DEFAULT_MAX_SHOTS,
progress: Callable[[str], None] | None = None,
) -> Artifacts:
"""Run the pipeline for ``source`` with the requested stages."""
pipeline = Pipeline(settings, max_shots=max_shots)
return await pipeline.run(source, want=want, force=force, progress=progress)
async def _fetch_source(url: str, *, cache_dir: Path, quality: int) -> IngestResult:
"""Download ``url`` through the ingest stage (imported lazily: yt-dlp is optional)."""
from .ingest import fetch as fetch_source
return await fetch_source(url, cache_dir=cache_dir, quality=quality)
async def _answer(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: StageCache | None = None,
) -> AnswerResult:
"""Answer ``question`` over ``report`` with the synthesis model (lazy import)."""
from .synthesis import answer_question_result
return await answer_question_result(report, question, settings=settings, cache=cache)
def _write_markdown(report: VideoReport, *, workdir: Path, out: Path) -> Path:
"""Render and write the Markdown report, returning the written path."""
target = out.expanduser()
target.parent.mkdir(parents=True, exist_ok=True)
keyframes = workdir / "keyframes"
relative: Path | None = None
if keyframes.is_dir():
try:
relative = Path(os.path.relpath(keyframes, start=target.parent.resolve()))
except ValueError: # pragma: no cover - only on platforms with per-drive roots
relative = None
markdown = render_markdown(report, keyframes_relpath=relative)
target.write_text(markdown, encoding="utf-8")
return target
def _sibling(target: Path, suffix: str) -> Path:
"""Return ``target`` with ``suffix`` (``report.md`` -> ``report.json``)."""
return target.with_suffix(suffix) if target.suffix else target.with_name(target.name + suffix)
def _write_report_artifacts(
report: VideoReport, *, workdir: Path, out: Path
) -> tuple[Path, Path, Path | None]:
"""Write PLAN §4's artifact set: ``report.md``, ``report.json`` and ``transcript.srt``.
The JSON and SRT files are siblings of ``--out`` using the same stem. The SRT is
omitted only when the report has no transcript.
"""
markdown_path = _write_markdown(report, workdir=workdir, out=out)
json_path = _sibling(markdown_path, ".json")
json_path.parent.mkdir(parents=True, exist_ok=True)
json_path.write_text(report.model_dump_json(indent=2) + "\n", encoding="utf-8")
srt_path: Path | None = None
if report.transcript is not None and report.transcript.segments:
srt_path = _sibling(markdown_path, ".srt")
srt_path.write_text(render_srt(report.transcript, speaker_labels=True), encoding="utf-8")
return markdown_path, json_path, srt_path
# --------------------------------------------------------------------------- #
# human-readable rendering
# --------------------------------------------------------------------------- #
def _render_media(media: MediaInfo) -> None:
"""Print a media-information table."""
resolution = f"{media.width}x{media.height}" if media.width and media.height else "unknown"
fps = f"{media.fps:.3g} fps" if media.fps else "unknown"
rows = [
("Source", media.source),
("Path", str(media.path)),
("Duration", f"{format_timestamp(media.duration)} ({media.duration:.1f} s)"),
("Resolution", resolution),
("Frame rate", fps),
("Video codec", media.video_codec or "none"),
("Audio codec", media.audio_codec or "none"),
("Size", _human_bytes(media.size_bytes)),
("Format", media.format or "unknown"),
]
table = Table(title="Media info", show_header=True, header_style="bold")
table.add_column("Field", style="bold", no_wrap=True)
table.add_column("Value", overflow="fold")
for field, value in rows:
table.add_row(Text(field), Text(value))
console.print(table)
def _render_transcript(transcript: Transcript, *, title: str = "Transcript") -> None:
"""Print transcript facts in a panel and every segment as a table row."""
speakers = sorted({segment.speaker for segment in transcript.segments if segment.speaker})
facts = [f"duration {transcript.duration:.1f} s", f"{len(transcript.segments)} segments"]
if transcript.language:
facts.append(f"language {transcript.language}")
if transcript.backend:
backend = f"backend {transcript.backend}"
if transcript.model:
backend += f" ({transcript.model})"
facts.append(backend)
if speakers:
facts.append("speakers " + ", ".join(speakers))
console.print(Panel(Text(" | ".join(facts)), title=title))
if not transcript.segments:
console.print(Text("No speech segments were transcribed."))
return
table = Table(show_header=True, header_style="bold")
table.add_column("Time", no_wrap=True)
table.add_column("Speaker", no_wrap=True)
table.add_column("Text", overflow="fold")
for segment in transcript.segments:
table.add_row(
Text(format_timestamp(segment.start)),
Text(segment.speaker or "-"),
Text(" ".join(segment.text.split())),
)
console.print(table)
def _render_turns(transcript: Transcript) -> None:
"""Print the speaker-turn table produced by the diarization stage."""
turns = transcript.speaker_turns
speakers = sorted({turn.speaker for turn in turns})
heading = f"{len(turns)} turns | {len(speakers)} speaker(s): {', '.join(speakers) or 'none'}"
console.print(Panel(Text(heading), title="Speaker turns"))
if not turns:
console.print(Text("No speaker turns were detected."))
return
table = Table(show_header=True, header_style="bold")
table.add_column("Start", no_wrap=True)
table.add_column("End", no_wrap=True)
table.add_column("Speaker", no_wrap=True)
for turn in turns:
table.add_row(
Text(f"{turn.start:.2f} s"),
Text(f"{turn.end:.2f} s"),
Text(turn.speaker),
)
console.print(table)
def _render_shots(shots: list[Shot], *, title: str = "Shots") -> None:
"""Print the shot list (index, time range, keyframe, description)."""
table = Table(title=title, show_header=True, header_style="bold")
table.add_column("#", justify="right", no_wrap=True)
table.add_column("Start", no_wrap=True)
table.add_column("End", no_wrap=True)
table.add_column("Keyframe", overflow="fold")
table.add_column("Description", overflow="fold")
for shot in shots:
description = "-"
if shot.description is not None:
description = f"{shot.description.shot_type}: {shot.description.summary}"
table.add_row(
Text(str(shot.index)),
Text(format_timestamp(shot.start)),
Text(format_timestamp(shot.end)),
Text(shot.keyframe.name if shot.keyframe is not None else "-"),
Text(description),
)
console.print(table)
def _render_report(
report: VideoReport,
*,
markdown_path: Path | None = None,
json_path: Path | None = None,
srt_path: Path | None = None,
) -> None:
"""Print the report summary, topics/people, highlights and the written paths."""
title = report.title or Path(report.source).name or "Video report"
facts = [f"duration {format_timestamp(report.duration)}", f"{len(report.shots)} shots"]
if report.transcript is not None:
facts.append(f"{len(report.transcript.segments)} segments")
facts.append(f"{len(report.highlights)} highlights")
console.print(Panel(Text(" | ".join(facts)), title=Text(title)))
console.print(Panel(Text(report.summary), title="Summary"))
facts_table = Table(show_header=False, box=None)
facts_table.add_column("Field", style="bold", no_wrap=True)
facts_table.add_column("Value", overflow="fold")
facts_table.add_row(Text("Topics"), Text(", ".join(report.topics) or "none"))
facts_table.add_row(Text("People"), Text(", ".join(report.people) or "none"))
console.print(facts_table)
if report.highlights:
table = Table(title="Highlights", show_header=True, header_style="bold")
table.add_column("Start", no_wrap=True)
table.add_column("End", no_wrap=True)
table.add_column("Description", overflow="fold")
for highlight in report.highlights:
table.add_row(
Text(format_timestamp(highlight.start)),
Text(format_timestamp(highlight.end)),
Text(highlight.description),
)
console.print(table)
if markdown_path is not None:
console.print(Text(f"Markdown report written to {markdown_path}"))
if json_path is not None:
console.print(Text(f"JSON report written to {json_path}"))
if srt_path is not None:
console.print(Text(f"Transcript written to {srt_path}"))
def _render_doctor(report: DoctorReport) -> None:
"""Print the doctor panel, the check table and the llama-server hint if needed."""
heading = f"profile: {report.profile}\ncache dir: {report.cache_dir}"
console.print(Panel(Text(heading), title="video-analyse doctor"))
style = {"ok": "green", "warn": "yellow", "fail": "red", "info": "cyan"}
table = Table(show_header=True, header_style="bold")
table.add_column("Check", no_wrap=True)
table.add_column("Status", no_wrap=True)
table.add_column("Detail", overflow="fold")
for check in report.checks:
table.add_row(
Text(check.name),
Text(check.status, style=style.get(check.status, "")),
Text(check.detail),
)
console.print(table)
if report.llama_server_command:
console.print(
Panel(
Text(report.llama_server_command),
title="Start the local VLM server",
subtitle="llama-server is not reachable",
)
)
# --------------------------------------------------------------------------- #
# the typer app
# --------------------------------------------------------------------------- #
app = typer.Typer(
name="va",
help="video-analyse: local-first, agent-friendly video analysis.",
add_completion=False,
no_args_is_help=False,
rich_markup_mode="rich",
context_settings={"help_option_names": ["-h", "--help"]},
)
def _print_version(value: bool) -> None:
"""Eager ``--version`` handler."""
if value:
typer.echo(__version__)
raise typer.Exit()
@app.callback(invoke_without_command=True)
def _root(
ctx: typer.Context,
version: bool = typer.Option(
False,
"--version",
"-V",
is_eager=True,
callback=_print_version,
help="Print the installed version and exit.",
),
json_output: bool = typer.Option(
False,
"--json",
help="Emit machine-readable JSON on stdout (same as each command's --json flag).",
),
) -> None:
"""video-analyse: local-first, agent-friendly video analysis."""
ctx.obj = _RootOptions(json_output=json_output)
if ctx.invoked_subcommand is None:
typer.echo(ctx.get_help())
@app.command()
def version() -> None:
"""Print the installed video-analyse version."""
typer.echo(__version__)
@app.command()
def fetch(
ctx: typer.Context,
url: str = typer.Argument(..., help="Video URL supported by yt-dlp (or a direct http URL)."),
quality: int = typer.Option(
1080, "--quality", min=144, max=4320, help="Maximum download height in pixels."
),
json_output: bool = typer.Option(False, "--json", help="Print the ingest result as JSON."),
) -> None:
"""Download a remote video into the cache and report the local file."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("fetch"):
settings = _settings()
result = asyncio.run(_fetch_source(url, cache_dir=settings.cache_dir, quality=quality))
if json_mode:
_emit_json(result)
return
table = Table(title="Fetched media", show_header=True, header_style="bold")
table.add_column("Field", style="bold", no_wrap=True)
table.add_column("Value", overflow="fold")
table.add_row(Text("Path"), Text(str(result.path)))
table.add_row(Text("Title"), Text(result.title or "unknown"))
table.add_row(
Text("Downloaded"), Text("yes" if result.downloaded else "no (already cached)")
)
size = _human_bytes(result.path.stat().st_size) if result.path.is_file() else "unknown"
table.add_row(Text("Size"), Text(size))
console.print(table)
@app.command()
def probe(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
json_output: bool = typer.Option(False, "--json", help="Print the media info as JSON."),
) -> None:
"""Probe a media file with ffprobe and print its technical metadata."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("probe"):
artifacts = asyncio.run(
_run_pipeline(_settings(), src, {"probe"}, progress=_progress(json_mode))
)
if artifacts.media is None:
raise RuntimeError("the probe stage returned no media information")
if json_mode:
_emit_json(artifacts.media)
return
_render_media(artifacts.media)
@app.command()
def transcribe(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
backend: STTBackend | None = typer.Option(
None, "--backend", help="STT backend; defaults to the backend of the active profile."
),
lang: str | None = typer.Option(
None,
"--lang",
help=(
"Language code such as 'en' (Parakeet v2) or 'auto' for Parakeet v3 "
"auto-detect. Defaults to VA_LANGUAGE when omitted."
),
),
diarize: bool | None = typer.Option(
None,
"--diarize/--no-diarize",
help="Run speaker diarization too (default for this command: off).",
),
output_format: TranscriptFormat = typer.Option(
TranscriptFormat.JSON, "--format", help="Transcript output format."
),
json_output: bool = typer.Option(False, "--json", help="Print the transcript as JSON."),
) -> None:
"""Transcribe the audio track, optionally with speaker diarization."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("transcribe"):
settings = _settings()
updates: dict[str, Any] = {}
if lang is not None:
updates["language"] = _normalise_language(lang)
if backend is not None:
updates["stt_backend"] = backend.value
if diarize is not None:
updates["diarize"] = diarize
settings = settings.model_copy(update=updates)
want: set[str] = {"probe", "audio", "transcribe"}
if diarize:
want.add("diarize")
artifacts = asyncio.run(_run_pipeline(settings, src, want, progress=_progress(json_mode)))
transcript = artifacts.transcript
if transcript is None:
raise RuntimeError("no transcript was produced; the source may have no audio stream")
if output_format is TranscriptFormat.SRT:
from .srt import render_srt
typer.echo(render_srt(transcript, speaker_labels=True), nl=False)
return
if json_mode:
_emit_json(transcript)
return
_render_transcript(transcript)
@app.command()
def diarize(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
backend: DiarizeBackend | None = typer.Option(
None, "--backend", help="Diarization backend; defaults to VA_DIARIZE_BACKEND."
),
json_output: bool = typer.Option(
False, "--json", help="Print the speaker-attributed transcript as JSON."
),
) -> None:
"""Detect speakers and attribute every transcript segment to one."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("diarize"):
settings = _settings()
updates: dict[str, Any] = {"diarize": True}
if backend is not None:
updates["diarize_backend"] = backend.value
settings = settings.model_copy(update=updates)
artifacts = asyncio.run(
_run_pipeline(
settings,
src,
{"probe", "audio", "transcribe", "diarize"},
progress=_progress(json_mode),
)
)
transcript = artifacts.transcript
if transcript is None:
raise RuntimeError("no transcript was produced; the source may have no audio stream")
if json_mode:
_emit_json(transcript)
return
_render_turns(transcript)
_render_transcript(transcript, title="Speaker-attributed transcript")
@app.command()
def shots(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
detector: str = typer.Option(
"adaptive",
"--detector",
help="Shot detector; the detection stage implements the adaptive detector.",
),
max_shots: int = typer.Option(
DEFAULT_MAX_SHOTS, "--max-shots", min=1, help="Upper bound on shots after merging."
),
json_output: bool = typer.Option(False, "--json", help="Print the shot list as JSON."),
) -> None:
"""Detect shots, extract one keyframe per shot and drop duplicate frames."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("shots"):
if detector.strip().lower() != "adaptive":
raise ValueError(
f"unsupported detector {detector!r}; only 'adaptive' (PySceneDetect "
"AdaptiveDetector) is implemented"
)
artifacts = asyncio.run(
_run_pipeline(
_settings(),
src,
{"probe", "shots"},
max_shots=max_shots,
progress=_progress(json_mode),
)
)
if json_mode:
payload = _ShotsPayload(
source=artifacts.source, workdir=artifacts.workdir, shots=artifacts.shots
)
_emit_json(payload)
return
if not artifacts.shots:
console.print(Text("No shots were detected (the source may have no video stream)."))
return
_render_shots(artifacts.shots)
@app.command()
def describe(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
model: str | None = typer.Option(
None,
"--model",
help="VLM model name or pydantic-ai model string; defaults to VA_VLM_MODEL.",
),
json_output: bool = typer.Option(False, "--json", help="Print the described shots as JSON."),
) -> None:
"""Describe every shot keyframe with the configured vision model."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("describe"):
settings = _settings()
if model is not None:
settings = settings.model_copy(update={"vlm_model": model})
artifacts = asyncio.run(
_run_pipeline(
settings,
src,
{"probe", "shots", "describe"},
progress=_progress(json_mode),
)
)
if json_mode:
payload = _ShotsPayload(
source=artifacts.source, workdir=artifacts.workdir, shots=artifacts.shots
)
_emit_json(payload)
return
if not artifacts.shots:
console.print(Text("No shots were detected, nothing to describe."))
return
_render_shots(artifacts.shots, title="Described shots")
@app.command()
def analyse(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL."),
no_diarize: bool = typer.Option(
False, "--no-diarize", help="Skip speaker diarization (the default is on)."
),
out: Path = typer.Option(
Path("report.md"), "--out", help="Where to write the Markdown report."
),
force: bool = typer.Option(
False, "--force", help="Re-run the wanted stages even when their cache entry exists."
),
json_output: bool = typer.Option(False, "--json", help="Print the report as JSON."),
) -> None:
"""Run the full pipeline and write a Markdown report."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("analyse"):
settings = _settings()
want = set(STAGE_ORDER)
if no_diarize:
want.discard("diarize")
settings = settings.model_copy(update={"diarize": False})
artifacts = asyncio.run(
_run_pipeline(
settings,
src,
want,
force=force,
progress=_progress(json_mode),
)
)
report = artifacts.report
if report is None:
raise RuntimeError(
"no report was produced; the source has neither an audio transcript nor video shots"
)
markdown_path, json_path, srt_path = _write_report_artifacts(
report, workdir=artifacts.workdir, out=out
)
if json_mode:
_emit_json(report)
return
_render_report(report, markdown_path=markdown_path, json_path=json_path, srt_path=srt_path)
@app.command()
def ask(
ctx: typer.Context,
src: str = typer.Argument(..., help="Local media path or http(s) URL with a cached report."),
question: list[str] = typer.Argument(..., help="Question about the video."),
no_cache: bool = typer.Option(
False, "--no-cache", help="Ask the model again even when an identical answer is cached."
),
json_output: bool = typer.Option(False, "--json", help="Print the answer as JSON."),
) -> None:
"""Answer a question grounded in the cached report (run 'va analyse' first)."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("ask"):
text = " ".join(question).strip()
if not text:
raise ValueError("the question must not be empty")
settings = _settings()
artifacts = asyncio.run(
_run_pipeline(settings, src, {"report"}, progress=_progress(json_mode))
)
report = artifacts.report
if report is None:
raise RuntimeError(f"no cached analysis for {src}; run 'va analyse {src}' first")
cache = None if no_cache else StageCache(settings.cache_dir)
answer = asyncio.run(_answer(report, text, settings=settings, cache=cache))
if json_mode:
payload = _AnswerPayload(
source=artifacts.source,
question=text,
answer=answer.answer,
cached=answer.cached,
cache_key=answer.cache_key,
citations=answer.citations,
)
_emit_json(payload)
return
console.print(Text(answer.answer))
if answer.cached:
console.print(Text("(cached answer)", style="dim"))
@app.command()
def doctor(
ctx: typer.Context,
json_output: bool = typer.Option(False, "--json", help="Print the checks as JSON."),
) -> None:
"""Check ffmpeg, yt-dlp, models, API keys, the llama-server, the cache and disk."""
json_mode = _json_mode(ctx, json_output)
with _error_boundary("doctor"):
from .doctor import run_doctor
report = asyncio.run(run_doctor(_settings()))
if json_mode:
_emit_json(report)
else:
_render_doctor(report)
if not report.ok:
raise typer.Exit(code=1)
def _mcp_server(transport: Transport, *, port: int) -> None:
"""Import the MCP server lazily and run it with the chosen transport."""
try:
module = importlib.import_module("video_analyse.mcp_server")
except ImportError as exc:
raise RuntimeError(
"video_analyse.mcp_server could not be imported "
f"({exc}); reinstall video-analyse or run from the project checkout"
) from exc
host = "127.0.0.1"
runner = getattr(module, "run", None) or getattr(module, "run_server", None)
if callable(runner):
runner(transport=transport.value, host=host, port=port)
return
server = getattr(module, "mcp", None) or getattr(module, "server", None)
if server is not None and callable(getattr(server, "run", None)):
if transport is Transport.STDIO:
server.run()
else:
server.run(transport="http", host=host, port=port)
return
raise RuntimeError(
"video_analyse.mcp_server exposes neither a run() function nor an 'mcp' server "
"object with run()"
)
@app.command("serve-mcp")
def serve_mcp(
transport: Transport = typer.Option(
Transport.STDIO, "--transport", help="MCP transport: stdio (default) or http."
),
port: int = typer.Option(
8000, "--port", min=1, max=65535, help="HTTP port (ignored for the stdio transport)."
),
) -> None:
"""Run the video-analyse MCP server for agent hosts such as pi."""
with _error_boundary("serve-mcp"):
_mcp_server(transport, port=port)
def main() -> None:
"""Console-script entry point (``va``)."""
app()
if __name__ == "__main__": # pragma: no cover - convenience for `python -m video_analyse.cli`
main()
+120
View File
@@ -0,0 +1,120 @@
"""Configuration (``VA_*`` environment variables) and per-stage model resolution."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Literal
from pydantic import field_validator
from pydantic_settings import (
BaseSettings,
PydanticBaseSettingsSource,
SettingsConfigDict,
TomlConfigSettingsSource,
)
DEFAULT_CACHE_DIR = Path("~/.cache/video-analyse")
DEFAULT_CONFIG_FILE = Path("~/.config/video-analyse/config.toml")
PROFILE = Literal["local", "hosted"]
STT_BACKENDS = ("parakeet", "whisper", "openai-transcriptions")
DIARIZE_BACKENDS = ("sherpa", "pyannote")
# The DeepSeek ``deepseek-flash`` alias floats to the current release. Users who
# need reproducible snapshots can pin e.g. ``deepseek:deepseek-v4.1-flash-1017`` or
# ``openrouter:deepseek/deepseek-v4.1-flash-1017`` via VA_VLM_MODEL/VA_SYNTHESIS_MODEL.
LOCAL_VLM_MODEL = "local:Qwen3-VL-4B-Instruct"
HOSTED_VLM_MODEL = "deepseek:deepseek-flash"
class Settings(BaseSettings):
"""Runtime settings; every field is overridable via a ``VA_``-prefixed env var."""
model_config = SettingsConfigDict(
env_prefix="VA_",
env_file=None,
toml_file=DEFAULT_CONFIG_FILE,
extra="ignore",
case_sensitive=False,
validate_default=True,
)
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
"""Precedence: constructor kwargs > ``VA_*`` env > TOML > dotenv > secrets.
The optional ``~/.config/video-analyse/config.toml`` (or ``$XDG_CONFIG_HOME``)
supplies defaults for every ``Settings`` field; environment variables still
win, so a TOML file can never silently override an explicit ``VA_*`` value.
"""
config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
toml_file = config_home / "video-analyse" / "config.toml"
return (
init_settings,
env_settings,
TomlConfigSettingsSource(settings_cls, toml_file=toml_file),
dotenv_settings,
file_secret_settings,
)
# --- profile / paths ---------------------------------------------------
profile: PROFILE = "local"
cache_dir: Path = DEFAULT_CACHE_DIR
# --- speech-to-text ----------------------------------------------------
language: str | None = None # None -> auto; "en" -> Parakeet v2
stt_backend: Literal["parakeet", "whisper", "openai-transcriptions"] | None = None
stt_api_base_url: str = "https://api.groq.com/openai/v1"
stt_api_model: str = "whisper-large-v3-turbo"
whisper_model: str = "large-v3-turbo"
#: Optional per-request upload cap for hosted STT (defaults are provider-aware).
stt_max_upload_bytes: int | None = None
# --- diarization -------------------------------------------------------
diarize: bool = True
diarize_backend: Literal["sherpa", "pyannote"] = "sherpa"
# --- vision / synthesis (pydantic-ai model strings) --------------------
vlm_model: str | None = None
llama_server_url: str = "http://127.0.0.1:8080/v1"
synthesis_model: str | None = None
@field_validator("cache_dir", mode="after")
@classmethod
def _expand_cache_dir(cls, value: Path) -> Path:
return value.expanduser()
# --- resolution rules --------------------------------------------------
def resolved_stt(self) -> str:
"""STT backend: explicit setting wins, else an explicitly configured Whisper
model selects ``whisper``, else the profile default.
The second rule keeps ``VA_WHISPER_MODEL=tiny va transcribe`` meaningful: naming a
Whisper checkpoint is a request for the faster-whisper backend (set
``VA_STT_BACKEND=parakeet`` to override it explicitly).
"""
if self.stt_backend is not None:
return self.stt_backend
if "whisper_model" in self.model_fields_set:
return "whisper"
return "parakeet" if self.profile == "local" else "openai-transcriptions"
def resolved_vlm(self) -> str:
"""Vision model spec: explicit setting wins, else the profile default."""
if self.vlm_model is not None:
return self.vlm_model
return LOCAL_VLM_MODEL if self.profile == "local" else HOSTED_VLM_MODEL
def resolved_synthesis(self) -> str:
"""Synthesis/QA model spec: explicit setting wins, else the profile default."""
if self.synthesis_model is not None:
return self.synthesis_model
return LOCAL_VLM_MODEL if self.profile == "local" else HOSTED_VLM_MODEL
+497
View File
@@ -0,0 +1,497 @@
"""Speaker diarization and transcript attribution.
Two backends are available, selected by ``Settings.diarize_backend``:
* ``"sherpa"`` (default): sherpa-onnx offline diarization on CPU. The two ONNX
models are plain GitHub-release downloads (see :mod:`video_analyse.model_assets`),
so there is no HuggingFace token, no gating and no PyTorch dependency. Audio is
processed on 16 kHz mono floats; ``num_threads`` defaults to :func:`os.cpu_count`.
* ``"pyannote"`` (optional extra): ``pyannote/speaker-diarization-community-1``.
Better clustering, but gated: it needs ``pip install "video-analyse[pyannote]"``,
a HuggingFace account, accepted model terms and ``HF_TOKEN``.
Inference runs in :func:`asyncio.to_thread`, so the event loop is never blocked.
"""
from __future__ import annotations
import asyncio
import inspect
import logging
import math
import os
import wave
from collections.abc import Iterable, Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Any
import numpy as np
from video_analyse.config import Settings
from video_analyse.model_assets import DiarizationModels, ensure_diarization_models
from video_analyse.models import SpeakerTurn, Transcript
if TYPE_CHECKING:
from sherpa_onnx import OfflineSpeakerDiarizationConfig
__all__ = [
"DEFAULT_CLUSTER_THRESHOLD",
"DEFAULT_MIN_DURATION_OFF",
"DEFAULT_MIN_DURATION_ON",
"PYANNOTE_MODEL_ID",
"attribute_speakers",
"build_sherpa_config",
"diarize_audio",
]
logger = logging.getLogger(__name__)
#: Gated pyannote pipeline used by the optional backend.
PYANNOTE_MODEL_ID = "pyannote/speaker-diarization-community-1"
PYANNOTE_INSTALL_HINT = (
"The pyannote diarization backend needs the optional extra: pip install "
'"video-analyse[pyannote]" (or `uv sync --extra pyannote` in a project checkout). '
"It also needs a HuggingFace token and prior acceptance of the gated model terms at "
f"https://hf.co/{PYANNOTE_MODEL_ID}: accept the terms there, then export "
"HF_TOKEN=<your token>."
)
#: Default clustering threshold when the speaker count is unknown (sherpa-onnx default).
DEFAULT_CLUSTER_THRESHOLD = 0.5
#: Drop diarization segments shorter than this many seconds.
DEFAULT_MIN_DURATION_ON = 0.3
#: Merge diarization segments separated by gaps shorter than this many seconds.
DEFAULT_MIN_DURATION_OFF = 0.5
#: Fraction of the segmentation window advanced per step (pyannote model default).
WINDOW_SHIFT_RATIO = 0.1
# Bucket size used to index turns for fast word-midpoint lookups.
_TURN_INDEX_BUCKET = 1.0
def _import_sherpa() -> Any:
"""Import sherpa-onnx lazily, with an actionable message if it is missing."""
try:
import sherpa_onnx
except ImportError as exc:
raise ImportError(
"sherpa-onnx is required for the default diarization backend. It is a core "
'dependency of video-analyse: reinstall with `pip install "video-analyse"` '
"or run `uv sync` in the project checkout."
) from exc
return sherpa_onnx
def build_sherpa_config(
segmentation_model: Path,
embedding_model: Path,
*,
num_threads: int = 1,
num_speakers: int = -1,
cluster_threshold: float = DEFAULT_CLUSTER_THRESHOLD,
min_duration_on: float = DEFAULT_MIN_DURATION_ON,
min_duration_off: float = DEFAULT_MIN_DURATION_OFF,
) -> OfflineSpeakerDiarizationConfig:
"""Build (but do not load) the sherpa-onnx diarization configuration.
Args:
segmentation_model: Path to the pyannote segmentation ``model.onnx``.
embedding_model: Path to the 3D-Speaker embedding ``.onnx`` file.
num_threads: Threads per ONNX session (both models).
num_speakers: Exact speaker count, or ``-1`` to cluster with
``cluster_threshold`` (a smaller threshold yields more speakers).
cluster_threshold: Clustering threshold used when ``num_speakers < 0``.
min_duration_on: Drop segments shorter than this (seconds).
min_duration_off: Merge gaps shorter than this (seconds).
Returns:
A configured ``sherpa_onnx.OfflineSpeakerDiarizationConfig``. No model
weights are read here; construction is cheap and side-effect free.
Raises:
ImportError: sherpa-onnx is not installed.
ValueError: A model path is missing or a numeric argument is out of range.
"""
for label, model_file in (
("segmentation", segmentation_model),
("embedding", embedding_model),
):
if not Path(model_file).is_file():
raise ValueError(
f"The {label} model {model_file} does not exist. "
"Fetch the pinned assets first with "
"`await ensure_diarization_models(cache_dir=settings.cache_dir)`."
)
if num_threads < 1:
raise ValueError(f"num_threads must be >= 1, got {num_threads}")
if num_speakers == 0 or num_speakers < -1:
raise ValueError(f"num_speakers must be -1 (auto) or >= 1, got {num_speakers}")
if cluster_threshold <= 0:
raise ValueError(f"cluster_threshold must be > 0, got {cluster_threshold}")
if min_duration_on < 0 or min_duration_off < 0:
raise ValueError(
"min_duration_on/min_duration_off must be >= 0, got "
f"{min_duration_on}/{min_duration_off}"
)
sherpa_onnx = _import_sherpa()
return sherpa_onnx.OfflineSpeakerDiarizationConfig(
segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(
pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(
model=str(segmentation_model),
window_shift_ratio=WINDOW_SHIFT_RATIO,
),
num_threads=num_threads,
debug=False,
provider="cpu",
),
embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(
model=str(embedding_model),
num_threads=num_threads,
debug=False,
provider="cpu",
),
clustering=sherpa_onnx.FastClusteringConfig(
num_clusters=num_speakers,
threshold=cluster_threshold,
compute_confidence=False,
),
min_duration_on=min_duration_on,
min_duration_off=min_duration_off,
)
def _pcm_to_float32(raw: bytes, sample_width: int) -> np.ndarray:
"""Convert little-endian PCM bytes to float32 samples in ``[-1, 1]``."""
if sample_width == 1:
return (np.frombuffer(raw, dtype=np.uint8).astype(np.float32) - 128.0) / 128.0
if sample_width == 2:
return np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
if sample_width == 3:
packed = np.frombuffer(raw, dtype=np.uint8)
if packed.size % 3:
raise ValueError("Truncated 24-bit PCM frame buffer")
triplets = packed.reshape(-1, 3).astype(np.int32)
values = triplets[:, 0] | (triplets[:, 1] << 8) | (triplets[:, 2] << 16)
values = np.where(values >= 1 << 23, values - (1 << 24), values)
return values.astype(np.float32) / float(1 << 23)
if sample_width == 4:
return np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0
raise ValueError(f"Unsupported WAV sample width: {sample_width * 8} bit")
def _resample(samples: np.ndarray, source_rate: int, target_rate: int) -> np.ndarray:
"""Linear-interpolation resampler (dependency-free; good enough for embeddings)."""
if samples.size == 0:
return samples
target_length = max(1, round(samples.size * target_rate / float(source_rate)))
positions = np.linspace(0.0, samples.size - 1.0, num=target_length)
grid = np.arange(samples.size, dtype=np.float64)
return np.interp(positions, grid, samples).astype(np.float32)
def _load_wav_mono(wav: Path, *, target_sample_rate: int | None = None) -> tuple[np.ndarray, int]:
"""Read a PCM WAV file as mono float32 samples, resampling when asked.
Args:
wav: Path to a PCM (8/16/24/32-bit) WAV file.
target_sample_rate: Resample to this rate when the file's rate differs.
Returns:
``(samples, sample_rate)`` with samples as a contiguous 1-D float32 array in
``[-1, 1]``.
Raises:
ValueError: The file is not a readable PCM WAV file.
"""
try:
with wave.open(str(wav), "rb") as handle:
channels = handle.getnchannels()
sample_width = handle.getsampwidth()
frame_rate = handle.getframerate()
raw = handle.readframes(handle.getnframes())
except (wave.Error, EOFError) as exc:
raise ValueError(f"{wav} is not a readable PCM WAV file: {exc}") from exc
samples = _pcm_to_float32(raw, sample_width)
if channels > 1:
usable = samples.size - samples.size % channels
samples = samples[:usable].reshape(-1, channels).mean(axis=1)
rate = frame_rate
if target_sample_rate is not None and frame_rate != target_sample_rate:
samples = _resample(samples, frame_rate, target_sample_rate)
rate = target_sample_rate
return np.ascontiguousarray(samples, dtype=np.float32), rate
def _labels_to_turns(spans: Iterable[tuple[float, float, Any]]) -> list[SpeakerTurn]:
"""Map raw ``(start, end, backend_label)`` spans to ``S1``/``S2``/... turns.
Labels are assigned in first-appearance order, so the first speaker to talk is
always ``S1`` and ids are stable across runs. Callers pass spans sorted by
start time (sherpa-onnx already does; pyannote spans are sorted explicitly).
"""
labels: dict[Any, str] = {}
turns: list[SpeakerTurn] = []
for start, end, raw_label in spans:
start = float(start)
end = float(end)
if not math.isfinite(start) or not math.isfinite(end) or end <= start:
continue
if raw_label not in labels:
labels[raw_label] = f"S{len(labels) + 1}"
turns.append(SpeakerTurn(start=start, end=end, speaker=labels[raw_label]))
return turns
def _segments_to_turns(segments: Iterable[Any]) -> list[SpeakerTurn]:
"""Convert sherpa-onnx diarization segments to speaker turns."""
return _labels_to_turns((seg.start, seg.end, seg.speaker) for seg in segments)
def _run_sherpa_diarization(
wav: Path,
models: DiarizationModels,
*,
num_threads: int,
num_speakers: int,
cluster_threshold: float,
min_duration_on: float,
min_duration_off: float,
) -> list[SpeakerTurn]:
"""Load the models, run offline diarization and return speaker turns (blocking)."""
sherpa_onnx = _import_sherpa()
config = build_sherpa_config(
models.segmentation,
models.embedding,
num_threads=num_threads,
num_speakers=num_speakers,
cluster_threshold=cluster_threshold,
min_duration_on=min_duration_on,
min_duration_off=min_duration_off,
)
diarizer = sherpa_onnx.OfflineSpeakerDiarization(config)
samples, rate = _load_wav_mono(wav, target_sample_rate=int(diarizer.sample_rate))
logger.info(
"Diarizing %s (%.1f s @ %d Hz, threads=%d)",
wav.name,
samples.size / rate if rate else 0.0,
rate,
num_threads,
)
result = diarizer.process(samples)
turns = _segments_to_turns(result.sort_by_start_time())
logger.info(
"Diarization of %s produced %d turns with %d speakers",
wav.name,
len(turns),
len({turn.speaker for turn in turns}),
)
if not turns:
logger.warning("Diarization of %s found no speech turns", wav.name)
return turns
def _pyannote_available() -> bool:
"""Return whether the optional pyannote extra is importable."""
try:
import pyannote.audio # noqa: F401 # import probe only
except ImportError:
return False
return True
def _run_pyannote_pipeline(wav: Path, *, num_speakers: int = -1) -> list[SpeakerTurn]:
"""Run the gated pyannote pipeline on ``wav`` (blocking; CPU by default)."""
from pyannote.audio import Pipeline
token = (
os.environ.get("HF_TOKEN")
or os.environ.get("HUGGING_FACE_HUB_TOKEN")
or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
)
kwargs: dict[str, Any] = {}
if token:
parameters = inspect.signature(Pipeline.from_pretrained).parameters
if "token" in parameters:
kwargs["token"] = token
elif "use_auth_token" in parameters:
kwargs["use_auth_token"] = token
try:
pipeline = Pipeline.from_pretrained(PYANNOTE_MODEL_ID, **kwargs)
except Exception as exc: # huggingface errors vary by version and library
raise RuntimeError(
f"Could not load the pyannote pipeline {PYANNOTE_MODEL_ID!r}: {exc}. "
f"Accept the gated model terms at https://hf.co/{PYANNOTE_MODEL_ID} and set "
"HF_TOKEN before retrying."
) from exc
if pipeline is None:
raise RuntimeError(
f"pyannote returned no pipeline for {PYANNOTE_MODEL_ID!r}. Accept the gated model "
f"terms at https://hf.co/{PYANNOTE_MODEL_ID} and set HF_TOKEN, then retry."
)
call_kwargs: dict[str, Any] = {"num_speakers": num_speakers} if num_speakers >= 1 else {}
output = pipeline(str(wav), **call_kwargs)
# pyannote.audio >= 4 returns a DiarizeOutput; <= 3 returns an Annotation.
annotation = getattr(output, "speaker_diarization", output)
if not hasattr(annotation, "itertuples"):
raise RuntimeError(
"Unexpected pyannote output: expected a diarization Annotation with itertuples(). "
"Check the installed pyannote.audio version (>= 4.0 is supported)."
)
spans = [
(float(segment.start), float(segment.end), label)
for segment, _track, label in annotation.itertuples()
]
spans.sort(key=lambda item: item[0])
turns = _labels_to_turns(spans)
logger.info("pyannote diarization of %s produced %d turns", wav.name, len(turns))
return turns
async def _diarize_with_pyannote(wav: Path, *, num_speakers: int = -1) -> list[SpeakerTurn]:
"""Validate the optional dependency, then run pyannote off the event loop."""
if not _pyannote_available():
raise ImportError(PYANNOTE_INSTALL_HINT)
return await asyncio.to_thread(_run_pyannote_pipeline, wav, num_speakers=num_speakers)
async def diarize_audio(
wav: Path,
*,
settings: Settings,
num_speakers: int = -1,
cluster_threshold: float = DEFAULT_CLUSTER_THRESHOLD,
min_duration_on: float = DEFAULT_MIN_DURATION_ON,
min_duration_off: float = DEFAULT_MIN_DURATION_OFF,
) -> list[SpeakerTurn]:
"""Diarize a 16 kHz mono WAV file into speaker turns.
Args:
wav: Audio file (ideally ``workdir/audio.wav`` from ``media.extract_audio``).
Non-16 kHz input is resampled on the fly for the sherpa backend.
settings: Runtime settings; ``settings.diarize_backend`` picks the backend
and ``settings.cache_dir`` holds the pinned sherpa-onnx models.
num_speakers: Exact speaker count, or ``-1`` to cluster automatically (both
backends honour it).
cluster_threshold: Clustering threshold when ``num_speakers < 0``, sherpa
backend only (smaller -> more speakers).
min_duration_on: Drop segments shorter than this (seconds); sherpa only.
min_duration_off: Merge gaps shorter than this (seconds); sherpa only.
Returns:
Speaker turns sorted by start time, labelled ``"S1"``, ``"S2"``, ... in
order of first appearance.
Raises:
ValueError: The audio file is missing or unreadable.
ImportError: The selected backend (or its optional extra) is unavailable.
RuntimeError: Model download/integrity failure or backend inference failure.
"""
wav = Path(wav)
if not wav.is_file():
raise ValueError(
f"Audio file not found: {wav}. Extract 16 kHz mono audio first "
"(media.extract_audio writes workdir/audio.wav)."
)
backend = settings.diarize_backend
if backend == "pyannote":
return await _diarize_with_pyannote(wav, num_speakers=num_speakers)
if backend != "sherpa":
raise ValueError(
f"Unknown diarization backend {backend!r}; expected 'sherpa' or 'pyannote'."
)
models = await ensure_diarization_models(cache_dir=settings.cache_dir)
num_threads = os.cpu_count() or 1
return await asyncio.to_thread(
_run_sherpa_diarization,
wav,
models,
num_threads=num_threads,
num_speakers=num_speakers,
cluster_threshold=cluster_threshold,
min_duration_on=min_duration_on,
min_duration_off=min_duration_off,
)
class _TurnIndex:
"""Second-bucketed interval index for word-midpoint lookups."""
def __init__(self, turns: Sequence[SpeakerTurn]) -> None:
buckets: dict[int, list[tuple[int, SpeakerTurn]]] = {}
for order, turn in enumerate(turns):
if turn.end < turn.start:
continue
first = math.floor(turn.start / _TURN_INDEX_BUCKET)
last = math.floor(turn.end / _TURN_INDEX_BUCKET)
for bucket in range(first, last + 1):
buckets.setdefault(bucket, []).append((order, turn))
self._buckets = buckets
def speaker_at(self, moment: float) -> str | None:
"""Return the speaker of the earliest turn containing ``moment``, if any."""
best: tuple[int, str] | None = None
bucket = math.floor(moment / _TURN_INDEX_BUCKET)
for order, turn in self._buckets.get(bucket, ()):
if turn.start <= moment <= turn.end and (best is None or order < best[0]):
best = (order, turn.speaker)
return None if best is None else best[1]
def _majority_speaker(counts: dict[str, int], first_seen: list[str]) -> str | None:
"""Pick the most frequent speaker; ties go to the earliest first appearance."""
best: str | None = None
best_count = 0
for speaker in first_seen:
if counts[speaker] > best_count:
best = speaker
best_count = counts[speaker]
return best
def attribute_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript:
"""Label transcript words and segments with speakers from ``turns``.
Each word is attributed by midpoint containment: the midpoint
``(word.start + word.end) / 2`` is looked up in the turns, using inclusive
bounds ``turn.start <= midpoint <= turn.end``. When several turns contain a
midpoint (overlapping turns, or a midpoint exactly on a boundary) the earliest
turn in ``turns`` wins. A segment's speaker is the majority of its attributed
words; ties go to the speaker of the earliest attributed word. Segments with no
words, or whose words all fall outside every turn, get ``speaker=None``.
Args:
transcript: Transcript produced by any STT backend.
turns: Diarization turns (e.g. from :func:`diarize_audio`).
Returns:
A new ``Transcript`` with ``speaker_turns`` filled in and per-segment
speakers set; the input object is never mutated. With an empty ``turns``
list the transcript is returned unchanged.
"""
if not turns:
logger.debug("No speaker turns to attribute; returning transcript unchanged")
return transcript.model_copy(deep=True)
result = transcript.model_copy(deep=True)
index = _TurnIndex(turns)
for segment in result.segments:
counts: dict[str, int] = {}
first_seen: list[str] = []
for word in segment.words:
midpoint = (word.start + word.end) / 2.0
speaker = index.speaker_at(midpoint)
if speaker is None:
continue
if speaker not in counts:
counts[speaker] = 0
first_seen.append(speaker)
counts[speaker] += 1
segment.speaker = _majority_speaker(counts, first_seen)
result.speaker_turns = [turn.model_copy(deep=True) for turn in turns]
return result
+512
View File
@@ -0,0 +1,512 @@
"""Environment diagnostics backing the ``va doctor`` command.
Every check is read-only and offline except for the llama-server health probe, which
only ever talks to ``Settings.llama_server_url`` (localhost by default). Nothing here
downloads models, loads weights or requires an API key: the report says what is
installed, what the active profile resolves to, and what is still missing.
"""
from __future__ import annotations
import asyncio
import importlib.util
import os
import shutil
import subprocess
import sys
from importlib import metadata
from pathlib import Path
from typing import Literal
from pydantic import BaseModel
from pydantic_ai.providers import infer_provider_class
from . import llm
from .config import Settings
from .model_assets import SHERPA_DIARIZATION_MODELS, model_path
from .vision import LLAMA_SERVER_COMMAND
__all__ = [
"PROVIDER_KEYS",
"REPORTED_KEYS",
"STT_KEY_VARS",
"DoctorCheck",
"DoctorReport",
"human_bytes",
"run_doctor",
"targets_local_server",
]
#: Outcome of one diagnostic line; only ``fail`` affects the command's exit code.
CheckStatus = Literal["ok", "warn", "fail", "info"]
#: API-key environment variable per pydantic-ai provider prefix (never required locally).
PROVIDER_KEYS: dict[str, str] = {
"deepseek": "DEEPSEEK_API_KEY",
"openrouter": "OPENROUTER_API_KEY",
"ollama": "OLLAMA_API_KEY",
"openai": "OPENAI_API_KEY",
"groq": "GROQ_API_KEY",
}
#: Keys the report always lists (presence only -- values are never read or printed).
REPORTED_KEYS: tuple[str, ...] = (
"GROQ_API_KEY",
"DEEPSEEK_API_KEY",
"OPENROUTER_API_KEY",
"OLLAMA_API_KEY",
)
#: Any of these keys authenticates the hosted transcription backend.
STT_KEY_VARS: tuple[str, ...] = ("GROQ_API_KEY", "VA_STT_API_KEY", "OPENAI_API_KEY")
#: Python minor version the project targets (``requires-python >=3.13,<3.14``).
SUPPORTED_PYTHON = (3, 13)
#: Below this much free space the report warns (CPU model caches are hundreds of MB).
MIN_FREE_BYTES = 1024**3
_SIZE_UNITS = ("B", "KiB", "MiB", "GiB", "TiB", "PiB")
class DoctorCheck(BaseModel):
"""One diagnostic line: what was checked, how it turned out, and why it matters."""
name: str
status: CheckStatus
detail: str
class DoctorReport(BaseModel):
"""Result of a full environment check (serialisable for ``va doctor --json``)."""
profile: str
cache_dir: Path
checks: list[DoctorCheck] = []
llama_server_command: str | None = None
@property
def ok(self) -> bool:
"""True when no check failed; warnings stay informational."""
return not any(check.status == "fail" for check in self.checks)
def human_bytes(size: int) -> str:
"""Render a byte count as compact human-readable text (``1.5 GiB``)."""
value = float(max(int(size), 0))
for unit in _SIZE_UNITS[:-1]:
if value < 1024.0:
return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024.0
return f"{value:.1f} {_SIZE_UNITS[-1]}"
def _has_env(name: str) -> bool:
"""True when the environment variable exists and is non-empty."""
return bool(os.environ.get(name, "").strip())
def _module_available(name: str) -> bool:
"""True when ``name`` can be located without importing it eagerly."""
try:
return importlib.util.find_spec(name) is not None
except (ImportError, ModuleNotFoundError, ValueError):
return False
def targets_local_server(spec: str) -> bool:
"""True when :func:`video_analyse.llm.build_model` routes ``spec`` to llama-server.
A bare model name, a ``local:<name>`` spec and an unknown ``vendor:name`` prefix all
resolve to the local OpenAI-compatible server; a prefix pydantic-ai knows (``deepseek``,
``openrouter``, ``ollama``, ...) is hosted. The bare ``"test"`` spec builds pydantic-ai's
``TestModel`` and needs no server.
"""
spec = (spec or "").strip()
if not spec or spec == "test":
return False
prefix, separator, _rest = spec.partition(":")
if not separator or prefix == llm.LOCAL_PREFIX:
return True
try:
infer_provider_class(prefix)
except ValueError:
return True # unknown prefix: llm.build_model keeps it as a local model name
except ImportError:
return False # known hosted provider without its optional SDK: not local
return False
def _python_check() -> DoctorCheck:
"""Report the interpreter version and whether it matches the supported range."""
info = sys.version_info
version = f"{info.major}.{info.minor}.{info.micro}"
supported = (info.major, info.minor) == SUPPORTED_PYTHON
status: CheckStatus = "ok" if supported else "warn"
range_hint = f"{SUPPORTED_PYTHON[0]}.{SUPPORTED_PYTHON[1]}"
detail = f"{version} at {sys.executable}"
if not supported:
detail += f"; the project targets Python {range_hint} (requires-python >=3.13,<3.14)"
return DoctorCheck(name="python", status=status, detail=detail)
def _profile_check(settings: Settings) -> DoctorCheck:
"""Report the active profile and every stage's resolved model/back end."""
diarize = "on" if settings.diarize else "off"
detail = (
f"{settings.profile} (stt={settings.resolved_stt()}, vlm={settings.resolved_vlm()}, "
f"synthesis={settings.resolved_synthesis()}, "
f"diarize={diarize}:{settings.diarize_backend})"
)
return DoctorCheck(name="profile", status="info", detail=detail)
def _tool_check(name: str, *, timeout: float) -> DoctorCheck:
"""Locate ``name`` on PATH and capture the first line of its version output."""
path = shutil.which(name)
if path is None:
hint = (
" Install it with 'sudo pacman -S ffmpeg' (Arch) or your package manager."
if name in {"ffmpeg", "ffprobe"}
else ""
)
return DoctorCheck(name=name, status="fail", detail=f"not found on PATH.{hint}")
try:
completed = subprocess.run(
[path, "-version"],
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
return DoctorCheck(name=name, status="warn", detail=f"{path} (version check failed: {exc})")
lines = (completed.stdout or completed.stderr or "").strip().splitlines()
version = lines[0].strip() if lines else "unknown version"
return DoctorCheck(name=name, status="ok", detail=f"{path} -- {version}")
def _ytdlp_check() -> DoctorCheck:
"""Report whether the yt-dlp module can be imported and which version it is."""
if not _module_available("yt_dlp"):
return DoctorCheck(
name="yt-dlp",
status="warn",
detail="not importable; URL ingest (va fetch) is unavailable",
)
try:
version = metadata.version("yt-dlp")
except metadata.PackageNotFoundError:
version = "unknown version"
return DoctorCheck(name="yt-dlp", status="ok", detail=f"importable ({version})")
def _required_keys(settings: Settings) -> list[tuple[str, tuple[str, ...]]]:
"""Hosted credentials the active configuration needs: ``(stage label, any-of keys)``."""
required: list[tuple[str, tuple[str, ...]]] = []
if settings.resolved_stt() == "openai-transcriptions":
required.append(("stt api key", STT_KEY_VARS))
stages = (
("vision api key", settings.resolved_vlm()),
("synthesis api key", settings.resolved_synthesis()),
)
for label, spec in stages:
if targets_local_server(spec):
continue
prefix = spec.partition(":")[0].strip().lower()
key = PROVIDER_KEYS.get(prefix)
if key is not None:
required.append((f"{label} ({spec})", (key,)))
return required
def _key_checks(settings: Settings) -> list[DoctorCheck]:
"""Presence checks for the keys the active profile needs, plus the standard four."""
checks: list[DoctorCheck] = []
required = _required_keys(settings)
if not required:
checks.append(
DoctorCheck(
name="hosted api keys",
status="info",
detail="none required by the active configuration (fully local)",
)
)
for label, key_vars in required:
present = [name for name in key_vars if _has_env(name)]
if present:
checks.append(DoctorCheck(name=label, status="ok", detail="set: " + ", ".join(present)))
else:
checks.append(
DoctorCheck(
name=label,
status="warn",
detail=(f"missing {' or '.join(key_vars)}; export it or use VA_PROFILE=local"),
)
)
for name in REPORTED_KEYS:
present = _has_env(name)
checks.append(
DoctorCheck(
name=name,
status="ok" if present else "info",
detail="set" if present else "not set",
)
)
return checks
def _diarization_checks(settings: Settings) -> list[DoctorCheck]:
"""Check that the configured diarization backend's dependencies/assets are present."""
if settings.diarize_backend == "pyannote":
installed = _module_available("pyannote.audio")
token = _has_env("HF_TOKEN")
status: CheckStatus = "ok" if installed and token else "warn"
detail = (
"optional pyannote backend: package "
+ ("installed" if installed else "missing (uv sync --extra pyannote)")
+ ", HF_TOKEN "
+ ("set" if token else "missing (gated model: accept the terms on HuggingFace)")
)
return [DoctorCheck(name="diarization", status=status, detail=detail)]
checks: list[DoctorCheck] = []
for name in SHERPA_DIARIZATION_MODELS:
path = model_path(name, cache_dir=settings.cache_dir)
if path.is_file():
checks.append(
DoctorCheck(
name=name,
status="ok",
detail=f"{path} ({human_bytes(path.stat().st_size)})",
)
)
else:
checks.append(
DoctorCheck(
name=name,
status="warn",
detail=(
f"not downloaded yet: {path} (auto-downloaded on the first "
"diarization run, about 46 MB in total)"
),
)
)
return checks
def _hf_cache_dir() -> Path:
"""HuggingFace hub cache directory (``HF_HOME`` aware)."""
root = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface"))
return root / "hub"
def _stt_model_checks(settings: Settings) -> list[DoctorCheck]:
"""Report whether the configured local STT weights are already cached."""
backend = settings.resolved_stt()
if backend == "openai-transcriptions":
return [
DoctorCheck(
name="stt model",
status="info",
detail=(
f"hosted: {settings.stt_api_model} at {settings.stt_api_base_url} "
"(no local weights needed)"
),
)
]
hub = _hf_cache_dir()
if backend == "whisper":
pattern = f"models--Systran--faster-whisper-{settings.whisper_model}"
label = f"faster-whisper {settings.whisper_model}"
else:
from .transcribe.parakeet_onnx import select_model_name
model_name = select_model_name(settings.language)
repo_name = model_name.removeprefix("nemo-")
pattern = f"models--istupakov--{repo_name}-onnx"
label = f"onnx-asr {model_name}"
path = hub / pattern
if path.is_dir():
return [DoctorCheck(name="stt model", status="ok", detail=f"{label} cached at {path}")]
return [
DoctorCheck(
name="stt model",
status="warn",
detail=(
f"{label} is not cached yet under {hub}; it is downloaded on the first "
"transcription run (several hundred MB)"
),
)
]
def _provider_sdk_checks(settings: Settings) -> list[DoctorCheck]:
"""Warn when a configured hosted model's optional provider SDK is not installed."""
checks: list[DoctorCheck] = []
seen: set[str] = set()
for spec in (settings.resolved_vlm(), settings.resolved_synthesis()):
if targets_local_server(spec) or spec == "test":
continue
prefix = spec.partition(":")[0].strip().lower()
if not prefix or prefix in seen:
continue
seen.add(prefix)
try:
infer_provider_class(prefix)
except ImportError:
checks.append(
DoctorCheck(
name=f"provider sdk ({prefix})",
status="warn",
detail=(
f"{spec!r} needs the pydantic-ai provider extra for {prefix}; install "
"it (for example 'uv sync --extra ...' or the matching provider "
"package) before using this model"
),
)
)
except ValueError:
continue
else:
checks.append(
DoctorCheck(
name=f"provider sdk ({prefix})",
status="ok",
detail=f"available for {spec}",
)
)
return checks
def _local_model_id(spec: str) -> str | None:
"""Model name llama-server should advertise for a local spec."""
if not targets_local_server(spec) or spec == "test":
return None
prefix, separator, rest = spec.partition(":")
if separator and prefix == llm.LOCAL_PREFIX:
return rest or None
return spec or None
def _cache_check(settings: Settings) -> DoctorCheck:
"""Report the cache directory location and how much it currently holds."""
cache_dir = settings.cache_dir
if not cache_dir.exists():
return DoctorCheck(name="cache dir", status="info", detail=f"{cache_dir} (not created yet)")
total = 0
files = 0
for entry in cache_dir.rglob("*"):
try:
if entry.is_file():
total += entry.stat().st_size
files += 1
except OSError:
continue
return DoctorCheck(
name="cache dir",
status="info",
detail=f"{cache_dir} ({human_bytes(total)} in {files} files)",
)
def _disk_check(settings: Settings) -> DoctorCheck:
"""Report free disk space on the filesystem that holds the cache."""
target = settings.cache_dir
while not target.exists() and target != target.parent:
target = target.parent
try:
usage = shutil.disk_usage(target)
except OSError as exc:
return DoctorCheck(
name="free disk", status="warn", detail=f"could not stat {target}: {exc}"
)
status: CheckStatus = "ok" if usage.free >= MIN_FREE_BYTES else "warn"
return DoctorCheck(
name="free disk",
status=status,
detail=f"{human_bytes(usage.free)} free of {human_bytes(usage.total)} on {target}",
)
async def _llama_check(settings: Settings) -> tuple[DoctorCheck, str | None]:
"""Check the local llama-server when a local VLM/synthesis spec is in use."""
specs = (settings.resolved_vlm(), settings.resolved_synthesis())
if not any(targets_local_server(spec) for spec in specs):
return (
DoctorCheck(
name="llama-server",
status="info",
detail="not needed: vision and synthesis use a hosted provider",
),
None,
)
if await llm.llama_server_up(settings):
served = await llm.llama_server_models(settings) or []
expected = [
model for model in (_local_model_id(spec) for spec in specs) if model is not None
]
missing = [model for model in expected if model not in served]
if missing:
return (
DoctorCheck(
name="llama-server",
status="warn",
detail=(
f"reachable at {settings.llama_server_url}, but it does not list "
f"{', '.join(missing)} (served: {', '.join(served) or 'none'}); "
"start it with the model VA_VLM_MODEL names"
),
),
LLAMA_SERVER_COMMAND,
)
return (
DoctorCheck(
name="llama-server",
status="ok",
detail=(
f"reachable at {settings.llama_server_url}; serving "
f"{', '.join(served) or 'no listed models'}"
),
),
None,
)
return (
DoctorCheck(
name="llama-server",
status="warn",
detail=f"not reachable at {settings.llama_server_url}; start it with the command below",
),
LLAMA_SERVER_COMMAND,
)
async def run_doctor(settings: Settings, *, timeout: float = 10.0) -> DoctorReport:
"""Collect every diagnostic check and return the report.
Args:
settings: the active settings (profile, cache dir, model specs).
timeout: seconds allowed for each external ``-version`` call.
Returns:
A :class:`DoctorReport`; ``report.ok`` is false only when ffmpeg or ffprobe is
missing, so a partial-but-usable setup still exits 0.
"""
checks: list[DoctorCheck] = [_python_check(), _profile_check(settings)]
for tool in ("ffmpeg", "ffprobe"):
checks.append(await asyncio.to_thread(_tool_check, tool, timeout=timeout))
checks.append(await asyncio.to_thread(_ytdlp_check))
llama_check, llama_command = await _llama_check(settings)
checks.append(llama_check)
checks.extend(_key_checks(settings))
checks.extend(_provider_sdk_checks(settings))
checks.extend(_stt_model_checks(settings))
checks.extend(await asyncio.to_thread(_diarization_checks, settings))
checks.append(await asyncio.to_thread(_cache_check, settings))
checks.append(await asyncio.to_thread(_disk_check, settings))
return DoctorReport(
profile=settings.profile,
cache_dir=settings.cache_dir,
checks=checks,
llama_server_command=llama_command,
)
+414
View File
@@ -0,0 +1,414 @@
"""Source ingest: resolve local media paths and download remote videos.
Local files are validated in place. ``http(s)`` URLs are downloaded with yt-dlp
into a deterministic per-URL directory under ``<cache_dir>/downloads/`` so that a
second run reuses the same files. Anything else (other URL schemes) is rejected
with a ``ValueError``.
The blocking yt-dlp call runs in a worker thread; nothing here touches the network
unless an ``http(s)`` URL is passed in.
"""
from __future__ import annotations
import asyncio
import contextlib
import hashlib
import json
import logging
import re
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
DOWNLOAD_DIR_NAME = "downloads"
INGEST_INFO_FILE_NAME = "ingest-info.json"
DIRECT_DOWNLOAD_TIMEOUT_S = 900.0
VIDEO_EXTENSIONS = frozenset(
{
".3gp",
".asf",
".avi",
".divx",
".f4v",
".flv",
".m2ts",
".m4v",
".mkv",
".mov",
".mp4",
".mpeg",
".mpg",
".mts",
".mxf",
".ogv",
".rm",
".rmvb",
".ts",
".vob",
".webm",
".wmv",
}
)
AUDIO_EXTENSIONS = frozenset({".aac", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".wma"})
MEDIA_EXTENSIONS = VIDEO_EXTENSIONS | AUDIO_EXTENSIONS
__all__ = ["IngestResult", "fetch"]
class IngestResult(BaseModel):
"""A resolved local media file plus provenance when it was downloaded."""
path: Path
info: dict[str, Any] = Field(default_factory=dict)
downloaded: bool
title: str | None = None
def _host_with_port(parsed: Any) -> str:
"""Return ``hostname[:port]`` without credentials, tolerating malformed ports."""
host = parsed.hostname or ""
try:
port = parsed.port
except ValueError:
port = None
return f"{host}:{port}" if port is not None else host
def _redacted_url(url: str) -> str:
"""Return ``url`` without credentials or query string (safe for logs and errors)."""
parsed = urlparse(url)
host = _host_with_port(parsed)
redacted = f"{parsed.scheme}://{host}{parsed.path}" if parsed.scheme else parsed.path
return redacted or "<url>"
def _safe_dir_name(url: str) -> str:
"""Deterministic, filesystem-safe directory name for a download URL.
Only the hostname (never userinfo) and path are used in the human-readable slug,
so credentials embedded in a URL never reach the cache path or a log line.
"""
parsed = urlparse(url)
raw = f"{_host_with_port(parsed)}{parsed.path}"
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", raw).strip("-._")
if not slug:
slug = "download"
digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:10]
return f"{slug[:64]}-{digest}"
def _download_dir_name(url: str, quality: int) -> str:
"""Download identity: URL *and* requested quality (PLAN section 3.4)."""
return f"{_safe_dir_name(url)}-q{int(quality)}"
def _is_direct_media_url(url: str) -> bool:
"""True for ``http(s)`` URLs that name a media file directly (no site extractor)."""
return Path(urlparse(url).path).suffix.lower() in MEDIA_EXTENSIONS
def _youtube_dl_options(target_dir: Path, quality: int) -> dict[str, Any]:
"""yt-dlp options for one analysis-friendly video+audio file plus metadata JSON."""
return {
# Best video at or below ``quality`` pixels high, muxed with the best audio;
# each fallback is progressively less picky. Never download a whole playlist.
"format": f"bv*[height<={quality}]+ba/b[height<={quality}]/b",
"outtmpl": "%(title)s [%(id)s].%(ext)s",
"paths": {"home": str(target_dir), "temp": str(target_dir)},
"noplaylist": True,
"extract_flat": False,
"writeinfojson": True,
"restrictfilenames": True,
"overwrites": False,
"continuedl": True,
"retries": 3,
"fragment_retries": 3,
"socket_timeout": 30.0,
"quiet": True,
"no_warnings": True,
"noprogress": True,
"no_color": True,
}
def _title_from_info(info: dict[str, Any]) -> str | None:
"""Extract a non-empty title string from a yt-dlp info dict."""
title = info.get("title")
if isinstance(title, str) and title.strip():
return title.strip()
return None
def _candidate_paths(ydl: Any, info: dict[str, Any], target_dir: Path) -> list[Path]:
"""Candidate local paths for a finished yt-dlp download, most specific first."""
candidates: list[Path] = []
filepath = info.get("filepath")
if isinstance(filepath, str) and filepath:
candidates.append(Path(filepath))
requested = info.get("requested_downloads")
if isinstance(requested, list):
for entry in requested:
if not isinstance(entry, dict):
continue
for key in ("filepath", "_filename", "filename"):
value = entry.get(key)
if isinstance(value, str) and value:
candidates.append(Path(value))
try:
prepared = ydl.prepare_filename(info)
except Exception as exc: # yt-dlp derives the name from arbitrary metadata
logger.debug("prepare_filename failed for %s: %s", info.get("id"), exc)
else:
if isinstance(prepared, str) and prepared:
candidates.append(Path(prepared))
return [
candidate if candidate.is_absolute() else target_dir / candidate for candidate in candidates
]
def _find_media_file(target_dir: Path) -> Path | None:
"""Return the newest media file already present in ``target_dir``, if any."""
if not target_dir.is_dir():
return None
media_files = [
entry
for entry in target_dir.iterdir()
if entry.is_file()
and entry.suffix.lower() in MEDIA_EXTENSIONS
and not entry.name.endswith(".part")
]
if not media_files:
return None
return max(media_files, key=lambda entry: entry.stat().st_mtime).resolve()
def _resolve_downloaded_path(ydl: Any, info: dict[str, Any], target_dir: Path) -> Path:
"""Find the media file yt-dlp just produced, tolerating container remuxing."""
for candidate in _candidate_paths(ydl, info, target_dir):
if candidate.is_file() and candidate.stat().st_size > 0:
return candidate.resolve()
# Remuxing/merging may change the extension, so fall back to the newest media file.
media_files = [
entry
for entry in target_dir.iterdir()
if entry.is_file()
and entry.suffix.lower() in MEDIA_EXTENSIONS
and not entry.name.endswith(".part")
]
if media_files:
newest = max(media_files, key=lambda entry: entry.stat().st_mtime)
logger.debug("Resolved download via directory scan: %s", newest)
return newest.resolve()
raise RuntimeError(
f"yt-dlp reported success for {info.get('webpage_url') or info.get('id') or 'the URL'} "
f"but no media file was found in {target_dir}"
)
def _download_sync(url: str, target_dir: Path, quality: int) -> tuple[Path, dict[str, Any]]:
"""Blocking yt-dlp download; run via ``asyncio.to_thread``."""
from yt_dlp import YoutubeDL
from yt_dlp.utils import YoutubeDLError
target_dir.mkdir(parents=True, exist_ok=True)
options = _youtube_dl_options(target_dir, quality)
try:
with YoutubeDL(options) as ydl:
info = ydl.extract_info(url, download=True)
if not isinstance(info, dict):
raise RuntimeError(f"yt-dlp returned no video metadata for {_redacted_url(url)}")
clean_info = ydl.sanitize_info(info)
if not isinstance(clean_info, dict):
clean_info = dict(info)
path = _resolve_downloaded_path(ydl, clean_info, target_dir)
except YoutubeDLError as exc:
shown = _redacted_url(url)
raise RuntimeError(
f"yt-dlp could not download {shown}: {exc}. Check that the URL is reachable and "
"supported by yt-dlp (a direct video URL works too), or download the file "
"manually and pass its local path instead."
) from exc
logger.info("Downloaded %s to %s", _redacted_url(url), path)
return path, clean_info
def _save_ingest_info(target_dir: Path, path: Path, info: dict[str, Any]) -> None:
"""Persist the resolved download path and metadata for later cache hits."""
payload = {"path": str(path), "info": info}
try:
(target_dir / INGEST_INFO_FILE_NAME).write_text(
json.dumps(payload, ensure_ascii=False, default=str) + "\n", encoding="utf-8"
)
except OSError as exc: # a read-only cache must not fail the download
logger.warning("could not write ingest metadata in %s: %s", target_dir, exc)
def _load_cached_download(target_dir: Path) -> tuple[Path, dict[str, Any]] | None:
"""Return a previously completed download for this URL+quality, if still present."""
payload_path = target_dir / INGEST_INFO_FILE_NAME
if not payload_path.is_file():
return None
try:
payload = json.loads(payload_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(payload, dict):
return None
raw_path = payload.get("path")
info = payload.get("info")
if not isinstance(raw_path, str) or not isinstance(info, dict):
return None
path = Path(raw_path)
if not path.is_file() or path.stat().st_size == 0:
return None
return path, info
async def _download_direct(url: str, target_dir: Path, quality: int) -> tuple[Path, dict[str, Any]]:
"""Fetch a direct media URL with ffmpeg (no yt-dlp, argument list, no shell)."""
parsed = urlparse(url)
suffix = Path(parsed.path).suffix.lower() or ".mp4"
stem = re.sub(r"[^A-Za-z0-9._-]+", "-", Path(parsed.path).stem).strip("-._") or "download"
target = target_dir / f"{stem}{suffix}"
target_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"ffmpeg",
"-hide_banner",
"-loglevel",
"error",
"-nostdin",
"-y",
"-i",
url,
"-c",
"copy",
str(target),
]
try:
process = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
except FileNotFoundError as exc:
raise RuntimeError(
"ffmpeg was not found on PATH; install ffmpeg to download direct media URLs"
) from exc
try:
_stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=DIRECT_DOWNLOAD_TIMEOUT_S
)
except TimeoutError as exc:
with contextlib.suppress(ProcessLookupError):
process.kill()
await process.wait()
raise RuntimeError(
f"ffmpeg timed out after {DIRECT_DOWNLOAD_TIMEOUT_S:.0f}s downloading "
f"{_redacted_url(url)}"
) from exc
except asyncio.CancelledError:
with contextlib.suppress(ProcessLookupError):
process.kill()
await process.wait()
raise
if process.returncode != 0 or not target.is_file() or target.stat().st_size == 0:
detail = stderr.decode("utf-8", errors="replace").strip()[-800:]
with contextlib.suppress(OSError):
target.unlink()
raise RuntimeError(
f"ffmpeg could not download {_redacted_url(url)} (exit {process.returncode}): "
f"{detail or 'no output'}"
)
info = {
"title": target.stem,
"webpage_url": _redacted_url(url),
"ext": suffix.lstrip("."),
"url": _redacted_url(url),
}
logger.info("Downloaded direct media URL %s to %s", _redacted_url(url), target)
_save_ingest_info(target_dir, target, info)
return target.resolve(), info
async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestResult:
"""Resolve ``source`` to a local media file, downloading http(s) URLs via yt-dlp.
``quality`` is the maximum video height in pixels for downloads. Local paths must
exist and carry a known media extension; URLs must be ``http``/``https``.
Raises:
ValueError: empty source, other URL schemes, missing/empty local file, an
unknown extension, or a non-positive ``quality``.
RuntimeError: yt-dlp failed, timed out, or produced no media file.
"""
if isinstance(quality, bool) or not isinstance(quality, int) or quality < 1:
raise ValueError(f"quality must be a positive integer (max video height), got {quality!r}")
source = source.strip()
if not source:
raise ValueError("source must not be empty")
parsed = urlparse(source)
scheme = parsed.scheme.lower()
if scheme in {"http", "https"}:
if not parsed.netloc:
raise ValueError(f"Malformed URL (missing host): {_redacted_url(source)!r}")
target_dir = (
Path(cache_dir).expanduser() / DOWNLOAD_DIR_NAME / _download_dir_name(source, quality)
)
cached = _load_cached_download(target_dir)
if cached is not None:
path, info = cached
logger.info("Reusing cached download %s", _redacted_url(source))
return IngestResult(
path=path, info=info, downloaded=False, title=_title_from_info(info)
)
logger.info("Downloading %s into %s", _redacted_url(source), target_dir)
if _is_direct_media_url(source):
path, info = await _download_direct(source, target_dir, quality)
else:
existing = _find_media_file(target_dir)
path, info = await asyncio.to_thread(_download_sync, source, target_dir, quality)
if existing is not None and path == existing:
logger.info("yt-dlp reused an existing file for %s", _redacted_url(source))
_save_ingest_info(target_dir, path, info)
return IngestResult(
path=path, info=info, downloaded=False, title=_title_from_info(info)
)
_save_ingest_info(target_dir, path, info)
return IngestResult(
path=path,
info=info,
downloaded=True,
title=_title_from_info(info),
)
if scheme:
raise ValueError(
f"Unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file path "
"or an http(s) URL"
)
local = Path(source).expanduser()
if not local.exists():
raise ValueError(f"Local media file not found: {local}")
if not local.is_file():
raise ValueError(f"Local path is not a regular file: {local}")
suffix = local.suffix.lower()
if suffix not in MEDIA_EXTENSIONS:
supported = ", ".join(sorted(MEDIA_EXTENSIONS))
shown = suffix if suffix else "<none>"
raise ValueError(
f"{local} does not look like a media file (extension {shown}); "
f"supported extensions: {supported}"
)
if local.stat().st_size == 0:
raise ValueError(f"Local media file is empty: {local}")
return IngestResult(path=local.resolve(), info={}, downloaded=False, title=None)
+106
View File
@@ -0,0 +1,106 @@
"""pydantic-ai model construction helpers.
Model specs accepted by :func:`build_model`:
* ``"local:<name>"`` - always the local llama-server (OpenAI-compatible).
* a bare name (``"Qwen3-VL-4B-Instruct"``) - the local llama-server.
* ``"<provider>:<model>"`` for a provider pydantic-ai knows
(``deepseek:``, ``openrouter:``, ``ollama:``, ``openai:``, ``groq:`` ...) -
delegated to :func:`pydantic_ai.models.infer_model`.
Verified against pydantic-ai 2.63.0 (see CONTRACTS.md).
"""
from __future__ import annotations
import logging
import httpx
from pydantic_ai.models import Model, infer_model
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers import infer_provider_class
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
from .config import Settings
logger = logging.getLogger(__name__)
LOCAL_PREFIX = "local" # used as "local:<model-name>"
LOCAL_PROVIDER_NAME = "llama-server"
def _is_known_provider(prefix: str) -> bool:
"""True when ``prefix`` names a provider pydantic-ai can instantiate."""
if not prefix:
return False
try:
infer_provider_class(prefix)
except ValueError:
return False
except ImportError:
# A registered provider whose optional SDK extra is not installed: it is still a
# hosted provider, so build_model must route it through infer_model (which then
# raises the actionable "install the extra" error) rather than to llama-server.
return True
return True
def build_local_model(name: str, settings: Settings) -> OpenAIChatModel:
"""Build an ``OpenAIChatModel`` pointed at the local llama-server."""
provider = OpenAICompatibleProvider(
LOCAL_PROVIDER_NAME,
base_url=settings.llama_server_url,
api_key="local",
)
return OpenAIChatModel(name, provider=provider)
def build_model(spec: str, *, settings: Settings) -> Model:
"""Turn a model spec into a pydantic-ai ``Model`` (no network I/O)."""
spec = (spec or "").strip()
if not spec:
raise ValueError("empty model spec")
if spec == "test": # pydantic-ai's TestModel, handy for tests
return infer_model(spec)
prefix, sep, rest = spec.partition(":")
if sep and prefix == LOCAL_PREFIX:
if not rest:
raise ValueError("model spec 'local:' is missing a model name")
return build_local_model(rest, settings)
if sep and _is_known_provider(prefix):
return infer_model(spec)
return build_local_model(spec, settings)
async def llama_server_models(settings: Settings) -> list[str] | None:
"""Return the model ids served by llama-server, or ``None`` when it is unreachable.
A malformed or out-of-range URL (``http://host:abc/v1``, port 99999), a connection
error and a timeout all return ``None`` instead of raising, so health checks and
``va doctor`` degrade to a warning row rather than a traceback.
"""
url = settings.llama_server_url.rstrip("/") + "/models"
try:
async with httpx.AsyncClient(timeout=2.0) as client:
response = await client.get(url)
if not response.is_success:
return None
payload = response.json()
except Exception as exc: # malformed URLs, invalid ports, HTTP and JSON errors
logger.debug("llama-server health check failed for %s: %s", url, exc)
return None
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, list):
return []
return [
str(entry["id"])
for entry in data
if isinstance(entry, dict) and isinstance(entry.get("id"), str)
]
async def llama_server_up(settings: Settings) -> bool:
"""Cheap health check: GET ``{llama_server_url}/models`` (2 s timeout)."""
return await llama_server_models(settings) is not None
File diff suppressed because it is too large. Load diff
+539
View File
@@ -0,0 +1,539 @@
"""Media probing, audio extraction, shot detection and keyframe handling.
Every external tool is invoked as an argument list through ``asyncio``'s
subprocess API (never through a shell) with an explicit timeout. CPU-bound work
(PySceneDetect/OpenCV, Pillow plus perceptual hashing) is dispatched with
``asyncio.to_thread`` so the event loop is never blocked.
Artifact layout inside a stage work directory:
* ``audio.wav`` -- 16 kHz, mono, 16-bit PCM WAV for speech-to-text;
* ``keyframes/shot-<index>.jpg`` -- one JPEG keyframe per shot.
"""
from __future__ import annotations
import asyncio
import contextlib
import itertools
import json
import logging
import re
from pathlib import Path
from typing import Any
from .models import MediaInfo, Shot
logger = logging.getLogger(__name__)
FFMPEG = "ffmpeg"
FFPROBE = "ffprobe"
PROBE_TIMEOUT_S = 60.0
AUDIO_TIMEOUT_S = 900.0
KEYFRAME_TIMEOUT_S = 120.0
AUDIO_SAMPLE_RATE = 16_000
AUDIO_FILE_NAME = "audio.wav"
KEYFRAME_DIR_NAME = "keyframes"
__all__ = ["dedup_keyframes", "detect_shots", "extract_audio", "extract_keyframes", "probe"]
# --------------------------------------------------------------------------- #
# subprocess plumbing
# --------------------------------------------------------------------------- #
async def _run_tool(cmd: list[str], *, timeout: float) -> tuple[int, bytes, bytes]:
"""Run an external command (argument list, no shell) and collect its output.
Returns ``(returncode, stdout, stderr)``. A missing executable or a timeout is
reported as ``RuntimeError`` with an actionable message.
"""
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
except FileNotFoundError as exc:
raise RuntimeError(
f"Required executable {cmd[0]!r} was not found on PATH; "
"install ffmpeg (which ships ffmpeg and ffprobe) and try again"
) from exc
try:
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except TimeoutError as exc:
with contextlib.suppress(ProcessLookupError):
proc.kill()
await proc.wait()
raise RuntimeError(f"{cmd[0]!r} timed out after {timeout:.0f}s") from exc
except asyncio.CancelledError:
# The caller (MCP client disconnect, asyncio.run teardown) cancelled us: do not
# leave ffmpeg/ffprobe running with open pipes for the rest of the timeout.
with contextlib.suppress(ProcessLookupError):
proc.kill()
await proc.wait()
raise
return proc.returncode or 0, stdout, stderr
def _stderr_tail(stderr: bytes, *, limit: int = 800) -> str:
"""Decode the tail of a process' stderr for an error message."""
text = stderr.decode("utf-8", errors="replace").strip()
if len(text) > limit:
text = "..." + text[-limit:]
return text or "(no output)"
def _require_file(path: Path) -> Path:
"""Expand ``path`` and assert it is an existing regular file."""
resolved = Path(path).expanduser()
if not resolved.exists():
raise ValueError(f"Media file not found: {resolved}")
if not resolved.is_file():
raise ValueError(f"Not a regular file: {resolved}")
return resolved
# --------------------------------------------------------------------------- #
# ffprobe helpers
# --------------------------------------------------------------------------- #
def _as_float(value: Any) -> float | None:
"""Best-effort conversion of an ffprobe scalar (string or number) to float."""
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def _as_int(value: Any) -> int | None:
"""Best-effort conversion of an ffprobe scalar (string or number) to int."""
number = _as_float(value)
return None if number is None else int(number)
def _parse_rate(value: Any) -> float | None:
"""Parse an ffprobe frame rate such as ``"30000/1001"``; ``None`` if unusable."""
if not isinstance(value, str) or not value:
return None
numerator, _, denominator = value.partition("/")
try:
top = float(numerator)
bottom = float(denominator) if denominator else 1.0
except ValueError:
return None
if top <= 0 or bottom <= 0:
return None
return top / bottom
def _is_cover_art(stream: dict[str, Any]) -> bool:
"""True for an embedded album-art image stream (not a real video track)."""
disposition = stream.get("disposition")
return isinstance(disposition, dict) and bool(disposition.get("attached_pic"))
def _media_info_from_probe(path: Path, payload: dict[str, Any]) -> MediaInfo:
"""Build a :class:`MediaInfo` from an ffprobe ``-of json`` payload."""
format_info = payload.get("format")
if not isinstance(format_info, dict):
format_info = {}
raw_streams = payload.get("streams")
if isinstance(raw_streams, list):
streams = [stream for stream in raw_streams if isinstance(stream, dict)]
else:
streams = []
video_stream = next(
(s for s in streams if s.get("codec_type") == "video" and not _is_cover_art(s)),
None,
)
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), None)
if video_stream is None and audio_stream is None:
raise RuntimeError(
f"No audio or video stream found in {path}; the file does not look like media"
)
duration = _as_float(format_info.get("duration"))
if duration is None or duration <= 0:
stream_durations = [
value
for value in (_as_float(stream.get("duration")) for stream in streams)
if value is not None and value > 0
]
duration = max(stream_durations) if stream_durations else 0.0
size_bytes = _as_int(format_info.get("size"))
if size_bytes is None:
size_bytes = path.stat().st_size
fps: float | None = None
if video_stream is not None:
fps = _parse_rate(video_stream.get("r_frame_rate"))
if fps is None:
fps = _parse_rate(video_stream.get("avg_frame_rate"))
format_name = format_info.get("format_name")
return MediaInfo(
path=path,
source=str(path),
duration=float(duration),
width=_as_int(video_stream.get("width")) if video_stream is not None else None,
height=_as_int(video_stream.get("height")) if video_stream is not None else None,
fps=fps,
has_audio=audio_stream is not None,
size_bytes=size_bytes,
format=str(format_name) if format_name else None,
video_codec=str(video_stream["codec_name"])
if video_stream is not None and video_stream.get("codec_name")
else None,
audio_codec=str(audio_stream["codec_name"])
if audio_stream is not None and audio_stream.get("codec_name")
else None,
extra={"ffprobe": payload, "bit_rate": _as_int(format_info.get("bit_rate"))},
)
async def probe(path: Path) -> MediaInfo:
"""Probe a media file with ffprobe and return its technical metadata.
Raises:
ValueError: ``path`` does not exist or is not a regular file.
RuntimeError: ffprobe is missing, failed, timed out or returned bad JSON.
"""
media_path = _require_file(path)
cmd = [
FFPROBE,
"-v",
"quiet",
"-show_format",
"-show_streams",
"-of",
"json",
str(media_path),
]
returncode, stdout, stderr = await _run_tool(cmd, timeout=PROBE_TIMEOUT_S)
if returncode != 0:
raise RuntimeError(
f"ffprobe failed for {media_path} (exit {returncode}): {_stderr_tail(stderr)}"
)
try:
payload = json.loads(stdout.decode("utf-8", errors="replace") or "{}")
except json.JSONDecodeError as exc:
raise RuntimeError(f"ffprobe returned invalid JSON for {media_path}: {exc}") from exc
if not isinstance(payload, dict):
raise RuntimeError(f"ffprobe returned an unexpected payload for {media_path}")
return _media_info_from_probe(media_path, payload)
# --------------------------------------------------------------------------- #
# audio extraction
# --------------------------------------------------------------------------- #
async def extract_audio(path: Path, workdir: Path) -> Path:
"""Extract a 16 kHz mono 16-bit PCM WAV at ``workdir/audio.wav``.
An existing file is overwritten. Returns the WAV path.
Raises:
ValueError: ``path`` is not an existing regular file.
RuntimeError: the file has no audio stream or ffmpeg failed.
"""
media_path = _require_file(path)
workdir_path = Path(workdir).expanduser()
workdir_path.mkdir(parents=True, exist_ok=True)
out = workdir_path / AUDIO_FILE_NAME
cmd = [
FFMPEG,
"-hide_banner",
"-loglevel",
"error",
"-nostdin",
"-y",
"-i",
str(media_path),
"-vn",
"-ac",
"1",
"-ar",
str(AUDIO_SAMPLE_RATE),
"-c:a",
"pcm_s16le",
str(out),
]
returncode, _stdout, stderr = await _run_tool(cmd, timeout=AUDIO_TIMEOUT_S)
if returncode != 0 or not out.is_file() or out.stat().st_size <= 44:
detail = _stderr_tail(stderr)
if "does not contain any stream" in detail:
raise RuntimeError(f"No audio stream to extract from {media_path}: {detail}")
raise RuntimeError(
f"ffmpeg audio extraction failed for {media_path} (exit {returncode}): {detail}"
)
return out
# --------------------------------------------------------------------------- #
# shot detection
# --------------------------------------------------------------------------- #
def _detect_cuts_sync(
path: Path, min_scene_len: float, fallback_duration: float
) -> tuple[list[float], float]:
"""Run PySceneDetect's AdaptiveDetector on a video (blocking; use a thread).
Returns the cut timestamps (seconds) and the video duration. The cut list is
empty when nothing is detected; the duration comes from the video itself and
falls back to ``fallback_duration`` when the container does not report one.
"""
from scenedetect import AdaptiveDetector, SceneManager, open_video
try:
video = open_video(str(path), backend="opencv")
except Exception as exc: # PySceneDetect raises backend-specific errors here
raise RuntimeError(f"PySceneDetect could not open {path}: {exc}") from exc
try:
duration = float(fallback_duration)
if video.duration is not None:
with contextlib.suppress(TypeError, ValueError):
measured = float(video.duration.seconds)
if measured > 0:
duration = measured
manager = SceneManager()
manager.add_detector(AdaptiveDetector(min_scene_len=min_scene_len))
manager.detect_scenes(video, show_progress=False)
scenes = manager.get_scene_list()
cuts = [float(start.seconds) for start, _end in scenes]
finally:
capture = getattr(video, "capture", None)
release = getattr(capture, "release", None)
if callable(release):
release()
return cuts, duration
def _cut_boundaries(cuts: list[float], duration: float) -> list[float]:
"""Turn cut timestamps into strictly increasing shot boundaries spanning the video."""
end = round(float(duration), 3)
if end <= 0:
end = float(duration)
boundaries = [0.0]
for cut in sorted(float(cut) for cut in cuts):
value = round(cut, 3)
if value <= boundaries[-1] or value >= end:
continue
boundaries.append(value)
boundaries.append(end)
return boundaries
def _merge_short_segments(
segments: list[tuple[float, float]], min_scene_len: float
) -> list[tuple[float, float]]:
"""Merge every segment shorter than ``min_scene_len`` into its closer neighbour."""
merged = list(segments)
epsilon = 1e-6 # boundaries are rounded to milliseconds; guard float subtraction
while len(merged) > 1:
shortest = min(range(len(merged)), key=lambda i: merged[i][1] - merged[i][0])
start, end = merged[shortest]
if end - start >= min_scene_len - epsilon:
break
if shortest == 0:
merged[1] = (start, merged[1][1])
del merged[0]
elif shortest == len(merged) - 1:
merged[-2] = (merged[-2][0], end)
del merged[-1]
else:
previous_cost = end - merged[shortest - 1][0]
next_cost = merged[shortest + 1][1] - start
if previous_cost <= next_cost:
merged[shortest - 1] = (merged[shortest - 1][0], end)
del merged[shortest]
else:
merged[shortest + 1] = (start, merged[shortest + 1][1])
del merged[shortest]
return merged
def _apply_shot_budget(
segments: list[tuple[float, float]], max_shots: int
) -> list[tuple[float, float]]:
"""Merge the shortest adjacent pair repeatedly until at most ``max_shots`` remain."""
if max_shots < 1:
raise ValueError(f"max_shots must be >= 1, got {max_shots}")
merged = list(segments)
while len(merged) > max_shots:
pair = min(range(len(merged) - 1), key=lambda i: merged[i + 1][1] - merged[i][0])
merged[pair] = (merged[pair][0], merged[pair + 1][1])
del merged[pair + 1]
return merged
async def detect_shots(
path: Path, info: MediaInfo, *, max_shots: int = 64, min_scene_len: float = 0.6
) -> list[Shot]:
"""Detect shots with PySceneDetect (AdaptiveDetector, OpenCV backend).
Shots shorter than ``min_scene_len`` are merged into their closer neighbour and
the shortest adjacent pairs are merged until at most ``max_shots`` remain. The
result always covers ``[0, duration]`` exactly once, in order; when no cut is
detected a single full-length shot is returned.
Raises:
ValueError: ``path`` is missing, the duration is unknown, or an argument is
out of range.
RuntimeError: the video could not be opened.
"""
media_path = _require_file(path)
if max_shots < 1:
raise ValueError(f"max_shots must be >= 1, got {max_shots}")
if min_scene_len < 0:
raise ValueError(f"min_scene_len must be >= 0, got {min_scene_len}")
fallback_duration = float(info.duration) if info.duration and info.duration > 0 else 0.0
cuts, duration = await asyncio.to_thread(
_detect_cuts_sync, media_path, min_scene_len, fallback_duration
)
if duration <= 0:
raise ValueError(
f"Cannot determine the duration of {media_path}; shot detection needs a positive "
"duration (probe the file first and pass MediaInfo.duration)"
)
boundaries = _cut_boundaries(cuts, duration)
segments = list(itertools.pairwise(boundaries))
if min_scene_len > 0:
segments = _merge_short_segments(segments, min_scene_len)
segments = _apply_shot_budget(segments, max_shots)
logger.info("Detected %d shot(s) in %s (duration %.3fs)", len(segments), media_path, duration)
return [Shot(index=index, start=start, end=end) for index, (start, end) in enumerate(segments)]
# --------------------------------------------------------------------------- #
# keyframes
# --------------------------------------------------------------------------- #
def _jpeg_qscale(quality: int) -> int:
"""Map a 0-100 JPEG quality percentage onto ffmpeg's mjpeg qscale (2=best, 31=worst)."""
clamped = min(max(int(quality), 0), 100)
return max(2, min(31, round(31 - clamped * 29 / 100)))
def _shot_midpoint(shot: Shot) -> float:
"""Frame timestamp at the middle of a shot (clamped at zero)."""
duration = shot.end - shot.start
midpoint = shot.start + duration / 2.0 if duration > 0 else shot.start
return max(midpoint, 0.0)
async def extract_keyframes(
path: Path,
shots: list[Shot],
workdir: Path,
*,
width: int = 768,
quality: int = 85,
namespace: str | None = None,
) -> list[Shot]:
"""Extract one JPEG keyframe per shot from the shot midpoint.
Frames are scaled to ``width`` pixels wide (height keeps the aspect ratio, rounded
to an even number) and written to ``workdir/keyframes/shot-<index>.jpg``. When
``namespace`` is given, they go to ``workdir/keyframes/<namespace>/shot-<index>.jpg``
instead, so runs with different shot-detection options never overwrite each other.
Existing files are overwritten and ``shot.keyframe`` is filled in for every shot.
Raises:
ValueError: ``path`` is missing, ``width < 2`` or ``quality`` is outside 0-100.
RuntimeError: ffmpeg failed to produce a frame for a shot.
"""
media_path = _require_file(path)
if width < 2:
raise ValueError(f"width must be >= 2, got {width}")
if not 0 <= quality <= 100:
raise ValueError(f"quality must be within 0-100, got {quality}")
frames_dir = Path(workdir).expanduser() / KEYFRAME_DIR_NAME
if namespace:
if not re.fullmatch(r"[0-9a-f]{8,64}", namespace):
raise ValueError(f"namespace must be 8-64 lowercase hex characters, got {namespace!r}")
frames_dir = frames_dir / namespace[:12]
frames_dir.mkdir(parents=True, exist_ok=True)
qscale = _jpeg_qscale(quality)
for shot in shots:
midpoint = _shot_midpoint(shot)
out = frames_dir / f"shot-{shot.index}.jpg"
cmd = [
FFMPEG,
"-hide_banner",
"-loglevel",
"error",
"-nostdin",
"-y",
"-ss",
f"{midpoint:.3f}",
"-i",
str(media_path),
"-frames:v",
"1",
"-vf",
f"scale={int(width)}:-2",
"-q:v",
str(qscale),
str(out),
]
returncode, _stdout, stderr = await _run_tool(cmd, timeout=KEYFRAME_TIMEOUT_S)
if returncode != 0 or not out.is_file() or out.stat().st_size == 0:
raise RuntimeError(
f"ffmpeg could not extract a keyframe for shot {shot.index} at "
f"{midpoint:.3f}s (exit {returncode}): {_stderr_tail(stderr)}"
)
shot.keyframe = out
return shots
def dedup_keyframes(shots: list[Shot], *, threshold: int = 8) -> list[Shot]:
"""Drop keyframes that are near-identical to an earlier one (perceptual hash).
Each kept shot gets ``phash`` (16 hex chars) from ``imagehash.phash``; a shot whose
keyframe is within ``threshold`` Hamming distance of a previously kept keyframe is
discarded (later duplicates lose, the first shot wins). Shots without a readable
keyframe are kept unchanged with ``phash = None``. ``Shot.index`` is left untouched
so that keyframe file names keep matching their shot, which means indices of the
returned shots can have gaps where duplicates were dropped.
"""
if threshold < 0:
raise ValueError(f"threshold must be >= 0, got {threshold}")
import imagehash
from PIL import Image
kept: list[Shot] = []
hashes: list[imagehash.ImageHash] = []
for shot in shots:
keyframe = shot.keyframe
if keyframe is None or not Path(keyframe).is_file():
shot.phash = None
kept.append(shot)
continue
try:
with Image.open(keyframe) as image:
digest = imagehash.phash(image)
except (OSError, ValueError) as exc:
logger.warning("Could not hash keyframe %s (shot %d): %s", keyframe, shot.index, exc)
shot.phash = None
kept.append(shot)
continue
if any(int(digest - previous) <= threshold for previous in hashes):
logger.debug("Dropping duplicate keyframe %s of shot %d", keyframe, shot.index)
continue
shot.phash = str(digest)
hashes.append(digest)
kept.append(shot)
logger.info("Deduplicated keyframes: kept %d of %d shot(s)", len(kept), len(shots))
return kept
+332
View File
@@ -0,0 +1,332 @@
"""Pinned downloads of the sherpa-onnx speaker-diarization model assets.
The sherpa-onnx offline diarization pipeline needs exactly two ONNX files:
* a pyannote segmentation model, published by the sherpa-onnx project as the
``.tar.bz2`` release asset ``sherpa-onnx-pyannote-segmentation-3-0.tar.bz2``
(the archive contains ``sherpa-onnx-pyannote-segmentation-3-0/model.onnx``);
* a 3D-Speaker speaker-embedding extractor, published as a single ``.onnx`` file.
Both live in pinned GitHub release tags of https://github.com/k2-fsa/sherpa-onnx
(the embedding tag really is spelled ``speaker-recongition-models`` upstream) and
are *not* gated, so no HuggingFace account, token or terms acceptance is involved.
Downloads are streamed into ``<cache_dir>/models/<name>/`` through a hidden
``.part`` file and atomically renamed, so an interrupted run can never leave a
truncated model behind. Each file is checked against a pinned SHA-256 digest and
size; a corrupted or silently replaced upstream asset is a hard error.
Typical use::
from video_analyse.model_assets import ensure_diarization_models
models = await ensure_diarization_models(cache_dir=settings.cache_dir)
models.segmentation # Path to model.onnx
models.embedding # Path to the 3D-Speaker .onnx file
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
import shutil
import tarfile
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Final
import httpx
from pydantic import BaseModel
__all__ = [
"EMBEDDING_MODEL",
"MODELS",
"MODEL_ASSETS",
"MODEL_DIR_NAME",
"SEGMENTATION_MODEL",
"DiarizationModels",
"ModelAsset",
"ensure_diarization_models",
"ensure_model",
"model_path",
]
logger = logging.getLogger(__name__)
GITHUB_RELEASES: Final = "https://github.com/k2-fsa/sherpa-onnx/releases/download"
#: Release tag holding the pyannote segmentation archives.
SEGMENTATION_RELEASE: Final = "speaker-segmentation-models"
#: Release tag holding the speaker-embedding ONNX files ("recongition" is upstream's typo).
EMBEDDING_RELEASE: Final = "speaker-recongition-models"
#: Cache sub-directory (inside ``cache_dir``) that holds downloaded models.
MODEL_DIR_NAME: Final = "models"
#: Canonical name of the pyannote segmentation asset.
SEGMENTATION_MODEL: Final = "sherpa-onnx-pyannote-segmentation-3-0"
#: Canonical name of the 3D-Speaker ERes2Net embedding asset.
EMBEDDING_MODEL: Final = "3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k"
DOWNLOAD_TIMEOUT: Final = httpx.Timeout(connect=15.0, read=180.0, write=180.0, pool=15.0)
@dataclass(frozen=True, slots=True)
class ModelAsset:
"""One pinned model file and everything needed to fetch and verify it."""
name: str
"""Registry name; also the ``<cache_dir>/models/<name>/`` directory name."""
url: str
"""Pinned download URL."""
filename: str
"""File name of the model inside ``<cache_dir>/models/<name>/``."""
size_bytes: int
"""Expected size of the final (post-extraction) model file."""
sha256: str
"""Expected SHA-256 of the final (post-extraction) model file."""
archive_member: str | None = None
"""Path of the model inside the downloaded archive, or ``None`` for a bare file."""
description: str = ""
"""Human-readable purpose, used in log lines."""
MODEL_ASSETS: Final[dict[str, ModelAsset]] = {
SEGMENTATION_MODEL: ModelAsset(
name=SEGMENTATION_MODEL,
url=f"{GITHUB_RELEASES}/{SEGMENTATION_RELEASE}/{SEGMENTATION_MODEL}.tar.bz2",
filename="model.onnx",
size_bytes=5_992_913,
sha256="220ad67ca923bef2fa91f2390c786097bf305bceb5e261d4af67b38e938e1079",
archive_member=f"{SEGMENTATION_MODEL}/model.onnx",
description="pyannote speaker-segmentation 3.0 (speech/non-speech + local speaker turns)",
),
EMBEDDING_MODEL: ModelAsset(
name=EMBEDDING_MODEL,
url=f"{GITHUB_RELEASES}/{EMBEDDING_RELEASE}/{EMBEDDING_MODEL}.onnx",
filename=f"{EMBEDDING_MODEL}.onnx",
size_bytes=39_593_761,
sha256="1a331345f04805badbb495c775a6ddffcdd1a732567d5ec8b3d5749e3c7a5e4b",
description="3D-Speaker ERes2Net speaker embedding extractor (16 kHz, base)",
),
}
# Backwards/short alias for the registry, handy for introspection in the CLI.
MODELS: Final[dict[str, ModelAsset]] = MODEL_ASSETS
#: Asset names required by the sherpa-onnx diarization backend, in config order.
SHERPA_DIARIZATION_MODELS: Final[tuple[str, ...]] = (SEGMENTATION_MODEL, EMBEDDING_MODEL)
class DiarizationModels(BaseModel):
"""Paths to the two ONNX files the sherpa diarization backend needs."""
segmentation: Path
embedding: Path
def _asset(name: str) -> ModelAsset:
"""Resolve a registry name (accepting a trailing file suffix) to its asset."""
key = name.strip()
for suffix in (".onnx", ".tar.bz2", ".tar"):
if key.endswith(suffix):
key = key[: -len(suffix)]
break
asset = MODEL_ASSETS.get(key)
if asset is None:
available = ", ".join(sorted(MODEL_ASSETS))
raise ValueError(
f"Unknown model {name!r}. Available models: {available}. "
"See video_analyse.model_assets.MODEL_ASSETS for URLs and checksums."
)
return asset
def model_path(name: str, *, cache_dir: Path) -> Path:
"""Return the cache path of ``name`` without touching the network.
The file may not exist yet; use :func:`ensure_model` to download it.
"""
asset = _asset(name)
return Path(cache_dir).expanduser() / MODEL_DIR_NAME / asset.name / asset.filename
async def ensure_model(
name: str,
*,
cache_dir: Path,
client: httpx.AsyncClient | None = None,
) -> Path:
"""Return the local path of a pinned model asset, downloading it once.
Args:
name: A key of :data:`MODEL_ASSETS` (a trailing ``.onnx``/``.tar.bz2`` is
tolerated).
cache_dir: Root cache directory (``Settings.cache_dir``); assets land in
``cache_dir/models/<name>/``.
client: Optional injected ``httpx.AsyncClient`` (tests, custom proxies).
When omitted a short-lived client with redirect-following is created.
Returns:
Path to the verified model file.
Raises:
ValueError: Unknown asset name.
RuntimeError: HTTP failure, empty download, or checksum/size mismatch.
"""
asset = _asset(name)
target = model_path(asset.name, cache_dir=cache_dir)
if target.is_file():
size = target.stat().st_size
if size > 0:
digest = await asyncio.to_thread(_sha256_file, target)
if size == asset.size_bytes and digest == asset.sha256:
logger.debug("Using verified cached %s at %s", asset.name, target)
return target
logger.warning(
"Cached model %s at %s failed verification (got %d bytes with sha256 %s, "
"expected %d bytes with sha256 %s); deleting and re-downloading.",
asset.name,
target,
size,
digest,
asset.size_bytes,
asset.sha256,
)
target.unlink(missing_ok=True)
else:
logger.warning("Removing empty cached model file %s", target)
target.unlink(missing_ok=True)
target.parent.mkdir(parents=True, exist_ok=True)
own_client = client is None
http = (
client
if client is not None
else httpx.AsyncClient(follow_redirects=True, timeout=DOWNLOAD_TIMEOUT)
)
try:
await _download(asset, target, client=http)
finally:
if own_client:
await http.aclose()
return target
async def ensure_diarization_models(
*,
cache_dir: Path,
client: httpx.AsyncClient | None = None,
) -> DiarizationModels:
"""Return both sherpa-onnx diarization model paths, downloading if needed.
Downloads the pyannote segmentation model first and the speaker-embedding
extractor second (about 46 MB in total on a cold cache).
"""
segmentation = await ensure_model(SEGMENTATION_MODEL, cache_dir=cache_dir, client=client)
embedding = await ensure_model(EMBEDDING_MODEL, cache_dir=cache_dir, client=client)
return DiarizationModels(segmentation=segmentation, embedding=embedding)
async def _download(asset: ModelAsset, target: Path, *, client: httpx.AsyncClient) -> None:
"""Stream ``asset`` into ``target`` atomically, verifying size and digest."""
target.parent.mkdir(parents=True, exist_ok=True)
fd, part_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".part", dir=target.parent)
os.close(fd)
part = Path(part_name)
staged = part
try:
logger.info("Downloading %s (%s) from %s", asset.name, asset.description, asset.url)
received = 0
async with client.stream("GET", asset.url) as response:
if response.status_code != httpx.codes.OK:
raise RuntimeError(
f"Download of {asset.name} failed: HTTP {response.status_code} from "
f"{asset.url}. Check network/proxy access to GitHub and retry."
)
with part.open("wb") as handle:
async for chunk in response.aiter_bytes():
if chunk:
handle.write(chunk)
received += len(chunk)
if received == 0:
raise RuntimeError(
f"Download of {asset.name} from {asset.url} returned no data. "
"Check network/proxy access to GitHub and retry."
)
if asset.archive_member is not None:
staged = await asyncio.to_thread(
_extract_member, part, asset.archive_member, target.parent
)
size = staged.stat().st_size
if size == 0:
raise RuntimeError(
f"Downloaded model file for {asset.name} is empty ({staged}); "
"delete the cache entry and retry."
)
digest = await asyncio.to_thread(_sha256_file, staged)
if digest != asset.sha256 or size != asset.size_bytes:
raise RuntimeError(
f"Integrity check failed for {asset.name}: got {size} bytes with sha256 "
f"{digest}, expected {asset.size_bytes} bytes with sha256 {asset.sha256}. "
f"The download from {asset.url} is corrupt or was replaced upstream; "
f"delete {target} and retry."
)
await asyncio.to_thread(os.replace, staged, target)
staged = target # ownership transferred; keep the finally-block from deleting it
logger.info("Cached %s at %s (%.1f MiB)", asset.name, target, size / (1024 * 1024))
finally:
part.unlink(missing_ok=True)
if staged != target:
staged.unlink(missing_ok=True)
def _extract_member(archive: Path, member: str, dest_dir: Path) -> Path:
"""Extract one file from a tarball into a fresh temp file in ``dest_dir``.
Only the named member is ever read, so archive path traversal is impossible.
"""
fd, name = tempfile.mkstemp(prefix=".extract-", suffix=".onnx", dir=dest_dir)
os.close(fd)
dest = Path(name)
try:
with tarfile.open(archive, mode="r:bz2") as tar:
try:
info = tar.getmember(member)
except KeyError as exc:
raise RuntimeError(
f"Archive {archive.name} does not contain {member!r}; the upstream release "
"layout changed. Clear the cached download and retry."
) from exc
if not info.isfile():
raise RuntimeError(
f"Entry {member!r} in {archive.name} is not a regular file; "
"the upstream release layout changed."
)
extracted = tar.extractfile(info)
if extracted is None:
raise RuntimeError(f"Could not read {member!r} from {archive.name}.")
with extracted, dest.open("wb") as handle:
shutil.copyfileobj(extracted, handle)
except BaseException:
dest.unlink(missing_ok=True)
raise
return dest
def _sha256_file(path: Path) -> str:
"""Return the hex SHA-256 digest of ``path`` (streamed, 1 MiB chunks)."""
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
+152
View File
@@ -0,0 +1,152 @@
"""Core pydantic data models shared by every stage of the pipeline.
All models are pydantic v2 ``BaseModel`` subclasses so they serialize to JSON
(and back) without loss. ``Path`` fields serialize as strings and validate
back into ``pathlib.Path``.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Literal
from pydantic import BaseModel
__all__ = [
"Artifacts",
"Highlight",
"MediaInfo",
"ReportCore",
"Segment",
"Shot",
"ShotDescription",
"SpeakerTurn",
"Transcript",
"VideoReport",
"Word",
]
class MediaInfo(BaseModel):
"""Technical metadata about a media file (ffprobe + source metadata)."""
path: Path
source: str
duration: float
width: int | None = None
height: int | None = None
fps: float | None = None
has_audio: bool
size_bytes: int
format: str | None = None
video_codec: str | None = None
audio_codec: str | None = None
extra: dict[str, Any] = {}
class Word(BaseModel):
"""A single transcribed word with timings in seconds."""
text: str
start: float
end: float
probability: float | None = None
class SpeakerTurn(BaseModel):
"""A contiguous span attributed to one speaker ("S1", "S2", ...)."""
start: float
end: float
speaker: str
class Segment(BaseModel):
"""A transcript segment (sentence-ish) with optional word timings."""
start: float
end: float
text: str
words: list[Word] = []
speaker: str | None = None
class Transcript(BaseModel):
"""Full transcription result, optionally speaker-attributed."""
language: str | None = None
duration: float
segments: list[Segment]
speaker_turns: list[SpeakerTurn] = []
backend: str | None = None
model: str | None = None
class Shot(BaseModel):
"""One detected shot (scene), its keyframe and optional VLM description."""
index: int
start: float
end: float
keyframe: Path | None = None
phash: str | None = None
transcript_slice: str = ""
description: ShotDescription | None = None
class ShotDescription(BaseModel):
"""Structured VLM description of a single keyframe."""
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
Shot.model_rebuild()
class Highlight(BaseModel):
"""A notable moment in the video, in seconds."""
start: float
end: float
description: str
class ReportCore(BaseModel):
"""The part of the report the synthesis LLM produces (code adds the rest)."""
title: str | None = None
summary: str
topics: list[str] = []
people: list[str] = []
highlights: list[Highlight] = []
class VideoReport(BaseModel):
"""The complete, validated analysis report for one video."""
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] = {}
class Artifacts(BaseModel):
"""Everything the pipeline produced for one source."""
source: str
workdir: Path
media: MediaInfo | None = None
transcript: Transcript | None = None
shots: list[Shot] = []
report: VideoReport | None = None
+975
View File
@@ -0,0 +1,975 @@
"""Stage orchestration: ordering, caching and artifact assembly.
The pipeline runs up to seven stages per source, in this fixed order::
probe -> audio -> transcribe -> diarize -> shots -> describe -> report
Every stage reads/writes a content-addressed artifact through
:class:`video_analyse.cache.StageCache`, so a second run over unchanged inputs only
reads JSON files. ``force=True`` re-runs the stages the caller asked for and drops
their downstream cache entries, so stale report/description data never survives a
deliberate refresh.
Stage callables
---------------
The ``stages`` mapping accepted by :class:`Pipeline` lets callers (and tests) replace
any stage. Real implementations are imported lazily *inside* the fallback methods, so
``import video_analyse.pipeline`` never imports faster-whisper, onnxruntime,
sherpa-onnx or OpenCV. A stage callable has the same signature as the module function
it wraps:
================ ==============================================================
``ingest`` ``async (source, *, cache_dir: Path, quality: int) -> IngestResult``
``probe`` ``async (path: Path) -> MediaInfo``
``audio`` ``async (path: Path, workdir: Path) -> Path``
``transcribe`` ``async (wav: Path, *, settings: Settings) -> Transcript``
``diarize`` ``async (wav: Path, *, settings: Settings) -> list[SpeakerTurn]``
``shots`` ``async (path, info, *, workdir: Path, settings) -> list[Shot]``
``describe`` ``async (shots, transcript, *, settings) -> list[Shot]``
``report`` ``async (shots, transcript, info, *, settings) -> VideoReport``
================ ==============================================================
``want`` semantics
------------------
``want`` names the stages whose *results* the caller needs. Stages required to
produce them run as well (``transcribe`` needs ``audio``, which needs ``probe``;
``diarize`` needs a transcript; ``describe`` needs shots). When only ``describe`` or
``report`` is wanted, already cached transcript, speaker-turn, shot and description
artifacts are loaded as context without re-running the expensive upstream stages, so a
cached report is reproduced from the cache instead of being synthesised again.
``probe`` always runs (it is a single cheap ffprobe call) because it supplies the media
metadata every artifact and report is built from.
Diarization runs only when ``settings.diarize`` is true *and* ``"diarize"`` is in
``want``; the speaker-attributed transcript then replaces the plain one in the
returned :class:`~video_analyse.models.Artifacts`.
"""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Awaitable, Callable, Collection, Mapping
from pathlib import Path
from typing import Any, TypeVar
from urllib.parse import urlparse
from pydantic import BaseModel
from .cache import StageCache
from .config import Settings
from .models import (
Artifacts,
MediaInfo,
Shot,
SpeakerTurn,
Transcript,
VideoReport,
)
logger = logging.getLogger(__name__)
__all__ = [
"DEFAULT_INGEST_QUALITY",
"DEFAULT_MAX_SHOTS",
"DEFAULT_MIN_SCENE_LEN",
"DETECTOR_NAME",
"STAGES",
"STAGE_ORDER",
"Pipeline",
]
#: Stages in execution order; the report always closes the run.
STAGE_ORDER: tuple[str, ...] = (
"probe",
"audio",
"transcribe",
"diarize",
"shots",
"describe",
"report",
)
#: Every name accepted in ``want`` and in the injectable ``stages`` mapping.
STAGES: frozenset[str] = frozenset({"ingest", *STAGE_ORDER})
DEFAULT_MAX_SHOTS = 64
DEFAULT_MIN_SCENE_LEN = 0.6
DEFAULT_INGEST_QUALITY = 1080
#: Shot-detection and keyframe options that participate in the shots cache key.
DETECTOR_NAME = "adaptive"
KEYFRAME_WIDTH = 768
KEYFRAME_QUALITY = 85
DEDUP_THRESHOLD = 8
#: Cache entries to drop when a stage is re-run with ``force=True``.
_DOWNSTREAM: dict[str, tuple[str, ...]] = {
"probe": ("audio", "transcribe", "diarize", "shots", "describe", "report"),
"audio": ("transcribe", "diarize", "describe", "report"),
"transcribe": ("diarize", "describe", "report"),
"diarize": ("describe", "report"),
"shots": ("describe", "report"),
"describe": ("report",),
"report": (),
}
ModelT = TypeVar("ModelT", bound=BaseModel)
StageCallable = Callable[..., Awaitable[Any]]
ProgressCallback = Callable[[str], None]
def _ignore_progress(message: str) -> None:
"""Default progress callback: keep the message in the debug log."""
logger.debug("%s", message)
class _AudioArtifact(BaseModel):
"""Cached result of the audio stage: the WAV path inside the source cache dir."""
path: Path
class _ShotsArtifact(BaseModel):
"""Cached result of the shots stage (and of the describe stage)."""
shots: list[Shot] = []
class _TurnsArtifact(BaseModel):
"""Cached result of the diarize stage.
Only the speaker turns are cached: they depend on the audio file and the backend,
not on the transcript, so a later run with a different STT backend reuses them and
re-applies :func:`video_analyse.diarize.attribute_speakers` to the new transcript.
"""
turns: list[SpeakerTurn] = []
# --------------------------------------------------------------------------- #
# stage input parameters (the cache keys hash exactly these)
# --------------------------------------------------------------------------- #
def _probe_params(video_sha: str, source: str) -> dict[str, Any]:
"""Inputs of the probe stage: the content hash and the original source string.
``MediaInfo.path``/``source`` are run-time values, so including ``source`` keeps
byte-identical copies under different names from sharing a cached artifact that
points at the first path (MCP frame tools read ``media.path``).
"""
return {"video_sha256": video_sha, "source": source}
def _audio_params(video_sha: str) -> dict[str, Any]:
"""Inputs of the audio stage: the content hash of the video file."""
return {"video_sha256": video_sha}
def _transcribe_params(
audio_sha: str,
*,
backend: str,
model: str,
language: str | None,
api_base_url: str | None,
) -> dict[str, Any]:
"""Inputs of the transcribe stage: the audio content hash and the full STT spec.
``api_base_url`` participates so repointing ``VA_STT_API_BASE_URL`` at another
provider never reuses a transcript produced by the previous endpoint.
"""
return {
"audio_sha256": audio_sha,
"backend": backend,
"model": model,
"language": language,
"api_base_url": api_base_url,
}
def _diarize_params(audio_sha: str, *, backend: str) -> dict[str, Any]:
"""Inputs of the diarize stage: the audio content hash and the backend."""
return {"audio_sha256": audio_sha, "backend": backend}
def _shots_params(video_sha: str, *, max_shots: int, min_scene_len: float) -> dict[str, Any]:
"""Inputs of the shots stage: the video hash plus detector and keyframe options."""
return {
"video_sha256": video_sha,
"detector": DETECTOR_NAME,
"max_shots": max_shots,
"min_scene_len": min_scene_len,
"keyframe_width": KEYFRAME_WIDTH,
"keyframe_quality": KEYFRAME_QUALITY,
"dedup_threshold": DEDUP_THRESHOLD,
}
def _describe_params(
shots_key: str | None,
*,
vlm: str,
transcript_key: str | None,
diarize_key: str | None,
diarize_applied: bool,
llama_server_url: str,
) -> dict[str, Any]:
"""Inputs of the describe stage: shots, transcript/speaker context and the VLM.
The per-shot prompt embeds the speaker-labelled transcript slice, so changing the
STT backend/language or ``--no-diarize`` must produce a new describe key. The
endpoint participates too: the same bare model name can be served by different
llama-server instances.
"""
return {
"shots_key": shots_key,
"vlm": vlm,
"transcript_key": transcript_key,
"diarize": {"key": diarize_key, "applied": diarize_applied},
"llama_server_url": llama_server_url,
}
def _report_params(
*,
source: str,
probe_key: str,
audio_key: str | None,
transcribe_key: str | None,
diarize_key: str | None,
diarize_applied: bool,
shots_key: str | None,
describe_key: str | None,
describe_applied: bool,
synthesis: str,
llama_server_url: str,
) -> dict[str, Any]:
"""Inputs of the report stage: every upstream key plus the synthesis spec.
``applied`` flags record whether speaker labels and shot descriptions are part of
the material, so a run without (or with) diarization/description never hits the
other variant's cached report. ``source`` keeps two aliases of the same bytes from
sharing a report whose ``source``/``metadata['path']`` point at the other file.
"""
return {
"source": source,
"probe": probe_key,
"audio": audio_key,
"transcribe": transcribe_key,
"diarize": {"key": diarize_key, "applied": diarize_applied},
"shots": shots_key,
"describe": {"key": describe_key, "applied": describe_applied},
"synthesis": synthesis,
"llama_server_url": llama_server_url,
}
class Pipeline:
"""Run the analysis stages for one source, reusing cached artifacts.
Args:
settings: runtime settings (cache dir, STT/diarize/vision/synthesis specs).
stages: optional mapping of stage name -> callable overriding the real
implementation for that stage (see the module docstring for signatures).
max_shots: upper bound on shots after merging; part of the shots cache key.
min_scene_len: shortest allowed shot in seconds (shorter ones are merged).
ingest_quality: maximum download height in pixels for URL sources.
Raises:
ValueError: an argument is out of range or ``stages`` names an unknown stage.
"""
def __init__(
self,
settings: Settings,
stages: Mapping[str, StageCallable] | None = None,
*,
max_shots: int = DEFAULT_MAX_SHOTS,
min_scene_len: float = DEFAULT_MIN_SCENE_LEN,
ingest_quality: int = DEFAULT_INGEST_QUALITY,
) -> None:
if isinstance(max_shots, bool) or not isinstance(max_shots, int) or max_shots < 1:
raise ValueError(f"max_shots must be an integer >= 1, got {max_shots!r}")
if min_scene_len < 0:
raise ValueError(f"min_scene_len must be >= 0, got {min_scene_len}")
if (
isinstance(ingest_quality, bool)
or not isinstance(ingest_quality, int)
or ingest_quality < 1
):
raise ValueError(f"ingest_quality must be an integer >= 1, got {ingest_quality!r}")
injected = dict(stages or {})
unknown = sorted(set(injected) - STAGES)
if unknown:
supported = ", ".join(sorted(STAGES))
raise ValueError(
f"unknown stage(s) {', '.join(unknown)}; supported stages: {supported}"
)
self.settings = settings
self.max_shots = max_shots
self.min_scene_len = min_scene_len
self.ingest_quality = ingest_quality
self._injected = injected
self._real: dict[str, StageCallable] = {
"ingest": self._real_ingest,
"probe": self._real_probe,
"audio": self._real_audio,
"transcribe": self._real_transcribe,
"diarize": self._real_diarize,
"shots": self._real_shots,
"describe": self._real_describe,
"report": self._real_report,
}
# ------------------------------------------------------------------ #
# public API
# ------------------------------------------------------------------ #
async def run(
self,
source: str,
*,
want: Collection[str] | None = None,
force: bool = False,
progress: ProgressCallback | None = None,
) -> Artifacts:
"""Run the pipeline for ``source`` and return the assembled artifacts.
Args:
source: local media path or ``http(s)`` URL.
want: stages whose results are needed; defaults to every stage in
:data:`STAGE_ORDER`. Prerequisites run as needed, so a bare
``{"transcribe"}`` still probes and extracts audio.
force: re-run the *wanted* stages even when their cache entry exists and
drop the cache entries of every downstream stage.
progress: called with a short ``"<stage>: <status>"`` message before each
stage runs, hits the cache or is skipped.
Returns:
The assembled :class:`~video_analyse.models.Artifacts`; also written to
``<workdir>/artifacts.json``.
Raises:
ValueError: empty/unsupported source, unknown stage name, or a stage
rejecting its input.
RuntimeError: a stage failed (download, ffmpeg, model server, ...).
"""
if not isinstance(source, str):
raise TypeError(f"source must be a string, got {type(source).__name__}")
original = source.strip()
if not original:
raise ValueError("source must not be empty")
wanted = self._normalise_want(want)
notify = progress if progress is not None else _ignore_progress
cache = StageCache(self.settings.cache_dir)
# --- ingest (URL sources only) ---------------------------------
local_path, ingested = await self._resolve_source(original, cache=cache, notify=notify)
video_sha = await asyncio.to_thread(cache.source_hash, local_path)
workdir = cache.source_dir(video_sha)
logger.info("pipeline source=%s sha256=%s workdir=%s", original, video_sha[:16], workdir)
# --- probe ------------------------------------------------------
probe_key = cache.stage_key("probe", _probe_params(video_sha, original))
probed, _ = await self._execute_stage(
"probe",
cache=cache,
source_sha=video_sha,
key=probe_key,
model_type=MediaInfo,
runner=lambda: self._stage("probe")(local_path),
notify=notify,
forced=self._forced("probe", wanted, force),
)
# ``path``/``source`` are run-time values, not content: always re-inject the
# current ones, and fold in yt-dlp's title/metadata for URL sources (PLAN §4).
media = self._rebase_media(probed, original, local_path, ingested)
# --- audio ------------------------------------------------------
wav = cache.audio_path(video_sha)
audio_key = cache.stage_key("audio", _audio_params(video_sha))
audio_wanted = bool(wanted & {"audio", "transcribe", "diarize"})
audio_ready = False
if not media.has_audio:
notify("audio: skipped (source has no audio)")
elif audio_wanted:
audio, _ = await self._execute_stage(
"audio",
cache=cache,
source_sha=video_sha,
key=audio_key,
model_type=_AudioArtifact,
runner=lambda: self._run_audio(local_path, workdir),
notify=notify,
forced=self._forced("audio", wanted, force),
validate=lambda item: item.path.is_file(),
)
wav = audio.path
audio_ready = True
else:
notify("audio: skipped (not requested)")
audio_ready = wav.is_file()
# --- transcribe -------------------------------------------------
transcribe_wanted = "transcribe" in wanted or "diarize" in wanted
context_wanted = bool(wanted & {"describe", "report"})
audio_sha: str | None = None
transcribe_key: str | None = None
transcript: Transcript | None = None
if not audio_ready:
reason = "no audio" if not media.has_audio else "not requested"
notify(f"transcribe: skipped ({reason})")
else:
audio_sha = await asyncio.to_thread(cache.source_hash, wav)
transcribe_key = cache.stage_key(
"transcribe",
_transcribe_params(
audio_sha,
backend=self.settings.resolved_stt(),
model=self._stt_model_id(),
language=self.settings.language,
api_base_url=self.settings.stt_api_base_url,
),
)
if transcribe_wanted:
transcript, _ = await self._execute_stage(
"transcribe",
cache=cache,
source_sha=video_sha,
key=transcribe_key,
model_type=Transcript,
runner=lambda: self._run_transcribe(wav),
notify=notify,
forced=self._forced("transcribe", wanted, force),
)
elif context_wanted:
cached_transcript = self._load_cached(
cache, video_sha, "transcribe", transcribe_key, Transcript
)
if cached_transcript is not None:
transcript = cached_transcript
notify("transcribe: cached (context)")
else:
notify("transcribe: skipped (not requested)")
else:
notify("transcribe: skipped (not requested)")
# --- diarize (speaker turns applied to the transcript) ----------
diarize_key: str | None = None
if audio_sha is not None:
diarize_key = cache.stage_key(
"diarize",
_diarize_params(audio_sha, backend=self.settings.diarize_backend),
)
diarize_applied = False
if "diarize" in wanted:
if not self.settings.diarize:
notify("diarize: skipped (disabled in settings)")
elif transcript is None or audio_sha is None or not wav.is_file():
notify("diarize: skipped (no transcript)")
else:
turns_artifact, _ = await self._execute_stage(
"diarize",
cache=cache,
source_sha=video_sha,
key=diarize_key,
model_type=_TurnsArtifact,
runner=lambda: self._run_diarize(wav),
notify=notify,
forced=self._forced("diarize", wanted, force),
)
transcript = self._apply_speakers(transcript, turns_artifact.turns)
diarize_applied = bool(turns_artifact.turns)
else:
# A report/description run can reuse already cached turns for free; the
# diarization backend itself only ever runs when explicitly requested.
cached_turns = None
reuse_turns = (
self.settings.diarize
and transcript is not None
and diarize_key is not None
and bool(wanted & {"describe", "report"})
)
if reuse_turns:
cached_turns = self._load_cached(
cache, video_sha, "diarize", diarize_key, _TurnsArtifact
)
if cached_turns is not None and cached_turns.turns:
transcript = self._apply_speakers(transcript, cached_turns.turns)
diarize_applied = True
notify("diarize: cached (context)")
else:
notify("diarize: skipped (not requested)")
# --- shots ------------------------------------------------------
has_video = media.width is not None or media.height is not None
shots_key: str | None = None
if has_video:
shots_key = cache.stage_key(
"shots",
_shots_params(
video_sha, max_shots=self.max_shots, min_scene_len=self.min_scene_len
),
)
shots_wanted = "shots" in wanted or "describe" in wanted
shots: list[Shot] = []
if not has_video:
notify("shots: skipped (source has no video)")
elif shots_wanted:
shots_artifact, _ = await self._execute_stage(
"shots",
cache=cache,
source_sha=video_sha,
key=shots_key,
model_type=_ShotsArtifact,
runner=lambda: self._run_shots(local_path, media, workdir, shots_key),
notify=notify,
forced=self._forced("shots", wanted, force),
validate=self._shots_usable,
)
shots = shots_artifact.shots
elif "report" in wanted:
cached_shots = self._load_cached(cache, video_sha, "shots", shots_key, _ShotsArtifact)
if cached_shots is not None and self._shots_usable(cached_shots):
shots = cached_shots.shots
notify("shots: cached (context)")
else:
notify("shots: skipped (not requested)")
else:
notify("shots: skipped (not requested)")
# --- describe ---------------------------------------------------
describe_key = cache.stage_key(
"describe",
_describe_params(
shots_key,
vlm=self.settings.resolved_vlm(),
transcript_key=transcribe_key,
diarize_key=diarize_key,
diarize_applied=diarize_applied,
llama_server_url=self.settings.llama_server_url,
),
)
describe_applied = False
if "describe" in wanted:
if not shots:
notify("describe: skipped (no shots)")
else:
described, _ = await self._execute_stage(
"describe",
cache=cache,
source_sha=video_sha,
key=describe_key,
model_type=_ShotsArtifact,
runner=lambda: self._run_describe(shots, transcript),
notify=notify,
forced=self._forced("describe", wanted, force),
validate=self._shots_usable,
)
shots = described.shots
describe_applied = any(shot.description is not None for shot in shots)
else:
# Reuse cached descriptions as report material without re-running the VLM.
described = None
if shots and "report" in wanted:
described = self._load_cached(
cache, video_sha, "describe", describe_key, _ShotsArtifact
)
if described is not None and not self._shots_usable(described):
logger.warning("cached descriptions point at missing keyframes; ignoring them")
described = None
if described is None:
notify("describe: skipped (not requested)")
else:
shots = described.shots
describe_applied = any(shot.description is not None for shot in shots)
notify("describe: cached (context)")
# PLAN §4: every shot carries the words spoken during it. Fill it here (the
# first point where shots and the speaker-attributed transcript coexist) and
# again inside describe_shots for callers of the vision stage directly.
self._populate_transcript_slices(shots, transcript)
# --- report -----------------------------------------------------
report_key = cache.stage_key(
"report",
_report_params(
source=original,
probe_key=probe_key,
audio_key=audio_key,
transcribe_key=transcribe_key,
diarize_key=diarize_key,
diarize_applied=diarize_applied,
shots_key=shots_key,
describe_key=describe_key,
describe_applied=describe_applied,
synthesis=self.settings.resolved_synthesis(),
llama_server_url=self.settings.llama_server_url,
),
)
report: VideoReport | None = None
if "report" not in wanted:
notify("report: skipped (not requested)")
elif transcript is None and not shots:
notify("report: skipped (no transcript or shots)")
else:
report, _ = await self._execute_stage(
"report",
cache=cache,
source_sha=video_sha,
key=report_key,
model_type=VideoReport,
runner=lambda: self._run_report(shots, transcript, media),
notify=notify,
forced=self._forced("report", wanted, force),
)
report = self._rebase_report(report, original, local_path)
artifacts = Artifacts(
source=original,
workdir=workdir,
media=media,
transcript=transcript,
shots=shots,
report=report,
)
self._persist_artifacts(cache, video_sha, artifacts)
return artifacts
# ------------------------------------------------------------------ #
# orchestration helpers
# ------------------------------------------------------------------ #
@staticmethod
def _normalise_want(want: Collection[str] | None) -> frozenset[str]:
"""Validate ``want`` and return it as a frozenset of stage names."""
if want is None:
return frozenset(STAGE_ORDER)
if isinstance(want, str):
raise TypeError("want must be a collection of stage names, not a single string")
wanted = frozenset(want)
unknown = sorted(wanted - STAGES)
if unknown:
supported = ", ".join(sorted(STAGES))
raise ValueError(
f"unknown pipeline stage(s) {', '.join(unknown)}; supported stages: {supported}"
)
return wanted
@staticmethod
def _forced(stage: str, wanted: frozenset[str], force: bool) -> bool:
"""True when ``force`` applies to ``stage`` (only requested stages are forced)."""
return force and stage in wanted
def _stage(self, name: str) -> StageCallable:
"""Return the injected callable for ``name``, else the real implementation."""
return self._injected.get(name) or self._real[name]
@staticmethod
def _shots_usable(artifact: _ShotsArtifact) -> bool:
"""True when every cached keyframe path still points at a readable file."""
return all(
shot.keyframe is None or Path(shot.keyframe).is_file() for shot in artifact.shots
)
@staticmethod
def _populate_transcript_slices(shots: list[Shot], transcript: Transcript | None) -> None:
"""Fill ``Shot.transcript_slice`` with the words spoken during each shot."""
if transcript is None:
return
from .vision import transcript_slice_for
for shot in shots:
shot.transcript_slice = transcript_slice_for(shot, transcript)
@staticmethod
def _rebase_media(
probed: MediaInfo, original: str, local_path: Path, ingested: Any | None
) -> MediaInfo:
"""Re-inject run-time path/source and merge yt-dlp metadata into ``extra``."""
extra = dict(probed.extra)
if ingested is not None:
info = getattr(ingested, "info", None)
if isinstance(info, dict) and info:
extra["yt_dlp"] = dict(info)
title = getattr(ingested, "title", None)
if isinstance(title, str) and title.strip():
extra["title"] = title.strip()
ffprobe = extra.get("ffprobe")
if isinstance(ffprobe, dict):
ffprobe = dict(ffprobe)
format_info = ffprobe.get("format")
if isinstance(format_info, dict):
format_info = dict(format_info)
format_info["filename"] = str(local_path)
ffprobe["format"] = format_info
extra["ffprobe"] = ffprobe
return probed.model_copy(update={"source": original, "path": local_path, "extra": extra})
@staticmethod
def _rebase_report(report: VideoReport, original: str, local_path: Path) -> VideoReport:
"""Keep a cached report's source/path fields in sync with the current run."""
metadata = dict(report.metadata)
metadata["path"] = str(local_path)
extra = metadata.get("extra")
if isinstance(extra, dict):
extra = dict(extra)
ffprobe = extra.get("ffprobe")
if isinstance(ffprobe, dict):
ffprobe = dict(ffprobe)
format_info = ffprobe.get("format")
if isinstance(format_info, dict):
format_info = dict(format_info)
format_info["filename"] = str(local_path)
ffprobe["format"] = format_info
extra["ffprobe"] = ffprobe
metadata["extra"] = extra
return report.model_copy(update={"source": original, "metadata": metadata})
async def _resolve_source(
self, source: str, *, cache: StageCache, notify: ProgressCallback
) -> tuple[Path, Any | None]:
"""Return the local media file for ``source`` plus its ingest result (URLs only)."""
scheme = urlparse(source).scheme.lower()
if scheme in {"http", "https"}:
notify(f"ingest: fetching {source}")
ingested = await self._stage("ingest")(
source, cache_dir=cache.cache_dir, quality=self.ingest_quality
)
local_path = Path(ingested.path).expanduser()
if not local_path.is_file():
raise RuntimeError(
f"ingest stage reported {local_path} for {source} but no such file exists"
)
notify(f"ingest: ready ({local_path.name})")
return local_path, ingested
if scheme:
raise ValueError(
f"unsupported URL scheme {scheme + ':'!r} in {source!r}; pass a local file "
"path or an http(s) URL"
)
notify("ingest: local file")
local_path = Path(source).expanduser()
if not local_path.exists():
raise ValueError(f"Local media file not found: {local_path}")
if not local_path.is_file():
raise ValueError(f"Local path is not a regular file: {local_path}")
return local_path.resolve(), None
async def _execute_stage(
self,
stage: str,
*,
cache: StageCache,
source_sha: str,
key: str | None,
model_type: type[ModelT],
runner: Callable[[], Awaitable[ModelT]],
notify: ProgressCallback,
forced: bool,
validate: Callable[[ModelT], bool] | None = None,
) -> tuple[ModelT, bool]:
"""Load a stage artifact from the cache, or run the stage and store it.
Returns:
``(value, executed)`` where ``executed`` is ``False`` for a cache hit.
"""
if key is None:
raise ValueError(f"stage {stage!r} has no cache key; its inputs are unavailable")
path = cache.stage_path(source_sha, stage, key)
if not forced:
cached = self._load_cached(cache, source_sha, stage, key, model_type)
if cached is not None and (validate is None or validate(cached)):
notify(f"{stage}: cached")
return cached, False
notify(f"{stage}: running")
value = await runner()
try:
cache.save_model(path, value)
except OSError as exc: # a read-only cache must not break an analysis
logger.warning("could not write cache artifact %s: %s", path, exc)
if forced:
self._invalidate_downstream(cache, source_sha, stage)
return value, True
@staticmethod
def _load_cached(
cache: StageCache,
source_sha: str,
stage: str,
key: str | None,
model_type: type[ModelT],
) -> ModelT | None:
"""Load one cached artifact, treating unreadable/corrupt entries as a miss."""
if key is None:
return None
path = cache.stage_path(source_sha, stage, key)
try:
return cache.load_model(path, model_type)
except ValueError as exc:
logger.warning("ignoring unusable cache artifact %s: %s", path, exc)
return None
@staticmethod
def _invalidate_downstream(cache: StageCache, source_sha: str, stage: str) -> None:
"""Drop every cached artifact of the stages that consume ``stage``'s output."""
for name in _DOWNSTREAM.get(stage, ()):
removed = cache.clear_stage(source_sha, name)
if removed:
logger.info(
"forced %s re-run: dropped %d cached %s artifact(s)", stage, removed, name
)
def _persist_artifacts(self, cache: StageCache, source_sha: str, artifacts: Artifacts) -> None:
"""Mirror the returned artifacts to ``<workdir>/artifacts.json`` (best effort)."""
path = cache.artifacts_path(source_sha)
try:
cache.save_model(path, artifacts)
except OSError as exc:
logger.warning("could not write %s: %s", path, exc)
def _stt_model_id(self) -> str:
"""Model identifier that participates in the transcribe cache key."""
backend = self.settings.resolved_stt()
if backend == "whisper":
return self.settings.whisper_model
if backend == "openai-transcriptions":
return self.settings.stt_api_model
from .transcribe.parakeet_onnx import select_model_name
return select_model_name(self.settings.language)
@staticmethod
def _apply_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript:
"""Attribute ``transcript`` words/segments to ``turns`` (pure, cheap)."""
from .diarize import attribute_speakers
return attribute_speakers(transcript, turns)
# ------------------------------------------------------------------ #
# stage runners (wrap an injected or real callable into a cache artifact)
# ------------------------------------------------------------------ #
async def _run_audio(self, path: Path, workdir: Path) -> _AudioArtifact:
"""Run the audio stage and wrap the returned WAV path in a cache artifact."""
wav = await self._stage("audio")(path, workdir)
return _AudioArtifact(path=Path(wav))
async def _run_transcribe(self, wav: Path) -> Transcript:
"""Run the transcribe stage for ``wav``."""
return await self._stage("transcribe")(wav, settings=self.settings)
async def _run_diarize(self, wav: Path) -> _TurnsArtifact:
"""Run the diarize stage and wrap the speaker turns in a cache artifact."""
turns = await self._stage("diarize")(wav, settings=self.settings)
return _TurnsArtifact(turns=list(turns))
async def _run_shots(
self, path: Path, info: MediaInfo, workdir: Path, shots_key: str | None
) -> _ShotsArtifact:
"""Run the shots stage and wrap the shot list in a cache artifact.
Real keyframes are namespaced by the shots cache key so runs with different
``--max-shots``/dedup options can never overwrite each other's JPEGs.
"""
if "shots" in self._injected:
shots = await self._stage("shots")(path, info, workdir=workdir, settings=self.settings)
else:
shots = await self._real_shots(
path, info, workdir=workdir, settings=self.settings, namespace=shots_key
)
return _ShotsArtifact(shots=list(shots))
async def _run_describe(
self, shots: list[Shot], transcript: Transcript | None
) -> _ShotsArtifact:
"""Run the describe stage and wrap the described shots in a cache artifact."""
described = await self._stage("describe")(shots, transcript, settings=self.settings)
return _ShotsArtifact(shots=list(described))
async def _run_report(
self, shots: list[Shot], transcript: Transcript | None, info: MediaInfo
) -> VideoReport:
"""Run the report stage for the available material."""
return await self._stage("report")(shots, transcript, info, settings=self.settings)
# ------------------------------------------------------------------ #
# real stage implementations (heavy imports stay inside the methods)
# ------------------------------------------------------------------ #
async def _real_ingest(self, source: str, *, cache_dir: Path, quality: int) -> Any:
"""Download ``source`` with yt-dlp (``video_analyse.ingest.fetch``)."""
from .ingest import fetch
return await fetch(source, cache_dir=cache_dir, quality=quality)
async def _real_probe(self, path: Path) -> MediaInfo:
"""Probe the media file with ffprobe (``video_analyse.media.probe``)."""
from .media import probe
return await probe(path)
async def _real_audio(self, path: Path, workdir: Path) -> Path:
"""Extract 16 kHz mono audio (``video_analyse.media.extract_audio``)."""
from .media import extract_audio
return await extract_audio(path, workdir)
async def _real_transcribe(self, wav: Path, *, settings: Settings) -> Transcript:
"""Transcribe audio with the configured STT backend."""
from .transcribe import get_transcriber
return await get_transcriber(settings).transcribe(wav, language=settings.language)
async def _real_diarize(self, wav: Path, *, settings: Settings) -> list[SpeakerTurn]:
"""Diarize audio with the configured backend (``video_analyse.diarize``)."""
from .diarize import diarize_audio
return await diarize_audio(wav, settings=settings)
async def _real_shots(
self,
path: Path,
info: MediaInfo,
*,
workdir: Path,
settings: Settings,
namespace: str | None = None,
) -> list[Shot]:
"""Detect shots, extract one keyframe per shot and drop duplicate frames."""
from .media import dedup_keyframes, detect_shots, extract_keyframes
detected = await detect_shots(
path, info, max_shots=self.max_shots, min_scene_len=self.min_scene_len
)
framed = await extract_keyframes(
path,
detected,
workdir,
width=KEYFRAME_WIDTH,
quality=KEYFRAME_QUALITY,
namespace=namespace,
)
return await asyncio.to_thread(dedup_keyframes, framed, threshold=DEDUP_THRESHOLD)
async def _real_describe(
self,
shots: list[Shot],
transcript: Transcript | None,
*,
settings: Settings,
) -> list[Shot]:
"""Describe every shot keyframe with the configured VLM."""
from .vision import describe_shots
return await describe_shots(shots, transcript, settings=settings)
async def _real_report(
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
settings: Settings,
) -> VideoReport:
"""Synthesise the validated report with the configured model."""
from .synthesis import synthesise_report
return await synthesise_report(shots, transcript, info, settings=settings)
+160
View File
@@ -0,0 +1,160 @@
"""Deterministic Markdown rendering of a :class:`~video_analyse.models.VideoReport`.
Rendering uses only the standard library plus ``video_analyse.models``: no model
runtime is imported, and the same report always renders to the same bytes.
Timestamps are rendered as ``MM:SS``; for videos longer than an hour the minutes
field keeps counting (``61:05``) instead of switching to ``HH:MM:SS``.
"""
from __future__ import annotations
import math
from pathlib import Path
from .models import Highlight, Shot, ShotDescription, Transcript, VideoReport
__all__ = ["format_timestamp", "render_markdown"]
#: Directory name the pipeline places keyframe JPEGs under (may nest a shots-key dir).
KEYFRAMES_DIR_NAME = "keyframes"
def format_timestamp(seconds: float) -> str:
"""Format ``seconds`` as ``MM:SS``.
Negative and non-finite values clamp to ``00:00`` so the output stays
deterministic for degenerate reports.
"""
value = 0.0 if not math.isfinite(seconds) else max(seconds, 0.0)
minutes, secs = divmod(int(value), 60)
return f"{minutes:02d}:{secs:02d}"
def _format_range(start: float, end: float) -> str:
"""Format a ``[MM:SS-MM:SS]`` span, ordering the bounds defensively."""
first, last = (start, end) if end >= start else (end, start)
return f"[{format_timestamp(first)}-{format_timestamp(last)}]"
def _one_line(text: str) -> str:
"""Collapse all whitespace runs in ``text`` to single spaces."""
return " ".join(text.split())
def _join_items(items: list[str]) -> str:
"""Comma-join ``items`` or say that nothing was identified."""
return ", ".join(item for item in items if item) if any(items) else "none identified"
def _keyframe_reference(shot: Shot, keyframes_relpath: Path | None) -> str | None:
"""Relative reference to the shot's keyframe JPEG, or ``None`` when absent."""
if shot.keyframe is None:
return None
parts = Path(shot.keyframe).parts
if KEYFRAMES_DIR_NAME in parts:
index = len(parts) - 1 - parts[::-1].index(KEYFRAMES_DIR_NAME)
relative = Path(*parts[index + 1 :])
else:
relative = Path(shot.keyframe.name)
if keyframes_relpath is None:
return relative.as_posix()
return (keyframes_relpath / relative).as_posix()
def _render_highlight(highlight: Highlight) -> str:
span = _format_range(highlight.start, highlight.end)
return f"- **{span}** {_one_line(highlight.description)}"
def _render_description(description: ShotDescription) -> list[str]:
"""Render the factual fields of a :class:`ShotDescription` as Markdown lines."""
lines = [
f"- **Type:** {description.shot_type}",
f"- **Summary:** {_one_line(description.summary)}",
]
if description.on_screen_text:
lines.append(f"- **On-screen text:** {_one_line(description.on_screen_text)}")
if description.people:
lines.append(f"- **People:** {_join_items(description.people)}")
if description.notable_objects:
lines.append(f"- **Objects:** {_join_items(description.notable_objects)}")
if description.setting:
lines.append(f"- **Setting:** {_one_line(description.setting)}")
return lines
def _render_shot(shot: Shot, keyframes_relpath: Path | None) -> list[str]:
"""Render one shot section (heading, keyframe, description, transcript slice)."""
lines = [f"### Shot {shot.index} — {_format_range(shot.start, shot.end)}", ""]
reference = _keyframe_reference(shot, keyframes_relpath)
if reference is not None:
lines += [f"![Shot {shot.index} keyframe]({reference})", ""]
if shot.description is None:
lines.append("- **Description:** no visual description available")
else:
lines += _render_description(shot.description)
if shot.transcript_slice:
lines.append(f"- **Transcript:** {_one_line(shot.transcript_slice)}")
lines.append("")
return lines
def _render_transcript(transcript: Transcript | None) -> list[str]:
"""Render the speaker-labelled transcript appendix."""
if transcript is None or not transcript.segments:
return ["No transcript available.", ""]
lines: list[str] = []
for segment in transcript.segments:
text = _one_line(segment.text)
stamp = format_timestamp(segment.start)
if segment.speaker:
lines.append(f"**[{stamp}] {segment.speaker}:** {text}")
else:
lines.append(f"**[{stamp}]** {text}")
lines.append("")
return lines
def render_markdown(report: VideoReport, *, keyframes_relpath: Path | None = None) -> str:
"""Render ``report`` as a self-contained Markdown document.
Sections, in order: title, media facts, summary, topics/people, highlights,
a shot-by-shot breakdown and the full transcript appendix.
Args:
report: validated report to render.
keyframes_relpath: directory, relative to the Markdown file, holding the
keyframe JPEGs. When given, images reference
``<keyframes_relpath>/<filename>``; when ``None`` the bare keyframe
filename is used so no absolute path leaks into the document.
Returns:
The Markdown document, ending with exactly one newline.
"""
title = report.title or Path(report.source).name or "Video report"
lines: list[str] = [f"# {title}", "", f"- **Source:** `{report.source}`"]
lines.append(f"- **Duration:** {format_timestamp(report.duration)}")
if report.transcript is not None and report.transcript.language:
lines.append(f"- **Language:** {report.transcript.language}")
if report.transcript is not None and report.transcript.backend:
backend = report.transcript.backend
if report.transcript.model:
backend = f"{backend} ({report.transcript.model})"
lines.append(f"- **Transcript:** {backend}")
lines += ["", "## Summary", "", _one_line(report.summary) or "No summary available.", ""]
lines.append(f"- **Topics:** {_join_items(report.topics)}")
lines.append(f"- **People:** {_join_items(report.people)}")
lines += ["", "## Highlights", ""]
if report.highlights:
lines += [_render_highlight(highlight) for highlight in report.highlights]
else:
lines.append("No highlights were identified.")
lines += ["", "## Shot-by-shot", ""]
if report.shots:
for shot in report.shots:
lines += _render_shot(shot, keyframes_relpath)
else:
lines += ["No shots were detected.", ""]
lines += ["## Transcript", ""]
lines += _render_transcript(report.transcript)
return "\n".join(lines).rstrip("\n") + "\n"
+65
View File
@@ -0,0 +1,65 @@
"""SubRip (SRT) subtitle rendering for a :class:`~video_analyse.models.Transcript`."""
from __future__ import annotations
import math
from .models import Segment, Transcript
__all__ = ["format_timestamp", "render_srt"]
_MIN_CUE_DURATION = 0.001
def format_timestamp(seconds: float) -> str:
"""Format ``seconds`` as an SRT timestamp (``HH:MM:SS,mmm``).
Negative, NaN and infinite values are clamped to ``00:00:00,000`` so a broken
transcript can never produce an unparsable cue header.
"""
value = float(seconds)
if not math.isfinite(value):
value = 0.0
value = max(0.0, value)
total_ms = round(value * 1000.0)
hours, remainder = divmod(total_ms, 3_600_000)
minutes, remainder = divmod(remainder, 60_000)
secs, millis = divmod(remainder, 1_000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
def _cue_text(segment: Segment, *, speaker_labels: bool) -> str:
"""Return the (single line) cue text, optionally prefixed with the speaker label."""
text = " ".join(segment.text.split())
if not text:
text = " ".join(word.text.strip() for word in segment.words if word.text.strip())
if not text:
return ""
if speaker_labels and segment.speaker:
return f"[{segment.speaker}] {text}"
return text
def render_srt(transcript: Transcript, *, speaker_labels: bool = False) -> str:
"""Render ``transcript`` as a valid SRT document.
Cues are numbered sequentially from 1, carry ``HH:MM:SS,mmm`` boundaries and are
separated by a blank line. Segments without any text (neither ``segment.text`` nor
word texts) are skipped; zero-length segments get a 1 ms duration so players accept
them. With ``speaker_labels=True`` every segment that has a ``speaker`` gets a
``[S1]`` style prefix.
"""
cues: list[str] = []
for segment in transcript.segments:
text = _cue_text(segment, speaker_labels=speaker_labels)
if not text:
continue
start = max(0.0, float(segment.start))
end = max(start, float(segment.end))
if end <= start:
end = start + _MIN_CUE_DURATION
index = len(cues) + 1
cues.append(f"{index}\n{format_timestamp(start)} --> {format_timestamp(end)}\n{text}")
if not cues:
return ""
return "\n\n".join(cues) + "\n"
+898
View File
@@ -0,0 +1,898 @@
"""Report synthesis and grounded question answering over a :class:`VideoReport`.
The synthesis agent authors only a :class:`~video_analyse.models.ReportCore`
(title, summary, topics, people, highlights); this module assembles the full
:class:`~video_analyse.models.VideoReport` from that core plus the shots, the
transcript and the media metadata, so the facts the model never sees (source,
duration, timings, technical metadata) cannot be hallucinated.
Prompt size is bounded by a deterministic character budget derived from a
``chars / 4`` token heuristic (:func:`default_char_budget`): ~6000 characters for
the local llama-server and ~96000 for hosted provider specs. Long transcripts are
summarised chunk-wise before the final reduce prompt; when material still does not
fit, the transcript is truncated first and an oversized fixed part is clipped
explicitly (:func:`fit_prompt`). Local prompts that would overflow the documented
``llama-server -c 8192`` context raise an actionable error instead of being sent.
"""
from __future__ import annotations
import hashlib
import json
import logging
import math
from typing import Any, Protocol
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from pydantic_ai.providers import infer_provider_class
from . import llm
from .cache import StageCache
from .config import Settings
from .models import (
Highlight,
MediaInfo,
ReportCore,
Shot,
Transcript,
VideoReport,
)
from .report import format_timestamp
logger = logging.getLogger(__name__)
__all__ = [
"CHARS_PER_TOKEN",
"LOCAL_CONTEXT_TOKENS",
"LOCAL_PROMPT_CHARS",
"LOCAL_PROMPT_TOKENS",
"MAX_QA_TOKENS",
"MAX_SYNTHESIS_TOKENS",
"PROVIDER_PROMPT_CHARS",
"PROVIDER_PROMPT_TOKENS",
"QA_INSTRUCTIONS",
"SYNTHESIS_INSTRUCTIONS",
"AnswerResult",
"ChunkCore",
"answer_question",
"answer_question_result",
"assemble_report",
"build_question_prompt",
"build_synthesis_prompt",
"default_char_budget",
"estimate_tokens",
"fit_prompt",
"format_media_metadata",
"format_shots",
"format_transcript",
"metadata_from_info",
"synthesise_report",
]
# --- prompt budget ---------------------------------------------------------
#: Heuristic: English text runs at roughly four characters per model token.
CHARS_PER_TOKEN = 4
#: Prompt budget (tokens) for the local llama-server default profile.
LOCAL_PROMPT_TOKENS = 1500
#: Prompt budget (tokens) for hosted provider specs (large context windows).
PROVIDER_PROMPT_TOKENS = 24_000
#: Prompt budget (characters) for the local llama-server default profile.
LOCAL_PROMPT_CHARS = LOCAL_PROMPT_TOKENS * CHARS_PER_TOKEN
#: Prompt budget (characters) for hosted provider specs.
PROVIDER_PROMPT_CHARS = PROVIDER_PROMPT_TOKENS * CHARS_PER_TOKEN
#: llama-server context the local defaults assume (PLAN section 5: ``-c 8192``).
LOCAL_CONTEXT_TOKENS = 8192
#: Output-token reservation of the report agent.
MAX_SYNTHESIS_TOKENS = 2000
#: Output-token reservation of the Q&A agent.
MAX_QA_TOKENS = 800
#: Transcript characters summarized per map step (local / hosted).
LOCAL_CHUNK_CHARS = 5000
PROVIDER_CHUNK_CHARS = 60_000
#: Maximum number of map chunks; beyond this the tail is truncated explicitly.
MAX_CHUNKS = 32
#: Longest shot summary kept per shot in the prompt (keeps 64-shot lists affordable).
MAX_SHOT_SUMMARY_CHARS = 240
#: Longest on-screen-text excerpt kept per shot in the prompt.
MAX_SHOT_ON_SCREEN_CHARS = 200
#: Fraction of the prompt budget the compact shot list may consume.
SHOT_BUDGET_FRACTION = 0.3
class ChunkCore(BaseModel):
"""Map-step summary of one transcript chunk (reduced into the final report)."""
summary: str
topics: list[str] = []
people: list[str] = []
highlights: list[Highlight] = []
class AnswerResult(BaseModel):
"""Grounded answer plus cache provenance (``va ask --json`` / MCP ask_video)."""
answer: str
cached: bool = False
cache_key: str | None = None
citations: list[str] = Field(default_factory=list)
class _NoteFactory(Protocol):
"""Builds the placeholder that replaces truncated material."""
def __call__(self, total_chars: int, kept_chars: int) -> str: ...
def estimate_tokens(text: str) -> int:
"""Estimate the token count of ``text`` with the ``chars / 4`` heuristic."""
return math.ceil(len(text) / CHARS_PER_TOKEN)
def _is_provider_prefixed(spec: str) -> bool:
"""True when ``spec`` names a pydantic-ai provider (and is therefore hosted).
``local:<name>`` is explicitly *not* a provider prefix in this sense: it is
routed to the local llama-server by :func:`video_analyse.llm.build_model`.
An unknown prefix (``qwen3-vl:4b``) is also a local llama-server model name.
"""
prefix, separator, rest = (spec or "").strip().partition(":")
if not (separator and prefix and rest) or prefix == llm.LOCAL_PREFIX:
return False
try:
infer_provider_class(prefix)
except ValueError:
return False
except ImportError:
# Registered provider whose optional SDK extra is not installed.
return True
return True
def default_char_budget(spec: str) -> int:
"""Character budget for a prompt sent to the model named by ``spec``.
Local llama-server models (bare names and ``local:<name>``) get
:data:`LOCAL_PROMPT_CHARS`; provider-prefixed specs (``deepseek:``,
``openrouter:``, ``ollama:``, ...) get :data:`PROVIDER_PROMPT_CHARS`.
"""
return PROVIDER_PROMPT_CHARS if _is_provider_prefixed(spec) else LOCAL_PROMPT_CHARS
def _transcript_truncation_note(total_chars: int, kept_chars: int) -> str:
"""Marker inserted into a prompt when transcript material was dropped."""
return (
"[... transcript truncated for the prompt budget: kept "
f"{kept_chars} of {total_chars} characters ...]"
)
def _fixed_truncation_note(total_chars: int, kept_chars: int) -> str:
"""Marker inserted when even the fixed prompt material had to be clipped."""
return (
"[... fixed prompt material truncated for the prompt budget: kept "
f"{kept_chars} of {total_chars} characters ...]"
)
def fit_prompt(
fixed: str,
transcript: str,
*,
max_chars: int,
note_factory: _NoteFactory = _transcript_truncation_note,
) -> tuple[str, bool]:
"""Join ``fixed`` and ``transcript`` within ``max_chars``, transcript last.
The ``fixed`` material (instructions, media facts, shot list) is never
trimmed; the transcript absorbs the whole overrun. Truncation keeps the
beginning of the transcript on a line boundary and appends a marker built by
``note_factory`` stating how much was dropped.
Args:
fixed: material that must always be present.
transcript: variable material, truncated first when the budget is tight.
max_chars: hard character budget for the returned text.
note_factory: builds the truncation marker from
``(total_chars, kept_chars)``.
Returns:
``(text, truncated)``.
Raises:
ValueError: if ``max_chars`` is not positive.
"""
if max_chars <= 0:
raise ValueError(f"max_chars must be positive, got {max_chars}")
if len(fixed) >= max_chars:
# The fixed material alone overflows the budget (e.g. a 64-shot report JSON).
# Clip it explicitly instead of returning an oversized prompt.
note = _fixed_truncation_note(len(fixed), 0)
for _ in range(2):
keep = max(max_chars - len(note) - 1, 0)
note = _fixed_truncation_note(len(fixed), keep)
body = fixed[: max(max_chars - len(note) - 1, 0)]
note = _fixed_truncation_note(len(fixed), len(body))
return f"{body}\n{note}"[:max_chars], True
if not transcript:
return fixed, False
separator = "\n\n"
available = max_chars - len(fixed) - len(separator)
if len(transcript) <= available:
return f"{fixed}{separator}{transcript}", False
# Two fixed-point rounds: the marker length depends on the number it reports.
keep = max(available, 0)
note = note_factory(len(transcript), keep)
for _ in range(2):
keep = max(available - len(note) - 1, 0) # one newline before the marker
note = note_factory(len(transcript), keep)
body = transcript[:keep]
newline = body.rfind("\n")
if newline >= len(body) // 2:
body = body[:newline]
note = note_factory(len(transcript), len(body))
overhead = len(fixed) + len(separator) + 1 # + the newline before the marker
if overhead + len(body) + len(note) > max_chars:
body = transcript[: max(max_chars - overhead - len(note), 0)].rstrip()
note = note_factory(len(transcript), len(body))
if not body:
return f"{fixed}{separator}{note}", True
return f"{fixed}{separator}{body}\n{note}", True
# --- compact serialisation of the model's ground truth --------------------
def _one_line(text: str, *, limit: int | None = None) -> str:
"""Collapse whitespace in ``text`` and optionally clip it to ``limit`` chars."""
collapsed = " ".join(text.split())
if limit is not None and len(collapsed) > limit:
collapsed = collapsed[: max(limit - 3, 0)].rstrip() + "..."
return collapsed
def _yes_no(value: bool) -> str:
return "yes" if value else "no"
def format_media_metadata(info: MediaInfo) -> str:
"""Render media facts as compact, one-fact-per-line text."""
lines = [
"VIDEO METADATA:",
f"- source: {info.source}",
f"- duration: {format_timestamp(info.duration)} ({info.duration:.2f} s)",
]
if info.width and info.height:
resolution = f"- resolution: {info.width}x{info.height}"
if info.fps:
resolution += f" at {info.fps:g} fps"
lines.append(resolution)
if info.format:
lines.append(f"- container: {info.format}")
if info.video_codec:
lines.append(f"- video codec: {info.video_codec}")
if info.audio_codec:
lines.append(f"- audio codec: {info.audio_codec}")
lines.append(f"- has audio: {_yes_no(info.has_audio)}")
return "\n".join(lines)
def format_shots(shots: list[Shot], *, max_chars: int | None = None) -> str:
"""Render the shot list as ``index, [MM:SS-MM:SS], summary, on-screen text`` lines.
Args:
shots: shots to render.
max_chars: optional hard cap; excess shots are replaced by an omission marker so
a 64-shot list can never consume the whole synthesis budget.
"""
if not shots:
return "SHOTS: none available"
lines = [f"SHOTS ({len(shots)}):"]
for shot in sorted(shots, key=lambda item: (item.start, item.index)):
span = f"[{format_timestamp(shot.start)}-{format_timestamp(shot.end)}]"
if shot.description is None:
lines.append(f"[{shot.index}] {span}: no visual description available")
continue
summary = _one_line(shot.description.summary, limit=MAX_SHOT_SUMMARY_CHARS)
entry = f"[{shot.index}] {span}: {summary}"
if shot.description.on_screen_text:
on_screen = _one_line(shot.description.on_screen_text, limit=MAX_SHOT_ON_SCREEN_CHARS)
entry += f' | on-screen: "{on_screen}"'
lines.append(entry)
text = "\n".join(lines)
if max_chars is None or len(text) <= max_chars:
return text
note = f"[... shot list truncated for the prompt budget; {len(shots)} shots total ...]"
body = text[: max(max_chars - len(note) - 1, 0)]
newline = body.rfind("\n")
if newline >= len(body) // 2:
body = body[:newline]
return f"{body}\n{note}"[:max_chars]
def format_transcript(transcript: Transcript | None) -> str:
"""Render the transcript as one ``[MM:SS] Speaker: text`` line per segment."""
if transcript is None or not transcript.segments:
return ""
lines = []
for segment in sorted(transcript.segments, key=lambda item: item.start):
text = _one_line(segment.text)
if not text:
continue
stamp = f"[{format_timestamp(segment.start)}]"
lines.append(f"{stamp} {segment.speaker}: {text}" if segment.speaker else f"{stamp} {text}")
return "\n".join(lines)
# --- prompts ---------------------------------------------------------------
SYNTHESIS_INSTRUCTIONS = (
"You write faithful, grounded reports about videos. You work only from the media "
"metadata, shot list and transcript you are given. Never invent facts, names, "
"numbers or events that are not present in that material, and never claim to have "
"watched anything beyond it. If the material is thin, say less rather than guess."
)
SYNTHESIS_TASK = (
"TASK: write the core of a report about this video from the material below.\n"
"- summary: a concise overview (at most 150 words) of what the video shows and says.\n"
"- topics: 3-10 short topical labels that the material supports.\n"
"- people: the names or clear speaker/visual labels that actually appear in the material.\n"
"- highlights: 3-8 notable moments, each with start/end seconds inside the video and a "
"description that begins with its [MM:SS] timestamp.\n"
"Use only the metadata, shot list and transcript below."
)
SYNTHESIS_FOOTER = (
"Return the report core now: a concise summary, topics, people and 3-8 highlights whose "
"descriptions begin with [MM:SS]. Do not add facts that are absent from the material above."
)
QA_INSTRUCTIONS = (
"You answer questions about one video using only the provided report material. "
"If the material does not contain the answer, say so plainly instead of guessing. "
"Cite the moments you rely on as [MM:SS]. Be terse and concrete."
)
CHUNK_INSTRUCTIONS = (
"You summarise one chronological chunk of a video transcript. Work only from the text "
"you are given: never invent names, numbers or events. Keep timestamps exactly as they "
"appear. If the chunk is small talk without substance, say that briefly."
)
CHUNK_TASK = (
"TASK: summarise this transcript chunk of a longer video.\n"
"- summary: at most 80 words on what is said and any decisions/results.\n"
"- topics: up to 5 short labels supported by this chunk.\n"
"- people: names or clear speaker labels that actually appear.\n"
"- highlights: 0-3 moments with start/end seconds and a [MM:SS]-prefixed description."
)
def _check_local_context(prompt: str, max_tokens: int, spec: str) -> None:
"""Refuse a local prompt that cannot fit ``llama-server -c 8192`` with its output."""
if _is_provider_prefixed(spec):
return
needed = estimate_tokens(prompt) + max_tokens
if needed > LOCAL_CONTEXT_TOKENS:
raise RuntimeError(
f"the {spec!r} prompt needs about {needed} tokens (prompt + max_tokens), but the "
f"documented llama-server context is {LOCAL_CONTEXT_TOKENS}. Restart llama-server "
f"with a larger -c (for example -c {needed + 1024}), or point "
"VA_SYNTHESIS_MODEL at a hosted model."
)
def _transcript_chunks(transcript: Transcript | None, *, chunk_chars: int) -> list[str]:
"""Split the formatted transcript into line-aligned chunks of at most ~``chunk_chars``."""
text = format_transcript(transcript)
if not text:
return []
chunks: list[str] = []
current: list[str] = []
used = 0
for line in text.splitlines():
if current and used + len(line) + 1 > chunk_chars:
chunks.append("\n".join(current))
current = []
used = 0
current.append(line)
used += len(line) + 1
if current:
chunks.append("\n".join(current))
return chunks
def _compact_chunk_notes(cores: list[ChunkCore], *, max_chars: int) -> str:
"""Render map-step results as bounded one-paragraph notes for the reduce prompt."""
notes: list[str] = []
for index, core in enumerate(cores, start=1):
parts = [f"[{index}] {_one_line(core.summary, limit=260)}"]
if core.topics:
parts.append("topics: " + ", ".join(core.topics[:5]))
if core.people:
parts.append("people: " + ", ".join(core.people[:8]))
for highlight in core.highlights[:3]:
parts.append(
f"[{format_timestamp(highlight.start)}] "
f"{_one_line(highlight.description, limit=160)}"
)
notes.append(" | ".join(parts))
text = "\n".join(notes)
if len(text) <= max_chars:
return text
note = "[... chunk summaries truncated for the prompt budget ...]"
body = text[: max(max_chars - len(note) - 1, 0)]
newline = body.rfind("\n")
if newline >= len(body) // 2:
body = body[:newline]
return f"{body}\n{note}"[:max_chars]
def _chunk_prompt(info: MediaInfo, chunk: str, index: int, total: int, *, max_chars: int) -> str:
"""Build the map-step prompt for one transcript chunk."""
fixed = "\n\n".join(
[CHUNK_TASK, format_media_metadata(info), f"TRANSCRIPT CHUNK {index}/{total}:"]
)
return fit_prompt(fixed, chunk, max_chars=max_chars)[0]
def build_synthesis_prompt(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
max_chars: int,
chunk_notes: str | None = None,
) -> str:
"""Build the synthesis prompt from compactly serialized stage artifacts.
Args:
shots: detected shots with optional VLM descriptions.
transcript: speaker-labelled transcript, or ``None`` when unavailable.
info: media metadata for the source.
max_chars: character budget for the whole prompt.
chunk_notes: pre-computed map-step summaries of a long transcript; when given,
they replace the raw transcript in the reduce prompt.
Returns:
The prompt text; the transcript portion is truncated first when needed.
Raises:
ValueError: if ``max_chars`` is not positive.
"""
if max_chars <= 0:
raise ValueError(f"max_chars must be positive, got {max_chars}")
shot_budget = max(int(max_chars * SHOT_BUDGET_FRACTION), 600)
material_text = format_shots(shots, max_chars=shot_budget)
if chunk_notes is not None:
transcript_heading = (
"CHUNK SUMMARIES (map-step summaries of the whole transcript, in order; "
"[MM:SS] prefixes):"
)
transcript_text = chunk_notes or "(no transcript available)"
else:
transcript_heading = "TRANSCRIPT (speaker-labelled where available, [MM:SS] prefixes):"
transcript_text = format_transcript(transcript) or "(no transcript available)"
fixed = "\n\n".join(
[
SYNTHESIS_TASK,
format_media_metadata(info),
material_text,
transcript_heading,
]
)
body_budget = max(max_chars - len(SYNTHESIS_FOOTER) - 2, 1)
material, truncated = fit_prompt(fixed, transcript_text, max_chars=body_budget)
if truncated:
logger.info("synthesis prompt truncated material to fit %d characters", max_chars)
return f"{material}\n\n{SYNTHESIS_FOOTER}"[:max_chars]
def _report_json(report: VideoReport, *, max_chars: int | None = None) -> str:
"""Compact, bounded JSON view of the report (no transcript, keyframes or ffprobe).
``metadata.extra`` can hold the whole ffprobe payload; it is omitted because the
answer-relevant facts (source, duration, summary, highlights, shots) are already
present. Shot summaries are capped and the list is dropped when the budget is tight.
"""
payload: dict[str, Any] = {
"source": report.source,
"title": report.title,
"duration": report.duration,
"summary": _one_line(report.summary, limit=1500),
"topics": list(report.topics),
"people": list(report.people),
"highlights": [
{
"start": item.start,
"end": item.end,
"description": _one_line(item.description, limit=300),
}
for item in report.highlights
],
}
shots: list[dict[str, Any]] = []
for shot in sorted(report.shots, key=lambda item: (item.start, item.index)):
entry: dict[str, Any] = {
"index": shot.index,
"start": shot.start,
"end": shot.end,
"summary": (
_one_line(shot.description.summary, limit=MAX_SHOT_SUMMARY_CHARS)
if shot.description is not None
else None
),
}
if shot.description is not None and shot.description.on_screen_text:
entry["on_screen_text"] = _one_line(
shot.description.on_screen_text, limit=MAX_SHOT_ON_SCREEN_CHARS
)
shots.append(entry)
candidate = json.dumps(
{**payload, "shots": shots}, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
if max_chars is not None and len(candidate) > max_chars:
shots.pop()
break
payload["shots"] = shots
if len(shots) < len(report.shots):
payload["shots_omitted"] = len(report.shots) - len(shots)
text = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
if max_chars is not None and len(text) > max_chars:
payload.pop("shots", None)
payload.pop("highlights", None)
payload["summary"] = _one_line(report.summary, limit=400)
text = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return text
def build_question_prompt(report: VideoReport, question: str, *, max_chars: int) -> str:
"""Build the grounded Q&A prompt: question, report JSON, then the transcript.
Args:
report: report to answer from.
question: the user's question, forwarded verbatim.
max_chars: character budget for the whole prompt.
Returns:
The prompt text; the report JSON is compact and the transcript is truncated
first when needed.
Raises:
ValueError: if ``question`` is blank or ``max_chars`` is not positive.
"""
if max_chars <= 0:
raise ValueError(f"max_chars must be positive, got {max_chars}")
question_text = _one_line(question)
if not question_text:
raise ValueError("question must be a non-empty string")
report_budget = max(int(max_chars * 0.4), 500)
fixed = "\n\n".join(
[
f"QUESTION: {question_text}",
"Answer only from the material below. If the answer is not in the material, say so. "
"Cite the moments you rely on as [MM:SS].",
f"REPORT (JSON):\n{_report_json(report, max_chars=report_budget)}",
"TRANSCRIPT (speaker-labelled where available, [MM:SS] prefixes):",
]
)
transcript_text = format_transcript(report.transcript) or "(no transcript available)"
return fit_prompt(fixed, transcript_text, max_chars=max_chars)[0]
# --- report assembly and agents -------------------------------------------
def metadata_from_info(info: MediaInfo) -> dict[str, Any]:
"""Flatten a :class:`MediaInfo` into the report's free-form metadata dict."""
metadata: dict[str, Any] = {
"path": str(info.path),
"format": info.format,
"video_codec": info.video_codec,
"audio_codec": info.audio_codec,
"width": info.width,
"height": info.height,
"fps": info.fps,
"has_audio": info.has_audio,
"size_bytes": info.size_bytes,
}
if info.extra:
metadata["extra"] = dict(info.extra)
return metadata
def _metadata_title(info: MediaInfo) -> str | None:
"""Best grounded title from the source metadata, if it carries one."""
title = info.extra.get("title")
if isinstance(title, str) and title.strip():
return title.strip()
yt_dlp = info.extra.get("yt_dlp")
if isinstance(yt_dlp, dict):
title = yt_dlp.get("title")
if isinstance(title, str) and title.strip():
return title.strip()
ffprobe = info.extra.get("ffprobe")
if isinstance(ffprobe, dict):
format_info = ffprobe.get("format")
if isinstance(format_info, dict):
tags = format_info.get("tags")
if isinstance(tags, dict):
title = tags.get("title")
if isinstance(title, str) and title.strip():
return title.strip()
tags = info.extra.get("tags")
if isinstance(tags, dict):
tagged = tags.get("title")
if isinstance(tagged, str) and tagged.strip():
return tagged.strip()
return None
def assemble_report(
core: ReportCore,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
prompt_info: dict[str, Any] | None = None,
) -> VideoReport:
"""Combine the LLM-authored core with the facts the code owns.
``prompt_info`` records whether the prompt was chunked/truncated so a partial
report is visible as such in ``metadata['synthesis']`` instead of looking complete.
"""
title = core.title if core.title and core.title.strip() else _metadata_title(info)
metadata = metadata_from_info(info)
if prompt_info:
metadata["synthesis"] = dict(prompt_info)
return VideoReport(
source=info.source,
title=title,
duration=info.duration,
summary=core.summary,
topics=list(core.topics),
people=list(core.people),
highlights=list(core.highlights),
shots=list(shots),
transcript=transcript,
metadata=metadata,
)
def _has_material(shots: list[Shot], transcript: Transcript | None) -> bool:
"""True when there is something to synthesise a report from."""
return bool(shots) or bool(transcript is not None and transcript.segments)
async def synthesise_report(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
settings: Settings,
) -> VideoReport:
"""Ask the synthesis model for a report core and assemble the full report.
Long transcripts are processed chunk-wise (map step: :class:`ChunkCore` per chunk,
reduce step: one :class:`ReportCore` over the compiled notes), which keeps a one-hour
video inside the local llama-server context instead of silently reporting on a
prefix. ``metadata['synthesis']`` records whether chunking/truncation happened.
Args:
shots: detected shots (with descriptions when the vision stage ran).
transcript: speaker-labelled transcript, or ``None`` when unavailable.
info: media metadata for the source.
settings: runtime settings; ``settings.resolved_synthesis()`` picks the model.
Returns:
A validated :class:`VideoReport`.
Raises:
ValueError: if there is neither a shot nor a transcript segment to ground on.
RuntimeError: the local prompt would overflow the documented llama-server context.
"""
if not _has_material(shots, transcript):
raise ValueError(
"cannot synthesise a report: no shots and no transcript were provided; "
"run the shots or transcribe stage first"
)
spec = settings.resolved_synthesis()
model = llm.build_model(spec, settings=settings)
budget = default_char_budget(spec)
chunk_chars = PROVIDER_CHUNK_CHARS if _is_provider_prefixed(spec) else LOCAL_CHUNK_CHARS
transcript_text = format_transcript(transcript)
chunks = _transcript_chunks(transcript, chunk_chars=chunk_chars)
truncated_chunks = 0
if len(chunks) > MAX_CHUNKS:
truncated_chunks = len(chunks) - MAX_CHUNKS
chunks = chunks[:MAX_CHUNKS]
chunked = len(chunks) > 1 and len(transcript_text) > max(budget // 2, 1200)
chunk_notes: str | None = None
if chunked:
map_agent = Agent(
model,
output_type=ChunkCore,
instructions=CHUNK_INSTRUCTIONS,
model_settings={"temperature": 0.1, "max_tokens": 800, "max_retries": 0},
retries={"output": 2},
)
cores: list[ChunkCore] = []
for index, chunk in enumerate(chunks, start=1):
prompt = _chunk_prompt(info, chunk, index, len(chunks), max_chars=budget)
logger.info(
"synthesis map step %d/%d for %s (%d chars)",
index,
len(chunks),
info.source,
len(prompt),
)
result = await map_agent.run(prompt)
cores.append(result.output)
chunk_notes = _compact_chunk_notes(cores, max_chars=max(budget // 2, 1200))
prompt = build_synthesis_prompt(
shots, transcript, info, max_chars=budget, chunk_notes=chunk_notes
)
_check_local_context(prompt, MAX_SYNTHESIS_TOKENS, spec)
prompt_info: dict[str, Any] = {
"chunked": chunked,
"chunks": len(chunks) if chunked else 0,
"chunks_truncated": truncated_chunks,
"truncated": "truncated for the prompt budget" in prompt,
"transcript_chars": len(transcript_text),
"prompt_chars": len(prompt),
}
logger.info(
"synthesising report for %s with %s (%d shots, %d chars, ~%d tokens, chunked=%s)",
info.source,
spec,
len(shots),
len(prompt),
estimate_tokens(prompt),
chunked,
)
agent = Agent(
model,
output_type=ReportCore,
instructions=SYNTHESIS_INSTRUCTIONS,
model_settings={
"temperature": 0.2,
"max_tokens": MAX_SYNTHESIS_TOKENS,
"max_retries": 0,
},
retries={"output": 2},
)
result = await agent.run(prompt)
core = result.output
return assemble_report(core, shots, transcript, info, prompt_info=prompt_info)
class _AnswerArtifact(BaseModel):
"""Cached Q&A answer (one stage entry per report fingerprint + question + model)."""
answer: str
def _report_fingerprint(report: VideoReport) -> str:
"""Content hash of a report, used as the source key of the answer cache."""
return hashlib.sha256(report.model_dump_json().encode("utf-8")).hexdigest()
def _answer_cache_key(
cache: StageCache, report: VideoReport, question: str, settings: Settings
) -> tuple[str, str]:
"""Return ``(report_sha256, stage_key)`` for one cached answer."""
fingerprint = _report_fingerprint(report)
key = cache.stage_key(
"answer",
{
"report_sha256": fingerprint,
"question": " ".join(question.split()).casefold(),
"synthesis": settings.resolved_synthesis(),
"llama_server_url": settings.llama_server_url,
},
)
return fingerprint, key
def _citations(answer: str) -> list[str]:
"""Extract unique ``[MM:SS]`` citations from a free-text answer, in order."""
import re
seen: list[str] = []
for match in re.findall(r"\[\d{1,3}:\d{2}\]", answer):
if match not in seen:
seen.append(match)
return seen
async def answer_question_result(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: StageCache | None = None,
) -> AnswerResult:
"""Answer from ``report`` with optional content-addressed caching.
The cache key covers the report's content, the normalised question, the resolved
synthesis model and the llama-server endpoint, so a repeated ``va ask`` is free while
a changed report/model never reuses an old answer.
Args:
report: the validated report to answer from.
question: the user's question.
settings: runtime settings; ``settings.resolved_synthesis()`` picks the model.
cache: stage cache to use; ``None`` disables caching (``va ask --no-cache``).
Returns:
An :class:`AnswerResult` with the answer, cache provenance and citations.
Raises:
ValueError: if ``question`` is blank.
"""
question_text = " ".join(question.split())
if not question_text:
raise ValueError("question must be a non-empty string")
spec = settings.resolved_synthesis()
fingerprint: str | None = None
key: str | None = None
if cache is not None:
fingerprint, key = _answer_cache_key(cache, report, question_text, settings)
path = cache.stage_path(fingerprint, "answer", key)
try:
cached = cache.load_model(path, _AnswerArtifact)
except ValueError as exc:
logger.warning("ignoring unusable cached answer %s: %s", path, exc)
cached = None
if cached is not None:
return AnswerResult(
answer=cached.answer,
cached=True,
cache_key=key,
citations=_citations(cached.answer),
)
budget = default_char_budget(spec)
prompt = build_question_prompt(report, question_text, max_chars=budget)
_check_local_context(prompt, MAX_QA_TOKENS, spec)
model = llm.build_model(spec, settings=settings)
logger.info(
"answering question about %s with %s (%d chars, ~%d tokens)",
report.source,
spec,
len(prompt),
estimate_tokens(prompt),
)
agent = Agent(
model,
instructions=QA_INSTRUCTIONS,
model_settings={"temperature": 0.0, "max_tokens": MAX_QA_TOKENS, "max_retries": 0},
)
result = await agent.run(prompt)
answer = str(result.output)
if cache is not None and fingerprint is not None and key is not None:
try:
cache.save_model(
cache.stage_path(fingerprint, "answer", key), _AnswerArtifact(answer=answer)
)
except OSError as exc:
logger.warning("could not cache the answer: %s", exc)
return AnswerResult(answer=answer, cached=False, cache_key=key, citations=_citations(answer))
async def answer_question(report: VideoReport, question: str, *, settings: Settings) -> str:
"""Answer ``question`` from ``report`` only, citing moments as ``[MM:SS]``.
Thin wrapper around :func:`answer_question_result` (uncached) kept for the
CONTRACTS ``-> str`` signature.
"""
result = await answer_question_result(report, question, settings=settings)
return result.answer
+41
View File
@@ -0,0 +1,41 @@
"""Speech-to-text backends and the ``get_transcriber`` registry.
Backends are imported lazily so ``import video_analyse`` never pulls in onnxruntime,
ctranslate2 or httpx-based hosted clients unless the selected backend needs them.
"""
from __future__ import annotations
from ..config import Settings
from .base import Transcriber
__all__ = ["STT_BACKENDS", "Transcriber", "get_transcriber"]
STT_BACKENDS = ("parakeet", "whisper", "openai-transcriptions")
def get_transcriber(settings: Settings) -> Transcriber:
"""Return the transcriber selected by ``settings.resolved_stt()``.
``parakeet`` is the local default (multilingual Parakeet TDT v3 via ``onnx-asr``),
``whisper`` is the faster-whisper fallback and ``openai-transcriptions`` is the
hosted backend used by the ``hosted`` profile.
Raises:
ValueError: if ``settings.resolved_stt()`` is not a known backend name.
"""
backend = settings.resolved_stt()
if backend == "parakeet":
from .parakeet_onnx import ParakeetOnnxTranscriber
return ParakeetOnnxTranscriber(settings)
if backend == "whisper":
from .faster_whisper import FasterWhisperTranscriber
return FasterWhisperTranscriber(settings)
if backend == "openai-transcriptions":
from .openai_transcriptions import OpenAITranscriptionsTranscriber
return OpenAITranscriptionsTranscriber(settings)
supported = ", ".join(STT_BACKENDS)
raise ValueError(f"unknown STT backend {backend!r}; expected one of: {supported}")
+17
View File
@@ -0,0 +1,17 @@
"""The ``Transcriber`` protocol every speech-to-text backend implements."""
from __future__ import annotations
from pathlib import Path
from typing import Protocol, runtime_checkable
from ..models import Transcript
@runtime_checkable
class Transcriber(Protocol):
"""Async speech-to-text backend producing a :class:`Transcript`."""
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript:
"""Transcribe a 16 kHz mono PCM WAV file."""
...
@@ -0,0 +1,181 @@
"""faster-whisper backend: CPU int8 inference with word-level timestamps."""
from __future__ import annotations
import asyncio
import logging
import threading
import wave
from collections.abc import Iterable
from pathlib import Path
from typing import Any
from ..config import Settings
from ..models import Segment, Transcript, Word
__all__ = ["FasterWhisperTranscriber", "segments_to_transcript"]
logger = logging.getLogger(__name__)
BACKEND = "whisper"
# One loaded model per model name, shared by every transcriber instance in the process.
_MODEL_CACHE: dict[str, Any] = {}
_MODEL_LOCK = threading.Lock()
def _build_model(model_name: str) -> Any:
"""Load a faster-whisper ``WhisperModel`` (the heavy import stays lazy)."""
from faster_whisper import WhisperModel
return WhisperModel(model_name, device="cpu", compute_type="int8")
def _get_model(model_name: str) -> Any:
"""Return the process-wide model for ``model_name``, loading it at most once."""
with _MODEL_LOCK:
model = _MODEL_CACHE.get(model_name)
if model is None:
logger.info("loading faster-whisper model %r (cpu, int8)", model_name)
model = _build_model(model_name)
_MODEL_CACHE[model_name] = model
return model
#: Sample rate faster-whisper expects when it is handed a numpy array.
SAMPLE_RATE = 16_000
def load_wav_samples(wav: Path) -> Any:
"""Decode a 16-bit PCM WAV into mono float32 samples in ``[-1, 1]``.
faster-whisper 1.2.1 decodes path/stream inputs through PyAV with an
``av.open(..., metadata_errors=...)`` keyword that PyAV 19 removed (it raises
``TypeError`` before any audio is read). The pipeline always writes 16 kHz mono s16le
WAV, so decoding it with the stdlib keeps transcription independent of that
incompatibility and skips a redundant decode pass.
"""
import numpy as np
try:
with wave.open(str(wav), "rb") as handle:
channels = handle.getnchannels()
width = handle.getsampwidth()
rate = handle.getframerate()
raw = handle.readframes(handle.getnframes())
except (wave.Error, EOFError) as exc:
raise ValueError(f"cannot decode {wav} as a PCM WAV file: {exc}") from exc
if width != 2:
raise ValueError(
f"{wav}: expected 16-bit PCM audio, got {width * 8}-bit; extract the audio with "
"video_analyse.media.extract_audio first"
)
if rate != SAMPLE_RATE:
raise ValueError(
f"{wav}: expected {SAMPLE_RATE} Hz audio, got {rate} Hz; extract the audio with "
"video_analyse.media.extract_audio first"
)
samples = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
if channels > 1:
samples = samples.reshape(-1, channels).mean(axis=1, dtype=np.float32)
return samples
def _as_float(value: Any, default: float = 0.0) -> float:
"""Best-effort float conversion for values coming out of the model/generator."""
try:
return float(value)
except (TypeError, ValueError):
return default
def _clamp(value: float, low: float, high: float) -> float:
"""Clamp ``value`` into ``[low, high]`` (``low`` wins for an inverted range)."""
if high < low:
return low
return min(max(value, low), high)
def segments_to_transcript(segments: Iterable[Any], info: Any, *, model: str) -> Transcript:
"""Map faster-whisper segments/info onto the shared :class:`Transcript` model.
``segments`` is the generator returned by ``WhisperModel.transcribe`` and ``info``
its ``TranscriptionInfo``; any objects exposing the same attributes work (this is
how the mapping is unit-tested without loading a model). Word times are clamped to
their segment so downstream diarization attribution cannot fall outside the cue.
"""
mapped: list[Segment] = []
for raw_segment in segments:
start = _as_float(getattr(raw_segment, "start", 0.0))
end = max(start, _as_float(getattr(raw_segment, "end", start)))
words: list[Word] = []
for raw_word in getattr(raw_segment, "words", None) or []:
text = str(getattr(raw_word, "word", "") or "").strip()
if not text:
continue
word_start = _clamp(_as_float(getattr(raw_word, "start", start)), start, end)
word_end = max(
word_start,
_clamp(_as_float(getattr(raw_word, "end", word_start)), start, end),
)
probability = getattr(raw_word, "probability", None)
words.append(
Word(
text=text,
start=word_start,
end=word_end,
probability=None if probability is None else float(probability),
)
)
mapped.append(
Segment(
start=start,
end=end,
text=str(getattr(raw_segment, "text", "") or "").strip(),
words=words,
)
)
duration = _as_float(getattr(info, "duration", 0.0))
if duration <= 0.0 and mapped:
duration = mapped[-1].end
language = getattr(info, "language", None)
return Transcript(
language=None if language is None else str(language),
duration=duration,
segments=mapped,
backend=BACKEND,
model=model,
)
class FasterWhisperTranscriber:
"""Transcribe 16 kHz mono WAV audio with faster-whisper (CPU, int8)."""
def __init__(self, settings: Settings, *, model_name: str | None = None) -> None:
"""Bind settings; ``model_name`` overrides ``settings.whisper_model`` if given."""
self._settings = settings
self.model_name = model_name or settings.whisper_model
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript:
"""Transcribe ``wav``; ``language=None`` falls back to ``settings.language``."""
wav = Path(wav)
if not wav.is_file():
raise ValueError(f"audio file not found: {wav}")
effective_language = language if language is not None else self._settings.language
return await asyncio.to_thread(self._transcribe_sync, wav, effective_language)
def _transcribe_sync(self, wav: Path, language: str | None) -> Transcript:
"""Blocking transcription body, executed in a worker thread."""
model = _get_model(self.model_name)
segments, info = model.transcribe(
load_wav_samples(wav),
language=language,
word_timestamps=True,
vad_filter=True,
beam_size=5,
condition_on_previous_text=False,
)
# ``segments`` is a lazy generator: it must be consumed inside this thread.
return segments_to_transcript(segments, info, model=self.model_name)
@@ -0,0 +1,492 @@
"""Hosted speech-to-text via an OpenAI-compatible ``/audio/transcriptions`` endpoint.
The client speaks the OpenAI ``verbose_json`` dialect (word + segment granularities),
which is what Groq's ``whisper-large-v3-turbo`` (the default hosted model) and OpenAI's
own transcription endpoints implement. Audio is uploaded as 16 kHz mono FLAC; files
above ``MAX_UPLOAD_BYTES`` are split with ffmpeg into ``CHUNK_SECONDS`` parts and the
timestamps of every part are stitched back together with cumulative offsets.
"""
from __future__ import annotations
import asyncio
import logging
import os
import shutil
import tempfile
from bisect import bisect_right
from collections.abc import Mapping, Sequence
from contextlib import nullcontext
from pathlib import Path
from typing import Any
import httpx
from ..config import Settings
from ..models import Segment, Transcript, Word
__all__ = [
"MAX_UPLOAD_BYTES",
"OPENAI_MAX_UPLOAD_BYTES",
"OpenAITranscriptionsTranscriber",
"compute_chunk_offsets",
"verbose_json_to_transcript",
]
logger = logging.getLogger(__name__)
BACKEND = "openai-transcriptions"
# Groq caps a request at 100 MB; stay below it with a safety margin.
MAX_UPLOAD_BYTES = 90 * 1024 * 1024
#: OpenAI's whisper-1/gpt-4o-transcribe endpoints cap uploads at 25 MB.
OPENAI_MAX_UPLOAD_BYTES = 24 * 1024 * 1024
CHUNK_SECONDS = 20 * 60.0
FFMPEG_TIMEOUT = 600.0
FFPROBE_TIMEOUT = 120.0
HTTP_TIMEOUT = 600.0
API_KEY_ENV_VARS = ("GROQ_API_KEY", "VA_STT_API_KEY", "OPENAI_API_KEY")
def compute_chunk_offsets(durations: Sequence[float]) -> list[float]:
"""Return the absolute start offset of every audio chunk.
``durations[i]`` is the duration of chunk ``i`` in seconds; negative values are
treated as zero so offsets never move backwards.
"""
offsets: list[float] = []
elapsed = 0.0
for duration in durations:
offsets.append(elapsed)
elapsed += max(0.0, float(duration))
return offsets
def _as_float(value: Any, default: float = 0.0) -> float:
"""Best-effort float conversion for JSON values (``None``/"N/A"/str included)."""
try:
return float(value)
except (TypeError, ValueError):
return default
def _extract_words(payload: Mapping[str, Any], offset: float) -> list[Word]:
"""Collect word entries of one ``verbose_json`` payload, shifted by ``offset``."""
raw_words = payload.get("words")
if not raw_words:
# Some providers nest the word list inside each segment instead of the root.
nested: list[Any] = []
for raw_segment in payload.get("segments") or []:
if isinstance(raw_segment, Mapping):
nested.extend(raw_segment.get("words") or [])
raw_words = nested
words: list[Word] = []
for raw in raw_words or []:
if not isinstance(raw, Mapping):
continue
text = str(raw.get("word") or raw.get("text") or "").strip()
if not text:
continue
start = max(0.0, offset + _as_float(raw.get("start")))
end = max(start, offset + _as_float(raw.get("end"), start - offset))
probability = raw.get("probability")
words.append(
Word(
text=text,
start=start,
end=end,
probability=None if probability is None else _as_float(probability),
)
)
return words
def _attach_words(words: list[Word], segments: list[Segment]) -> list[Segment]:
"""Assign each word to the segment containing its midpoint (nearest as fallback)."""
if not words or not segments:
return segments
starts = [segment.start for segment in segments]
buckets: list[list[Word]] = [[] for _ in segments]
for word in words:
midpoint = (word.start + word.end) / 2.0
index = bisect_right(starts, midpoint) - 1
if index < 0:
index = 0
elif midpoint >= segments[index].end and index + 1 < len(segments):
distance_to_end = midpoint - segments[index].end
distance_to_next = segments[index + 1].start - midpoint
if distance_to_next < distance_to_end:
index += 1
buckets[index].append(word)
return [
segment.model_copy(update={"words": bucket})
for segment, bucket in zip(segments, buckets, strict=True)
]
def verbose_json_to_transcript(
payloads: Sequence[Mapping[str, Any]],
offsets: Sequence[float],
*,
model: str,
language: str | None = None,
) -> Transcript:
"""Map one or more ``verbose_json`` payloads (one per chunk) to a :class:`Transcript`.
``offsets[i]`` is the absolute start time of the chunk that produced ``payloads[i]``
(see :func:`compute_chunk_offsets`); every timestamp is shifted by it so the result
is continuous across chunks.
"""
if len(payloads) != len(offsets):
raise ValueError(
f"got {len(payloads)} payload(s) but {len(offsets)} offset(s); they must match"
)
segments: list[Segment] = []
words: list[Word] = []
detected_language = language
duration = 0.0
for payload, raw_offset in zip(payloads, offsets, strict=True):
offset = max(0.0, float(raw_offset))
words.extend(_extract_words(payload, offset))
for raw_segment in payload.get("segments") or []:
if not isinstance(raw_segment, Mapping):
continue
start = max(0.0, offset + _as_float(raw_segment.get("start")))
end = max(start, offset + _as_float(raw_segment.get("end"), start - offset))
segments.append(
Segment(
start=start,
end=end,
text=str(raw_segment.get("text") or "").strip(),
)
)
if detected_language is None:
payload_language = payload.get("language")
if payload_language:
detected_language = str(payload_language)
duration = max(duration, offset + _as_float(payload.get("duration")))
if not segments and words:
segments = [
Segment(
start=words[0].start,
end=words[-1].end,
text=" ".join(word.text for word in words),
)
]
if segments:
duration = max(duration, segments[-1].end)
return Transcript(
language=detected_language,
duration=duration,
segments=_attach_words(words, segments),
backend=BACKEND,
model=model,
)
def _seconds_argument(seconds: float) -> str:
"""Format a duration for an ffmpeg command line (``1200`` rather than ``1200.0``)."""
return f"{seconds:g}"
async def _run_ffmpeg(arguments: Sequence[str], *, timeout: float = FFMPEG_TIMEOUT) -> None:
"""Run ffmpeg with an argument list (never a shell) and raise on failure."""
executable = shutil.which("ffmpeg")
if executable is None:
raise RuntimeError("ffmpeg not found on PATH; install ffmpeg to upload hosted STT audio")
command = [executable, "-nostdin", "-y", "-loglevel", "error", *arguments]
try:
process = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
except OSError as exc: # pragma: no cover - defensive, ffmpeg exists on this host
raise RuntimeError(f"could not start ffmpeg: {exc}") from exc
try:
_, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except TimeoutError:
process.kill()
await process.wait()
raise RuntimeError(f"ffmpeg timed out after {timeout:.0f}s") from None
except asyncio.CancelledError:
process.kill()
await process.wait()
raise
if process.returncode != 0:
detail = " ".join(stderr.decode("utf-8", "replace").strip().splitlines()[-5:])
raise RuntimeError(f"ffmpeg failed (exit {process.returncode}): {detail or 'no stderr'}")
async def _probe_duration(path: Path) -> float:
"""Return the media duration in seconds (``0.0`` when ffprobe cannot tell)."""
executable = shutil.which("ffprobe")
if executable is None:
raise RuntimeError("ffprobe not found on PATH; install ffmpeg to upload hosted STT audio")
command = [
executable,
"-v",
"quiet",
"-show_entries",
"format=duration",
"-of",
"default=nw=1:nk=1",
str(path),
]
try:
process = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
except OSError as exc: # pragma: no cover - defensive, ffprobe exists on this host
raise RuntimeError(f"could not start ffprobe: {exc}") from exc
try:
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=FFPROBE_TIMEOUT)
except TimeoutError:
process.kill()
await process.wait()
raise RuntimeError(f"ffprobe timed out after {FFPROBE_TIMEOUT:.0f}s") from None
except asyncio.CancelledError:
process.kill()
await process.wait()
raise
if process.returncode != 0:
raise RuntimeError(f"ffprobe failed (exit {process.returncode}) for {path}")
return max(0.0, _as_float(stdout.decode("utf-8", "replace").strip()))
async def _convert_to_flac(wav: Path, target: Path) -> Path:
"""Convert ``wav`` to 16 kHz mono FLAC at ``target``."""
await _run_ffmpeg(
[
"-i",
str(wav),
"-vn",
"-map",
"0:a:0",
"-c:a",
"flac",
"-ar",
"16000",
"-ac",
"1",
"-f",
"flac",
str(target),
]
)
if not target.is_file() or target.stat().st_size == 0:
raise RuntimeError(f"ffmpeg produced no FLAC output for {wav}")
return target
async def _prepare_upload_parts(
flac: Path, workdir: Path, *, max_upload_bytes: int = MAX_UPLOAD_BYTES
) -> list[tuple[Path, float]]:
"""Return ``(flac_part, duration)`` pairs that together cover the whole audio.
The duration is only used to compute absolute chunk offsets; the transcript duration
itself comes from the API payloads, so the single-chunk case reports ``0.0``.
A single FLAC file is uploaded as-is. Larger files are cut with ffmpeg's segment
muxer into WAV parts (whose headers carry exact durations), then each part is
re-encoded to FLAC so every upload gets a correct STREAMINFO duration header.
"""
size = flac.stat().st_size
if size <= max_upload_bytes:
# A single chunk always starts at 0; its duration comes from the API payload.
return [(flac, 0.0)]
logger.info(
"audio is %.1f MB (> %.0f MB); splitting into %.0f s chunks",
size / 1_000_000,
max_upload_bytes / 1_000_000,
CHUNK_SECONDS,
)
parts_dir = workdir / "parts"
parts_dir.mkdir(parents=True, exist_ok=True)
await _run_ffmpeg(
[
"-i",
str(flac),
"-f",
"segment",
"-segment_time",
_seconds_argument(CHUNK_SECONDS),
"-c:a",
"pcm_s16le",
str(parts_dir / "part-%04d.wav"),
]
)
wav_parts = sorted(parts_dir.glob("part-*.wav"))
if not wav_parts:
raise RuntimeError(f"ffmpeg produced no audio chunks for {flac}")
parts: list[tuple[Path, float]] = []
for wav_part in wav_parts:
duration = await _probe_duration(wav_part)
if duration <= 0.0:
logger.debug("skipping empty audio chunk %s", wav_part)
continue
flac_part = wav_part.with_suffix(".flac")
await _run_ffmpeg(
[
"-i",
str(wav_part),
"-vn",
"-c:a",
"flac",
"-ar",
"16000",
"-ac",
"1",
str(flac_part),
]
)
if not flac_part.is_file() or flac_part.stat().st_size == 0:
raise RuntimeError(f"ffmpeg produced an empty audio chunk: {flac_part}")
parts.append((flac_part, duration))
if not parts:
raise RuntimeError(f"could not split {flac} into usable audio chunks")
return parts
class OpenAITranscriptionsTranscriber:
"""Hosted transcription through an OpenAI-compatible transcriptions API."""
def __init__(
self,
settings: Settings,
client: httpx.AsyncClient | None = None,
*,
api_key: str | None = None,
) -> None:
"""Bind settings and optionally inject an ``httpx.AsyncClient`` and API key.
An injected client is not closed by this transcriber (the caller owns it).
Without ``api_key`` the key is read from ``GROQ_API_KEY``, ``VA_STT_API_KEY``
or ``OPENAI_API_KEY`` (first non-empty wins).
"""
self._settings = settings
self._client = client
self._api_key = api_key
self.model = settings.stt_api_model
self.endpoint = f"{settings.stt_api_base_url.rstrip('/')}/audio/transcriptions"
def _max_upload_bytes(self) -> int:
"""Effective per-request upload cap: explicit setting, provider default, 90 MB."""
configured = self._settings.stt_max_upload_bytes
if configured is not None:
if configured < 1:
raise ValueError(f"VA_STT_MAX_UPLOAD_BYTES must be positive, got {configured!r}")
return configured
if "api.openai.com" in self._settings.stt_api_base_url.lower():
return OPENAI_MAX_UPLOAD_BYTES
return MAX_UPLOAD_BYTES
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript:
"""Upload ``wav`` (as FLAC) and return the stitched word/segment transcript."""
wav = Path(wav)
if not wav.is_file():
raise ValueError(f"audio file not found: {wav}")
api_key = self._resolve_api_key()
effective_language = language if language is not None else self._settings.language
client_context = (
nullcontext(self._client)
if self._client is not None
else httpx.AsyncClient(timeout=HTTP_TIMEOUT)
)
async with client_context as client:
with tempfile.TemporaryDirectory(prefix="va-stt-") as tmp_name:
workdir = Path(tmp_name)
flac = await _convert_to_flac(wav, workdir / "audio.flac")
parts = await _prepare_upload_parts(
flac, workdir, max_upload_bytes=self._max_upload_bytes()
)
offsets = compute_chunk_offsets([duration for _, duration in parts])
payloads = [
await self._post_chunk(
client,
part,
api_key=api_key,
language=effective_language,
)
for part, _ in parts
]
return verbose_json_to_transcript(
payloads,
offsets,
model=self.model,
language=effective_language,
)
def _resolve_api_key(self) -> str:
"""Return the configured or environment-provided API key."""
if self._api_key:
return self._api_key
for name in API_KEY_ENV_VARS:
value = os.environ.get(name, "").strip()
if value:
return value
expected = ", ".join(API_KEY_ENV_VARS)
raise RuntimeError(
f"missing API key for the {BACKEND} backend; set one of {expected} "
f"or switch to a local backend (VA_STT_BACKEND=parakeet)"
)
async def _post_chunk(
self,
client: httpx.AsyncClient,
part: Path,
*,
api_key: str,
language: str | None,
) -> dict[str, Any]:
"""POST one FLAC chunk and return its ``verbose_json`` payload."""
form: dict[str, Any] = {
"model": self.model,
"response_format": "verbose_json",
# httpx expands list values into repeated form fields (``[]`` array syntax).
"timestamp_granularities[]": ["word", "segment"],
}
if language:
form["language"] = language
audio_bytes = await asyncio.to_thread(part.read_bytes)
try:
response = await client.post(
self.endpoint,
headers={
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
},
files={"file": (part.name, audio_bytes, "audio/flac")},
data=form,
timeout=HTTP_TIMEOUT,
)
except httpx.HTTPError as exc:
raise RuntimeError(f"hosted transcription request failed: {exc}") from exc
if response.status_code >= 400:
detail = " ".join(response.text.strip().splitlines())[:300]
raise RuntimeError(
f"hosted transcription failed with HTTP {response.status_code}: "
f"{detail or response.reason_phrase}"
)
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError(
f"hosted transcription returned invalid JSON (HTTP {response.status_code})"
) from exc
if not isinstance(payload, dict):
raise RuntimeError(
"hosted transcription returned an unexpected payload: "
f"{type(payload).__name__} instead of a JSON object"
)
return payload
@@ -0,0 +1,271 @@
"""Parakeet TDT 0.6B backend via ``onnx-asr`` (onnxruntime, int8), with VAD chunking.
``onnx-asr`` exposes token-level timestamps only; word timings are derived from the
SentencePiece word-boundary marker (``"▁"``, which ``onnx-asr`` already normalises to a
leading space in ``result.tokens``). Each token timestamp is relative to the start of
its VAD segment, so absolute times are ``segment.start + token_time``.
"""
from __future__ import annotations
import asyncio
import itertools
import logging
import math
import threading
import wave
from collections.abc import Iterable
from pathlib import Path
from typing import Any
from ..config import Settings
from ..models import Segment, Transcript, Word
__all__ = [
"ENGLISH_MODEL",
"MULTILINGUAL_MODEL",
"ParakeetOnnxTranscriber",
"results_to_transcript",
"select_model_name",
"tokens_to_words",
]
logger = logging.getLogger(__name__)
BACKEND = "parakeet"
MULTILINGUAL_MODEL = "nemo-parakeet-tdt-0.6b-v3"
ENGLISH_MODEL = "nemo-parakeet-tdt-0.6b-v2"
QUANTIZATION = "int8"
VAD_MODEL = "silero"
# Parakeet accepts roughly 20-30 s of audio per pass; VAD chunking stays well below.
VAD_MAX_SPEECH_DURATION_S = 20.0
# Used only when a word's derived end would be degenerate (start == end).
WORD_FALLBACK_DURATION = 0.04
_RECOGNIZER_CACHE: dict[str, Any] = {}
_RECOGNIZER_LOCK = threading.Lock()
_VAD_CACHE: dict[str, Any] = {}
_VAD_LOCK = threading.Lock()
def select_model_name(language: str | None) -> str:
"""Return the Parakeet checkpoint for ``language``.
English (``"en"``, ``"en-US"``, ...) uses the slightly stronger English-only v2
checkpoint; every other language, and auto-detection (``None``), uses the
multilingual v3 checkpoint (see PLAN.md section 3.1 / section 5: ``--lang en``
switches to v2).
"""
if language:
base = language.strip().lower().replace("_", "-").split("-")[0]
if base == "en":
return ENGLISH_MODEL
return MULTILINGUAL_MODEL
def _build_vad() -> Any:
"""Load the Silero VAD model (lazy import; downloads on first use)."""
import onnx_asr
return onnx_asr.load_vad(VAD_MODEL)
def _get_vad() -> Any:
"""Return the process-wide Silero VAD model, loading it at most once."""
with _VAD_LOCK:
vad = _VAD_CACHE.get(VAD_MODEL)
if vad is None:
logger.info("loading onnx-asr VAD model %r", VAD_MODEL)
vad = _build_vad()
_VAD_CACHE[VAD_MODEL] = vad
return vad
def _build_recognizer(model_name: str) -> Any:
"""Load a Parakeet model and wrap it with VAD chunking + token timestamps."""
import onnx_asr
logger.info("loading onnx-asr model %r (quantization=%s)", model_name, QUANTIZATION)
model = onnx_asr.load_model(model_name, quantization=QUANTIZATION)
vad = _get_vad()
# Order matters: with_vad() first, then with_timestamps() on the VAD adapter.
return model.with_vad(vad, max_speech_duration_s=VAD_MAX_SPEECH_DURATION_S).with_timestamps()
def _get_recognizer(model_name: str) -> Any:
"""Return the cached VAD+timestamp recognizer for ``model_name``, loading it once."""
with _RECOGNIZER_LOCK:
recognizer = _RECOGNIZER_CACHE.get(model_name)
if recognizer is None:
recognizer = _build_recognizer(model_name)
_RECOGNIZER_CACHE[model_name] = recognizer
return recognizer
def _as_float(value: Any, default: float = 0.0) -> float:
"""Best-effort float conversion for optional numeric values."""
try:
return float(value)
except (TypeError, ValueError):
return default
def tokens_to_words(
tokens: Iterable[str] | None,
timestamps: Iterable[float] | None,
logprobs: Iterable[float] | None = None,
*,
start: float = 0.0,
end: float | None = None,
) -> list[Word]:
"""Merge SentencePiece tokens into words with absolute timings.
A token starts a new word when it is the first token, follows a lone space token,
or carries the SentencePiece boundary marker (``"▁"`` or a leading space). Tokens
without a marker are sub-word continuations and are appended to the current word.
A word ends where the next word starts (or at ``end`` for the last one), so word
boundaries are derived from real token emissions rather than invented durations.
``probability`` is the geometric mean of the token probabilities in the word
(``exp(mean(logprobs))``) when ``logprobs`` is available.
"""
if not tokens or not timestamps:
return []
grouped: list[dict[str, Any]] = []
pending_boundary = True
pairs = zip(
tokens,
timestamps,
logprobs if logprobs is not None else itertools.repeat(None),
strict=False,
)
for token, timestamp, logprob in pairs:
raw = str(token).replace("\u2581", " ")
piece = raw.strip()
if not piece:
if raw.startswith(" "):
pending_boundary = True
continue
if pending_boundary or raw.startswith(" ") or not grouped:
grouped.append({"text": piece, "start": start + _as_float(timestamp), "logprobs": []})
else:
grouped[-1]["text"] += piece
if logprob is not None:
grouped[-1]["logprobs"].append(float(logprob))
pending_boundary = False
if not grouped:
return []
segment_end = _as_float(end) if end is not None else grouped[-1]["start"]
words: list[Word] = []
for index, item in enumerate(grouped):
word_start = max(_as_float(item["start"]), _as_float(start))
next_start = (
_as_float(grouped[index + 1]["start"]) if index + 1 < len(grouped) else segment_end
)
word_end = min(next_start, segment_end) if segment_end > word_start else next_start
if word_end <= word_start:
word_end = word_start + WORD_FALLBACK_DURATION
probabilities: list[float] = item["logprobs"]
probability = math.exp(sum(probabilities) / len(probabilities)) if probabilities else None
if probability is not None:
probability = min(1.0, max(0.0, probability))
words.append(
Word(text=item["text"], start=word_start, end=word_end, probability=probability)
)
return words
def results_to_transcript(
results: Iterable[Any],
*,
model: str,
language: str | None,
duration: float | None = None,
) -> Transcript:
"""Map ``onnx-asr`` VAD segment results to a :class:`Transcript`.
Each result is a ``TimestampedSegmentResult``: absolute ``start``/``end`` plus
chunk-relative token ``timestamps``. Results without any text are dropped.
"""
segments: list[Segment] = []
for result in results:
words = tokens_to_words(
getattr(result, "tokens", None),
getattr(result, "timestamps", None),
getattr(result, "logprobs", None),
start=_as_float(getattr(result, "start", 0.0)),
end=_as_float(getattr(result, "end", 0.0)),
)
text = str(getattr(result, "text", "") or "").strip()
if not text and not words:
continue
start = max(0.0, _as_float(getattr(result, "start", 0.0)))
end = max(start, _as_float(getattr(result, "end", start)))
segments.append(Segment(start=start, end=end, text=text, words=words))
if duration is not None and duration > 0.0:
total_duration = float(duration)
elif segments:
total_duration = segments[-1].end
else:
total_duration = 0.0
reported_language = language
if model == ENGLISH_MODEL and reported_language is None:
reported_language = "en"
return Transcript(
language=reported_language,
duration=total_duration,
segments=segments,
backend=BACKEND,
model=model,
)
def _wav_duration(path: Path) -> float | None:
"""Read a PCM WAV duration with the stdlib; ``None`` when the file is unreadable."""
try:
with wave.open(str(path), "rb") as handle:
frames = handle.getnframes()
frame_rate = handle.getframerate()
except (wave.Error, OSError, EOFError):
logger.warning("could not read WAV duration from %s", path)
return None
if frame_rate <= 0:
return None
return frames / float(frame_rate)
class ParakeetOnnxTranscriber:
"""Transcribe 16 kHz mono WAV audio with Parakeet TDT 0.6B (ONNX, int8)."""
def __init__(self, settings: Settings, *, model_name: str | None = None) -> None:
"""Bind settings; ``model_name`` overrides the checkpoint chosen from language."""
self._settings = settings
self.model_name = model_name
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript:
"""Transcribe ``wav``; ``language=None`` falls back to ``settings.language``."""
wav = Path(wav)
if not wav.is_file():
raise ValueError(f"audio file not found: {wav}")
effective_language = language if language is not None else self._settings.language
return await asyncio.to_thread(self._transcribe_sync, wav, effective_language)
def _transcribe_sync(self, wav: Path, language: str | None) -> Transcript:
"""Blocking transcription body, executed in a worker thread."""
model_name = self.model_name or select_model_name(language)
recognizer = _get_recognizer(model_name)
raw = recognizer.recognize(str(wav))
# A VAD adapter returns an iterator of segments; tolerate a single result too.
results = raw if isinstance(raw, Iterable) else [raw]
return results_to_transcript(
results,
model=model_name,
language=language,
duration=_wav_duration(wav),
)
+369
View File
@@ -0,0 +1,369 @@
"""Per-shot visual description with a provider-agnostic pydantic-ai agent.
The describer is a single ``Agent`` (``output_type=ShotDescription``) that receives one
keyframe plus the factual context of that shot: its index and time range, the speaker-labelled
transcript slice spoken during it, and the previous shot's summary (for continuity). The
model spec comes from :meth:`video_analyse.config.Settings.resolved_vlm`, so the very same code
talks to the local llama-server (default, zero API keys) or to a hosted vision model
(``VA_VLM_MODEL=deepseek:deepseek-flash``).
Everything here is plain I/O around the agent, so the calls themselves are cheap to run
offline against ``pydantic_ai.models.function.FunctionModel`` / ``TestModel``; no network request
is made unless :func:`describe_shots` is actually awaited with a real model.
"""
from __future__ import annotations
import asyncio
import io
import logging
from pathlib import Path
from pydantic import BaseModel
from pydantic_ai import Agent, BinaryImage, ModelSettings
from pydantic_ai.models import Model
from pydantic_ai.providers import infer_provider_class
from . import llm
from .config import Settings
from .models import Shot, ShotDescription, Transcript
__all__ = [
"DESCRIBER_INSTRUCTIONS",
"LLAMA_SERVER_COMMAND",
"MOMENT_INSTRUCTIONS",
"VISION_MAX_WIDTH",
"FrameNote",
"MomentDescription",
"build_describer_agent",
"describe_moment",
"describe_shots",
"frame_prompt",
"llama_server_up",
"transcript_slice_for",
]
logger = logging.getLogger(__name__)
#: Exact startup command for the local VLM server (PLAN.md, section 5 / "Serving the VLM").
LLAMA_SERVER_COMMAND = (
"llama-server -hf bartowski/Qwen_Qwen3-VL-4B-Instruct-GGUF:Q4_K_M \\\n"
" --jinja -c 8192 -t 14 --image-max-tokens 448 --flash-attn auto \\\n"
" --host 127.0.0.1 --port 8080"
)
#: Literal, strict instructions for the describer agent (anti-hallucination, verbatim OCR).
DESCRIBER_INSTRUCTIONS = """\
You are the shot describer of a video-analysis pipeline. Each request contains exactly one
video keyframe plus factual context about that shot (index and time range, the transcript of
what was said, and the previous shot's summary).
Rules:
1. Describe only what is visible in the attached image. Never guess, never embellish, never
infer events that the image does not show.
2. `summary`: one or two literal sentences about the visible scene, subject and framing.
3. `on_screen_text`: transcribe every readable on-screen text verbatim (captions, titles, slides,
UI labels, lower-thirds). Keep the original wording, casing and line breaks; do not translate,
correct, complete or summarise it. Use null when no text is readable.
4. `shot_type`: choose exactly one of "wide", "medium", "close-up", "screen", "other".
Use "screen" when the frame is dominated by a display, slide or user interface.
5. `people`: short factual appearance descriptions (e.g. "man in a blue shirt"); an empty list
when nobody is visible. Never invent names or identities.
6. `notable_objects`: at most five clearly visible salient objects; an empty list if none.
7. `setting`: the visible location or environment in a few words, or null when unclear.
8. The transcript is context only: never repeat speech in `summary` unless it is also visible
on screen, and never assume the image shows what was being said.
9. If the image is unusable (black, blank, blurred or corrupted), say so in `summary` and use
`shot_type` "other".
Fill every field, using null or an empty list instead of inventing content."""
#: Maximum number of characters of transcript context handed to the model per shot.
MAX_TRANSCRIPT_CHARS = 1200
#: PLAN §3.2: 448-576 px frames keep an 8K llama-server context affordable.
VISION_MAX_WIDTH = 576
class FrameNote(BaseModel):
"""One timestamped observation about a frame of an analyzed moment."""
timestamp: float
description: str
class MomentDescription(BaseModel):
"""Structured VLM reading of up to four frames of one moment (single request)."""
summary: str
on_screen_text: str | None = None
frames: list[FrameNote] = []
MOMENT_INSTRUCTIONS = """\
You describe a short window of a video from a few keyframes. The request contains the window's
time range and up to four frames in chronological order, each preceded by its timestamp.
Describe only what is visible. Never guess names, identities or events. Transcribe on-screen
text verbatim in `on_screen_text` (null when none is readable). In `summary`, give one or two
sentences about what changes across the frames. In `frames`, add one short factual note per frame
using the timestamp that preceded it. If a frame is black, blank or blurred, say so."""
def _mmss(seconds: float) -> str:
"""Format ``seconds`` as a compact ``MM:SS`` (or ``H:MM:SS`` past an hour) marker."""
total = max(int(seconds), 0)
hours, rest = divmod(total, 3600)
minutes, secs = divmod(rest, 60)
if hours:
return f"{hours:d}:{minutes:02d}:{secs:02d}"
return f"{minutes:02d}:{secs:02d}"
def transcript_slice_for(
shot: Shot, transcript: Transcript | None, *, max_chars: int = MAX_TRANSCRIPT_CHARS
) -> str:
"""Return the speaker-labelled, timestamped transcript text spoken during ``shot``.
Segments overlapping ``[shot.start, shot.end)`` are rendered one per line as
``[MM:SS] S1: text``. When a segment carries word timings the words whose midpoint falls
inside the shot are used, so a sentence straddling a cut is split at the cut. Falls back to
``shot.transcript_slice`` when no transcript is available (or it holds no overlap).
"""
if transcript is None:
return shot.transcript_slice.strip()
lines: list[str] = []
for segment in transcript.segments:
if segment.end <= shot.start or segment.start >= shot.end:
continue
if segment.words:
text = " ".join(
word.text.strip()
for word in segment.words
if shot.start <= (word.start + word.end) / 2 < shot.end
)
else:
text = segment.text
text = " ".join(text.split())
if not text:
continue
marker = f"[{_mmss(max(segment.start, shot.start))}]"
speaker = f" {segment.speaker}:" if segment.speaker else ""
lines.append(f"{marker}{speaker} {text}")
if not lines:
return shot.transcript_slice.strip()
joined = "\n".join(lines)
if len(joined) > max_chars:
joined = joined[:max_chars].rstrip() + " [...]"
return joined
def frame_prompt(shot: Shot, prev_summary: str | None = None, transcript_slice: str = "") -> str:
"""Build the text part of the per-shot request (pure; no I/O).
``prev_summary`` is the previous shot's summary (``None`` for the first shot) and
``transcript_slice`` the already formatted speech for this shot's time range.
"""
duration = max(shot.end - shot.start, 0.0)
lines = [
f"Shot index: {shot.index}",
f"Time range: {_mmss(shot.start)} - {_mmss(shot.end)} ({duration:.1f} s)",
]
if prev_summary and prev_summary.strip():
lines.append(f"Previous shot summary: {prev_summary.strip()}")
else:
lines.append("Previous shot summary: none (this is the first described shot)")
if transcript_slice.strip():
lines.append("Transcript spoken during this shot:")
lines.append(transcript_slice.strip())
else:
lines.append("Transcript spoken during this shot: none")
lines.append("Describe the attached keyframe of this shot.")
return "\n".join(lines)
def build_describer_agent(model: Model) -> Agent[None, ShotDescription]:
"""Build the structured-output describer agent for ``model`` (no request is made)."""
return Agent(
model,
name="shot-describer",
output_type=ShotDescription,
instructions=DESCRIBER_INSTRUCTIONS,
model_settings=ModelSettings(temperature=0.1, max_tokens=400, max_retries=0),
retries={"output": 2},
)
def _targets_local_server(spec: str) -> bool:
"""True when :func:`video_analyse.llm.build_model` routes ``spec`` to llama-server."""
spec = (spec or "").strip()
if not spec or spec == "test": # the bare "test" spec builds pydantic-ai's TestModel
return False
prefix, sep, _rest = spec.partition(":")
if not sep or prefix == llm.LOCAL_PREFIX:
return True # bare model name or explicit "local:<name>"
try:
infer_provider_class(prefix)
except ValueError:
return True # unknown "vendor:name" prefix stays a local model name (llm.build_model)
except ImportError:
return False # known hosted provider whose optional SDK is missing: not local
return False
def _prepare_image_bytes(data: bytes, *, max_width: int = VISION_MAX_WIDTH) -> bytes:
"""Downscale a JPEG to ``max_width`` (blocking; run in a worker thread)."""
if max_width <= 0:
return data
try:
with io.BytesIO(data) as buffer:
from PIL import Image
with Image.open(buffer) as image:
if image.width <= max_width:
return data
height = max(round(image.height * max_width / image.width), 1)
resized = image.convert("RGB").resize((max_width, height))
output = io.BytesIO()
resized.save(output, format="JPEG", quality=85)
return output.getvalue()
except (OSError, ValueError) as exc:
logger.warning("could not downscale a keyframe (%s); sending it unchanged", exc)
return data
async def _image_part(keyframe: Path, *, hosted: bool) -> BinaryImage:
"""Read, downscale and wrap one keyframe; hosted models get ``detail: low``."""
data = await asyncio.to_thread(keyframe.read_bytes)
data = await asyncio.to_thread(_prepare_image_bytes, data)
metadata = {"detail": "low"} if hosted else None
return BinaryImage(data=data, media_type="image/jpeg", vendor_metadata=metadata)
def _llama_hint(settings: Settings, spec: str) -> str:
"""RuntimeError message with the exact llama-server startup command."""
return (
f"llama-server is not reachable at {settings.llama_server_url}, but the vision model "
f"{spec!r} is served by it. Start it with:\n\n{LLAMA_SERVER_COMMAND}\n\n"
"Then re-run the description stage. To describe shots without a local server, point "
"VA_VLM_MODEL at a hosted model spec (for example VA_VLM_MODEL=deepseek:deepseek-flash)."
)
async def llama_server_up(settings: Settings) -> bool:
"""True when the local llama-server answers ``GET {llama_server_url}/models``.
Thin alias of :func:`video_analyse.llm.llama_server_up` (2 s timeout, never raises); the
local health check used by :func:`describe_shots` and the CLI.
"""
return await llm.llama_server_up(settings)
async def describe_shots(
shots: list[Shot], transcript: Transcript | None, *, settings: Settings
) -> list[Shot]:
"""Describe every shot's keyframe and fill ``Shot.description``; returns the same list.
One agent call per shot, sequentially (the local VLM is CPU-bound). The model is built from
``settings.resolved_vlm()``; when that spec is served by the local llama-server the server is
health-checked once up front and a ``RuntimeError`` carrying the startup command is raised if
it is down. Shots without a readable keyframe file are logged and left undescribed.
"""
if not shots:
return shots
if not any(shot.keyframe is not None and shot.keyframe.is_file() for shot in shots):
logger.warning("no shot has a readable keyframe; nothing to describe")
return shots
spec = settings.resolved_vlm()
if _targets_local_server(spec) and not await llama_server_up(settings):
raise RuntimeError(_llama_hint(settings, spec))
agent = build_describer_agent(llm.build_model(spec, settings=settings))
hosted = not _targets_local_server(spec)
# The server serialises requests on CPU; keep that property explicit if this ever changes.
limiter = asyncio.Semaphore(1)
previous = shots[0].description.summary if shots[0].description else None
completed = 0
for shot in shots:
keyframe = shot.keyframe
if keyframe is None or not keyframe.is_file():
logger.warning(
"shot %s has no readable keyframe (%s); left undescribed", shot.index, keyframe
)
continue
# Persist exactly the speech context the description was generated from (PLAN §4).
slice_text = transcript_slice_for(shot, transcript)
shot.transcript_slice = slice_text
prompt = frame_prompt(shot, previous, slice_text)
image = await _image_part(keyframe, hosted=hosted)
logger.info("describing shot %s (%.1f-%.1f s)", shot.index, shot.start, shot.end)
try:
async with limiter:
result = await agent.run([prompt, image])
except Exception as exc: # re-raised with the shot context; the cause stays chained
raise RuntimeError(f"describing shot {shot.index} failed: {exc}") from exc
shot.description = result.output
previous = result.output.summary
completed += 1
logger.info("described %d/%d shots with %s", completed, len(shots), spec)
return shots
async def describe_moment(
frames: list[bytes], timestamps: list[float], *, settings: Settings
) -> MomentDescription:
"""Describe up to four moment frames in one VLM request (analyze_moment zoom-in).
Args:
frames: JPEG bytes in chronological order (at most four).
timestamps: one timestamp per frame, in seconds.
settings: runtime settings; ``settings.resolved_vlm()`` picks the model.
Returns:
A validated :class:`MomentDescription`.
Raises:
ValueError: the frame/timestamp lists differ in length or are empty.
RuntimeError: the local llama-server is unreachable or the model call fails.
"""
if not frames:
raise ValueError("describe_moment needs at least one frame")
if len(frames) != len(timestamps):
raise ValueError(
f"describe_moment got {len(frames)} frame(s) but {len(timestamps)} timestamp(s)"
)
spec = settings.resolved_vlm()
hosted = not _targets_local_server(spec)
if not hosted and not await llama_server_up(settings):
raise RuntimeError(_llama_hint(settings, spec))
agent = Agent(
llm.build_model(spec, settings=settings),
name="moment-describer",
output_type=MomentDescription,
instructions=MOMENT_INSTRUCTIONS,
model_settings=ModelSettings(temperature=0.1, max_tokens=600, max_retries=0),
retries={"output": 2},
)
lines = [
f"Window: {_mmss(timestamps[0])} - {_mmss(timestamps[-1])} "
f"({len(frames)} frame(s), chronological)",
"Frames:",
]
parts: list[object] = []
for index, (frame, stamp) in enumerate(zip(frames, timestamps, strict=True)):
lines.append(f"- frame {index}: {stamp:.3f} s ([{_mmss(stamp)}])")
data = await asyncio.to_thread(_prepare_image_bytes, frame)
metadata = {"detail": "low"} if hosted else None
parts.append(BinaryImage(data=data, media_type="image/jpeg", vendor_metadata=metadata))
prompt = "\n".join(lines) + "\n\nDescribe this moment."
try:
result = await agent.run([prompt, *parts])
except Exception as exc:
raise RuntimeError(f"describing the moment with {spec} failed: {exc}") from exc
return result.output
+47
View File
@@ -0,0 +1,47 @@
"""Shared pytest fixtures for the video-analyse test suite."""
from __future__ import annotations
import os
import shutil
import subprocess
from pathlib import Path
import pytest
# Keep pydantic-ai's one-off banner out of test output.
os.environ.setdefault("PYDANTIC_AI_NO_BANNER", "1")
FFMPEG = shutil.which("ffmpeg")
# Exact generator command (synthetic 640x360 @ 12 fps, 10 s, 440 Hz tone).
FFMPEG_ARGS = [
"-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",
]
@pytest.fixture(scope="session")
def sample_video(tmp_path_factory: pytest.TempPathFactory) -> Path:
"""Generate a 10 s test video (video + audio) once per test session."""
if FFMPEG is None:
pytest.skip("ffmpeg not found on PATH; cannot generate sample_video")
out = tmp_path_factory.mktemp("media") / "sample.mp4"
subprocess.run([FFMPEG, *FFMPEG_ARGS, str(out)], check=True, capture_output=True)
assert out.is_file() and out.stat().st_size > 0, "ffmpeg produced no output"
return out
+316
View File
@@ -0,0 +1,316 @@
"""Tests for the content-addressed stage cache (``video_analyse.cache``).
Everything here is local: file hashing uses the synthetic ``sample_video`` fixture or
small temporary files, and the model round-trips use the pydantic models from
``video_analyse.models``. No network access, no model downloads.
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import pytest
from video_analyse import cache as cache_module
from video_analyse.cache import StageCache
from video_analyse.models import MediaInfo, Segment, Transcript, Word
@pytest.fixture
def cache(tmp_path: Path) -> StageCache:
"""Cache rooted at a temporary directory (nothing is created eagerly)."""
return StageCache(tmp_path / "cache")
@pytest.fixture
def sample_media(sample_video: Path) -> MediaInfo:
"""A MediaInfo for the conftest sample video (the fixture skips without ffmpeg)."""
return MediaInfo(
path=sample_video,
source=str(sample_video),
duration=10.0,
width=640,
height=360,
fps=12.0,
has_audio=True,
size_bytes=sample_video.stat().st_size,
format="mov,mp4,m4a,3gp,3g2,mj2",
video_codec="h264",
audio_codec="aac",
extra={"fixture": True},
)
# --------------------------------------------------------------------------- #
# hashing
# --------------------------------------------------------------------------- #
def test_source_hash_matches_hashlib_for_a_real_file(cache: StageCache, sample_video: Path) -> None:
expected = hashlib.sha256(sample_video.read_bytes()).hexdigest()
assert cache.source_hash(sample_video) == expected
assert cache.source_hash(sample_video) == cache.source_hash(sample_video)
assert len(expected) == 64
def test_source_hash_streams_regardless_of_chunk_size(
cache: StageCache, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = bytes(range(256)) * 8193 # 2 MiB + 256 bytes: several chunks, odd tail
path = tmp_path / "blob.mp4"
path.write_bytes(payload)
expected = hashlib.sha256(payload).hexdigest()
assert cache.source_hash(path) == expected
monkeypatch.setattr(cache_module, "HASH_CHUNK_SIZE", 7)
assert cache.source_hash(path) == expected
monkeypatch.setattr(cache_module, "HASH_CHUNK_SIZE", 2**20)
assert cache.source_hash(path) == expected
def test_source_hash_changes_with_content(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "clip.mp4"
path.write_bytes(b"first version")
first = cache.source_hash(path)
path.write_bytes(b"second version")
assert cache.source_hash(path) != first
def test_source_hash_rejects_missing_files_and_directories(
cache: StageCache, tmp_path: Path
) -> None:
with pytest.raises(ValueError, match="missing file"):
cache.source_hash(tmp_path / "nope.mp4")
with pytest.raises(ValueError, match="non-file path"):
cache.source_hash(tmp_path)
# --------------------------------------------------------------------------- #
# stage keys
# --------------------------------------------------------------------------- #
def test_stage_key_is_stable_and_param_order_insensitive(cache: StageCache) -> None:
first = cache.stage_key("transcribe", {"backend": "whisper", "model": "tiny"})
second = cache.stage_key("transcribe", {"model": "tiny", "backend": "whisper"})
assert first == second
assert first == cache.stage_key("transcribe", {"backend": "whisper", "model": "tiny"})
assert len(first) == 64
int(first, 16) # lowercase hex, parseable
def test_stage_key_is_sensitive_to_every_parameter(cache: StageCache) -> None:
base = cache.stage_key("shots", {"max_shots": 64, "detector": "adaptive"})
assert cache.stage_key("shots", {"max_shots": 65, "detector": "adaptive"}) != base
assert cache.stage_key("shots", {"max_shots": 64, "detector": "content"}) != base
assert cache.stage_key("report", {"max_shots": 64, "detector": "adaptive"}) != base
assert cache.stage_key("shots", {"max_shots": 64}) != base
assert cache.stage_key("shots", {"max_shots": 64, "detector": "adaptive", "x": None}) != base
assert cache.stage_key("shots") == cache.stage_key("shots", {})
def test_stage_key_stringifies_non_json_values(cache: StageCache, tmp_path: Path) -> None:
media = tmp_path / "a.mp4"
key = cache.stage_key("probe", {"path": media, "opts": (1, 2)})
# Paths render through str(); tuples become JSON arrays like lists do.
assert key == cache.stage_key("probe", {"path": str(media), "opts": [1, 2]})
assert key != cache.stage_key("probe", {"path": str(media), "opts": "(1, 2)"})
assert key != cache.stage_key("probe", {"path": str(media)})
def test_stage_key_rejects_bad_input(cache: StageCache) -> None:
for bad_name in ("", "bad name", "../escape", "stage:1", "-leading"):
with pytest.raises(ValueError, match="invalid stage name"):
cache.stage_key(bad_name, {"a": 1})
with pytest.raises(TypeError, match="params must be a mapping"):
cache.stage_key("probe", ["not", "a", "mapping"]) # type: ignore[arg-type]
# --------------------------------------------------------------------------- #
# path layout
# --------------------------------------------------------------------------- #
def test_stage_path_layout(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
key = cache.stage_key("transcribe", {"audio_sha256": digest})
path = cache.stage_path(digest, "transcribe", key)
assert path == cache.cache_dir / digest[:16] / f"stage-transcribe-{key}.json"
assert path.parent == cache.source_dir(digest)
assert path.parent.name == digest[:16]
assert len(digest[:16]) == cache_module.SOURCE_HASH_PREFIX_LENGTH
def test_asset_paths_share_the_source_dir(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
root = cache.cache_dir / digest[:16]
assert cache.source_dir(digest) == root
assert cache.asset_dir(digest) == root
assert cache.audio_path(digest) == root / "audio.wav"
assert cache.keyframes_dir(digest) == root / "keyframes"
assert cache.keyframe_path(digest, 3) == root / "keyframes" / "shot-3.jpg"
assert cache.artifacts_path(digest) == root / "artifacts.json"
def test_paths_accept_short_prefixes_and_uppercase_digests(
cache: StageCache, sample_video: Path
) -> None:
digest = cache.source_hash(sample_video)
assert cache.source_dir(digest[:16]) == cache.source_dir(digest)
assert cache.source_dir(digest.upper()) == cache.source_dir(digest)
with pytest.raises(ValueError, match="invalid source sha256"):
cache.source_dir(digest[:15])
with pytest.raises(ValueError, match="invalid source sha256"):
cache.source_dir("z" * 16)
with pytest.raises(TypeError, match="source_sha must be a string"):
cache.source_dir(42) # type: ignore[arg-type]
def test_paths_reject_unsafe_stage_keys_and_indices(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
assert (
cache.stage_path(digest, "probe", "0123456789abcdef").name
== "stage-probe-0123456789abcdef.json"
)
for bad_key in ("", "../escape", "0123456789ABCDEF", "zz", "0" * 65):
with pytest.raises(ValueError, match="invalid stage key"):
cache.stage_path(digest, "probe", bad_key)
for bad_index in (-1, 1.5, True):
with pytest.raises(ValueError, match="shot_index"):
cache.keyframe_path(digest, bad_index) # type: ignore[arg-type]
def test_cache_dir_expands_the_home_directory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
cache = StageCache("~/video-cache")
assert cache.cache_dir == tmp_path / "video-cache"
assert not cache.cache_dir.exists() # constructing a cache creates nothing
# --------------------------------------------------------------------------- #
# model / JSON round-trips
# --------------------------------------------------------------------------- #
def test_save_and_load_model_round_trip(
cache: StageCache, sample_video: Path, sample_media: MediaInfo
) -> None:
digest = cache.source_hash(sample_video)
key = cache.stage_key("probe", {"video_sha256": digest})
path = cache.stage_path(digest, "probe", key)
cache.save_model(path, sample_media)
assert path.is_file()
assert path.read_text(encoding="utf-8").endswith("\n")
assert json.loads(path.read_text(encoding="utf-8"))["duration"] == 10.0
loaded = cache.load_model(path, MediaInfo)
assert loaded == sample_media
assert loaded is not None and isinstance(loaded.path, Path)
def test_save_and_load_nested_models(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "nested" / "artifact.json"
transcript = Transcript(
language="en",
duration=2.0,
segments=[
Segment(
start=0.0,
end=1.0,
text="hello world",
words=[Word(text="hello", start=0.0, end=0.5, probability=0.9)],
speaker="S1",
)
],
)
cache.save_model(path, transcript)
assert path.parent.is_dir()
assert cache.load_model(path, Transcript) == transcript
def test_save_model_rejects_plain_values(cache: StageCache, tmp_path: Path) -> None:
with pytest.raises(TypeError, match="pydantic BaseModel"):
cache.save_model(tmp_path / "x.json", {"not": "a model"}) # type: ignore[arg-type]
def test_load_model_handles_missing_and_corrupt_artifacts(
cache: StageCache, tmp_path: Path
) -> None:
missing = tmp_path / "missing.json"
assert cache.load_model(missing, MediaInfo) is None
corrupt = tmp_path / "corrupt.json"
corrupt.write_text("{not json", encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaInfo"):
cache.load_model(corrupt, MediaInfo)
wrong_shape = tmp_path / "wrong.json"
wrong_shape.write_text('{"duration": 1.0}', encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaInfo"):
cache.load_model(wrong_shape, MediaInfo)
with pytest.raises(TypeError, match="model_type must be a pydantic BaseModel"):
cache.load_model(missing, dict) # type: ignore[arg-type]
def test_save_and_load_json_payloads(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "raw" / "payload.json"
payload = {"turns": [{"start": 0.0, "end": 1.5, "speaker": "S1"}], "path": tmp_path}
cache.save_json(path, payload)
assert json.loads(path.read_text(encoding="utf-8"))["path"] == str(tmp_path)
assert cache.load_json(path) == {
"turns": [{"start": 0.0, "end": 1.5, "speaker": "S1"}],
"path": str(tmp_path),
}
assert cache.load_json(tmp_path / "absent.json") is None
path.write_text("[", encoding="utf-8")
with pytest.raises(ValueError, match="not valid JSON"):
cache.load_json(path)
# --------------------------------------------------------------------------- #
# existence / invalidation
# --------------------------------------------------------------------------- #
def test_exists_only_true_for_regular_files(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "artifact.json"
assert cache.exists(path) is False
path.write_text("{}", encoding="utf-8")
assert cache.exists(path) is True
assert cache.exists(tmp_path) is False
def test_clear_stage_removes_only_that_stage(
cache: StageCache, sample_video: Path, sample_media: MediaInfo
) -> None:
digest = cache.source_hash(sample_video)
keep = cache.stage_path(digest, "probe", cache.stage_key("probe", {"video_sha256": digest}))
for key in ("a" * 64, "b" * 64):
cache.save_model(cache.stage_path(digest, "report", key), sample_media)
cache.save_model(keep, sample_media)
assert cache.clear_stage(digest, "report") == 2
assert cache.clear_stage(digest, "report") == 0
assert keep.is_file()
assert list(cache.source_dir(digest).glob("stage-report-*.json")) == []
assert list(cache.source_dir(digest).glob("stage-probe-*.json")) == [keep]
def test_writes_are_atomic_and_leave_no_temporary_files(
cache: StageCache, tmp_path: Path, sample_media: MediaInfo
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
assert [entry.name for entry in tmp_path.iterdir()] == ["artifact.json"]
+598
View File
@@ -0,0 +1,598 @@
"""CLI tests: typer wiring, help text, JSON output and error mapping.
No network and no model is touched. The media tests use the synthetic ``sample_video``
fixture; every model-dependent command runs against a stub ``Pipeline`` (patched at
``video_analyse.cli.Pipeline``) that returns hand-built artifacts.
"""
from __future__ import annotations
import json
import shutil
import sys
import types
from pathlib import Path
from typing import Any
import pytest
from click.testing import Result
from typer.testing import CliRunner
from video_analyse import __version__, cli
from video_analyse.config import Settings
from video_analyse.ingest import IngestResult
from video_analyse.models import (
Artifacts,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.synthesis import AnswerResult
FFMPEG = shutil.which("ffmpeg")
FFPROBE = shutil.which("ffprobe")
needs_ffprobe = pytest.mark.skipif(FFPROBE is None, reason="ffprobe not on PATH")
needs_ffmpeg_tools = pytest.mark.skipif(
FFMPEG is None or FFPROBE is None, reason="ffmpeg/ffprobe not on PATH"
)
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
COMMANDS = (
"version",
"fetch",
"probe",
"transcribe",
"diarize",
"shots",
"describe",
"analyse",
"ask",
"doctor",
"serve-mcp",
)
COMMAND_OPTIONS: dict[str, tuple[str, ...]] = {
"fetch": ("--quality", "--json"),
"probe": ("--json",),
"transcribe": ("--backend", "--lang", "--diarize", "--no-diarize", "--format", "--json"),
"diarize": ("--backend", "--json"),
"shots": ("--detector", "--max-shots", "--json"),
"describe": ("--model", "--json"),
"analyse": ("--no-diarize", "--out", "--force", "--json"),
"ask": ("--json",),
"doctor": ("--json",),
"serve-mcp": ("--transport", "--port"),
}
@pytest.fixture(autouse=True)
def _isolated_environment(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep tests independent of the developer's environment and real cache."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("VA_CACHE_DIR", str(tmp_path / "cache"))
def _invoke(*args: str) -> Result:
"""Invoke the CLI with a fixed terminal width so rich help text does not wrap."""
runner = CliRunner()
return runner.invoke(cli.app, list(args), env={"COLUMNS": "120", "TERM": "dumb"})
def _install_stub_pipeline(
monkeypatch: pytest.MonkeyPatch, artifacts: Artifacts
) -> list[dict[str, Any]]:
"""Patch ``cli.Pipeline`` with an async stub and return the recorded calls."""
calls: list[dict[str, Any]] = []
class StubPipeline:
def __init__(self, settings: Settings, **options: Any) -> None:
self.settings = settings
self.options = options
async def run(
self,
source: str,
*,
want: Any = None,
force: bool = False,
progress: Any = None,
) -> Artifacts:
calls.append(
{
"settings": self.settings,
"options": self.options,
"source": source,
"want": set(want or ()),
"force": force,
"progress": progress,
}
)
return artifacts
monkeypatch.setattr(cli, "Pipeline", StubPipeline)
return calls
def _sample_transcript() -> Transcript:
"""A two-speaker transcript with word timings and speaker turns."""
return Transcript(
language="en",
duration=3.0,
backend="stub",
model="stub-model",
segments=[
Segment(
start=0.0,
end=1.5,
text="Hello there.",
speaker="S1",
words=[
Word(text="Hello", start=0.0, end=0.6),
Word(text="there.", start=0.6, end=1.4),
],
),
Segment(start=1.5, end=3.0, text="General Kenobi.", speaker="S2"),
],
speaker_turns=[
SpeakerTurn(start=0.0, end=1.5, speaker="S1"),
SpeakerTurn(start=1.5, end=3.0, speaker="S2"),
],
)
def _sample_shots() -> list[Shot]:
"""Two shots, the first one described."""
return [
Shot(
index=0,
start=0.0,
end=4.0,
description=ShotDescription(
summary="A test pattern fills the frame.", shot_type="other"
),
),
Shot(index=1, start=4.0, end=10.0),
]
def _sample_report(source: str) -> VideoReport:
"""A minimal validated report used by the analyse/ask stubs."""
return VideoReport(
source=source,
title="Sample analysis",
duration=10.0,
summary="A synthetic test pattern with a tone.",
topics=["testing"],
people=[],
highlights=[],
shots=[Shot(index=0, start=0.0, end=10.0)],
transcript=None,
metadata={},
)
def _stub_artifacts(tmp_path: Path, *, transcript: Transcript | None = None) -> Artifacts:
"""Artifacts shell rooted in ``tmp_path`` for the stub pipeline."""
return Artifacts(
source=str(tmp_path / "clip.mp4"),
workdir=tmp_path / "work",
transcript=transcript,
shots=_sample_shots(),
)
# --------------------------------------------------------------------------- #
# help, version, argument parsing
# --------------------------------------------------------------------------- #
def test_root_help_lists_every_command() -> None:
result = _invoke("--help")
assert result.exit_code == 0, result.output
assert "Usage" in result.stdout
for command in COMMANDS:
assert command in result.stdout
def test_bare_invocation_prints_help() -> None:
result = _invoke()
assert result.exit_code == 0, result.output
assert "Usage" in result.stdout
@pytest.mark.parametrize(("command", "options"), sorted(COMMAND_OPTIONS.items()))
def test_command_help_lists_its_options(command: str, options: tuple[str, ...]) -> None:
result = _invoke(command, "--help")
assert result.exit_code == 0, result.output
for option in options:
assert option in result.stdout, f"{option} missing from `va {command} --help`"
def test_version_is_available_as_flag_and_command() -> None:
flagged = _invoke("--version")
assert flagged.exit_code == 0, flagged.output
assert flagged.stdout.strip() == __version__
command = _invoke("version")
assert command.exit_code == 0, command.output
assert command.stdout.strip() == __version__
def test_transcribe_rejects_unknown_format(tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
result = _invoke("transcribe", str(media), "--format", "vtt")
assert result.exit_code != 0
assert "--format" in result.output
def test_shots_rejects_unknown_detector(tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
result = _invoke("shots", str(media), "--detector", "content")
assert result.exit_code == 1, result.output
assert "adaptive" in result.output
def test_serve_mcp_rejects_unknown_transport() -> None:
result = _invoke("serve-mcp", "--transport", "websocket")
assert result.exit_code != 0
assert "--transport" in result.output
@pytest.mark.parametrize(
("extra_args", "expected"),
[
((), {"transport": "stdio", "host": "127.0.0.1", "port": 8000}),
(
("--transport", "http", "--port", "9100"),
{"transport": "http", "host": "127.0.0.1", "port": 9100},
),
],
)
def test_serve_mcp_dispatches_to_the_server_entry_point(
monkeypatch: pytest.MonkeyPatch, extra_args: tuple[str, ...], expected: dict[str, Any]
) -> None:
calls: list[dict[str, Any]] = []
fake_module = types.ModuleType("video_analyse.mcp_server")
fake_module.run = lambda **kwargs: calls.append(kwargs) # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "video_analyse.mcp_server", fake_module)
result = _invoke("serve-mcp", *extra_args)
assert result.exit_code == 0, result.output
assert calls == [expected]
# --------------------------------------------------------------------------- #
# real media: probe (ffprobe only, no models)
# --------------------------------------------------------------------------- #
@needs_ffprobe
def test_probe_json_on_sample_video(sample_video: Path) -> None:
result = _invoke("probe", str(sample_video), "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout) # stdout is exactly one JSON document
for key in (
"path",
"source",
"duration",
"width",
"height",
"fps",
"has_audio",
"size_bytes",
"extra",
):
assert key in payload
assert Path(payload["path"]) == sample_video.resolve()
assert payload["duration"] == pytest.approx(10.0, abs=0.5)
assert payload["width"] == 640
assert payload["height"] == 360
assert payload["has_audio"] is True
# The global --json flag (before the subcommand) produces the same document.
global_result = _invoke("--json", "probe", str(sample_video))
assert global_result.exit_code == 0, global_result.output
assert json.loads(global_result.stdout)["has_audio"] is True
@needs_ffprobe
def test_probe_human_output_on_sample_video(sample_video: Path) -> None:
result = _invoke("probe", str(sample_video))
assert result.exit_code == 0, result.output
assert "Media info" in result.stdout
assert "640x360" in result.stdout
assert "00:10" in result.stdout
@pytest.mark.parametrize("command", ["probe", "transcribe", "diarize", "shots", "analyse"])
def test_missing_file_exits_nonzero_with_message(command: str, tmp_path: Path) -> None:
missing = tmp_path / "missing.mp4"
result = _invoke(command, str(missing))
assert result.exit_code == 1, result.output
assert "missing.mp4" in result.output
assert "not found" in result.output.lower()
# --------------------------------------------------------------------------- #
# model-dependent commands against a stub pipeline
# --------------------------------------------------------------------------- #
def test_transcribe_json_and_srt_from_stub_pipeline(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
transcript = _sample_transcript()
artifacts = Artifacts(source=str(media), workdir=tmp_path / "work", transcript=transcript)
calls = _install_stub_pipeline(monkeypatch, artifacts)
json_result = _invoke(
"transcribe",
str(media),
"--diarize",
"--lang",
"en",
"--backend",
"whisper",
"--json",
)
assert json_result.exit_code == 0, json_result.output
payload = json.loads(json_result.stdout)
assert payload["language"] == "en"
assert [segment["text"] for segment in payload["segments"]] == [
"Hello there.",
"General Kenobi.",
]
assert payload["segments"][0]["speaker"] == "S1"
assert calls[0]["want"] == {"probe", "audio", "transcribe", "diarize"}
assert calls[0]["settings"].language == "en"
assert calls[0]["settings"].resolved_stt() == "whisper"
assert calls[0]["settings"].diarize is True
srt_result = _invoke("transcribe", str(media), "--format", "srt")
assert srt_result.exit_code == 0, srt_result.output
assert srt_result.stdout.startswith("1\n00:00:00,000 --> 00:00:01,500\n[S1] Hello there.")
assert "[S2] General Kenobi." in srt_result.stdout
assert calls[1]["want"] == {"probe", "audio", "transcribe"}
def test_transcribe_honours_va_language_unless_lang_is_passed(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Omitting --lang must not clobber VA_LANGUAGE; an explicit 'auto' still does."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
artifacts = Artifacts(
source=str(media), workdir=tmp_path / "work", transcript=_sample_transcript()
)
calls = _install_stub_pipeline(monkeypatch, artifacts)
monkeypatch.setenv("VA_LANGUAGE", "en")
assert _invoke("transcribe", str(media), "--json").exit_code == 0
assert calls[-1]["settings"].language == "en"
assert _invoke("transcribe", str(media), "--lang", "auto", "--json").exit_code == 0
assert calls[-1]["settings"].language is None
def test_shots_and_describe_json_from_stub_pipeline(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
calls = _install_stub_pipeline(monkeypatch, _stub_artifacts(tmp_path))
shots_result = _invoke("shots", str(media), "--max-shots", "8", "--json")
assert shots_result.exit_code == 0, shots_result.output
payload = json.loads(shots_result.stdout)
assert [shot["index"] for shot in payload["shots"]] == [0, 1]
assert calls[0]["options"] == {"max_shots": 8}
assert calls[0]["want"] == {"probe", "shots"}
describe_result = _invoke("describe", str(media), "--model", "stub:vlm", "--json")
assert describe_result.exit_code == 0, describe_result.output
payload = json.loads(describe_result.stdout)
assert payload["shots"][0]["description"]["summary"].startswith("A test pattern")
assert calls[1]["settings"].vlm_model == "stub:vlm"
assert calls[1]["want"] == {"probe", "shots", "describe"}
def test_diarize_json_from_stub_pipeline(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
transcript = _sample_transcript()
artifacts = Artifacts(source=str(media), workdir=tmp_path / "work", transcript=transcript)
calls = _install_stub_pipeline(monkeypatch, artifacts)
result = _invoke("diarize", str(media), "--backend", "sherpa", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["speaker_turns"][0]["speaker"] == "S1"
assert "diarize" in calls[0]["want"]
assert calls[0]["settings"].diarize is True
assert calls[0]["settings"].diarize_backend == "sherpa"
def test_analyse_writes_markdown_and_honours_no_diarize(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media))
artifacts = Artifacts(
source=str(media),
workdir=tmp_path / "work",
shots=report.shots,
report=report,
)
calls = _install_stub_pipeline(monkeypatch, artifacts)
out = tmp_path / "out" / "report.md"
result = _invoke("analyse", str(media), "--no-diarize", "--out", str(out), "--force")
assert result.exit_code == 0, result.output
assert out.is_file()
assert out.with_suffix(".json").is_file()
written = json.loads(out.with_suffix(".json").read_text(encoding="utf-8"))
assert written["title"] == "Sample analysis"
assert "JSON report written to" in result.stdout
markdown = out.read_text(encoding="utf-8")
assert markdown.startswith("# Sample analysis")
assert "A synthetic test pattern with a tone." in markdown
assert "Markdown report written to" in result.stdout
call = calls[0]
assert "diarize" not in call["want"]
assert "report" in call["want"]
assert call["force"] is True
assert call["settings"].diarize is False
json_result = _invoke("analyse", str(media), "--out", str(out.parent / "again.md"), "--json")
assert json_result.exit_code == 0, json_result.output
payload = json.loads(json_result.stdout)
assert payload["title"] == "Sample analysis"
assert payload["topics"] == ["testing"]
def test_analyse_writes_the_srt_artifact_when_a_transcript_exists(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media)).model_copy(update={"transcript": _sample_transcript()})
artifacts = Artifacts(
source=str(media), workdir=tmp_path / "work", report=report, transcript=report.transcript
)
_install_stub_pipeline(monkeypatch, artifacts)
out = tmp_path / "out" / "report.md"
result = _invoke("analyse", str(media), "--out", str(out))
assert result.exit_code == 0, result.output
srt = out.with_suffix(".srt")
assert srt.is_file()
assert srt.read_text(encoding="utf-8").startswith("1\n00:00:00,000 --> 00:00:01,500")
assert "Transcript written to" in result.stdout
def test_ask_prints_grounded_answer(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
report = _sample_report(str(media))
artifacts = Artifacts(source=str(media), workdir=tmp_path / "work", report=report)
calls = _install_stub_pipeline(monkeypatch, artifacts)
async def fake_answer(
report_arg: VideoReport,
question: str,
*,
settings: Settings,
cache: Any = None,
) -> AnswerResult:
assert report_arg is report
return AnswerResult(answer=f"Answer to: {question}", cached=False)
monkeypatch.setattr(cli, "_answer", fake_answer)
result = _invoke("ask", str(media), "what", "happens?", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["question"] == "what happens?"
assert payload["answer"] == "Answer to: what happens?"
assert calls[0]["want"] == {"report"}
def test_ask_without_cached_report_exits_nonzero(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
artifacts = Artifacts(source=str(media), workdir=tmp_path / "work")
_install_stub_pipeline(monkeypatch, artifacts)
result = _invoke("ask", str(media), "why?")
assert result.exit_code == 1, result.output
assert "va analyse" in result.output
def test_pipeline_failure_maps_to_exit_code_1(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
class FailingPipeline:
def __init__(self, settings: Settings, **options: Any) -> None:
self.settings = settings
async def run(self, *args: Any, **kwargs: Any) -> Artifacts:
raise RuntimeError("llama-server is not reachable at http://127.0.0.1:8080/v1")
monkeypatch.setattr(cli, "Pipeline", FailingPipeline)
media = tmp_path / "clip.mp4"
media.write_bytes(b"not a real video")
result = _invoke("describe", str(media))
assert result.exit_code == 1, result.output
assert "llama-server is not reachable" in result.output
def test_fetch_reports_downloaded_file(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
downloaded = tmp_path / "downloads" / "demo.mp4"
downloaded.parent.mkdir(parents=True)
downloaded.write_bytes(b"video bytes")
async def fake_fetch(url: str, *, cache_dir: Path, quality: int) -> IngestResult:
assert url == "https://example.invalid/v"
assert quality == 720
return IngestResult(path=downloaded, info={"id": "abc"}, downloaded=True, title="Demo")
monkeypatch.setattr(cli, "_fetch_source", fake_fetch)
result = _invoke("fetch", "https://example.invalid/v", "--quality", "720", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["title"] == "Demo"
assert payload["downloaded"] is True
assert Path(payload["path"]) == downloaded
# --------------------------------------------------------------------------- #
# doctor
# --------------------------------------------------------------------------- #
@needs_ffmpeg_tools
def test_doctor_exits_zero_and_prints_profile_line() -> None:
result = _invoke("doctor")
assert result.exit_code == 0, result.output
assert "profile" in result.stdout.lower()
assert "local" in result.stdout
assert "ffmpeg" in result.stdout
assert "ffprobe" in result.stdout
assert "cache dir" in result.stdout
assert "GROQ_API_KEY" in result.stdout
@needs_ffmpeg_tools
def test_doctor_json_payload_has_check_list() -> None:
result = _invoke("doctor", "--json")
assert result.exit_code == 0, result.output
payload = json.loads(result.stdout)
assert payload["profile"] == "local"
names = {check["name"] for check in payload["checks"]}
assert {"python", "profile", "ffmpeg", "ffprobe", "cache dir", "free disk"} <= names
assert {"ok", "warn", "fail", "info"} >= {check["status"] for check in payload["checks"]}
assert payload["llama_server_command"] is None or isinstance(
payload["llama_server_command"], str
)
+169
View File
@@ -0,0 +1,169 @@
"""Settings: env overrides and per-profile resolution rules."""
from __future__ import annotations
from pathlib import Path
import pytest
from video_analyse.config import (
HOSTED_VLM_MODEL,
LOCAL_VLM_MODEL,
Settings,
)
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make every test independent of the developer's environment."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("HOME", "/home/tester")
def test_defaults() -> None:
s = Settings()
assert s.profile == "local"
assert s.cache_dir == Path("/home/tester/.cache/video-analyse")
assert s.language is None
assert s.stt_backend is None
assert s.stt_api_base_url == "https://api.groq.com/openai/v1"
assert s.stt_api_model == "whisper-large-v3-turbo"
assert s.whisper_model == "large-v3-turbo"
assert s.diarize is True
assert s.diarize_backend == "sherpa"
assert s.vlm_model is None
assert s.synthesis_model is None
assert s.llama_server_url == "http://127.0.0.1:8080/v1"
def test_cache_dir_tilde_is_expanded() -> None:
assert Settings().cache_dir.is_absolute()
assert "~" not in str(Settings().cache_dir)
def test_env_overrides(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("VA_PROFILE", "hosted")
monkeypatch.setenv("VA_CACHE_DIR", "~/va-cache")
monkeypatch.setenv("VA_LANGUAGE", "en")
monkeypatch.setenv("VA_STT_BACKEND", "whisper")
monkeypatch.setenv("VA_STT_API_BASE_URL", "https://example.invalid/v1")
monkeypatch.setenv("VA_STT_API_MODEL", "whisper-1")
monkeypatch.setenv("VA_WHISPER_MODEL", "small.en")
monkeypatch.setenv("VA_DIARIZE", "false")
monkeypatch.setenv("VA_DIARIZE_BACKEND", "pyannote")
monkeypatch.setenv("VA_VLM_MODEL", "openrouter:acme/vlm")
monkeypatch.setenv("VA_LLAMA_SERVER_URL", "http://127.0.0.1:9999/v1")
monkeypatch.setenv("VA_SYNTHESIS_MODEL", "deepseek:deepseek-flash")
s = Settings()
assert s.profile == "hosted"
assert str(s.cache_dir).endswith("va-cache") and s.cache_dir.is_absolute()
assert s.language == "en"
assert s.stt_backend == "whisper"
assert s.stt_api_base_url == "https://example.invalid/v1"
assert s.stt_api_model == "whisper-1"
assert s.whisper_model == "small.en"
assert s.diarize is False
assert s.diarize_backend == "pyannote"
assert s.vlm_model == "openrouter:acme/vlm"
assert s.llama_server_url == "http://127.0.0.1:9999/v1"
assert s.synthesis_model == "deepseek:deepseek-flash"
def test_invalid_profile_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("VA_PROFILE", "cloud")
with pytest.raises(ValueError):
Settings()
def test_local_profile_defaults() -> None:
s = Settings(profile="local")
assert s.resolved_stt() == "parakeet"
assert s.resolved_vlm() == LOCAL_VLM_MODEL == "local:Qwen3-VL-4B-Instruct"
assert s.resolved_synthesis() == LOCAL_VLM_MODEL
def test_hosted_profile_defaults() -> None:
s = Settings(profile="hosted")
assert s.resolved_stt() == "openai-transcriptions"
assert s.resolved_vlm() == HOSTED_VLM_MODEL == "deepseek:deepseek-flash"
assert s.resolved_synthesis() == HOSTED_VLM_MODEL
def test_explicit_overrides_beat_profile_defaults() -> None:
s = Settings(
profile="local",
stt_backend="openai-transcriptions",
vlm_model="openrouter:acme/vlm",
synthesis_model="ollama:qwen3-vl:4b",
)
assert s.resolved_stt() == "openai-transcriptions"
assert s.resolved_vlm() == "openrouter:acme/vlm"
assert s.resolved_synthesis() == "ollama:qwen3-vl:4b"
hosted = Settings(
profile="hosted",
stt_backend="parakeet",
vlm_model="local:Qwen3-VL-2B-Instruct",
synthesis_model="local:Qwen3-VL-2B-Instruct",
)
assert hosted.resolved_stt() == "parakeet"
assert hosted.resolved_vlm() == "local:Qwen3-VL-2B-Instruct"
assert hosted.resolved_synthesis() == "local:Qwen3-VL-2B-Instruct"
def test_explicit_whisper_model_selects_whisper_backend(monkeypatch: pytest.MonkeyPatch) -> None:
"""Naming a Whisper checkpoint implies the faster-whisper backend."""
monkeypatch.setenv("VA_WHISPER_MODEL", "tiny")
s = Settings()
assert s.whisper_model == "tiny"
assert s.resolved_stt() == "whisper"
assert Settings(stt_backend="parakeet", whisper_model="tiny").resolved_stt() == "parakeet"
monkeypatch.delenv("VA_WHISPER_MODEL")
assert Settings(profile="hosted").resolved_stt() == "openai-transcriptions"
def test_language_is_independent_of_profile() -> None:
assert Settings(profile="hosted", language="en").language == "en"
assert Settings(language=None).language is None
def test_optional_toml_config_is_read_with_env_precedence(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""PLAN §5: ~/.config/video-analyse/config.toml works, but VA_* still wins."""
home = tmp_path / "home"
config_dir = home / ".config" / "video-analyse"
config_dir.mkdir(parents=True)
(config_dir / "config.toml").write_text(
'profile = "hosted"\nlanguage = "de"\nwhisper_model = "small"\n', encoding="utf-8"
)
monkeypatch.setenv("HOME", str(home))
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
from_file = Settings()
assert from_file.profile == "hosted"
assert from_file.language == "de"
assert from_file.resolved_stt() == "whisper"
monkeypatch.setenv("VA_LANGUAGE", "en")
assert Settings().language == "en"
+579
View File
@@ -0,0 +1,579 @@
"""Diarization tests: speaker attribution, model cache, sherpa config (offline only)."""
from __future__ import annotations
import hashlib
import importlib.util
import io
import tarfile
import wave
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import numpy as np
import pytest
from video_analyse import model_assets
from video_analyse.config import Settings
from video_analyse.diarize import (
_labels_to_turns,
_load_wav_mono,
_pcm_to_float32,
_segments_to_turns,
attribute_speakers,
build_sherpa_config,
diarize_audio,
)
from video_analyse.model_assets import (
EMBEDDING_MODEL,
MODEL_ASSETS,
SEGMENTATION_MODEL,
ModelAsset,
ensure_diarization_models,
ensure_model,
model_path,
)
from video_analyse.models import Segment, SpeakerTurn, Transcript, Word
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"HF_TOKEN",
"HUGGING_FACE_HUB_TOKEN",
"HUGGINGFACEHUB_API_TOKEN",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make every test independent of the developer's environment."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
def _settings(tmp_path: Path, **overrides: Any) -> Settings:
return Settings(cache_dir=tmp_path, **overrides)
def _word(text: str, start: float, end: float) -> Word:
return Word(text=text, start=start, end=end)
def _transcript(segments: list[Segment], **kwargs: Any) -> Transcript:
duration = max((segment.end for segment in segments), default=0.0)
return Transcript(duration=duration, segments=segments, **kwargs)
# ---------------------------------------------------------------------------
# attribute_speakers
# ---------------------------------------------------------------------------
def test_attribute_speakers_uses_word_midpoints() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=3.0,
text="one two three",
words=[
# midpoint 0.5 -> S1
_word("one", 0.0, 1.0),
# starts in S1 but the midpoint (1.2) is in S2 -> S2
_word("two", 0.8, 1.6),
# midpoint 2.5 -> S2
_word("three", 2.4, 2.6),
],
)
]
)
turns = [
SpeakerTurn(start=0.0, end=1.0, speaker="S1"),
SpeakerTurn(start=1.0, end=3.0, speaker="S2"),
]
result = attribute_speakers(transcript, turns)
assert result.segments[0].speaker == "S2"
assert result.speaker_turns == turns
# the input transcript is left untouched
assert transcript.segments[0].speaker is None
assert transcript.speaker_turns == []
assert result is not transcript
def test_attribute_speakers_majority_beats_first_word() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=4.0,
text="a b c",
words=[
_word("a", 2.2, 2.4), # S2 (1 word)
_word("b", 0.2, 0.4), # S1
_word("c", 0.6, 0.8), # S1
],
)
]
)
turns = [
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
result = attribute_speakers(transcript, turns)
assert result.segments[0].speaker == "S1"
def test_attribute_speakers_tie_goes_to_first_attributed_word() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=4.0,
text="a b",
words=[_word("a", 2.2, 2.4), _word("b", 0.2, 0.4)],
)
]
)
turns = [
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
result = attribute_speakers(transcript, turns)
# 1:1 tie -> the earliest attributed word is "a" (S2)
assert result.segments[0].speaker == "S2"
def test_attribute_speakers_without_turns_is_unchanged() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=1.0,
text="hello",
words=[_word("hello", 0.1, 0.9)],
speaker="S7",
)
],
speaker_turns=[SpeakerTurn(start=0.0, end=1.0, speaker="S7")],
)
result = attribute_speakers(transcript, [])
assert result == transcript
assert result is not transcript
assert result.segments[0].speaker == "S7"
def test_attribute_speakers_words_without_a_turn_get_no_speaker() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=2.0,
text="outside",
words=[_word("outside", 0.0, 2.0)],
speaker="S3",
),
Segment(start=2.0, end=3.0, text="no words"),
]
)
turns = [SpeakerTurn(start=10.0, end=12.0, speaker="S1")]
result = attribute_speakers(transcript, turns)
assert result.segments[0].speaker is None # stale label cleared
assert result.segments[1].speaker is None # no words -> no attribution
assert result.speaker_turns == turns
def test_attribute_speakers_boundary_midpoint_belongs_to_earliest_turn() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=2.0,
text="edge",
# midpoint is exactly 1.0 = end of turn S1 and start of turn S2
words=[_word("edge", 0.6, 1.4)],
)
]
)
turns = [
SpeakerTurn(start=0.0, end=1.0, speaker="S1"),
SpeakerTurn(start=1.0, end=2.0, speaker="S2"),
]
result = attribute_speakers(transcript, turns)
assert result.segments[0].speaker == "S1"
def test_attribute_speakers_overlapping_turns_prefer_the_earliest() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=4.0,
text="overlap",
words=[_word("overlap", 2.0, 3.0)], # midpoint 2.5 is in both turns
)
]
)
turns = [
SpeakerTurn(start=0.0, end=3.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
result = attribute_speakers(transcript, turns)
assert result.segments[0].speaker == "S1"
def test_attribute_speakers_handles_turns_out_of_order() -> None:
transcript = _transcript(
[
Segment(
start=0.0,
end=4.0,
text="late early",
words=[_word("late", 3.0, 3.5), _word("early", 0.5, 1.0)],
)
]
)
turns = [
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
]
result = attribute_speakers(transcript, turns)
# tie 1:1 -> earliest word "late" is S2
assert result.segments[0].speaker == "S2"
assert [turn.speaker for turn in result.speaker_turns] == ["S2", "S1"]
# ---------------------------------------------------------------------------
# sherpa-onnx turn mapping / config construction (no inference, no download)
# ---------------------------------------------------------------------------
def test_labels_to_turns_assigns_ids_by_first_appearance() -> None:
spans = [
(0.0, 1.0, 7),
(1.0, 2.0, 3),
(2.0, 3.0, 7),
(3.0, 3.0, 9), # zero-length -> dropped
]
turns = _labels_to_turns(spans)
assert [turn.speaker for turn in turns] == ["S1", "S2", "S1"]
assert turns[0].start == 0.0 and turns[0].end == 1.0
def test_segments_to_turns_maps_sherpa_segments() -> None:
segments = [
SimpleNamespace(start=0.0, end=0.8, speaker=5),
SimpleNamespace(start=0.8, end=1.6, speaker=2),
SimpleNamespace(start=1.6, end=2.4, speaker=5),
]
turns = _segments_to_turns(segments)
assert [turn.speaker for turn in turns] == ["S1", "S2", "S1"]
def test_build_sherpa_config_from_dummy_model_paths(tmp_path: Path) -> None:
sherpa_onnx = pytest.importorskip("sherpa_onnx")
segmentation = tmp_path / "model.onnx"
embedding = tmp_path / "embedding.onnx"
segmentation.write_bytes(b"dummy segmentation placeholder")
embedding.write_bytes(b"dummy embedding placeholder")
config = build_sherpa_config(
segmentation,
embedding,
num_threads=16,
num_speakers=2,
cluster_threshold=0.42,
min_duration_on=0.25,
min_duration_off=0.6,
)
assert isinstance(config, sherpa_onnx.OfflineSpeakerDiarizationConfig)
assert config.segmentation.pyannote.model == str(segmentation)
assert config.segmentation.pyannote.window_shift_ratio == pytest.approx(0.1, abs=1e-6)
assert config.segmentation.num_threads == 16
assert config.segmentation.provider == "cpu"
assert config.segmentation.debug is False
assert config.embedding.model == str(embedding)
assert config.embedding.num_threads == 16
assert config.embedding.provider == "cpu"
assert config.clustering.num_clusters == 2
assert config.clustering.threshold == pytest.approx(0.42, abs=1e-6)
assert config.clustering.compute_confidence is False
assert config.min_duration_on == pytest.approx(0.25, abs=1e-6)
assert config.min_duration_off == pytest.approx(0.6, abs=1e-6)
assert config.validate() is True
def test_build_sherpa_config_defaults(tmp_path: Path) -> None:
pytest.importorskip("sherpa_onnx")
segmentation = tmp_path / "model.onnx"
embedding = tmp_path / "embedding.onnx"
segmentation.write_bytes(b"x")
embedding.write_bytes(b"y")
config = build_sherpa_config(segmentation, embedding)
assert config.segmentation.num_threads == 1
assert config.clustering.num_clusters == -1
assert config.clustering.threshold == pytest.approx(0.5, abs=1e-6)
assert config.min_duration_on == pytest.approx(0.3, abs=1e-6)
assert config.min_duration_off == pytest.approx(0.5, abs=1e-6)
def test_build_sherpa_config_rejects_missing_models(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="does not exist"):
build_sherpa_config(tmp_path / "missing-seg.onnx", tmp_path / "missing-emb.onnx")
# ---------------------------------------------------------------------------
# WAV loading
# ---------------------------------------------------------------------------
def _write_wav(path: Path, samples: np.ndarray, rate: int, channels: int = 1) -> Path:
with wave.open(str(path), "wb") as handle:
handle.setnchannels(channels)
handle.setsampwidth(2)
handle.setframerate(rate)
handle.writeframes(np.asarray(samples, dtype="<i2").tobytes())
return path
def test_load_wav_mono_decodes_16k_mono(tmp_path: Path) -> None:
samples = np.full(1600, 16384, dtype=np.int16) # 0.5 * 32768, 0.1 s
wav = _write_wav(tmp_path / "mono.wav", samples, 16_000)
loaded, rate = _load_wav_mono(wav)
assert rate == 16_000
assert loaded.dtype == np.float32
assert loaded.shape == (1600,)
assert float(loaded.mean()) == pytest.approx(0.5, abs=1e-4)
def test_load_wav_mono_downmixes_and_resamples(tmp_path: Path) -> None:
one_second = np.zeros((8000, 2), dtype=np.int16)
one_second[:, 0] = 16384 # left 0.5
one_second[:, 1] = -16384 # right -0.5 -> average 0.0
wav = _write_wav(tmp_path / "stereo8k.wav", one_second.reshape(-1), 8000, channels=2)
loaded, rate = _load_wav_mono(wav, target_sample_rate=16_000)
assert rate == 16_000
assert abs(loaded.size - 16_000) <= 2
assert float(np.abs(loaded).max()) < 1e-3
def test_pcm_to_float32_sign_extends_24_bit() -> None:
raw = b"\x00\x00\x40" + b"\x00\x00\xc0"
values = _pcm_to_float32(raw, 3)
assert values[0] == pytest.approx(0.5, abs=1e-6)
assert values[1] == pytest.approx(-0.5, abs=1e-6)
# ---------------------------------------------------------------------------
# model_assets: path layout, idempotency, mocked downloads (no real network)
# ---------------------------------------------------------------------------
def test_model_path_layout(tmp_path: Path) -> None:
segmentation = model_path(SEGMENTATION_MODEL, cache_dir=tmp_path)
embedding = model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
assert segmentation == tmp_path / "models" / SEGMENTATION_MODEL / "model.onnx"
assert embedding == tmp_path / "models" / EMBEDDING_MODEL / f"{EMBEDDING_MODEL}.onnx"
# a trailing suffix is tolerated
assert model_path(f"{EMBEDDING_MODEL}.onnx", cache_dir=tmp_path) == embedding
async def test_ensure_model_is_idempotent_without_download(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = b"already-cached-dummy-model"
asset = _dummy_asset(EMBEDDING_MODEL, payload, filename="embedding.onnx")
monkeypatch.setitem(MODEL_ASSETS, EMBEDDING_MODEL, asset)
target = model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
target.parent.mkdir(parents=True)
target.write_bytes(payload)
def _no_http(*args: Any, **kwargs: Any) -> Any:
raise AssertionError("ensure_model must not open an HTTP client for a cached file")
monkeypatch.setattr(model_assets.httpx, "AsyncClient", _no_http)
first = await ensure_model(EMBEDDING_MODEL, cache_dir=tmp_path)
second = await ensure_model(EMBEDDING_MODEL, cache_dir=tmp_path)
assert first == second == target
assert target.read_bytes() == payload
async def test_ensure_model_rejects_unknown_name(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="Available models"):
await ensure_model("not-a-model", cache_dir=tmp_path)
def _dummy_asset(name: str, payload: bytes, **kwargs: Any) -> ModelAsset:
return ModelAsset(
name=name,
url=f"https://example.invalid/{name}.bin",
filename=kwargs.pop("filename", f"{name}.onnx"),
size_bytes=len(payload),
sha256=hashlib.sha256(payload).hexdigest(),
**kwargs,
)
async def test_ensure_model_streams_download_and_replaces_empty_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = b"onnx-bytes" * 512
asset = _dummy_asset("unit-test-embedding", payload)
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
target = model_path(asset.name, cache_dir=tmp_path)
target.parent.mkdir(parents=True)
target.write_bytes(b"") # truncated leftovers from an interrupted run
def handler(request: httpx.Request) -> httpx.Response:
assert str(request.url) == asset.url
return httpx.Response(200, content=payload)
transport = httpx.MockTransport(handler)
async with httpx.AsyncClient(transport=transport) as client:
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
assert resolved == target
assert target.read_bytes() == payload
assert [entry.name for entry in target.parent.iterdir()] == [target.name]
async def test_ensure_model_extracts_archive_member(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = b"fake segmentation onnx payload"
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w:bz2") as tar:
info = tarfile.TarInfo(f"{SEGMENTATION_MODEL}/model.onnx")
info.size = len(payload)
tar.addfile(info, io.BytesIO(payload))
archive_bytes = buffer.getvalue()
asset = _dummy_asset(
"unit-test-segmentation",
payload,
filename="model.onnx",
archive_member=f"{SEGMENTATION_MODEL}/model.onnx",
)
asset = replace(asset, url="https://example.invalid/unit-test-segmentation.tar.bz2")
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=archive_bytes))
async with httpx.AsyncClient(transport=transport) as client:
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
assert resolved == tmp_path / "models" / asset.name / "model.onnx"
assert resolved.read_bytes() == payload
assert [entry.name for entry in resolved.parent.iterdir()] == ["model.onnx"]
async def test_ensure_model_redownloads_a_corrupted_cached_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = b"correct-model-payload"
asset = _dummy_asset("unit-test-cached-corrupt", payload)
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
target = model_path(asset.name, cache_dir=tmp_path)
target.parent.mkdir(parents=True)
target.write_bytes(b"x" * len(payload))
assert target.stat().st_size == len(payload)
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=payload))
async with httpx.AsyncClient(transport=transport) as client:
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
assert resolved == target
assert target.read_bytes() == payload
async def test_ensure_model_rejects_corrupt_download(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = b"corrupt bytes"
asset = replace(_dummy_asset("unit-test-corrupt", payload), sha256="0" * 64)
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=payload))
async with httpx.AsyncClient(transport=transport) as client:
with pytest.raises(RuntimeError, match="Integrity check failed"):
await ensure_model(asset.name, cache_dir=tmp_path, client=client)
target = model_path(asset.name, cache_dir=tmp_path)
assert not target.exists()
assert list(target.parent.iterdir()) == []
async def test_ensure_diarization_models_returns_both_cached_paths(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payloads = {
SEGMENTATION_MODEL: b"cached-segmentation-model",
EMBEDDING_MODEL: b"cached-embedding-model",
}
for name, payload in payloads.items():
asset = _dummy_asset(name, payload, filename=f"{name}.onnx")
monkeypatch.setitem(MODEL_ASSETS, name, asset)
path = model_path(name, cache_dir=tmp_path)
path.parent.mkdir(parents=True)
path.write_bytes(payload)
def _no_http(*args: Any, **kwargs: Any) -> Any:
raise AssertionError("both models are cached; no HTTP client should be created")
monkeypatch.setattr(model_assets.httpx, "AsyncClient", _no_http)
models = await ensure_diarization_models(cache_dir=tmp_path)
assert models.segmentation == model_path(SEGMENTATION_MODEL, cache_dir=tmp_path)
assert models.embedding == model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
# ---------------------------------------------------------------------------
# diarize_audio entry point (no downloads, no inference)
# ---------------------------------------------------------------------------
async def test_diarize_audio_missing_file_raises(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="not found"):
await diarize_audio(tmp_path / "missing.wav", settings=_settings(tmp_path))
async def test_pyannote_backend_without_extra_reports_install_hint(tmp_path: Path) -> None:
try:
available = importlib.util.find_spec("pyannote.audio") is not None
except (ImportError, ValueError):
available = False
if available:
pytest.skip("pyannote.audio is installed; the missing-extra path cannot be tested")
wav = tmp_path / "audio.wav"
wav.write_bytes(b"RIFF-not-really-a-wav")
settings = _settings(tmp_path, diarize_backend="pyannote")
with pytest.raises(ImportError, match=r"video-analyse\[pyannote\]") as excinfo:
await diarize_audio(wav, settings=settings)
assert "HF_TOKEN" in str(excinfo.value)
+217
View File
@@ -0,0 +1,217 @@
"""Tests for ``video_analyse.ingest``.
The remote branch is exercised with a fake in-memory ``yt_dlp.YoutubeDL``: these
tests never open a socket and never download anything.
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any, ClassVar
import pytest
from yt_dlp.utils import DownloadError
from video_analyse.ingest import IngestResult, _safe_dir_name, fetch
URL = "https://example.invalid/watch?v=abc123&list=PL123"
DOWNLOAD_FILE_NAME = "My Clip [abc123].mp4"
class _FakeYoutubeDL:
"""Minimal stand-in for ``yt_dlp.YoutubeDL`` writing a fake media file."""
calls: ClassVar[list[dict[str, Any]]] = []
fail_with: ClassVar[str | None] = None
def __init__(self, params: dict[str, Any] | None = None) -> None:
self.options = dict(params or {})
type(self).calls.append(self.options)
def __enter__(self) -> _FakeYoutubeDL:
return self
def __exit__(self, *exc_info: object) -> bool:
return False
def extract_info(self, url: str, download: bool = True) -> dict[str, Any]:
if type(self).fail_with is not None:
raise DownloadError(type(self).fail_with)
assert download is True
home = Path(self.options["paths"]["home"])
home.mkdir(parents=True, exist_ok=True)
target = home / DOWNLOAD_FILE_NAME
target.write_bytes(b"\x00" * 2048)
return {
"id": "abc123",
"title": "My Clip",
"ext": "mp4",
"webpage_url": url,
"duration": 42.5,
"filepath": str(target),
"requested_downloads": [{"filepath": str(target)}],
}
def sanitize_info(self, info: dict[str, Any]) -> dict[str, Any]:
return dict(info)
def prepare_filename(self, info: dict[str, Any]) -> str:
return str(Path(self.options["paths"]["home"]) / DOWNLOAD_FILE_NAME)
@pytest.fixture(autouse=True)
def _reset_fake_ydl() -> None:
_FakeYoutubeDL.calls = []
_FakeYoutubeDL.fail_with = None
@pytest.fixture
def fake_ydl(monkeypatch: pytest.MonkeyPatch) -> type[_FakeYoutubeDL]:
monkeypatch.setattr("yt_dlp.YoutubeDL", _FakeYoutubeDL)
return _FakeYoutubeDL
async def test_fetch_local_file_does_not_touch_ytdlp(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
clip = tmp_path / "clip.MP4"
clip.write_bytes(b"\x00" * 1024)
def _no_download(*_args: object, **_kwargs: object) -> None:
raise AssertionError("local files must not be downloaded")
monkeypatch.setattr("yt_dlp.YoutubeDL", _no_download)
result = await fetch(str(clip), cache_dir=tmp_path / "cache")
assert isinstance(result, IngestResult)
assert result.downloaded is False
assert result.path == clip.resolve()
assert result.info == {}
assert result.title is None
assert not (tmp_path / "cache").exists()
async def test_fetch_missing_local_file_raises_value_error(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="not found"):
await fetch(str(tmp_path / "nope.mp4"), cache_dir=tmp_path / "cache")
async def test_fetch_rejects_non_media_extension(tmp_path: Path) -> None:
text_file = tmp_path / "notes.txt"
text_file.write_text("hello", encoding="utf-8")
with pytest.raises(ValueError, match="does not look like a media file"):
await fetch(str(text_file), cache_dir=tmp_path / "cache")
async def test_fetch_rejects_empty_local_file(tmp_path: Path) -> None:
empty = tmp_path / "empty.mp4"
empty.touch()
with pytest.raises(ValueError, match="empty"):
await fetch(str(empty), cache_dir=tmp_path / "cache")
@pytest.mark.parametrize("source", ["ftp://example.invalid/clip.mp4", "file:///tmp/clip.mp4"])
async def test_fetch_rejects_other_url_schemes(source: str, tmp_path: Path) -> None:
with pytest.raises(ValueError, match="Unsupported URL scheme"):
await fetch(source, cache_dir=tmp_path / "cache")
async def test_fetch_rejects_invalid_quality(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
clip = tmp_path / "clip.mp4"
clip.write_bytes(b"\x00" * 16)
for quality in (0, -720):
with pytest.raises(ValueError, match="quality"):
await fetch(str(clip), cache_dir=tmp_path / "cache", quality=quality)
assert fake_ydl.calls == []
async def test_fetch_downloads_http_url_into_cache(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
cache_dir = tmp_path / "cache"
result = await fetch(URL, cache_dir=cache_dir, quality=720)
slug = f"{_safe_dir_name(URL)}-q720"
expected_dir = (cache_dir / "downloads" / slug).resolve()
assert result.downloaded is True
assert result.title == "My Clip"
assert result.info["id"] == "abc123"
assert result.info["duration"] == pytest.approx(42.5)
assert result.path.is_file()
assert result.path.name == DOWNLOAD_FILE_NAME
assert result.path.parent == expected_dir
assert len(fake_ydl.calls) == 1
options = fake_ydl.calls[0]
assert options["format"] == "bv*[height<=720]+ba/b[height<=720]/b"
assert options["noplaylist"] is True
assert options["writeinfojson"] is True
assert "%(id)s" in options["outtmpl"]
assert Path(options["paths"]["home"]).resolve() == expected_dir
async def test_fetch_uses_a_stable_directory_per_url(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
cache_dir = tmp_path / "cache"
first = await fetch(URL, cache_dir=cache_dir)
second = await fetch(URL, cache_dir=cache_dir)
home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls}
assert len(home_dirs) == 1
assert first.downloaded is True
assert second.downloaded is False # reused from the URL+quality cache directory
assert len(fake_ydl.calls) == 1
assert first.path == second.path
assert first.info == second.info
async def test_fetch_keys_the_download_directory_by_quality(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
"""PLAN §3.4: changing --quality must not silently reuse the previous height."""
cache_dir = tmp_path / "cache"
await fetch(URL, cache_dir=cache_dir, quality=720)
await fetch(URL, cache_dir=cache_dir, quality=1080)
home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls}
assert len(home_dirs) == 2
assert len(fake_ydl.calls) == 2
async def test_fetch_maps_download_errors_to_actionable_runtime_error(
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
) -> None:
fake_ydl.fail_with = "ERROR: Video unavailable"
with pytest.raises(RuntimeError) as excinfo:
await fetch(URL, cache_dir=tmp_path / "cache")
message = str(excinfo.value)
assert "https://example.invalid/watch" in message
assert "abc123" not in message # query strings are redacted from errors
assert "Video unavailable" in message
assert "local path" in message
assert excinfo.value.__cause__ is not None
def test_safe_dir_name_is_stable_filesystem_safe_and_url_specific() -> None:
slug = _safe_dir_name(URL)
assert slug == _safe_dir_name(URL)
assert re.fullmatch(r"[A-Za-z0-9._-]+", slug)
assert "/" not in slug and "?" not in slug and "&" not in slug
assert len(slug) <= 75
assert slug != _safe_dir_name("https://example.invalid/other?v=abc123")
# a URL with nothing usable still yields a directory name
assert re.fullmatch(r"[A-Za-z0-9._-]+", _safe_dir_name("https://example.invalid/"))
def test_safe_dir_name_never_contains_url_credentials() -> None:
slug = _safe_dir_name("https://alice:s3cr3t@example.invalid/private/clip.mp4")
assert "s3cr3t" not in slug
assert "alice" not in slug
assert slug.startswith("example.invalid")
+172
View File
@@ -0,0 +1,172 @@
"""llm.build_model wiring (construction only, no network) + llama_server_up."""
from __future__ import annotations
import asyncio
import pytest
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.function import AgentInfo
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.models.test import TestModel
from video_analyse.config import Settings
from video_analyse.llm import build_model, llama_server_up
PROVIDER_ENV = (
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"DEEPSEEK_API_KEY",
"OPENROUTER_API_KEY",
"OLLAMA_BASE_URL",
"OLLAMA_API_KEY",
"OPENAI_API_KEY",
)
@pytest.fixture(autouse=True)
def clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
for name in PROVIDER_ENV:
monkeypatch.delenv(name, raising=False)
def test_build_model_bare_name_uses_local_llama_server() -> None:
settings = Settings()
model = build_model("Qwen3-VL-4B-Instruct", settings=settings)
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "Qwen3-VL-4B-Instruct"
assert model.system == "llama-server"
assert str(model.base_url).startswith("http://127.0.0.1:8080/v1")
def test_build_model_local_prefix_uses_settings_url() -> None:
settings = Settings(llama_server_url="http://127.0.0.1:9999/v1")
model = build_model("local:Qwen3-VL-2B-Instruct", settings=settings)
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "Qwen3-VL-2B-Instruct"
assert str(model.base_url).startswith("http://127.0.0.1:9999/v1")
def test_build_model_local_prefix_without_name_raises() -> None:
with pytest.raises(ValueError):
build_model("local:", settings=Settings())
def test_build_model_empty_spec_raises() -> None:
with pytest.raises(ValueError):
build_model(" ", settings=Settings())
def test_build_model_unknown_prefix_is_a_local_model_name() -> None:
"""A "vendor:model" string that is not a known pydantic-ai provider stays local."""
model = build_model("acme:some-model", settings=Settings())
assert isinstance(model, OpenAIChatModel)
assert model.model_name == "acme:some-model"
def test_build_model_deepseek_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
model = build_model("deepseek:deepseek-flash", settings=Settings(profile="hosted"))
assert model.model_name == "deepseek-flash"
assert model.system == "deepseek"
assert type(model).__name__ == "OpenAIChatModel"
def test_build_model_openrouter_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
model = build_model(
"openrouter:deepseek/deepseek-v4.1-flash-1017", settings=Settings(profile="hosted")
)
assert model.model_name == "deepseek/deepseek-v4.1-flash-1017"
assert model.system == "openrouter"
assert type(model).__name__ == "OpenRouterModel"
def test_build_model_ollama_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OLLAMA_BASE_URL", "http://127.0.0.1:11434")
model = build_model("ollama:qwen3-vl:4b", settings=Settings())
assert model.model_name == "qwen3-vl:4b"
assert model.system == "ollama"
assert type(model).__name__ == "OllamaModel"
def test_settings_resolution_feeds_build_model(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
hosted = Settings(profile="hosted")
model = build_model(hosted.resolved_vlm(), settings=hosted)
assert model.system == "deepseek"
local = Settings(profile="local")
local_model = build_model(local.resolved_vlm(), settings=local)
assert isinstance(local_model, OpenAIChatModel)
assert local_model.model_name == "Qwen3-VL-4B-Instruct"
def test_build_model_test_spec_returns_test_model() -> None:
assert isinstance(build_model("test", settings=Settings()), TestModel)
def test_agent_with_local_model_constructs() -> None:
"""Agent construction with the local model: no request is made here."""
class Desc(BaseModel):
summary: str
agent = Agent(
build_model("local:Qwen3-VL-4B-Instruct", settings=Settings()),
output_type=Desc,
model_settings={"temperature": 0.1, "max_tokens": 400, "max_retries": 0},
retries={"output": 2},
system_prompt="Describe the frame.",
)
assert agent.output_type is Desc
assert agent.model_settings["temperature"] == 0.1
assert agent.model_settings["max_retries"] == 0
def test_test_model_agent_runs_offline_with_structured_output() -> None:
class Desc(BaseModel):
summary: str
shot_type: str = "other"
agent = Agent(TestModel(), output_type=Desc, system_prompt="describe")
result = asyncio.run(agent.run("describe this frame"))
assert isinstance(result.output, Desc)
def test_function_model_type_is_available() -> None:
"""FunctionModel is importable and usable for scripted offline agents."""
from pydantic_ai.models.function import FunctionModel
def fn(messages, info: AgentInfo):
raise AssertionError("must not be called at construction time")
agent = Agent(FunctionModel(fn))
assert isinstance(agent.model, FunctionModel)
def test_llama_server_up_dead_port_is_fast_false() -> None:
import time
settings = Settings(llama_server_url="http://127.0.0.1:9/v1") # discard port: closed
started = time.monotonic()
assert asyncio.run(llama_server_up(settings)) is False
assert time.monotonic() - started < 2.5
def test_llama_server_up_unresolvable_host_is_false() -> None:
settings = Settings(llama_server_url="http://127.0.0.1:1/v1")
assert asyncio.run(llama_server_up(settings)) is False
@pytest.mark.parametrize(
"url",
[
"http://localhost:abc/v1", # httpx.InvalidURL
"http://127.0.0.1:99999/v1", # OverflowError inside the connect attempt
],
)
def test_llama_server_up_treats_malformed_urls_as_down(url: str) -> None:
"""va doctor and describe must warn, never crash, on a bad VA_LLAMA_SERVER_URL."""
assert asyncio.run(llama_server_up(Settings(llama_server_url=url))) is False
+781
View File
@@ -0,0 +1,781 @@
"""Tests for the FastMCP server: tool surface, structured shapes and real ffmpeg frames.
``video_analyse.pipeline.Pipeline`` is monkeypatched with a stub returning canned
``Artifacts``, so no test starts a real pipeline, downloads a model or opens a socket
beyond the in-memory client transport. ``get_frame_at`` and ``analyze_moment`` still
run real ffmpeg against the ``sample_video`` fixture and must come back with JPEG image
content; ``analyze_moment`` also exercises the cached-artifact lookups through
:class:`StageCache`.
"""
from __future__ import annotations
import base64
import io
from pathlib import Path
from typing import Any, ClassVar
import pytest
from fastmcp import Client
from fastmcp.exceptions import ToolError
from PIL import Image as PilImage
import video_analyse.mcp_server as mcp_server
import video_analyse.pipeline as pipeline_module
import video_analyse.synthesis as synthesis_module
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.models import (
Artifacts,
Highlight,
MediaInfo,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.pipeline import STAGE_ORDER
from video_analyse.synthesis import AnswerResult
EXPECTED_TOOLS = {
"transcribe_video",
"extract_keyframes",
"analyze_video",
"analyze_moment",
"get_frame_at",
"ask_video",
}
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Keep every test independent of the developer's environment and cache."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("VA_CACHE_DIR", str(tmp_path / "cache"))
class StubPipeline:
"""Stand-in for ``video_analyse.pipeline.Pipeline`` returning canned artifacts."""
instances: ClassVar[list[StubPipeline]] = []
artifacts: ClassVar[Artifacts | None] = None
failure: ClassVar[BaseException | None] = None
def __init__(self, settings: Settings, **options: Any) -> None:
self.settings = settings
self.options = options
self.runs: list[dict[str, Any]] = []
self._artifacts = StubPipeline.artifacts
self._failure = StubPipeline.failure
StubPipeline.instances.append(self)
async def run(
self,
source: str,
*,
want: Any,
force: bool = False,
progress: Any = None,
) -> Artifacts:
"""Record the call, emit a few progress messages and return the canned result."""
self.runs.append({"source": source, "want": set(want), "force": force})
if progress is not None:
for message in ("ingest: local file", "probe: cached", "report: cached"):
progress(message)
if self._failure is not None:
raise self._failure
if self._artifacts is None:
raise AssertionError("StubPipeline.artifacts was not configured for this test")
return self._artifacts
@pytest.fixture
def stub_pipeline(monkeypatch: pytest.MonkeyPatch) -> type[StubPipeline]:
"""Replace the real pipeline with :class:`StubPipeline` for one test."""
StubPipeline.instances = []
StubPipeline.artifacts = None
StubPipeline.failure = None
monkeypatch.setattr(pipeline_module, "Pipeline", StubPipeline)
return StubPipeline
def _transcript(*, speakers: bool = True) -> Transcript:
"""A two-segment, word-timed transcript, speaker-labelled when ``speakers``."""
turns = (
[
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
if speakers
else []
)
return Transcript(
language="en",
duration=10.0,
segments=[
Segment(
start=0.0,
end=2.0,
text="Hello there.",
words=[
Word(text="Hello", start=0.1, end=0.6, probability=0.91),
Word(text="there.", start=0.7, end=1.2, probability=0.88),
],
speaker="S1" if speakers else None,
),
Segment(
start=2.0,
end=4.0,
text="General Kenobi.",
words=[
Word(text="General", start=2.1, end=2.6),
Word(text="Kenobi.", start=2.7, end=3.2),
],
speaker="S2" if speakers else None,
),
],
speaker_turns=turns,
backend="stub",
model="stub-stt",
)
def _jpeg(path: Path, color: tuple[int, int, int]) -> Path:
"""Write a tiny solid-colour JPEG and return its path."""
path.parent.mkdir(parents=True, exist_ok=True)
PilImage.new("RGB", (64, 36), color).save(path, format="JPEG")
return path
def _shots(frames_dir: Path, *, described: bool = True) -> list[Shot]:
"""Two shots with real JPEG keyframes and optional descriptions."""
first = ShotDescription(summary="A red test pattern.", shot_type="screen", on_screen_text="0")
second = ShotDescription(summary="A blue test pattern.", shot_type="wide")
return [
Shot(
index=0,
start=0.0,
end=5.0,
keyframe=_jpeg(frames_dir / "shot-0.jpg", (200, 30, 30)),
phash="0000000000000001",
description=first if described else None,
),
Shot(
index=1,
start=5.0,
end=10.0,
keyframe=_jpeg(frames_dir / "shot-1.jpg", (30, 30, 200)),
phash="0000000000000002",
description=second if described else None,
),
]
def _media(path: Path, *, has_audio: bool = True, has_video: bool = True) -> MediaInfo:
"""Synthetic media facts for ``path`` (the file is never opened)."""
size = path.stat().st_size if path.is_file() else 0
return MediaInfo(
path=path,
source=str(path),
duration=10.0,
width=640 if has_video else None,
height=360 if has_video else None,
fps=12.0 if has_video else None,
has_audio=has_audio,
size_bytes=size,
format="mp4",
video_codec="h264" if has_video else None,
audio_codec="aac" if has_audio else None,
)
def _artifacts(
path: Path,
*,
transcript: Transcript | None = None,
shots: list[Shot] | None = None,
report: VideoReport | None = None,
has_audio: bool = True,
has_video: bool = True,
) -> Artifacts:
"""Canned pipeline artifacts for one stub call."""
return Artifacts(
source=str(path),
workdir=path.parent,
media=_media(path, has_audio=has_audio, has_video=has_video),
transcript=transcript,
shots=shots or [],
report=report,
)
def _report(path: Path, transcript: Transcript, shots: list[Shot]) -> VideoReport:
"""A validated report built from the canned transcript and shots."""
return VideoReport(
source=str(path),
title="Synthetic clip",
duration=10.0,
summary="A synthetic test pattern with two spoken lines.",
topics=["test pattern"],
people=["S1", "S2"],
highlights=[
Highlight(start=2.0, end=4.0, description="[00:02] The second speaker answers.")
],
shots=shots,
transcript=transcript,
metadata={"path": str(path), "width": 640, "height": 360},
)
def _seed_cache(tmp_path: Path, video: Path, *, transcript: Transcript, shots: list[Shot]) -> None:
"""Write cached transcribe/diarize/describe artifacts for ``video``."""
cache = StageCache(tmp_path / "cache")
source_sha = cache.source_hash(video)
transcribe_key = cache.stage_key("transcribe", {"seed": "transcribe"})
cache.save_model(cache.stage_path(source_sha, "transcribe", transcribe_key), transcript)
diarize_key = cache.stage_key("diarize", {"seed": "diarize"})
cache.save_json(
cache.stage_path(source_sha, "diarize", diarize_key),
{"turns": [turn.model_dump(mode="json") for turn in _turns()]},
)
describe_key = cache.stage_key("describe", {"seed": "describe"})
cache.save_json(
cache.stage_path(source_sha, "describe", describe_key),
{"shots": [shot.model_dump(mode="json") for shot in shots]},
)
def _turns() -> list[SpeakerTurn]:
"""The speaker turns applied to the cached transcript by ``analyze_moment``."""
return [
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
]
def _image_blocks(result: Any) -> list[Any]:
"""Every image content block of a tool result, in order."""
return [block for block in result.content if block.type == "image"]
async def test_server_registers_exactly_the_six_documented_tools() -> None:
"""The server advertises the six planned tools with docstring descriptions."""
assert mcp_server.mcp.name == "video-analyse"
async with Client(mcp_server.mcp) as client:
tools = await client.list_tools()
assert {tool.name for tool in tools} == EXPECTED_TOOLS
for tool in tools:
assert tool.description, f"{tool.name} is missing a tool description"
assert len(tool.description) > 40
schemas = {tool.name: tool.input_schema for tool in tools}
assert "ctx" not in schemas["analyze_video"]["properties"]
assert schemas["transcribe_video"]["properties"]["diarize"]["default"] is None
assert schemas["extract_keyframes"]["properties"]["max_shots"]["default"] == 64
assert set(schemas["analyze_moment"]["required"]) == {"source", "t_start", "t_end"}
async def test_transcribe_video_returns_a_speaker_labelled_transcript(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""transcribe_video wants probe/audio/transcribe/diarize and returns the Transcript."""
stub_pipeline.artifacts = _artifacts(sample_video, transcript=_transcript())
async with Client(mcp_server.mcp) as client:
result = await client.call_tool("transcribe_video", {"source": str(sample_video)})
payload = result.structured_content
assert payload["language"] == "en"
assert payload["backend"] == "stub"
assert [segment["text"] for segment in payload["segments"]] == [
"Hello there.",
"General Kenobi.",
]
assert payload["segments"][0]["speaker"] == "S1"
assert payload["segments"][1]["speaker"] == "S2"
assert payload["segments"][0]["words"][0] == {
"text": "Hello",
"start": 0.1,
"end": 0.6,
"probability": 0.91,
}
assert payload["speaker_turns"] == [
{"start": 0.0, "end": 2.0, "speaker": "S1"},
{"start": 2.0, "end": 4.0, "speaker": "S2"},
]
pipeline = stub_pipeline.instances[-1]
assert pipeline.settings.diarize is True
assert pipeline.runs[-1]["source"] == str(sample_video)
assert pipeline.runs[-1]["want"] == {"probe", "audio", "transcribe", "diarize"}
async def test_transcribe_video_follows_va_diarize(
stub_pipeline: type[StubPipeline],
sample_video: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Omitting diarize follows VA_DIARIZE instead of forcing the extra model pass."""
monkeypatch.setenv("VA_DIARIZE", "false")
stub_pipeline.artifacts = _artifacts(sample_video, transcript=_transcript(speakers=False))
async with Client(mcp_server.mcp) as client:
await client.call_tool("transcribe_video", {"source": str(sample_video)})
pipeline = stub_pipeline.instances[-1]
assert pipeline.settings.diarize is False
assert pipeline.runs[-1]["want"] == {"probe", "audio", "transcribe"}
async def test_transcribe_video_respects_the_diarize_flag(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""diarize=False disables the setting and drops the diarize stage from ``want``."""
stub_pipeline.artifacts = _artifacts(sample_video, transcript=_transcript(speakers=False))
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"transcribe_video", {"source": str(sample_video), "diarize": False}
)
assert result.structured_content["speaker_turns"] == []
pipeline = stub_pipeline.instances[-1]
assert pipeline.settings.diarize is False
assert pipeline.runs[-1]["want"] == {"probe", "audio", "transcribe"}
async def test_url_sources_are_forwarded_to_the_pipeline(
stub_pipeline: type[StubPipeline], tmp_path: Path
) -> None:
"""An http(s) source is accepted and handed to the ingest stage (no network here)."""
url = "https://example.com/lecture.mp4"
stub_pipeline.artifacts = _artifacts(tmp_path / "lecture.mp4", transcript=_transcript())
async with Client(mcp_server.mcp) as client:
await client.call_tool("transcribe_video", {"source": url})
assert stub_pipeline.instances[-1].runs[-1]["source"] == url
async def test_transcribe_video_explains_a_missing_audio_stream(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""A silent video fails with the actual reason instead of an empty transcript."""
stub_pipeline.artifacts = _artifacts(sample_video, transcript=None, has_audio=False)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="no audio stream"):
await client.call_tool("transcribe_video", {"source": str(sample_video)})
async def test_extract_keyframes_returns_shots_plus_image_blocks(
stub_pipeline: type[StubPipeline], sample_video: Path, tmp_path: Path
) -> None:
"""extract_keyframes returns the shot list as data and one JPEG block per keyframe."""
stub_pipeline.artifacts = _artifacts(sample_video, shots=_shots(tmp_path / "keyframes"))
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"extract_keyframes", {"source": str(sample_video), "max_shots": 2}
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["count"] == 2
assert [shot["index"] for shot in payload["shots"]] == [0, 1]
assert payload["shots"][0]["start"] == 0.0 and payload["shots"][0]["end"] == 5.0
assert payload["shots"][0]["description"]["shot_type"] == "screen"
assert payload["shots"][1]["keyframe"].endswith("shot-1.jpg")
images = _image_blocks(result)
assert len(images) == 2
for block in images:
assert block.mime_type == "image/jpeg"
assert base64.b64decode(block.data)[:2] == b"\xff\xd8"
assert result.content[0].type == "text"
assert "2 shot(s)" in result.content[0].text
pipeline = stub_pipeline.instances[-1]
assert pipeline.options == {"max_shots": 2}
assert pipeline.runs[-1]["want"] == {"probe", "shots"}
async def test_analyze_video_returns_a_report_and_reports_progress(
stub_pipeline: type[StubPipeline], sample_video: Path, tmp_path: Path
) -> None:
"""analyze_video runs every stage, streams progress and returns the validated report."""
transcript = _transcript()
shots = _shots(tmp_path / "keyframes")
stub_pipeline.artifacts = _artifacts(
sample_video,
transcript=transcript,
shots=shots,
report=_report(sample_video, transcript, shots),
)
notifications: list[tuple[float, float | None, str | None]] = []
async def handler(progress: float, total: float | None, message: str | None) -> None:
notifications.append((progress, total, message))
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_video", {"source": str(sample_video)}, progress_handler=handler
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["title"] == "Synthetic clip"
assert payload["duration"] == 10.0
assert payload["summary"] == "A synthetic test pattern with two spoken lines."
assert payload["topics"] == ["test pattern"]
assert payload["people"] == ["S1", "S2"]
assert payload["highlights"] == [
{"start": 2.0, "end": 4.0, "description": "[00:02] The second speaker answers."}
]
assert payload["shots"][0]["description"]["summary"] == "A red test pattern."
assert payload["transcript"]["segments"][1]["speaker"] == "S2"
# Default result is bounded: no word timings, transcript cap recorded in metadata.
assert payload["transcript"]["segments"][0]["words"] == []
assert payload["metadata"]["transcript_words_included"] is False
assert "transcript_truncated" in payload["metadata"]
assert notifications, "analyze_video should forward pipeline progress to the client"
assert all(total == 1.0 for _progress, total, _message in notifications)
assert notifications[-1][0] == 1.0
assert notifications[-1][2] is not None
assert "analysis finished" in notifications[-1][2]
pipeline = stub_pipeline.instances[-1]
assert pipeline.runs[-1]["want"] == set(STAGE_ORDER)
async def test_analyze_video_surfaces_model_server_failures(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""A down llama-server reaches the client with the pipeline's actionable hint."""
stub_pipeline.artifacts = _artifacts(sample_video)
stub_pipeline.failure = RuntimeError(
"llama-server is not reachable at http://127.0.0.1:8080/v1; start it with: "
"llama-server -hf bartowski/Qwen_Qwen3-VL-4B-Instruct-GGUF:Q4_K_M"
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="llama-server is not reachable") as excinfo:
await client.call_tool("analyze_video", {"source": str(sample_video)})
message = str(excinfo.value)
assert "Qwen_Qwen3-VL-4B-Instruct-GGUF" in message
assert "analyze_video failed" in message
assert "va doctor" in message
async def test_analyze_video_requires_audio_or_video(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""No report (no material at all) becomes an actionable error, not a None result."""
stub_pipeline.artifacts = _artifacts(
sample_video, transcript=None, has_audio=False, has_video=False
)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="no report was produced"):
await client.call_tool("analyze_video", {"source": str(sample_video)})
async def test_ask_video_answers_from_the_cached_report(
monkeypatch: pytest.MonkeyPatch,
stub_pipeline: type[StubPipeline],
sample_video: Path,
tmp_path: Path,
) -> None:
"""ask_video answers from the cached report and delegates to the synthesis result."""
transcript = _transcript()
shots = _shots(tmp_path / "keyframes")
stub_pipeline.artifacts = _artifacts(
sample_video,
transcript=transcript,
shots=shots,
report=_report(sample_video, transcript, shots),
)
calls: list[tuple[str, str]] = []
async def fake_answer(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: Any = None,
) -> AnswerResult:
calls.append((report.source, question))
return AnswerResult(answer="A synthetic test pattern [00:02].", cached=False)
monkeypatch.setattr(synthesis_module, "answer_question_result", fake_answer)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"ask_video", {"source": str(sample_video), "question": " What is shown? "}
)
assert result.structured_content["answer"] == "A synthetic test pattern [00:02]."
assert calls == [(str(sample_video), "What is shown?")]
assert stub_pipeline.instances[-1].runs[-1]["want"] == {"report"}
async def test_ask_video_is_cached_only_by_default(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""No report in the cache is an actionable error naming analyze_video, not a full run."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="Run analyze_video first"):
await client.call_tool(
"ask_video", {"source": str(sample_video), "question": "What happens?"}
)
assert stub_pipeline.instances[-1].runs[-1]["want"] == {"report"}
async def test_ask_video_rejects_a_blank_question(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""A blank question fails before any pipeline or model work starts."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="question must be a non-empty string"):
await client.call_tool("ask_video", {"source": str(sample_video), "question": " "})
assert stub_pipeline.instances == []
async def test_ask_video_explains_an_unreachable_model(
monkeypatch: pytest.MonkeyPatch,
stub_pipeline: type[StubPipeline],
sample_video: Path,
tmp_path: Path,
) -> None:
"""A failing synthesis model is reported with llama-server/hosted advice."""
transcript = _transcript()
shots = _shots(tmp_path / "ask-keyframes")
stub_pipeline.artifacts = _artifacts(
sample_video,
transcript=transcript,
shots=shots,
report=_report(sample_video, transcript, shots),
)
async def failing_answer(
report: VideoReport,
question: str,
*,
settings: Settings,
cache: Any = None,
) -> AnswerResult:
raise ConnectionError("Connection error.")
monkeypatch.setattr(synthesis_module, "answer_question_result", failing_answer)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="synthesis model could not answer") as excinfo:
await client.call_tool(
"ask_video", {"source": str(sample_video), "question": "What happens?"}
)
message = str(excinfo.value)
assert "Connection error." in message
assert "llama-server" in message
assert "deepseek:deepseek-flash" in message
async def test_get_frame_at_returns_a_real_jpeg(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""get_frame_at runs real ffmpeg against the fixture and returns a scaled JPEG."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool("get_frame_at", {"source": str(sample_video), "t": 2.5})
images = _image_blocks(result)
assert len(images) == 1
assert images[0].mime_type == "image/jpeg"
raw = base64.b64decode(images[0].data)
with PilImage.open(io.BytesIO(raw)) as frame:
assert frame.format == "JPEG"
assert 0 < frame.width <= mcp_server.FRAME_WIDTH
assert frame.height > 0
assert stub_pipeline.instances[-1].runs[-1]["want"] == {"probe"}
async def test_get_frame_at_rejects_timestamps_past_the_end(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""A timestamp outside the video surfaces as an actionable tool error."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="beyond the end"):
await client.call_tool("get_frame_at", {"source": str(sample_video), "t": 99.0})
async def test_analyze_moment_uses_real_frames_and_cached_context(
stub_pipeline: type[StubPipeline], sample_video: Path, tmp_path: Path
) -> None:
"""analyze_moment returns ffmpeg frames plus cached transcript slices and shot data."""
shots = _shots(tmp_path / "keyframes")
_seed_cache(tmp_path, sample_video, transcript=_transcript(speakers=False), shots=shots)
stub_pipeline.artifacts = _artifacts(sample_video, shots=shots)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 0.5, "t_end": 4.0},
)
payload = result.structured_content
assert payload["source"] == str(sample_video)
assert payload["t_start"] == 0.5
assert payload["t_end"] == 4.0
assert payload["duration"] == 10.0
assert len(payload["frame_timestamps"]) == 4
assert payload["frame_timestamps"] == sorted(payload["frame_timestamps"])
assert all(0.5 < stamp < 4.0 for stamp in payload["frame_timestamps"])
segments = payload["transcript"]
assert [segment["text"] for segment in segments] == ["there.", "General Kenobi."]
assert [segment["speaker"] for segment in segments] == ["S1", "S2"]
assert payload["transcript_text"] == "[00:00] S1: there.\n[00:02] S2: General Kenobi."
assert [shot["index"] for shot in payload["shots"]] == [0]
assert payload["shots"][0]["description"]["summary"] == "A red test pattern."
assert payload["notes"] == []
images = _image_blocks(result)
assert len(images) == 4
for block in images:
assert block.mime_type == "image/jpeg"
raw = base64.b64decode(block.data)
with PilImage.open(io.BytesIO(raw)) as frame:
assert frame.format == "JPEG"
assert frame.width <= mcp_server.FRAME_WIDTH
assert stub_pipeline.instances[-1].runs[-1]["want"] == {"probe"}
async def test_analyze_moment_without_cached_artifacts_explains_the_gap(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""With an empty cache, analyze_moment still returns frames and explains what is missing."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
result = await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 1.0, "t_end": 2.0},
)
payload = result.structured_content
assert payload["transcript"] == []
assert payload["transcript_text"] == ""
assert payload["shots"] == []
notes = " ".join(payload["notes"])
assert "No cached transcript" in notes
assert "No cached shots" in notes
assert len(_image_blocks(result)) == 4
async def test_analyze_moment_validates_the_window(
stub_pipeline: type[StubPipeline], sample_video: Path
) -> None:
"""A non-positive window is rejected before any ffmpeg work happens."""
stub_pipeline.artifacts = _artifacts(sample_video)
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError, match="t_end must be greater than t_start"):
await client.call_tool(
"analyze_moment",
{"source": str(sample_video), "t_start": 3.0, "t_end": 2.0},
)
async def test_missing_source_reports_an_actionable_error(
stub_pipeline: type[StubPipeline], tmp_path: Path
) -> None:
"""A missing local file fails fast with the resolved path in the message."""
missing = tmp_path / "not-here.mp4"
async with Client(mcp_server.mcp) as client:
with pytest.raises(ToolError) as excinfo:
await client.call_tool("transcribe_video", {"source": str(missing)})
message = str(excinfo.value)
assert "media file not found" in message
assert str(missing) in message
assert stub_pipeline.instances == []
class _RecordingServer:
"""Minimal stand-in for the FastMCP server, recording ``run`` calls."""
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def run(self, **kwargs: Any) -> None:
"""Record the transport options of one server start."""
self.calls.append(kwargs)
def test_run_defaults_to_stdio(monkeypatch: pytest.MonkeyPatch) -> None:
"""``run()`` and ``main()`` start the server over stdio without transport arguments."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
mcp_server.run()
mcp_server.main()
assert fake.calls == [{}, {}]
def test_run_serves_http_when_requested(monkeypatch: pytest.MonkeyPatch) -> None:
"""Requesting HTTP passes the host and port through to FastMCP."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
mcp_server.run(transport="http", host="0.0.0.0", port=9000)
assert fake.calls == [{"transport": "http", "host": "0.0.0.0", "port": 9000}]
def test_run_rejects_unknown_transports(monkeypatch: pytest.MonkeyPatch) -> None:
"""An unknown transport is rejected before any server is started."""
fake = _RecordingServer()
monkeypatch.setattr(mcp_server, "mcp", fake)
with pytest.raises(ValueError, match="unknown MCP transport"):
mcp_server.run(transport="carrier-pigeon")
assert fake.calls == []
+268
View File
@@ -0,0 +1,268 @@
"""Tests for ffprobe/ffmpeg/PySceneDetect helpers in ``video_analyse.media``.
Everything here runs locally against the synthetic ``sample_video`` fixture or
generated still images; no network access and no model downloads.
"""
from __future__ import annotations
import itertools
import json
import shutil
import subprocess
from pathlib import Path
import pytest
from PIL import Image, ImageDraw
from video_analyse.media import (
_apply_shot_budget,
_merge_short_segments,
dedup_keyframes,
detect_shots,
extract_audio,
extract_keyframes,
probe,
)
from video_analyse.models import Shot
FFPROBE = shutil.which("ffprobe")
def _ffprobe_json(path: Path) -> dict:
"""Run ffprobe -of json on a local file (test helper, no network)."""
if FFPROBE is None:
pytest.skip("ffprobe not found on PATH")
result = subprocess.run(
[
FFPROBE,
"-v",
"quiet",
"-show_format",
"-show_streams",
"-of",
"json",
str(path),
],
check=True,
capture_output=True,
text=True,
timeout=60,
)
return json.loads(result.stdout)
async def test_probe_reads_container_and_stream_fields(sample_video: Path) -> None:
info = await probe(sample_video)
assert info.path == sample_video
assert info.source == str(sample_video)
assert info.duration == pytest.approx(10.0, abs=0.2)
assert info.width == 640
assert info.height == 360
assert info.fps == pytest.approx(12.0, abs=0.01)
assert info.has_audio is True
assert info.size_bytes == sample_video.stat().st_size > 0
assert info.format is not None
assert "mp4" in info.format
assert info.video_codec == "h264"
assert info.audio_codec == "aac"
# the raw ffprobe payload is kept for reports/telemetry
assert info.extra["ffprobe"]["format"]["format_name"] == info.format
async def test_probe_missing_file_raises_value_error(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="not found"):
await probe(tmp_path / "does-not-exist.mp4")
async def test_probe_directory_raises_value_error(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="Not a regular file"):
await probe(tmp_path)
async def test_extract_audio_writes_16k_mono_s16_wav(sample_video: Path, tmp_path: Path) -> None:
wav = await extract_audio(sample_video, tmp_path)
assert wav == tmp_path / "audio.wav"
assert wav.is_file() and wav.stat().st_size > 44
streams = _ffprobe_json(wav)["streams"]
audio = next(stream for stream in streams if stream["codec_type"] == "audio")
assert audio["codec_name"] == "pcm_s16le"
assert int(audio["sample_rate"]) == 16_000
assert int(audio["channels"]) == 1
assert int(audio["bits_per_sample"]) == 16
assert audio["sample_fmt"] == "s16"
assert float(audio["duration"]) == pytest.approx(10.0, abs=0.2)
# probe() handles audio-only files: no video fields, still readable metadata
info = await probe(wav)
assert info.has_audio is True
assert info.audio_codec == "pcm_s16le"
assert info.width is None and info.height is None and info.fps is None
async def test_extract_audio_overwrites_existing_file(sample_video: Path, tmp_path: Path) -> None:
stale = tmp_path / "audio.wav"
stale.write_bytes(b"stale")
wav = await extract_audio(sample_video, tmp_path)
assert wav == stale
assert stale.stat().st_size > len(b"stale")
async def test_detect_shots_covers_duration_in_order(sample_video: Path) -> None:
info = await probe(sample_video)
shots = await detect_shots(sample_video, info, max_shots=2, min_scene_len=0.6)
assert 1 <= len(shots) <= 2
assert [shot.index for shot in shots] == list(range(len(shots)))
assert shots[0].start == 0.0
assert shots[-1].end == pytest.approx(info.duration, abs=0.01)
for shot in shots:
assert 0.0 <= shot.start < shot.end <= info.duration + 0.01
for previous, following in itertools.pairwise(shots):
assert previous.end == following.start
async def test_detect_shots_respects_shot_budget(sample_video: Path) -> None:
info = await probe(sample_video)
shots = await detect_shots(sample_video, info, max_shots=1)
assert len(shots) == 1
assert shots[0].index == 0
assert shots[0].start == 0.0
assert shots[0].end == pytest.approx(info.duration, abs=0.01)
with pytest.raises(ValueError, match="max_shots"):
await detect_shots(sample_video, info, max_shots=0)
async def test_detect_shots_requires_known_duration(sample_video: Path, tmp_path: Path) -> None:
info = (await probe(sample_video)).model_copy(update={"duration": 0.0})
# scenedetect still reports the duration from the container, so this succeeds ...
shots = await detect_shots(sample_video, info)
assert len(shots) >= 1
# ... while a file that is not a video is rejected
bad = tmp_path / "bad.mp4"
bad.write_bytes(b"not a video")
with pytest.raises((ValueError, RuntimeError)):
await detect_shots(bad, info)
def test_merge_short_segments_folds_into_closer_neighbour() -> None:
segments = [(0.0, 0.2), (0.2, 5.0), (5.0, 5.3), (5.3, 10.0)]
merged = _merge_short_segments(segments, 0.6)
assert merged == [(0.0, 5.0), (5.0, 10.0)]
# nothing shorter than the threshold -> untouched
assert _merge_short_segments(segments[1:], 0.3) == segments[1:]
# a single, unavoidable short segment is kept as-is
assert _merge_short_segments([(0.0, 0.2)], 0.6) == [(0.0, 0.2)]
def test_apply_shot_budget_merges_shortest_adjacent_pairs() -> None:
segments = [(0.0, 1.0), (1.0, 2.0), (2.0, 10.0)]
assert _apply_shot_budget(segments, 3) == segments
assert _apply_shot_budget(segments, 2) == [(0.0, 2.0), (2.0, 10.0)]
assert _apply_shot_budget(segments, 1) == [(0.0, 10.0)]
with pytest.raises(ValueError, match="max_shots"):
_apply_shot_budget(segments, 0)
async def test_extract_keyframes_writes_jpeg_per_shot(sample_video: Path, tmp_path: Path) -> None:
info = await probe(sample_video)
shots = await detect_shots(sample_video, info, max_shots=3)
extracted = await extract_keyframes(sample_video, shots, tmp_path)
assert len(extracted) == len(shots)
for shot in extracted:
assert shot.keyframe is not None
assert shot.keyframe == tmp_path / "keyframes" / f"shot-{shot.index}.jpg"
assert shot.keyframe.is_file() and shot.keyframe.stat().st_size > 0
assert shot.keyframe.read_bytes().startswith(b"\xff\xd8\xff") # JPEG SOI marker
with Image.open(shot.keyframe) as image:
width, height = image.size
assert 0 < width <= 768
assert height > 0
async def test_extract_keyframes_validates_arguments(sample_video: Path, tmp_path: Path) -> None:
shots = [Shot(index=0, start=0.0, end=1.0)]
with pytest.raises(ValueError, match="width"):
await extract_keyframes(sample_video, shots, tmp_path, width=0)
with pytest.raises(ValueError, match="quality"):
await extract_keyframes(sample_video, shots, tmp_path, quality=101)
with pytest.raises(ValueError, match="namespace"):
await extract_keyframes(sample_video, shots, tmp_path, namespace="../escape")
async def test_extract_keyframes_namespaces_frames_per_shots_key(
sample_video: Path, tmp_path: Path
) -> None:
"""Different shot-detection runs must not overwrite each other's keyframe JPEGs."""
shots = [Shot(index=0, start=0.0, end=5.0)]
first = await extract_keyframes(sample_video, shots, tmp_path, namespace="a" * 12)
first_bytes = first[0].keyframe.read_bytes() if first[0].keyframe else b""
other = [Shot(index=0, start=5.0, end=10.0)]
second = await extract_keyframes(sample_video, other, tmp_path, namespace="b" * 12)
assert first[0].keyframe == tmp_path / "keyframes" / ("a" * 12) / "shot-0.jpg"
assert second[0].keyframe == tmp_path / "keyframes" / ("b" * 12) / "shot-0.jpg"
assert first[0].keyframe.read_bytes() == first_bytes
assert first[0].keyframe.read_bytes() != second[0].keyframe.read_bytes()
def _pattern_image(path: Path, boxes: list[tuple[int, int, int, int]]) -> Path:
"""Write a small high-contrast JPEG so perceptual hashes are meaningful."""
image = Image.new("RGB", (96, 96), "white")
draw = ImageDraw.Draw(image)
for box in boxes:
draw.rectangle(box, fill="black")
image.save(path, format="JPEG", quality=90)
return path
def test_dedup_keyframes_drops_duplicate_content(tmp_path: Path) -> None:
original = _pattern_image(tmp_path / "a.jpg", [(0, 0, 30, 30), (30, 30, 96, 60)])
copy = _pattern_image(tmp_path / "a-copy.jpg", [(0, 0, 30, 30), (30, 30, 96, 60)])
different = _pattern_image(tmp_path / "b.jpg", [(60, 60, 96, 96), (0, 60, 40, 96)])
def fresh_shots() -> list[Shot]:
return [
Shot(index=0, start=0.0, end=1.0, keyframe=original),
Shot(index=1, start=1.0, end=2.0, keyframe=copy),
Shot(index=2, start=2.0, end=3.0, keyframe=different),
Shot(index=3, start=3.0, end=4.0, keyframe=None),
]
kept = dedup_keyframes(fresh_shots())
assert len(kept) == 3
# indices are preserved (the duplicate left a gap) so keyframe names keep matching
assert [shot.index for shot in kept] == [0, 2, 3]
assert kept[0].keyframe == original
assert kept[1].keyframe == different
assert kept[2].keyframe is None
assert kept[0].phash is not None and len(kept[0].phash) == 16
assert kept[1].phash is not None and len(kept[1].phash) == 16
assert kept[0].phash != kept[1].phash
assert kept[2].phash is None
# threshold 0 still drops exact duplicates ...
assert len(dedup_keyframes(fresh_shots(), threshold=0)) == 3
# ... while a large threshold also swallows the visibly different frame
assert len(dedup_keyframes(fresh_shots(), threshold=100)) == 2
with pytest.raises(ValueError, match="threshold"):
dedup_keyframes(fresh_shots(), threshold=-1)
def test_dedup_keyframes_keeps_unreadable_keyframes(tmp_path: Path) -> None:
broken = tmp_path / "broken.jpg"
broken.write_bytes(b"definitely not a jpeg")
shots = [
Shot(index=0, start=0.0, end=1.0, keyframe=broken),
Shot(index=1, start=1.0, end=2.0, keyframe=tmp_path / "missing.jpg"),
]
kept = dedup_keyframes(shots)
assert len(kept) == 2
assert all(shot.phash is None for shot in kept)
+186
View File
@@ -0,0 +1,186 @@
"""Round-trip and default tests for every pydantic model."""
from __future__ import annotations
from pathlib import Path
from video_analyse.models import (
Artifacts,
Highlight,
MediaInfo,
ReportCore,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
def _transcript() -> Transcript:
return Transcript(
language="en",
duration=12.5,
backend="faster-whisper",
model="large-v3-turbo",
segments=[
Segment(
start=0.0,
end=1.5,
text="hello world",
words=[Word(text="hello", start=0.0, end=0.7, probability=0.93)],
speaker="S1",
)
],
speaker_turns=[SpeakerTurn(start=0.0, end=12.5, speaker="S1")],
)
def _shot(tmp_path: Path) -> Shot:
return Shot(
index=0,
start=0.0,
end=4.2,
keyframe=tmp_path / "keyframes" / "000.jpg",
phash="f0e1d2c3b4a59687",
transcript_slice="S1: hello world",
description=ShotDescription(
summary="A person speaks to camera",
on_screen_text="HELLO",
shot_type="close-up",
people=["presenter"],
notable_objects=["microphone"],
setting="studio",
),
)
def test_media_info_roundtrip(tmp_path: Path) -> None:
media = MediaInfo(
path=tmp_path / "video.mp4",
source="video.mp4",
duration=10.0,
width=640,
height=360,
fps=12.0,
has_audio=True,
size_bytes=12345,
format="mp4",
video_codec="h264",
audio_codec="aac",
extra={"bit_rate": "48k"},
)
assert isinstance(media.path, Path)
dumped = media.model_dump_json()
restored = MediaInfo.model_validate_json(dumped)
assert restored == media
assert isinstance(restored.path, Path)
assert restored.extra["bit_rate"] == "48k"
def test_nullable_media_info_fields_default_to_none(tmp_path: Path) -> None:
media = MediaInfo(
path=tmp_path / "audio_only.m4a",
source="audio_only.m4a",
duration=3.0,
has_audio=True,
size_bytes=1,
)
assert media.width is None
assert media.fps is None
assert media.video_codec is None
assert media.format is None
assert media.extra == {}
def test_word_and_segment_defaults() -> None:
word = Word(text="hi", start=0.0, end=0.2)
assert word.probability is None
segment = Segment(start=0.0, end=0.2, text="hi")
assert segment.words == []
assert segment.speaker is None
# default containers are per-instance, not shared
segment.words.append(word)
assert Segment(start=0.0, end=0.2, text="hi").words == []
def test_transcript_roundtrip(tmp_path: Path) -> None:
transcript = _transcript()
restored = Transcript.model_validate_json(transcript.model_dump_json())
assert restored == transcript
assert restored.segments[0].words[0].probability == 0.93
assert restored.speaker_turns[0].speaker == "S1"
assert restored.backend == "faster-whisper"
def test_shot_roundtrip_with_nested_description(tmp_path: Path) -> None:
shot = _shot(tmp_path)
restored = Shot.model_validate_json(shot.model_dump_json())
assert restored == shot
assert isinstance(restored.keyframe, Path)
assert restored.description is not None
assert restored.description.shot_type == "close-up"
bare = Shot(index=1, start=4.2, end=8.0)
assert bare.keyframe is None
assert bare.phash is None
assert bare.transcript_slice == ""
assert bare.description is None
def test_shot_description_requires_known_shot_type() -> None:
desc = ShotDescription(summary="s", shot_type="screen")
assert desc.people == [] and desc.notable_objects == [] and desc.on_screen_text is None
assert ShotDescription.model_validate_json(desc.model_dump_json()) == desc
def test_report_core_and_highlight() -> None:
core = ReportCore(
title="Talk",
summary="A short talk",
topics=["ai"],
people=["Ada"],
highlights=[Highlight(start=1.0, end=2.0, description="key line")],
)
restored = ReportCore.model_validate_json(core.model_dump_json())
assert restored == core
assert restored.highlights[0].description == "key line"
def test_video_report_roundtrip(tmp_path: Path) -> None:
report = VideoReport(
source="video.mp4",
title="Talk",
duration=10.0,
summary="A short talk about things",
topics=["ai", "video"],
people=["Ada"],
highlights=[Highlight(start=1.0, end=2.0, description="key line")],
shots=[_shot(tmp_path)],
transcript=_transcript(),
metadata={"ffprobe": {"format_name": "mov,mp4"}},
)
restored = VideoReport.model_validate_json(report.model_dump_json())
assert restored == report
assert restored.transcript is not None
assert restored.shots[0].keyframe == tmp_path / "keyframes" / "000.jpg"
assert isinstance(restored.shots[0].keyframe, Path)
# transcript is optional
no_transcript = report.model_copy(update={"transcript": None})
assert VideoReport.model_validate_json(no_transcript.model_dump_json()).transcript is None
def test_artifacts_defaults_and_roundtrip(tmp_path: Path) -> None:
artifacts = Artifacts(source="video.mp4", workdir=tmp_path)
assert artifacts.media is None
assert artifacts.transcript is None
assert artifacts.shots == []
assert artifacts.report is None
restored = Artifacts.model_validate_json(artifacts.model_dump_json())
assert restored == artifacts
assert isinstance(restored.workdir, Path)
+730
View File
@@ -0,0 +1,730 @@
"""Pipeline orchestration tests using injected fake stages.
The ``stages`` dependency-injection mapping of
:class:`video_analyse.pipeline.Pipeline` replaces every stage, so these tests never
import the ffmpeg/ffprobe wrappers, an STT/diarization backend or the VLM modules and
never touch the network or a model file. Media files are plain bytes: only their
content hash matters to the pipeline.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
import pytest
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.ingest import IngestResult
from video_analyse.models import (
Artifacts,
MediaInfo,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.pipeline import STAGE_ORDER, Pipeline
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep every test independent of the developer's environment."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
def _settings(tmp_path: Path, **overrides: Any) -> Settings:
"""Settings rooted at ``tmp_path`` with explicit, key-relevant values."""
values: dict[str, Any] = {
"cache_dir": tmp_path / "cache",
"profile": "local",
"language": None,
"stt_backend": "whisper",
"whisper_model": "tiny",
"diarize": True,
"diarize_backend": "sherpa",
"vlm_model": "local:fake-vlm",
"synthesis_model": "local:fake-synthesis",
}
values.update(overrides)
return Settings(**values)
def _make_source(tmp_path: Path, name: str = "clip.mp4", payload: bytes = b"fake video") -> Path:
"""Create a local file whose bytes the pipeline can hash."""
path = tmp_path / "media" / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(payload)
return path
class FakeStages:
"""Deterministic stand-ins for every pipeline stage, recording every call."""
def __init__(
self,
source: Path,
*,
has_audio: bool = True,
has_video: bool = True,
shots: list[Shot] | None = None,
turns: list[SpeakerTurn] | None = None,
) -> None:
self.source = source
self.has_audio = has_audio
self.has_video = has_video
self.shot_template = (
shots
if shots is not None
else [Shot(index=0, start=0.0, end=5.0), Shot(index=1, start=5.0, end=10.0)]
)
self.turn_template = (
turns
if turns is not None
else [
SpeakerTurn(start=0.0, end=5.0, speaker="S1"),
SpeakerTurn(start=5.0, end=10.0, speaker="S2"),
]
)
self.calls: list[str] = []
self.ingest_calls: list[tuple[str, Path, int]] = []
self.probe_calls: list[Path] = []
self.audio_calls: list[tuple[Path, Path]] = []
self.transcribe_calls: list[Path] = []
self.diarize_calls: list[Path] = []
self.shots_calls: list[tuple[Path, Path]] = []
self.describe_calls: list[int] = []
self.report_calls: list[bool] = []
def mapping(self) -> dict[str, Any]:
"""The ``stages`` mapping for :class:`Pipeline`."""
return {
"ingest": self.ingest,
"probe": self.probe,
"audio": self.audio,
"transcribe": self.transcribe,
"diarize": self.diarize,
"shots": self.shots,
"describe": self.describe,
"report": self.report,
}
# ------------------------------------------------------------------ #
# stage fakes
# ------------------------------------------------------------------ #
async def ingest(self, source: str, *, cache_dir: Path, quality: int) -> IngestResult:
"""Pretend to download ``source`` into the cache."""
self.calls.append("ingest")
self.ingest_calls.append((source, cache_dir, quality))
return IngestResult(
path=self.source, info={"title": "Fake video"}, downloaded=True, title="Fake video"
)
async def probe(self, path: Path) -> MediaInfo:
"""Return synthetic media facts for ``path``."""
self.calls.append("probe")
self.probe_calls.append(path)
return MediaInfo(
path=path,
source=str(path),
duration=10.0,
width=640 if self.has_video else None,
height=360 if self.has_video else None,
fps=12.0 if self.has_video else None,
has_audio=self.has_audio,
size_bytes=path.stat().st_size,
format="mp4",
extra={"title": "Fake video"},
)
async def audio(self, path: Path, workdir: Path) -> Path:
"""Write a placeholder WAV where the real extractor would."""
self.calls.append("audio")
self.audio_calls.append((path, workdir))
wav = Path(workdir) / "audio.wav"
wav.parent.mkdir(parents=True, exist_ok=True)
wav.write_bytes(b"RIFF" + b"\x00" * 64)
return wav
async def transcribe(self, wav: Path, *, settings: Settings) -> Transcript:
"""Return a two-segment transcript with word timings."""
self.calls.append("transcribe")
self.transcribe_calls.append(wav)
return Transcript(
language=settings.language or "en",
duration=10.0,
segments=[
Segment(
start=0.0,
end=4.0,
text="first line",
words=[Word(text="first", start=1.0, end=1.5)],
),
Segment(
start=5.0,
end=9.0,
text="second line",
words=[Word(text="second", start=6.0, end=6.5)],
),
],
backend="fake",
model="fake-model",
)
async def diarize(self, wav: Path, *, settings: Settings) -> list[SpeakerTurn]:
"""Return the canned speaker turns."""
self.calls.append("diarize")
self.diarize_calls.append(wav)
return [turn.model_copy(deep=True) for turn in self.turn_template]
async def shots(
self, path: Path, info: MediaInfo, *, workdir: Path, settings: Settings
) -> list[Shot]:
"""Return the canned shot list."""
self.calls.append("shots")
self.shots_calls.append((path, workdir))
return [shot.model_copy(deep=True) for shot in self.shot_template]
async def describe(
self, shots: list[Shot], transcript: Transcript | None, *, settings: Settings
) -> list[Shot]:
"""Attach a description to every shot."""
self.calls.append("describe")
self.describe_calls.append(len(shots))
for shot in shots:
shot.description = ShotDescription(
summary=f"shot {shot.index} summary", shot_type="screen"
)
return shots
async def report(
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
settings: Settings,
) -> VideoReport:
"""Assemble a report from exactly the material that was handed in."""
self.calls.append("report")
self.report_calls.append(transcript is not None)
return VideoReport(
source=info.source,
title="Fake video",
duration=info.duration,
summary="fake report",
topics=["fakes"],
people=[],
highlights=[],
shots=[shot.model_copy(deep=True) for shot in shots],
transcript=transcript,
metadata={"has_audio": info.has_audio},
)
def _stage_messages(messages: list[str]) -> list[str]:
"""Return the stage name of every progress message, in order."""
return [message.split(":", 1)[0] for message in messages]
# --------------------------------------------------------------------------- #
# happy path, ordering, progress
# --------------------------------------------------------------------------- #
async def test_full_run_orders_stages_and_assembles_artifacts(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == list(STAGE_ORDER)
assert _stage_messages(messages) == ["ingest", *STAGE_ORDER]
assert "probe: running" in messages and "report: running" in messages
cache = StageCache(settings.cache_dir)
assert artifacts.source == str(source)
assert artifacts.workdir == cache.source_dir(cache.source_hash(source))
assert artifacts.media is not None
assert artifacts.media.source == str(source)
assert artifacts.media.path == source.resolve()
assert artifacts.transcript is not None
assert [segment.speaker for segment in artifacts.transcript.segments] == ["S1", "S2"]
assert len(artifacts.transcript.speaker_turns) == 2
assert len(artifacts.shots) == 2
assert all(shot.description is not None for shot in artifacts.shots)
assert fakes.describe_calls == [2]
assert artifacts.report is not None
assert artifacts.report.source == str(source)
assert artifacts.report.transcript == artifacts.transcript
assert artifacts.report.shots == artifacts.shots
assert fakes.report_calls == [True]
async def test_stage_callables_receive_source_and_workdir(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
artifacts = await pipeline.run(str(source), want={"transcribe", "shots"})
assert fakes.probe_calls == [source.resolve()]
assert fakes.audio_calls == [(source.resolve(), artifacts.workdir)]
assert fakes.transcribe_calls == [artifacts.workdir / "audio.wav"]
assert fakes.shots_calls == [(source.resolve(), artifacts.workdir)]
# --------------------------------------------------------------------------- #
# caching
# --------------------------------------------------------------------------- #
async def test_second_run_is_fully_cached(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
executed = list(fakes.calls)
messages: list[str] = []
second = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == executed # every stage was a cache hit
assert all(f"{stage}: cached" in messages for stage in STAGE_ORDER)
assert second.report is not None
assert second.report.model_dump(mode="json") == first.report.model_dump(mode="json")
assert second.transcript == first.transcript
async def test_report_only_run_reuses_cached_material(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
executed = list(fakes.calls)
messages: list[str] = []
second = await pipeline.run(str(source), want={"report"}, progress=messages.append)
assert fakes.calls == executed
assert "probe: cached" in messages
assert "audio: skipped (not requested)" in messages
assert "transcribe: cached (context)" in messages
assert "diarize: cached (context)" in messages
assert "shots: cached (context)" in messages
assert "describe: cached (context)" in messages
assert "report: cached" in messages
assert second.report is not None
assert second.report.model_dump(mode="json") == first.report.model_dump(mode="json")
async def test_force_reruns_wanted_stage_and_drops_downstream_cache(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
workdir = first.workdir
assert list(workdir.glob("stage-diarize-*.json"))
assert list(workdir.glob("stage-report-*.json"))
fakes.calls.clear()
messages: list[str] = []
second = await pipeline.run(
str(source), want={"transcribe"}, force=True, progress=messages.append
)
assert fakes.calls == ["transcribe"] # probe/audio stayed cached
assert "probe: cached" in messages
assert "audio: cached" in messages
assert "transcribe: running" in messages
assert list(workdir.glob("stage-transcribe-*.json"))
assert not list(workdir.glob("stage-diarize-*.json"))
assert not list(workdir.glob("stage-report-*.json"))
# Descriptions embed the transcript slice, so a forced re-transcription must drop
# them as well (the describe key now includes the transcript/diarize keys).
assert not list(workdir.glob("stage-describe-*.json"))
assert second.transcript is not None
assert second.report is None
async def test_force_shots_drops_descriptions_and_report(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
workdir = first.workdir
fakes.calls.clear()
messages: list[str] = []
second = await pipeline.run(str(source), want={"shots"}, force=True, progress=messages.append)
assert fakes.calls == ["shots"]
assert "shots: running" in messages
assert not list(workdir.glob("stage-describe-*.json"))
assert not list(workdir.glob("stage-report-*.json"))
assert list(workdir.glob("stage-diarize-*.json"))
assert len(second.shots) == 2
assert all(shot.description is None for shot in second.shots)
async def test_force_report_reruns_only_the_report(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
await pipeline.run(str(source))
fakes.calls.clear()
messages: list[str] = []
artifacts = await pipeline.run(
str(source), want={"report"}, force=True, progress=messages.append
)
assert fakes.calls == ["report"]
assert "report: running" in messages
assert artifacts.report is not None
async def test_corrupt_cache_artifact_is_treated_as_a_miss(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
(report_file,) = first.workdir.glob("stage-report-*.json")
report_file.write_text("{not json", encoding="utf-8")
fakes.calls.clear()
messages: list[str] = []
second = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["report"]
assert "report: running" in messages
assert second.report is not None
async def test_transcribe_cache_key_tracks_stt_configuration(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path, whisper_model="tiny"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["probe", "audio", "transcribe"]
fakes.calls.clear()
await Pipeline(_settings(tmp_path, whisper_model="base"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["transcribe"]
fakes.calls.clear()
await Pipeline(_settings(tmp_path, whisper_model="base", language="en"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["transcribe"]
async def test_transcribe_cache_key_tracks_the_stt_endpoint(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
base = {
"stt_backend": "openai-transcriptions",
"stt_api_base_url": "https://one.example.invalid/v1",
}
await Pipeline(_settings(tmp_path, **base), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["probe", "audio", "transcribe"]
fakes.calls.clear()
await Pipeline(
_settings(tmp_path, **{**base, "stt_api_base_url": "https://two.example.invalid/v1"}),
fakes.mapping(),
).run(str(source), want={"transcribe"})
assert fakes.calls == ["transcribe"]
async def test_artifacts_json_is_persisted(tmp_path: Path) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
artifacts = await pipeline.run(str(source))
path = artifacts.workdir / "artifacts.json"
assert path.is_file()
loaded = Artifacts.model_validate_json(path.read_text(encoding="utf-8"))
assert loaded.model_dump(mode="json") == artifacts.model_dump(mode="json")
# --------------------------------------------------------------------------- #
# diarization gating
# --------------------------------------------------------------------------- #
async def test_diarize_disabled_in_settings_skips_the_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path, diarize=False), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert "diarize" not in fakes.calls
assert "diarize: skipped (disabled in settings)" in messages
assert artifacts.transcript is not None
assert artifacts.transcript.speaker_turns == []
assert all(segment.speaker is None for segment in artifacts.transcript.segments)
async def test_diarize_not_in_want_skips_the_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), want={"transcribe"}, progress=messages.append)
assert fakes.calls == ["probe", "audio", "transcribe"]
assert "diarize: skipped (not requested)" in messages
assert artifacts.transcript is not None
assert artifacts.transcript.speaker_turns == []
async def test_diarize_attributes_speakers_into_the_transcript(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
artifacts = await Pipeline(_settings(tmp_path), fakes.mapping()).run(
str(source), want={"diarize"}
)
assert fakes.calls == ["probe", "audio", "transcribe", "diarize"]
assert artifacts.transcript is not None
assert [segment.speaker for segment in artifacts.transcript.segments] == ["S1", "S2"]
assert [turn.speaker for turn in artifacts.transcript.speaker_turns] == ["S1", "S2"]
assert artifacts.report is None
# --------------------------------------------------------------------------- #
# graceful degradation
# --------------------------------------------------------------------------- #
async def test_describe_skipped_without_shots(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, shots=[])
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert "describe" not in fakes.calls
assert "describe: skipped (no shots)" in messages
assert artifacts.shots == []
assert artifacts.report is not None # the transcript alone is enough material
async def test_report_skipped_without_any_material(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, has_audio=False, shots=[])
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["probe", "shots"]
assert "report: skipped (no transcript or shots)" in messages
assert artifacts.transcript is None
assert artifacts.report is None
assert artifacts.media is not None
async def test_source_without_audio_skips_speech_stages(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, has_audio=False)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["probe", "shots", "describe", "report"]
assert "audio: skipped (source has no audio)" in messages
assert "transcribe: skipped (no audio)" in messages
assert "diarize: skipped (no transcript)" in messages
assert artifacts.transcript is None
assert len(artifacts.shots) == 2
assert artifacts.report is not None
assert artifacts.report.transcript is None
async def test_source_without_video_skips_shots(tmp_path: Path) -> None:
source = _make_source(tmp_path, name="audio.mp3")
fakes = FakeStages(source, has_video=False)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[str] = []
artifacts = await pipeline.run(
str(source), want={"shots", "transcribe"}, progress=messages.append
)
assert fakes.calls == ["probe", "audio", "transcribe"]
assert "shots: skipped (source has no video)" in messages
assert artifacts.shots == []
# --------------------------------------------------------------------------- #
# URL sources and the ingest stage
# --------------------------------------------------------------------------- #
async def test_url_source_runs_the_ingest_stage_first(tmp_path: Path) -> None:
url = "https://example.com/videos/clip.mp4"
local = _make_source(tmp_path)
fakes = FakeStages(local)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping(), ingest_quality=720)
messages: list[str] = []
artifacts = await pipeline.run(url, want={"probe"}, progress=messages.append)
assert fakes.calls == ["ingest", "probe"]
assert fakes.ingest_calls == [(url, settings.cache_dir, 720)]
assert fakes.probe_calls == [local]
assert messages[0] == f"ingest: fetching {url}"
assert "ingest: ready (clip.mp4)" in messages
assert artifacts.source == url
assert artifacts.media is not None
assert artifacts.media.source == url
assert artifacts.media.path == local
async def test_local_source_never_calls_the_ingest_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path), fakes.mapping()).run(str(source), want={"probe"})
assert "ingest" not in fakes.calls
assert fakes.calls == ["probe"]
# --------------------------------------------------------------------------- #
# validation
# --------------------------------------------------------------------------- #
async def test_unknown_stage_names_are_rejected(tmp_path: Path) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
with pytest.raises(ValueError, match="unknown pipeline stage"):
await pipeline.run(str(source), want={"probe", "nope"})
with pytest.raises(TypeError, match="collection of stage names"):
await pipeline.run(str(source), want="probe") # type: ignore[arg-type]
with pytest.raises(ValueError, match="source must not be empty"):
await pipeline.run(" ")
async def test_missing_and_unsupported_sources_are_rejected(tmp_path: Path) -> None:
pipeline = Pipeline(_settings(tmp_path), FakeStages(_make_source(tmp_path)).mapping())
with pytest.raises(ValueError, match="Local media file not found"):
await pipeline.run(str(tmp_path / "absent.mp4"))
with pytest.raises(ValueError, match="unsupported URL scheme"):
await pipeline.run("ftp://example.com/clip.mp4")
def test_constructor_validates_its_options(tmp_path: Path) -> None:
settings = _settings(tmp_path)
with pytest.raises(ValueError, match="max_shots"):
Pipeline(settings, max_shots=0)
with pytest.raises(ValueError, match="min_scene_len"):
Pipeline(settings, min_scene_len=-0.5)
with pytest.raises(ValueError, match="ingest_quality"):
Pipeline(settings, ingest_quality=0)
with pytest.raises(ValueError, match="unknown stage"):
Pipeline(settings, {"bogus": object()}) # type: ignore[dict-item]
async def test_transcript_slice_is_populated_for_every_shot(tmp_path: Path) -> None:
"""PLAN §4: shots carry the words spoken during them (speaker-prefixed)."""
source = _make_source(tmp_path)
artifacts = await Pipeline(_settings(tmp_path), FakeStages(source).mapping()).run(str(source))
assert [shot.transcript_slice for shot in artifacts.shots] == [
"[00:00] S1: first",
"[00:05] S2: second",
]
assert artifacts.report is not None
assert artifacts.report.shots[1].transcript_slice == "[00:05] S2: second"
async def test_probe_and_report_use_the_current_source_path(tmp_path: Path) -> None:
"""Byte-identical copies under different names must not share a stale path."""
first = _make_source(tmp_path, name="one.mp4")
settings = _settings(tmp_path)
await Pipeline(settings, FakeStages(first).mapping()).run(str(first), want={"probe"})
first.unlink()
second = _make_source(tmp_path, name="two.mp4")
messages: list[str] = []
artifacts = await Pipeline(settings, FakeStages(second).mapping()).run(
str(second), want={"probe"}, progress=messages.append
)
assert artifacts.media is not None
assert artifacts.media.path == second.resolve()
assert artifacts.media.source == str(second)
assert "probe: running" in messages
def test_rebase_media_merges_yt_dlp_metadata_and_title(tmp_path: Path) -> None:
"""PLAN §4: URL reports carry ffprobe + yt-dlp metadata, including the title."""
local = _make_source(tmp_path)
probed = MediaInfo(
path=local,
source=str(local),
duration=10.0,
has_audio=True,
size_bytes=local.stat().st_size,
extra={"ffprobe": {"format": {"filename": str(local)}}},
)
ingested = IngestResult(
path=local,
info={"title": "Real title", "id": "abc"},
downloaded=True,
title="Real title",
)
media = Pipeline._rebase_media(probed, "https://example.invalid/watch?v=abc", local, ingested)
assert media.source == "https://example.invalid/watch?v=abc"
assert media.path == local
assert media.extra["title"] == "Real title"
assert media.extra["yt_dlp"]["id"] == "abc"
async def test_describe_cache_key_tracks_diarization_context(tmp_path: Path) -> None:
"""Descriptions embed the speaker-labelled transcript, so --no-diarize re-describes."""
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path), fakes.mapping()).run(str(source))
assert fakes.describe_calls == [2]
fakes.calls.clear()
fakes.describe_calls.clear()
await Pipeline(_settings(tmp_path, diarize=False), fakes.mapping()).run(str(source))
assert fakes.describe_calls == [2]
+220
View File
@@ -0,0 +1,220 @@
"""Offline tests for the deterministic Markdown report renderer."""
from __future__ import annotations
from pathlib import Path
import pytest
from video_analyse.models import (
Highlight,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
)
from video_analyse.report import format_timestamp, render_markdown
@pytest.fixture
def report() -> VideoReport:
"""A fully-populated report exercising every rendered section."""
transcript = Transcript(
language="en",
duration=95.0,
backend="parakeet",
model="nemo-parakeet-tdt-0.6b-v3",
segments=[
Segment(start=0.0, end=5.5, text=" Hello and welcome to the demo. ", speaker="S1"),
Segment(start=65.25, end=70.0, text="Let us look\nat the results.", speaker="S2"),
Segment(start=70.0, end=72.0, text="Any questions?"),
],
speaker_turns=[
SpeakerTurn(start=0.0, end=5.5, speaker="S1"),
SpeakerTurn(start=65.25, end=72.0, speaker="S2"),
],
)
shots = [
Shot(
index=0,
start=0.0,
end=15.4,
keyframe=Path("/media/keyframes/000.jpg"),
phash="8000000000000000",
transcript_slice="Hello and welcome to the demo.",
description=ShotDescription(
summary="Title slide on a blue background.",
on_screen_text="DEMO 2026",
shot_type="screen",
notable_objects=["slide"],
setting="studio",
),
),
Shot(
index=1,
start=15.4,
end=95.0,
keyframe=Path("/media/keyframes/001.jpg"),
description=ShotDescription(
summary="Presenter standing at a whiteboard.",
shot_type="medium",
people=["Alice"],
),
),
]
return VideoReport(
source="/media/sample.mp4",
title="Demo report",
duration=95.0,
summary="A short demo about testing.\nIt covers two topics.",
topics=["testing", "demo"],
people=["Alice", "Bob"],
highlights=[
Highlight(start=65.25, end=70.0, description="[01:05] Results are shown."),
Highlight(start=0.0, end=5.5, description="Intro and agenda."),
],
shots=shots,
transcript=transcript,
metadata={"format": "mp4"},
)
@pytest.mark.parametrize(
("seconds", "expected"),
[
(0.0, "00:00"),
(5.9, "00:05"),
(65.25, "01:05"),
(599.0, "09:59"),
(3599.9, "59:59"),
(3661.0, "61:01"),
(-3.0, "00:00"),
(float("nan"), "00:00"),
(float("inf"), "00:00"),
],
)
def test_format_timestamp_renders_mm_ss(seconds: float, expected: str) -> None:
assert format_timestamp(seconds) == expected
def test_render_markdown_has_the_expected_sections_in_order(report: VideoReport) -> None:
markdown = render_markdown(report)
headings = [
"# Demo report",
"## Summary",
"## Highlights",
"## Shot-by-shot",
"## Transcript",
]
positions = [markdown.index(heading) for heading in headings]
assert positions == sorted(positions)
assert markdown.startswith("# Demo report\n")
assert markdown.endswith("\n") and not markdown.endswith("\n\n")
def test_render_markdown_renders_media_facts_and_summary(report: VideoReport) -> None:
markdown = render_markdown(report)
assert "- **Source:** `/media/sample.mp4`" in markdown
assert "- **Duration:** 01:35" in markdown
assert "- **Language:** en" in markdown
assert "- **Transcript:** parakeet (nemo-parakeet-tdt-0.6b-v3)" in markdown
assert "A short demo about testing. It covers two topics." in markdown
assert "- **Topics:** testing, demo" in markdown
assert "- **People:** Alice, Bob" in markdown
def test_render_markdown_renders_highlights_with_mmss(report: VideoReport) -> None:
markdown = render_markdown(report)
assert "- **[01:05-01:10]** [01:05] Results are shown." in markdown
assert "- **[00:00-00:05]** Intro and agenda." in markdown
def test_render_markdown_renders_shot_headings_and_descriptions(report: VideoReport) -> None:
markdown = render_markdown(report)
assert "### Shot 0 — [00:00-00:15]" in markdown
assert "### Shot 1 — [00:15-01:35]" in markdown
assert "- **Type:** screen" in markdown
assert "- **Summary:** Title slide on a blue background." in markdown
assert "- **On-screen text:** DEMO 2026" in markdown
assert "- **Objects:** slide" in markdown
assert "- **Setting:** studio" in markdown
assert "- **People:** Alice" in markdown
assert "- **Transcript:** Hello and welcome to the demo." in markdown
def test_render_markdown_links_keyframes_relative_to_the_document(report: VideoReport) -> None:
markdown = render_markdown(report, keyframes_relpath=Path("assets/keyframes"))
assert "![Shot 0 keyframe](assets/keyframes/000.jpg)" in markdown
assert "![Shot 1 keyframe](assets/keyframes/001.jpg)" in markdown
assert "/media/keyframes" not in markdown
def test_render_markdown_keeps_the_shots_keyframe_subdirectory(report: VideoReport) -> None:
"""Namespaced keyframes stay linked: keyframes/<shots-key>/shot-N.jpg."""
report.shots[0].keyframe = Path("/media/keyframes/0123456789ab/000.jpg")
markdown = render_markdown(report, keyframes_relpath=Path("keyframes"))
assert "![Shot 0 keyframe](keyframes/0123456789ab/000.jpg)" in markdown
def test_render_markdown_defaults_to_bare_keyframe_filenames(report: VideoReport) -> None:
markdown = render_markdown(report)
assert "![Shot 0 keyframe](000.jpg)" in markdown
assert "/media/keyframes" not in markdown
def test_render_markdown_dot_relative_keyframes_are_clean(report: VideoReport) -> None:
markdown = render_markdown(report, keyframes_relpath=Path("."))
assert "![Shot 0 keyframe](000.jpg)" in markdown
def test_render_markdown_renders_the_speaker_labelled_transcript(report: VideoReport) -> None:
markdown = render_markdown(report)
appendix = markdown.split("## Transcript", 1)[1]
assert "**[00:00] S1:** Hello and welcome to the demo." in appendix
assert "**[01:05] S2:** Let us look at the results." in appendix
assert "**[01:10]** Any questions?" in appendix
def test_render_markdown_handles_empty_sections() -> None:
empty = VideoReport(
source="/media/empty.mp4",
duration=1.0,
summary="",
topics=[],
people=[],
highlights=[],
shots=[],
)
markdown = render_markdown(empty)
assert markdown.startswith("# empty.mp4\n")
assert "No summary available." in markdown
assert "- **Topics:** none identified" in markdown
assert "- **People:** none identified" in markdown
assert "No highlights were identified." in markdown
assert "No shots were detected." in markdown
assert "No transcript available." in markdown
def test_render_markdown_marks_undescribed_shots() -> None:
report = VideoReport(
source="/media/sample.mp4",
title="Sparse",
duration=10.0,
summary="Sparse report.",
topics=["t"],
people=[],
highlights=[],
shots=[Shot(index=3, start=2.0, end=8.0)],
)
markdown = render_markdown(report)
assert "### Shot 3 — [00:02-00:08]" in markdown
assert "- **Description:** no visual description available" in markdown
def test_render_markdown_is_deterministic(report: VideoReport) -> None:
first = render_markdown(report, keyframes_relpath=Path("keyframes"))
second = render_markdown(report, keyframes_relpath=Path("keyframes"))
assert first == second
assert first.count("\n") == second.count("\n")
+568
View File
@@ -0,0 +1,568 @@
"""Offline tests for synthesis: prompt budgeting, report assembly and Q&A.
Every test monkeypatches ``video_analyse.llm.build_model`` with a
``FunctionModel`` (pydantic-ai's scripted, network-free model), so nothing here
touches a socket, an API key or a model download.
"""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
import pytest
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, ToolCallPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
from video_analyse import llm, synthesis
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.models import (
Highlight,
MediaInfo,
ReportCore,
Segment,
Shot,
ShotDescription,
Transcript,
VideoReport,
)
from video_analyse.synthesis import (
LOCAL_PROMPT_CHARS,
PROVIDER_PROMPT_CHARS,
answer_question,
answer_question_result,
assemble_report,
build_question_prompt,
build_synthesis_prompt,
default_char_budget,
estimate_tokens,
fit_prompt,
format_shots,
format_transcript,
metadata_from_info,
synthesise_report,
)
LOCAL_SETTINGS = Settings(profile="local", synthesis_model=None)
HOSTED_SETTINGS = Settings(profile="hosted", synthesis_model="deepseek:deepseek-flash")
def _info(**overrides: object) -> MediaInfo:
data: dict[str, object] = {
"path": Path("/media/sample.mp4"),
"source": "/media/sample.mp4",
"duration": 95.0,
"width": 640,
"height": 360,
"fps": 12.0,
"has_audio": True,
"size_bytes": 4096,
"format": "mp4",
"video_codec": "h264",
"audio_codec": "aac",
"extra": {"title": "Metadata title"},
}
data.update(overrides)
return MediaInfo(**data) # type: ignore[arg-type]
def _transcript() -> Transcript:
return Transcript(
language="en",
duration=95.0,
backend="parakeet",
model="nemo-parakeet-tdt-0.6b-v3",
segments=[
Segment(start=0.0, end=5.5, text=" Hello and welcome to the demo. ", speaker="S1"),
Segment(start=65.25, end=70.0, text="Let us look at the results.", speaker="S2"),
],
)
def _shots() -> list[Shot]:
return [
Shot(
index=0,
start=0.0,
end=15.4,
keyframe=Path("/media/keyframes/000.jpg"),
phash="8000000000000000",
transcript_slice="Hello and welcome to the demo.",
description=ShotDescription(
summary="Title slide on a blue background.",
on_screen_text="DEMO 2026",
shot_type="screen",
notable_objects=["slide"],
setting="studio",
),
),
Shot(
index=1,
start=15.4,
end=95.0,
keyframe=Path("/media/keyframes/001.jpg"),
description=ShotDescription(
summary="Presenter at a whiteboard.",
shot_type="medium",
people=["Alice"],
),
),
]
def _report() -> VideoReport:
core = ReportCore(
title="Demo report",
summary="A short demo about testing.",
topics=["testing", "demo"],
people=["Alice"],
highlights=[Highlight(start=65.25, end=70.0, description="[01:05] Results are shown.")],
)
return assemble_report(core, _shots(), _transcript(), _info())
def _prompt_text(messages: list[ModelMessage]) -> str:
"""Flatten every string prompt part of a rendered conversation."""
chunks: list[str] = []
for message in messages:
for part in message.parts:
content = getattr(part, "content", None)
if isinstance(content, str):
chunks.append(content)
return "\n".join(chunks)
def _patch_model(
monkeypatch: pytest.MonkeyPatch,
respond: Callable[[AgentInfo], ModelResponse],
) -> dict[str, list[str]]:
"""Replace ``llm.build_model`` with a scripted FunctionModel; record calls."""
captured: dict[str, list[str]] = {"prompts": [], "specs": []}
def fake_build_model(spec: str, *, settings: Settings) -> FunctionModel:
captured["specs"].append(spec)
def function(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
captured["prompts"].append(_prompt_text(messages))
return respond(info)
return FunctionModel(function)
monkeypatch.setattr(llm, "build_model", fake_build_model)
return captured
def _canned_responder(core: ReportCore) -> Callable[[AgentInfo], ModelResponse]:
def respond(info: AgentInfo) -> ModelResponse:
tool = info.output_tools[0].name
return ModelResponse(parts=[ToolCallPart(tool, core.model_dump(mode="json"))])
return respond
def _long_transcript(segments: int = 300) -> Transcript:
return Transcript(
duration=95.0,
segments=[
Segment(
start=float(index), end=float(index) + 0.9, text="lorem ipsum " * 20, speaker="S1"
)
for index in range(1, segments + 1)
],
)
# --- token / character budget ---------------------------------------------
def test_budget_constants_match_the_documented_defaults() -> None:
assert LOCAL_PROMPT_CHARS == 6000
assert PROVIDER_PROMPT_CHARS == 96_000
@pytest.mark.parametrize(
("spec", "expected"),
[
("Qwen3-VL-4B-Instruct", LOCAL_PROMPT_CHARS),
("local:Qwen3-VL-4B-Instruct", LOCAL_PROMPT_CHARS),
("qwen3-vl:4b", LOCAL_PROMPT_CHARS), # unknown prefix -> local llama-server name
("test", LOCAL_PROMPT_CHARS),
("deepseek:deepseek-flash", PROVIDER_PROMPT_CHARS),
("openrouter:deepseek/deepseek-v4.1-flash-1017", PROVIDER_PROMPT_CHARS),
("ollama:qwen3-vl:4b", PROVIDER_PROMPT_CHARS),
],
)
def test_default_char_budget_follows_the_model_spec(spec: str, expected: int) -> None:
assert default_char_budget(spec) == expected
def test_estimate_tokens_uses_the_chars_over_four_heuristic() -> None:
assert estimate_tokens("") == 0
assert estimate_tokens("abcd") == 1
assert estimate_tokens("abcde") == 2
assert estimate_tokens("x" * 4000) == 1000
def test_fit_prompt_keeps_a_short_transcript_untouched() -> None:
text, truncated = fit_prompt("FIXED", "short transcript", max_chars=200)
assert text == "FIXED\n\nshort transcript"
assert truncated is False
def test_fit_prompt_without_a_transcript_returns_the_fixed_part() -> None:
assert fit_prompt("FIXED", "", max_chars=200) == ("FIXED", False)
def test_fit_prompt_truncates_the_transcript_first_and_notes_it() -> None:
transcript = "\n".join(f"line {index:02d} " + "x" * 40 for index in range(50))
text, truncated = fit_prompt("FIXED", transcript, max_chars=400)
assert truncated is True
assert text.startswith("FIXED\n\n")
assert "line 00" in text
assert "line 49" not in text
assert "transcript truncated for the prompt budget" in text
assert len(text) <= 400
def test_fit_prompt_drops_the_transcript_when_the_fixed_part_fills_the_budget() -> None:
text, truncated = fit_prompt("F" * 100, "x" * 5000, max_chars=140)
assert truncated is True
assert text.startswith("F" * 100)
assert "xxxx" not in text
assert "transcript truncated" in text
def test_fit_prompt_uses_the_injected_note_factory() -> None:
def note(total: int, kept: int) -> str:
return f"<clipped {kept}/{total}>"
text, truncated = fit_prompt("F", "y" * 900, max_chars=120, note_factory=note)
assert truncated is True
assert "<clipped " in text
assert len(text) <= 120
def test_fit_prompt_is_deterministic() -> None:
transcript = "\n".join(f"row {index} " + "z" * 30 for index in range(30))
first = fit_prompt("FIXED", transcript, max_chars=300)
assert first == fit_prompt("FIXED", transcript, max_chars=300)
@pytest.mark.parametrize("budget", [0, -10])
def test_fit_prompt_rejects_non_positive_budgets(budget: int) -> None:
with pytest.raises(ValueError, match="max_chars must be positive"):
fit_prompt("FIXED", "transcript", max_chars=budget)
# --- compact serialisation + prompts --------------------------------------
def test_format_transcript_uses_mmss_and_speaker_labels() -> None:
lines = format_transcript(_transcript()).splitlines()
assert lines[0] == "[00:00] S1: Hello and welcome to the demo."
assert lines[1] == "[01:05] S2: Let us look at the results."
assert format_transcript(None) == ""
def test_format_shots_carries_index_span_summary_and_on_screen_text() -> None:
lines = format_shots(_shots()).splitlines()
assert lines[0] == "SHOTS (2):"
assert (
lines[1] == '[0] [00:00-00:15]: Title slide on a blue background. | on-screen: "DEMO 2026"'
)
assert lines[2] == "[1] [00:15-01:35]: Presenter at a whiteboard."
assert format_shots([]) == "SHOTS: none available"
def test_build_synthesis_prompt_contains_metadata_shots_and_transcript() -> None:
prompt = build_synthesis_prompt(_shots(), _transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS)
assert "TASK: write the core of a report about this video" in prompt
assert "VIDEO METADATA:" in prompt
assert "- source: /media/sample.mp4" in prompt
assert "- duration: 01:35 (95.00 s)" in prompt
assert "- resolution: 640x360 at 12 fps" in prompt
assert "[0] [00:00-00:15]: Title slide on a blue background." in prompt
assert "[00:00] S1: Hello and welcome to the demo." in prompt
assert "[01:05] S2: Let us look at the results." in prompt
assert "3-8 highlights" in prompt
assert len(prompt) <= LOCAL_PROMPT_CHARS
def test_build_synthesis_prompt_without_transcript_says_so() -> None:
prompt = build_synthesis_prompt(_shots(), None, _info(), max_chars=LOCAL_PROMPT_CHARS)
assert "(no transcript available)" in prompt
assert "transcript truncated" not in prompt
def test_build_synthesis_prompt_truncates_long_transcripts_and_keeps_shots() -> None:
prompt = build_synthesis_prompt(
_shots(), _long_transcript(), _info(), max_chars=LOCAL_PROMPT_CHARS
)
assert "transcript truncated for the prompt budget" in prompt
assert "[0] [00:00-00:15]: Title slide on a blue background." in prompt
assert "- source: /media/sample.mp4" in prompt
assert len(prompt) <= LOCAL_PROMPT_CHARS
def test_build_question_prompt_contains_report_json_and_question() -> None:
prompt = build_question_prompt(
_report(), "What is shown at 01:05?", max_chars=LOCAL_PROMPT_CHARS
)
assert prompt.startswith("QUESTION: What is shown at 01:05?")
assert "REPORT (JSON):" in prompt
assert '"summary":"A short demo about testing."' in prompt
assert "[01:05] Results are shown." in prompt
assert "[00:00] S1: Hello and welcome to the demo." in prompt
assert "cite the moments" in prompt.lower()
def test_build_question_prompt_truncates_the_transcript_first() -> None:
report = _report()
report.transcript = _long_transcript()
prompt = build_question_prompt(report, "Summarise the demo.", max_chars=1500)
assert prompt.startswith("QUESTION: Summarise the demo.")
assert "transcript truncated for the prompt budget" in prompt
assert '"summary":"A short demo about testing."' in prompt
assert len(prompt) <= 1500
@pytest.mark.parametrize("question", ["", " "])
def test_build_question_prompt_rejects_blank_questions(question: str) -> None:
with pytest.raises(ValueError, match="question must be a non-empty string"):
build_question_prompt(_report(), question, max_chars=1000)
# --- report assembly -------------------------------------------------------
def test_assemble_report_uses_the_code_owned_facts() -> None:
core = ReportCore(
summary="Grounded summary.",
topics=["testing"],
people=["Alice"],
highlights=[Highlight(start=1.0, end=2.5, description="[00:01] Something happens.")],
)
info = _info()
report = assemble_report(core, _shots(), _transcript(), info)
assert report.source == "/media/sample.mp4"
assert report.duration == 95.0
assert report.summary == "Grounded summary."
assert report.topics == ["testing"]
assert report.people == ["Alice"]
assert report.highlights == core.highlights
assert report.shots == _shots()
assert report.transcript == _transcript()
assert report.metadata["path"] == str(info.path)
assert report.metadata["format"] == "mp4"
assert report.metadata["has_audio"] is True
assert report.metadata["extra"] == {"title": "Metadata title"}
def test_assemble_report_prefers_the_core_title_and_falls_back_to_metadata() -> None:
core = ReportCore(title="Model title", summary="Summary.")
assert assemble_report(core, _shots(), None, _info()).title == "Model title"
untitled = ReportCore(title=None, summary="Summary.")
assert assemble_report(untitled, _shots(), None, _info()).title == "Metadata title"
plain = _info(extra={})
assert assemble_report(untitled, _shots(), None, plain).title is None
def test_assemble_report_reads_yt_dlp_and_ffprobe_titles() -> None:
core = ReportCore(title=None, summary="Summary.")
from_yt_dlp = assemble_report(core, [], None, _info(extra={"yt_dlp": {"title": "YT title"}}))
assert from_yt_dlp.title == "YT title"
from_ffprobe = assemble_report(
core,
[],
None,
_info(extra={"ffprobe": {"format": {"tags": {"title": "Container title"}}}}),
)
assert from_ffprobe.title == "Container title"
def test_assemble_report_copies_lists_instead_of_aliasing_the_core() -> None:
core = ReportCore(summary="Summary.", topics=["one"])
report = assemble_report(core, _shots(), None, _info())
core.topics.append("two")
assert report.topics == ["one"]
def test_metadata_from_info_flattens_the_media_fields() -> None:
metadata = metadata_from_info(_info(extra={}))
assert metadata == {
"path": "/media/sample.mp4",
"format": "mp4",
"video_codec": "h264",
"audio_codec": "aac",
"width": 640,
"height": 360,
"fps": 12.0,
"has_audio": True,
"size_bytes": 4096,
}
# --- agents (FunctionModel, no network) -----------------------------------
async def test_synthesise_report_assembles_a_video_report(
monkeypatch: pytest.MonkeyPatch,
) -> None:
canned = ReportCore(
title="Canned title",
summary="Canned summary.",
topics=["topic a", "topic b"],
people=["Alice"],
highlights=[Highlight(start=65.25, end=70.0, description="[01:05] Results are shown.")],
)
captured = _patch_model(monkeypatch, _canned_responder(canned))
report = await synthesise_report(_shots(), _transcript(), _info(), settings=LOCAL_SETTINGS)
assert isinstance(report, VideoReport)
assert report.title == "Canned title"
assert report.summary == "Canned summary."
assert report.topics == ["topic a", "topic b"]
assert report.people == ["Alice"]
assert report.highlights == canned.highlights
assert report.source == "/media/sample.mp4"
assert report.duration == 95.0
assert report.shots == _shots()
assert report.transcript == _transcript()
assert report.metadata["format"] == "mp4"
assert captured["specs"] == ["local:Qwen3-VL-4B-Instruct"]
assert len(captured["prompts"]) == 1
assert "[0] [00:00-00:15]: Title slide on a blue background." in captured["prompts"][0]
assert "[00:00] S1: Hello and welcome to the demo." in captured["prompts"][0]
async def test_synthesise_report_truncates_a_long_transcript(
monkeypatch: pytest.MonkeyPatch,
) -> None:
canned = ReportCore(summary="Canned summary.")
captured = _patch_model(monkeypatch, _canned_responder(canned))
await synthesise_report(_shots(), _long_transcript(), _info(), settings=LOCAL_SETTINGS)
# A long transcript is map-reduced: one prompt per chunk, then a final reduce prompt
# built from chunk summaries. Every prompt stays inside the local budget.
assert len(captured["prompts"]) > 1
assert all(len(prompt) <= LOCAL_PROMPT_CHARS for prompt in captured["prompts"])
assert "TRANSCRIPT CHUNK 1/" in captured["prompts"][0]
assert "CHUNK SUMMARIES" in captured["prompts"][-1]
assert "lorem ipsum" not in captured["prompts"][-1]
async def test_synthesise_report_uses_the_provider_budget_for_hosted_models(
monkeypatch: pytest.MonkeyPatch,
) -> None:
seen: dict[str, int] = {}
real_build_prompt = synthesis.build_synthesis_prompt
def spy(
shots: list[Shot],
transcript: Transcript | None,
info: MediaInfo,
*,
max_chars: int,
chunk_notes: str | None = None,
) -> str:
seen["max_chars"] = max_chars
return real_build_prompt(
shots, transcript, info, max_chars=max_chars, chunk_notes=chunk_notes
)
monkeypatch.setattr(synthesis, "build_synthesis_prompt", spy)
captured = _patch_model(monkeypatch, _canned_responder(ReportCore(summary="Summary.")))
await synthesise_report(_shots(), _transcript(), _info(), settings=HOSTED_SETTINGS)
assert seen["max_chars"] == PROVIDER_PROMPT_CHARS
assert captured["specs"] == ["deepseek:deepseek-flash"]
async def test_synthesise_report_requires_grounding_material(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def explode(spec: str, *, settings: Settings) -> FunctionModel: # pragma: no cover
raise AssertionError("no model may be built without material")
monkeypatch.setattr(llm, "build_model", explode)
with pytest.raises(ValueError, match="no shots and no transcript"):
await synthesise_report([], None, _info(), settings=LOCAL_SETTINGS)
with pytest.raises(ValueError, match="no shots and no transcript"):
await synthesise_report(
[], Transcript(duration=1.0, segments=[]), _info(), settings=LOCAL_SETTINGS
)
async def test_answer_question_returns_the_model_answer(monkeypatch: pytest.MonkeyPatch) -> None:
answer = "The demo shows a slide at [00:05] and results at [01:05]."
captured = _patch_model(monkeypatch, lambda info: ModelResponse(parts=[TextPart(answer)]))
result = await answer_question(_report(), "What happens at 00:05?", settings=LOCAL_SETTINGS)
assert result == answer
assert captured["specs"] == ["local:Qwen3-VL-4B-Instruct"]
prompt = captured["prompts"][0]
assert "What happens at 00:05?" in prompt
assert "REPORT (JSON):" in prompt
assert "[00:00] S1: Hello and welcome to the demo." in prompt
async def test_answer_question_truncates_a_long_transcript(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured = _patch_model(
monkeypatch, lambda info: ModelResponse(parts=[TextPart("Answer [00:10].")])
)
report = _report()
report.transcript = _long_transcript()
result = await answer_question(report, "Summarise the demo.", settings=LOCAL_SETTINGS)
assert result == "Answer [00:10]."
prompt = captured["prompts"][0]
assert "transcript truncated for the prompt budget" in prompt
assert len(prompt) <= LOCAL_PROMPT_CHARS
async def test_answer_question_result_caches_repeated_questions(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""README/PLAN: a repeated question must not pay for the model again."""
answer = "The demo shows a slide at [00:05]."
captured = _patch_model(monkeypatch, lambda info: ModelResponse(parts=[TextPart(answer)]))
cache = StageCache(tmp_path / "cache")
first = await answer_question_result(
_report(), "What happens at 00:05?", settings=LOCAL_SETTINGS, cache=cache
)
second = await answer_question_result(
_report(), " what HAPPENS at 00:05? ", settings=LOCAL_SETTINGS, cache=cache
)
assert first.cached is False and second.cached is True
assert first.answer == second.answer == answer
assert first.cache_key == second.cache_key
assert first.citations == ["[00:05]"]
assert len(captured["prompts"]) == 1
async def test_prompt_budget_holds_for_an_oversized_fixed_part() -> None:
"""A 64-shot report JSON may not blow the local 6k budget (audit finding)."""
shots = [
Shot(
index=index,
start=float(index),
end=float(index + 1),
description=ShotDescription(summary="detail " * 200, shot_type="other"),
)
for index in range(64)
]
report = _report()
report.shots = shots
prompt = build_question_prompt(report, "What is shown?", max_chars=LOCAL_PROMPT_CHARS)
assert len(prompt) <= LOCAL_PROMPT_CHARS
assert "fixed prompt material truncated" in prompt or "shots_omitted" in prompt
+806
View File
@@ -0,0 +1,806 @@
"""Unit tests for the STT backends, the transcriber registry and SRT rendering.
Nothing here downloads a model or opens a network connection: the hosted backend runs
against ``httpx.MockTransport`` and the local model backends are exercised through
their pure mapping helpers. Tests that need a real model are opt-in (``VA_HEAVY_TESTS=1``).
"""
from __future__ import annotations
import itertools
import math
import os
import re
import shutil
import wave
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import pytest
from video_analyse.config import Settings
from video_analyse.models import Segment, Transcript, Word
from video_analyse.srt import format_timestamp, render_srt
from video_analyse.transcribe import faster_whisper as faster_whisper_module
from video_analyse.transcribe import get_transcriber
from video_analyse.transcribe import openai_transcriptions as openai_module
from video_analyse.transcribe import parakeet_onnx as parakeet_module
from video_analyse.transcribe.base import Transcriber
from video_analyse.transcribe.faster_whisper import (
FasterWhisperTranscriber,
segments_to_transcript,
)
from video_analyse.transcribe.openai_transcriptions import (
OpenAITranscriptionsTranscriber,
compute_chunk_offsets,
verbose_json_to_transcript,
)
from video_analyse.transcribe.parakeet_onnx import (
ENGLISH_MODEL,
MULTILINGUAL_MODEL,
ParakeetOnnxTranscriber,
results_to_transcript,
select_model_name,
tokens_to_words,
)
FFMPEG = shutil.which("ffmpeg")
FFPROBE = shutil.which("ffprobe")
requires_ffmpeg = pytest.mark.skipif(
FFMPEG is None or FFPROBE is None,
reason="ffmpeg and ffprobe are required to convert/split upload audio",
)
HEAVY_TESTS = os.environ.get("VA_HEAVY_TESTS", "").strip().lower() not in {
"",
"0",
"false",
"no",
}
heavy = pytest.mark.skipif(
not HEAVY_TESTS,
reason="set VA_HEAVY_TESTS=1 to run tests that load real models",
)
CUE_PATTERN = re.compile(
r"(?P<index>\d+)\n"
r"(?P<start>\d{2}:\d{2}:\d{2},\d{3}) --> (?P<end>\d{2}:\d{2}:\d{2},\d{3})\n"
r"(?P<text>.+)",
re.DOTALL,
)
@pytest.fixture(autouse=True)
def _isolated_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""Drop ``VA_*`` overrides and reset the process-wide model caches per test."""
for name in list(os.environ):
if name.startswith("VA_"):
monkeypatch.delenv(name, raising=False)
_clear_model_caches()
yield
_clear_model_caches()
def _clear_model_caches() -> None:
faster_whisper_module._MODEL_CACHE.clear()
parakeet_module._RECOGNIZER_CACHE.clear()
parakeet_module._VAD_CACHE.clear()
def write_silent_wav(path: Path, seconds: float = 1.0, rate: int = 16_000) -> Path:
"""Write a silent 16-bit mono PCM WAV of exactly ``seconds`` seconds."""
frames = round(rate * seconds)
with wave.open(str(path), "wb") as handle:
handle.setnchannels(1)
handle.setsampwidth(2)
handle.setframerate(rate)
handle.writeframes(b"\x00\x00" * frames)
return path
def parse_srt(text: str) -> list[dict[str, str]]:
"""Parse an SRT document into cue dicts, asserting every cue is well formed."""
blocks = [block for block in text.strip("\n").split("\n\n") if block]
cues: list[dict[str, str]] = []
for block in blocks:
match = CUE_PATTERN.fullmatch(block)
assert match is not None, f"invalid SRT cue: {block!r}"
cues.append(match.groupdict())
return cues
def verbose_payload(*, duration: float = 0.4) -> dict[str, Any]:
"""A canned Groq/OpenAI ``verbose_json`` response with words and one segment."""
return {
"task": "transcribe",
"language": "english",
"duration": duration,
"text": " Hello world.",
"segments": [
{
"id": 0,
"start": 0.0,
"end": duration,
"text": " Hello world.",
"no_speech_prob": 0.01,
}
],
"words": [
{"word": " Hello", "start": 0.0, "end": 0.2},
{"word": " world.", "start": 0.22, "end": duration},
],
}
# --------------------------------------------------------------------------- SRT
def test_render_srt_is_valid_and_sequential() -> None:
transcript = Transcript(
duration=62.0,
segments=[
Segment(start=0.0, end=1.25, text=" First line."),
Segment(start=1.5, end=2.0, text=" Second line."),
Segment(start=61.5, end=62.0, text=" Last line."),
],
)
text = render_srt(transcript)
assert text.endswith("\n")
cues = parse_srt(text)
assert [cue["index"] for cue in cues] == ["1", "2", "3"]
assert cues[0]["start"] == "00:00:00,000"
assert cues[0]["end"] == "00:00:01,250"
assert cues[1]["start"] == "00:00:01,500"
assert cues[2]["start"] == "00:01:01,500"
assert cues[2]["end"] == "00:01:02,000"
assert [cue["text"] for cue in cues] == ["First line.", "Second line.", "Last line."]
def test_render_srt_speaker_labels() -> None:
transcript = Transcript(
duration=3.0,
segments=[
Segment(start=0.0, end=1.0, text="Hello there", speaker="S1"),
Segment(start=1.0, end=2.0, text="Hi", speaker="S2"),
Segment(start=2.0, end=3.0, text="Bye"),
],
)
labelled = parse_srt(render_srt(transcript, speaker_labels=True))
assert [cue["text"] for cue in labelled] == ["[S1] Hello there", "[S2] Hi", "Bye"]
plain = parse_srt(render_srt(transcript))
assert [cue["text"] for cue in plain] == ["Hello there", "Hi", "Bye"]
def test_render_srt_uses_words_when_segment_text_is_empty() -> None:
transcript = Transcript(
duration=2.0,
segments=[
Segment(
start=0.0,
end=1.0,
text="",
words=[Word(text="Word", start=0.0, end=0.5)],
),
Segment(start=1.0, end=1.5, text=" "),
Segment(start=1.5, end=2.0, text=" done "),
],
)
cues = parse_srt(render_srt(transcript))
assert [cue["text"] for cue in cues] == ["Word", "done"]
assert [cue["index"] for cue in cues] == ["1", "2"]
def test_render_srt_empty_transcript() -> None:
assert render_srt(Transcript(duration=0.0, segments=[])) == ""
def test_render_srt_collapses_whitespace_and_fixes_zero_duration() -> None:
transcript = Transcript(
duration=2.0,
segments=[Segment(start=2.0, end=2.0, text="line one\n line two")],
)
cues = parse_srt(render_srt(transcript))
assert cues[0]["text"] == "line one line two"
assert cues[0]["start"] == "00:00:02,000"
assert cues[0]["end"] == "00:00:02,001"
@pytest.mark.parametrize(
("seconds", "expected"),
[
(0.0, "00:00:00,000"),
(1.0006, "00:00:01,001"),
(59.9996, "00:01:00,000"),
(3661.5, "01:01:01,500"),
(-5.0, "00:00:00,000"),
(float("nan"), "00:00:00,000"),
(float("inf"), "00:00:00,000"),
],
)
def test_format_timestamp(seconds: float, expected: str) -> None:
assert format_timestamp(seconds) == expected
# ---------------------------------------------------------------------- registry
def test_registry_defaults_to_parakeet_in_the_local_profile() -> None:
settings = Settings()
assert settings.resolved_stt() == "parakeet"
transcriber = get_transcriber(settings)
assert isinstance(transcriber, ParakeetOnnxTranscriber)
assert isinstance(transcriber, Transcriber)
def test_registry_honours_explicit_backends() -> None:
whisper = get_transcriber(Settings(stt_backend="whisper"))
assert isinstance(whisper, FasterWhisperTranscriber)
assert whisper.model_name == Settings(stt_backend="whisper").whisper_model
parakeet = get_transcriber(Settings(stt_backend="parakeet"))
assert isinstance(parakeet, ParakeetOnnxTranscriber)
hosted = get_transcriber(Settings(stt_backend="openai-transcriptions"))
assert isinstance(hosted, OpenAITranscriptionsTranscriber)
assert hosted.model == Settings(stt_backend="openai-transcriptions").stt_api_model
def test_registry_hosted_profile_uses_hosted_stt() -> None:
settings = Settings(profile="hosted")
assert settings.resolved_stt() == "openai-transcriptions"
transcriber = get_transcriber(settings)
assert isinstance(transcriber, OpenAITranscriptionsTranscriber)
assert transcriber.endpoint == "https://api.groq.com/openai/v1/audio/transcriptions"
def test_registry_rejects_unknown_backend(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(Settings, "resolved_stt", lambda self: "nope")
with pytest.raises(ValueError, match="nope"):
get_transcriber(Settings())
async def test_transcribers_reject_missing_audio(tmp_path: Path) -> None:
missing = tmp_path / "missing.wav"
for transcriber in (
FasterWhisperTranscriber(Settings()),
ParakeetOnnxTranscriber(Settings()),
OpenAITranscriptionsTranscriber(Settings(), api_key="test"),
):
with pytest.raises(ValueError, match="audio file not found"):
await transcriber.transcribe(missing)
# ---------------------------------------------------------------- faster-whisper
def test_segments_to_transcript_maps_segments_and_words() -> None:
raw_segments = [
SimpleNamespace(
start=0.0,
end=2.0,
text=" Hello world.",
words=[
SimpleNamespace(word=" Hello", start=0.1, end=0.4, probability=0.9),
SimpleNamespace(word=" world.", start=0.5, end=1.1, probability=0.8),
SimpleNamespace(word=" ", start=1.2, end=1.3, probability=0.5),
],
),
SimpleNamespace(start=2.2, end=3.0, text=" Bye.", words=None),
]
info = SimpleNamespace(language="en", duration=3.0)
transcript = segments_to_transcript(raw_segments, info, model="small")
assert transcript.backend == "whisper"
assert transcript.model == "small"
assert transcript.language == "en"
assert transcript.duration == pytest.approx(3.0)
assert [segment.text for segment in transcript.segments] == ["Hello world.", "Bye."]
assert transcript.segments[1].words == []
words = transcript.segments[0].words
assert [word.text for word in words] == ["Hello", "world."]
assert [word.probability for word in words] == pytest.approx([0.9, 0.8])
assert words[0].start == pytest.approx(0.1)
assert words[0].end == pytest.approx(0.4)
def test_segments_to_transcript_clamps_word_times_and_keeps_unknown_probability() -> None:
raw_segments = [
SimpleNamespace(
start=1.0,
end=2.0,
text=" x",
words=[SimpleNamespace(word="x", start=0.2, end=5.0)],
)
]
transcript = segments_to_transcript(
raw_segments, SimpleNamespace(language="de", duration=2.0), model="m"
)
word = transcript.segments[0].words[0]
assert (word.start, word.end) == (1.0, 2.0)
assert word.probability is None
assert transcript.language == "de"
def test_segments_to_transcript_falls_back_to_last_segment_end() -> None:
raw_segments = [SimpleNamespace(start=0.0, end=1.75, text=" a", words=[])]
transcript = segments_to_transcript(
raw_segments, SimpleNamespace(language=None, duration=0.0), model="m"
)
assert transcript.duration == pytest.approx(1.75)
assert transcript.language is None
assert transcript.segments[0].words == []
def test_faster_whisper_model_cache_loads_once(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_build(name: str) -> Any:
calls.append(name)
return SimpleNamespace(name=name)
monkeypatch.setattr(faster_whisper_module, "_build_model", fake_build)
first = faster_whisper_module._get_model("tiny")
second = faster_whisper_module._get_model("tiny")
assert first is second
assert calls == ["tiny"]
async def test_faster_whisper_transcriber_consumes_generator(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.5)
captured: dict[str, Any] = {}
def generator() -> Iterator[Any]:
yield SimpleNamespace(
start=0.0,
end=0.5,
text=" Hi.",
words=[SimpleNamespace(word=" Hi.", start=0.0, end=0.5, probability=0.9)],
)
class FakeModel:
def transcribe(self, audio: Any, **kwargs: Any) -> tuple[Iterator[Any], Any]:
captured.update(kwargs)
captured["audio"] = audio
return generator(), SimpleNamespace(language="en", duration=0.5)
monkeypatch.setattr(faster_whisper_module, "_get_model", lambda name: FakeModel())
transcript = await FasterWhisperTranscriber(Settings()).transcribe(wav, language="en")
assert captured["audio"].shape == (8_000,)
assert captured["audio"].dtype == "float32"
assert captured["word_timestamps"] is True
assert captured["vad_filter"] is True
assert captured["language"] == "en"
assert transcript.backend == "whisper"
assert transcript.segments[0].words[0].text == "Hi."
# -------------------------------------------------------------------- parakeet
def test_select_model_name() -> None:
assert select_model_name(None) == MULTILINGUAL_MODEL
assert select_model_name("en") == ENGLISH_MODEL
assert select_model_name("EN-us") == ENGLISH_MODEL
assert select_model_name("de") == MULTILINGUAL_MODEL
assert select_model_name("fr") == MULTILINGUAL_MODEL
def test_tokens_to_words_merges_pieces_and_derives_boundaries() -> None:
tokens = [" Hel", "lo", " world", "."]
timestamps = [0.0, 0.16, 0.8, 1.12]
logprobs = [-0.1, -0.2, -0.3, -0.4]
words = tokens_to_words(tokens, timestamps, logprobs, start=10.0, end=12.0)
assert [word.text for word in words] == ["Hello", "world."]
assert words[0].start == pytest.approx(10.0)
assert words[0].end == pytest.approx(10.8)
assert words[1].start == pytest.approx(10.8)
assert words[1].end == pytest.approx(12.0)
assert words[0].probability == pytest.approx(math.exp((-0.1 - 0.2) / 2))
assert words[1].probability == pytest.approx(math.exp((-0.3 - 0.4) / 2))
def test_tokens_to_words_accepts_sentencepiece_boundary_markers() -> None:
tokens = ["\u2581Hel", "lo", "\u2581there", "\u2581"]
timestamps = [0.0, 0.2, 0.5, 0.6]
words = tokens_to_words(tokens, timestamps, None, start=0.0, end=1.0)
assert [word.text for word in words] == ["Hello", "there"]
assert words[0].probability is None
assert words[1].end == pytest.approx(1.0)
def test_tokens_to_words_without_timestamps_returns_nothing() -> None:
assert tokens_to_words([" hello"], None) == []
assert tokens_to_words(None, [0.0]) == []
assert tokens_to_words([], []) == []
def test_results_to_transcript_maps_vad_segments() -> None:
results = [
SimpleNamespace(
start=0.0,
end=2.0,
text=" Hello world.",
timestamps=[0.0, 0.5],
tokens=[" Hello", " world."],
logprobs=[-0.1, -0.2],
),
SimpleNamespace(
start=2.5,
end=3.0,
text=" Bye.",
timestamps=[0.0],
tokens=[" Bye."],
logprobs=[-0.3],
),
SimpleNamespace(
start=3.0,
end=3.1,
text=" ",
timestamps=None,
tokens=None,
logprobs=None,
),
]
transcript = results_to_transcript(
(result for result in results), model=MULTILINGUAL_MODEL, language=None, duration=3.1
)
assert transcript.backend == "parakeet"
assert transcript.model == MULTILINGUAL_MODEL
assert transcript.language is None
assert transcript.duration == pytest.approx(3.1)
assert [segment.text for segment in transcript.segments] == ["Hello world.", "Bye."]
first = transcript.segments[0]
assert [word.text for word in first.words] == ["Hello", "world."]
assert first.words[0].end == pytest.approx(0.5)
assert first.words[1].start == pytest.approx(0.5)
assert first.words[1].end == pytest.approx(2.0)
assert first.words[0].probability == pytest.approx(math.exp(-0.1))
def test_results_to_transcript_reports_english_for_v2_and_uses_last_end() -> None:
results = [
SimpleNamespace(
start=0.5,
end=1.5,
text=" Hi.",
timestamps=[0.0],
tokens=[" Hi."],
logprobs=None,
)
]
transcript = results_to_transcript(results, model=ENGLISH_MODEL, language=None, duration=None)
assert transcript.language == "en"
assert transcript.duration == pytest.approx(1.5)
def test_parakeet_recognizer_cache_is_keyed_by_model(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_build(name: str) -> Any:
calls.append(name)
return SimpleNamespace(name=name)
monkeypatch.setattr(parakeet_module, "_build_recognizer", fake_build)
first = parakeet_module._get_recognizer(MULTILINGUAL_MODEL)
second = parakeet_module._get_recognizer(MULTILINGUAL_MODEL)
third = parakeet_module._get_recognizer(ENGLISH_MODEL)
assert first is second
assert third is not first
assert calls == [MULTILINGUAL_MODEL, ENGLISH_MODEL]
def test_wav_duration_reads_pcm_headers(tmp_path: Path) -> None:
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.25)
assert parakeet_module._wav_duration(wav) == pytest.approx(1.25)
assert parakeet_module._wav_duration(tmp_path / "nope.wav") is None
async def test_parakeet_transcriber_selects_checkpoint_from_language(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.5)
calls: list[str] = []
class FakeRecognizer:
def recognize(self, path: str) -> list[Any]:
calls.append(path)
return [
SimpleNamespace(
start=0.0,
end=0.5,
text=" Hi.",
timestamps=[0.0],
tokens=[" Hi."],
logprobs=[-0.2],
)
]
def fake_get_recognizer(name: str) -> FakeRecognizer:
calls.append(name)
return FakeRecognizer()
monkeypatch.setattr(parakeet_module, "_get_recognizer", fake_get_recognizer)
transcript = await ParakeetOnnxTranscriber(Settings(language="en")).transcribe(wav)
assert calls == [ENGLISH_MODEL, str(wav)]
assert transcript.backend == "parakeet"
assert transcript.model == ENGLISH_MODEL
assert transcript.language == "en"
assert transcript.duration == pytest.approx(0.5)
assert transcript.segments[0].words[0].text == "Hi."
# ----------------------------------------------------- openai transcriptions
def test_compute_chunk_offsets() -> None:
assert compute_chunk_offsets([]) == []
assert compute_chunk_offsets([10.0]) == [0.0]
assert compute_chunk_offsets([10.0, 20.0, 5.0]) == pytest.approx([0.0, 10.0, 30.0])
assert compute_chunk_offsets([10.0, -3.0, 2.0]) == pytest.approx([0.0, 10.0, 10.0])
def test_verbose_json_to_transcript_maps_words_and_segments() -> None:
payload = {
"language": "english",
"duration": 2.5,
"text": " Hello world.",
"segments": [
{"start": 0.0, "end": 1.2, "text": " Hello"},
{"start": 1.2, "end": 2.5, "text": " world."},
],
"words": [
{"word": " Hello", "start": 0.1, "end": 0.4},
{"word": " world.", "start": 1.3, "end": 1.8, "probability": 0.7},
],
}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-large-v3-turbo")
assert transcript.backend == "openai-transcriptions"
assert transcript.model == "whisper-large-v3-turbo"
assert transcript.language == "english"
assert transcript.duration == pytest.approx(2.5)
assert [segment.text for segment in transcript.segments] == ["Hello", "world."]
assert [word.text for word in transcript.segments[0].words] == ["Hello"]
assert [word.text for word in transcript.segments[1].words] == ["world."]
assert transcript.segments[0].words[0].probability is None
assert transcript.segments[1].words[0].probability == pytest.approx(0.7)
def test_verbose_json_to_transcript_stitches_chunks_with_offsets() -> None:
payloads = [verbose_payload(duration=2.0), verbose_payload(duration=1.5)]
offsets = compute_chunk_offsets([2.0, 1.5])
transcript = verbose_json_to_transcript(payloads, offsets, model="whisper-1")
assert offsets == pytest.approx([0.0, 2.0])
assert transcript.duration == pytest.approx(3.5)
assert [segment.start for segment in transcript.segments] == pytest.approx([0.0, 2.0])
assert [segment.end for segment in transcript.segments] == pytest.approx([2.0, 3.5])
assert [segment.words[0].start for segment in transcript.segments] == pytest.approx([0.0, 2.0])
assert transcript.segments[1].words[1].start == pytest.approx(2.22)
def test_verbose_json_to_transcript_synthesises_segment_from_words() -> None:
payload = {"language": "en", "words": [{"word": "Hi", "start": 0.0, "end": 0.3}]}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-1")
assert transcript.duration == pytest.approx(0.3)
assert len(transcript.segments) == 1
assert transcript.segments[0].text == "Hi"
assert transcript.segments[0].words[0].start == pytest.approx(0.0)
def test_verbose_json_to_transcript_reads_nested_words() -> None:
payload = {
"language": "en",
"duration": 1.0,
"segments": [
{
"start": 0.0,
"end": 1.0,
"text": "Hello",
"words": [{"word": "Hello", "start": 0.0, "end": 0.5}],
}
],
}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-1")
assert transcript.segments[0].words[0].text == "Hello"
def test_verbose_json_to_transcript_requires_matching_offsets() -> None:
with pytest.raises(ValueError, match="offset"):
verbose_json_to_transcript([verbose_payload()], [], model="m")
def test_openai_transcriber_endpoint_normalises_trailing_slash() -> None:
settings = Settings(stt_api_base_url="https://example.test/v1/", stt_api_model="m")
transcriber = OpenAITranscriptionsTranscriber(settings, api_key="k")
assert transcriber.endpoint == "https://example.test/v1/audio/transcriptions"
def test_openai_transcriber_requires_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
for name in openai_module.API_KEY_ENV_VARS:
monkeypatch.delenv(name, raising=False)
transcriber = OpenAITranscriptionsTranscriber(Settings())
with pytest.raises(RuntimeError, match="GROQ_API_KEY"):
transcriber._resolve_api_key()
def test_openai_transcriber_api_key_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("VA_STT_API_KEY", raising=False)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setenv("GROQ_API_KEY", "from-env")
assert OpenAITranscriptionsTranscriber(Settings())._resolve_api_key() == "from-env"
monkeypatch.delenv("GROQ_API_KEY")
monkeypatch.setenv("VA_STT_API_KEY", "from-va")
assert OpenAITranscriptionsTranscriber(Settings())._resolve_api_key() == "from-va"
@requires_ffmpeg
async def test_openai_transcriber_posts_multipart_and_maps_response(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.6)
requests: list[httpx.Request] = []
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.6))
transport = httpx.MockTransport(handler)
async with httpx.AsyncClient(transport=transport) as client:
transcriber = OpenAITranscriptionsTranscriber(Settings(), client=client)
transcript = await transcriber.transcribe(wav)
assert len(requests) == 1
request = requests[0]
body = bodies[0]
assert str(request.url) == "https://api.groq.com/openai/v1/audio/transcriptions"
assert request.headers["authorization"] == "Bearer secret-key"
assert body.count(b'name="timestamp_granularities[]"') == 2
assert b"verbose_json" in body
assert b"whisper-large-v3-turbo" in body
assert b'filename="audio.flac"' in body
assert b"fLaC" in body
assert transcript.backend == "openai-transcriptions"
assert transcript.model == "whisper-large-v3-turbo"
assert transcript.language == "english"
assert transcript.duration == pytest.approx(0.6)
assert [segment.text for segment in transcript.segments] == ["Hello world."]
assert [word.text for word in transcript.segments[0].words] == ["Hello", "world."]
@requires_ffmpeg
async def test_openai_transcriber_forwards_language(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.3)
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.3))
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(Settings(), client=client)
transcript = await transcriber.transcribe(wav, language="de")
assert b'name="language"' in bodies[0]
assert b"\r\n\r\nde\r\n" in bodies[0]
assert transcript.language == "de"
@requires_ffmpeg
async def test_openai_transcriber_raises_on_http_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "bad-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.3)
async def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": {"message": "Invalid API key"}})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(Settings(), client=client)
with pytest.raises(RuntimeError, match="401"):
await transcriber.transcribe(wav)
@requires_ffmpeg
async def test_openai_transcriber_splits_and_stitches_long_audio(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
# Force the splitting branch and use sub-second chunks so a tiny WAV exercises it.
monkeypatch.setattr(openai_module, "MAX_UPLOAD_BYTES", 1)
monkeypatch.setattr(openai_module, "CHUNK_SECONDS", 0.4)
wav = write_silent_wav(tmp_path / "audio.wav", seconds=1.2)
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.4))
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(Settings(), client=client)
transcript = await transcriber.transcribe(wav)
assert len(bodies) >= 3
assert all(b"fLaC" in body for body in bodies)
starts = [segment.start for segment in transcript.segments]
assert len(starts) == len(bodies)
assert starts[0] == pytest.approx(0.0)
assert starts == sorted(starts)
for previous, current in itertools.pairwise(starts):
assert 0.2 < current - previous < 0.7
assert transcript.duration == pytest.approx(1.2, abs=0.15)
assert transcript.segments[-1].words[0].start > 0.6
# ------------------------------------------------------------------ heavy tests
@heavy
async def test_faster_whisper_real_model_smoke(tmp_path: Path) -> None:
pytest.importorskip("faster_whisper")
model_name = os.environ.get("VA_HEAVY_WHISPER_MODEL", "tiny")
settings = Settings(profile="local", stt_backend="whisper", whisper_model=model_name)
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.0)
transcript = await FasterWhisperTranscriber(settings).transcribe(wav)
assert transcript.backend == "whisper"
assert transcript.model == model_name
assert transcript.duration > 0.0
@heavy
async def test_parakeet_real_model_smoke(tmp_path: Path) -> None:
pytest.importorskip("onnx_asr")
settings = Settings(profile="local", stt_backend="parakeet", language="en")
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.0)
transcript = await ParakeetOnnxTranscriber(settings).transcribe(wav)
assert transcript.backend == "parakeet"
assert transcript.model == ENGLISH_MODEL
assert transcript.language == "en"
assert transcript.duration == pytest.approx(1.0)
+427
View File
@@ -0,0 +1,427 @@
"""Offline tests for ``vision.describe_shots``, ``frame_prompt`` and ``llama_server_up``.
No llama-server, no network beyond localhost, no model downloads: the describer agent runs on
pydantic-ai's ``FunctionModel`` and the health check is exercised against a throw-away HTTP stub
on 127.0.0.1 plus a closed port.
"""
from __future__ import annotations
import asyncio
import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, ClassVar
import pytest
from PIL import Image
from pydantic_ai.messages import BinaryImage, ModelMessage, ModelResponse, ToolCallPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
from video_analyse import llm, vision
from video_analyse.config import Settings
from video_analyse.models import Segment, Shot, ShotDescription, Transcript, Word
ENV_VARS = (
"VA_PROFILE",
"VA_VLM_MODEL",
"VA_SYNTHESIS_MODEL",
"VA_LLAMA_SERVER_URL",
"DEEPSEEK_API_KEY",
"OPENROUTER_API_KEY",
"OLLAMA_BASE_URL",
"OLLAMA_API_KEY",
"OPENAI_API_KEY",
)
@pytest.fixture(autouse=True)
def clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep ambient ``VA_*`` / provider-key environment out of these tests."""
for name in ENV_VARS:
monkeypatch.delenv(name, raising=False)
class Recorder:
"""FunctionModel handler: records every request and returns a valid ``ShotDescription``."""
def __init__(self) -> None:
self.texts: list[str] = []
self.tool_calls: list[list[str]] = []
self.images: list[BinaryImage] = []
self.instructions: list[str | None] = []
self.calls = 0
def __call__(self, messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
self.calls += 1
self.instructions.append(info.instructions)
self.tool_calls.append([tool.name for tool in info.output_tools])
self.texts.append(_user_text(messages[-1]))
self.images.extend(_binary_images(messages[-1]))
args: dict[str, Any] = {
"summary": f"recorded frame {self.calls}",
"on_screen_text": "DEMO",
"shot_type": "screen",
"people": [],
"notable_objects": ["test pattern"],
"setting": "unknown",
}
return ModelResponse(parts=[ToolCallPart(tool_name="final_result", args=args)])
def _user_text(message: ModelMessage) -> str:
"""Concatenated text of the user prompt parts of ``message``."""
chunks: list[str] = []
for part in message.parts:
content = getattr(part, "content", None)
if isinstance(content, str):
chunks.append(content)
elif isinstance(content, list):
chunks.extend(item for item in content if isinstance(item, str))
return "\n".join(chunks)
def _binary_images(message: ModelMessage) -> list[BinaryImage]:
"""All ``BinaryImage`` parts carried by ``message``'s user prompt."""
images: list[BinaryImage] = []
for part in message.parts:
content = getattr(part, "content", None)
if isinstance(content, list):
images.extend(item for item in content if isinstance(item, BinaryImage))
return images
def _write_jpeg(path: Path, colour: tuple[int, int, int]) -> Path:
"""Write a tiny real JPEG (8x8) so ``BinaryImage.from_path`` has something to read."""
path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (8, 8), colour).save(path, format="JPEG")
return path
@pytest.fixture
def keyframes(tmp_path: Path) -> list[Path]:
return [
_write_jpeg(tmp_path / "keyframes" / "000.jpg", (200, 30, 30)),
_write_jpeg(tmp_path / "keyframes" / "001.jpg", (30, 30, 200)),
]
@pytest.fixture
def shots(keyframes: list[Path]) -> list[Shot]:
return [
Shot(index=0, start=0.0, end=5.0, keyframe=keyframes[0]),
Shot(index=1, start=5.0, end=10.0, keyframe=keyframes[1]),
]
@pytest.fixture
def transcript() -> Transcript:
return Transcript(
language="en",
duration=10.0,
segments=[
Segment(
start=0.2,
end=2.0,
text="Welcome to the demo.",
speaker="S1",
words=[
Word(text="Welcome", start=0.2, end=0.6),
Word(text="to", start=0.6, end=0.8),
Word(text="the", start=0.8, end=1.0),
Word(text="demo.", start=1.0, end=1.3),
],
),
# Straddles the cut at 5.0 s: "alpha" belongs to shot 0, "beta" to shot 1.
Segment(
start=4.6,
end=5.6,
text="alpha beta",
speaker="S1",
words=[
Word(text="alpha", start=4.6, end=4.9),
Word(text="beta", start=5.2, end=5.5),
],
),
Segment(start=5.5, end=8.0, text="Here is the parser.", speaker="S2"),
],
)
def _closed_port() -> int:
"""An ephemeral localhost port that nothing listens on (bound then closed)."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
def _forbidden(what: str) -> Any:
"""Callable that fails the test when invoked."""
def fail(*args: Any, **kwargs: Any) -> Any:
raise AssertionError(f"unexpected call: {what}")
return fail
# --------------------------------------------------------------------------- frame_prompt
def test_frame_prompt_contains_index_timings_and_context() -> None:
shot = Shot(index=3, start=12.4, end=18.9, keyframe=Path("frame.jpg"))
prompt = vision.frame_prompt(shot, "A wide shot of a lecture hall.", "[00:12] S1: hello")
assert "Shot index: 3" in prompt
assert "Time range: 00:12 - 00:18 (6.5 s)" in prompt
assert "Previous shot summary: A wide shot of a lecture hall." in prompt
assert "Transcript spoken during this shot:" in prompt
assert "[00:12] S1: hello" in prompt
assert shot.description is None # pure helper: nothing is written back
def test_frame_prompt_marks_first_shot_and_empty_transcript() -> None:
prompt = vision.frame_prompt(Shot(index=0, start=0.0, end=1.5), None)
assert "first described shot" in prompt
assert "Transcript spoken during this shot: none" in prompt
assert prompt.endswith("Describe the attached keyframe of this shot.")
# ----------------------------------------------------------------- transcript_slice_for
def test_transcript_slice_prefers_words_inside_the_shot(transcript: Transcript) -> None:
first = vision.transcript_slice_for(Shot(index=0, start=0.0, end=5.0), transcript)
assert "[00:00] S1: Welcome to the demo." in first
assert "alpha" in first
assert "beta" not in first
assert "Here is the parser." not in first
second = vision.transcript_slice_for(Shot(index=1, start=5.0, end=10.0), transcript)
assert "[00:05] S1: beta" in second
assert "[00:05] S2: Here is the parser." in second
assert "Welcome" not in second
def test_transcript_slice_falls_back_to_shot_field() -> None:
shot = Shot(index=0, start=0.0, end=2.0, transcript_slice=" pre-filled slice ")
assert vision.transcript_slice_for(shot, None) == "pre-filled slice"
empty = Shot(index=0, start=0.0, end=2.0, transcript_slice="kept")
no_overlap = Transcript(duration=10.0, segments=[Segment(start=6.0, end=7.0, text="later")])
assert vision.transcript_slice_for(empty, no_overlap) == "kept"
def test_transcript_slice_is_length_capped() -> None:
long_segment = Segment(start=0.0, end=2.0, text="word " * 400)
transcript = Transcript(duration=2.0, segments=[long_segment])
sliced = vision.transcript_slice_for(Shot(index=0, start=0.0, end=2.0), transcript)
assert len(sliced) <= vision.MAX_TRANSCRIPT_CHARS + len(" [...]")
assert sliced.endswith("[...]")
# ------------------------------------------------------------------------ describe_shots
def test_build_describer_agent_uses_contract_settings() -> None:
agent = vision.build_describer_agent(FunctionModel(Recorder()))
assert agent.output_type is ShotDescription
assert agent.model_settings["temperature"] == 0.1
assert agent.model_settings["max_tokens"] == 400
assert agent.model_settings["max_retries"] == 0
assert agent._max_output_retries == 2
assert "only what is visible" in vision.DESCRIBER_INSTRUCTIONS
async def test_describe_shots_fills_every_shot(
shots: list[Shot],
keyframes: list[Path],
transcript: Transcript,
monkeypatch: pytest.MonkeyPatch,
) -> None:
recorder = Recorder()
model = FunctionModel(recorder)
seen_specs: list[str] = []
health_checks = 0
def fake_build_model(spec: str, *, settings: Settings) -> Any:
seen_specs.append(spec)
return model
async def fake_up(_settings: Settings) -> bool:
nonlocal health_checks
health_checks += 1
return True
monkeypatch.setattr(llm, "build_model", fake_build_model)
monkeypatch.setattr(vision, "llama_server_up", fake_up)
settings = Settings(profile="local")
result = await vision.describe_shots(shots, transcript, settings=settings)
assert result is shots
assert [shot.description for shot in shots] == [
ShotDescription(
summary="recorded frame 1",
on_screen_text="DEMO",
shot_type="screen",
people=[],
notable_objects=["test pattern"],
setting="unknown",
),
ShotDescription(
summary="recorded frame 2",
on_screen_text="DEMO",
shot_type="screen",
people=[],
notable_objects=["test pattern"],
setting="unknown",
),
]
assert recorder.calls == 2
assert seen_specs == ["local:Qwen3-VL-4B-Instruct"]
assert health_checks == 1 # once per call, not once per shot
# Each request carried exactly one image: the shot's own keyframe.
assert len(recorder.images) == 2
assert all(image.media_type == "image/jpeg" for image in recorder.images)
assert recorder.images[0].data == keyframes[0].read_bytes()
assert recorder.images[1].data == keyframes[1].read_bytes()
# The prompt carries index/timings plus the speaker-prefixed transcript slice of that shot.
assert "Shot index: 0" in recorder.texts[0]
assert "Time range: 00:00 - 00:05 (5.0 s)" in recorder.texts[0]
assert "[00:00] S1: Welcome to the demo." in recorder.texts[0]
assert "Shot index: 1" in recorder.texts[1]
assert "[00:05] S2: Here is the parser." in recorder.texts[1]
# The slice is persisted onto the shot, so reports carry the same context.
assert shots[0].transcript_slice.startswith("[00:00] S1: Welcome to the demo.")
assert shots[1].transcript_slice.startswith("[00:05] S1: beta\n[00:05] S2: Here is the parser.")
# ... and the previous shot's summary, for continuity.
assert "first described shot" in recorder.texts[0]
assert "Previous shot summary: recorded frame 1" in recorder.texts[1]
# The strict instructions reached the model, and structured output uses the output tool.
instructions = recorder.instructions[0]
assert instructions is not None
assert "only what is visible" in instructions
assert recorder.tool_calls == [["final_result"], ["final_result"]]
async def test_describe_shots_empty_list_short_circuits(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(llm, "build_model", _forbidden("build_model"))
settings = Settings(profile="local")
assert await vision.describe_shots([], None, settings=settings) == []
async def test_describe_shots_skips_all_when_no_keyframe_exists(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(llm, "build_model", _forbidden("no model is needed without keyframes"))
shots = [Shot(index=0, start=0.0, end=1.0, keyframe=None)]
result = await vision.describe_shots(shots, None, settings=Settings(profile="local"))
assert result is shots
assert shots[0].description is None
async def test_describe_shots_describes_only_shots_with_a_keyframe(
keyframes: list[Path],
transcript: Transcript,
monkeypatch: pytest.MonkeyPatch,
) -> None:
recorder = Recorder()
monkeypatch.setattr(llm, "build_model", lambda spec, *, settings: FunctionModel(recorder))
async def fake_up(_settings: Settings) -> bool:
return True
monkeypatch.setattr(vision, "llama_server_up", fake_up)
shots = [
Shot(index=0, start=0.0, end=5.0, keyframe=keyframes[0]),
Shot(index=1, start=5.0, end=10.0, keyframe=None),
]
result = await vision.describe_shots(shots, transcript, settings=Settings(profile="local"))
assert result is shots
assert shots[0].description is not None
assert shots[1].description is None
assert recorder.calls == 1
assert "Shot index: 0" in recorder.texts[0]
async def test_describe_shots_local_server_down_raises_hint(
keyframes: list[Path],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(llm, "build_model", _forbidden("build_model must not be reached"))
settings = Settings(profile="local", llama_server_url=f"http://127.0.0.1:{_closed_port()}/v1")
shots = [Shot(index=0, start=0.0, end=1.0, keyframe=keyframes[0])]
with pytest.raises(RuntimeError) as excinfo:
await vision.describe_shots(shots, None, settings=settings)
message = str(excinfo.value)
assert "llama-server is not reachable" in message
assert "llama-server -hf bartowski/Qwen_Qwen3-VL-4B-Instruct-GGUF:Q4_K_M" in message
assert "--image-max-tokens 448" in message
assert settings.llama_server_url in message
assert shots[0].description is None
async def test_describe_shots_hosted_spec_skips_health_check(
keyframes: list[Path],
monkeypatch: pytest.MonkeyPatch,
) -> None:
recorder = Recorder()
monkeypatch.setattr(llm, "build_model", lambda spec, *, settings: FunctionModel(recorder))
monkeypatch.setattr(vision, "llama_server_up", _forbidden("health check is local-only"))
settings = Settings(profile="hosted")
shots = [Shot(index=0, start=0.0, end=1.0, keyframe=keyframes[0])]
result = await vision.describe_shots(shots, None, settings=settings)
assert result[0].description is not None
assert recorder.calls == 1
# --------------------------------------------------------------------- llama_server_up
class _ModelsHandler(BaseHTTPRequestHandler):
"""Minimal llama-server stand-in: answers every GET with a 200 JSON model list."""
hits: ClassVar[list[str]] = []
def do_GET(self) -> None:
type(self).hits.append(self.path)
body = b'{"object": "list", "data": [{"id": "Qwen3-VL-4B-Instruct"}]}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format: str, *args: Any) -> None:
"""Silence the default stderr access log."""
def test_llama_server_up_against_localhost_stub() -> None:
_ModelsHandler.hits = []
server = ThreadingHTTPServer(("127.0.0.1", 0), _ModelsHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
port = server.server_address[1]
settings = Settings(llama_server_url=f"http://127.0.0.1:{port}/v1")
assert asyncio.run(vision.llama_server_up(settings)) is True
assert _ModelsHandler.hits == ["/v1/models"]
# A trailing slash in the configured URL must not produce a double slash.
assert asyncio.run(
vision.llama_server_up(Settings(llama_server_url=f"http://127.0.0.1:{port}/v1/"))
)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
def test_llama_server_up_closed_port_is_false() -> None:
settings = Settings(llama_server_url=f"http://127.0.0.1:{_closed_port()}/v1")
assert asyncio.run(vision.llama_server_up(settings)) is False
Generated
+3367
View File
File diff suppressed because it is too large. Load diff