|
| 1 | +"""Pluggable batch transcription for S2S frameworks that emit no transcript. |
| 2 | +
|
| 3 | +Some speech-to-speech models (notably Smallest Hydra) stream audio in both |
| 4 | +directions but never put text on the wire. EVA's audit log — which nearly all |
| 5 | +accuracy/experience metrics read — still needs a per-turn transcript, so the |
| 6 | +server transcribes each completed utterance (the PCM it sent or received) with a |
| 7 | +separate batch STT call. |
| 8 | +
|
| 9 | +The provider is configurable via the ``transcription`` block inside |
| 10 | +``s2s_params``:: |
| 11 | +
|
| 12 | + "transcription": { |
| 13 | + "provider": "smallest" | "openai" | "deepgram", |
| 14 | + "model": "...", # provider-specific; sensible default per provider |
| 15 | + "api_key": "...", # falls back to the S2S api_key (smallest) / env |
| 16 | + "language": "en", # falls back to the run language |
| 17 | + "base_url": "..." # optional override |
| 18 | + } |
| 19 | +
|
| 20 | +All providers are called over a single shared async ``httpx`` client so the |
| 21 | +module has no heavy SDK import surface and is straightforward to mock in tests. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import os |
| 27 | +from typing import Any |
| 28 | + |
| 29 | +import httpx |
| 30 | + |
| 31 | +from eva.assistant.audio_bridge import pcm16_to_wav_bytes |
| 32 | +from eva.utils.logging import get_logger |
| 33 | + |
| 34 | +logger = get_logger(__name__) |
| 35 | + |
| 36 | +_SMALLEST_STT_URL = "https://api.smallest.ai/waves/v1/stt/" |
| 37 | +_OPENAI_STT_URL = "https://api.openai.com/v1/audio/transcriptions" |
| 38 | +_DEEPGRAM_STT_URL = "https://api.deepgram.com/v1/listen" |
| 39 | + |
| 40 | +# Default model per provider. Smallest Pulse-pro is English-only; for any other |
| 41 | +# language we fall back to the multilingual Pulse model. |
| 42 | +_DEFAULT_MODELS = { |
| 43 | + "smallest": "pulse-pro", |
| 44 | + "openai": "whisper-1", |
| 45 | + "deepgram": "nova-3", |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | +class BatchTranscriber: |
| 50 | + """Transcribe completed utterances via a configurable batch STT provider.""" |
| 51 | + |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + provider: str, |
| 55 | + model: str, |
| 56 | + api_key: str, |
| 57 | + language: str, |
| 58 | + base_url: str | None = None, |
| 59 | + timeout: float = 30.0, |
| 60 | + ) -> None: |
| 61 | + self.provider = provider |
| 62 | + self.model = model |
| 63 | + self.api_key = api_key |
| 64 | + self.language = language |
| 65 | + self.base_url = base_url |
| 66 | + self._client = httpx.AsyncClient(timeout=timeout) |
| 67 | + |
| 68 | + async def transcribe(self, pcm: bytes, sample_rate: int) -> str: |
| 69 | + """Transcribe raw 16-bit mono PCM. Returns "" on any failure (fail-soft). |
| 70 | +
|
| 71 | + Transcription errors must never abort a conversation — a dropped |
| 72 | + transcript degrades that turn's text metrics but the audio recording and |
| 73 | + tool calls are preserved. |
| 74 | + """ |
| 75 | + if not pcm: |
| 76 | + return "" |
| 77 | + wav = pcm16_to_wav_bytes(pcm, sample_rate) |
| 78 | + try: |
| 79 | + if self.provider == "smallest": |
| 80 | + return await self._transcribe_smallest(wav) |
| 81 | + if self.provider == "openai": |
| 82 | + return await self._transcribe_openai(wav) |
| 83 | + if self.provider == "deepgram": |
| 84 | + return await self._transcribe_deepgram(wav) |
| 85 | + logger.error(f"Unknown transcription provider: {self.provider!r}") |
| 86 | + return "" |
| 87 | + except Exception as e: # noqa: BLE001 - fail-soft by design |
| 88 | + logger.error(f"{self.provider} transcription failed: {e}", exc_info=True) |
| 89 | + return "" |
| 90 | + |
| 91 | + async def _transcribe_smallest(self, wav: bytes) -> str: |
| 92 | + url = self.base_url or _SMALLEST_STT_URL |
| 93 | + resp = await self._client.post( |
| 94 | + url, |
| 95 | + params={"model": self.model, "language": self.language}, |
| 96 | + headers={ |
| 97 | + "Authorization": f"Bearer {self.api_key}", |
| 98 | + "Content-Type": "application/octet-stream", |
| 99 | + }, |
| 100 | + content=wav, |
| 101 | + ) |
| 102 | + resp.raise_for_status() |
| 103 | + return (resp.json().get("transcription") or "").strip() |
| 104 | + |
| 105 | + async def _transcribe_openai(self, wav: bytes) -> str: |
| 106 | + url = self.base_url or _OPENAI_STT_URL |
| 107 | + resp = await self._client.post( |
| 108 | + url, |
| 109 | + headers={"Authorization": f"Bearer {self.api_key}"}, |
| 110 | + files={"file": ("audio.wav", wav, "audio/wav")}, |
| 111 | + data={"model": self.model, "language": self.language}, |
| 112 | + ) |
| 113 | + resp.raise_for_status() |
| 114 | + return (resp.json().get("text") or "").strip() |
| 115 | + |
| 116 | + async def _transcribe_deepgram(self, wav: bytes) -> str: |
| 117 | + url = self.base_url or _DEEPGRAM_STT_URL |
| 118 | + resp = await self._client.post( |
| 119 | + url, |
| 120 | + params={"model": self.model, "language": self.language, "smart_format": "true"}, |
| 121 | + headers={ |
| 122 | + "Authorization": f"Token {self.api_key}", |
| 123 | + "Content-Type": "audio/wav", |
| 124 | + }, |
| 125 | + content=wav, |
| 126 | + ) |
| 127 | + resp.raise_for_status() |
| 128 | + alternatives = resp.json()["results"]["channels"][0]["alternatives"] |
| 129 | + return (alternatives[0]["transcript"] if alternatives else "").strip() |
| 130 | + |
| 131 | + async def aclose(self) -> None: |
| 132 | + await self._client.aclose() |
| 133 | + |
| 134 | + |
| 135 | +def create_transcriber(s2s_params: dict[str, Any], language: str) -> BatchTranscriber: |
| 136 | + """Build a :class:`BatchTranscriber` from ``s2s_params['transcription']``. |
| 137 | +
|
| 138 | + Defaults to the Smallest Pulse provider keyed on the S2S ``api_key`` so an |
| 139 | + in-stack transcript works with no extra configuration. The Pulse-pro model is |
| 140 | + English-only; for any non-English run the default model falls back to the |
| 141 | + multilingual ``pulse`` model. |
| 142 | + """ |
| 143 | + cfg = dict(s2s_params.get("transcription") or {}) |
| 144 | + provider = cfg.get("provider", "smallest") |
| 145 | + lang = cfg.get("language") or language or "en" |
| 146 | + |
| 147 | + model = cfg.get("model") |
| 148 | + if not model: |
| 149 | + model = _DEFAULT_MODELS.get(provider, "") |
| 150 | + # Smallest Pulse-pro is English-only; use multilingual Pulse otherwise. |
| 151 | + if provider == "smallest" and not lang.startswith("en"): |
| 152 | + model = "pulse" |
| 153 | + |
| 154 | + # API key resolution: explicit transcription key, else a sensible fallback — |
| 155 | + # the shared S2S key for Smallest, or the provider's standard env var. |
| 156 | + api_key = cfg.get("api_key") |
| 157 | + if not api_key: |
| 158 | + if provider == "smallest": |
| 159 | + api_key = s2s_params.get("api_key", "") |
| 160 | + elif provider == "openai": |
| 161 | + api_key = os.environ.get("OPENAI_API_KEY", "") |
| 162 | + elif provider == "deepgram": |
| 163 | + api_key = os.environ.get("DEEPGRAM_API_KEY", "") |
| 164 | + if not api_key: |
| 165 | + raise ValueError( |
| 166 | + f"No API key for transcription provider {provider!r}. " |
| 167 | + f"Set s2s_params.transcription.api_key (or s2s_params.api_key for 'smallest', " |
| 168 | + f"OPENAI_API_KEY for 'openai', DEEPGRAM_API_KEY for 'deepgram')." |
| 169 | + ) |
| 170 | + |
| 171 | + logger.info(f"S2S transcription: provider={provider} model={model} language={lang}") |
| 172 | + return BatchTranscriber( |
| 173 | + provider=provider, |
| 174 | + model=model, |
| 175 | + api_key=api_key, |
| 176 | + language=lang, |
| 177 | + base_url=cfg.get("base_url"), |
| 178 | + ) |
0 commit comments