Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]"` |
Expand Down
159 changes: 157 additions & 2 deletions graphify/transcribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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/<stem><ext>, 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.

Expand Down
Loading