From 0d4cd81bed148220fe4a49dd59dca33314a69015 Mon Sep 17 00:00:00 2001 From: mac Date: Tue, 13 Oct 2026 20:59:22 +0500 Subject: [PATCH] Add agy engine: Gemini via the signed-in Antigravity CLI New `agy` engine and transcription backend (scripts/agy.py): the video is downloaded locally and Gemini reads it through the user's Antigravity CLI, with no API key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ skills/watch/SKILL.md | 28 +++--- skills/watch/scripts/agy.py | 166 ++++++++++++++++++++++++++++++++ skills/watch/scripts/config.py | 19 +++- skills/watch/scripts/setup.py | 24 ++++- skills/watch/scripts/watch.py | 158 ++++++++++++++++++++++++++++-- skills/watch/scripts/whisper.py | 43 ++++++++- tests/test_packaging.py | 2 +- 8 files changed, 415 insertions(+), 31 deletions(-) create mode 100644 skills/watch/scripts/agy.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f46717e..bbbff78c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to `/watch` are documented here. +## [Unreleased] + +### Added +- **agy engine.** `--engine agy` / `WATCH_ENGINE=agy` downloads the video (≤720p), extracts its audio, and has Gemini answer through the user's signed-in [Antigravity](https://antigravity.google) CLI — no API key. agy runs headless without `--dangerously-skip-permissions` and gets `--add-dir` for the run's work dir only. `WATCH_AGY_MODEL`, `WATCH_AGY_TIMEOUT`, `WATCH_AGY_BIN` tune it. +- **agy transcription backend.** `--whisper agy` / `WATCH_WHISPER_BACKEND=agy` transcribes caption-less audio in 10-minute chunks via `WATCH_AGY_TRANSCRIBE_MODEL`, restoring source-time offsets. In `auto`, agy is used when no Groq/OpenAI key is present and `agy` is installed. + ## [0.3.2] — 2026-09-25 ### Changed diff --git a/skills/watch/SKILL.md b/skills/watch/SKILL.md index 5affb5f9..1f4f92f5 100644 --- a/skills/watch/SKILL.md +++ b/skills/watch/SKILL.md @@ -1,6 +1,6 @@ --- name: watch -description: Watch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or local WhisperX / cloud Whisper fallback), and hands the result to the agent so it can answer questions about what's in the video. With a Gemini API key, Google's agentic video model watches the full video instead. +description: Watch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or local WhisperX / cloud Whisper fallback), and hands the result to the agent so it can answer questions about what's in the video. With a Gemini API key, Google's agentic video model watches the full video instead; with the signed-in Antigravity CLI (agy), Gemini watches it with no key. license: MIT allowed-tools: Bash, Read, AskUserQuestion metadata: @@ -9,7 +9,7 @@ metadata: # /watch -Run the bundled Python script. With the **gemini** engine (a `GEMINI_API_KEY` is configured) Google's video model watches the video and the report carries its timestamped answer for you to relay. With the **local** engine the script produces timestamped frames and a transcript; view the frames and answer from that evidence. Native captions come first; the chosen local or cloud backend is only a fallback. Transcript-only evidence cannot establish visual facts. +Run the bundled Python script. With the **gemini** engine (a `GEMINI_API_KEY` is configured) Google's video model watches the video and the report carries its timestamped answer for you to relay. With the **agy** engine the script downloads the video and has Gemini, through the user's signed-in Antigravity CLI (`agy`), read the video, its audio, and any captions, and the report carries Gemini's answer the same way. With the **local** engine the script produces timestamped frames and a transcript; view the frames and answer from that evidence. Native captions come first; the chosen local or cloud backend is only a fallback. Transcript-only evidence cannot establish visual facts. ## Resolve the skill and interpreter @@ -38,9 +38,10 @@ python3 "${SKILL_DIR}/scripts/setup.py" --json **Question 1 — "How should watch view videos?"** - `gemini` (recommended) — Google's Gemini model watches the whole video, including audio, and answers directly. Needs a free key from https://aistudio.google.com/apikey. YouTube URLs are sent to Google; local or downloaded videos are uploaded to Google, then deleted after the answer. +- `agy` — Gemini through the Antigravity CLI the user is already signed into (`agy` on PATH, or `WATCH_AGY_BIN`). No API key. The video is downloaded locally and Gemini reads only that run's work dir; agy runs headless with its default permissions, so it cannot run commands. - `local` — frames + transcript extracted on this machine and read by you. No key needed. -If `gemini`, run: +If `agy`, run `setup.py --engine agy` (exit 2 means agy is not found or base binaries are missing), then ask only the detail question and use `--backend agy` for transcription. If `gemini`, run: ```bash python3 "${SKILL_DIR}/scripts/setup.py" --engine gemini @@ -67,7 +68,8 @@ Then ask: **For videos without captions, how should watch transcribe?** Present: 1. `whisperx` (recommended): local transcription, no API key; audio stays on the machine. One-time download of about 1.5 GB. Requires 3 GB free disk, 8 GB RAM, and a compatible 64-bit CPU. Apple Silicon macOS is verified; Linux/Windows recipes and Intel macOS are untested. 2. `groq`: fast cloud transcription, needs a Groq key. 3. `openai`: cloud transcription, needs an OpenAI key. -4. `none`: captions only; no speech fallback. +4. `agy`: Gemini through the signed-in Antigravity CLI, no API key; audio is read by Google's Gemini. +5. `none`: captions only; no speech fallback. Use an existing explicit backend choice without asking again. Do not treat silence as permission to install local models or upload audio; the no-key/no-install path remains available. @@ -75,7 +77,7 @@ Complete the selected setup using the user's detail value: ```bash python3 "${SKILL_DIR}/scripts/setup.py" --backend whisperx --detail balanced -# Or: --backend groq / openai / none +# Or: --backend agy / groq / openai / none ``` For WhisperX, relay progress while the installer provisions uv, Python 3.12, pinned dependencies, and both model caches. `setup.py --install-whisperx` reruns this managed installer if needed. It writes the backend, executable, model, and completion marker only after warm-up succeeds. A failed local installation never selects a cloud backend automatically. @@ -97,16 +99,17 @@ python3 "${SKILL_DIR}/scripts/watch.py" "" --question ":` line), tell the user what failed and offer to rerun with `--engine local`. Do not switch engines without asking: the user may not want a long download, or may have chosen Gemini deliberately. Likewise use `--engine local` when the user says the video is private or must not leave the machine. +**No silent fallback.** If a Gemini or agy run fails (`## Unavailable evidence` with a `Gemini :` or `agy :` line), tell the user what failed and offer to rerun with `--engine local`. Do not switch engines without asking: the user may not want a long download, or may have chosen Gemini deliberately. Likewise use `--engine local` when the user says the video is private or must not leave the machine. | Option | Behavior | |---|---| -| `--engine auto|gemini|local` | Override the saved engine for this run | -| `--question TEXT` | The user's question; sent to Gemini, unused locally | +| `--engine auto|gemini|agy|local` | Override the saved engine for this run | +| `--question TEXT` | The user's question; sent to Gemini (API or agy), unused locally | | `--detail transcript|efficient|balanced|token-burner` | Override the saved detail | | `--start T --end T` | Focus on a source-time interval; SS, MM:SS, or HH:MM:SS | | `--timestamps T1,T2,...` | Pin cue frames; reserves their budget before detail selection | @@ -114,7 +117,7 @@ python3 "${SKILL_DIR}/scripts/watch.py" "" --question " SystemExit: + detail = diagnostic(detail, 600) + return SystemExit(f'agy {category}: {_HINTS[category]}.' + (f' Detail: {detail}.' if detail else '')) + + +def find_binary(configured: str = '') -> str | None: + if configured: + return configured if Path(configured).is_absolute() and Path(configured).is_file() else None + found = shutil.which('agy') + if found: + return found + fallback = Path.home() / '.local' / 'bin' / 'agy' + return str(fallback) if fallback.is_file() else None + + +def command(binary: str, prompt: str, *, model: str, add_dirs, timeout: float) -> list[str]: + cmd = [binary, '--model', model, '--output-format', 'json', '--disable-slash-commands', + '--print-timeout', f'{int(timeout)}s'] + for directory in add_dirs: + cmd += ['--add-dir', str(Path(directory).resolve())] + return cmd + [f'--print={prompt}'] # Attached, so a prompt can never be read as a flag. + + +def parse_output(stdout: str) -> dict: + """agy prints one JSON object; diagnostics may precede it on their own lines.""" + for line in reversed((stdout or '').splitlines()): + line = line.strip() + if line.startswith('{'): + try: + data = json.loads(line) + except ValueError: + continue + if isinstance(data, dict): + return data + raise _fail('response', stdout[-300:] if stdout else 'no output') + + +def run(prompt: str, *, add_dirs, model: str, timeout: float, binary: str | None, cwd: Path) -> dict: + if not binary: + raise _fail('missing') + result = run_text(command(binary, prompt, model=model, add_dirs=add_dirs, timeout=timeout), + cwd=str(cwd), timeout=timeout + 60) + try: + data = parse_output(result.stdout) + except SystemExit: + if result.returncode: + raise _fail('failed', f'exit {result.returncode}: {result.stderr or result.stdout}') from None + raise + text = str(data.get('response') or '').strip() + if data.get('status') != 'SUCCESS' and not text: + raise _fail('failed', f"status {data.get('status')}: {result.stderr}") + if not text: + denied = [str(item.get('display_name') or item.get('action')) for item in data.get('denied_actions') or [] + if isinstance(item, dict)] + raise _fail('denied', ', '.join(denied)) if denied else _fail('empty') + usage = data.get('usage') if isinstance(data.get('usage'), dict) else {} + tokens = usage.get('total_tokens') + return {'text': text, 'model': model, 'total_tokens': tokens if isinstance(tokens, int) else None} + + +def _seconds(stamp: str) -> float: + return sum(float(part) * 60 ** i for i, part in enumerate(reversed(stamp.split(':')))) + + +def parse_transcript(text: str, duration: float | None = None) -> Segments: + """Read `[START-END] text` lines into segments; anything else is ignored.""" + if text.strip() == 'NO_SPEECH': + return Segments(no_speech=True) + segments = [] + for line in text.splitlines(): + match = _LINE.match(line) + if not match: + continue + try: + start, end = _seconds(match.group(1)), _seconds(match.group(2)) + except ValueError: + continue + if duration and start > duration + 2: # Past the end of the audio: invented, not heard. + continue + segments.append({'start': round(start, 2), 'end': round(max(start, end), 2), 'text': match.group(3)}) + if not segments: + raise _fail('transcript', text[:200]) + segments.sort(key=lambda seg: seg['start']) + return Segments(segments) + + +def transcribe_file(audio: Path, *, model: str, timeout: float, binary: str | None, + duration: float | None = None) -> Segments: + audio = Path(audio).resolve() + prompt = (f'Open the audio file {audio} and transcribe all speech verbatim in its original language. ' + f'{_TOOLS_NOTE}\nOutput ONLY transcript lines, one per sentence or short phrase, in exactly ' + 'this format with times in seconds from the start of the file:\n[START-END] text\n' + 'Example: [12.4-15.9] and that is how it works.\n' + 'No headings, commentary, or markdown. If there is no speech, output exactly: NO_SPEECH') + result = run(prompt, add_dirs=[audio.parent], model=model, timeout=timeout, binary=binary, cwd=audio.parent) + return parse_transcript(result['text'], duration) + + +def _clock(seconds: float) -> str: + seconds = int(seconds) + hours, rest = divmod(seconds, 3600) + minutes, secs = divmod(rest, 60) + return f'{hours}:{minutes:02d}:{secs:02d}' if hours else f'{minutes:02d}:{secs:02d}' + + +def build_prompt(question: str | None, *, video: Path, audio: Path | None, transcript: Path | None, + offset: float = 0.0) -> str: + files = [f'- {video} — the video. Your viewer shows its frames but not its sound.'] + if audio: + files.append(f'- {audio} — the soundtrack of that video, on the same timeline. Listen to it.') + if transcript: + files.append(f'- {transcript} — the platform captions, timestamps in source-video time. ' + 'Use them to check what you hear.') + timing = '' + if offset: + timing = (f'\nThe video and audio files are a clip that starts at {_clock(offset)} in the source video. ' + f'Add {_clock(offset)} to every position you observe so all cited timestamps are source-video time.') + return ('Answer the question about a video using these local files. ' + _TOOLS_NOTE + '\n' + + '\n'.join(files) + timing + + f'\n\nQuestion: {(question or "").strip() or DEFAULT_QUESTION}\n\n' + 'Cite an MM:SS (or H:MM:SS) timestamp for every claim about a specific moment. Separate what is ' + 'seen from what is heard when it matters. If the video does not show or say something needed ' + 'to answer, say so plainly instead of guessing.') + + +def ask(question: str | None, *, video: Path, audio: Path | None, transcript: Path | None, offset: float, + model: str, timeout: float, binary: str | None, work: Path) -> dict: + prompt = build_prompt(question, video=Path(video).resolve(), audio=Path(audio).resolve() if audio else None, + transcript=Path(transcript).resolve() if transcript else None, offset=offset) + return run(prompt, add_dirs=[work], model=model, timeout=timeout, binary=binary, cwd=work) diff --git a/skills/watch/scripts/config.py b/skills/watch/scripts/config.py index 988cebe3..113b0dec 100644 --- a/skills/watch/scripts/config.py +++ b/skills/watch/scripts/config.py @@ -12,9 +12,11 @@ CONFIG_FILE = CONFIG_DIR / '.env' DEFAULT_DETAIL = 'balanced' DETAILS = {'transcript', 'efficient', 'balanced', 'token-burner'} -BACKENDS = {'auto', 'groq', 'openai', 'whisperx', 'none'} -ENGINES = {'auto', 'gemini', 'local'} +BACKENDS = {'auto', 'groq', 'openai', 'whisperx', 'agy', 'none'} +ENGINES = {'auto', 'gemini', 'agy', 'local'} DEFAULT_GEMINI_MODEL = 'gemini-3.7-flash' +DEFAULT_AGY_MODEL = 'gemini-3.8-flash-medium' +DEFAULT_AGY_TRANSCRIBE_MODEL = 'gemini-3.8-flash-low' class ConfigError(ValueError): @@ -122,7 +124,9 @@ def load_gemini_key() -> str | None: def resolve_engine(choice: str, has_key: bool) -> str: if choice not in ENGINES: - raise ConfigError('WATCH_ENGINE must be auto, gemini, or local.') + raise ConfigError('WATCH_ENGINE must be auto, gemini, agy, or local.') + if choice == 'agy': + return 'agy' if choice == 'gemini' and not has_key: raise ConfigError('The gemini engine needs GEMINI_API_KEY in the environment or ' f'{CONFIG_FILE}. Add it, or rerun with --engine local.') @@ -136,10 +140,10 @@ def setting(name, default=''): detail = setting('WATCH_DETAIL', DEFAULT_DETAIL) backend = backend_override if backend_override is not None else setting('WATCH_WHISPER_BACKEND', 'auto') if backend not in BACKENDS: - raise ConfigError('WATCH_WHISPER_BACKEND must be auto, groq, openai, whisperx, or none.') + raise ConfigError('WATCH_WHISPER_BACKEND must be auto, groq, openai, whisperx, agy, or none.') engine = setting('WATCH_ENGINE', 'auto') if engine not in ENGINES: - raise ConfigError('WATCH_ENGINE must be auto, gemini, or local.') + raise ConfigError('WATCH_ENGINE must be auto, gemini, agy, or local.') return { 'detail': detail if detail in DETAILS else DEFAULT_DETAIL, 'config_file': str(CONFIG_FILE), @@ -147,6 +151,11 @@ def setting(name, default=''): 'engine': engine, 'gemini_model': setting('WATCH_GEMINI_MODEL', DEFAULT_GEMINI_MODEL) or DEFAULT_GEMINI_MODEL, 'gemini_timeout': positive_number(setting('WATCH_GEMINI_TIMEOUT', '600'), 'WATCH_GEMINI_TIMEOUT'), + 'agy_bin': setting('WATCH_AGY_BIN'), + 'agy_model': setting('WATCH_AGY_MODEL', DEFAULT_AGY_MODEL) or DEFAULT_AGY_MODEL, + 'agy_transcribe_model': (setting('WATCH_AGY_TRANSCRIBE_MODEL', DEFAULT_AGY_TRANSCRIBE_MODEL) + or DEFAULT_AGY_TRANSCRIBE_MODEL), + 'agy_timeout': positive_number(setting('WATCH_AGY_TIMEOUT', '900'), 'WATCH_AGY_TIMEOUT'), 'sub_lang': setting('WATCH_SUB_LANG', 'auto'), 'cookies_file': setting('WATCH_COOKIES_FILE'), 'cookies_from_browser': setting('WATCH_COOKIES_FROM_BROWSER'), diff --git a/skills/watch/scripts/setup.py b/skills/watch/scripts/setup.py index 8170e020..6967f46e 100755 --- a/skills/watch/scripts/setup.py +++ b/skills/watch/scripts/setup.py @@ -15,6 +15,7 @@ from config import (CONFIG_DIR, CONFIG_FILE, ConfigError, DETAILS, ENGINES, get_config, load_api_key, load_gemini_key, read_env_file, resolve_engine, write_settings) from runtime import configure_stdio, diagnostic, run_text +import agy REQUIRED_BINARIES = ['ffmpeg', 'ffprobe', 'yt-dlp'] WHISPERX_VERSION = '3.8.6' @@ -23,8 +24,10 @@ # Native captions always come first. Optional fallback: auto|whisperx|groq|openai|none. # auto preserves the Groq-then-OpenAI preference for existing installations. # The first-run skill wizard sets WATCH_DETAIL and WATCH_WHISPER_BACKEND. -# WATCH_ENGINE=auto|gemini|local. auto uses Gemini when GEMINI_API_KEY is set. +# WATCH_ENGINE=auto|gemini|agy|local. auto uses Gemini when GEMINI_API_KEY is set. # With the gemini engine, local videos are uploaded to Google for analysis. +# agy: no key; Gemini through the signed-in Antigravity CLI reads the downloaded media. +# WATCH_WHISPER_BACKEND=agy transcribes caption-less audio the same way. GEMINI_API_KEY= GROQ_API_KEY= OPENAI_API_KEY= @@ -150,14 +153,22 @@ def _status(detailed=False): engine = resolve_engine(cfg['engine'], gemini_key) except ConfigError: engine = 'gemini' # Explicitly chosen but the key is missing; gemini_key_present reports it. - binaries_required = engine == 'local' + binaries_required = engine in ('local', 'agy') has_key, detected = _have_api_key() chosen = cfg['whisper_backend'] + agy_bin = agy.find_binary(cfg['agy_bin']) backend = detected if chosen == 'auto' else chosen + if chosen == 'auto' and not detected and agy_bin: + backend = 'agy' local_ready = _whisperx_status(cfg, detailed) - backend_ready = local_ready if chosen == 'whisperx' else (bool(load_api_key(backend)[1]) if backend in ('groq', 'openai') else chosen == 'none') + backend_ready = (local_ready if chosen == 'whisperx' else bool(agy_bin) if backend == 'agy' + else bool(load_api_key(backend)[1]) if backend in ('groq', 'openai') else chosen == 'none') + if not agy_bin and (engine == 'agy' or chosen == 'agy'): + missing.append('agy') + binaries_required = True blocked = bool(missing) and binaries_required result = {'status': 'needs_install' if blocked else 'ready', 'can_proceed': not blocked, + 'agy_bin': agy_bin, 'agy_model': cfg['agy_model'], 'agy_transcribe_model': cfg['agy_transcribe_model'], 'engine': engine, 'configured_engine': cfg['engine'], 'gemini_key_present': gemini_key, 'gemini_model': cfg['gemini_model'], 'binaries_required': binaries_required, 'first_run': is_first_run(), 'setup_complete': not is_first_run(), @@ -187,6 +198,8 @@ def cmd_check(): status = _status() if status['can_proceed']: return 0 + if 'agy' in status['missing_binaries']: + print(f'[watch] {agy._HINTS["missing"]}.', file=sys.stderr) print(f"[watch] Missing {', '.join(status['missing_binaries'])}. Run python3 \"{Path(__file__).resolve()}\".", file=sys.stderr) return 2 @@ -200,6 +213,9 @@ def cmd_install(backend=None, detail=None, engine=None): if engine: _scaffold_env() write_settings({'WATCH_ENGINE': engine}, CONFIG_FILE) + if (engine == 'agy' or backend == 'agy') and not agy.find_binary(get_config()['agy_bin']): + print(f'[setup] {agy._HINTS["missing"]}.', file=sys.stderr) + return 2 if engine == 'gemini': if not load_gemini_key(): print(f'[setup] Add GEMINI_API_KEY privately to {CONFIG_FILE} (free key: https://aistudio.google.com/apikey), ' @@ -318,7 +334,7 @@ def main(): mode.add_argument('--check', action='store_true') mode.add_argument('--json', action='store_true') mode.add_argument('--install-whisperx', action='store_true') - parser.add_argument('--backend', choices=['auto', 'whisperx', 'groq', 'openai', 'none']) + parser.add_argument('--backend', choices=['auto', 'whisperx', 'groq', 'openai', 'agy', 'none']) parser.add_argument('--detail', choices=sorted(DETAILS)) parser.add_argument('--engine', choices=sorted(ENGINES)) args = parser.parse_args() diff --git a/skills/watch/scripts/watch.py b/skills/watch/scripts/watch.py index b5b322aa..213c46c9 100755 --- a/skills/watch/scripts/watch.py +++ b/skills/watch/scripts/watch.py @@ -8,6 +8,7 @@ import argparse import math +import os import shutil import sys import tempfile @@ -18,11 +19,13 @@ sys.path.insert(0, str(SCRIPT_DIR)) from config import ConfigError, frame_cap, get_config, load_gemini_key, resolve_engine # noqa: E402 +import agy # noqa: E402 import gemini # noqa: E402 from download import download, fetch_captions, is_url, auth_args # noqa: E402 from frames import MAX_FPS, auto_fps, auto_fps_focus, extract_at_timestamps, extract_keyframes, extract_scene_or_uniform, format_time, get_metadata, merge_frames, parse_time, parse_timestamps, validate_controls # noqa: E402 from transcribe import filter_range, format_transcript, parse_vtt # noqa: E402 -from whisper import load_api_key, transcribe_video # noqa: E402 +from whisper import extract_audio, load_api_key, transcribe_video # noqa: E402 +from runtime import run_text # noqa: E402 from runtime import configure_stdio # noqa: E402 @@ -91,6 +94,136 @@ def run_gemini(args, config, key, start_sec, end_sec, auth) -> int: return 0 +# agy sends the whole file inline in one request. A full-size phone clip (66 MB of 1080p HEVC for +# 57 s) hung for over 15 min or died with "write: broken pipe"; the same clip at 720p (6.6 MB, +# ~6 s to encode) answered in ~2 min. Gemini samples video at about 1 fps anyway. +AGY_PROXY_MIN_BYTES = 20_000_000 +AGY_PROXY_SHORT_SIDE = 720 + + +def _agy_view(source: Path, work: Path, start_sec, end_sec, meta=None) -> Path: + """The file agy opens: the focus range, or the whole video - as-is when small, else a 720p proxy.""" + clip = start_sec is not None or end_sec is not None + if not clip: + dims = [d for d in ((meta or {}).get("width"), (meta or {}).get("height")) if d] + small = source.stat().st_size <= AGY_PROXY_MIN_BYTES and (not dims or min(dims) <= AGY_PROXY_SHORT_SIDE) + if small: + if source.resolve().is_relative_to(work.resolve()): + return source + view = work / f"source{source.suffix or '.mp4'}" + try: + os.link(source, view) + except OSError: + shutil.copy2(source, view) # agy only reads inside the work dir; never widen it to the user's folder. + return view + view = work / ("clip.mp4" if clip else "proxy.mp4") + side = AGY_PROXY_SHORT_SIDE + cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + if start_sec is not None: + cmd += ["-ss", f"{start_sec:.3f}"] + if end_sec is not None: + cmd += ["-to", f"{end_sec:.3f}"] if start_sec is None else ["-t", f"{end_sec - start_sec:.3f}"] + cmd += ["-i", str(source.resolve()), "-map", "0:v:0", "-map", "0:a:0?", # drop phone metadata tracks + "-vf", f"scale='if(gt(iw,ih),-2,min({side},iw))':'if(gt(iw,ih),min({side},ih),-2)'", # short side + "-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-c:a", "aac", "-b:a", "96k", str(view)] + result = run_text(cmd) + if result.returncode or not view.exists(): + what = "cut the focus range" if clip else "make the 720p proxy" + raise SystemExit(f"ffmpeg could not {what}: {result.stderr.strip()}") + return view + + +def run_agy(args, config, start_sec, end_sec, auth) -> int: + """Gemini, signed in through the agy CLI, watches local media. No API key; nothing is uploaded by us.""" + ignored = [flag for flag, name in LOCAL_ONLY_FLAGS + if name not in ("whisper", "sub_lang") and getattr(args, name) is not None] + ignored += ["--no-dedup"] if args.no_dedup else [] + clip = start_sec is not None or end_sec is not None + binary = agy.find_binary(config["agy_bin"]) + parent = Path(args.out_dir).expanduser().resolve() if args.out_dir else None + if parent: + parent.mkdir(parents=True, exist_ok=True) + work = Path(tempfile.mkdtemp(prefix="watch-", dir=parent)) + print(f"[watch] working dir: {work}", file=sys.stderr) + dl, result, error, notes, transcript_label = {"info": {}}, None, None, [], None + try: + if not binary: + raise agy._fail("missing") + segments = [] + if is_url(args.source): + print("[watch] checking metadata/captions via yt-dlp…", file=sys.stderr) + dl = fetch_captions(args.source, work / "download", + sub_lang=args.sub_lang or config["sub_lang"], **auth) + if dl.get("subtitle_path"): + try: + segments = parse_vtt(dl["subtitle_path"]) + except (OSError, ValueError) as exc: + notes.append(f"Caption parsing failed: {exc}") + print("[watch] downloading media…", file=sys.stderr) + dl.update(download(args.source, work / "download", context=dl, **auth)) + else: + print("[watch] using local file…", file=sys.stderr) + dl.update(download(args.source, work / "download")) + source = Path(dl["video_path"]) + meta = get_metadata(str(source)) + if clip and start_sec is not None and meta["duration_seconds"] and start_sec >= meta["duration_seconds"]: + raise SystemExit(f"--start {start_sec:.1f}s is past end of video ({meta['duration_seconds']:.1f}s)") + view = _agy_view(source, work, start_sec, end_sec, meta) + audio = None + if meta.get("has_audio"): + audio = extract_audio(str(view), work / "audio.mp3") + transcript = None + segments = filter_range(segments, start_sec, end_sec) if clip else segments + if segments: + transcript = work / "captions.txt" + transcript.write_text(format_transcript(segments) + "\n", encoding="utf-8") + track = dl.get("caption_track") or {} + transcript_label = f"captions ({track.get('language', 'unknown')}, {track.get('kind', 'unknown')})" + print(f"[watch] asking {config['agy_model']} via agy…", file=sys.stderr) + result = agy.ask(args.question, video=view, audio=audio, transcript=transcript, offset=start_sec or 0.0, + model=config["agy_model"], timeout=config["agy_timeout"], binary=binary, work=work) + except SystemExit as exc: + error = str(exc) + + info = dl.get("info") or {} + print() + print("# watch: video report") + print() + print(f"- **Source:** {args.source} (read locally by agy; Gemini sees only the work dir)") + if info.get("title"): + print(f"- **Title:** {info['title']}") + if info.get("uploader"): + print(f"- **Uploader:** {info['uploader']}") + print(f"- **Engine:** agy {config['agy_model']} ({'answered' if result else 'failed'})") + if clip: + print(f"- **Focus range:** {format_time(start_sec or 0)} → {format_time(end_sec) if end_sec is not None else 'end'}") + if transcript_label: + print(f"- **Captions given to Gemini:** {transcript_label}") + if ignored: + print(f"- **Ignored local options:** {', '.join(ignored)} (these only apply with --engine local)") + if result and result["total_tokens"] is not None: + print(f"- **Gemini tokens:** {result['total_tokens']}") + for note in notes: + print(f"- **Note:** {note}") + print() + if error: + print("## Unavailable evidence") + print() + print(f"- {error}") + print("- No local fallback was attempted; rerun with `--engine local` to use frames + transcript.") + else: + print("## Answer (from Gemini via agy)") + print() + print("_These are Gemini's observations of the video, not frames you viewed yourself. " + "Relay them as such; rerun with `--engine local` (same work dir media) to inspect frames directly._") + print() + print(result["text"]) + print() + print("---") + print(f"_Work dir: `{work}` — delete when done._") + return 1 if error else 0 + + def main() -> int: ap = argparse.ArgumentParser( prog="watch", @@ -125,7 +258,7 @@ def main() -> int: ) ap.add_argument( "--whisper", - choices=["groq", "openai", "whisperx"], + choices=["groq", "openai", "whisperx", "agy"], default=None, help="Select the fallback backend for this run; native captions still come first.", ) @@ -139,11 +272,12 @@ def main() -> int: cookies = ap.add_mutually_exclusive_group() cookies.add_argument("--cookies", default=None, help="Explicit cookie file (yt-dlp may update this jar)") cookies.add_argument("--cookies-from-browser", default=None, help="Explicit yt-dlp browser selector") - ap.add_argument("--engine", choices=["auto", "gemini", "local"], default=None, + ap.add_argument("--engine", choices=["auto", "gemini", "agy", "local"], default=None, help="gemini: Google watches the video and answers (needs GEMINI_API_KEY). " + "agy: Gemini via the signed-in Antigravity CLI reads the downloaded video and audio. " "local: frames + transcript on this machine. Default auto: gemini when a key exists.") ap.add_argument("--question", default=None, - help="The user's question. Sent to Gemini on a gemini run; unused by the local engine.") + help="The user's question. Sent to Gemini on a gemini or agy run; unused by the local engine.") args = ap.parse_args() if args.no_whisper and args.whisper: ap.error("--no-whisper conflicts with --whisper") @@ -162,8 +296,11 @@ def main() -> int: auth = {"cookies_file": cookies_file, "cookies_from_browser": cookies_browser} gemini_key = load_gemini_key() - if resolve_engine(args.engine or config["engine"], bool(gemini_key)) == "gemini": + engine = resolve_engine(args.engine or config["engine"], bool(gemini_key)) + if engine == "gemini": return run_gemini(args, config, gemini_key, start_sec, end_sec, auth) + if engine == "agy": + return run_agy(args, config, start_sec, end_sec, auth) parent = Path(args.out_dir).expanduser().resolve() if args.out_dir else None if parent: @@ -265,14 +402,21 @@ def main() -> int: transcript_state = "missing" if not track_available and backend_choice != "none" and video_path and meta.get("has_audio"): - backend, api_key = ("whisperx", None) if backend_choice == "whisperx" else load_api_key(None if backend_choice == "auto" else backend_choice) + if backend_choice in ("whisperx", "agy"): + backend, api_key = backend_choice, None + else: + backend, api_key = load_api_key(None if backend_choice == "auto" else backend_choice) + if not backend and backend_choice == "auto" and agy.find_binary(config["agy_bin"]): + backend = "agy" # Last resort for keyless installs: Gemini through the signed-in agy CLI. if backend: try: all_segments, used_backend = transcribe_video(video_path, work / "audio.mp3", backend=backend, api_key=api_key) gaps = getattr(all_segments, "gaps", []) track_available = True transcript_state = "no speech" if not all_segments else "available" - if used_backend == "whisperx": + if used_backend == "agy": + transcript_source = f"gemini via agy ({config['agy_transcribe_model']})" + elif used_backend == "whisperx": language = config["whisperx_language"] or "auto (unverified)" transcript_source = f"whisper (whisperx {config['whisperx_model']}, language {language})" else: diff --git a/skills/watch/scripts/whisper.py b/skills/watch/scripts/whisper.py index 391e253a..be329daf 100755 --- a/skills/watch/scripts/whisper.py +++ b/skills/watch/scripts/whisper.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Transcribe a video via local WhisperX or the Groq/OpenAI Whisper APIs. +"""Transcribe a video via local WhisperX, Gemini through agy, or the Groq/OpenAI Whisper APIs. Strategy: extract audio (mono 16kHz mp3, tiny payload), upload to whichever API has a key. Returns segments in the same shape as transcribe.parse_vtt so @@ -344,6 +344,41 @@ def _transcribe_file(backend: str, api_key: str, audio_path: Path) -> list[dict] return _segments_from_response(response) +def time_chunks(total_seconds: float, chunk_seconds: float) -> list[tuple[float, float]]: + """Even (offset, duration) chunks no longer than chunk_seconds.""" + if total_seconds <= chunk_seconds: + return [(0.0, total_seconds)] + n = math.ceil(total_seconds / chunk_seconds) + step = total_seconds / n + return [(round(i * step, 3), round(total_seconds - i * step if i == n - 1 else step, 3)) for i in range(n)] + + +def _transcribe_agy(video_path: str, audio_out: Path) -> list[dict]: + import agy + from config import get_config + cfg = get_config() + binary = agy.find_binary(cfg["agy_bin"]) + if not binary: + raise agy._fail("missing") + model = cfg["agy_transcribe_model"] + print(f"[watch] extracting audio for Gemini via agy ({model})…", file=sys.stderr) + audio_path = extract_audio(video_path, audio_out) + duration = audio_duration(audio_path) + plan = time_chunks(duration, agy.CHUNK_SECONDS) + chunks = [(audio_path, 0.0)] if len(plan) == 1 else split_audio(audio_path, audio_out.parent / "chunks", plan) + if len(chunks) > 1: + print(f"[watch] audio: {duration / 60:.0f} min — transcribing in {len(chunks)} chunks…", file=sys.stderr) + durations = {path: length for (path, _), (_, length) in zip(chunks, plan)} + + def transcribe_one(path: Path) -> list[dict]: + return agy.transcribe_file(path, model=model, timeout=cfg["agy_timeout"], binary=binary, + duration=durations.get(path)) + + segments = transcribe_chunks(chunks, transcribe_one) + print(f"[watch] transcribed {len(segments)} segments via agy ({model})", file=sys.stderr) + return segments + + def transcribe_video( video_path: str, audio_out: Path, @@ -362,6 +397,10 @@ def transcribe_video( from local_whisperx import transcribe_audio segments = transcribe_audio(extract_audio(video_path, audio_out)) return segments, "whisperx" + if backend == "agy": + if api_key is not None: + raise SystemExit("agy signs in with your Google account and does not accept an API key.") + return _transcribe_agy(video_path, audio_out), "agy" if backend not in (None, "groq", "openai"): raise SystemExit("Unknown transcription backend.") if backend is None or api_key is None: @@ -416,7 +455,7 @@ def transcribe_one(path: Path) -> list[dict]: parser = argparse.ArgumentParser(description="Transcribe local media with the selected Whisper backend.") parser.add_argument("video") parser.add_argument("audio_out", nargs="?", default="audio.mp3", type=Path) - parser.add_argument("--backend", choices=["groq", "openai", "whisperx"]) + parser.add_argument("--backend", choices=["groq", "openai", "whisperx", "agy"]) args = parser.parse_args() try: segments, backend = transcribe_video(args.video, Path(args.audio_out), backend=args.backend) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index eaa0b6fd..babd383f 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -44,7 +44,7 @@ def test_skill_documents_and_bundles_the_gemini_engine(): assert needle in skill, needle assert 'CLAUDE_SKILL_DIR' not in skill runtime = sorted(p.name for p in (ROOT / 'skills/watch/scripts').glob('*.py')) - assert runtime == ['config.py', 'download.py', 'frames.py', 'gemini.py', 'local_whisperx.py', + assert runtime == ['agy.py', 'config.py', 'download.py', 'frames.py', 'gemini.py', 'local_whisperx.py', 'runtime.py', 'setup.py', 'transcribe.py', 'watch.py', 'whisper.py']