Files
capri-core-rust/crates/capri-voice/README.md
T
2026-11-11 20:20:48 +01:00

148 lines
8.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# capri-voice
Capri's voice features, all in Rust (no Python, no venv, no package manager at runtime):
microphone, wake phrase, speech recognition, Capri's spoken voice, voice effects, subtitle timing,
mouth levels, music listening with BPM, and call audio through a PipeWire virtual cable.
Ported from CapriCore 1.0.4 (`docs/spec/07-voice-audio.md`), GPL-3.0-only.
| Area | Module | Capri source |
|---|---|---|
| Microphone capture (cpal, or a named PipeWire source via `parec`), 16 kHz frames, level | `capture` | `renderer/microphone*.mjs`, `audio-input-settings.mjs` |
| VAD (Silero v5 through ONNX Runtime) and utterance segmentation | `segment` | `asr_runtime/recognition.py` |
| Wake phrase "Capri" / "Hey, Capri", command window, follow-up | `wake`, `mic` | `wake-phrase.mjs`, `microphone-service.mjs` |
| Echo guard, "stop", "microphone off", barge-in | `echo`, `mic` | `microphone-service.mjs` |
| Recognition (whisper.cpp), vocabulary prompt, word boundaries | `asr` | `asr_runtime/*` |
| Capri's voice (Chatterbox ONNX + Capri reference voice) | `tts` | `voice_runtime/*` |
| Sentence chunking, spoken text, follow-up question test | `text` | `renderer/speech-text.mjs`, `voice-follow-up.mjs` |
| Playback queue, level, mouth layers, wake tone | `player` | `renderer/voice-player.mjs`, `avatar-mouth.mjs` |
| Effects DSP (presets, glide, glitch, room, delay) | `effects` | `renderer/voice-effects*.mjs` |
| Music detection (YAMNet), tempo and beat phase, decision | `music` | `music_runtime/*.py`, `music-listening-service.mjs` |
| Virtual call cable (`pactl`), call voice (`pacat`) | `call` | `call-audio-setup.mjs`, `virtual-cable-installer.mjs` |
| Pinned, resumable, SHA-256 verified downloads; install job | `download`, `install` | `model_download.py`, `speech-install-service.mjs` |
| Settings sections and egui pages | `settings`, `ui` | settings panels |
## Models (downloaded on demand into `<data>/speech/`, every file pinned by revision and SHA-256)
| Use | Model | Size |
|---|---|---|
| Recognition | whisper.cpp `ggml-large-v3-turbo-q5_0` (default), q8, `small-q5_1`, `base-q5_1` | 57–834 MB |
| Speech detection | Silero VAD v5 (Capri's pin) | 2.3 MB |
| English voice | `ResembleAI/chatterbox-turbo-ONNX` | 1.24 GB balanced / 3.3 GB full |
| Other 22 voice languages | `onnx-community/chatterbox-multilingual-ONNX` | 1.55 GB balanced / 3.3 GB full |
| Capri's voice identity | `references/neutral.wav` from the CapriCore v1.0.4 voice pack `capri-en-v1.zip` | 12.6 MB zip |
| Music | Qualcomm YAMNet ONNX (Capri's pin), into `<data>/models/music-detector/` | 13.9 MB zip |
Recognition mapping: Capri used Parakeet TDT 0.6B v2 for English, Parakeet v3 for 24 European languages and
faster-whisper large-v3-turbo otherwise. sherpa-onnx cannot be built here (bindgen needs libclang), so whisper
large-v3-turbo serves every language; Capri's hotwords become a whisper initial prompt. Expect slower recognition
on CPU than Parakeet INT8 (try `small-q5_1` on slow machines).
### Voice quality trade-offs (Chatterbox ONNX versus Capri 1.0.4 PyTorch)
- English: Capri used Chatterbox Turbo plus a **trained Capri LoRA adapter**. The ONNX export cannot load LoRA
weights, so the voice is cloned zero-shot from Capri's neutral reference: same character, less consistent timbre
and prosody than the trained voice.
- Multilingual: no classifier-free guidance (Capri used `cfg_weight 0.5`), exaggeration fixed at 0.5. Chinese
Cangjie conversion, Japanese kana conversion and Hebrew diacritics are not implemented (those three sound worse);
Korean jamo decomposition is.
- `balanced` quality uses 4-bit language models (and 4-bit Turbo speech encoder/embeddings); `full` is float32.
The vocoder (conditional decoder) is always float32.
- Inference runs on the CPU (ONNX Runtime). Capri used the GPU; expect roughly real time or slower on CPU for
long sentences. Sentences are synthesized while earlier ones play.
- No Perth watermark (Capri applied one).
- Sampling follows Capri (repetition penalty 1.2, temperature 0.8, top-k 1000, top-p 0.95, seed 417 per phrase,
800-token cap retried once with seed 418).
## Integration
### Public API
```rust
use capri_voice::{VoiceEvent, VoiceHandle};
let (voice, mut events) = VoiceHandle::start(store.clone); // inside the tokio runtime; opens nothing
```
`VoiceHandle` (alias `VoiceService`) is `Clone + Send + Sync`:
| Method | Use |
|---|---|
| `set_microphone(bool) -> Result<>` | owner toggle; off at every launch; error text is user-facing |
| `listen_now`, `typed_input` | composer mic button; owner typed (closes the command window) |
| `microphone_on`, `microphone_level -> f32` | UI state, level meter 0..1 |
| `input_devices`, `refresh_devices` | device menu (ids are exact; `pulse:<source>` for PipeWire sources) |
| `set_voice_enabled(bool) -> Result<>` | speaker button; loads the model in the background; off frees its memory |
| `begin_turn(turn_id, from_microphone)`, `speak_delta(turn_id, text)`, `finish_turn(turn_id)` | reply speech |
| `stop_speaking` | immediate stop (cancel, mute) |
| `preview_voice(Option<VoiceEffects>)` | Capri's preview sentence |
| `audio_level -> f32`, `mouth -> Mouth`, `speaking` | per-frame avatar feed |
| `set_music(bool)`, `music_state` | music listening (explicit owner action only) |
| `install_speech(recognition, voice)`, `cancel_install`, `install_status` | setup UI; progress also as events |
| `create_call_cable`, `remove_call_cable`, `set_share_replies(bool)`, `call_active` | call audio (owner approval) |
| `shutdown` | app exit: stops capture, unloads the cable |
`settings_ui(ui, &store, &voice)` draws the Speech, Microphone, Voice model, Voice effects, Music listening and
Call audio pages (plain egui).
### Wiring the conversation
```rust
// TurnEvents from Engine::submit → speech
match event {
TurnEvent::Started { turn_id, .. } => voice.begin_turn(&turn_id, origin_was_microphone),
TurnEvent::Delta { turn_id, text } => voice.speak_delta(&turn_id, &text),
TurnEvent::Completed { turn_id, .. } => voice.finish_turn(&turn_id), // arms follow-up listening after a question
TurnEvent::Failed { .. } | TurnEvent::Cancelled { .. } => voice.stop_speaking,
TurnEvent::Avatar { .. } => {}
}
// When the owner types a message: voice.typed_input before Engine::submit.
// Voice events → app
while let Some(event) = events.recv.await {
match event {
VoiceEvent::Submit { text, .. } => { /* Engine::submit(&text, …) with origin = microphone */ }
VoiceEvent::Interrupt => engine.cancel, // barge-in; speech already stopped
VoiceEvent::Transcript { text, is_final, .. } => { /* composer preview; empty + !is_final clears it */ }
VoiceEvent::Speaking { mouth, .. } => avatar.speaking(mouth != Mouth::Closed),
VoiceEvent::Subtitle { text, duration_ms, .. } => { /* page subtitles over the sentence */ }
VoiceEvent::MusicState(m) => { /* dance: m.playing, m.bpm, m.beat_at_ms */ }
VoiceEvent::Wake { .. } | VoiceEvent::Microphone(_) | VoiceEvent::Voice(_) => { /* UI badges */ }
VoiceEvent::Error { message, .. } => { /* notice */ }
_ => {}
}
}
```
Echo: Capri relied on Chromium's echo cancellation. Here only the text echo guard exists; with speakers (not a
headset) load PipeWire's echo canceller and select its source as the microphone:
`pactl load-module module-echo-cancel aec_method=webrtc source_name=capri_ec_source sink_name=capri_ec_sink`.
### Settings sections (`settings.json → sections`)
`speech` (`SpeechSettings`: recognition language, pause, wake phrase, auto send, barge-in, follow-up, wake sound,
microphone device, whisper model, GPU, threads), `voice` (`VoiceSettings`: speech language, quality, threads),
`voiceEffects` (`VoiceEffects`), `music` (`MusicSettings`), `callAudio` (`CallSettings`). Microphone, voice output,
music capture and the call cable are session-only and never saved.
### Install steps for the owner
1. Nothing to install system-wide on this machine: `parec`, `pacat` and `pactl` come from `libpulse`
(present), ONNX Runtime is bundled by `ort`, whisper.cpp is compiled in.
2. In Settings → Speech: "Install speech recognition" (547 MB by default).
3. In Settings → Voice model: "Install Capri's voice for this language" (1.2–1.6 GB balanced).
4. Music listening downloads its 14 MB detector the first time it is started.
GPU: build with `--features capri-voice/cuda` (needs the CUDA toolkit for whisper.cpp) to make the recognition
GPU switch effective. The voice stays on CPU (shortcut: register ONNX Runtime's CUDA provider in `tts::session`).
### Not ported
System audio mixed into recognition, "Ask Capri in call" model routing (belongs to the agent),
voice training, wake sound `file`/`voice` modes, music artwork pack (avatar crate).
### Tests
`cargo test -p capri-voice` uses synthetic audio and mocked HTTP only. Opt-in checks with real models:
`CAPRI_VOICE_SPEECH_DIR=<data>/speech`, `CAPRI_VOICE_DATA_DIR=<tmp>`, `CAPRI_VOICE_TOKENIZERS=<dir>` then
`cargo test -p capri-voice -- --ignored`.