diff --git a/README.md b/README.md index 3e60b8e6c8..3050611d2f 100644 --- a/README.md +++ b/README.md @@ -302,7 +302,7 @@ Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native P | `pdf` | PDF extraction | `uv tool install "graphifyy[pdf]"` | | `office` | `.docx` and `.xlsx` support | `uv tool install "graphifyy[office]"` | | `google` | Google Sheets rendering | `uv tool install "graphifyy[google]"` | -| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` | +| `video` | Video/audio transcription (faster-whisper + yt-dlp; set `HUNTAPI_API_KEY` to download URLs through [HuntAPI](https://huntapi.com) where YouTube blocks yt-dlp) | `uv tool install "graphifyy[video]"` | | `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` | | `watch` | Auto-rebuild on file changes (`graphify watch`) | `uv tool install "graphifyy[watch]"` | | `neo4j` | Neo4j push support | `uv tool install "graphifyy[neo4j]"` | diff --git a/graphify/transcribe.py b/graphify/transcribe.py index 8e45bcaa2f..635b9106d6 100644 --- a/graphify/transcribe.py +++ b/graphify/transcribe.py @@ -2,7 +2,13 @@ # Converts video/audio files to text transcripts for graph extraction from __future__ import annotations +import json +import math import os +import time +import urllib.error +import urllib.parse +import urllib.request from pathlib import Path from graphify.paths import out_path as _out_path @@ -51,11 +57,12 @@ def download_audio(url: str, output_dir: Path) -> Path: """Download audio-only stream from a URL using yt-dlp. Returns the path to the downloaded audio file (.m4a or .opus). - Uses cached file if already downloaded. + Uses cached file if already downloaded. When HUNTAPI_API_KEY is set, the + download goes through HuntAPI instead of yt-dlp (see + _download_audio_huntapi), which works where YouTube blocks yt-dlp. """ from graphify.security import validate_url validate_url(url) # blocks private IPs, bad schemes before yt-dlp runs - yt_dlp = _get_yt_dlp() output_dir.mkdir(parents=True, exist_ok=True) # yt-dlp uses %(title)s which can be long/weird — use a stable name based on URL hash @@ -70,6 +77,11 @@ def download_audio(url: str, output_dir: Path) -> Path: print(f" cached audio: {candidate.name}") return candidate + huntapi_key = _huntapi_key() + if huntapi_key: + return _download_audio_huntapi(url, output_dir, f"yt_{url_hash}", huntapi_key) + + yt_dlp = _get_yt_dlp() ydl_opts = { 'format': 'bestaudio[ext=m4a]/bestaudio/best', 'outtmpl': out_template, @@ -92,6 +104,149 @@ def download_audio(url: str, output_dir: Path) -> Path: return downloaded +# --------------------------------------------------------------------------- +# Optional HuntAPI download backend +# --------------------------------------------------------------------------- +# yt-dlp is walled by YouTube's "Sign in to confirm you're not a bot" check on +# datacenter and VPS IPs (#3049). When HUNTAPI_API_KEY is set, download_audio() +# asks HuntAPI (https://huntapi.com) to fetch the audio instead and downloads +# the resulting file. Opt-in only: without the key nothing changes, and no new +# dependency is needed (stdlib urllib through graphify's SSRF-guarded opener). + +_HUNTAPI_BASE = "https://api.huntapi.com" +_HUNTAPI_TERMINAL = {"CompletedJob", "Error", "NotFound", "BadRequest"} +_HUNTAPI_AUDIO_EXTS = ('.mp3', '.m4a', '.opus', '.ogg', '.wav', '.webm') +_HUNTAPI_MAX_BYTES = 524_288_000 # 500 MB cap for the downloaded audio file +_HUNTAPI_DEFAULT_TIMEOUT = 900 # seconds to wait for the download job +_HUNTAPI_POLL_START = 3.0 +_HUNTAPI_POLL_MAX = 30.0 + + +def _huntapi_key() -> str: + return os.environ.get("HUNTAPI_API_KEY", "").strip() + + +def _huntapi_timeout() -> float: + raw = os.environ.get("GRAPHIFY_HUNTAPI_TIMEOUT", "").strip() + if not raw: + return float(_HUNTAPI_DEFAULT_TIMEOUT) + try: + value = float(raw) + except ValueError as exc: + raise ValueError(f"GRAPHIFY_HUNTAPI_TIMEOUT must be a number of seconds, got {raw!r}") from exc + if not math.isfinite(value) or value <= 0: + raise ValueError(f"GRAPHIFY_HUNTAPI_TIMEOUT must be a positive, finite number of seconds, got {raw!r}") + return value + + +def _huntapi_error_detail(exc: urllib.error.HTTPError) -> str: + """Return the API's error message from an HTTP error body, if any.""" + try: + body = exc.read(65_536) + message = json.loads(body).get("error") + except Exception: + return "" + return f": {message}" if isinstance(message, str) and message else "" + + +def _huntapi_request(method: str, path: str, key: str, body: dict | None = None) -> dict: + """Call the HuntAPI JSON API. The key travels in the x-api-key header only.""" + from graphify.security import _build_opener + + data = json.dumps(body).encode("utf-8") if body is not None else None + headers = {"x-api-key": key, "Accept": "application/json", "User-Agent": "graphify"} + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(_HUNTAPI_BASE + path, data=data, method=method, headers=headers) + try: + with _build_opener().open(req, timeout=30) as resp: + raw = resp.read(1_048_576) + except urllib.error.HTTPError as exc: + hint = " (check HUNTAPI_API_KEY)" if exc.code == 401 else "" + hint = " (insufficient HuntAPI credits)" if exc.code == 402 else hint + raise RuntimeError( + f"HuntAPI {method} {path} failed: HTTP {exc.code}{_huntapi_error_detail(exc)}{hint}" + ) from None + try: + payload = json.loads(raw or b"{}") + except ValueError as exc: + raise RuntimeError(f"HuntAPI {method} {path} returned invalid JSON") from exc + if not isinstance(payload, dict): + raise RuntimeError(f"HuntAPI {method} {path} returned an unexpected payload") + return payload + + +def _huntapi_wait(job_id: str, key: str) -> dict: + """Poll a HuntAPI job until it reaches a terminal status or the timeout passes.""" + deadline = time.monotonic() + _huntapi_timeout() + interval = _HUNTAPI_POLL_START + last_status = None + while True: + job = _huntapi_request("GET", f"/v1/jobs/{urllib.parse.quote(job_id, safe='')}", key) + status = job.get("status") + if status in _HUNTAPI_TERMINAL: + return job + if status != last_status: + print(f" HuntAPI job {job_id}: {status or 'Queued'}", flush=True) + last_status = status + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RuntimeError( + f"HuntAPI job {job_id} still {status or 'pending'} after " + f"{_huntapi_timeout():.0f}s (raise GRAPHIFY_HUNTAPI_TIMEOUT to wait longer)" + ) + time.sleep(min(interval, remaining)) + interval = min(interval * 1.5, _HUNTAPI_POLL_MAX) + + +def _huntapi_save(file_url: str, output_dir: Path, stem: str) -> Path: + """Stream the finished audio file to output_dir/, size-capped.""" + from graphify.security import _build_opener, validate_url + + validate_url(file_url) + ext = Path(urllib.parse.urlparse(file_url).path).suffix.lower() + if ext not in _HUNTAPI_AUDIO_EXTS: + ext = ".mp3" + dest = output_dir / f"{stem}{ext}" + part = output_dir / f"{stem}{ext}.part" + req = urllib.request.Request(file_url, headers={"User-Agent": "graphify"}) + total = 0 + try: + with _build_opener().open(req, timeout=60) as resp, open(part, "wb") as fh: + while True: + chunk = resp.read(65_536) + if not chunk: + break + total += len(chunk) + if total > _HUNTAPI_MAX_BYTES: + raise OSError( + f"HuntAPI audio file exceeds the {_HUNTAPI_MAX_BYTES // 1_048_576} MB limit" + ) + fh.write(chunk) + os.replace(part, dest) + except BaseException: + part.unlink(missing_ok=True) + raise + return dest + + +def _download_audio_huntapi(url: str, output_dir: Path, stem: str, key: str) -> Path: + """Download the audio of *url* through HuntAPI and return the saved file.""" + print(f" downloading audio via HuntAPI: {url[:80]} ...", flush=True) + submitted = _huntapi_request("POST", "/v1/audio/download", key, {"query": url}) + job_id = submitted.get("job_id") + if not isinstance(job_id, str) or not job_id: + raise RuntimeError("HuntAPI did not return a job_id for the audio download") + job = _huntapi_wait(job_id, key) + raw_result = job.get("result") + result: dict = raw_result if isinstance(raw_result, dict) else {} + file_url = result.get("response") + if job.get("status") != "CompletedJob" or job.get("success") is False or not isinstance(file_url, str) or not file_url: + reason = job.get("error") or result.get("error") or job.get("status") or "no file returned" + raise RuntimeError(f"HuntAPI could not download {url!r}: {reason}") + return _huntapi_save(file_url, output_dir, stem) + + def build_whisper_prompt(god_nodes: list[dict]) -> str: """Build a domain hint for Whisper from god nodes extracted from the corpus. diff --git a/tests/test_transcribe_huntapi.py b/tests/test_transcribe_huntapi.py new file mode 100644 index 0000000000..49e242d252 --- /dev/null +++ b/tests/test_transcribe_huntapi.py @@ -0,0 +1,219 @@ +"""Tests for the opt-in HuntAPI download backend in graphify.transcribe (#3049). + +No test touches the network: the SSRF-guarded opener is replaced by a fake +that answers the HuntAPI endpoints, and validate_url is stubbed for the +public hostnames used here. +""" +from __future__ import annotations + +import io +import json +import urllib.error +from email.message import Message +from pathlib import Path + +import pytest + +import graphify.security as security +import graphify.transcribe as transcribe + +VIDEO_URL = "https://www.youtube.com/watch?v=Z5YP8kznWZs" +FILE_URL = "https://s3.huntapi.com/audios/abc.m4a" + + +class _Resp(io.BytesIO): + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + + +class FakeHuntAPI: + """Stands in for graphify.security._build_opener().""" + + def __init__(self, statuses, final=None, file_bytes=b"fake audio bytes", submit_error=None): + self.statuses = list(statuses) + self.final = final or { + "status": "CompletedJob", + "success": True, + "result": {"response": FILE_URL}, + } + self.file_bytes = file_bytes + self.submit_error = submit_error + self.requests = [] + + def __call__(self): + return self + + def open(self, req, timeout=None): + self.requests.append(req) + url = req.full_url + if url == "https://api.huntapi.com/v1/audio/download": + if self.submit_error is not None: + code, body = self.submit_error + raise urllib.error.HTTPError(url, code, f"HTTP {code}", Message(), io.BytesIO(body)) + return _Resp(json.dumps({"job_id": "job-1"}).encode()) + if url == "https://api.huntapi.com/v1/jobs/job-1": + if self.statuses: + return _Resp(json.dumps({"id": "job-1", "status": self.statuses.pop(0)}).encode()) + return _Resp(json.dumps({"id": "job-1", **self.final}).encode()) + if url == FILE_URL: + return _Resp(self.file_bytes) + raise AssertionError(f"unexpected request to {url}") + + +@pytest.fixture(autouse=True) +def _isolate(monkeypatch): + monkeypatch.delenv("HUNTAPI_API_KEY", raising=False) + monkeypatch.delenv("GRAPHIFY_HUNTAPI_TIMEOUT", raising=False) + monkeypatch.setattr(security, "validate_url", lambda url: url) + monkeypatch.setattr(transcribe.time, "sleep", lambda s: None) + + +def _no_yt_dlp(): + raise AssertionError("yt-dlp must not run when HUNTAPI_API_KEY is set") + + +def test_huntapi_downloads_when_key_is_set(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + fake = FakeHuntAPI(["Queued", "Running"]) + monkeypatch.setattr(security, "_build_opener", fake) + monkeypatch.setattr(transcribe, "_get_yt_dlp", _no_yt_dlp) + + out = transcribe.download_audio(VIDEO_URL, tmp_path) + + assert out.parent == tmp_path + assert out.name.startswith("yt_") and out.suffix == ".m4a" + assert out.read_bytes() == b"fake audio bytes" + assert not list(tmp_path.glob("*.part")) + submit = fake.requests[0] + assert submit.get_method() == "POST" + assert json.loads(submit.data) == {"query": VIDEO_URL} + assert submit.get_header("X-api-key") == "test-key-not-real" + # The key goes to the API host only, never to the file host. + assert fake.requests[-1].full_url == FILE_URL + assert fake.requests[-1].get_header("X-api-key") is None + + +def test_second_call_uses_cached_file(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + fake = FakeHuntAPI([]) + monkeypatch.setattr(security, "_build_opener", fake) + + first = transcribe.download_audio(VIDEO_URL, tmp_path) + calls = len(fake.requests) + second = transcribe.download_audio(VIDEO_URL, tmp_path) + + assert second == first + assert len(fake.requests) == calls + + +def test_without_key_yt_dlp_is_used(tmp_path, monkeypatch): + def boom(): + raise AssertionError("HuntAPI must not be called without HUNTAPI_API_KEY") + + monkeypatch.setattr(security, "_build_opener", boom) + + class FakeYDL: + def __init__(self, opts): + self.template = opts["outtmpl"] + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def extract_info(self, url, download): + Path(self.template.replace("%(ext)s", "m4a")).write_bytes(b"yt") + return {"ext": "m4a"} + + class FakeYtDlp: + YoutubeDL = FakeYDL + + monkeypatch.setattr(transcribe, "_get_yt_dlp", lambda: FakeYtDlp) + + out = transcribe.download_audio(VIDEO_URL, tmp_path) + assert out.read_bytes() == b"yt" + + +def test_failed_job_raises_with_reason(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + fake = FakeHuntAPI([], final={"status": "Error", "success": False, "error": "private video"}) + monkeypatch.setattr(security, "_build_opener", fake) + + with pytest.raises(RuntimeError, match="private video"): + transcribe.download_audio(VIDEO_URL, tmp_path) + assert not list(tmp_path.iterdir()) + + +def test_completed_job_without_file_raises(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + fake = FakeHuntAPI([], final={"status": "CompletedJob", "success": True, "result": {}}) + monkeypatch.setattr(security, "_build_opener", fake) + + with pytest.raises(RuntimeError, match="could not download"): + transcribe.download_audio(VIDEO_URL, tmp_path) + + +def test_unauthorized_key_is_reported_without_leaking(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + fake = FakeHuntAPI([], submit_error=(401, b'{"error": "Invalid API key"}')) + monkeypatch.setattr(security, "_build_opener", fake) + + with pytest.raises(RuntimeError) as exc_info: + transcribe.download_audio(VIDEO_URL, tmp_path) + message = str(exc_info.value) + assert "HTTP 401" in message and "Invalid API key" in message and "HUNTAPI_API_KEY" in message + assert "test-key-not-real" not in message + + +def test_job_timeout(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + monkeypatch.setenv("GRAPHIFY_HUNTAPI_TIMEOUT", "10") + fake = FakeHuntAPI(["Running"] * 100) + monkeypatch.setattr(security, "_build_opener", fake) + clock = iter(range(0, 1000, 4)) + monkeypatch.setattr(transcribe.time, "monotonic", lambda: next(clock)) + + with pytest.raises(RuntimeError, match="GRAPHIFY_HUNTAPI_TIMEOUT"): + transcribe.download_audio(VIDEO_URL, tmp_path) + + +@pytest.mark.parametrize("value", ["soon", "0", "-5", "nan", "inf", "-inf"]) +def test_invalid_timeout_env(monkeypatch, value): + monkeypatch.setenv("GRAPHIFY_HUNTAPI_TIMEOUT", value) + with pytest.raises(ValueError, match="GRAPHIFY_HUNTAPI_TIMEOUT"): + transcribe._huntapi_timeout() + + +def test_oversized_file_is_not_kept(tmp_path, monkeypatch): + monkeypatch.setenv("HUNTAPI_API_KEY", "test-key-not-real") + monkeypatch.setattr(transcribe, "_HUNTAPI_MAX_BYTES", 8) + fake = FakeHuntAPI([], file_bytes=b"x" * 64) + monkeypatch.setattr(security, "_build_opener", fake) + + with pytest.raises(OSError, match="limit"): + transcribe.download_audio(VIDEO_URL, tmp_path) + assert not list(tmp_path.iterdir()) + + +def test_unknown_file_extension_defaults_to_mp3(tmp_path, monkeypatch): + monkeypatch.setattr(security, "_build_opener", lambda: _OneFile()) + out = transcribe._huntapi_save("https://s3.huntapi.com/audios/abc", tmp_path, "yt_x") + assert out.name == "yt_x.mp3" + + +def test_file_url_on_private_host_is_blocked(tmp_path, monkeypatch): + monkeypatch.undo() # real validate_url; literal IPs need no DNS + with pytest.raises(ValueError, match="Blocked"): + transcribe._huntapi_save("http://127.0.0.1/a.mp3", tmp_path, "yt_x") + + +class _OneFile: + def open(self, req, timeout=None): + return _Resp(b"audio")