File size: 6,798 Bytes
0041cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""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}")