"""Free-tier cloud speech: transcription + synthesis through one typed surface. Why this exists --------------- The browser's own `SpeechRecognition` is free but it is also the thing people complain about: it is unavailable in Firefox, it has no vocabulary tuning (so "Dracull", "SPF", "DKIM" come back mangled), and it silently stops after ~60 s. This module adds the *free API tiers* as an opt-in second engine behind the same frontend hooks, so accuracy can improve without changing the UI. Design rules ------------ * **Keys never linger.** A key arrives per request from the UI (the same pattern `/api/chat` already uses) or falls back to an env var for headless use. It is never logged, never written to disk, never echoed in an error message. * **No dead model IDs.** Groq shut `playai-tts` down on 2025-12-31; shipping it would produce a guaranteed 400. The table below carries the replacement (Orpheus) and says so. * **Every failure is one sentence with a next step**, carrying a stable `code` the UI can branch on and a `diagnostic` id so a support thread can find the log line. No raw upstream JSON is ever shown to the user. * **Never invent success.** An empty transcript is a no-speech outcome, not an error, and is reported as `text: ""` rather than a fabricated string. Cost note: everything here is on a provider free tier, but free tiers are rate-limited, not unlimited. On Groq HTTP 429, synthesis uses the configured Deepgram key as a backup; otherwise the frontend falls back to browser voice. """ from __future__ import annotations import re import time import uuid from dataclasses import dataclass, field from typing import Any import aiohttp from .config import settings # Hard ceiling on one upload. Voice commands are seconds long; anything bigger # is a mistake (or an attack) and is rejected before it reaches a provider. MAX_AUDIO_BYTES = 12 * 1024 * 1024 # 12 MB ≈ several minutes of Opus MAX_TEXT_CHARS = 4_000 # long enough for any spoken reply, short enough to cap spend class VoiceError(RuntimeError): """A speech failure described in terms a user can act on.""" def __init__( self, message: str, *, code: str = "voice-failed", status: int = 502, diagnostic: str | None = None, ) -> None: super().__init__(message) self.message = message self.code = code self.status = status self.diagnostic = diagnostic or uuid.uuid4().hex[:12] def as_payload(self) -> dict[str, Any]: return { "error": self.message, "code": self.code, "diagnostic": self.diagnostic, } @dataclass(frozen=True) class SpeechProvider: """Everything that differs between the free-tier providers, in one place.""" id: str label: str base_url: str api_key_env: str stt_models: tuple[str, ...] tts_models: tuple[str, ...] # Transcription request encoding: "multipart" (file upload) or "json". stt_mode: str = "multipart" # Synthesis request encoding: "openai" posts {model, input, voice, # response_format} to the /audio/speech shape; "deepgram" posts {text} # to /speak with the model in the query string (Deepgram's native shape). tts_style: str = "openai" # Path appended to the base URL for synthesis; Deepgram uses /speak. tts_path: str = "audio/speech" # Auth header scheme: "bearer" (Authorization: Bearer …) or "token" # (Authorization: Token …, Deepgram's documented form). auth_scheme: str = "bearer" # Response encodings the provider accepts; the first is the default. Groq's # Orpheus endpoint answers 400 for anything but wav. tts_formats: tuple[str, ...] = ("mp3", "wav", "opus", "flac", "aac") default_voice: str = "" free_tier_note: str = "" # Extra body fields a provider requires beyond model/input. tts_extra: dict[str, Any] = field(default_factory=dict) @property def stt_url(self) -> str: return f"{self.effective_base_url.rstrip('/')}/audio/transcriptions" @property def tts_url(self) -> str: return f"{self.effective_base_url.rstrip('/')}/{self.tts_path.lstrip('/')}" @property def effective_base_url(self) -> str: """A self-hosted endpoint is configured, not compiled in. `openai-compatible` carries no default host on purpose: pointing it at the wrong server silently (say, a public one) would leak audio, so the operator must set VOICE_BASE_URL explicitly. """ if self.id == "openai-compatible": return (getattr(settings, "voice_base_url", "") or "").strip().rstrip("/") return self.base_url # ── Provider table ─────────────────────────────────────────────────────────── # Prices/limits are from the vendors' own pages (checked 2026-11); they are # documented here because "free" is what makes this feature shippable at all. PROVIDERS: dict[str, SpeechProvider] = { "groq": SpeechProvider( id="groq", label="Groq (Whisper + Orpheus)", base_url="https://api.groq.com/openai/v1", api_key_env="GROQ_API_KEY", stt_models=("whisper-large-v3-turbo", "whisper-large-v3"), # playai-tts was retired 2025-12-31 — Orpheus replaced it. tts_models=("canopylabs/orpheus-v1-english",), stt_mode="multipart", tts_formats=("wav",), # "hannah" is the app's chosen reply persona (frontend/src/stores/ # voice.ts DEFAULT_CLOUD_VOICE). Both sides must agree, or the Settings # panel advertises one voice while the chat speaks another. default_voice="hannah", free_tier_note=( "Whisper: 7,200 audio s/hour, 28,800 s/day (8 h), 2,000 requests/day, " "no card. Speech synthesis is the tighter cap (~100 requests/day), so " "speaking every reply aloud will hit it before transcription does." ), ), "mistral": SpeechProvider( id="mistral", label="Mistral (Voxtral)", base_url="https://api.mistral.ai/v1", api_key_env="MISTRAL_API_KEY", stt_models=("voxtral-mini-latest",), tts_models=("voxtral-mini-tts-latest",), stt_mode="multipart", default_voice="", free_tier_note="Studio free mode: API access with no card; the voice quota is not published.", ), "deepgram": SpeechProvider( id="deepgram", label="Deepgram (Aura-2 — speaking only)", base_url="https://api.deepgram.com/v1", api_key_env="DEEPGRAM_API_KEY", # Speaking only: Aura-2 is a synthesis engine, and Dracull keeps # transcription on Groq Whisper (free tier, already integrated). An # empty stt_models marks this provider TTS-only everywhere. stt_models=(), tts_models=("aura-2-thalia-en",), stt_mode="multipart", tts_style="deepgram", tts_path="speak", auth_scheme="token", tts_formats=("mp3",), default_voice="aura-2-thalia-en", free_tier_note=( "New accounts get $200 credit with no card — roughly 6.6M characters " "(≈20 months of Dracull's speaking volume) at Aura-2's $30/1M. " "Speaks replies only; transcription stays on Groq Whisper." ), ), "openai-compatible": SpeechProvider( id="openai-compatible", label="OpenAI-compatible (Whisper server, LocalAI, LM Studio)", base_url="", api_key_env="VOICE_API_KEY", stt_models=("whisper-1",), tts_models=("tts-1",), stt_mode="multipart", default_voice="alloy", free_tier_note="Self-hosted: no per-request cost, you pay for the machine.", ), } DEFAULT_PROVIDER = "groq" def get_provider(provider: str | None) -> SpeechProvider: """Resolve a provider id, defaulting rather than raising on nonsense.""" key = (provider or DEFAULT_PROVIDER).strip().lower() if key not in PROVIDERS: raise VoiceError( f"Unknown speech provider '{key}'. Choose one of: " + ", ".join(sorted(PROVIDERS)) + ".", code="unknown-provider", status=400, ) return PROVIDERS[key] def resolve_key(spec: SpeechProvider, api_key: str | None) -> str: """Per-request key first, then env. Never log or return this value.""" key = (api_key or "").strip() if not key: key = (getattr(settings, spec.api_key_env.lower(), None) or "").strip() if not key: raise VoiceError( f"{spec.label} needs an API key. Add it in Settings → Voice, " f"or set {spec.api_key_env} on the backend.", code="missing-key", status=503, ) if spec.id == "openai-compatible" and not spec.effective_base_url: raise VoiceError( "The OpenAI-compatible voice provider needs a Base URL " "(for example http://localhost:8080/v1).", code="missing-base-url", status=400, ) return key def describe_providers(provided_keys: dict[str, str] | None = None) -> list[dict[str, Any]]: """Capability + readiness table for the Settings UI. `configured` answers "will a request work right now?" without ever revealing the key. The UI uses it to grey out engines instead of letting someone record a sentence and then get a 503. """ provided = provided_keys or {} out: list[dict[str, Any]] = [] for spec in PROVIDERS.values(): supplied = (provided.get(spec.id) or "").strip() env_key = (getattr(settings, spec.api_key_env.lower(), None) or "").strip() out.append( { "id": spec.id, "label": spec.label, "stt_models": list(spec.stt_models), "tts_models": list(spec.tts_models), "default_voice": spec.default_voice, "free_tier_note": spec.free_tier_note, "api_key_env": spec.api_key_env, "configured": bool(supplied or env_key), "key_source": "request" if supplied else ("env" if env_key else ""), } ) return out def _auth_headers(key: str, spec: SpeechProvider | None = None) -> dict[str, str]: """Auth header in the provider's documented scheme. Deepgram's API answers `Authorization: Token `; everything else here is OpenAI-shaped and takes `Bearer`. Both keep the key out of the URL. """ if spec is not None and spec.auth_scheme == "token": return {"Authorization": f"Token {key}"} return {"Authorization": f"Bearer {key}"} _CODE_FENCE = re.compile(r"```.*?```", re.DOTALL) _INLINE_CODE = re.compile(r"`([^`]*)`") _MD_LINK = re.compile(r"\[([^\]]+)\]\([^)]*\)") _URL = re.compile(r"https?://\S+") _EMPHASIS = re.compile(r"(\*\*|__|\*|_)(?=\S)(.+?)(?<=\S)\1") _HEADING = re.compile(r"^\s{0,3}#{1,6}\s*", re.MULTILINE) _UNTRUSTED = re.compile(r"<<<[^>]*>>>") def to_speakable(text: str) -> str: """Reduce markdown to something a voice should actually say. Mirrors the frontend scrubber. It is duplicated here on purpose: this endpoint is callable by anything (curl, the extension, a future mobile client), so correctness must not depend on the caller being our UI. A synthesiser reading "asterisk asterisk" is the bug this prevents, and stripping first also means we are not billed for markup. """ out = (text or "") out = _CODE_FENCE.sub(" (code block omitted) ", out) out = _INLINE_CODE.sub(r"\1", out) out = _MD_LINK.sub(r"\1", out) out = _URL.sub("", out) out = _UNTRUSTED.sub("", out) out = _EMPHASIS.sub(r"\2", out) out = _HEADING.sub("", out) out = out.replace("|", " ").replace("---", "") return " ".join(out.split()) def _clean_text(text: str) -> str: """Bound synthesis input so a pasted document cannot become a bill.""" cleaned = to_speakable(text) if len(cleaned) > MAX_TEXT_CHARS: # Cut at a sentence boundary where possible so the audio does not stop # mid-clause, which sounds like a bug to the listener. clipped = cleaned[:MAX_TEXT_CHARS] cut = max(clipped.rfind(". "), clipped.rfind("! "), clipped.rfind("? ")) cleaned = clipped[: cut + 1] if cut > MAX_TEXT_CHARS // 2 else clipped return cleaned async def _read_error(resp: aiohttp.ClientResponse) -> str: """Upstream detail, trimmed, for logs only — never returned verbatim.""" try: body = await resp.text() except Exception: # noqa: BLE001 - diagnostics must never mask the error return "" return " ".join(body.split())[:300] def _failure(spec: SpeechProvider, resp_status: int, detail: str, *, action: str) -> VoiceError: """Map an upstream status onto one actionable sentence.""" if resp_status in (401, 403): return VoiceError( f"{spec.label} rejected the API key. Check the key in Settings → Voice.", code="bad-key", status=401, ) if resp_status == 429: return VoiceError( f"{spec.label}'s free tier is rate-limited right now. " "Try again shortly, or switch to browser voice.", code="rate-limited", status=429, ) if "model_terms_required" in detail: # Gated models (e.g. Groq Orpheus) answer 400 until the org admin has # accepted their terms once in the provider console. The fix is a # console visit, not a retry, so say exactly that instead of leaking # the raw upstream JSON. return VoiceError( f"{spec.label}'s speech model needs a one-time terms acceptance. " "Sign in at console.groq.com as the org admin, open the model in " "the playground, and accept the terms — then try again.", code="model-terms-required", status=400, ) if 400 <= resp_status < 500: return VoiceError( f"{spec.label} could not {action} (HTTP {resp_status}). {detail}", code="bad-request", status=502, ) return VoiceError( f"{spec.label} could not {action} (HTTP {resp_status}). {detail}", code="upstream-error", status=502, ) async def transcribe( audio: bytes, *, filename: str = "clip.webm", content_type: str = "audio/webm", provider: str | None = None, model: str | None = None, api_key: str | None = None, language: str | None = None, prompt: str | None = None, timeout_seconds: float = 30.0, ) -> dict[str, Any]: """Speech → text via a free-tier provider. `prompt` is a hint (Groq/Whisper vocabulary biasing) — useful for domain words the recogniser keeps missing, e.g. "Dracull, SPF, DKIM, Voxtral". """ spec = get_provider(provider) key = resolve_key(spec, api_key) # TTS-only providers (Deepgram) must fail with a sentence, not an IndexError # or a POST to a URL that does not exist. if not spec.stt_models: raise VoiceError( f"{spec.label} speaks replies but cannot transcribe. " "Choose Groq, Mistral, or the browser engine for the microphone.", code="stt-unsupported", status=400, ) model_id = (model or spec.stt_models[0]).strip() if not audio: raise VoiceError( "No audio was received. Hold the mic button while you speak.", code="empty-audio", status=400, ) if len(audio) > MAX_AUDIO_BYTES: raise VoiceError( f"That recording is larger than {MAX_AUDIO_BYTES // (1024 * 1024)} MB. " "Keep voice commands under about a minute.", code="audio-too-large", status=413, ) form = aiohttp.FormData() form.add_field("model", model_id) form.add_field( "file", audio, filename=filename or "clip.webm", content_type=content_type or "audio/webm", ) if language: form.add_field("language", language) if prompt: # Truncated: some providers reject very long prompts. form.add_field("prompt", prompt[:900]) started = time.perf_counter() url = spec.stt_url try: timeout = aiohttp.ClientTimeout(total=timeout_seconds) async with ( aiohttp.ClientSession(timeout=timeout) as session, session.post(url, data=form, headers=_auth_headers(key, spec)) as resp, ): if resp.status != 200: detail = await _read_error(resp) raise _failure(spec, resp.status, detail, action="transcribe that recording") payload = await resp.json(content_type=None) except aiohttp.ClientError as exc: raise VoiceError( f"Could not reach {spec.label} ({type(exc).__name__}). " "Check this machine's internet connection.", code="network", status=502, ) from exc except TimeoutError as exc: raise VoiceError( f"{spec.label} took too long to transcribe. Try a shorter phrase.", code="timeout", status=504, ) from exc # Shape varies by provider: OpenAI-style {text}, Mistral may use # {transcription}. A key that is simply ABSENT must raise — silently # coercing it to "" would report a provider failure as "you said nothing". text = None if isinstance(payload, dict): for field_name in ("text", "transcription"): if field_name in payload: text = payload[field_name] break if not isinstance(text, str): raise VoiceError( f"{spec.label} returned an unexpected response shape.", code="bad-payload", status=502, ) return { "text": text.strip(), "provider": spec.id, "model": model_id, "duration_ms": int((time.perf_counter() - started) * 1000), } async def synthesize( text: str, *, provider: str | None = None, model: str | None = None, voice: str | None = None, api_key: str | None = None, response_format: str = "mp3", timeout_seconds: float = 30.0, ) -> tuple[bytes, str]: """Text → speech via a free-tier provider. Returns (audio bytes, mime type).""" spec = get_provider(provider) key = resolve_key(spec, api_key) model_id = (model or spec.tts_models[0]).strip() voice_id = (voice or spec.default_voice).strip() cleaned = _clean_text(text) if not cleaned: raise VoiceError( "There is no text to speak.", code="empty-text", status=400, ) # A format the provider does not carry degrades to its default rather than # failing the request: the caller wants audio, and the mime type below # always tells it what it actually got. fmt = response_format if response_format in spec.tts_formats else spec.tts_formats[0] params: dict[str, str] = {} if spec.tts_style == "deepgram": # Deepgram's native /speak shape: the model *is* the voice and travels # in the query string; the body carries only the text. params["model"] = model_id body: dict[str, Any] = {"text": cleaned} else: body = {"model": model_id, "input": cleaned} if voice_id: body["voice"] = voice_id if spec.id in {"groq", "openai-compatible"}: body["response_format"] = fmt body.update(spec.tts_extra) url = spec.tts_url try: timeout = aiohttp.ClientTimeout(total=timeout_seconds) async with aiohttp.ClientSession(timeout=timeout) as session, session.post( url, json=body, params=params, headers=_auth_headers(key, spec) ) as resp: if resp.status != 200: detail = await _read_error(resp) error = _failure(spec, resp.status, detail, action="speak that text") # A rejected voice name is by far the most common 400 here; # say so instead of leaving the user with an HTTP number. if resp.status == 400 and "voice" in detail.lower(): error.message = ( f"{spec.label} does not recognise the voice " f"'{voice_id or spec.default_voice}'. Set a valid voice " "in Settings → Voice." ) error.code = "bad-voice" raise error audio = await resp.read() except VoiceError as exc: # Groq's Orpheus free tier is request-capped. If the backend operator # configured Deepgram, use it only for that quota response; bad keys, # invalid models, and network failures must remain visible as failures. fallback_key = (getattr(settings, "deepgram_api_key", None) or "").strip() if spec.id == "groq" and exc.code == "rate-limited" and fallback_key: return await synthesize( cleaned, provider="deepgram", api_key=fallback_key, response_format="mp3", timeout_seconds=timeout_seconds, ) raise except aiohttp.ClientError as exc: raise VoiceError( f"Could not reach {spec.label} ({type(exc).__name__}).", code="network", status=502, ) from exc except TimeoutError as exc: raise VoiceError( f"{spec.label} took too long to speak that text.", code="timeout", status=504, ) from exc if not audio: raise VoiceError( f"{spec.label} returned empty audio.", code="empty-response", status=502, ) mime = { "mp3": "audio/mpeg", "wav": "audio/wav", "opus": "audio/ogg", "flac": "audio/flac", "aac": "audio/aac", }.get(fmt, "audio/mpeg") return audio, mime