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:
4
src/voice_worker/__init__.py
Normal file
4
src/voice_worker/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
"""Jarvis v2 voice worker: multi-speaker streaming STT and sentence TTS over a local WebSocket.
|
||||
|
||||
See ``voice_worker.spec.md`` next to this file.
|
||||
"""
|
||||
66
src/voice_worker/__main__.py
Normal file
66
src/voice_worker/__main__.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""``JARVIS_VOICE_TOKEN=... python -m voice_worker`` (see voice_worker.spec.md)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(prog="voice_worker")
|
||||
ap.add_argument("--host", default="127.0.0.1")
|
||||
ap.add_argument("--port", type=int, default=8771)
|
||||
ap.add_argument("--stt-model", default="large-v3-turbo")
|
||||
ap.add_argument("--stt-device", default="cuda")
|
||||
ap.add_argument("--stt-compute", default="int8_float16")
|
||||
ap.add_argument("--melo-python", default=None, help="python of the MeloTTS venv; no TTS without it")
|
||||
ap.add_argument("--melo-device", default="cuda")
|
||||
ap.add_argument("--melo-speed", type=float, default=1.5)
|
||||
ap.add_argument("--melo-language", default="KR")
|
||||
args = ap.parse_args()
|
||||
|
||||
token = os.environ.get("JARVIS_VOICE_TOKEN", "")
|
||||
if not token:
|
||||
print("JARVIS_VOICE_TOKEN is not set", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
from .server import VoiceWorker, is_loopback
|
||||
from .stt_whisper import WhisperTranscriber
|
||||
from .vad import SileroVad
|
||||
|
||||
if not is_loopback(args.host):
|
||||
print("the voice worker only listens on a loopback address", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
transcriber = WhisperTranscriber(args.stt_model, args.stt_device, args.stt_compute)
|
||||
transcriber.warm_up()
|
||||
vad = SileroVad()
|
||||
tts = None
|
||||
if args.melo_python:
|
||||
from .tts_melo import MeloEngine
|
||||
tts = MeloEngine(args.melo_python, args.melo_device, args.melo_speed, args.melo_language)
|
||||
|
||||
async def run() -> None:
|
||||
worker = VoiceWorker(token, transcriber, vad.stream, tts)
|
||||
server = await worker.serve(args.host, args.port)
|
||||
debug_log(f"voice worker listening on {args.host}:{args.port} tts={'on' if tts else 'off'}",
|
||||
"voice_worker")
|
||||
print(f"READY {args.host}:{args.port}", flush=True)
|
||||
await server.serve_forever()
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
if tts:
|
||||
tts.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
58
src/voice_worker/audio.py
Normal file
58
src/voice_worker/audio.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Incoming PCM to 16 kHz mono float32, and clip normalisation before transcription."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
TARGET_RATE = 16000
|
||||
_TAPS = 97 # windowed-sinc low-pass for the 48 kHz -> 16 kHz decimation
|
||||
_CUTOFF_HZ = 7200 # below the new 8 kHz Nyquist
|
||||
|
||||
|
||||
def _lowpass(rate: int) -> np.ndarray:
|
||||
n = np.arange(_TAPS) - (_TAPS - 1) / 2
|
||||
fc = _CUTOFF_HZ / rate
|
||||
h = 2 * fc * np.sinc(2 * fc * n) * np.blackman(_TAPS)
|
||||
return (h / h.sum()).astype(np.float64)
|
||||
|
||||
|
||||
class InputConverter:
|
||||
"""Streaming converter for one speaker. Keeps filter history and odd bytes between frames."""
|
||||
|
||||
def __init__(self, rate: int, channels: int):
|
||||
if rate not in (16000, 48000):
|
||||
raise ValueError("audio rate must be 16000 or 48000")
|
||||
if channels not in (1, 2):
|
||||
raise ValueError("audio channels must be 1 or 2")
|
||||
self.channels = channels
|
||||
self.factor = rate // TARGET_RATE
|
||||
self._carry = b""
|
||||
if self.factor > 1:
|
||||
self._h = _lowpass(rate)
|
||||
self._hist = np.zeros(_TAPS - 1, dtype=np.float64)
|
||||
self._phase = 0 # input samples to skip before the next kept output
|
||||
|
||||
def push(self, pcm: bytes) -> np.ndarray:
|
||||
data = self._carry + pcm
|
||||
frame_bytes = 2 * self.channels
|
||||
usable = len(data) - len(data) % frame_bytes
|
||||
self._carry = data[usable:]
|
||||
x = np.frombuffer(data[:usable], dtype="<i2").astype(np.float64) / 32768.0
|
||||
if self.channels == 2:
|
||||
x = x.reshape(-1, 2).mean(axis=1)
|
||||
if self.factor == 1:
|
||||
return x.astype(np.float32)
|
||||
buf = np.concatenate([self._hist, x])
|
||||
self._hist = buf[-(_TAPS - 1):]
|
||||
y = np.convolve(buf, self._h, mode="valid") # one output per new input sample
|
||||
out = y[self._phase::self.factor]
|
||||
self._phase = (self._phase - len(y)) % self.factor
|
||||
return out.astype(np.float32)
|
||||
|
||||
|
||||
def peak_normalise(x: np.ndarray, target: float = 0.9, max_gain: float = 10.0) -> np.ndarray:
|
||||
peak = float(np.max(np.abs(x))) if len(x) else 0.0
|
||||
if peak <= 0:
|
||||
return x.astype(np.float32)
|
||||
gain = min(target / peak, max_gain)
|
||||
return (x * gain).astype(np.float32)
|
||||
103
src/voice_worker/melo_child.py
Normal file
103
src/voice_worker/melo_child.py
Normal file
@@ -0,0 +1,103 @@
|
||||
"""MeloTTS child process for the voice worker. Runs in its own Python 3.11 venv (transformers 4.27).
|
||||
|
||||
Stand-alone on purpose: it must not import the worker package, which lives in another venv.
|
||||
|
||||
stdin: one JSON request per line: {"text": "...", "rate": 48000}
|
||||
stdout: frames of u32 LE header length | header JSON | payload. The first frame is
|
||||
{"ready": true, "rate": <native rate>}; each reply is {"ok": true, "samples": N} followed by N
|
||||
int16 LE mono samples at the requested rate, or {"ok": false, "error": "..."} with no payload.
|
||||
Library output that would land on stdout is sent to stderr so it cannot corrupt the frames.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import types
|
||||
|
||||
|
||||
def korean_only_patches() -> None:
|
||||
"""MeloTTS imports its Japanese front end (module-level MeCab.Tagger()) even for Korean, and on
|
||||
Windows g2pkk asks for ``eunjeon`` instead of python-mecab-ko. Same fix as the M0 kit."""
|
||||
try:
|
||||
import MeCab # noqa: F401
|
||||
MeCab.Tagger # noqa: B018
|
||||
except Exception:
|
||||
stub = types.ModuleType("MeCab")
|
||||
|
||||
class Tagger:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def parse(self, text):
|
||||
raise RuntimeError("Japanese MeCab is not installed")
|
||||
|
||||
stub.Tagger = Tagger
|
||||
sys.modules["MeCab"] = stub
|
||||
try:
|
||||
import g2pkk.g2pkk as g2p_mod
|
||||
except Exception:
|
||||
return
|
||||
if g2p_mod.platform.system() == "Windows":
|
||||
g2p_mod.G2p.check_mecab = lambda self: None
|
||||
g2p_mod.G2p.get_mecab = lambda self: importlib.import_module("mecab").MeCab()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# Python puts this file's folder first on sys.path; drop it so the worker's own modules there
|
||||
# never shadow the MeloTTS packages.
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path[:] = [p for p in sys.path if os.path.abspath(p or ".") != here]
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--language", default="KR")
|
||||
ap.add_argument("--device", default="cuda")
|
||||
ap.add_argument("--speed", type=float, default=1.5)
|
||||
args = ap.parse_args()
|
||||
|
||||
out = os.fdopen(os.dup(sys.stdout.fileno()), "wb")
|
||||
os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
def reply(header: dict, payload: bytes = b"") -> None:
|
||||
raw = json.dumps(header).encode()
|
||||
out.write(struct.pack("<I", len(raw)) + raw + payload)
|
||||
out.flush()
|
||||
|
||||
try:
|
||||
korean_only_patches()
|
||||
import numpy as np
|
||||
from melo.api import TTS
|
||||
from scipy.signal import resample_poly
|
||||
model = TTS(language=args.language, device=args.device)
|
||||
spk_map = model.hps.data.spk2id
|
||||
speaker = spk_map[args.language] if args.language in spk_map else spk_map[list(spk_map.keys())[0]]
|
||||
native = int(model.hps.data.sampling_rate)
|
||||
model.tts_to_file("워밍업입니다.", speaker, None, speed=args.speed, quiet=True)
|
||||
except Exception as e:
|
||||
reply({"ready": False, "error": f"{type(e).__name__}: {e}"})
|
||||
return 1
|
||||
reply({"ready": True, "rate": native})
|
||||
|
||||
for line in sys.stdin:
|
||||
try:
|
||||
req = json.loads(line)
|
||||
rate = int(req["rate"])
|
||||
audio = model.tts_to_file(str(req["text"]), speaker, None, speed=args.speed, quiet=True)
|
||||
audio = np.asarray(audio, dtype=np.float64)
|
||||
if rate != native:
|
||||
from math import gcd
|
||||
g = gcd(rate, native)
|
||||
audio = resample_poly(audio, rate // g, native // g)
|
||||
pcm = (np.clip(audio, -1.0, 1.0) * 32767).astype("<i2")
|
||||
reply({"ok": True, "samples": int(len(pcm))}, pcm.tobytes())
|
||||
except Exception as e:
|
||||
reply({"ok": False, "error": f"{type(e).__name__}: {e}"})
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
56
src/voice_worker/protocol.py
Normal file
56
src/voice_worker/protocol.py
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Binary frame layout shared with the Electron voice core (see voice_worker.spec.md)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
|
||||
KIND_AUDIO = 0x01
|
||||
KIND_TTS = 0x02
|
||||
|
||||
|
||||
class ProtocolError(ValueError):
|
||||
"""A frame or message that does not follow the protocol."""
|
||||
|
||||
|
||||
def _encode_id(value: str) -> bytes:
|
||||
raw = value.encode("utf-8")
|
||||
if not 0 < len(raw) < 256:
|
||||
raise ProtocolError("id must be 1-255 bytes of UTF-8")
|
||||
return bytes([len(raw)]) + raw
|
||||
|
||||
|
||||
def _decode_id(frame: bytes, kind: int) -> tuple[str, int]:
|
||||
if len(frame) < 2 or frame[0] != kind:
|
||||
raise ProtocolError("unexpected frame kind")
|
||||
n = frame[1]
|
||||
end = 2 + n
|
||||
if n == 0 or len(frame) < end:
|
||||
raise ProtocolError("truncated id")
|
||||
try:
|
||||
return frame[2:end].decode("utf-8"), end
|
||||
except UnicodeDecodeError as e:
|
||||
raise ProtocolError("id is not UTF-8") from e
|
||||
|
||||
|
||||
def encode_audio_frame(speaker: str, pcm: bytes) -> bytes:
|
||||
return bytes([KIND_AUDIO]) + _encode_id(speaker) + pcm
|
||||
|
||||
|
||||
def decode_audio_frame(frame: bytes) -> tuple[str, bytes]:
|
||||
speaker, end = _decode_id(frame, KIND_AUDIO)
|
||||
pcm = frame[end:]
|
||||
if not pcm or len(pcm) % 2:
|
||||
raise ProtocolError("audio payload must be a non-empty run of 16-bit samples")
|
||||
return speaker, pcm
|
||||
|
||||
|
||||
def encode_tts_frame(request_id: str, seq: int, pcm: bytes) -> bytes:
|
||||
return bytes([KIND_TTS]) + _encode_id(request_id) + struct.pack("<I", seq) + pcm
|
||||
|
||||
|
||||
def decode_tts_frame(frame: bytes) -> tuple[str, int, bytes]:
|
||||
request_id, end = _decode_id(frame, KIND_TTS)
|
||||
if len(frame) < end + 4:
|
||||
raise ProtocolError("truncated sequence number")
|
||||
(seq,) = struct.unpack_from("<I", frame, end)
|
||||
return request_id, seq, frame[end + 4:]
|
||||
12
src/voice_worker/requirements.txt
Normal file
12
src/voice_worker/requirements.txt
Normal file
@@ -0,0 +1,12 @@
|
||||
# Voice worker venv (Python 3.12). Same STT pins the M0 kit measured on the game PC.
|
||||
faster-whisper==1.2.1
|
||||
ctranslate2==4.8.1
|
||||
nvidia-cublas-cu12==12.9.2.10
|
||||
nvidia-cudnn-cu12==9.24.0.43
|
||||
onnxruntime>=1.17
|
||||
websockets>=13
|
||||
numpy
|
||||
# jarvis.debug (debug_log) reads the jarvis config, which needs python-dotenv.
|
||||
python-dotenv==1.0.1
|
||||
# MeloTTS runs in its own Python 3.11 venv (see the "melo" entry in scripts/m0/m0lib/envs.py) and is
|
||||
# reached through melo_child.py; pass that venv's python with --melo-python.
|
||||
128
src/voice_worker/scheduler.py
Normal file
128
src/voice_worker/scheduler.py
Normal 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")
|
||||
138
src/voice_worker/segmenter.py
Normal file
138
src/voice_worker/segmenter.py
Normal file
@@ -0,0 +1,138 @@
|
||||
"""Per-speaker utterance segmentation on 16 kHz mono audio (rules in voice_worker.spec.md)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .settings import SttSettings
|
||||
|
||||
SR = 16000
|
||||
WINDOW = 512 # Silero window at 16 kHz
|
||||
WINDOW_MS = WINDOW * 1000 / SR # 32 ms
|
||||
START_PROB = 0.5
|
||||
KEEP_PROB = 0.35
|
||||
PRE_ROLL_MS = 200
|
||||
MIN_SPEECH_MS = 250
|
||||
TAIL_KEEP_MS = 200
|
||||
MAX_UTTERANCE_MS = 28000
|
||||
|
||||
|
||||
class VadStream(Protocol):
|
||||
def prob(self, window: np.ndarray) -> float: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class SpeechStart:
|
||||
utt: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Partial:
|
||||
utt: int
|
||||
audio: np.ndarray
|
||||
|
||||
|
||||
@dataclass
|
||||
class Final:
|
||||
utt: int
|
||||
audio: np.ndarray
|
||||
reason: str # silence | speaking_end | idle | max_length
|
||||
decided_at: float
|
||||
|
||||
|
||||
def _windows(ms: float) -> int:
|
||||
return int(ms // WINDOW_MS)
|
||||
|
||||
|
||||
class Segmenter:
|
||||
def __init__(self, vad: VadStream, settings: SttSettings):
|
||||
self.vad = vad
|
||||
self.settings = settings
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
self._pre: list[np.ndarray] = []
|
||||
self._utt_count = 0
|
||||
self._last_audio_at: float | None = None
|
||||
self._reset()
|
||||
|
||||
def _reset(self) -> None:
|
||||
self._active = False
|
||||
self._win: list[np.ndarray] = []
|
||||
self._speech = 0
|
||||
self._trailing = 0
|
||||
self._started = False
|
||||
self._last_partial_at = 0.0
|
||||
self._last_partial_len = 0
|
||||
|
||||
@property
|
||||
def open_utt(self) -> int | None:
|
||||
"""The utterance that sent speech_start and has not ended yet."""
|
||||
return self._utt_count if self._active and self._started else None
|
||||
|
||||
def push(self, samples: np.ndarray, now: float) -> list:
|
||||
self._last_audio_at = now
|
||||
data = np.concatenate([self._pending, samples.astype(np.float32, copy=False)])
|
||||
n = len(data) // WINDOW * WINDOW
|
||||
self._pending = data[n:]
|
||||
events: list = []
|
||||
for i in range(0, n, WINDOW):
|
||||
events += self._window(data[i:i + WINDOW], now)
|
||||
if self.open_utt is not None and len(self._win) > self._last_partial_len \
|
||||
and now - self._last_partial_at >= self.settings.partial_interval_ms / 1000:
|
||||
self._last_partial_at = now
|
||||
self._last_partial_len = len(self._win)
|
||||
events.append(Partial(self._utt_count, np.concatenate(self._win)))
|
||||
return events
|
||||
|
||||
def _window(self, w: np.ndarray, now: float) -> list:
|
||||
p = self.vad.prob(w)
|
||||
if not self._active:
|
||||
if p >= START_PROB:
|
||||
self._active = True
|
||||
self._win = self._pre + [w]
|
||||
self._pre = []
|
||||
self._speech = 1
|
||||
self._trailing = 0
|
||||
else:
|
||||
self._pre.append(w)
|
||||
del self._pre[:-_windows(PRE_ROLL_MS)]
|
||||
return []
|
||||
self._win.append(w)
|
||||
if p >= KEEP_PROB:
|
||||
self._speech += 1
|
||||
self._trailing = 0
|
||||
else:
|
||||
self._trailing += 1
|
||||
events: list = []
|
||||
if not self._started and self._speech * WINDOW_MS >= MIN_SPEECH_MS:
|
||||
self._started = True
|
||||
self._utt_count += 1
|
||||
self._last_partial_at = now
|
||||
events.append(SpeechStart(self._utt_count))
|
||||
if self._trailing * WINDOW_MS >= self.settings.end_silence_ms:
|
||||
events += self._end("silence", now)
|
||||
elif len(self._win) * WINDOW_MS >= MAX_UTTERANCE_MS:
|
||||
events += self._end("max_length", now)
|
||||
return events
|
||||
|
||||
def _end(self, reason: str, now: float) -> list:
|
||||
events: list = []
|
||||
if self._active and self._started:
|
||||
drop = max(0, self._trailing - _windows(TAIL_KEEP_MS))
|
||||
kept = self._win[:len(self._win) - drop]
|
||||
events.append(Final(self._utt_count, np.concatenate(kept), reason, now))
|
||||
self._reset()
|
||||
return events
|
||||
|
||||
def speaking_end(self, now: float) -> list:
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
return self._end("speaking_end", now) if self._active else []
|
||||
|
||||
def tick(self, now: float) -> list:
|
||||
if self._active and self._last_audio_at is not None \
|
||||
and now - self._last_audio_at >= self.settings.end_silence_ms / 1000:
|
||||
self._pending = np.zeros(0, dtype=np.float32)
|
||||
return self._end("idle", now)
|
||||
return []
|
||||
76
src/voice_worker/sentences.py
Normal file
76
src/voice_worker/sentences.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""Punctuation-only sentence splitting for streaming TTS (language-agnostic).
|
||||
|
||||
Same rule as the v1 bridge (``bridge/text_utils.py``), which is legacy and goes away with v2; the
|
||||
worker keeps its own copy so it does not depend on the v1 package.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
# A boundary is a run of newlines, a run of CJK terminators (always a sentence end, CJK puts no space
|
||||
# after one), or a run of ASCII terminators that really ends a sentence: followed by whitespace, a
|
||||
# closing quote or bracket, or the end of the text. Dots inside tokens (17.5, v2.0, example.com) are
|
||||
# followed by a non-space character, so they never match.
|
||||
_BOUNDARY = re.compile(
|
||||
r"""
|
||||
(?P<nl>\n+)
|
||||
| (?P<cjk>[。!?…]+)
|
||||
| (?P<ascii>[.!?]+)(?=[)\]"'”’》」』]*(?:\s|$))
|
||||
""",
|
||||
re.VERBOSE,
|
||||
)
|
||||
|
||||
|
||||
def split_sentences(text: str | None, min_len: int = 5) -> list[str]:
|
||||
"""Split ``text`` into sentence chunks; fragments under ``min_len`` characters join a neighbour."""
|
||||
return _split(text, min_len, merge_short_tail=True)
|
||||
|
||||
|
||||
def _split(text: str | None, min_len: int, merge_short_tail: bool) -> list[str]:
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
chunks: list[str] = []
|
||||
buf = ""
|
||||
last = 0
|
||||
for m in _BOUNDARY.finditer(text):
|
||||
buf += text[last:m.end()]
|
||||
last = m.end()
|
||||
if len(buf.strip()) >= min_len:
|
||||
chunks.append(buf.strip())
|
||||
buf = ""
|
||||
tail = (buf + text[last:]).strip()
|
||||
if tail:
|
||||
if merge_short_tail and chunks and len(tail) < min_len:
|
||||
chunks[-1] = chunks[-1] + " " + tail
|
||||
else:
|
||||
chunks.append(tail)
|
||||
return chunks
|
||||
|
||||
|
||||
class StreamingSplitter:
|
||||
"""Feed text as it streams in; get back every sentence that is certainly complete."""
|
||||
|
||||
def __init__(self, min_len: int = 5):
|
||||
self.min_len = min_len
|
||||
self._buf = ""
|
||||
|
||||
def feed(self, text: str) -> list[str]:
|
||||
self._buf += text
|
||||
# The tail may still grow, so it is not merged backwards here.
|
||||
chunks = _split(self._buf, self.min_len, merge_short_tail=False)
|
||||
if len(chunks) <= 1:
|
||||
return []
|
||||
done = chunks[:-1]
|
||||
# Keep the raw text after the last emitted chunk, so spacing inside the tail is untouched.
|
||||
consumed = 0
|
||||
for c in done:
|
||||
consumed = self._buf.index(c, consumed) + len(c)
|
||||
self._buf = self._buf[consumed:]
|
||||
return done
|
||||
|
||||
def finish(self) -> list[str]:
|
||||
rest = self._buf.strip()
|
||||
self._buf = ""
|
||||
return [rest] if rest else []
|
||||
310
src/voice_worker/server.py
Normal file
310
src/voice_worker/server.py
Normal file
@@ -0,0 +1,310 @@
|
||||
"""Local WebSocket server: one session per connection (protocol in voice_worker.spec.md)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hmac
|
||||
import ipaddress
|
||||
import itertools
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
from .audio import InputConverter
|
||||
from .protocol import KIND_AUDIO, ProtocolError, decode_audio_frame, encode_tts_frame
|
||||
from .scheduler import DecodeOptions, SttResult, SttScheduler, Transcriber
|
||||
from .segmenter import SR, Final, Partial, Segmenter, SpeechStart, VadStream
|
||||
from .settings import SttSettings
|
||||
from .tts import TtsEngine, TtsRequest, TtsService
|
||||
|
||||
CLOSE_BAD_HELLO = 4400
|
||||
CLOSE_BAD_TOKEN = 4401
|
||||
MAX_SPEAKERS = 32
|
||||
|
||||
|
||||
def is_loopback(host: str) -> bool:
|
||||
if host == "localhost":
|
||||
return True
|
||||
try:
|
||||
return ipaddress.ip_address(host).is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
class VoiceWorker:
|
||||
def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream],
|
||||
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05):
|
||||
if not token:
|
||||
raise ValueError("a connection token is required")
|
||||
self.token = token
|
||||
self.transcriber = transcriber
|
||||
self.vad_factory = vad_factory
|
||||
self.tts_engine = tts_engine
|
||||
self.hello_timeout_s = hello_timeout_s
|
||||
self.tick_s = tick_s
|
||||
self.scheduler: SttScheduler | None = None
|
||||
self.tts: TtsService | None = None
|
||||
self._ids = itertools.count(1)
|
||||
|
||||
async def start(self) -> None:
|
||||
if self.transcriber is not None:
|
||||
self.scheduler = SttScheduler(self.transcriber)
|
||||
self.scheduler.start()
|
||||
if self.tts_engine is not None:
|
||||
self.tts = TtsService(self.tts_engine)
|
||||
self.tts.start()
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self.scheduler:
|
||||
await self.scheduler.stop()
|
||||
if self.tts:
|
||||
await self.tts.stop()
|
||||
|
||||
async def serve(self, host: str, port: int):
|
||||
"""Start listening; returns the websockets server. Loopback addresses only."""
|
||||
if not is_loopback(host):
|
||||
raise ValueError("the voice worker only listens on a loopback address")
|
||||
from websockets.asyncio.server import serve
|
||||
await self.start()
|
||||
return await serve(self.handle, host, port, max_size=2 ** 20)
|
||||
|
||||
async def handle(self, ws) -> None:
|
||||
try:
|
||||
first = await asyncio.wait_for(ws.recv(), self.hello_timeout_s)
|
||||
hello = json.loads(first) if isinstance(first, str) else None
|
||||
except (asyncio.TimeoutError, ValueError):
|
||||
hello = None
|
||||
except Exception:
|
||||
return
|
||||
if not isinstance(hello, dict) or hello.get("type") != "hello":
|
||||
debug_log("connection refused: no hello", "voice_worker")
|
||||
await ws.close(CLOSE_BAD_HELLO, "hello expected")
|
||||
return
|
||||
token = hello.get("token")
|
||||
if not isinstance(token, str) or not hmac.compare_digest(token.encode(), self.token.encode()):
|
||||
debug_log("connection refused: bad token", "voice_worker")
|
||||
await ws.close(CLOSE_BAD_TOKEN, "bad token")
|
||||
return
|
||||
try:
|
||||
session = Session(self, ws, next(self._ids), hello)
|
||||
except ValueError as e:
|
||||
await ws.close(CLOSE_BAD_HELLO, str(e)[:100])
|
||||
return
|
||||
await session.run()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Speaker:
|
||||
converter: InputConverter
|
||||
segmenter: Segmenter
|
||||
|
||||
|
||||
def _format(value, default: dict, rates: tuple[int, ...] | None) -> dict:
|
||||
if value is None:
|
||||
return dict(default)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("format must be an object")
|
||||
rate, channels = value.get("rate", default["rate"]), value.get("channels", default["channels"])
|
||||
ok_rate = isinstance(rate, int) and (rate in rates if rates else 8000 <= rate <= 96000)
|
||||
if not ok_rate or channels not in (1, 2) or isinstance(channels, bool):
|
||||
raise ValueError("unsupported audio format")
|
||||
return {"rate": rate, "channels": channels}
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, worker: VoiceWorker, ws, sid: int, hello: dict):
|
||||
self.worker = worker
|
||||
self.ws = ws
|
||||
self.sid = sid
|
||||
self.audio = _format(hello.get("audio"), {"rate": 48000, "channels": 2}, (16000, 48000))
|
||||
self.tts_format = _format(hello.get("tts"), {"rate": 48000, "channels": 2}, None)
|
||||
self.settings = SttSettings()
|
||||
stt = hello.get("stt")
|
||||
if stt is not None:
|
||||
if not isinstance(stt, dict):
|
||||
raise ValueError("stt must be an object")
|
||||
self.settings.update(stt)
|
||||
self.speakers: dict[str, _Speaker] = {}
|
||||
self.tts_requests: dict[str, TtsRequest] = {}
|
||||
self.out: asyncio.Queue = asyncio.Queue()
|
||||
self.closed = False
|
||||
|
||||
# --- outbound -------------------------------------------------------------------------------
|
||||
def send(self, msg) -> None:
|
||||
if not self.closed:
|
||||
self.out.put_nowait(msg if isinstance(msg, bytes) else json.dumps(msg, ensure_ascii=False))
|
||||
|
||||
def error(self, code: str, message: str, **extra) -> None:
|
||||
self.send({"type": "error", "code": code, "message": message, **extra})
|
||||
|
||||
async def _writer(self) -> None:
|
||||
while True:
|
||||
await self.ws.send(await self.out.get())
|
||||
|
||||
# --- lifecycle ------------------------------------------------------------------------------
|
||||
async def run(self) -> None:
|
||||
w = self.worker
|
||||
debug_log(f"session {self.sid} connected audio={self.audio} tts={self.tts_format}", "voice_worker")
|
||||
self.send({"type": "hello_ok", "stt_ready": w.scheduler is not None, "tts_ready": w.tts is not None,
|
||||
"audio": self.audio, "tts": self.tts_format, "stt": self.settings.as_dict()})
|
||||
writer = asyncio.create_task(self._writer())
|
||||
ticker = asyncio.create_task(self._ticker())
|
||||
try:
|
||||
async for frame in self.ws:
|
||||
if isinstance(frame, bytes):
|
||||
self._on_binary(frame)
|
||||
else:
|
||||
self._on_text(frame)
|
||||
except Exception as e: # connection dropped
|
||||
debug_log(f"session {self.sid} receive ended: {type(e).__name__}", "voice_worker")
|
||||
finally:
|
||||
self.closed = True
|
||||
ticker.cancel()
|
||||
writer.cancel()
|
||||
if w.scheduler:
|
||||
w.scheduler.drop_partials(lambda key: key[0] == self.sid)
|
||||
if w.tts:
|
||||
for req in list(self.tts_requests.values()):
|
||||
w.tts.cancel(req)
|
||||
debug_log(f"session {self.sid} closed", "voice_worker")
|
||||
|
||||
async def _ticker(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(self.worker.tick_s)
|
||||
now = time.monotonic()
|
||||
for speaker, st in list(self.speakers.items()):
|
||||
self._handle_events(speaker, st, st.segmenter.tick(now))
|
||||
|
||||
# --- STT ------------------------------------------------------------------------------------
|
||||
def _on_binary(self, frame: bytes) -> None:
|
||||
if not frame or frame[0] != KIND_AUDIO:
|
||||
self.error("bad_frame", "unknown binary frame kind")
|
||||
return
|
||||
try:
|
||||
speaker, pcm = decode_audio_frame(frame)
|
||||
except ProtocolError as e:
|
||||
self.error("bad_frame", str(e))
|
||||
return
|
||||
st = self.speakers.get(speaker)
|
||||
if st is None:
|
||||
if len(self.speakers) >= MAX_SPEAKERS:
|
||||
self.error("bad_frame", f"more than {MAX_SPEAKERS} speakers")
|
||||
return
|
||||
st = _Speaker(InputConverter(self.audio["rate"], self.audio["channels"]),
|
||||
Segmenter(self.worker.vad_factory(), self.settings))
|
||||
self.speakers[speaker] = st
|
||||
samples = st.converter.push(pcm)
|
||||
self._handle_events(speaker, st, st.segmenter.push(samples, time.monotonic()))
|
||||
|
||||
def _opts(self, beam: int) -> DecodeOptions:
|
||||
return DecodeOptions(beam=beam, language=self.settings.language, hotwords=self.settings.hotwords)
|
||||
|
||||
def _handle_events(self, speaker: str, st: _Speaker, events: list) -> None:
|
||||
sched = self.worker.scheduler
|
||||
for ev in events:
|
||||
if isinstance(ev, SpeechStart):
|
||||
self.send({"type": "speech_start", "speaker": speaker, "utt": ev.utt})
|
||||
elif isinstance(ev, Partial):
|
||||
if sched and self.settings.partials:
|
||||
sched.submit_partial((self.sid, speaker), ev.audio, self._opts(1),
|
||||
self._partial_cb(speaker, st, ev.utt))
|
||||
elif isinstance(ev, Final):
|
||||
debug_log(f"utterance end speaker={speaker} utt={ev.utt} reason={ev.reason} "
|
||||
f"ms={len(ev.audio) * 1000 // SR}", "voice_worker")
|
||||
if sched is None:
|
||||
self._send_final(speaker, ev, SttResult("", 0, "stt unavailable"))
|
||||
else:
|
||||
sched.submit_final((self.sid, speaker), ev.audio, self._opts(self.settings.final_beam),
|
||||
lambda res, ev=ev: self._send_final(speaker, ev, res))
|
||||
|
||||
def _partial_cb(self, speaker: str, st: _Speaker, utt: int):
|
||||
def cb(res: SttResult) -> None:
|
||||
# Drop it when the utterance already ended or captions were turned off meanwhile.
|
||||
if st.segmenter.open_utt == utt and self.settings.partials and not res.error:
|
||||
self.send({"type": "partial", "speaker": speaker, "utt": utt, "text": res.text})
|
||||
return cb
|
||||
|
||||
def _send_final(self, speaker: str, ev: Final, res: SttResult) -> None:
|
||||
self.send({"type": "final", "speaker": speaker, "utt": ev.utt, "text": res.text,
|
||||
"end_reason": ev.reason, "audio_ms": len(ev.audio) * 1000 // SR,
|
||||
"wait_ms": int((time.monotonic() - ev.decided_at) * 1000), "stt_ms": res.stt_ms})
|
||||
|
||||
# --- text messages --------------------------------------------------------------------------
|
||||
def _on_text(self, raw: str) -> None:
|
||||
try:
|
||||
msg = json.loads(raw)
|
||||
except ValueError:
|
||||
self.error("bad_message", "not JSON")
|
||||
return
|
||||
if not isinstance(msg, dict):
|
||||
self.error("bad_message", "not an object")
|
||||
return
|
||||
kind = msg.get("type")
|
||||
handler = {"speaking_end": self._on_speaking_end, "config": self._on_config, "tts": self._on_tts,
|
||||
"tts_cancel": self._on_tts_cancel}.get(kind)
|
||||
if handler is None:
|
||||
self.error("bad_message", f"unknown type: {kind!r}")
|
||||
return
|
||||
handler(msg)
|
||||
|
||||
def _on_speaking_end(self, msg: dict) -> None:
|
||||
st = self.speakers.get(msg.get("speaker"))
|
||||
if st is not None:
|
||||
self._handle_events(msg["speaker"], st, st.segmenter.speaking_end(time.monotonic()))
|
||||
|
||||
def _on_config(self, msg: dict) -> None:
|
||||
changes = {k: v for k, v in msg.items() if k != "type"}
|
||||
try:
|
||||
self.settings.update(changes)
|
||||
except ValueError as e:
|
||||
self.error("bad_message", str(e))
|
||||
return
|
||||
if not self.settings.partials and self.worker.scheduler:
|
||||
self.worker.scheduler.drop_partials(lambda key: key[0] == self.sid)
|
||||
debug_log(f"session {self.sid} settings changed: {sorted(changes)}", "voice_worker")
|
||||
|
||||
def _on_tts(self, msg: dict) -> None:
|
||||
rid, text, more = msg.get("id"), msg.get("text", ""), msg.get("more", False)
|
||||
if not isinstance(rid, str) or not 0 < len(rid.encode()) < 256 or not isinstance(text, str) \
|
||||
or not isinstance(more, bool):
|
||||
self.error("bad_message", "tts needs a string id and text, and a boolean more")
|
||||
return
|
||||
tts = self.worker.tts
|
||||
if tts is None:
|
||||
self.error("tts_unavailable", "no TTS engine is loaded", id=rid)
|
||||
return
|
||||
req = self.tts_requests.get(rid)
|
||||
if req is None:
|
||||
req = TtsRequest(rid, self.tts_format["rate"], self._tts_chunk_cb(rid), self._tts_done,
|
||||
self._tts_error)
|
||||
self.tts_requests[rid] = req
|
||||
elif req.closed:
|
||||
self.error("bad_message", "this tts id is already closed", id=rid)
|
||||
return
|
||||
tts.feed(req, text, more)
|
||||
|
||||
def _on_tts_cancel(self, msg: dict) -> None:
|
||||
req = self.tts_requests.get(msg.get("id"))
|
||||
if req is not None and self.worker.tts:
|
||||
self.worker.tts.cancel(req)
|
||||
|
||||
def _tts_chunk_cb(self, rid: str):
|
||||
def cb(seq: int, pcm: np.ndarray) -> None:
|
||||
pcm = np.asarray(pcm, dtype="<i2")
|
||||
if self.tts_format["channels"] == 2:
|
||||
pcm = np.repeat(pcm, 2)
|
||||
self.send(encode_tts_frame(rid, seq, pcm.tobytes()))
|
||||
return cb
|
||||
|
||||
def _tts_done(self, req: TtsRequest) -> None:
|
||||
self.tts_requests.pop(req.id, None)
|
||||
self.send({"type": "tts_done", "id": req.id, "chunks": req.chunks, "cancelled": req.cancelled,
|
||||
"failed": req.failed})
|
||||
|
||||
def _tts_error(self, req: TtsRequest, message: str) -> None:
|
||||
self.error("tts_failed", message, id=req.id)
|
||||
60
src/voice_worker/settings.py
Normal file
60
src/voice_worker/settings.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Per-connection STT settings, validated as a whole before any of them change."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, fields
|
||||
|
||||
|
||||
@dataclass
|
||||
class SttSettings:
|
||||
partials: bool = True
|
||||
partial_interval_ms: int = 400
|
||||
end_silence_ms: int = 300
|
||||
final_beam: int = 2
|
||||
language: str | None = "ko"
|
||||
hotwords: tuple[str, ...] = ()
|
||||
|
||||
def update(self, changes: dict) -> None:
|
||||
"""Apply ``changes``; raises ValueError and changes nothing if any value is bad."""
|
||||
names = {f.name for f in fields(self)}
|
||||
staged = asdict(self)
|
||||
for key, value in changes.items():
|
||||
if key not in names:
|
||||
raise ValueError(f"unknown STT setting: {key}")
|
||||
staged[key] = _check(key, value)
|
||||
for key, value in staged.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
d = asdict(self)
|
||||
d["hotwords"] = list(self.hotwords)
|
||||
return d
|
||||
|
||||
|
||||
def _int_in(key: str, value, lo: int, hi: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
|
||||
raise ValueError(f"{key} must be an integer in {lo}-{hi}")
|
||||
return value
|
||||
|
||||
|
||||
def _check(key: str, value):
|
||||
if key == "partials":
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError("partials must be true or false")
|
||||
return value
|
||||
if key == "partial_interval_ms":
|
||||
return _int_in(key, value, 100, 5000)
|
||||
if key == "end_silence_ms":
|
||||
return _int_in(key, value, 100, 2000)
|
||||
if key == "final_beam":
|
||||
return _int_in(key, value, 1, 5)
|
||||
if key == "language":
|
||||
if value is not None and (not isinstance(value, str) or not 2 <= len(value) <= 8):
|
||||
raise ValueError("language must be a language code or null")
|
||||
return value
|
||||
if key == "hotwords":
|
||||
if (not isinstance(value, (list, tuple)) or len(value) > 50
|
||||
or not all(isinstance(w, str) and 0 < len(w) <= 64 for w in value)):
|
||||
raise ValueError("hotwords must be a list of up to 50 short strings")
|
||||
return tuple(value)
|
||||
raise ValueError(f"unknown STT setting: {key}") # pragma: no cover
|
||||
78
src/voice_worker/stt_whisper.py
Normal file
78
src/voice_worker/stt_whisper.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""faster-whisper batch transcription: one encoder and one decoder pass for every clip in a batch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
from .audio import peak_normalise
|
||||
from .scheduler import DecodeOptions
|
||||
|
||||
SR = 16000
|
||||
NO_SPEECH_THRESHOLD = 0.5 # same gate as v1 (whisper_no_speech_threshold)
|
||||
MIN_CONFIDENCE = 0.3 # avg_logprob + 1, same as v1 (whisper_min_confidence)
|
||||
|
||||
|
||||
def add_cuda_dll_dirs() -> None:
|
||||
"""On Windows ctranslate2 loads cuBLAS/cuDNN from the PATH; the pip wheels put them in nvidia/*/bin."""
|
||||
if not hasattr(os, "add_dll_directory"):
|
||||
return
|
||||
for sp in sys.path:
|
||||
for d in glob.glob(os.path.join(sp, "nvidia", "*", "bin")):
|
||||
if os.path.isdir(d):
|
||||
os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "")
|
||||
os.add_dll_directory(d)
|
||||
|
||||
|
||||
class WhisperTranscriber:
|
||||
def __init__(self, model: str = "large-v3-turbo", device: str = "cuda", compute_type: str = "int8_float16"):
|
||||
add_cuda_dll_dirs()
|
||||
from faster_whisper import WhisperModel
|
||||
self.model = WhisperModel(model, device=device, compute_type=compute_type)
|
||||
self._tokenizers: dict = {}
|
||||
debug_log(f"whisper loaded model={model} device={device} compute={compute_type}", "voice_worker")
|
||||
|
||||
def _tokenizer(self, language: str):
|
||||
tok = self._tokenizers.get(language)
|
||||
if tok is None:
|
||||
from faster_whisper.tokenizer import Tokenizer
|
||||
tok = Tokenizer(self.model.hf_tokenizer, self.model.model.is_multilingual, task="transcribe",
|
||||
language=language)
|
||||
self._tokenizers[language] = tok
|
||||
return tok
|
||||
|
||||
def warm_up(self) -> None:
|
||||
self.transcribe([np.zeros(SR, dtype=np.float32)], DecodeOptions(beam=1, language="en", hotwords=()))
|
||||
|
||||
def transcribe(self, clips: list[np.ndarray], opts: DecodeOptions) -> list[str]:
|
||||
m = self.model
|
||||
n_frames = m.feature_extractor.nb_max_frames
|
||||
feats = []
|
||||
for c in clips:
|
||||
a = peak_normalise(c[: SR * 30])
|
||||
a = np.pad(a, (0, SR * 30 - len(a)))
|
||||
feats.append(m.feature_extractor(a, padding=0)[:, :n_frames])
|
||||
enc = m.encode(np.stack(feats).astype(np.float32))
|
||||
if opts.language:
|
||||
langs = [opts.language] * len(clips)
|
||||
else:
|
||||
langs = [r[0][0][2:-2] for r in m.model.detect_language(enc)]
|
||||
hot = " ".join(opts.hotwords) or None
|
||||
prompts = [m.get_prompt(self._tokenizer(lang), [], without_timestamps=True, hotwords=hot) for lang in langs]
|
||||
results = m.model.generate(enc, prompts, beam_size=opts.beam, max_length=224,
|
||||
suppress_blank=True, suppress_tokens=[-1], return_scores=True,
|
||||
return_no_speech_prob=True)
|
||||
texts = []
|
||||
for lang, r in zip(langs, results):
|
||||
tokens = r.sequences_ids[0]
|
||||
avg_logprob = r.scores[0] * len(tokens) / (len(tokens) + 1)
|
||||
if r.no_speech_prob >= NO_SPEECH_THRESHOLD or avg_logprob + 1 < MIN_CONFIDENCE:
|
||||
texts.append("")
|
||||
else:
|
||||
texts.append(self._tokenizer(lang).decode(tokens).strip())
|
||||
return texts
|
||||
105
src/voice_worker/tts.py
Normal file
105
src/voice_worker/tts.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""Sentence-by-sentence TTS shared by every connection, first come first served."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Protocol
|
||||
|
||||
import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
from .sentences import StreamingSplitter
|
||||
|
||||
|
||||
class TtsEngine(Protocol):
|
||||
def synthesize(self, text: str, rate: int) -> np.ndarray:
|
||||
"""Return int16 mono samples at ``rate``."""
|
||||
...
|
||||
|
||||
|
||||
@dataclass
|
||||
class TtsRequest:
|
||||
id: str
|
||||
rate: int
|
||||
on_chunk: Callable[[int, np.ndarray], None]
|
||||
on_done: Callable[["TtsRequest"], None]
|
||||
on_error: Callable[["TtsRequest", str], None]
|
||||
splitter: StreamingSplitter = field(default_factory=StreamingSplitter)
|
||||
next_seq: int = 0
|
||||
outstanding: int = 0
|
||||
chunks: int = 0
|
||||
closed: bool = False
|
||||
cancelled: bool = False
|
||||
failed: bool = False
|
||||
finished: bool = False
|
||||
|
||||
|
||||
class TtsService:
|
||||
def __init__(self, engine: TtsEngine):
|
||||
self.engine = engine
|
||||
self._queue: asyncio.Queue = asyncio.Queue()
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="tts")
|
||||
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 feed(self, req: TtsRequest, text: str, more: bool) -> None:
|
||||
sentences = req.splitter.feed(text)
|
||||
if not more:
|
||||
sentences += req.splitter.finish()
|
||||
req.closed = True
|
||||
for s in sentences:
|
||||
req.outstanding += 1
|
||||
self._queue.put_nowait((req, req.next_seq, s))
|
||||
req.next_seq += 1
|
||||
self._maybe_done(req)
|
||||
|
||||
def cancel(self, req: TtsRequest) -> None:
|
||||
req.cancelled = True
|
||||
req.closed = True
|
||||
debug_log(f"tts cancel id={req.id} sent={req.chunks}", "voice_worker")
|
||||
self._maybe_done(req)
|
||||
|
||||
def _maybe_done(self, req: TtsRequest) -> None:
|
||||
if req.closed and req.outstanding == 0 and not req.finished:
|
||||
req.finished = True
|
||||
req.on_done(req)
|
||||
|
||||
async def _run(self) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
while True:
|
||||
req, seq, text = await self._queue.get()
|
||||
try:
|
||||
if req.cancelled or req.failed:
|
||||
continue
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
pcm = await loop.run_in_executor(self._executor, self.engine.synthesize, text, req.rate)
|
||||
except Exception as e:
|
||||
req.failed = True
|
||||
req.closed = True
|
||||
debug_log(f"tts failed id={req.id} seq={seq}: {type(e).__name__}: {e}", "voice_worker")
|
||||
req.on_error(req, f"{type(e).__name__}: {e}")
|
||||
continue
|
||||
debug_log(f"tts sentence id={req.id} seq={seq} chars={len(text)} "
|
||||
f"ms={int((time.perf_counter() - t0) * 1000)}", "voice_worker")
|
||||
if not req.cancelled:
|
||||
req.chunks += 1
|
||||
req.on_chunk(seq, pcm)
|
||||
finally:
|
||||
req.outstanding -= 1
|
||||
self._maybe_done(req)
|
||||
65
src/voice_worker/tts_melo.py
Normal file
65
src/voice_worker/tts_melo.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""TTS engine that drives ``melo_child.py`` in the MeloTTS venv over stdin/stdout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
CHILD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "melo_child.py")
|
||||
|
||||
|
||||
class MeloEngine:
|
||||
def __init__(self, python: str, device: str = "cuda", speed: float = 1.5, language: str = "KR"):
|
||||
self.cmd = [python, CHILD, "--device", device, "--speed", str(speed), "--language", language]
|
||||
self._lock = threading.Lock()
|
||||
self._proc: subprocess.Popen | None = None
|
||||
self.native_rate: int | None = None
|
||||
self._start()
|
||||
|
||||
def _start(self) -> None:
|
||||
self._proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=None, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
header, _ = self._read()
|
||||
if not header.get("ready"):
|
||||
self.close()
|
||||
raise RuntimeError(f"MeloTTS failed to start: {header.get('error')}")
|
||||
self.native_rate = header["rate"]
|
||||
debug_log(f"melo ready native_rate={self.native_rate}", "voice_worker")
|
||||
|
||||
def _read(self) -> tuple[dict, bytes]:
|
||||
out = self._proc.stdout
|
||||
raw = out.read(4)
|
||||
if len(raw) < 4:
|
||||
raise RuntimeError("MeloTTS child exited")
|
||||
(n,) = struct.unpack("<I", raw)
|
||||
header = json.loads(out.read(n))
|
||||
payload = out.read(header.get("samples", 0) * 2) if header.get("ok") else b""
|
||||
return header, payload
|
||||
|
||||
def synthesize(self, text: str, rate: int) -> np.ndarray:
|
||||
with self._lock:
|
||||
if self._proc is None or self._proc.poll() is not None:
|
||||
debug_log("melo child not running, restarting", "voice_worker")
|
||||
self._start()
|
||||
self._proc.stdin.write((json.dumps({"text": text, "rate": rate}) + "\n").encode())
|
||||
self._proc.stdin.flush()
|
||||
header, payload = self._read()
|
||||
if not header.get("ok"):
|
||||
raise RuntimeError(header.get("error", "MeloTTS failed"))
|
||||
return np.frombuffer(payload, dtype="<i2")
|
||||
|
||||
def close(self) -> None:
|
||||
if self._proc and self._proc.poll() is None:
|
||||
self._proc.stdin.close()
|
||||
try:
|
||||
self._proc.wait(5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._proc.kill()
|
||||
45
src/voice_worker/vad.py
Normal file
45
src/voice_worker/vad.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""Streaming Silero VAD (the v6 model bundled with faster-whisper), one state per speaker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .segmenter import WINDOW
|
||||
|
||||
_CONTEXT = 64
|
||||
|
||||
|
||||
class SileroVad:
|
||||
"""Owns the ONNX session; ``stream()`` gives each speaker its own recurrent state."""
|
||||
|
||||
def __init__(self, path: str | None = None):
|
||||
import onnxruntime
|
||||
if path is None:
|
||||
from faster_whisper.utils import get_assets_path
|
||||
path = os.path.join(get_assets_path(), "silero_vad_v6.onnx")
|
||||
opts = onnxruntime.SessionOptions()
|
||||
opts.inter_op_num_threads = 1
|
||||
opts.intra_op_num_threads = 1
|
||||
opts.enable_cpu_mem_arena = False
|
||||
opts.log_severity_level = 4
|
||||
self.session = onnxruntime.InferenceSession(path, providers=["CPUExecutionProvider"], sess_options=opts)
|
||||
|
||||
def stream(self) -> "SileroStream":
|
||||
return SileroStream(self.session)
|
||||
|
||||
|
||||
class SileroStream:
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.h = np.zeros((1, 1, 128), dtype=np.float32)
|
||||
self.c = np.zeros((1, 1, 128), dtype=np.float32)
|
||||
self.context = np.zeros(_CONTEXT, dtype=np.float32)
|
||||
|
||||
def prob(self, window: np.ndarray) -> float:
|
||||
assert len(window) == WINDOW
|
||||
x = np.concatenate([self.context, window.astype(np.float32, copy=False)])[None, :]
|
||||
out, self.h, self.c = self.session.run(None, {"input": x, "h": self.h, "c": self.c})
|
||||
self.context = x[0, -_CONTEXT:]
|
||||
return float(np.asarray(out).reshape(-1)[0])
|
||||
148
src/voice_worker/voice_worker.spec.md
Normal file
148
src/voice_worker/voice_worker.spec.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# Voice worker spec (v2 M1)
|
||||
|
||||
The voice worker is the Python process that turns many Discord speakers' audio into text and the
|
||||
assistant's reply text into speech. The Electron app's Discord voice core talks to it over one local
|
||||
WebSocket. Design background lives in `docs/v2/voice-and-llm.md` and `docs/v2/architecture.md`.
|
||||
|
||||
## Principles
|
||||
|
||||
- **Local and private.** The server binds to a loopback address only and refuses any other host. Every
|
||||
connection must present the token the app generated; the token comes from the environment
|
||||
(`JARVIS_VOICE_TOKEN`), never from the command line, so it does not show in process listings. Logs
|
||||
carry timings, sizes and counts, never transcript or reply text.
|
||||
- **One shared model.** A single faster-whisper model serves every speaker. Speakers that need
|
||||
transcription at the same moment go through the model in one batch.
|
||||
- **Finals before partials.** A finished utterance is always transcribed before any live caption.
|
||||
- **Language-agnostic.** Nothing in the worker matches words. The STT language is a setting (`null`
|
||||
means detect per utterance); sentence splitting uses punctuation only.
|
||||
- **Engines are pluggable.** STT, VAD and TTS sit behind small interfaces so the logic is tested with
|
||||
fakes and the real models are tested separately.
|
||||
|
||||
## Running
|
||||
|
||||
```
|
||||
JARVIS_VOICE_TOKEN=<secret> python -m voice_worker --host 127.0.0.1 --port 8771 \
|
||||
[--stt-model large-v3-turbo] [--stt-device cuda] [--stt-compute int8_float16] \
|
||||
[--melo-python <path to the MeloTTS venv python>] [--melo-device cuda] [--melo-speed 1.5]
|
||||
```
|
||||
|
||||
Run from `src/` (or with `src/` on `PYTHONPATH`) in a venv built from `voice_worker/requirements.txt`. MeloTTS needs its own Python 3.11 venv
|
||||
(transformers 4.27), so it runs as a child process (`voice_worker/melo_child.py`) under
|
||||
`--melo-python`. Without `--melo-python` the worker has no TTS and answers `tts` requests with an
|
||||
error. Both models load and warm up once at start; `hello_ok` reports whether each is ready.
|
||||
|
||||
## Protocol
|
||||
|
||||
Text frames are JSON objects with a `type`. Binary frames start with a one-byte kind.
|
||||
|
||||
### Handshake
|
||||
|
||||
The first frame must be `hello` within 5 seconds, otherwise the worker closes with code 4400. A wrong
|
||||
token closes with 4401.
|
||||
|
||||
```
|
||||
-> {"type": "hello", "token": "...",
|
||||
"audio": {"rate": 48000, "channels": 2}, // incoming PCM format: rate 16000|48000, channels 1|2
|
||||
"tts": {"rate": 48000, "channels": 2}, // outgoing PCM format (any rate, channels 1|2)
|
||||
"stt": { ...settings, see config... }} // optional
|
||||
<- {"type": "hello_ok", "stt_ready": true, "tts_ready": true,
|
||||
"audio": {...}, "tts": {...}, "stt": { ...effective settings... }}
|
||||
```
|
||||
|
||||
### STT
|
||||
|
||||
```
|
||||
-> binary 0x01 | u8 n | speaker id (n bytes UTF-8) | PCM16LE samples in the hello "audio" format
|
||||
-> {"type": "speaking_end", "speaker": "..."} // Discord speaking stopped for this speaker
|
||||
-> {"type": "config", ...any STT settings...} // takes effect immediately
|
||||
<- {"type": "speech_start", "speaker": "...", "utt": 3}
|
||||
<- {"type": "partial", "speaker": "...", "utt": 3, "text": "..."}
|
||||
<- {"type": "final", "speaker": "...", "utt": 3, "text": "...", "end_reason": "silence",
|
||||
"audio_ms": 2310, "wait_ms": 160, "stt_ms": 120}
|
||||
```
|
||||
|
||||
`utt` counts utterances per speaker. `final` always closes an utterance that sent `speech_start`, even
|
||||
when the text is empty (noise that Whisper rejected). `wait_ms` is from the moment the end was decided
|
||||
to the moment the final was sent; `stt_ms` is the model time of the batch it went through.
|
||||
|
||||
STT settings (all optional in `hello` and `config`):
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `partials` | `true` | Send live captions. `false` drops queued partials and stops new ones; finals continue. The app turns it off while the LLM answers during a game. |
|
||||
| `partial_interval_ms` | 400 | At most one partial per speaker per interval, only when audio grew. |
|
||||
| `end_silence_ms` | 300 | Trailing VAD silence that ends an utterance. Range 100-2000. |
|
||||
| `final_beam` | 2 | Beam size for finals (partials always use 1). Range 1-5. |
|
||||
| `language` | `"ko"` | Whisper language code, or `null` to detect per utterance. |
|
||||
| `hotwords` | `[]` | Words (wake words, names) passed to Whisper as a hint. |
|
||||
|
||||
### Utterance rules
|
||||
|
||||
Each speaker's audio is mixed to mono, resampled to 16 kHz with a streaming filter, and run through
|
||||
its own streaming Silero VAD (512-sample windows, state kept between frames).
|
||||
|
||||
- **Start**: the first window with speech probability at or above 0.5. The 200 ms before it are kept.
|
||||
- **speech_start** is sent once the utterance holds 250 ms of speech windows. An utterance that ends
|
||||
before that is dropped without any message (a click or a cough).
|
||||
- **Speech continues** while windows stay at or above 0.35 (hysteresis); a quieter window counts as
|
||||
silence.
|
||||
- **End**, with `end_reason`:
|
||||
- `silence`: trailing silence reached `end_silence_ms`.
|
||||
- `speaking_end`: the app sent `speaking_end`. Discord stops sending packets when a user stops
|
||||
talking, so the worker cannot wait for silence that never arrives.
|
||||
- `idle`: no audio arrived for `end_silence_ms` (a missed `speaking_end`).
|
||||
- `max_length`: the utterance reached 28 seconds (Whisper's window). The next audio starts a new
|
||||
utterance.
|
||||
- The final clip keeps at most 200 ms of trailing silence.
|
||||
- Before transcription the clip is peak-normalised to 0.9 with the gain capped at 10x.
|
||||
|
||||
### Scheduling
|
||||
|
||||
One thread owns the STT model and loops:
|
||||
|
||||
1. If any finals are waiting, take all of them (up to 16) and transcribe in one batch with
|
||||
`final_beam`.
|
||||
2. Otherwise take up to 2 waiting partials and transcribe them in one batch with beam 1. A speaker
|
||||
has at most one waiting partial; a newer request replaces the older one and goes to the back of the
|
||||
line, so speakers take turns.
|
||||
|
||||
Whisper's encoder always runs on a full 30-second window, so its cost grows with every clip in a batch
|
||||
(measured on an RTX 5050: 0.2 s for one clip, 2.1 s for ten). A large partial batch would make a final
|
||||
wait seconds behind it; two clips keep that wait to about one clip's time. With many people talking,
|
||||
captions fall behind and only the newest audio per speaker is transcribed.
|
||||
|
||||
Batches are grouped by decode settings (beam, language, hotwords). A partial whose utterance has
|
||||
already ended, or that is older than the last partial sent, is dropped. Whisper output is rejected
|
||||
(empty text) when `no_speech_prob >= 0.5` or the confidence (`avg_logprob + 1`) is below 0.3, the
|
||||
same gate as v1.
|
||||
|
||||
### TTS
|
||||
|
||||
```
|
||||
-> {"type": "tts", "id": "r1", "text": "...", "more": false} // more=true: more text follows for r1
|
||||
-> {"type": "tts_cancel", "id": "r1"}
|
||||
<- binary 0x02 | u8 n | id (n bytes UTF-8) | u32 LE seq | PCM16LE in the hello "tts" format
|
||||
<- {"type": "tts_done", "id": "r1", "chunks": 3, "cancelled": false, "failed": false}
|
||||
```
|
||||
|
||||
Text is split into sentences on punctuation only: a run of newlines, CJK terminators (`。!?…`), or
|
||||
ASCII terminators followed by whitespace, a closing quote or bracket, or the end of the text, so
|
||||
decimals, versions and URLs stay whole. Fragments under 5 characters are merged into a neighbour.
|
||||
With `more=true` the worker synthesises every complete sentence at once and holds the unfinished tail
|
||||
until more text or `more=false` arrives (a short last fragment is then spoken on its own, because the
|
||||
sentence before it has already gone out). One audio chunk is sent per sentence, in order, as soon as it
|
||||
is ready. Requests are served first come, first served by one TTS engine. `tts_cancel` drops the
|
||||
request's unsent sentences, and `tts_done` follows with `cancelled: true`. A sentence that fails to
|
||||
synthesise is reported with `error` (`code: "tts_failed"`) and the request ends with `failed: true`.
|
||||
|
||||
### Errors
|
||||
|
||||
`{"type": "error", "code": "...", "message": "...", "id": "..."}`. Codes: `bad_message` (unknown type,
|
||||
bad JSON, bad field), `bad_frame` (malformed binary frame), `tts_unavailable`, `tts_failed`. Errors
|
||||
never close the connection after the handshake.
|
||||
|
||||
## Debug logging
|
||||
|
||||
`debug_log(..., "voice_worker")` at: connection accepted or refused, settings changed, utterance end
|
||||
(speaker, reason, length), each STT batch (kind, size, model time), each TTS sentence (length, time),
|
||||
cancel, and engine failures.
|
||||
Reference in New Issue
Block a user