modulate's picture
squash: clean history after accidental venv upload
0041cfd
Raw
History Blame Contribute Delete
6.8 kB
"""STT provider adapters.
Every adapter takes WAV bytes and returns a transcript string. Add a vendor by
writing one function and registering it in PROVIDERS -- or skip that entirely
and use --provider http with --endpoint / --response-path.
API keys are read from an environment variable, never from argv, so they do not
end up in shell history or in the run manifest.
"""
from __future__ import annotations
import json
import os
import time
from typing import Any, Callable
import requests
DEFAULT_TIMEOUT = 120
class ProviderError(RuntimeError):
pass
def _dig(payload: Any, path: str) -> str:
"""Pull a transcript out of a JSON body with a dotted path.
Supports list indices: results.channels.0.alternatives.0.transcript
"""
node = payload
for part in path.split("."):
if part == "":
continue
if isinstance(node, list):
try:
node = node[int(part)]
except (ValueError, IndexError) as exc:
raise ProviderError(f"bad response path '{path}' at '{part}': {exc}")
elif isinstance(node, dict):
if part not in node:
raise ProviderError(
f"bad response path '{path}': key '{part}' missing. "
f"Available: {list(node)[:12]}"
)
node = node[part]
else:
raise ProviderError(f"bad response path '{path}': cannot descend into {type(node)}")
if node is None:
return ""
return str(node)
def _key(cfg: dict) -> str:
env = cfg["api_key_env"]
value = os.environ.get(env, "")
if not value:
raise ProviderError(f"environment variable {env} is empty -- export your API key first")
return value
# ---------------------------------------------------------------- vendors --
def deepgram(audio: bytes, cfg: dict) -> str:
params = {"model": cfg["opts"].get("model", "nova-3")}
for k, v in cfg["opts"].items():
if k != "model":
params[k] = v
resp = requests.post(
cfg["opts"].get("endpoint", "https://api.deepgram.com/v1/listen"),
params=params,
headers={"Authorization": f"Token {_key(cfg)}", "Content-Type": "audio/wav"},
data=audio,
timeout=cfg["timeout"],
)
_raise(resp)
return _dig(resp.json(), "results.channels.0.alternatives.0.transcript")
def openai(audio: bytes, cfg: dict) -> str:
data = {"model": cfg["opts"].get("model", "gpt-4o-transcribe"), "response_format": "json"}
if "language" in cfg["opts"]:
data["language"] = cfg["opts"]["language"]
resp = requests.post(
cfg["opts"].get("endpoint", "https://api.openai.com/v1/audio/transcriptions"),
headers={"Authorization": f"Bearer {_key(cfg)}"},
files={"file": ("clip.wav", audio, "audio/wav")},
data=data,
timeout=cfg["timeout"],
)
_raise(resp)
return _dig(resp.json(), "text")
def elevenlabs(audio: bytes, cfg: dict) -> str:
resp = requests.post(
cfg["opts"].get("endpoint", "https://api.elevenlabs.io/v1/speech-to-text"),
headers={"xi-api-key": _key(cfg)},
files={"file": ("clip.wav", audio, "audio/wav")},
data={"model_id": cfg["opts"].get("model", "scribe_v1")},
timeout=cfg["timeout"],
)
_raise(resp)
return _dig(resp.json(), "text")
def http(audio: bytes, cfg: dict) -> str:
"""Generic adapter for any endpoint that takes audio and returns JSON.
--send body raw bytes in the request body (default)
--send multipart multipart/form-data under --field-name
"""
endpoint = cfg["opts"].get("endpoint") or cfg.get("endpoint")
if not endpoint:
raise ProviderError("--provider http requires --endpoint")
headers: dict[str, str] = {}
if cfg.get("api_key_env") and os.environ.get(cfg["api_key_env"]):
template = cfg["opts"].get("auth_header", "Authorization: Bearer {key}")
name, _, value = template.partition(":")
headers[name.strip()] = value.strip().format(key=_key(cfg))
for raw in cfg["opts"].get("header", []) if isinstance(cfg["opts"].get("header"), list) else []:
name, _, value = raw.partition(":")
headers[name.strip()] = value.strip()
if cfg["opts"].get("send", "body") == "multipart":
resp = requests.post(
endpoint,
headers=headers,
files={cfg["opts"].get("field_name", "file"): ("clip.wav", audio, "audio/wav")},
timeout=cfg["timeout"],
)
else:
headers.setdefault("Content-Type", cfg["opts"].get("content_type", "audio/wav"))
resp = requests.post(endpoint, headers=headers, data=audio, timeout=cfg["timeout"])
_raise(resp)
body = resp.text.strip()
path = cfg["opts"].get("response_path", "text")
if path in ("", "-", "raw"):
return body
try:
return _dig(json.loads(body), path)
except json.JSONDecodeError:
raise ProviderError(f"response was not JSON (first 200 chars): {body[:200]}")
def mock(audio: bytes, cfg: dict) -> str:
"""Offline provider for testing the harness itself. Reads transcripts from a
JSON file mapping clip id -> transcript, supplied as --provider-opt file=...
Selected per clip by run_benchmark via cfg['clip_id']."""
path = cfg["opts"].get("file")
if not path:
raise ProviderError("--provider mock requires --provider-opt file=<hyps.json>")
with open(path) as fh:
table = json.load(fh)
return table.get(cfg.get("clip_id", ""), "")
PROVIDERS: dict[str, Callable[[bytes, dict], str]] = {
"deepgram": deepgram,
"openai": openai,
"elevenlabs": elevenlabs,
"http": http,
"mock": mock,
}
def _raise(resp: "requests.Response") -> None:
if resp.status_code >= 400:
raise ProviderError(f"HTTP {resp.status_code}: {resp.text[:300]}")
def transcribe(audio: bytes, cfg: dict, retries: int = 3, backoff: float = 2.0) -> str:
fn = PROVIDERS.get(cfg["provider"])
if fn is None:
raise ProviderError(f"unknown provider '{cfg['provider']}'. Known: {list(PROVIDERS)}")
last: Exception | None = None
for attempt in range(retries):
try:
return fn(audio, cfg)
except ProviderError as exc:
message = str(exc)
# Auth and request-shape errors will not fix themselves.
if any(code in message for code in ("HTTP 401", "HTTP 403", "HTTP 400")) or "environment variable" in message:
raise
last = exc
except requests.RequestException as exc:
last = exc
if attempt < retries - 1:
time.sleep(backoff * (2**attempt))
raise ProviderError(f"failed after {retries} attempts: {last}")