vwatch 0.2.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vwatch/__init__.py +3 -0
- vwatch/arms/__init__.py +27 -0
- vwatch/arms/baseline.py +74 -0
- vwatch/arms/common.py +145 -0
- vwatch/arms/external.py +356 -0
- vwatch/arms/external_audit.py +175 -0
- vwatch/arms/external_obs.py +180 -0
- vwatch/arms/external_proc.py +126 -0
- vwatch/arms/tools.py +162 -0
- vwatch/arms/watcher.py +347 -0
- vwatch/cli.py +127 -0
- vwatch/dataset/__init__.py +0 -0
- vwatch/dataset/_causal_scene.py +266 -0
- vwatch/dataset/_causal_templates.py +230 -0
- vwatch/dataset/_common.py +85 -0
- vwatch/dataset/_commons.py +123 -0
- vwatch/dataset/_encode.py +68 -0
- vwatch/dataset/_render.py +203 -0
- vwatch/dataset/_segment.py +156 -0
- vwatch/dataset/_source.py +252 -0
- vwatch/dataset/_t1x_verify.py +140 -0
- vwatch/dataset/build.py +125 -0
- vwatch/dataset/inject.py +297 -0
- vwatch/dataset/qa.py +217 -0
- vwatch/dataset/synth_causal.py +87 -0
- vwatch/dataset/synth_events.py +214 -0
- vwatch/dataset/t1x.py +213 -0
- vwatch/dataset/tvbench.py +418 -0
- vwatch/detectors.py +368 -0
- vwatch/evaluation/__init__.py +0 -0
- vwatch/evaluation/cells.py +213 -0
- vwatch/evaluation/compare.py +116 -0
- vwatch/evaluation/criteria.py +171 -0
- vwatch/evaluation/plots.py +55 -0
- vwatch/evaluation/render.py +184 -0
- vwatch/evaluation/render_extra.py +63 -0
- vwatch/evaluation/render_fmt.py +48 -0
- vwatch/evaluation/render_t5.py +33 -0
- vwatch/evaluation/report.py +144 -0
- vwatch/evaluation/runner.py +210 -0
- vwatch/evaluation/runs.py +49 -0
- vwatch/evaluation/scorecard.py +169 -0
- vwatch/evaluation/scoring.py +436 -0
- vwatch/evaluation/scoring_mcq.py +67 -0
- vwatch/evaluation/stats.py +165 -0
- vwatch/imaging.py +129 -0
- vwatch/llm/__init__.py +21 -0
- vwatch/llm/anthropic_api.py +79 -0
- vwatch/llm/base.py +79 -0
- vwatch/llm/claude_cli.py +141 -0
- vwatch/llm/fake.py +49 -0
- vwatch/llm/judge.py +23 -0
- vwatch/mcp_server.py +201 -0
- vwatch/mcp_tools.py +542 -0
- vwatch/media.py +352 -0
- vwatch/schemas.py +291 -0
- vwatch/signals.py +254 -0
- vwatch/tasks.py +122 -0
- vwatch/transcribe.py +162 -0
- vwatch-0.2.6.dist-info/METADATA +208 -0
- vwatch-0.2.6.dist-info/RECORD +64 -0
- vwatch-0.2.6.dist-info/WHEEL +4 -0
- vwatch-0.2.6.dist-info/entry_points.txt +4 -0
- vwatch-0.2.6.dist-info/licenses/LICENSE +21 -0
vwatch/__init__.py
ADDED
vwatch/arms/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Arms: the different ways of showing a video to the model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from vwatch.arms.baseline import run_baseline
|
|
6
|
+
from vwatch.arms.common import ArmResult, VideoContext
|
|
7
|
+
from vwatch.arms.external import EXTERNAL_ARMS, run_external
|
|
8
|
+
from vwatch.arms.watcher import VARIANTS, run_watcher
|
|
9
|
+
from vwatch.llm.base import Backend
|
|
10
|
+
from vwatch.schemas import Arm, Task
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def run_arm(arm: Arm, ctx: VideoContext, task: Task, prompt: str, budget: int, backend: Backend) -> ArmResult:
|
|
14
|
+
if arm is Arm.B0:
|
|
15
|
+
return run_baseline(ctx, task, prompt, budget, backend, with_transcript=False)
|
|
16
|
+
if arm in (Arm.B1, Arm.B2):
|
|
17
|
+
return run_baseline(ctx, task, prompt, budget, backend, with_transcript=True)
|
|
18
|
+
if arm is Arm.B1H:
|
|
19
|
+
return run_baseline(ctx, task, prompt, budget, backend, with_transcript=True, with_hints=True)
|
|
20
|
+
if arm in VARIANTS:
|
|
21
|
+
return run_watcher(ctx, task, prompt, budget, backend, arm=arm)
|
|
22
|
+
if arm in EXTERNAL_ARMS: # uncapped: budget is ignored (see arms/external.py)
|
|
23
|
+
return run_external(arm, ctx, task, prompt, backend)
|
|
24
|
+
raise ValueError(f"unknown arm {arm}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__all__ = ["ArmResult", "VideoContext", "run_arm"]
|
vwatch/arms/baseline.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Baselines B0/B1/B2: how Claude handles video by default — uniformly sampled frames, one shot.
|
|
2
|
+
|
|
3
|
+
B0: frames only. B1: frames + timestamped transcript. B2 is B1 run at twice the budget (runner's job).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from vwatch import media
|
|
11
|
+
from vwatch.arms.common import (HINTS_HEADER, RECOVERABLE, ArmResult, Conversation, Evidence, VideoContext,
|
|
12
|
+
add_hints, failed, finish, select_hints, video_header)
|
|
13
|
+
from vwatch.signals import describe
|
|
14
|
+
from vwatch.imaging import estimate_image_tokens, estimate_text_tokens, fmt_time, stamp
|
|
15
|
+
from vwatch.llm.base import Backend
|
|
16
|
+
from vwatch.schemas import Task
|
|
17
|
+
|
|
18
|
+
FRAME_WIDTH = 360
|
|
19
|
+
MIN_FRAMES = 4
|
|
20
|
+
|
|
21
|
+
SYSTEM = ("You analyse videos from the frames and transcript you are given. Be precise about times. "
|
|
22
|
+
"Follow the requested JSON format exactly.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def uniform_times(duration: float, n: int) -> list[float]:
|
|
26
|
+
step = duration / n
|
|
27
|
+
return [round((k + 0.5) * step, 3) for k in range(n)]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def frame_budget(ctx: VideoContext, budget: int, text_tokens: int) -> int:
|
|
31
|
+
w = FRAME_WIDTH
|
|
32
|
+
h = int(round(ctx.info.height * w / ctx.info.width))
|
|
33
|
+
per_frame = estimate_image_tokens(w, h) + 6 # + the timestamp text block
|
|
34
|
+
n = (budget - text_tokens) // per_frame
|
|
35
|
+
return int(max(MIN_FRAMES, min(n, ctx.info.nb_frames)))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def run_baseline(ctx: VideoContext, task: Task, prompt: str, budget: int, backend: Backend,
|
|
39
|
+
*, with_transcript: bool, with_hints: bool = False) -> ArmResult:
|
|
40
|
+
started = time.monotonic()
|
|
41
|
+
ev = Evidence()
|
|
42
|
+
conv: Conversation | None = None
|
|
43
|
+
try:
|
|
44
|
+
transcript = ctx.transcript.to_text() if with_transcript else ""
|
|
45
|
+
intro = video_header(ctx)
|
|
46
|
+
hints = select_hints(ctx.candidates) if with_hints else []
|
|
47
|
+
hint_text = HINTS_HEADER + describe(hints) if with_hints else ""
|
|
48
|
+
text_tokens = estimate_text_tokens(intro + transcript + prompt + hint_text) + 60
|
|
49
|
+
n = frame_budget(ctx, budget, text_tokens)
|
|
50
|
+
if n >= ctx.info.nb_frames: # budget covers every frame: take them exactly
|
|
51
|
+
times = [ctx.info.frame_time(i) for i in range(ctx.info.nb_frames)]
|
|
52
|
+
else:
|
|
53
|
+
times = uniform_times(ctx.info.duration, n)
|
|
54
|
+
frames = media.frames_at(ctx.path, times, FRAME_WIDTH)
|
|
55
|
+
ev.text(f"{intro}\nBelow are {len(frames)} frames sampled uniformly "
|
|
56
|
+
f"(about one every {ctx.info.duration / max(1, len(frames)):.2f} s).")
|
|
57
|
+
for t, f in frames:
|
|
58
|
+
ev.text(f"t={fmt_time(t)}")
|
|
59
|
+
ev.image(stamp(f, fmt_time(t)), "frame", t, t)
|
|
60
|
+
if with_transcript:
|
|
61
|
+
ev.text("TRANSCRIPT (automatic speech recognition, timestamped):\n" + transcript)
|
|
62
|
+
for s in ctx.transcript.segments:
|
|
63
|
+
ev.observe("transcript", s.t0, s.t1)
|
|
64
|
+
if with_hints:
|
|
65
|
+
add_hints(ev, hints)
|
|
66
|
+
ev.text(prompt)
|
|
67
|
+
conv = Conversation(backend.open(SYSTEM))
|
|
68
|
+
reply = conv.send(ev.take())
|
|
69
|
+
return finish(conv, task, ev, started, reply.text)
|
|
70
|
+
except RECOVERABLE as exc:
|
|
71
|
+
return failed(conv, ev, started, exc)
|
|
72
|
+
finally:
|
|
73
|
+
if conv is not None:
|
|
74
|
+
conv.session.close()
|
vwatch/arms/common.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Pieces shared by every arm: the per-video context, the evidence log and the final answer step."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from vwatch import media, signals, transcribe
|
|
12
|
+
from vwatch.imaging import estimate_image_tokens, estimate_text_tokens, image_block
|
|
13
|
+
from vwatch.llm.base import LLMError, Reply, Session, text_block
|
|
14
|
+
from vwatch.schemas import Observation, Task, Usage
|
|
15
|
+
from vwatch.tasks import REPAIR_PROMPT, parse_report
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class VideoContext:
|
|
20
|
+
"""Everything computed once per video and shared by all arms and repeats."""
|
|
21
|
+
|
|
22
|
+
path: Path
|
|
23
|
+
info: media.VideoInfo
|
|
24
|
+
transcript: transcribe.Transcript
|
|
25
|
+
track: signals.SignalTrack
|
|
26
|
+
candidates: tuple[signals.Candidate, ...]
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def load(cls, path: str | Path, *, language: str | None = None) -> VideoContext:
|
|
30
|
+
p = Path(path)
|
|
31
|
+
info = media.probe(p)
|
|
32
|
+
tr = transcribe.transcribe(p, language=language) if info.has_audio else transcribe.EMPTY
|
|
33
|
+
track = signals.compute(p)
|
|
34
|
+
return cls(path=p, info=info, transcript=tr, track=track,
|
|
35
|
+
candidates=tuple(signals.find_candidates(track)))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ArmResult:
|
|
40
|
+
raw_output: str
|
|
41
|
+
parsed: dict | None
|
|
42
|
+
parse_error: str | None
|
|
43
|
+
content_tokens_est: int
|
|
44
|
+
usage: Usage
|
|
45
|
+
cost_usd: float
|
|
46
|
+
wall_s: float
|
|
47
|
+
turns: int
|
|
48
|
+
observations: tuple[Observation, ...]
|
|
49
|
+
error: str | None = None
|
|
50
|
+
tool_calls: tuple[dict, ...] = () # external agent arms: {"name", "input"} per tool call, for human review
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Evidence:
|
|
55
|
+
"""Builds one user turn and tracks the evidence budget. Local to a single run."""
|
|
56
|
+
|
|
57
|
+
blocks: list[dict] = field(default_factory=list)
|
|
58
|
+
observations: list[Observation] = field(default_factory=list)
|
|
59
|
+
tokens: int = 0
|
|
60
|
+
|
|
61
|
+
def text(self, s: str) -> None:
|
|
62
|
+
self.blocks.append(text_block(s))
|
|
63
|
+
self.tokens += estimate_text_tokens(s)
|
|
64
|
+
|
|
65
|
+
def image(self, frame: np.ndarray, kind: str, t0: float, t1: float) -> None:
|
|
66
|
+
h, w = frame.shape[:2]
|
|
67
|
+
self.blocks.append(image_block(frame))
|
|
68
|
+
self.tokens += estimate_image_tokens(w, h)
|
|
69
|
+
self.observations.append(Observation(kind=kind, t0=round(t0, 3), t1=round(t1, 3)))
|
|
70
|
+
|
|
71
|
+
def observe(self, kind: str, t0: float, t1: float) -> None:
|
|
72
|
+
self.observations.append(Observation(kind=kind, t0=round(t0, 3), t1=round(t1, 3)))
|
|
73
|
+
|
|
74
|
+
def take(self) -> list[dict]:
|
|
75
|
+
"""Return the pending blocks and start a new turn (observations and tokens keep accumulating)."""
|
|
76
|
+
out, self.blocks = self.blocks, []
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class Conversation:
|
|
82
|
+
"""Wraps a session; accumulates usage, cost, wall time and turns."""
|
|
83
|
+
|
|
84
|
+
session: Session
|
|
85
|
+
usage: Usage = Usage()
|
|
86
|
+
cost: float = 0.0
|
|
87
|
+
wall: float = 0.0
|
|
88
|
+
turns: int = 0
|
|
89
|
+
last_text: str = ""
|
|
90
|
+
|
|
91
|
+
def send(self, blocks: list[dict]) -> Reply:
|
|
92
|
+
reply = self.session.send(blocks)
|
|
93
|
+
self.usage = self.usage.plus(reply.usage)
|
|
94
|
+
self.cost += reply.cost_usd
|
|
95
|
+
self.wall += reply.wall_s
|
|
96
|
+
self.turns += 1
|
|
97
|
+
self.last_text = reply.text
|
|
98
|
+
return reply
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def finish(conv: Conversation, task: Task, ev: Evidence, started: float, text: str) -> ArmResult:
|
|
102
|
+
"""Parse the final answer, with one repair turn on failure."""
|
|
103
|
+
parsed, err = parse_report(task, text)
|
|
104
|
+
if parsed is None:
|
|
105
|
+
reply = conv.send([text_block(REPAIR_PROMPT.format(error=err))])
|
|
106
|
+
text = reply.text
|
|
107
|
+
parsed, err = parse_report(task, text)
|
|
108
|
+
return ArmResult(raw_output=text, parsed=parsed, parse_error=err, content_tokens_est=ev.tokens,
|
|
109
|
+
usage=conv.usage, cost_usd=conv.cost, wall_s=time.monotonic() - started,
|
|
110
|
+
turns=conv.turns, observations=tuple(ev.observations))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def failed(conv: Conversation | None, ev: Evidence, started: float, exc: Exception) -> ArmResult:
|
|
114
|
+
return ArmResult(raw_output=conv.last_text if conv else "", parsed=None, parse_error=None,
|
|
115
|
+
content_tokens_est=ev.tokens, usage=conv.usage if conv else Usage(),
|
|
116
|
+
cost_usd=conv.cost if conv else 0.0, wall_s=time.monotonic() - started,
|
|
117
|
+
turns=conv.turns if conv else 0, observations=tuple(ev.observations),
|
|
118
|
+
error=f"{type(exc).__name__}: {exc}")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
RECOVERABLE = (LLMError, media.MediaError, OSError, ValueError)
|
|
122
|
+
|
|
123
|
+
MAX_HINTS = 40
|
|
124
|
+
HINTS_HEADER = "LOW-LEVEL SIGNAL HINTS (computed from every frame and the audio; hints, not verdicts):\n"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def select_hints(cands: tuple[signals.Candidate, ...] | list[signals.Candidate],
|
|
128
|
+
kinds: tuple[str, ...] | None = None, k: int = MAX_HINTS) -> list[signals.Candidate]:
|
|
129
|
+
"""The k highest-scoring candidates (optionally of given kinds), returned in time order."""
|
|
130
|
+
pool = [c for c in cands if kinds is None or c.kind in kinds]
|
|
131
|
+
top = sorted(pool, key=lambda c: (-c.score, c.t0))[:k]
|
|
132
|
+
return sorted(top, key=lambda c: c.t0)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def add_hints(ev: Evidence, hints: list[signals.Candidate]) -> None:
|
|
136
|
+
ev.text(HINTS_HEADER + signals.describe(hints))
|
|
137
|
+
for c in hints:
|
|
138
|
+
ev.observe("signal", c.t0, c.t1)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def video_header(ctx: VideoContext) -> str:
|
|
142
|
+
i = ctx.info
|
|
143
|
+
speech = "yes" if ctx.transcript.segments else "no speech detected"
|
|
144
|
+
return (f"VIDEO: {i.duration:.2f} s long, {i.width}x{i.height}, {i.fps:.0f} fps. Speech: {speech}. "
|
|
145
|
+
"Times are seconds from the start; every image has its timestamp burned in (mm:ss.ss).")
|
vwatch/arms/external.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
"""External-tool arms: Claude Code as people actually use it to watch video.
|
|
2
|
+
|
|
3
|
+
CC plain headless Claude Code (its normal system prompt) with Bash (read-only media commands) + Read.
|
|
4
|
+
CVV CC + the claude-video-vision plugin (jordanrendric/claude-video-vision), loaded with --plugin-dir.
|
|
5
|
+
POP CC + the popcorn MCP server (haithamelmengad/popcorn), attached with --mcp-config.
|
|
6
|
+
VWP CC + the vwatch plugin from this repo (plugins/vwatch: MCP tools + watch-video skill), run from the checkout.
|
|
7
|
+
|
|
8
|
+
Each run: a fresh temp dir outside the repo holding only `video.mp4` (neutral name: dataset names
|
|
9
|
+
encode the defect), `claude -p` with cwd there, no user settings / CLAUDE.md / hooks / plugins / MCP
|
|
10
|
+
of the user, permission mode dontAsk with an allowlist, a hard timeout that kills the process tree,
|
|
11
|
+
an audit of every tool call, then the temp dir is deleted.
|
|
12
|
+
|
|
13
|
+
These arms are NOT budget-capped: `budget` is ignored and content_tokens_est is 0, because that is
|
|
14
|
+
how these tools are used in practice. Compare them on accuracy and on billed cost / wall time.
|
|
15
|
+
Third-party code is pinned (PINS) and built by scripts/setup_external.sh into vendor/ (gitignored).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import shutil
|
|
24
|
+
import subprocess
|
|
25
|
+
import tempfile
|
|
26
|
+
import time
|
|
27
|
+
import uuid
|
|
28
|
+
from collections.abc import Mapping
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from vwatch.arms.common import ArmResult, VideoContext
|
|
33
|
+
from vwatch.arms.external_audit import audit, tool_calls
|
|
34
|
+
from vwatch.arms.external_obs import infer_observations
|
|
35
|
+
from vwatch.arms.external_proc import AgentProcess, AgentTimeout
|
|
36
|
+
from vwatch.llm.base import DEFAULT_MODEL, LLMError
|
|
37
|
+
from vwatch.llm.claude_cli import find_claude_binary, parse_usage
|
|
38
|
+
from vwatch.schemas import Arm, Task, Usage
|
|
39
|
+
from vwatch.tasks import REPAIR_PROMPT, parse_report
|
|
40
|
+
|
|
41
|
+
log = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
44
|
+
EXTERNAL_ARMS = (Arm.CC, Arm.CVV, Arm.POP, Arm.VWP)
|
|
45
|
+
DEFAULT_TIMEOUT_S = 900.0
|
|
46
|
+
PINS = {
|
|
47
|
+
"claude-video-vision": "4a4f99016f249a24018cd19b66531ebbcd58024b", # v1.4.0
|
|
48
|
+
"popcorn": "e6a2b2887c235f5157bb47fdbd3ca8ae9f112cc1", # 0.4.0
|
|
49
|
+
"whisper.cpp": "5eaee0cc9024eb9e9a99469199920c8b7f5cb9ec", # whisper-cli for the CVV local backend
|
|
50
|
+
}
|
|
51
|
+
# Shell commands the agent may run (what a user would approve for "look at this video"). No network
|
|
52
|
+
# tools (curl, wget), no rm/mv/sed/awk/xargs. python3 can do anything; leaks are caught by the audit.
|
|
53
|
+
BASH_COMMANDS = ("ffmpeg", "ffprobe", "python3", "python", "ls", "mkdir", "cd", "pwd", "echo", "which", "cat",
|
|
54
|
+
"head", "tail", "wc", "sort", "uniq", "cut", "tr", "grep", "bc", "file", "stat", "du")
|
|
55
|
+
CVV_MCP = "mcp__claude-video-vision"
|
|
56
|
+
POP_MCP = "mcp__popcorn"
|
|
57
|
+
# Named like the plugin-provided server so the plugin's /vwatch:watch allowed-tools match unchanged.
|
|
58
|
+
VWP_SERVER = "plugin_vwatch_vwatch"
|
|
59
|
+
VWP_MCP = f"mcp__{VWP_SERVER}"
|
|
60
|
+
CVV_WHISPER_MODEL = "small" # same size as our own transcriber; the wizard's "auto" would pick by RAM
|
|
61
|
+
_ENV_KEEP = ("HOME", "USER", "LOGNAME", "SHELL", "LANG", "TERM", "TMPDIR", "PATH", "CLAUDE_CONFIG_DIR")
|
|
62
|
+
_SANDBOX_NOTE = ("Sandbox: keep every file you create inside the current directory. Shell commands allowed here: "
|
|
63
|
+
+ ", ".join(BASH_COMMANDS) + " (anything else is blocked); no network. Commands that use shell "
|
|
64
|
+
"variables, loops or $(...) are blocked too: write each command out literally (&& and pipes are fine).")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class ExternalConfig:
|
|
69
|
+
model: str = DEFAULT_MODEL
|
|
70
|
+
effort: str | None = "medium"
|
|
71
|
+
timeout_s: float = DEFAULT_TIMEOUT_S
|
|
72
|
+
binary: str | None = None # default: find_claude_binary()
|
|
73
|
+
vendor_dir: Path = REPO_ROOT / "vendor"
|
|
74
|
+
log_dir: Path | None = REPO_ROOT / "eval" / "runs" / "external" # None = no sidecar log
|
|
75
|
+
temp_root: Path | None = None # default $TMPDIR/vwatch-ext
|
|
76
|
+
check_pins: bool = True
|
|
77
|
+
base_env: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_backend(cls, backend: object) -> ExternalConfig:
|
|
81
|
+
env = os.environ
|
|
82
|
+
return cls(model=getattr(backend, "model", DEFAULT_MODEL), effort=getattr(backend, "effort", "medium"),
|
|
83
|
+
timeout_s=float(env.get("VWATCH_EXT_TIMEOUT_S", DEFAULT_TIMEOUT_S)),
|
|
84
|
+
vendor_dir=Path(env.get("VWATCH_VENDOR_DIR", REPO_ROOT / "vendor")),
|
|
85
|
+
log_dir=Path(env["VWATCH_EXT_LOG_DIR"]) if env.get("VWATCH_EXT_LOG_DIR")
|
|
86
|
+
else REPO_ROOT / "eval" / "runs" / "external")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class RunDirs:
|
|
91
|
+
root: Path # everything for this run; deleted afterwards
|
|
92
|
+
work: Path # the agent's cwd: only video.mp4 at start
|
|
93
|
+
video: Path
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SetupError(RuntimeError):
|
|
97
|
+
"""A third-party tool is not installed/built as pinned. Run scripts/setup_external.sh."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ---------------------------------------------------------------- setup
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def make_run_dirs(src_video: Path, temp_root: Path | None) -> RunDirs:
|
|
104
|
+
base = temp_root or Path(tempfile.gettempdir()) / "vwatch-ext"
|
|
105
|
+
root = base / uuid.uuid4().hex
|
|
106
|
+
work = root / "work"
|
|
107
|
+
work.mkdir(parents=True)
|
|
108
|
+
(root / "tmp").mkdir()
|
|
109
|
+
video = work / "video.mp4"
|
|
110
|
+
shutil.copyfile(src_video, video)
|
|
111
|
+
return RunDirs(root=root, work=work, video=video)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def agent_env(base: Mapping[str, str], repo_root: Path = REPO_ROOT) -> dict[str, str]:
|
|
115
|
+
"""Minimal environment for claude: nothing that points into the repo (e.g. uv's VIRTUAL_ENV)."""
|
|
116
|
+
repo = str(repo_root)
|
|
117
|
+
env = {k: v for k, v in base.items()
|
|
118
|
+
if (k in _ENV_KEEP or k.startswith(("LC_", "ANTHROPIC_"))) and repo not in v}
|
|
119
|
+
env["PATH"] = os.pathsep.join(p for p in base.get("PATH", "").split(os.pathsep) if p and repo not in p)
|
|
120
|
+
env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1"
|
|
121
|
+
env["DISABLE_AUTOUPDATER"] = "1"
|
|
122
|
+
return env
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _pinned(vendor: Path, name: str, check: bool) -> Path:
|
|
126
|
+
repo = vendor / name
|
|
127
|
+
if not repo.is_dir():
|
|
128
|
+
raise SetupError(f"{repo} missing: run scripts/setup_external.sh")
|
|
129
|
+
if check:
|
|
130
|
+
head = subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True, text=True)
|
|
131
|
+
if head.returncode != 0 or head.stdout.strip() != PINS[name]:
|
|
132
|
+
raise SetupError(f"{repo} is at {head.stdout.strip() or '?'} but PINS says {PINS[name]}")
|
|
133
|
+
return repo
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _need(path: Path, what: str) -> Path:
|
|
137
|
+
if not path.exists():
|
|
138
|
+
raise SetupError(f"{what} not found at {path}: run scripts/setup_external.sh")
|
|
139
|
+
return path
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _node(env: Mapping[str, str]) -> str:
|
|
143
|
+
node = shutil.which("node", path=env.get("PATH"))
|
|
144
|
+
if not node:
|
|
145
|
+
raise SetupError("node not found on PATH (needed by the MCP servers)")
|
|
146
|
+
return node
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def setup_cvv(cfg: ExternalConfig, dirs: RunDirs, env: Mapping[str, str]) -> list[str]:
|
|
150
|
+
"""Per-run copy of the plugin whose MCP server runs our pinned build (not `npx ...@latest`)."""
|
|
151
|
+
repo = _pinned(cfg.vendor_dir, "claude-video-vision", cfg.check_pins)
|
|
152
|
+
server = _need(repo / "mcp-server" / "dist" / "index.js", "claude-video-vision MCP build")
|
|
153
|
+
wcpp = _pinned(cfg.vendor_dir, "whisper.cpp", cfg.check_pins)
|
|
154
|
+
whisper_bin = _need(wcpp / "build" / "bin" / "whisper-cli", "whisper-cli").parent
|
|
155
|
+
plugin = dirs.root / "plugin"
|
|
156
|
+
for part in (".claude-plugin", "commands", "skills", "agents"):
|
|
157
|
+
shutil.copytree(repo / part, plugin / part)
|
|
158
|
+
home = dirs.root / "home"
|
|
159
|
+
conf_dir = home / ".claude-video-vision"
|
|
160
|
+
conf_dir.mkdir(parents=True)
|
|
161
|
+
(conf_dir / "config.json").write_text(json.dumps(
|
|
162
|
+
{"backend": "local", "whisper_engine": "cpp", "whisper_model": CVV_WHISPER_MODEL}))
|
|
163
|
+
models = cfg.vendor_dir / "cvv-models"
|
|
164
|
+
models.mkdir(exist_ok=True)
|
|
165
|
+
(conf_dir / "models").symlink_to(models, target_is_directory=True)
|
|
166
|
+
server_env = {"HOME": str(home), "TMPDIR": str(dirs.root / "tmp"),
|
|
167
|
+
"PATH": f"{whisper_bin}{os.pathsep}{env.get('PATH', '')}"}
|
|
168
|
+
# --strict-mcp-config (which keeps the user's MCP servers out) also drops plugin-declared servers,
|
|
169
|
+
# so the plugin's own server is attached explicitly under the same name.
|
|
170
|
+
(plugin / ".mcp.json").write_text("{}")
|
|
171
|
+
conf = dirs.root / "mcp.json"
|
|
172
|
+
conf.write_text(json.dumps({"mcpServers": {"claude-video-vision": {
|
|
173
|
+
"command": _node(env), "args": [str(server)], "env": server_env}}}, indent=2))
|
|
174
|
+
return ["--plugin-dir", str(plugin), "--mcp-config", str(conf)]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def setup_pop(cfg: ExternalConfig, dirs: RunDirs, env: Mapping[str, str]) -> list[str]:
|
|
178
|
+
repo = _pinned(cfg.vendor_dir, "popcorn", cfg.check_pins)
|
|
179
|
+
server = _need(repo / "dist" / "index.js", "popcorn build")
|
|
180
|
+
venv_bin = _need(cfg.vendor_dir / "popcorn-venv" / "bin" / "python3", "popcorn transcription venv").parent
|
|
181
|
+
server_env = {"PATH": f"{venv_bin}{os.pathsep}{env.get('PATH', '')}", "TMPDIR": str(dirs.root / "tmp"),
|
|
182
|
+
"HF_HOME": str(cfg.vendor_dir / "hf-cache")}
|
|
183
|
+
conf = dirs.root / "mcp.json"
|
|
184
|
+
conf.write_text(json.dumps(
|
|
185
|
+
{"mcpServers": {"popcorn": {"command": _node(env), "args": [str(server)], "env": server_env}}}, indent=2))
|
|
186
|
+
return ["--mcp-config", str(conf)]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def setup_vwp(cfg: ExternalConfig, dirs: RunDirs, env: Mapping[str, str], repo_root: Path = REPO_ROOT) -> list[str]:
|
|
190
|
+
"""Per-run copy of this repo's plugin; its MCP server runs from the local checkout (not the release tag)."""
|
|
191
|
+
src = _need(repo_root / "plugins" / "vwatch", "vwatch plugin directory")
|
|
192
|
+
plugin = dirs.root / "plugin"
|
|
193
|
+
shutil.copytree(src, plugin)
|
|
194
|
+
(plugin / ".mcp.json").write_text("{}")
|
|
195
|
+
manifest = plugin / ".claude-plugin" / "plugin.json"
|
|
196
|
+
data = json.loads(manifest.read_text())
|
|
197
|
+
data.pop("mcpServers", None) # attached below; --strict-mcp-config drops plugin-declared servers anyway
|
|
198
|
+
manifest.write_text(json.dumps(data, indent=2))
|
|
199
|
+
uv = shutil.which("uv", path=env.get("PATH"))
|
|
200
|
+
if not uv:
|
|
201
|
+
raise SetupError("uv not found on PATH (needed to run the vwatch MCP server from the checkout)")
|
|
202
|
+
server_env = {"TMPDIR": str(dirs.root / "tmp")}
|
|
203
|
+
conf = dirs.root / "mcp.json"
|
|
204
|
+
conf.write_text(json.dumps({"mcpServers": {VWP_SERVER: {
|
|
205
|
+
"command": uv, "args": ["run", "--project", str(repo_root), "--extra", "mcp", "vwatch-mcp"],
|
|
206
|
+
"env": server_env}}}, indent=2))
|
|
207
|
+
return ["--plugin-dir", str(plugin), "--mcp-config", str(conf)]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ---------------------------------------------------------------- command and prompt
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def allowed_tools(arm: Arm) -> tuple[str, ...]:
|
|
214
|
+
bash = tuple(r for c in BASH_COMMANDS for r in (f"Bash({c})", f"Bash({c} *)"))
|
|
215
|
+
base = ("Read(./**)",) + bash
|
|
216
|
+
if arm is Arm.CVV:
|
|
217
|
+
return base + ("Skill", CVV_MCP)
|
|
218
|
+
if arm is Arm.POP:
|
|
219
|
+
return base + (POP_MCP,)
|
|
220
|
+
if arm is Arm.VWP:
|
|
221
|
+
return base + ("Skill", VWP_MCP)
|
|
222
|
+
return base
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def builtin_tools(arm: Arm) -> str:
|
|
226
|
+
return "Bash,Read,Skill" if arm in (Arm.CVV, Arm.VWP) else "Bash,Read"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def build_command(arm: Arm, cfg: ExternalConfig, binary: str, extra: list[str]) -> list[str]:
|
|
230
|
+
cmd = [binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
|
|
231
|
+
"--model", cfg.model, "--setting-sources", "", "--strict-mcp-config", "--no-session-persistence",
|
|
232
|
+
"--permission-mode", "dontAsk", "--permission-prompts", "none",
|
|
233
|
+
"--tools", builtin_tools(arm), "--allowedTools", *allowed_tools(arm),
|
|
234
|
+
"--disallowedTools", "WebFetch", "WebSearch"]
|
|
235
|
+
if cfg.effort:
|
|
236
|
+
cmd += ["--effort", cfg.effort]
|
|
237
|
+
return cmd + extra
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def agent_prompt(arm: Arm, task_text: str) -> str:
|
|
241
|
+
if arm is Arm.CVV:
|
|
242
|
+
return f"/claude-video-vision:watch-video ./video.mp4 {task_text}\n\n{_SANDBOX_NOTE}"
|
|
243
|
+
if arm is Arm.POP:
|
|
244
|
+
return f"The video is ./video.mp4. Use the popcorn MCP tools to watch it.\n{task_text}\n\n{_SANDBOX_NOTE}"
|
|
245
|
+
if arm is Arm.VWP:
|
|
246
|
+
return f"/vwatch:watch ./video.mp4 {task_text}\n\n{_SANDBOX_NOTE}"
|
|
247
|
+
return f"The video is ./video.mp4. {task_text}\n\n{_SANDBOX_NOTE}"
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ---------------------------------------------------------------- run
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _turns(events: list[dict]) -> int:
|
|
254
|
+
"""Model turns = distinct assistant message ids (stream-json emits one event per content block)."""
|
|
255
|
+
ids = set()
|
|
256
|
+
for e in events:
|
|
257
|
+
if e.get("type") == "assistant":
|
|
258
|
+
msg = e.get("message")
|
|
259
|
+
ids.add((msg.get("id") if isinstance(msg, dict) else None) or id(e))
|
|
260
|
+
return len(ids)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _usage(results: list[dict]) -> tuple[Usage, float]:
|
|
264
|
+
usage = Usage()
|
|
265
|
+
for r in results:
|
|
266
|
+
usage = usage.plus(parse_usage(r.get("usage")))
|
|
267
|
+
cost = max((float(r.get("total_cost_usd") or 0.0) for r in results), default=0.0) # cumulative
|
|
268
|
+
return usage, cost
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _converse(agent: AgentProcess, task: Task, prompt: str) -> tuple[list[dict], str, dict | None, str | None]:
|
|
272
|
+
results = [agent.ask(prompt)]
|
|
273
|
+
if results[-1].get("is_error"):
|
|
274
|
+
raise LLMError(f"claude returned an error: {str(results[-1].get('result'))[:300]}")
|
|
275
|
+
text = str(results[-1].get("result") or "")
|
|
276
|
+
parsed, err = parse_report(task, text)
|
|
277
|
+
if parsed is None:
|
|
278
|
+
results.append(agent.ask(REPAIR_PROMPT.format(error=err)))
|
|
279
|
+
if not results[-1].get("is_error"):
|
|
280
|
+
text = str(results[-1].get("result") or "")
|
|
281
|
+
parsed, err = parse_report(task, text)
|
|
282
|
+
return results, text, parsed, err
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _write_log(cfg: ExternalConfig, arm: Arm, src: Path, record: dict) -> None:
|
|
286
|
+
if cfg.log_dir is None:
|
|
287
|
+
return
|
|
288
|
+
path = cfg.log_dir / f"{arm.value}_{src.stem}_{uuid.uuid4().hex[:8]}.json"
|
|
289
|
+
try:
|
|
290
|
+
cfg.log_dir.mkdir(parents=True, exist_ok=True)
|
|
291
|
+
path.write_text(json.dumps(record, indent=1, ensure_ascii=False))
|
|
292
|
+
except OSError as exc:
|
|
293
|
+
log.warning("could not write external-arm log %s: %s", path, exc)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _cleanup(root: Path) -> None:
|
|
297
|
+
try:
|
|
298
|
+
shutil.rmtree(root)
|
|
299
|
+
except OSError as exc:
|
|
300
|
+
log.warning("could not delete run dir %s: %s", root, exc)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _launch(arm: Arm, cfg: ExternalConfig, dirs: RunDirs, task: Task, prompt: str,
|
|
304
|
+
box: list[AgentProcess]) -> tuple[list[dict], str, dict | None, str | None]:
|
|
305
|
+
env = agent_env(cfg.base_env)
|
|
306
|
+
setups = {Arm.CVV: setup_cvv, Arm.POP: setup_pop, Arm.VWP: setup_vwp}
|
|
307
|
+
extra = setups[arm](cfg, dirs, env) if arm in setups else []
|
|
308
|
+
cmd = build_command(arm, cfg, cfg.binary or find_claude_binary(), extra)
|
|
309
|
+
box.append(AgentProcess.start(cmd, cwd=str(dirs.work), env=env, timeout_s=cfg.timeout_s))
|
|
310
|
+
return _converse(box[0], task, agent_prompt(arm, prompt))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def run_external(arm: Arm, ctx: VideoContext, task: Task, prompt: str, backend: object,
|
|
314
|
+
cfg: ExternalConfig | None = None) -> ArmResult:
|
|
315
|
+
"""Run one external agent on one video. Never raises for run failures: they land in `error`."""
|
|
316
|
+
if arm not in EXTERNAL_ARMS:
|
|
317
|
+
raise ValueError(f"{arm} is not an external arm")
|
|
318
|
+
cfg = cfg or ExternalConfig.from_backend(backend)
|
|
319
|
+
started = time.monotonic()
|
|
320
|
+
dirs: RunDirs | None = None
|
|
321
|
+
box: list[AgentProcess] = [] # the agent, once started
|
|
322
|
+
results: list[dict] = []
|
|
323
|
+
text, parsed, perr, error = "", None, None, None
|
|
324
|
+
try:
|
|
325
|
+
try:
|
|
326
|
+
dirs = make_run_dirs(Path(ctx.path), cfg.temp_root)
|
|
327
|
+
results, text, parsed, perr = _launch(arm, cfg, dirs, task, prompt, box)
|
|
328
|
+
except AgentTimeout as exc:
|
|
329
|
+
error = f"timeout after {cfg.timeout_s:.0f}s: {exc}"
|
|
330
|
+
except (LLMError, SetupError, OSError, ValueError) as exc:
|
|
331
|
+
error = f"{type(exc).__name__}: {exc}"
|
|
332
|
+
finally:
|
|
333
|
+
if box:
|
|
334
|
+
box[0].close()
|
|
335
|
+
events = box[0].events if box else []
|
|
336
|
+
results = results or [e for e in events if e.get("type") == "result"]
|
|
337
|
+
calls = tool_calls(events)
|
|
338
|
+
flags = audit(calls, dirs.work, repo_root=REPO_ROOT) if dirs else ()
|
|
339
|
+
if flags:
|
|
340
|
+
error = "audit: " + " | ".join(flags)[:1500] + (f" (also: {error})" if error else "")
|
|
341
|
+
usage, cost = _usage(results)
|
|
342
|
+
obs = infer_observations(events, dirs.work, ctx.info.duration) if dirs else ()
|
|
343
|
+
res = ArmResult(raw_output=text, parsed=parsed, parse_error=perr, content_tokens_est=0, usage=usage,
|
|
344
|
+
cost_usd=cost, wall_s=time.monotonic() - started, turns=_turns(events),
|
|
345
|
+
observations=obs, error=error, tool_calls=tuple(c.to_log() for c in calls))
|
|
346
|
+
_write_log(cfg, arm, Path(ctx.path), {
|
|
347
|
+
"arm": arm.value, "video": str(ctx.path), "task": task.value, "model": cfg.model,
|
|
348
|
+
"workdir": str(dirs.work) if dirs else None, "error": error, "audit": list(flags),
|
|
349
|
+
"parse_error": perr, "raw_output": text, "cost_usd": cost, "wall_s": res.wall_s, "turns": res.turns,
|
|
350
|
+
"usage": usage.model_dump(), "tool_calls": list(res.tool_calls),
|
|
351
|
+
"permission_denials": [d.get("tool_input") for r in results for d in r.get("permission_denials") or []],
|
|
352
|
+
"observations": [o.model_dump() for o in obs], "stderr_tail": box[0].stderr_tail if box else ""})
|
|
353
|
+
return res
|
|
354
|
+
finally:
|
|
355
|
+
if dirs is not None:
|
|
356
|
+
_cleanup(dirs.root)
|