feat(voice_worker): M1 multi-speaker streaming STT and sentence TTS over a local WebSocket

- One shared faster-whisper model for every speaker, batched; finals go before partials and
  partial batches are capped at two so a final never waits behind a ten-speaker pass.
- Per-speaker 48k stereo to 16k mono conversion, streaming Silero VAD, utterance ends on VAD
  silence, Discord speaking_end, missing audio, or the 28 s Whisper window.
- MeloTTS in its own venv through a child process; sentences stream out one chunk each, with
  incremental text, cancel and failure reporting.
- Loopback-only server with a token from the environment; logs carry no transcript text.
- Spec in src/voice_worker/voice_worker.spec.md; unit tests with fake engines and an opt-in
  real-GPU test that streams ten speakers at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 10:00:06 +09:00
parent b4926d5e19
commit a7685e9078
26 changed files with 2660 additions and 1 deletions

View File

@@ -0,0 +1,128 @@
"""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 jarvis.debug 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) -> list[str]: ...
Callback = Callable[[SttResult], None]
@dataclass
class _Job:
key: Hashable
audio: np.ndarray
opts: DecodeOptions
callback: Callback
class SttScheduler:
def __init__(self, transcriber: Transcriber, max_batch: int = 16, max_partial_batch: int = 2):
self.transcriber = transcriber
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) -> None:
self._finals.append(_Job(key, audio, opts, callback))
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 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:
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)
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 ""), "voice_worker")
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}", "voice_worker")