from __future__ import annotations import asyncio import dataclasses import difflib import json import logging import re from collections.abc import Sequence import numpy as np from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt, wait_exponential from portal.globals import get_http_client from portal.transcription.providers.base import ( BoothTranscriptionState, ProviderConfig, TranscriptionProvider, is_retryable_transcription_error, load_glossary_terms, pcm_to_wav, ) from portal.translations.vocabulary import MAX_KEYTERMS, fit_speech_terms logger = logging.getLogger(__name__) # Allow delayed finals after audio EOF without retaining a session indefinitely. FINAL_TRANSCRIPT_TIMEOUT_SECONDS = 3.0 # OpenAI gives whisper-1 prompts a 224-token limit and doesn't say what happens past it (other # Whisper servers refuse the whole request). Each Whisper token is at least one byte, so a prompt # of at most 224 UTF-8 bytes fits in any script without a tokenizer. MAX_PROMPT_BYTES = 224 PROMPT_PREFIX = "Glossary: " # What the terms may use once the prefix and the closing "." are in. PROMPT_TERM_BUDGET = MAX_PROMPT_BYTES - len(PROMPT_PREFIX) - len(".") # With a prompt, Whisper answers a chunk with no sound with a stock line ("Thank you for # watching!") that would become a caption, so such a chunk is not sent. A 100 ms frame above # this level (about -55 dBFS) counts as sound. It is kept this low so a quiet microphone still # gets captions: at the realtime path's 500, speech at -42 dBFS was dropped entirely. Room noise # and hum above it are sent, and the plain answer decides what was said in them. SILENCE_RMS = 60.0 # The prompt is only meant to fix spellings, but Whisper reads it as words already said. On real # speech cut into 3 s chunks it finishes sentences nobody finished ("... 1.3 million, we're going to # be able to do that."), drops speech ("The" for "about VoxBento, MediaMTX and Jitsi") and copies the # glossary in. So each spoken chunk is also sent without the prompt, and the caption is the plain # text with only the glossary terms taken from the prompted one: a term replaces the plain words it # lines up with when their letters are this alike, and they are at most this many words longer. # Measured on a real earnings call, a far-field meeting recording, a talk read in a room and # synthetic speech in four languages, this had fewer word errors than no prompt on every one. MIN_TERM_LIKENESS = 0.6 MAX_EXTRA_WORDS = 2 # A chunk waits for the slower of its two answers, and the 3 s chunks queue up behind it: on a slow # Whisper host the worker started dropping audio. So the prompted answer gets this long after the # plain one, and the plain text is the caption without it. PROMPTED_GRACE_SECONDS = 1.0 # Latin words, runs of other scripts and numbers, so a term inside non-Latin text is still its own word. _TOKEN = re.compile(r"[A-Za-z]+|[^\W\d_A-Za-z]+|\d+") def prompt_term_cost(term: str) -> int: # The term's bytes and the ", " before it; the first term has none, so this never undercounts. return len(term.encode()) + 2 def prompt_terms(terms: Sequence[str]) -> list[str]: """The terms that fit in Whisper's prompt, most important first.""" # Whisper has no limit on the number of terms; the byte budget ends the list long before 100. return fit_speech_terms(terms, max_terms=MAX_KEYTERMS, budget=PROMPT_TERM_BUDGET, cost=prompt_term_cost) def glossary_prompt(terms: Sequence[str]) -> str | None: """The terms as Whisper's prompt, in the form the live demo uses; None without terms.""" kept = prompt_terms(terms) return f"{PROMPT_PREFIX}{', '.join(kept)}." if kept else None def has_speech(pcm: bytes, sample_rate: int) -> bool: """Whether any 100 ms of this 16-bit PCM is louder than silence.""" samples = np.frombuffer(pcm[: len(pcm) // 2 * 2], dtype=np.int16).astype(np.float32) if not samples.size: return False frames = np.array_split(samples, max(1, samples.size // (sample_rate // 10))) return max(float(np.sqrt(np.mean(frame * frame))) for frame in frames) >= SILENCE_RMS def _letters(text: str) -> str: return re.sub(r"[\W_]+", "", text.casefold()) def _words(text: str) -> list[re.Match[str]]: return [m for m in _TOKEN.finditer(text) if _letters(m.group())] def with_glossary_terms(prompted: str, plain: str, terms: Sequence[str]) -> str: """The plain text, with each glossary term of the prompted text in place of the plain words that stand for it.""" wanted = {_letters(term) for term in terms} - {""} # Words only: punctuation would line up by itself and pull the words out of place. p, q = _words(prompted), _words(plain) if not wanted or not q: return plain.strip() pk, qk = [_letters(m.group()) for m in p], [_letters(m.group()) for m in q] longest = max(len(_words(term)) for term in terms) # The plain tokens each prompted token lines up with. lines_up = [(0, 0)] * len(p) for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, qk, pk, autojunk=False).get_opcodes(): for j in range(j1, j2): lines_up[j] = (i1 + j - j1, i1 + j - j1 + 1) if tag == "equal" else (i1, i2) swaps = [] j = 0 while j < len(p): size = next( (n for n in range(min(longest, len(p) - j), 0, -1) if "".join(pk[j : j + n]) in wanted), 0, ) if not size: j += 1 continue term_key = "".join(pk[j : j + size]) most_words = size + MAX_EXTRA_WORDS lo, hi = lines_up[j][0], lines_up[j + size - 1][1] # The run of plain words that looks most like the term. best = max( ( (difflib.SequenceMatcher(None, "".join(qk[a:b]), term_key).ratio(), a, b) for a in range(lo, hi) for b in range(a + 1, hi + 1) if b - a <= most_words ), default=None, ) text = prompted[p[j].start() : p[j + size - 1].end()] if best and best[0] >= MIN_TERM_LIKENESS and plain[q[best[1]].start() : q[best[2] - 1].end()] != text: swaps.append((best[1], best[2], text)) j += size out, at = [], 0 for a, b, text in sorted(swaps): if a < at: continue out += [plain[q[at - 1].end() if at else 0 : q[a].start()], text] at = b out.append(plain[q[at - 1].end() if at else 0 :]) return "".join(out).strip() async def load_prompt_terms(config: ProviderConfig, room_id: int | None) -> list[str]: """The prompt's terms from the config (the live demo) or else the room's glossary.""" return prompt_terms( config.keyterms or await load_glossary_terms(room_id, max_terms=MAX_KEYTERMS, budget=PROMPT_TERM_BUDGET, cost=prompt_term_cost) ) class OpenAIProvider(TranscriptionProvider): # The realtime API takes 24 kHz PCM sample_rate = 24000 async def process_chunk( self, chunk: bytes, language_code: str, model_variant: str, config: ProviderConfig, booth_state: BoothTranscriptionState | None = None, ) -> str: api_key = config.get_key() if not api_key: logger.error("OpenAI API key missing") return "" if config.prompt and not has_speech(chunk, self.sample_rate): return "" files = {"file": ("audio.wav", pcm_to_wav(chunk, sample_rate=self.sample_rate), "audio/wav")} data = {"model": model_variant, "language": language_code} if not config.prompt: return await self._transcribe(api_key, files, data) prompted_call = asyncio.ensure_future( self._transcribe_or_error(api_key, files, {**data, "prompt": config.prompt}) ) plain_call = asyncio.ensure_future(self._transcribe_or_error(api_key, files, data)) try: plain = await plain_call if isinstance(plain, Exception): prompted = await prompted_call else: try: prompted = await asyncio.wait_for(prompted_call, PROMPTED_GRACE_SECONDS) except TimeoutError: logger.debug("OpenAI text with the glossary prompt is late; using the plain text") return plain finally: for call in (prompted_call, plain_call): call.cancel() await asyncio.gather(prompted_call, plain_call, return_exceptions=True) if isinstance(prompted, Exception): if isinstance(plain, Exception): raise prompted return plain if isinstance(plain, Exception): return prompted return with_glossary_terms(prompted, plain, config.keyterms) async def _transcribe_or_error(self, api_key: str, files: dict, data: dict) -> str | Exception: # One failed request must not lose the other's caption; cancellation still stops both. try: return await self._transcribe(api_key, files, data) except Exception as e: return e async def _transcribe(self, api_key: str, files: dict, data: dict) -> str: headers = {"Authorization": f"Bearer {api_key}"} client = get_http_client() try: async for attempt in AsyncRetrying( wait=wait_exponential(multiplier=1, min=2, max=10), stop=stop_after_attempt(3), retry=retry_if_exception(is_retryable_transcription_error), ): with attempt: resp = await client.post( "https://api.openai.com/v1/audio/transcriptions", headers=headers, files=files, data=data ) # Surface every non-2xx (401/403/400/500…) instead of dropping the chunk silently. resp.raise_for_status() return resp.json().get("text", "").strip() except Exception as e: logger.error(f"OpenAI request failed: {e}") raise e return "" async def run_stream( self, process: asyncio.subprocess.Process, language_code: str, model_variant: str, config: ProviderConfig, broadcast_callback, booth_id: str, room_id: int | None = None, ) -> None: terms = await load_prompt_terms(config, room_id) prompt = glossary_prompt(terms) if prompt: logger.info( "[%s] OpenAI %s prompted with the glossary (%d bytes)", booth_id, model_variant, len(prompt.encode()) ) if model_variant in ("whisper-1", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"): # Each chunk is its own request, so the prompt and its terms ride on the config to process_chunk. # They are always the fitted ones: a caller's own prompt (the live demo's) could be over the limit. config = dataclasses.replace(config, prompt=prompt, keyterms=tuple(terms)) await super().run_stream( process, language_code, model_variant, config, broadcast_callback, booth_id, room_id ) return from portal.transcription.aggregator import CaptionAggregator aggregator = CaptionAggregator(broadcast_callback, room_id=room_id) api_key = config.get_key() if not api_key: logger.error("OpenAI API key missing") return transcription = {"model": model_variant, "language": language_code} if prompt: transcription["prompt"] = prompt url = f"wss://api.openai.com/v1/realtime?model={model_variant}" headers = {"Authorization": f"Bearer {api_key}", "OpenAI-Beta": "realtime=v1"} consecutive_errors = 0 while process.returncode is None: try: import base64 import websockets async with websockets.connect(url, additional_headers=headers) as ws: consecutive_errors = 0 session_update = { "type": "session.update", "session": { "type": "transcription", "audio": { "input": { "format": {"type": "audio/pcm", "rate": 24000}, "transcription": transcription, } }, }, } await ws.send(json.dumps(session_update)) async def sender(): try: silence_frames = 0 while True: chunk = await process.stdout.read(4096) if not chunk: return "EOF" audio_data = np.frombuffer(chunk, dtype=np.int16) rms = np.sqrt(np.mean(np.square(audio_data.astype(np.float32)))) if rms < 500.0: silence_frames += 1 else: silence_frames = 0 payload = { "type": "input_audio_buffer.append", "audio": base64.b64encode(chunk).decode("utf-8"), } await ws.send(json.dumps(payload)) if silence_frames == 12: await ws.send(json.dumps({"type": "input_audio_buffer.commit"})) silence_frames = 0 except Exception as e: logger.error(f"[{booth_id}] OpenAI WS sender error: {e}") return "ERROR" async def receiver(): try: current_transcription = "" async for msg in ws: data = json.loads(msg) event_type = data.get("type") if event_type == "conversation.item.input_audio_transcription.completed": transcript = data.get("transcript", "").strip() if transcript: await aggregator.handle_final(booth_id, transcript) current_transcription = "" elif event_type == "conversation.item.input_audio_transcription.delta": delta = data.get("delta", "") if delta: current_transcription += delta await aggregator.handle_partial(booth_id, current_transcription) elif event_type == "input_audio_buffer.speech_stopped": if current_transcription: await aggregator.handle_clear(booth_id) current_transcription = "" except Exception as e: logger.error(f"[{booth_id}] OpenAI WS receiver error: {e}") return "ERROR" sender_task = asyncio.create_task(sender()) receiver_task = asyncio.create_task(receiver()) try: done, _ = await asyncio.wait([sender_task, receiver_task], return_when=asyncio.FIRST_COMPLETED) if sender_task in done and sender_task.result() == "EOF": # Commit does not close the socket. Keep receiving delayed finals # for a bounded interval, including replies to earlier VAD commits. await ws.send(json.dumps({"type": "input_audio_buffer.commit"})) try: await asyncio.wait_for(receiver_task, FINAL_TRANSCRIPT_TIMEOUT_SECONDS) except TimeoutError: logger.debug("[%s] Final transcript drain finished", booth_id) return if receiver_task in done: receiver_task.result() raise OSError("Speech WebSocket disconnected") finally: for task in (sender_task, receiver_task): if not task.done(): task.cancel() await asyncio.gather(sender_task, receiver_task, return_exceptions=True) except Exception as e: consecutive_errors += 1 logger.warning(f"[{booth_id}] OpenAI Realtime connection failed ({consecutive_errors}): {e}") if consecutive_errors > 5: logger.error(f"[{booth_id}] OpenAI Realtime connection repeatedly failed. Giving up.") break await asyncio.sleep(2)