MediaInfo conflated content facts with a run-time handle, so byte-identical aliases could not share a probe artifact and every cache read needed a path-rebasing sweep. - models: replace MediaInfo in one sweep with content-only MediaFacts and run-time MediaRef; Artifacts gains ref; MediaFacts.extra drops local filename/path keys on construction - media.probe returns MediaFacts with no path/source and no ffprobe filename - pipeline: probe params are the content hash only; attach MediaRef on every run; delete _rebase_media/_rebase_report; keep yt-dlp title/metadata as sanitized run-time facts for reports - synthesis: prompts and metadata consume facts only; report assembly takes the run-time source; report metadata carries no local path - cli/mcp: compose facts + ref where a local path or source display is needed - CONTRACTS sections 3-4, README and PLAN reference the new shapes; tests cover the alias cache hit, facts round-trip and path-free report metadata Cache migration: dropping source from the probe params changes probe keys, so existing probe entries are a one-time invalidation (one cheap ffprobe call per source). Closes #7
882 lines
31 KiB
Python
882 lines
31 KiB
Python
"""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
|
|
|
|
import hashlib
|
|
import json
|
|
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,
|
|
MediaFacts,
|
|
ReportCore,
|
|
Segment,
|
|
Shot,
|
|
ShotDescription,
|
|
Transcript,
|
|
VideoReport,
|
|
)
|
|
from video_analyse.synthesis import (
|
|
CHUNK_INSTRUCTIONS,
|
|
CHUNK_TASK,
|
|
LOCAL_PROMPT_CHARS,
|
|
PROVIDER_PROMPT_CHARS,
|
|
QA_INSTRUCTIONS,
|
|
SYNTHESIS_FOOTER,
|
|
SYNTHESIS_INSTRUCTIONS,
|
|
SYNTHESIS_TASK,
|
|
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")
|
|
SOURCE = "/media/sample.mp4"
|
|
|
|
|
|
def _facts(**overrides: object) -> MediaFacts:
|
|
data: dict[str, object] = {
|
|
"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 MediaFacts(**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(), _facts(), source=SOURCE)
|
|
|
|
|
|
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_prompt_text_is_pinned_byte_for_byte() -> None:
|
|
"""Prompt wording is behaviour: any change to it must be deliberate.
|
|
|
|
The constants are implicitly concatenated across lines for line-length, so this snapshot
|
|
guards the rendered text rather than the source layout.
|
|
"""
|
|
assert 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."
|
|
)
|
|
assert 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: names or clear labels of genuinely distinct people (by name, role or "
|
|
"appearance) that appear in the material. Speaker labels (S1, S2, ...) come from "
|
|
"automatic diarization and often split one person into several labels; collapse "
|
|
"labels describing the same voice or person into a single entry.\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."
|
|
)
|
|
assert 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."
|
|
)
|
|
assert 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."
|
|
)
|
|
assert 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."
|
|
)
|
|
assert 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 genuinely distinct people that appear (diarization labels like "
|
|
"S1/S2 often repeat one person).\n"
|
|
"- highlights: 0-3 moments with start/end seconds and a [MM:SS]-prefixed description."
|
|
)
|
|
|
|
|
|
def test_build_synthesis_prompt_contains_metadata_shots_and_transcript() -> None:
|
|
prompt, _info_value = build_synthesis_prompt(
|
|
_shots(), _transcript(), _facts(), 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:" not 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, _info_value = build_synthesis_prompt(
|
|
_shots(), None, _facts(), 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, _info_value = build_synthesis_prompt(
|
|
_shots(), _long_transcript(), _facts(), 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:" not 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 = _facts()
|
|
report = assemble_report(core, _shots(), _transcript(), info, source=SOURCE)
|
|
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 "path" not in report.metadata
|
|
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, _facts(), source=SOURCE).title == "Model title"
|
|
untitled = ReportCore(title=None, summary="Summary.")
|
|
assert (
|
|
assemble_report(untitled, _shots(), None, _facts(), source=SOURCE).title == "Metadata title"
|
|
)
|
|
plain = _facts(extra={})
|
|
assert assemble_report(untitled, _shots(), None, plain, source=SOURCE).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, _facts(extra={"yt_dlp": {"title": "YT title"}}), source=SOURCE
|
|
)
|
|
assert from_yt_dlp.title == "YT title"
|
|
from_ffprobe = assemble_report(
|
|
core,
|
|
[],
|
|
None,
|
|
_facts(extra={"ffprobe": {"format": {"tags": {"title": "Container title"}}}}),
|
|
source=SOURCE,
|
|
)
|
|
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, _facts(), source=SOURCE)
|
|
core.topics.append("two")
|
|
assert report.topics == ["one"]
|
|
|
|
|
|
def test_metadata_from_info_flattens_the_media_fields() -> None:
|
|
metadata = metadata_from_info(_facts(extra={}))
|
|
assert metadata == {
|
|
"format": "mp4",
|
|
"video_codec": "h264",
|
|
"audio_codec": "aac",
|
|
"width": 640,
|
|
"height": 360,
|
|
"fps": 12.0,
|
|
"has_audio": True,
|
|
"size_bytes": 4096,
|
|
}
|
|
|
|
|
|
def test_metadata_from_info_omits_local_filenames() -> None:
|
|
facts = _facts(
|
|
extra={"ffprobe": {"format": {"filename": "/media/sample.mp4", "format_name": "mp4"}}}
|
|
)
|
|
|
|
metadata = metadata_from_info(facts)
|
|
|
|
assert "path" not in metadata
|
|
assert metadata["extra"] == {"ffprobe": {"format": {"format_name": "mp4"}}}
|
|
|
|
|
|
# --- 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(),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=LOCAL_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
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(),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=LOCAL_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
# 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: MediaFacts,
|
|
*,
|
|
max_chars: int,
|
|
chunk_notes: str | None = None,
|
|
chunk_notes_truncated: bool = False,
|
|
) -> tuple[str, synthesis.PromptInfo]:
|
|
seen["max_chars"] = max_chars
|
|
return real_build_prompt(
|
|
shots,
|
|
transcript,
|
|
info,
|
|
max_chars=max_chars,
|
|
chunk_notes=chunk_notes,
|
|
chunk_notes_truncated=chunk_notes_truncated,
|
|
)
|
|
|
|
monkeypatch.setattr(synthesis, "build_synthesis_prompt", spy)
|
|
captured = _patch_model(monkeypatch, _canned_responder(ReportCore(summary="Summary.")))
|
|
|
|
await synthesise_report(
|
|
_shots(),
|
|
_transcript(),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=HOSTED_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
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, _facts(), source=SOURCE, options=LOCAL_SETTINGS.options_for("report")
|
|
)
|
|
with pytest.raises(ValueError, match="no shots and no transcript"):
|
|
await synthesise_report(
|
|
[],
|
|
Transcript(duration=1.0, segments=[]),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=LOCAL_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
|
|
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
|
|
|
|
|
|
# --- PromptInfo: truncation provenance as a value -------------------------
|
|
|
|
|
|
def test_build_synthesis_prompt_reports_prompt_info_as_a_value() -> None:
|
|
prompt, info = build_synthesis_prompt(
|
|
_shots(), _transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
|
|
)
|
|
|
|
assert info == synthesis.PromptInfo(
|
|
truncated=False, char_budget=LOCAL_PROMPT_CHARS, included_shots=2
|
|
)
|
|
assert len(prompt) <= LOCAL_PROMPT_CHARS
|
|
assert "transcript truncated for the prompt budget" not in prompt
|
|
|
|
|
|
def test_build_synthesis_prompt_reports_transcript_truncation_as_a_value() -> None:
|
|
prompt, info = build_synthesis_prompt(
|
|
_shots(), _long_transcript(), _facts(), max_chars=LOCAL_PROMPT_CHARS
|
|
)
|
|
|
|
assert info.truncated is True
|
|
assert info.char_budget == LOCAL_PROMPT_CHARS
|
|
assert info.included_shots == 2
|
|
assert "transcript truncated for the prompt budget" in prompt
|
|
|
|
|
|
def test_build_synthesis_prompt_counts_only_the_shots_that_fit() -> None:
|
|
shots = [
|
|
Shot(
|
|
index=index,
|
|
start=float(index),
|
|
end=float(index + 1),
|
|
description=ShotDescription(
|
|
summary=f"shot {index} " + "detail " * 50, shot_type="other"
|
|
),
|
|
)
|
|
for index in range(20)
|
|
]
|
|
|
|
prompt, info = build_synthesis_prompt(shots, _transcript(), _facts(), max_chars=900)
|
|
|
|
assert info.truncated is True
|
|
assert info.char_budget == 900
|
|
assert 0 < info.included_shots < len(shots)
|
|
assert "truncated for the prompt budget" in prompt
|
|
|
|
|
|
def test_assemble_report_exposes_prompt_info_truncation_without_an_agent_run() -> None:
|
|
prompt_info = synthesis.PromptInfo(
|
|
truncated=True, char_budget=6000, included_shots=1
|
|
).model_dump()
|
|
|
|
report = assemble_report(
|
|
ReportCore(summary="Summary."),
|
|
_shots(),
|
|
None,
|
|
_facts(),
|
|
source=SOURCE,
|
|
prompt_info={"prompt_info": prompt_info},
|
|
)
|
|
|
|
assert report.metadata["synthesis"]["prompt_info"]["truncated"] is True
|
|
assert report.metadata["synthesis"]["prompt_info"] == prompt_info
|
|
|
|
|
|
async def test_synthesise_report_records_prompt_info_in_metadata(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
_patch_model(monkeypatch, _canned_responder(ReportCore(summary="Canned summary.")))
|
|
|
|
report = await synthesise_report(
|
|
_shots(),
|
|
_transcript(),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=LOCAL_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
prompt_info = report.metadata["synthesis"]["prompt_info"]
|
|
assert prompt_info == {
|
|
"truncated": False,
|
|
"char_budget": LOCAL_PROMPT_CHARS,
|
|
"included_shots": 2,
|
|
}
|
|
assert report.metadata["synthesis"]["truncated"] is False
|
|
|
|
|
|
async def test_synthesise_report_records_a_truncated_prompt_in_metadata(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
_patch_model(monkeypatch, _canned_responder(ReportCore(summary="Canned summary.")))
|
|
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 = await synthesise_report(
|
|
shots,
|
|
_transcript(),
|
|
_facts(),
|
|
source=SOURCE,
|
|
options=LOCAL_SETTINGS.options_for("report"),
|
|
)
|
|
|
|
assert report.metadata["synthesis"]["prompt_info"]["truncated"] is True
|
|
assert report.metadata["synthesis"]["prompt_info"]["included_shots"] < len(shots)
|
|
assert report.metadata["synthesis"]["truncated"] is True
|
|
|
|
|
|
# --- _report_json budget behaviour ----------------------------------------
|
|
|
|
|
|
def _detailed_shots(count: int) -> list[Shot]:
|
|
return [
|
|
Shot(
|
|
index=index,
|
|
start=float(index),
|
|
end=float(index + 1),
|
|
description=ShotDescription(summary="detail " * 40, shot_type="other"),
|
|
)
|
|
for index in range(count)
|
|
]
|
|
|
|
|
|
def test_report_json_budget_keeps_a_shot_prefix_and_reports_omissions() -> None:
|
|
"""Pin the incremental budget: a whole shot is dropped and counted, never halved."""
|
|
report = _report()
|
|
report.shots = _detailed_shots(20)
|
|
budget = 1200
|
|
|
|
text = synthesis._report_json(report, max_chars=budget)
|
|
payload = json.loads(text)
|
|
|
|
assert len(text) <= budget
|
|
assert 0 < len(payload["shots"]) < len(report.shots)
|
|
assert [shot["index"] for shot in payload["shots"]] == list(range(len(payload["shots"])))
|
|
assert payload["shots_omitted"] == len(report.shots) - len(payload["shots"])
|
|
assert payload["highlights"] # highlights survive a truncated shot list
|
|
assert '"detail detail detail' in text # shot summaries are capped, not dropped
|
|
|
|
|
|
def test_report_json_budget_drops_shots_and_highlights_when_nothing_fits() -> None:
|
|
"""Pin the second fallback: the answer-relevant facts survive, the extras go."""
|
|
report = _report()
|
|
report.shots = _detailed_shots(20)
|
|
|
|
text = synthesis._report_json(report, max_chars=250)
|
|
payload = json.loads(text)
|
|
|
|
assert len(text) <= 250
|
|
assert "shots" not in payload
|
|
assert "highlights" not in payload
|
|
assert payload["summary"] == "A short demo about testing."
|
|
assert payload["source"] == "/media/sample.mp4"
|
|
|
|
|
|
async def test_answer_cache_is_content_addressed_by_report_under_stage_ask(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
answer = "The demo shows a slide at [00:05]."
|
|
_patch_model(monkeypatch, lambda info: ModelResponse(parts=[TextPart(answer)]))
|
|
cache = StageCache(tmp_path / "cache")
|
|
report = _report()
|
|
|
|
result = await answer_question_result(
|
|
report, "What happens at 00:05?", settings=LOCAL_SETTINGS, cache=cache
|
|
)
|
|
|
|
fingerprint = hashlib.sha256(report.model_dump_json().encode("utf-8")).hexdigest()
|
|
path = cache.stage_path(fingerprint, "ask", result.cache_key or "")
|
|
assert path.is_file()
|
|
assert path.parent == cache.source_dir(fingerprint)
|
|
assert list(path.parent.glob("stage-answer-*.json")) == []
|
|
|
|
|
|
async def test_answer_question_result_treats_a_corrupt_cached_answer_as_a_miss(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
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
|
|
)
|
|
path = cache.stage_path(
|
|
hashlib.sha256(_report().model_dump_json().encode("utf-8")).hexdigest(),
|
|
"ask",
|
|
first.cache_key or "",
|
|
)
|
|
path.write_text("{not json", encoding="utf-8")
|
|
|
|
second = await answer_question_result(
|
|
_report(), "What happens at 00:05?", settings=LOCAL_SETTINGS, cache=cache
|
|
)
|
|
|
|
assert second.cached is False
|
|
assert second.answer == answer
|
|
assert len(captured["prompts"]) == 2
|
|
assert cache.load_model(path, synthesis._AnswerArtifact) == synthesis._AnswerArtifact(
|
|
answer=answer
|
|
)
|