Architecture¶
AbstractVoice 0.10.x is built around a small public facade and engine adapters
that keep optional heavy runtimes out of the default path.
Use docs/api.md for the supported integrator contract, docs/repl_guide.md
for REPL behavior and commands, and docs/known-issues.md for current release
caveats.
For acronyms used here (TTS/STT/VAD/VM/MM), see docs/acronyms.md.
TL;DR¶
abstractvoice.VoiceManageris the orchestration façade (abstractvoice/vm/*).- TTS (default): TTS adapter registry resolves
openai/autotoOpenAICompatibleTTSAdapter; local opt-in engines include Piper and Supertonic 3; playback usesAdapterTTSEngine->NonBlockingAudioPlayerwhen local audio output is requested. - STT (default):
openai/autoroutestranscribe_*()andlisten()recognition toOpenAICompatibleSTTAdapter. Local microphone capture still usesVoiceRecognizer→VoiceDetectorand can pass captured audio to the selected STT adapter. - STT (local):
faster_whisper(CTranslate2, CUDA or CPU),mlx-whisper(Apple GPU) andtransformers-asr(Whisper, Qwen3-ASR, Cohere Transcribe) implement the sameSTTAdaptercontract as the remote adapter. - Voice cloning (optional):
VoiceCloner+ clone store + engine backends (omnivoice|f5_tts|chroma|audiodit|qwen3-tts|openai|openai-compatible); new local clones default to OmniVoice. The clone store also exposes the read-only built-in voice pack (70 Qwen3-TTS voices stored as clone prompts inabstractvoice/assets/voices/qwen3_tts/; see Built-in voices). - Voice modes are implemented by wiring TTS playback callbacks to recognizer controls (
abstractvoice/vm/core.py).
Component diagrams¶
Four small diagrams, from the whole down to each path. Names are the classes in the code map below.
Components¶
VoiceManager routes speech to the TTS engine or, for a cloned voice id, to the cloner; listening and
transcription go through the recognizer. Playback can feed the recognizer for echo cancellation.
flowchart TB
App["Your app · CLI · REPL"] <--> VM["VoiceManager<br/>vm/manager.py + mixins"]
VM -->|"speak() · speak_to_*()"| TTSEngine["AdapterTTSEngine"]
VM -->|"speak(voice=id)"| Cloner["VoiceCloner"]
VM -->|"listen() · transcribe_*()"| Rec["VoiceRecognizer"]
TTSEngine --> TTSAdapter["TTSAdapter<br/>one per engine"]
TTSEngine --> Player["NonBlockingAudioPlayer"]
Cloner --> Store["VoiceCloneStore"]
Cloner --> CloneEngine["Clone engine<br/>one per voice"]
Rec --> STTAdapter["STTAdapter<br/>one per engine"]
Player -. "on_audio_chunk, optional AEC" .-> Rec
Speaking with a base engine¶
Every engine implements TTSAdapter. Qwen3-TTS picks its backend at load (ADR 0008).
flowchart TB
TTSAdapter["TTSAdapter"] --> Simple["Piper · Supertonic 3 · OmniVoice<br/>AudioDiT · OpenAI-compatible"]
TTSAdapter --> Qwen3["Qwen3TTSAdapter"]
Qwen3 --> Runtime["Qwen3TTSRuntime<br/>backend policy, ADR 0008"]
Runtime -->|"Apple silicon"| MLX["MLX port<br/>one generation per reply,<br/>codec-frame streaming"]
Runtime -->|"CUDA · CPU"| Torch["PyTorch model<br/>ADR 0005 device policy"]
Speaking with a cloned voice¶
The store holds your clones and the read-only built-in voice pack; each voice names the engine that renders it.
flowchart TB
Cloner["VoiceCloner"] --> Store["VoiceCloneStore"]
Store --> UserVoices[("your clones<br/>user data dir")]
Store --> Builtin[("built-in voice pack<br/>read-only clone prompts")]
Cloner --> OtherClone["OmniVoice · OpenF5 · Chroma<br/>AudioDiT · remote"]
Cloner --> QwenClone["Qwen3 clone engine"]
QwenClone --> Runtime["Qwen3TTSRuntime<br/>MLX or PyTorch"]
QwenClone --> Check["Speaker check<br/>speaker_similarity() per generation,<br/>delay line before delivery"]
Check -->|"the clone"| Out["audio chunks"]
Check -->|"opening under the bar"| Retry["regenerate once,<br/>then keep that take"]
Retry --> Out
Check -->|"later window under the block bar"| Rec["recorded in low_windows,<br/>playback continues"]
Rec --> Out
Listening¶
Every speech-to-text engine implements STTAdapter; the recognizer adds the microphone and voice activity detection.
flowchart TB
Rec["VoiceRecognizer"] --> In[("sounddevice<br/>InputStream")]
Rec --> VAD["VoiceDetector<br/>webrtcvad"]
Rec --> STTAdapter["STTAdapter"]
STTAdapter --> FW["FasterWhisperAdapter<br/>CUDA · CPU"]
STTAdapter --> MW["MLXWhisperAdapter<br/>Apple GPU"]
STTAdapter --> TA["TransformersASRAdapter<br/>Whisper · Qwen3-ASR · Cohere"]
STTAdapter --> RemoteSTT["OpenAICompatibleSTTAdapter"]
Player["NonBlockingAudioPlayer"] -. "on_audio_chunk, optional AEC" .-> Rec
Code map (evidence)¶
Start points (in call order):
- Public façade:
abstractvoice/voice_manager.py→abstractvoice/vm/manager.py - TTS orchestration:
abstractvoice/vm/tts_mixin.py - STT/listening orchestration:
abstractvoice/vm/stt_mixin.py - Playback/lifecycle wiring + voice modes:
abstractvoice/vm/core.py
TTS implementation:
- TTS adapter interface:
abstractvoice/adapters/base.py - Piper adapter:
abstractvoice/adapters/tts_piper.py - Supertonic adapter/runtime:
abstractvoice/adapters/tts_supertonic.py,abstractvoice/supertonic/runtime.py - Remote OpenAI-compatible TTS adapter:
abstractvoice/adapters/tts_openai_compatible.py+abstractvoice/adapters/openai_compatible_http.py - TTS engine selection (registry):
abstractvoice/adapters/tts_registry.py - Local model presence (filesystem only, no engine imports):
abstractvoice/local_models.py - Engine runtime status (
find_speconly, no engine imports):abstractvoice/engine_runtime.py - AudioDiT adapter/runtime:
abstractvoice/adapters/tts_audiodit.py,abstractvoice/audiodit/runtime.py - OmniVoice adapter/runtime:
abstractvoice/adapters/tts_omnivoice.py,abstractvoice/omnivoice/runtime.py - Qwen3-TTS adapter/runtime:
abstractvoice/adapters/tts_qwen3_tts.py,abstractvoice/qwen3_tts/(vendored 12Hz model core + codec + runtime; seeabstractvoice/_hf_compat.pyfor the transformers-version seams shared withqwen3_asr). Backend selection (ADR 0008):abstractvoice/qwen3_tts/backend.pypicksmlxon Apple silicon whenmlxis importable, elsetorch; the MLX port lives inabstractvoice/qwen3_tts/mlx/(talker, codec with a streaming decoder, speaker encoder,tokenizers-based text tokenizer, strict weight loading + on-load quantization) and streams codec frames of one generation per reply through the runtime'sstream_*methods; the adapter exposes that asnative_frame_streaming, whichvm/tts_mixin.pyandcloning/engine_qwen3_tts.pyhonour by passing a whole reply as one segment. - TTS engine wrapper (back-compat contract):
abstractvoice/tts/adapter_tts_engine.py - Low-latency audio player:
abstractvoice/tts/tts_engine.py
STT implementation:
- Mic/VAD/STT loop:
abstractvoice/recognition.py - VAD wrapper:
abstractvoice/vad/voice_detector.py - faster-whisper adapter (CTranslate2: CUDA or CPU):
abstractvoice/adapters/stt_faster_whisper.py; device and compute type:abstractvoice/compute/device.py(resolve_faster_whisper_device), CUDA 12 library preparation:abstractvoice/compute/windows_cuda.py - mlx-whisper adapter (Apple GPU, one dedicated MLX thread):
abstractvoice/adapters/stt_mlx_whisper.py - Remote OpenAI-compatible STT adapter:
abstractvoice/adapters/stt_openai_compatible.py - Stop phrase normalization:
abstractvoice/stop_phrase.py
Optional features:
- AEC (extra):
abstractvoice/aec/webrtc_apm.py(used byabstractvoice/recognition.py) - Voice cloning (extra):
abstractvoice/cloning/*(manager/engines/store; used byabstractvoice/vm/tts_mixin.py) - Remote cloning bridge:
abstractvoice/cloning/engine_remote.py - AbstractCore plugin:
abstractvoice/integrations/abstractcore_plugin.py
Data flows¶
TTS (playback)¶
1) Your app calls VoiceManager.speak() (abstractvoice/vm/tts_mixin.py).
2) Default path (OpenAI remote): AdapterTTSEngine.speak() (abstractvoice/tts/adapter_tts_engine.py)
- synthesizes audio via the selected adapter (default OpenAICompatibleTTSAdapter, abstractvoice/adapters/tts_openai_compatible.py)
- enqueues audio into NonBlockingAudioPlayer.play_audio() (abstractvoice/tts/tts_engine.py)
3) Playback runs in the PortAudio callback thread (sounddevice.OutputStream).
Pause/resume is implemented by toggling a lock-protected paused flag inside the audio callback (see NonBlockingAudioPlayer.pause()/resume()).
STT (microphone listening)¶
1) Your app calls VoiceManager.listen() (abstractvoice/vm/stt_mixin.py).
2) A VoiceRecognizer instance is created (abstractvoice/recognition.py) with:
- a VAD (VoiceDetector, abstractvoice/vad/voice_detector.py)
- the configured STT adapter (OpenAI remote by default; FasterWhisperAdapter when explicitly selected)
3) The recognizer thread opens a sounddevice.InputStream and loops:
- optional AEC preprocessing
- VAD detection and buffering
- transcription and callback emission
Stop phrase behavior:
- The recognizer checks stop phrases on completed transcriptions, and can also run a low-rate rolling detector while normal transcriptions are suppressed (see _maybe_detect_stop_phrase_continuous() in abstractvoice/recognition.py).
Coordination: voice modes while speaking¶
AbstractVoice wires TTS lifecycle to listening behavior in abstractvoice/vm/core.py:
tts_engine.on_playback_start→VoiceManagerCore._on_tts_start()tts_engine.on_playback_end→VoiceManagerCore._on_tts_end()
set_voice_mode(mode) is public (abstractvoice/vm/stt_mixin.py). Modes:
- full: keep listening; allow barge‑in (interrupt TTS on detected speech). Intended for AEC/headset; speakers may self-interrupt (mitigated by echo gating heuristics in
abstractvoice/recognition.py). - wait: pause mic processing while speaking (
VoiceRecognizer.pause_listening()/resume_listening()). - stop: keep mic processing, but suppress normal transcriptions while speaking and disable speech-triggered interruption; a stop-phrase detector remains active (
pause_transcriptions()+ rolling stop detector). - ptt: push‑to‑talk profile (thresholds tuned for short utterances). While speaking it behaves like stop mode; capture is controlled by the integrator/REPL.
Design decisions behind these modes:
- ADR 0001: docs/adr/0001-local_assistant_out_of_box.md
- ADR 0002: docs/adr/0002_barge_in_interruption.md
Threading model (practical)¶
- Main thread: your app / REPL.
- Recognizer thread: mic capture + VAD + STT (
VoiceRecognizer._recognition_loop()). - Audio callback thread: speaker output callback (
NonBlockingAudioPlayer._audio_callback()). - Cloned TTS synthesis thread (optional): streaming/cancellation worker in
abstractvoice/vm/tts_mixin.py.
Remote-first and offline model policy¶
The library default uses OpenAI remote audio and requires OPENAI_API_KEY or
remote_api_key=...; it does not download local model weights. Local engines
are explicit (tts_engine="piper", tts_engine="supertonic",
stt_engine="faster_whisper", etc.) and
respect allow_downloads. The REPL creates VoiceManager(...,
allow_downloads=False) so local engines never fetch weights implicitly.
The CLI and web examples use an additional install-aware TTS resolver:
installed Supertonic first, installed Piper second, then OpenAI remote. That
keeps plain abstractvoice remote/OpenAI while full local install profiles
such as abstractvoice[all-apple] and abstractvoice[all-gpu] launch on
Supertonic without changing the library/server VoiceManager() default.
Runtime base-TTS switching goes through VoiceManager.set_tts_engine(...).
That replaces the adapter, rewires the playback wrapper, and resets the active
profile to the default for the engine/language so stale Piper/Supertonic/remote
voice selections do not bleed across engine changes.
AdapterTTSEngine.warmup_audio_output() can open the playback stream before
the first utterance; NonBlockingAudioPlayer prefers the hardware default
output sample rate and resamples synthesized audio when needed, avoiding slow
first-call CoreAudio negotiation on macOS.
The output device itself is resolved live, not taken from PortAudio's
launch-time snapshot: abstractvoice/tts/audio_devices.py asks the system
(the CoreAudio HAL on macOS) for the current default or for a device named by
its stable UID, and the player opens it by explicit index, re-resolving before
each utterance. If that device cannot be opened, playback falls back to the
system default only and reports it through on_output_device_problem; a
stream the OS stopped (sleep, USB interruption) is reopened on the next
utterance without losing queued audio.
NonBlockingAudioPlayer.playback_status() returns a snapshot of
frames_written, pending_frames, is_playing, paused, stream_active,
sample_rate, callback_error, and recovering_output. Frame counts refer
to samples submitted to the output, not proof of acoustic delivery. A host
can use progress to suspend stall accounting during pause, and call
recover_stream(cancelled=...) once from its playback worker when output
stops progressing. AbstractVoice owns device and queue recovery; the host
owns the generation, pause policy, retry budget and user reporting.
Recovery closes the old output before collecting its unsubmitted suffix and
queued arrays, converts those arrays if the output sample rate changes,
and preserves pause state. It never refreshes global PortAudio, because that
would invalidate microphone streams. The cancellation predicate is checked
before and after opening and resampling so an outgoing generation cannot be
requeued after cancellation. A disconnected device can still lose frames
already submitted to its hardware buffer; recovery does not replay those
frames or restart the message. Optional callback hooks run outside the
short buffer lock, and progress snapshots use constant-time queue accounting.
For GUI cancellation, try_stop_stream() first requests cancellation and
returns False if another control operation owns the output lock. The host
can detach that player and finish stop_stream() on a worker; the in-flight
open or recovery observes the cancellation before enqueueing any more audio.
An uncontended try_stop_stream() performs the normal output stop itself.
Discovery follows the same policy from the other direction: asking which providers and models are
available is a filesystem question, answered by abstractvoice/local_models.py without importing an
engine runtime or loading weights. A local engine is discoverable when its runtime is importable and
at least one of its models is cached; engines that download Hugging Face repos are matched against
the shared HF cache, while piper and supertonic expose their own cache probes
(cached_piper_model_ids, cached_piper_voice_profiles, is_supertonic_cached). Remote providers
are probed concurrently under a single discovery budget, so a listing costs the slowest provider
rather than the sum of their timeouts, and a provider that does not answer is reported as unreachable
rather than as one with nothing to offer.
Explicit prefetch entry points:
- python -m abstractvoice download ... (abstractvoice/__main__.py)
- abstractvoice-prefetch ... (abstractvoice/prefetch.py)
Supertonic 3 is implemented as an internal ONNX adapter, not through
Supertone's Python SDK. Its artifacts are fetched from
Supertone/supertonic-3 into ~/.cache/abstractvoice/supertonic-3 with
--supertonic; profile metadata (M1-M5, F1-F5) is available without
loading or downloading the model.
See docs/installation.md and docs/model-management.md.
Optional: AbstractCore plugin integration¶
When installed alongside abstractcore, AbstractVoice exposes a capability plugin via the entry point:
pyproject.toml→[project.entry-points."abstractcore.capabilities_plugins"]- Implementation:
abstractvoice/integrations/abstractcore_plugin.py - Artifact store adapter (AbstractRuntime-compatible, duck-typed):
abstractvoice/artifacts.py
It provides:
- a voice backend (TTS+STT) that can optionally store generated audio into an artifact_store
- an audio backend (STT) for transcription-only use
The voice backend's tts_stream(...) turns VoiceManager.speak_to_audio_segments() into
transport-safe events: one standalone WAV segment per audio event, at most 2 s of
audio each (STREAM_LINE_MAX_SECONDS), each naming its text segment and that segment's
span of the request text; a segment_end event after each segment's last audio; then a
done (or cancelled) event with the engine's metrics. The engine marks its own
generations (Qwen3-TTS through its delivery outbox, base engines per sentence group);
SegmentLocator maps each one back to the caller's text, so a client resumes a broken
stream from the last segment it received whole, exactly at that boundary (ADR 0009). See
docs/api.md for the event fields and the retry rule.
flowchart LR
Core["AbstractCore<br/>core.voice.tts_stream()"] --> Cap["_VoiceCapability.tts_stream"]
Cap --> VM["VoiceManager<br/>speak_to_audio_segments()"]
Eng["engine generations<br/>SegmentStart, audio, SegmentEnd"] --> VM
VM -->|"SegmentLocator: text_start, text_end"| Cap
Cap --> Split["slices of at most 2 s"]
Split --> Audio["audio events<br/>sequence 0..n, segment, text_start, text_end"]
Cap --> End["segment_end event<br/>after each segment's last slice"]
Cap --> Done["done / cancelled event<br/>chunks, segments, metrics"]
The local FastAPI web UI (abstractvoice web) is a small example wrapper around
VoiceManager for quick browser testing. Its local /api/* routes map directly
to VoiceManager functions and include browser-only conveniences such as
assistant/user voice defaults. It also includes an example-only LLM bridge that
forwards one OpenAI-compatible chat request to a local provider such as Ollama;
the /v1/audio/* routes are smoke-test aliases.
AbstractCore owns the production HTTP server surface. When AbstractCore Server
is installed and running, these capability backends can power OpenAI-compatible
endpoints such as POST /v1/audio/speech and POST /v1/audio/transcriptions.
This is not required for using AbstractVoice as a standalone library.