diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f46717e..2168a227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to `/watch` are documented here. +## [Unreleased] + +### Added +- **OpenRouter provider for the Gemini engine.** With an `OPENROUTER_API_KEY` (and no `GEMINI_API_KEY`, or with `WATCH_GEMINI_PROVIDER=openrouter`), watch sends YouTube URLs to Gemini through OpenRouter's chat completions API. Other sources fail before anything is sent, because OpenRouter's Google AI Studio route accepts only YouTube video URLs. `WATCH_GEMINI_MODEL` IDs get a `google/` prefix, `--start/--end` become a request in the prompt, and the report shows the OpenRouter cost. + +### Fixed +- HTTP 402 (spent prepaid credit) is reported as `Gemini quota`, not as `Gemini rejected` with a hint about private or unsupported videos. + ## [0.3.2] — 2026-09-25 ### Changed diff --git a/README.md b/README.md index c9ca1da3..7b777906 100644 --- a/README.md +++ b/README.md @@ -190,8 +190,10 @@ See the official guides for [Claude Code on the web](https://code.claude.com/doc | Setting | Default and behavior | |---|---| -| `WATCH_ENGINE` / `--engine` | `auto`: Gemini when a `GEMINI_API_KEY` resolves, otherwise `local`. `gemini` without a key is an error before any network call. `local` never contacts Google. | +| `WATCH_ENGINE` / `--engine` | `auto`: Gemini when a `GEMINI_API_KEY` (or `OPENROUTER_API_KEY`) resolves, otherwise `local`. `gemini` without a key is an error before any network call. `local` never contacts Google. | | `GEMINI_API_KEY` | Looked up in the environment, then `~/.config/watch/.env`, then a cwd `.env`. Sent only as a request header; never logged. | +| `OPENROUTER_API_KEY` | Runs the Gemini engine through [OpenRouter](https://openrouter.ai/keys) when no `GEMINI_API_KEY` resolves. Same lookup order. YouTube URLs only; `--start`/`--end` become a request in the prompt. OpenRouter bills each request, and the report shows the cost. | +| `WATCH_GEMINI_PROVIDER` | `auto`: `GEMINI_API_KEY` first, then `OPENROUTER_API_KEY`. `google` or `openrouter` uses only that key. | | `WATCH_GEMINI_MODEL` | `gemini-3.7-flash`. Free-form, so newer model IDs work without an update. | | `WATCH_GEMINI_TIMEOUT` | `600` seconds for the question itself; upload and processing waits are bounded separately. | diff --git a/skills/watch/SKILL.md b/skills/watch/SKILL.md index 5affb5f9..efb107ca 100644 --- a/skills/watch/SKILL.md +++ b/skills/watch/SKILL.md @@ -37,7 +37,7 @@ 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. +- `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. An OpenRouter key (`OPENROUTER_API_KEY`, https://openrouter.ai/keys) also works, for YouTube URLs only; OpenRouter bills each request. - `local` — frames + transcript extracted on this machine and read by you. No key needed. If `gemini`, run: @@ -46,9 +46,9 @@ If `gemini`, run: python3 "${SKILL_DIR}/scripts/setup.py" --engine gemini ``` -Exit 3 means the key is missing; the command has created `~/.config/watch/.env` for it. Point the user to https://aistudio.google.com/apikey for a free key and let them choose how to add it: +Exit 3 means the key is missing; the command has created `~/.config/watch/.env` for it. Point the user to https://aistudio.google.com/apikey for a free key (or https://openrouter.ai/keys for an `OPENROUTER_API_KEY`, YouTube URLs only) and let them choose how to add it: -- **Paste it in chat.** Write it on the `GEMINI_API_KEY=` line of the config file (add the line if it is missing) with a file-editing tool, preserving the other lines. +- **Paste it in chat.** Write it on the `GEMINI_API_KEY=` (or `OPENROUTER_API_KEY=`) line of the config file (add the line if it is missing) with a file-editing tool, preserving the other lines. - **Add it themselves.** Offer to open the config file in their text editor (`open -t` on macOS, `notepad` on Windows, `xdg-open` on Linux) so they can paste the key after `GEMINI_API_KEY=` and save. This only works when you run on the user's own computer; otherwise give them the file path. Never print the key or put it in a shell command. Once it is saved, rerun `setup.py --engine gemini`. On exit 0 setup is complete — **skip the detail and transcription questions**; they only apply to the local engine. If `local`: run `setup.py --engine local` (this also installs missing base binaries and scaffolds the private config) and continue with the two questions below. An existing explicit `WATCH_ENGINE` is not asked again. @@ -97,9 +97,10 @@ 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. @@ -159,6 +160,7 @@ For follow-ups, reuse evidence already viewed before rerunning. Remove only the - yt-dlp contacts the source service/CDNs for metadata, one selected caption track, and media; access may require explicitly configured authentication. A cookie file is a read/write jar. - With the Gemini engine, YouTube URLs are sent to Google and local or downloaded videos are uploaded to Google's Files API (generativelanguage.googleapis.com), then deleted after the answer; an upload that cannot be deleted expires within 48 hours. The key is sent only as a request header. The local engine never contacts Google. +- With the gemini engine via OpenRouter, the YouTube URL and the question go to openrouter.ai, which passes them to Google. The key is sent only as an Authorization header, and OpenRouter bills the account for each request. - FFmpeg/ffprobe run locally for probing, frames, and mono audio extraction. - With `whisperx` selected, audio never leaves the machine. First setup downloads packages and models from PyPI, Hugging Face, and GitHub, with uv/Python installers as needed. Pyannote telemetry is disabled. Warm caches allow offline inference; model libraries may still attempt cache/update network checks. - With `groq` or `openai` selected, only extracted audio is uploaded to that provider's transcription endpoint; keys are never shared between providers or logged by watch. diff --git a/skills/watch/scripts/config.py b/skills/watch/scripts/config.py index 988cebe3..60d08e85 100644 --- a/skills/watch/scripts/config.py +++ b/skills/watch/scripts/config.py @@ -14,6 +14,7 @@ DETAILS = {'transcript', 'efficient', 'balanced', 'token-burner'} BACKENDS = {'auto', 'groq', 'openai', 'whisperx', 'none'} ENGINES = {'auto', 'gemini', 'local'} +GEMINI_PROVIDERS = {'auto', 'google', 'openrouter'} DEFAULT_GEMINI_MODEL = 'gemini-3.7-flash' @@ -109,22 +110,36 @@ def load_api_key(preferred: str | None = None) -> tuple[str | None, str | None]: return None, None -def load_gemini_key() -> str | None: +def _lookup_key(name: str) -> str | None: """Environment, then the user config, then a project .env; never logged.""" - value = os.environ.get('GEMINI_API_KEY', '').strip() + value = os.environ.get(name, '').strip() if not value: for path in (CONFIG_FILE, Path.cwd() / '.env'): - value = read_env_file(path).get('GEMINI_API_KEY', '').strip() + value = read_env_file(path).get(name, '').strip() if value: break return value or None +def load_gemini_key() -> str | None: + return _lookup_key('GEMINI_API_KEY') + + +def load_gemini_credentials(provider: str = 'auto') -> tuple[str | None, str | None]: + """(provider, key) for the gemini engine. auto prefers GEMINI_API_KEY over OPENROUTER_API_KEY.""" + for name, variable in (('google', 'GEMINI_API_KEY'), ('openrouter', 'OPENROUTER_API_KEY')): + if provider in ('auto', name): + value = _lookup_key(variable) + if value: + return name, value + return None, 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.') if choice == 'gemini' and not has_key: - raise ConfigError('The gemini engine needs GEMINI_API_KEY in the environment or ' + raise ConfigError('The gemini engine needs GEMINI_API_KEY (or OPENROUTER_API_KEY) in the environment or ' f'{CONFIG_FILE}. Add it, or rerun with --engine local.') return 'gemini' if choice == 'gemini' or (choice == 'auto' and has_key) else 'local' @@ -140,11 +155,15 @@ def setting(name, default=''): engine = setting('WATCH_ENGINE', 'auto') if engine not in ENGINES: raise ConfigError('WATCH_ENGINE must be auto, gemini, or local.') + provider = setting('WATCH_GEMINI_PROVIDER', 'auto') + if provider not in GEMINI_PROVIDERS: + raise ConfigError('WATCH_GEMINI_PROVIDER must be auto, google, or openrouter.') return { 'detail': detail if detail in DETAILS else DEFAULT_DETAIL, 'config_file': str(CONFIG_FILE), 'whisper_backend': backend, 'engine': engine, + 'gemini_provider': provider, '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'), 'sub_lang': setting('WATCH_SUB_LANG', 'auto'), diff --git a/skills/watch/scripts/gemini.py b/skills/watch/scripts/gemini.py index 845bb549..b73c410b 100644 --- a/skills/watch/scripts/gemini.py +++ b/skills/watch/scripts/gemini.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """Gemini engine: Google watches the video (agentic processing) and answers. -Standard library only. The key travels in the x-goog-api-key header and is -scrubbed from every diagnostic. +Standard library only. The key travels in a request header (x-goog-api-key for Google, +Authorization for OpenRouter) and is scrubbed from every diagnostic. """ from __future__ import annotations @@ -19,6 +19,7 @@ API = 'https://generativelanguage.googleapis.com' INTERACTIONS = f'{API}/v1beta/interactions' +OPENROUTER = 'https://openrouter.ai/api/v1/chat/completions' _YOUTUBE = re.compile( r'^https?://(?:(?:www\.|m\.|music\.)?youtube\.com/(?:watch\?\S*\bv=|shorts/|live/)|youtu\.be/)\S+$', re.I) _HINTS = { @@ -30,6 +31,12 @@ 'response': 'Gemini returned something this version cannot read', 'upload': 'the video could not be uploaded to or processed by the Gemini Files API', } +_OPENROUTER_HINTS = { + 'auth': 'check OPENROUTER_API_KEY (create one at https://openrouter.ai/keys)', + 'quota': 'the OpenRouter key is rate-limited or out of credits; wait or add credits', + 'rejected': 'OpenRouter or Gemini refused this request; the video may be private, unsupported, or too long', + 'network': 'could not reach openrouter.ai; check network, proxy, or egress rules', +} DEFAULT_QUESTION = ('Give a thorough summary of this video: what is shown, any on-screen text or code, ' 'and what is said, in chronological order.') PROMPT_SUFFIX = ('\n\nCite an MM:SS (or H:MM:SS) timestamp for every claim about a specific moment. ' @@ -45,9 +52,10 @@ def build_prompt(question: str | None) -> str: return ((question or '').strip() or DEFAULT_QUESTION) + PROMPT_SUFFIX -def _fail(category: str, detail: str, key: str) -> SystemExit: +def _fail(category: str, detail: str, key: str, provider: str = 'google') -> SystemExit: detail = diagnostic(detail, 600).replace(key, '[redacted]') if key else diagnostic(detail, 600) - return SystemExit(f'Gemini {category}: {_HINTS[category]}. Detail: {detail or "none"}. ' + hint = (_OPENROUTER_HINTS if provider == 'openrouter' else {}).get(category, _HINTS[category]) + return SystemExit(f'Gemini {category}: {hint}. Detail: {detail or "none"}. ' 'No local fallback was attempted; rerun with --engine local to use frames + transcript.') @@ -62,19 +70,25 @@ def _error_message(body: bytes) -> str: return text -def _call(method: str, url: str, key: str, *, data=None, headers=None, timeout: float = 60.0): - request = Request(url, data=data, method=method, headers={'x-goog-api-key': key, **(headers or {})}) +def _category(code: int, message: str) -> str: + # The Files API answers a malformed key with 400 "API key not valid", not 401. + # 402 is spent prepaid credit (AI Studio prepayment, OpenRouter balance). + return ('auth' if code in (401, 403) or 'api key' in message.lower() else 'quota' if code in (402, 429) + else 'service' if code >= 500 else 'rejected') + + +def _call(method: str, url: str, key: str, *, data=None, headers=None, timeout: float = 60.0, + provider: str = 'google'): + auth = {'Authorization': f'Bearer {key}'} if provider == 'openrouter' else {'x-goog-api-key': key} + request = Request(url, data=data, method=method, headers={**auth, **(headers or {})}) try: with urlopen(request, timeout=timeout) as response: return response.status, dict(response.headers), response.read() except HTTPError as exc: message = _error_message(exc.read()) - # The Files API answers a malformed key with 400 "API key not valid", not 401. - category = ('auth' if exc.code in (401, 403) or 'api key' in message.lower() else 'quota' if exc.code == 429 - else 'service' if exc.code >= 500 else 'rejected') - raise _fail(category, f'HTTP {exc.code}: {message}', key) from None + raise _fail(_category(exc.code, message), f'HTTP {exc.code}: {message}', key, provider) from None except (URLError, TimeoutError, OSError) as exc: - raise _fail('network', f'{type(exc).__name__}: {getattr(exc, "reason", exc)}', key) from None + raise _fail('network', f'{type(exc).__name__}: {getattr(exc, "reason", exc)}', key, provider) from None def _clock(seconds: int) -> str: @@ -116,6 +130,45 @@ def ask(video: dict, question: str | None, *, model: str, key: str, clip=None, t 'total_tokens': tokens if isinstance(tokens, int) else None} +def openrouter_model(model: str) -> str: + """OpenRouter names Google's models google/; a slashed ID is used as given.""" + return model if '/' in model else f'google/{model}' + + +def ask_openrouter(url: str, question: str | None, *, model: str, key: str, clip=None, + timeout: float = 600.0) -> dict: + """YouTube URL only: OpenRouter's Google AI Studio route accepts no other video URL.""" + model, prompt, label = openrouter_model(model), build_prompt(question), 'agentic' + if clip and not (clip[0] is None and clip[1] is None): + # OpenRouter exposes no clip offsets, so the focus range can only be asked for in the prompt. + start, end = clip + span = f'{_clock(int(math.floor(start or 0)))}–{_clock(int(math.ceil(end))) if end is not None else "end"}' + prompt = f'Only consider the part of the video from {span}.\n\n{prompt}' + label = f'agentic, focus {span} requested in the prompt' + payload = {'model': model, 'messages': [{'role': 'user', 'content': [ + {'type': 'text', 'text': prompt}, + {'type': 'video_url', 'video_url': {'url': url, 'processing': 'agentic'}}]}]} + _, _, body = _call('POST', OPENROUTER, key, data=json.dumps(payload).encode('utf-8'), + headers={'Content-Type': 'application/json'}, timeout=timeout, provider='openrouter') + try: + data = json.loads(body) + if isinstance(data.get('error'), dict): # Upstream failures can arrive with HTTP 200. + message = str(data['error'].get('message')) + code = data['error'].get('code') + code = code if isinstance(code, int) else 0 + raise _fail(_category(code, message), f'{code or "error"}: {message}', key, 'openrouter') + text = data['choices'][0]['message']['content'] + usage = data.get('usage') or {} + except (ValueError, KeyError, TypeError, IndexError, AttributeError): + raise _fail('response', body[:300].decode('utf-8', errors='replace'), key, 'openrouter') from None + if not isinstance(text, str) or not text.strip(): + raise _fail('response', 'no answer text', key, 'openrouter') + tokens, cost = usage.get('total_tokens'), usage.get('cost') + return {'text': text.strip(), 'model': model, 'processing': label, + 'total_tokens': tokens if isinstance(tokens, int) else None, + 'cost': cost if isinstance(cost, (int, float)) else None} + + def upload_file(path: Path, key: str, *, poll_seconds: float = 2.0, max_wait: float = 900.0, sleep=time.sleep) -> dict: path = Path(path) size = path.stat().st_size diff --git a/skills/watch/scripts/setup.py b/skills/watch/scripts/setup.py index 8170e020..c9523271 100755 --- a/skills/watch/scripts/setup.py +++ b/skills/watch/scripts/setup.py @@ -13,7 +13,7 @@ from pathlib import Path 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) + load_api_key, load_gemini_credentials, read_env_file, resolve_engine, write_settings) from runtime import configure_stdio, diagnostic, run_text REQUIRED_BINARIES = ['ffmpeg', 'ffprobe', 'yt-dlp'] @@ -25,7 +25,10 @@ # 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. # With the gemini engine, local videos are uploaded to Google for analysis. +# OPENROUTER_API_KEY runs the gemini engine through OpenRouter: YouTube URLs only, billed by OpenRouter. +# WATCH_GEMINI_PROVIDER=auto|google|openrouter. auto prefers GEMINI_API_KEY. GEMINI_API_KEY= +OPENROUTER_API_KEY= GROQ_API_KEY= OPENAI_API_KEY= ''' @@ -145,7 +148,8 @@ def _status(detailed=False): missing = _check_binaries() _check_file_permissions(CONFIG_FILE) cfg = get_config() - gemini_key = bool(load_gemini_key()) + gemini_provider, gemini_secret = load_gemini_credentials(cfg['gemini_provider']) + gemini_key = bool(gemini_secret) try: engine = resolve_engine(cfg['engine'], gemini_key) except ConfigError: @@ -159,6 +163,7 @@ def _status(detailed=False): blocked = bool(missing) and binaries_required result = {'status': 'needs_install' if blocked else 'ready', 'can_proceed': not blocked, 'engine': engine, 'configured_engine': cfg['engine'], 'gemini_key_present': gemini_key, + 'gemini_provider': gemini_provider, 'gemini_model': cfg['gemini_model'], 'binaries_required': binaries_required, 'first_run': is_first_run(), 'setup_complete': not is_first_run(), 'missing_binaries': missing, 'whisper_backend': backend, 'configured_backend': chosen, @@ -201,14 +206,17 @@ def cmd_install(backend=None, detail=None, engine=None): _scaffold_env() write_settings({'WATCH_ENGINE': engine}, CONFIG_FILE) if engine == 'gemini': - if not load_gemini_key(): + provider, key = load_gemini_credentials(get_config()['gemini_provider']) + if not key: print(f'[setup] Add GEMINI_API_KEY privately to {CONFIG_FILE} (free key: https://aistudio.google.com/apikey), ' + 'or OPENROUTER_API_KEY for YouTube URLs only (https://openrouter.ai/keys), ' 'then rerun --engine gemini. Local videos will be uploaded to Google for analysis.', file=sys.stderr) return 3 _write_setup_complete() missing = _check_binaries() note = (f" Optional: install {', '.join(_brew_pkg(missing))} for non-YouTube URLs and --engine local." if missing else '') - print(f'[setup] Gemini engine is ready. Configuration: {CONFIG_FILE}.{note}') + via = ' via OpenRouter (YouTube URLs only)' if provider == 'openrouter' else '' + print(f'[setup] Gemini engine is ready{via}. Configuration: {CONFIG_FILE}.{note}') return 0 missing = _check_binaries() if missing: diff --git a/skills/watch/scripts/watch.py b/skills/watch/scripts/watch.py index b5b322aa..3e9d2ef0 100755 --- a/skills/watch/scripts/watch.py +++ b/skills/watch/scripts/watch.py @@ -17,7 +17,7 @@ SCRIPT_DIR = Path(__file__).parent.resolve() sys.path.insert(0, str(SCRIPT_DIR)) -from config import ConfigError, frame_cap, get_config, load_gemini_key, resolve_engine # noqa: E402 +from config import ConfigError, frame_cap, get_config, load_gemini_credentials, resolve_engine # 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 @@ -30,14 +30,27 @@ ("--timestamps", "timestamps"), ("--whisper", "whisper"), ("--sub-lang", "sub_lang")) -def run_gemini(args, config, key, start_sec, end_sec, auth) -> int: +def run_gemini(args, config, key, start_sec, end_sec, auth, provider="google") -> int: """Google watches the video. No captions, frames, or Whisper; no fallback on failure.""" + model = (f"{gemini.openrouter_model(config['gemini_model'])} via OpenRouter" if provider == "openrouter" + else config["gemini_model"]) ignored = [flag for flag, name in LOCAL_ONLY_FLAGS if getattr(args, name) is not None] ignored += [flag for flag, on in (("--no-whisper", args.no_whisper), ("--no-dedup", args.no_dedup)) if on] clip = (start_sec, end_sec) if start_sec is not None or end_sec is not None else None uploaded, warning, result, error, sent, work = None, None, None, None, "URL sent to Google", None + video: dict = {} try: - if gemini.is_youtube(args.source): + if provider == "openrouter": + if not gemini.is_youtube(args.source): + sent = "not sent" + raise SystemExit("Gemini rejected: OpenRouter accepts only YouTube URLs for Gemini. Set GEMINI_API_KEY " + "(WATCH_GEMINI_PROVIDER=google) for other sources. No local fallback was attempted; " + "rerun with --engine local to use frames + transcript.") + sent = "URL sent to OpenRouter and Google" + print(f"[watch] asking {model}…", file=sys.stderr) + result = gemini.ask_openrouter(args.source, args.question, model=config["gemini_model"], key=key, + clip=clip, timeout=config["gemini_timeout"]) + elif gemini.is_youtube(args.source): video = {"uri": args.source} else: parent = Path(args.out_dir).expanduser().resolve() if args.out_dir else None @@ -52,9 +65,10 @@ def run_gemini(args, config, key, start_sec, end_sec, auth) -> int: uploaded = gemini.upload_file(Path(media["video_path"]), key) video = {"uri": uploaded["uri"], "mime_type": uploaded["mime_type"]} sent = "video uploaded to Google, deleted after the answer" - print(f"[watch] asking {config['gemini_model']}…", file=sys.stderr) - result = gemini.ask(video, args.question, model=config["gemini_model"], key=key, - clip=clip, timeout=config["gemini_timeout"]) + if result is None: + print(f"[watch] asking {model}…", file=sys.stderr) + result = gemini.ask(video, args.question, model=config["gemini_model"], key=key, + clip=clip, timeout=config["gemini_timeout"]) except SystemExit as exc: error = str(exc) finally: @@ -67,13 +81,15 @@ def run_gemini(args, config, key, start_sec, end_sec, auth) -> int: print("# watch: video report") print() print(f"- **Source:** {args.source} ({sent})") - print(f"- **Engine:** {config['gemini_model']} ({result['processing'] if result else 'failed'})") + print(f"- **Engine:** {model} ({result['processing'] 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 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']}") + if result and result.get("cost") is not None: + print(f"- **OpenRouter cost:** ${result['cost']:.4f}") if warning: print(f"- **Cleanup warning:** {warning}") print() @@ -140,7 +156,8 @@ def main() -> int: 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, - help="gemini: Google watches the video and answers (needs GEMINI_API_KEY). " + help="gemini: Google watches the video and answers (needs GEMINI_API_KEY, or OPENROUTER_API_KEY " + "for YouTube URLs). " "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.") @@ -161,9 +178,9 @@ def main() -> int: auth_args(cookies_file, cookies_browser) # Validate even before starting network work. auth = {"cookies_file": cookies_file, "cookies_from_browser": cookies_browser} - gemini_key = load_gemini_key() + provider, gemini_key = load_gemini_credentials(config["gemini_provider"]) if resolve_engine(args.engine or config["engine"], bool(gemini_key)) == "gemini": - return run_gemini(args, config, gemini_key, start_sec, end_sec, auth) + return run_gemini(args, config, gemini_key, start_sec, end_sec, auth, provider) parent = Path(args.out_dir).expanduser().resolve() if args.out_dir else None if parent: diff --git a/tests/conftest.py b/tests/conftest.py index dcb5db70..8d87f480 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,7 +22,8 @@ def isolated_user(monkeypatch, tmp_path): cwd.mkdir() for key in list(os.environ): if key.startswith("WATCH_") or key in { - "GROQ_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY", "SETUP_COMPLETE", "XDG_CONFIG_HOME", + "GROQ_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY", "SETUP_COMPLETE", + "XDG_CONFIG_HOME", }: monkeypatch.delenv(key) monkeypatch.setenv("HOME", str(home)) diff --git a/tests/test_config.py b/tests/test_config.py index 7ec8bdef..08e7d5bd 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -117,3 +117,21 @@ def test_invalid_engine_and_timeout_rejected(monkeypatch): monkeypatch.setenv('WATCH_GEMINI_TIMEOUT', '-5') with pytest.raises(config.ConfigError, match='WATCH_GEMINI_TIMEOUT'): config.get_config() + + +def test_gemini_credentials_prefer_google_then_openrouter(monkeypatch): + assert config.load_gemini_credentials() == (None, None) + monkeypatch.setenv('OPENROUTER_API_KEY', 'or-key') + assert config.load_gemini_credentials() == ('openrouter', 'or-key') + monkeypatch.setenv('GEMINI_API_KEY', 'g-key') + assert config.load_gemini_credentials() == ('google', 'g-key') + assert config.load_gemini_credentials('openrouter') == ('openrouter', 'or-key') + monkeypatch.delenv('OPENROUTER_API_KEY') + assert config.load_gemini_credentials('openrouter') == (None, None) + + +def test_gemini_provider_setting(monkeypatch): + assert config.get_config()['gemini_provider'] == 'auto' + monkeypatch.setenv('WATCH_GEMINI_PROVIDER', 'vertex') + with pytest.raises(config.ConfigError, match='WATCH_GEMINI_PROVIDER'): + config.get_config() diff --git a/tests/test_gemini.py b/tests/test_gemini.py index 96dd89f4..430faf7a 100644 --- a/tests/test_gemini.py +++ b/tests/test_gemini.py @@ -217,3 +217,62 @@ def test_invalid_key_reported_as_http_400_is_still_auth(calls): calls.replies = [http_error(400, b'{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","status":"INVALID_ARGUMENT"}}')] with pytest.raises(SystemExit, match='^Gemini auth:'): gemini.ask({'uri': 'https://youtu.be/abc'}, None, model='m', key=KEY) + + +def openrouter_answer(text='At 00:10 it turns blue.'): + return json.dumps({'model': 'google/gemini-3.7-flash', 'choices': [{'message': {'role': 'assistant', 'content': text}}], + 'usage': {'total_tokens': 135034, 'cost': 0.1074}}).encode() + + +def test_openrouter_payload_bearer_key_and_model_prefix(calls): + calls.replies = [FakeResponse(openrouter_answer())] + result = gemini.ask_openrouter('https://youtu.be/abc', 'When does it change?', model='gemini-3.7-flash', key=KEY) + request = calls[0] + assert request.full_url == 'https://openrouter.ai/api/v1/chat/completions' + assert request.get_header('Authorization') == f'Bearer {KEY}' + assert request.get_header('X-goog-api-key') is None + payload = json.loads(request.data) + assert payload['model'] == 'google/gemini-3.7-flash' + text, video = payload['messages'][0]['content'] + assert 'When does it change?' in text['text'] and 'MM:SS' in text['text'] + assert video == {'type': 'video_url', 'video_url': {'url': 'https://youtu.be/abc', 'processing': 'agentic'}} + assert result == {'text': 'At 00:10 it turns blue.', 'model': 'google/gemini-3.7-flash', + 'processing': 'agentic', 'total_tokens': 135034, 'cost': 0.1074} + + +def test_openrouter_model_keeps_a_slashed_id(): + assert gemini.openrouter_model('gemini-3.8-flash') == 'google/gemini-3.8-flash' + assert gemini.openrouter_model('google/gemini-3.8-flash') == 'google/gemini-3.8-flash' + + +def test_openrouter_clip_is_requested_in_the_prompt(calls): + calls.replies = [FakeResponse(openrouter_answer())] + result = gemini.ask_openrouter('https://youtu.be/abc', None, model='m', key=KEY, clip=(90.0, None)) + assert json.loads(calls[0].data)['messages'][0]['content'][0]['text'].startswith( + 'Only consider the part of the video from 01:30–end.') + assert result['processing'] == 'agentic, focus 01:30–end requested in the prompt' + + +@pytest.mark.parametrize('reply,category', [ + (http_error(401, b'{"error":{"message":"No auth credentials found","code":401}}'), 'auth'), + (http_error(402, b'{"error":{"message":"Insufficient credits","code":402}}'), 'quota'), + (http_error(429, b'{"error":{"message":"Rate limited","code":429}}'), 'quota'), + (http_error(502, b'{"error":{"message":"Provider returned error","code":502}}'), 'service'), + (FakeResponse(json.dumps({'error': {'message': 'Provider returned error', 'code': 503}}).encode()), 'service'), + (FakeResponse(json.dumps({'choices': []}).encode()), 'response'), + (URLError('no route'), 'network'), +]) +def test_openrouter_failures_are_categorized_and_never_leak_the_key(calls, reply, category): + calls.replies = [reply] + with pytest.raises(SystemExit) as caught: + gemini.ask_openrouter('https://youtu.be/abc', None, model='m', key=KEY) + message = str(caught.value) + assert message.startswith(f'Gemini {category}:') and KEY not in message and '--engine local' in message + if category in ('auth', 'quota', 'network'): + assert 'openrouter' in message.lower() + + +def test_spent_google_prepayment_is_quota_not_rejected(calls): + calls.replies = [http_error(402, b'{"error":{"message":"Your prepayment credits are depleted.","code":402}}')] + with pytest.raises(SystemExit, match='^Gemini quota:'): + gemini.ask({'uri': 'https://youtu.be/abc'}, None, model='m', key=KEY) diff --git a/tests/test_setup.py b/tests/test_setup.py index c7dda2bd..07fb0e45 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -145,3 +145,13 @@ def test_engine_gemini_with_key_completes_setup_and_preserves_lines(monkeypatch) assert '# my notes' in text and 'GROQ_API_KEY=keep-me' in text values = config.read_env_file(config.CONFIG_FILE) assert values['WATCH_ENGINE'] == 'gemini' and values['SETUP_COMPLETE'] == 'true' + + +def test_engine_gemini_with_only_an_openrouter_key(monkeypatch, capsys): + monkeypatch.setattr(setup, '_check_binaries', lambda: list(setup.REQUIRED_BINARIES)) + monkeypatch.setenv('OPENROUTER_API_KEY', 'unit-key') + status = setup._status() + assert status['engine'] == 'gemini' and status['gemini_provider'] == 'openrouter' + assert status['gemini_key_present'] is True and 'unit-key' not in json.dumps(status) + assert setup.cmd_install(engine='gemini') == 0 + assert 'via OpenRouter' in capsys.readouterr().out diff --git a/tests/test_watch.py b/tests/test_watch.py index 1bc00e9d..d472b951 100644 --- a/tests/test_watch.py +++ b/tests/test_watch.py @@ -284,3 +284,34 @@ def boom(path, key, **kw): assert 'URL sent to Google' not in out and 'upload to Google failed' in out assert out_dir.is_dir() and list(out_dir.iterdir()) == [], 'the run-owned work dir must be removed' assert static_clip.is_file(), 'the user source file is never deleted' + + +def test_openrouter_key_watches_youtube_through_openrouter(monkeypatch, capsys): + import gemini + seen = {} + def fake(url, question, **kw): + seen.update(url=url, question=question, **kw) + return {'text': 'At 00:10 it turns blue.', 'model': 'google/' + kw['model'], 'processing': 'agentic', + 'total_tokens': 10, 'cost': 0.1074} + monkeypatch.setattr(gemini, 'ask_openrouter', fake) + monkeypatch.setattr(gemini, 'ask', lambda *a, **kw: pytest.fail('the Google endpoint must not be called')) + monkeypatch.setenv('OPENROUTER_API_KEY', 'unit-key') + monkeypatch.setattr(sys, 'argv', ['watch', 'https://youtu.be/abc', '--question', 'When?']) + assert watch.main() == 0 + out = capsys.readouterr().out + assert seen['url'] == 'https://youtu.be/abc' and seen['key'] == 'unit-key' and seen['model'] == 'gemini-3.7-flash' + assert '**Engine:** google/gemini-3.7-flash via OpenRouter (agentic)' in out + assert 'URL sent to OpenRouter and Google' in out and '**OpenRouter cost:** $0.1074' in out + assert 'unit-key' not in out + + +def test_openrouter_rejects_non_youtube_before_sending_anything(monkeypatch, capsys, static_clip): + import gemini + monkeypatch.setenv('OPENROUTER_API_KEY', 'unit-key') + for name in ('ask', 'ask_openrouter', 'upload_file'): + monkeypatch.setattr(gemini, name, lambda *a, **kw: pytest.fail('nothing may be sent')) + monkeypatch.setattr(watch, 'download', lambda *a, **kw: pytest.fail('must not download')) + monkeypatch.setattr(sys, 'argv', ['watch', str(static_clip)]) + assert watch.main() == 1 + out = capsys.readouterr().out + assert 'only YouTube URLs' in out and '(not sent)' in out and '## Frames' not in out