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

+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")