"""One shared STT model for every speaker: finals first, then partials, each batched. All queue state lives on the asyncio loop; the model runs on one executor thread. """ from __future__ import annotations import asyncio import time from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from typing import Callable, Hashable, Protocol import numpy as np from .log import debug_log @dataclass(frozen=True) class DecodeOptions: beam: int language: str | None hotwords: tuple[str, ...] @dataclass class SttResult: text: str stt_ms: int error: str | None = None class Transcriber(Protocol): def transcribe(self, clips: list[np.ndarray], opts: DecodeOptions, contexts: list[str] | None = None) -> list[str]: ... Callback = Callable[[SttResult], None] @dataclass class _Job: key: Hashable audio: np.ndarray opts: DecodeOptions callback: Callback context: str = "" # finals only: the recent conversation, as the model's prompt class SttScheduler: def __init__(self, transcriber: Transcriber, max_batch: int = 16, max_partial_batch: int = 2, partials_held: Callable[[], bool] = lambda: False): self.transcriber = transcriber # While this says so (an answer is written in a game), partial passes wait; finals never do. self.partials_held = partials_held self.max_batch = max_batch # Whisper's encoder always runs on a 30 s window, so its cost grows with every clip in a batch # and batching saves little. A small partial batch bounds how long a final can wait behind one. self.max_partial_batch = max_partial_batch self._finals: list[_Job] = [] self._partials: "OrderedDict[Hashable, _Job]" = OrderedDict() self._wake = asyncio.Event() self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="stt") self._task: asyncio.Task | None = None def start(self) -> None: self._task = asyncio.get_running_loop().create_task(self._run()) async def stop(self) -> None: if self._task: self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._executor.shutdown(wait=False, cancel_futures=True) def submit_final(self, key: Hashable, audio: np.ndarray, opts: DecodeOptions, callback: Callback, context: str = "") -> None: self._finals.append(_Job(key, audio, opts, callback, context)) self._wake.set() def submit_partial(self, key: Hashable, audio: np.ndarray, opts: DecodeOptions, callback: Callback) -> None: self._partials.pop(key, None) # a newer partial replaces the waiting one self._partials[key] = _Job(key, audio, opts, callback) self._wake.set() def wake(self) -> None: """Look again (partials are no longer held).""" self._wake.set() def drop_partials(self, predicate: Callable[[Hashable], bool]) -> None: for key in [k for k in self._partials if predicate(k)]: del self._partials[key] def _take(self) -> tuple[str, list[_Job]]: if self._finals: kind, pool = "final", self._finals elif self._partials and not self.partials_held(): kind, pool = "partial", list(self._partials.values()) else: return "", [] opts = pool[0].opts cap = self.max_batch if kind == "final" else self.max_partial_batch batch = [j for j in pool if j.opts == opts][:cap] if kind == "final": taken = {id(j) for j in batch} self._finals = [j for j in self._finals if id(j) not in taken] else: for j in batch: del self._partials[j.key] return kind, batch async def _run(self) -> None: loop = asyncio.get_running_loop() while True: kind, batch = self._take() if not batch: self._wake.clear() await self._wake.wait() continue clips = [j.audio for j in batch] t0 = time.perf_counter() try: texts = await loop.run_in_executor(self._executor, self.transcriber.transcribe, clips, batch[0].opts, [j.context for j in batch]) error = None except Exception as e: # the model failing must not stop every speaker's STT texts, error = [""] * len(batch), f"{type(e).__name__}: {e}" ms = int((time.perf_counter() - t0) * 1000) debug_log(f"stt batch kind={kind} size={len(batch)} beam={batch[0].opts.beam} ms={ms}" + (f" error={error}" if error else ""), "stt") for job, text in zip(batch, texts): try: job.callback(SttResult(text, ms, error)) except Exception as e: # pragma: no cover - a broken session must not stop the loop debug_log(f"stt callback failed: {type(e).__name__}: {e}", "stt")