CONTRACTS: sync the ownership map and signatures to the branch (code-review S1, S2)

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

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

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

Sections 4-6 follow: MediaFacts.has_video, ShotsPayload, the enum-typed Settings
fields plus load_settings, and the llm routing record/endpoint protocol/startup
command.
This commit is contained in:
alex committed 2026-11-24 12:57:22 +00:00
1 parent dca19074f4
commit 08a4af9b86
1 file changed
+61 -23
+61 -23
View File
@@ -61,13 +61,13 @@ Environment: `uv`, venv pinned by `.python-version` = `3.13`, `uv sync` installs
| 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 (front doors)** | `cli.py` (replaces the stub), `mcp_server.py`, `tests/test_cli.py`, `tests/test_mcp.py` | `analysis.py`, `config.py`, `models.py`, `ingest.py` (fetch), `report.py`, `srt.py` |
| **G — analysis module** | `analysis.py`, `tests/test_analysis.py` | `pipeline.py`, `cache.py`, `media.py`, `config.py`, `models.py` |
| **A — ingest & media** | `src/video_analyse/ingest.py`, `media.py`, `tests/test_ingest.py`, `tests/test_media.py` | `models.py`, `cache.py` (ingest caches downloads) |
| **B — speech-to-text** | `transcribe/__init__.py` (registry), `transcribe/faster_whisper.py`, `transcribe/parakeet_onnx.py`, `transcribe/openai_transcriptions.py`, `srt.py`, `tests/test_transcribe_*.py`, `tests/test_srt.py` | `transcribe/base.py`, `models.py` |
| **C — diarization** | `diarize.py`, `model_assets.py`, `tests/test_diarize.py`, `tests/test_model_assets.py` | `models.py` (and its own `model_assets.py`) |
| **D — vision, synthesis, report** | `vision.py`, `synthesis.py`, `report.py`, `tests/test_vision.py`, `tests/test_synthesis.py`, `tests/test_report.py` | `models.py`, `llm.py`, `config.py`, `cache.py` (Q&A answer cache), `report.py` (timestamps) |
| **E — cache & pipeline** | `cache.py`, `pipeline.py`, `tests/test_cache.py`, `tests/test_pipeline.py` | all stage modules, `cache.py`, `models.py`, `config.py` |
| **F — CLI & MCP (front doors)** | `cli.py` (replaces the stub), `mcp_server.py`, `tests/test_cli.py`, `tests/test_mcp.py` | `analysis.py`, `config.py`, `models.py`, `diarize.py`, `ingest.py` (fetch), `report.py`, `srt.py`, `synthesis.py`, `transcribe.py` |
| **G — analysis module** | `analysis.py`, `tests/test_analysis.py` | `pipeline.py`, `cache.py`, `media.py`, `config.py`, `models.py`, `report.py`, `synthesis.py` (Q&A), `vision.py` (moment) |
| **Foundation (frozen during phase 2; reopened post-v1 — ADR-0001)** | `pyproject.toml`, `.python-version`, `.gitignore`, `__init__.py`, `models.py`, `config.py`, `llm.py`, `transcribe/base.py`, `tests/conftest.py`, `CONTRACTS.md` | — |
Already implemented by the foundation and usable as-is:
@@ -75,8 +75,10 @@ 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.llm.build_model(spec, *, settings)` — pydantic-ai model factory, plus
`llm.route_model(spec)`, `llm.llama_server_models(settings)` / `llm.llama_server_up(settings)`
and `llm.LLAMA_SERVER_COMMAND` (section 6). `settings` is any `llm.ModelEndpoints` value:
the `Settings` bag or a stage's own frozen option value.
* `video_analyse.transcribe.base.Transcriber` — the protocol to implement.
* `video_analyse.cli`: placeholder `va` typer app with a `version` command + `main()`; agent F
replaces the body while keeping `app` and `main()` importable from
@@ -92,49 +94,64 @@ ordering in the `Pipeline`). Keyframe JPEGs go to `workdir/keyframes/`, audio to
## 3. SIGNATURES (verbatim contract — implement exactly these)
```
ingest.py: async def fetch(source: str, *, cache_dir: Path, quality: int = 1080) -> IngestResult
ingest.py: async def fetch(source: str, *, cache_dir: Path, quality: int = 1080, force: bool = False) -> IngestResult
IngestResult(BaseModel): path: Path; info: dict[str, Any] = {}; downloaded: bool; title: str | None = None
media.py: async def probe(path: Path) -> MediaFacts
media.py: async def extract_audio(path: Path, workdir: Path) -> Path # 16 kHz mono s16le WAV at workdir/audio.wav
media.py: class ShotOptions(BaseModel) # frozen value: max_shots=64, min_scene_len=0.6, sampling="adaptive", sampling_interval_seconds=15.0, subdivide_after_seconds=20.0
media.py: def plan_shots(duration: float, cuts: list[float], curve: list[tuple[float, float]] | None, *, options: ShotOptions) -> list[Shot] # pure: no Path/I/O; global budget applied after subdivision
media.py: async def detect_shots(path: Path, *, duration_hint: float | None = None, options: ShotOptions | None = None) -> list[Shot]
media.py: async def extract_keyframes(path: Path, shots: list[Shot], workdir: Path, *, width: int = 768, quality: int = 85) -> list[Shot] # fills Shot.keyframe (JPEG in workdir/keyframes/), frame at shot midpoint
media.py: async def extract_keyframes(path: Path, shots: list[Shot], workdir: Path, *, width: int = 768, quality: int = 85, namespace: str | None = None) -> list[Shot] # fills Shot.keyframe (JPEG in workdir/keyframes/[<namespace[:12]>/]), frame at Shot.keyframe_time else the midpoint
media.py: def dedup_keyframes(shots: list[Shot], *, threshold: int = 8) -> list[Shot] # imagehash phash Hamming <= threshold dedup, fills Shot.phash
transcribe/base.py: class Transcriber(Protocol): async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript
transcribe/__init__.py: class SttOptions(BaseModel) # frozen value: backend, language, whisper_model, api_base_url, api_model, max_upload_bytes
transcribe/base.py: class Transcriber(Protocol)
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript
def identity(self) -> ModelIdentity # backend, model, endpoint; hashed into the transcribe cache key
def readiness(self) -> Readiness # weights_present, weights_location, requirements; offline, never raises
transcribe/__init__.py: class SttBackend(StrEnum) # parakeet | whisper | openai-transcriptions; STT_BACKENDS = their values
transcribe/__init__.py: class SttOptions(BaseModel) # frozen value: backend (SttBackend), language, whisper_model, api_base_url, api_model, max_upload_bytes
transcribe/__init__.py: def get_transcriber(options: SttOptions) -> Transcriber
transcribe/faster_whisper.py: class FasterWhisperTranscriber(Transcriber) # WhisperModel(options.whisper_model, device="cpu", compute_type="int8"); word_timestamps=True, vad_filter=True; run via asyncio.to_thread
transcribe/parakeet_onnx.py: class ParakeetOnnxTranscriber(Transcriber) # onnx-asr nemo-parakeet-tdt-0.6b-v3 (language None) else -v2; int8; with_vad + with_timestamps per installed API; token->word merge
transcribe/openai_transcriptions.py: class OpenAITranscriptionsTranscriber(Transcriber) # httpx multipart POST {base}/audio/transcriptions; verbose_json + timestamp_granularities word,segment; WAV->FLAC upload, chunk if >90MB with offset stitching; injectable httpx.AsyncClient for tests
srt.py: def render_srt(transcript: Transcript, *, speaker_labels: bool = False) -> str
diarize.py: class DiarizeOptions(BaseModel) # frozen value: backend, cluster_threshold (no independent default), min_duration_on, min_duration_off, cache_dir, num_speakers=-1
diarize.py: class DiarizeBackend(StrEnum) # sherpa | pyannote; DIARIZE_BACKENDS = their values
diarize.py: class DiarizeOptions(BaseModel) # frozen value: backend (DiarizeBackend), cluster_threshold (no independent default), min_duration_on, min_duration_off, cache_dir, num_speakers=-1
diarize.py: class Diarizer(Protocol): def cache_params(self) -> dict[str, Any]; async def diarize(self, wav: Path) -> list[SpeakerTurn] # constructor owns the option value; cache_params lists only the options it applies
diarize.py: def get_diarizer(options: DiarizeOptions) -> Diarizer
diarize.py: async def diarize_audio(wav: Path, options: DiarizeOptions) -> list[SpeakerTurn]
diarize.py: def attribute_speakers(transcript: Transcript, turns: list[SpeakerTurn]) -> Transcript # word-midpoint containment; segment.speaker = majority of word speakers; fills transcript.speaker_turns
model_assets.py: async def ensure_model(name: str, *, cache_dir: Path) -> Path # pinned-download cache for sherpa-onnx diarization assets
vision.py: class DescribeOptions(BaseModel) # frozen value: vlm_model, llama_server_url, ollama_base_url, ollama_api_key
vision.py: async def describe_shots(shots: list[Shot], transcript: Transcript | None, *, options: DescribeOptions) -> list[Shot] # pydantic-ai agent, output_type=ShotDescription, one call per shot, fills .description
vision.py: async def llama_server_up(settings: Settings) -> bool
vision.py: class TranscriptWindow(NamedTuple); def window_segments(transcript: Transcript | None, start: float, end: float) -> list[TranscriptWindow] # the half-open [start, end) word-midpoint clipper both the shot prompt and moment use
synthesis.py: class ReportOptions(BaseModel) # frozen value: synthesis_model, llama_server_url, ollama_base_url, ollama_api_key
synthesis.py: async def synthesise_report(shots: list[Shot], transcript: Transcript | None, info: MediaFacts, *, source: str, options: ReportOptions) -> VideoReport # agent outputs ReportCore; code assembles VideoReport from content facts + run-time source
synthesis.py: async def answer_question(report: VideoReport, question: str, *, settings: Settings) -> str
report.py: def render_markdown(report: VideoReport, *, keyframes_relpath: Path | None = None) -> str
cache.py: class StageCache # sha256 file hash; stage_key(stage, params) sha256 of canonical params JSON; paths cache_dir/<sha[:16]>/stage-<name>-<key>.json; load/save pydantic or raw JSON; exists()
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[[ProgressEvent], None] | None = None) -> Artifacts
cache.py: async def cached_run(path, model_type, runner, *, validate=None, force=False, on_hit=None) -> ModelT # the one load -> miss -> run -> save policy
pipeline.py: class Pipeline # __init__(settings: Settings, stages: Mapping[str, Callable] | None = None, *, max_shots: int = 64, min_scene_len: float = 0.6, ingest_quality: int = 1080); async def run(source: str, *, want: set[str], force: bool = False, progress: Callable[[ProgressEvent], None] | None = None) -> Artifacts
async def cached(source: str, *, want: set[str] | None = None) -> Artifacts | None # cache-only, current option keys
stage order: probe -> audio -> transcribe -> diarize(attribute) -> shots -> describe -> report; diarize only when settings.diarize and "diarize" in want; describe needs shots; report needs transcript or shots
ProgressEvent(stage: str, state: "start" | "cached" | "skipped" | "done", index: int, total: int)
analysis.py: class AnalysisOptions # diarize: bool | None = None; describe: bool = True; force: bool = False; max_shots: int = Field(64, ge=1); language: str | None = None; no_cache: bool = False; ingest_quality: int = 1080
analysis.py: async def analyse(source: str, options: AnalysisOptions, *, settings: Settings, progress: Callable[[ProgressEvent], None] | None = None) -> Artifacts
analysis.py: async def transcript(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Transcript
analysis.py: async def shots(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> list[Shot]
analysis.py: async def describe(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> list[Shot]
analysis.py: async def shots(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Artifacts # the run's artifacts; the shot list is artifacts.shots
analysis.py: async def describe(source: str, options: AnalysisOptions, *, settings: Settings, progress: ... = None) -> Artifacts # descriptions on artifacts.shots
analysis.py: async def probe(source: str, *, settings: Settings, progress: ... = None) -> Artifacts # MediaFacts + MediaRef
analysis.py: async def ask(source: str, question: str, options: AnalysisOptions, *, settings: Settings, allow_analysis: bool = False) -> AnswerResult
analysis.py: async def moment(source: str, t_start: float, t_end: float, options: AnalysisOptions, *, settings: Settings, max_frames: int = 4, width: int = 768) -> MomentResult
analysis.py: async def frame(source: str, timestamp: float, *, settings: Settings, width: int = 768) -> FrameResult
analysis.py: async def cached(source: str, *, settings: Settings, options: AnalysisOptions | None = None) -> Artifacts | None
analysis.py: async def cached(source: str, *, settings: Settings, options: AnalysisOptions | None = None) -> Artifacts | None # None when nothing is cached (an uncached URL has no resolved hash)
analysis.py: def checked_int(value: object, name: str, *, minimum: int, maximum: int | None = None) -> int # the shared bounded-integer guard both doors use
stage callables take option values (SttOptions, DiarizeOptions, ShotOptions, DescribeOptions, ReportOptions), never Settings; lazy-import real stages inside methods; injectable stages dict enables unit tests with fakes; per-stage caching + skip; force re-runs requested stages and downstream; URL source -> fetch first
llm.py: class ModelEndpoints(Protocol) # llama_server_url; ollama_base_url | None; ollama_api_key | None (Settings or a stage's frozen options)
llm.py: def route_model(spec: str) -> ModelRoute # spec, model, local, prefix, provider, credential_env: the one routing fact behind vision/synthesis/doctor
llm.py: def build_model(spec: str, *, settings: ModelEndpoints) -> Model
llm.py: async def llama_server_models(settings: ModelEndpoints) -> list[str] | None # None when unreachable/malformed
llm.py: async def llama_server_up(settings: ModelEndpoints) -> bool
llm.py: LLAMA_SERVER_COMMAND: str # the exact local llama-server startup command (vision hint, va doctor)
cli.py: typer app "va": fetch, probe, transcribe, diarize, shots, describe, analyse, moment, ask, doctor, serve-mcp (+ main() entry); argv -> AnalysisOptions, output shaping only
mcp_server.py: FastMCP("video-analyse") with exactly 6 tools: transcribe_video, extract_keyframes, analyze_video, analyze_moment, get_frame_at, ask_video; tool args -> AnalysisOptions, output shaping only; run() stdio default
```
@@ -148,6 +165,7 @@ MediaFacts(duration: float, width: int | None = None, height: int | None = None,
fps: float | None = None, has_audio: bool, size_bytes: int,
format: str | None = None, video_codec: str | None = None,
audio_codec: str | None = None, extra: dict[str, Any] = {})
# computed property: has_video (a width or height was probed)
MediaRef(source: str, local_path: Path)
Word(text: str, start: float, end: float, probability: float | None = None)
SpeakerTurn(start: float, end: float, speaker: str) # "S1", "S2", ...
@@ -162,6 +180,7 @@ ShotDescription(summary: str, on_screen_text: str | None = None,
shot_type: Literal["wide", "medium", "close-up", "screen", "other"],
people: list[str] = [], notable_objects: list[str] = [],
setting: str | None = None)
ShotsPayload(source: str, workdir: Path, shots: list[Shot] = []) # the shots outcome as both doors render it
Highlight(start: float, end: float, description: str)
ReportCore(title: str | None = None, summary: str, topics: list[str] = [],
people: list[str] = [], highlights: list[Highlight] = [])
@@ -200,12 +219,12 @@ 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_backend # None | SttBackend ("parakeet" | "whisper" | "openai-transcriptions")
s.stt_api_base_url # https://api.groq.com/openai/v1
s.stt_api_model # whisper-large-v3-turbo
s.whisper_model # large-v3-turbo
s.diarize # bool, True (VA_DIARIZE=false works)
s.diarize_backend # "sherpa" | "pyannote"
s.diarize_backend # DiarizeBackend ("sherpa" | "pyannote")
s.diarize_cluster_threshold # float, 0.7
s.diarize_min_duration_on # float, 0.3 (sherpa)
s.diarize_min_duration_off # float, 0.5 (sherpa)
@@ -217,6 +236,11 @@ s.resolved_stt() # alias of s.options_for("stt").backend
s.resolved_vlm() # explicit vlm_model, else "local:Qwen3-VL-4B-Instruct" / "deepseek:deepseek-flash"
s.resolved_synthesis() # same rule as resolved_vlm
# config.py: the front doors' one construction path. Builds Settings once at a command/tool
# entry point; only the explicit (non-None) profile fields override VA_*/TOML. Behavioural flags
# (diarize, language, shot caps, cache policy) are AnalysisOptions fields, never settings.
load_settings(stt_backend=..., diarize_backend=..., vlm_model=...)
s.options_for("stt") # SttOptions (backend rule: explicit stt_backend, else a non-default
# whisper_model selects "whisper", else the profile default)
s.options_for("diarize") # DiarizeOptions; fills diarize_cluster_threshold (the single 0.7),
@@ -237,17 +261,31 @@ Module constants: `LOCAL_VLM_MODEL`, `HOSTED_VLM_MODEL`, `DEFAULT_CACHE_DIR`,
```python
from video_analyse.config import Settings
from video_analyse.llm import build_model, llama_server_up
from video_analyse.llm import (
LLAMA_SERVER_COMMAND,
ModelEndpoints,
build_model,
llama_server_models,
llama_server_up,
route_model,
)
settings = Settings()
route = route_model("deepseek:deepseek-flash") # .spec/.model/.local/.prefix/.provider/.credential_env
route.credential_env # "DEEPSEEK_API_KEY" - the one routing fact vision/synthesis/doctor share
model = build_model("local:Qwen3-VL-4B-Instruct", settings=settings) # llama-server
model = build_model("Qwen3-VL-4B-Instruct", settings=settings) # bare name -> llama-server
model = build_model("deepseek:deepseek-flash", settings=settings) # needs DEEPSEEK_API_KEY
model = build_model("ollama:deepseek-v4.1-flash:1017", settings=settings) # Ollama Cloud
model = build_model(settings.resolved_vlm(), settings=settings)
up = await llama_server_up(settings) # GET {url}/models, 2 s
up = await llama_server_up(settings) # GET {url}/models, 2 s; never raises
served = await llama_server_models(settings) # list[str] | None when unreachable/malformed
LLAMA_SERVER_COMMAND # exact startup command shown by the vision hint and `va doctor`
```
`settings` in every call above is any `llm.ModelEndpoints` value: the `Settings` bag from a front
door, or the frozen `DescribeOptions`/`ReportOptions` a stage already holds.
Resolution rules: `local:<name>` → `OpenAIChatModel(name, provider=OpenAICompatibleProvider(
"llama-server", base_url=settings.llama_server_url, api_key="local"))`; a bare name (or an
**unknown** `vendor:name` prefix, e.g. `qwen3-vl:4b`) → the same local model with the full spec as