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:
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