Issue #6's "alias" criterion was unfinished: vision.llama_server_up was a one-line pass-through and vision also owned LLAMA_SERVER_COMMAND, which doctor imported from vision - so the llama-server facts were spread over two modules and a third consumed the copy. - llm: owns LLAMA_SERVER_COMMAND next to the local provider name and the llama_server_models/llama_server_up health check - vision: drops the alias and the constant; describe_shots/describe_moment call llm.llama_server_up, the actionable hint interpolates llm.LLAMA_SERVER_COMMAND - doctor: imports the startup command from llm - tests: the describer health-check stubs target llm.llama_server_up; the localhost server stub (path + trailing-slash check) moves to tests/test_llm.py with the rest of the llama-server tests; the duplicate closed-port test goes
394 lines
15 KiB
Python
394 lines
15 KiB
Python
"""Offline tests for ``vision.describe_shots``, ``frame_prompt`` and transcript windowing.
|
|
|
|
No llama-server and no model downloads: the describer agent runs on pydantic-ai's
|
|
``FunctionModel``, and the server health check is stubbed through ``llm`` (its own tests
|
|
live in ``tests/test_llm.py``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import socket
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
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_window_segments_is_the_half_open_clipper_both_paths_use(transcript: Transcript) -> None:
|
|
"""Word-midpoint clipping lives once: a word at the window end belongs to the next one."""
|
|
windows = vision.window_segments(transcript, 4.0, 5.0)
|
|
assert [(window.start, window.end, window.speaker, window.text) for window in windows] == [
|
|
(4.6, 5.6, "S1", "alpha")
|
|
]
|
|
assert vision.window_segments(transcript, 5.0, 5.0) == []
|
|
|
|
|
|
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(llm, "llama_server_up", fake_up)
|
|
settings = Settings(profile="local")
|
|
|
|
result = await vision.describe_shots(
|
|
shots, transcript, options=settings.options_for("describe")
|
|
)
|
|
|
|
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, options=settings.options_for("describe")) == []
|
|
|
|
|
|
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, options=Settings(profile="local").options_for("describe")
|
|
)
|
|
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(llm, "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, options=Settings(profile="local").options_for("describe")
|
|
)
|
|
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, options=settings.options_for("describe"))
|
|
|
|
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(llm, "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, options=settings.options_for("describe"))
|
|
|
|
assert result[0].description is not None
|
|
assert recorder.calls == 1
|