Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(tts): add Piper as the first on-device, keyless voice

Ruben Lütke78e7ec31a043
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.py
index a12feb39be..56c522dafd 100644
--- a/jarvis/plugins/tts/__init__.py
+++ b/jarvis/plugins/tts/__init__.py
@@ -694,6 +694,29 @@ def _build_provider(tts_cfg: Any, provider: str) -> Any:
speed=tts_cfg.speed,
)
+ if provider in ("piper-local", "piper"):
+ try:
+ from jarvis.plugins.tts.piper_local import PiperLocalTTS
+ except ImportError as exc:
+ raise RuntimeError(
+ f"TTS provider 'piper-local' configured, but the plugin is not "
+ f"importable: {exc}. Check that "
+ f"jarvis/plugins/tts/piper_local.py exists.",
+ ) from exc
+ # No voice_de/voice_en pass-through: a Piper voice IS a language, so the
+ # provider resolves the file from the turn's language itself. What it
+ # does carry over is the speaker PROFILE, derived from whichever curated
+ # voice the config already names — so switching to the local voice keeps
+ # the masculine/feminine choice the user made on their cloud provider
+ # instead of silently changing who is speaking (voice-profile
+ # continuity, 2026-07-17).
+ from jarvis.plugins.tts.curated_catalog import voice_gender
+
+ profile = voice_gender(getattr(tts_cfg, "voice_de", None)) or voice_gender(
+ getattr(tts_cfg, "voice_en", None)
+ )
+ return PiperLocalTTS(gender=profile, speed=tts_cfg.speed)
+
if provider not in ("gemini-flash-tts", "gemini-flash", "gemini"):
log.warning(
"Unknown TTS provider %r — falling back to gemini-flash-tts.",
diff --git a/jarvis/plugins/tts/piper_local.py b/jarvis/plugins/tts/piper_local.py
new file mode 100644
index 0000000000..096cb8b5d4
--- /dev/null
+++ b/jarvis/plugins/tts/piper_local.py
@@ -0,0 +1,263 @@
+"""On-device text-to-speech: Piper voices played through sherpa-onnx.
+
+The speaking half of the local voice path — the first TTS in this repo that
+needs no key and sends no text anywhere. Piper is the de-facto standard for
+offline neural speech: small VITS voices exported to ONNX, real time on a
+Raspberry Pi, and the only widely-used open family with genuine German voices
+(Kokoro, the prettier alternative, ships nine languages and German is not one).
+
+Two decisions worth stating, because both are easy to get wrong later:
+
+**Licensing.** Piper's own runtime moved from MIT to GPL-3 in October 2025
+(the project now lives at OHF-Voice/piper1-gpl). This repo is MIT, so the GPL
+library is NOT used: the voices are plain ONNX files, and sherpa-onnx
+(Apache-2.0) loads them. Do not "simplify" this by depending on piper1-gpl.
+
+**One voice speaks one language.** Unlike a cloud TTS, a Piper voice is
+monolingual. The pipeline resolves ONE output language per turn
+(``resolve_output_language``) and hands it here as a BCP-47 code; this provider
+maps it to the matching voice. That mapping is the whole reason the local voice
+can honour the runtime-language doctrine instead of answering German text in an
+English accent.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk
+
+log = logging.getLogger(__name__)
+
+#: int16 full scale — Piper emits float32 in [-1, 1]; the pipeline plays int16.
+_INT16_FULL_SCALE = 32767.0
+
+#: Speed factor handed to the synthesiser. 1.0 is the voice's natural pace.
+_DEFAULT_SPEED = 1.0
+
+
+class PiperLocalTTS:
+ """Local neural text-to-speech (keyless, on-device, multilingual by voice)."""
+
+ name = "piper-local"
+ supports_streaming = False
+ #: Which voice actually spoke last — read by the per-turn transcript label,
+ #: so a new provider that leaves these unset makes the label lie.
+ last_voice: str | None = None
+ last_voice_provider: str | None = None
+ #: Nothing spoken here leaves the machine. Mirrors the STT-side declaration
+ #: so a caller can ask the same question of both halves of the voice path.
+ runs_on_device = True
+
+ def __init__(
+ self,
+ *,
+ voice: str | None = None,
+ gender: str | None = None,
+ num_threads: int = 2,
+ speed: float = _DEFAULT_SPEED,
+ ) -> None:
+ self._preferred_voice = (voice or "").strip() or None
+ # Voice PROFILE rather than a single voice id: the pipeline may switch
+ # language between turns, and the replacement must be the same kind of
+ # speaker. Without this a language switch also switches sex, which is
+ # the BUG-086 complaint in a different provider.
+ self._gender = (gender or "").strip().lower() or "masculine"
+ self._num_threads = max(1, int(num_threads))
+ self._speed = float(speed) if speed and speed > 0 else _DEFAULT_SPEED
+ #: model_id -> loaded engine. Voices load lazily and stay cached; a
+ #: German-only conversation never pays for the Spanish voice.
+ self._engines: dict[str, Any] = {}
+ self._load_lock = asyncio.Lock()
+
+ # -- voice selection ----------------------------------------------------
+ def _catalog(self) -> dict[str, Any]:
+ from jarvis.speech.local_models import SHERPA_BUNDLES
+
+ return {
+ model_id: bundle
+ for model_id, bundle in SHERPA_BUNDLES.items()
+ if bundle.language
+ }
+
+ def _installed_voices(self) -> dict[str, Any]:
+ """Catalogued voices whose files are actually on this machine.
+
+ A voice that is merely *listed* is not offerable: picking it would fail
+ at synthesis time, which in a voice assistant means silence.
+ """
+ from jarvis.speech.local_models import bundle_present
+
+ return {
+ model_id: bundle
+ for model_id, bundle in self._catalog().items()
+ if bundle_present(model_id)
+ }
+
+ def _resolve_voice(
+ self, voice: str | None, language_code: str | None
+ ) -> str | None:
+ """Pick the voice for ONE turn: explicit request, else language + profile.
+
+ Returns None when nothing is installed — the caller then raises the
+ honest "no voice downloaded" error rather than emitting silence.
+ """
+ installed = self._installed_voices()
+ if not installed:
+ return None
+ requested = (voice or self._preferred_voice or "").strip()
+ if requested in installed:
+ return requested
+
+ language = (language_code or "").strip().lower().split("-", 1)[0]
+ candidates = [
+ model_id
+ for model_id, bundle in installed.items()
+ if not language or bundle.language == language
+ ]
+ if not candidates:
+ # The turn's language has no local voice. Speaking it in another
+ # language's accent is the wrong trade-off to make silently, but
+ # saying nothing is worse — so fall back and say so in the log.
+ log.warning(
+ "No local Piper voice is installed for language %r; using another "
+ "installed voice. Download the matching voice from the API-Keys "
+ "view to fix the accent.",
+ language or "unknown",
+ )
+ candidates = list(installed)
+ # Same speaker profile across languages where possible.
+ preferred = [
+ m for m in candidates if installed[m].gender == self._gender
+ ]
+ return (preferred or candidates)[0]
+
+ def list_voices(self, language: str | None = None) -> list[str]:
+ """Installed voices, optionally filtered by language."""
+ installed = self._installed_voices()
+ if language:
+ short = language.lower().split("-", 1)[0]
+ return [m for m, b in installed.items() if b.language == short]
+ return list(installed)
+
+ # -- engine -------------------------------------------------------------
+ def _build_engine(self, model_id: str) -> Any:
+ try:
+ import sherpa_onnx # noqa: PLC0415 — optional engine, lazy on purpose
+ except ImportError as exc:
+ raise RuntimeError(
+ "The local speech runtime (sherpa-onnx) is not installed, so the "
+ "on-device voice cannot speak. Install it from the API-Keys view."
+ ) from exc
+
+ from jarvis.speech.sherpa_models import model_paths
+
+ paths = model_paths(model_id)
+ onnx = next(
+ (p for name, p in paths.items() if name.endswith(".onnx")), None
+ )
+ tokens = paths.get("tokens.txt")
+ data_dir = paths.get("espeak-ng-data")
+ if onnx is None or tokens is None or data_dir is None:
+ raise RuntimeError(f"Voice '{model_id}' is not catalogued correctly.")
+ missing = [p.name for p in (onnx, tokens, data_dir) if not p.exists()]
+ if missing:
+ raise RuntimeError(
+ f"The voice '{model_id}' is not fully downloaded (missing: "
+ f"{', '.join(missing)}). Download it from the API-Keys view."
+ )
+
+ log.info("Loading local Piper voice %s", model_id)
+ config = sherpa_onnx.OfflineTtsConfig(
+ model=sherpa_onnx.OfflineTtsModelConfig(
+ vits=sherpa_onnx.OfflineTtsVitsModelConfig(
+ model=str(onnx),
+ tokens=str(tokens),
+ # espeak-ng's phoneme rules: how letters become sounds. A
+ # Piper voice cannot speak without them.
+ data_dir=str(data_dir),
+ ),
+ num_threads=self._num_threads,
+ provider="cpu",
+ ),
+ )
+ return sherpa_onnx.OfflineTts(config)
+
+ async def _engine_for(self, model_id: str) -> Any:
+ engine = self._engines.get(model_id)
+ if engine is not None:
+ return engine
+ async with self._load_lock:
+ engine = self._engines.get(model_id)
+ if engine is None:
+ engine = await asyncio.to_thread(self._build_engine, model_id)
+ self._engines[model_id] = engine
+ return engine
+
+ # -- synthesis ----------------------------------------------------------
+ async def synthesize(
+ self,
+ text: str,
+ voice: str | None = None,
+ language_code: str | None = None,
+ ) -> AsyncIterator[AudioChunk]:
+ """Speak *text* with the voice matching this turn's output language."""
+ spoken = (text or "").strip()
+ if not spoken:
+ return
+ model_id = self._resolve_voice(voice, language_code)
+ if model_id is None:
+ raise RuntimeError(
+ "No local voice is downloaded yet, so the on-device voice cannot "
+ "speak. Download the voices from the API-Keys view, or switch "
+ "voice output to a provider you have a key for."
+ )
+ engine = await self._engine_for(model_id)
+ audio = await asyncio.to_thread(engine.generate, spoken, 0, self._speed)
+
+ samples = np.asarray(audio.samples, dtype=np.float32)
+ if samples.size == 0:
+ log.warning("Local voice %s produced no audio for the turn.", model_id)
+ return
+ # Clip before scaling: a value beyond [-1, 1] would wrap around into
+ # loud noise once cast to int16.
+ pcm = (np.clip(samples, -1.0, 1.0) * _INT16_FULL_SCALE).astype(np.int16)
+ self.last_voice = model_id
+ self.last_voice_provider = self.name
+ yield AudioChunk(
+ pcm=pcm.tobytes(),
+ sample_rate=int(audio.sample_rate),
+ timestamp_ns=0,
+ channels=1,
+ )
+
+ async def _ensure_client(self) -> None:
+ """Warm-up hook the speech pipeline calls; loads the default voice.
+
+ Kept cheap and failure-tolerant: warming is an optimisation, and a host
+ with no voices downloaded must still boot and tell the user why it
+ cannot speak when a turn actually needs it.
+ """
+ model_id = self._resolve_voice(None, None)
+ if model_id is None:
+ return
+ try:
+ await self._engine_for(model_id)
+ except Exception as exc: # noqa: BLE001 — warm-up must never break boot
+ log.debug("Local voice warm-up skipped (%s).", exc)
+
+ async def aclose(self) -> None:
+ """Drop the loaded voices so a switched-away provider frees its memory."""
+ self._engines.clear()
+
+
+def voice_files(model_id: str) -> dict[str, Path]:
+ """Paths of one voice's files — exposed for diagnostics and tests."""
+ from jarvis.speech.sherpa_models import model_paths
+
+ return model_paths(model_id)
diff --git a/jarvis/speech/local_install.py b/jarvis/speech/local_install.py
index 3daa412523..8761fdb9bd 100644
--- a/jarvis/speech/local_install.py
+++ b/jarvis/speech/local_install.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import importlib
import logging
import threading
+from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Literal
@@ -71,7 +72,9 @@ def _install_engine(entry: LocalProvider) -> tuple[bool, str]:
return install_pip_package(entry.pip_package, only_binary=True)
-def _download_model(entry: LocalProvider) -> None:
+def _download_model(
+ entry: LocalProvider, progress: Callable[[str], None] | None = None
+) -> None:
"""Fetch the weights for *entry*. Raises with a usable message on failure."""
if entry.runtime == "faster-whisper":
# The same cache layout WhisperModel(name) resolves at runtime, so the
@@ -82,7 +85,10 @@ def _download_model(entry: LocalProvider) -> None:
return
from jarvis.speech.sherpa_models import download_sherpa_model
- download_sherpa_model(entry.model_id)
+ # Every bundle, not just the first: a local voice needs one per language,
+ # and stopping after German would leave the assistant mute in English.
+ for model_id in entry.bundles:
+ download_sherpa_model(model_id, progress=progress)
def _run_install(provider_id: str) -> None:
@@ -109,7 +115,13 @@ def _run_install(provider_id: str) -> None:
if ok:
try:
- _download_model(entry)
+
+ def _note(text: str) -> None:
+ """Publish each download step so the UI shows real progress."""
+ with run.lock:
+ run.message = text
+
+ _download_model(entry, _note)
message = f"{entry.model_label} is ready — it runs on this machine now."
except Exception as exc: # noqa: BLE001 — surface an honest retry state
ok = False
diff --git a/jarvis/speech/local_models.py b/jarvis/speech/local_models.py
index 7fddac3030..95e5dda06d 100644
--- a/jarvis/speech/local_models.py
+++ b/jarvis/speech/local_models.py
@@ -162,7 +162,10 @@ def sherpa_model_present(
if not directory.is_dir():
return False
if required_files:
- missing = [f for f in required_files if not (directory / f).is_file()]
+ # ``exists``, not ``is_file``: a Piper voice's ``espeak-ng-data`` is
+ # a DIRECTORY of phoneme rules, and requiring a file here reported
+ # every correctly-downloaded voice as missing.
+ missing = [f for f in required_files if not (directory / f).exists()]
if missing:
log.debug(
"Local model %r is incomplete -- missing %s.",
@@ -206,21 +209,33 @@ def whisper_status(model: str) -> LocalModelStatus:
)
+def bundle_present(model_id: str, *, data_dir: str | None = None) -> bool:
+ """True when the catalogued bundle *model_id* is complete on disk."""
+ bundle = SHERPA_BUNDLES.get(model_id)
+ if bundle is None:
+ return False
+ return sherpa_model_present(
+ model_id, data_dir=data_dir, required_files=bundle.required_files
+ )
+
+
def sherpa_status(
- model_id: str,
+ model_ids: tuple[str, ...],
*,
model_label: str,
download_size: str,
- required_files: tuple[str, ...] = (),
data_dir: str | None = None,
) -> LocalModelStatus:
- """Readiness of a sherpa-onnx backed local provider (STT or TTS)."""
+ """Readiness of a sherpa-onnx backed local provider (STT or TTS).
+
+ ALL of *model_ids* must be present. For the local voice that means one
+ voice per supported language: a provider that can only answer in German is
+ not ready for an assistant whose reply language follows the conversation.
+ """
engine = runtime_installed("sherpa-onnx")
present = (
- sherpa_model_present(
- model_id, data_dir=data_dir, required_files=required_files
- )
- if engine
+ all(bundle_present(mid, data_dir=data_dir) for mid in model_ids)
+ if engine and model_ids
else False
)
if not engine:
@@ -254,6 +269,36 @@ def sherpa_status(
# the downloader never fetches.
+@dataclass(frozen=True, slots=True)
+class SherpaBundle:
+ """One downloadable ONNX model bundle: where it comes from, what it is.
+
+ Two shapes, because the upstreams differ: an ASR model is a handful of loose
+ files in a model repo, while a Piper voice is a tar.bz2 whose payload
+ includes a 390-file phoneme-data directory that would be absurd to fetch one
+ file at a time. Exactly one of ``archive_url`` / ``hf_repo`` is set.
+ """
+
+ #: Directory name under ``data/models/`` — also how every other layer names
+ #: this bundle.
+ model_id: str
+ #: Human-readable name for the UI.
+ label: str
+ #: Files that must be present for the bundle to count as complete. Doubles
+ #: as the download list for ``hf_repo`` bundles, so a bundle can never be
+ #: declared ready against a shorter list than the one that was fetched.
+ required_files: tuple[str, ...]
+ #: A tar.bz2 whose single top-level directory is stripped on extraction.
+ archive_url: str | None = None
+ #: A HuggingFace repo whose ``required_files`` are fetched individually.
+ hf_repo: str | None = None
+ #: Voice bundles only: the language it speaks and the voice's gender, so the
+ #: per-turn voice pick can stay consistent across a language switch (a voice
+ #: that changes sex mid-conversation is BUG-086's shape).
+ language: str = ""
+ gender: str = ""
+
+
@dataclass(frozen=True, slots=True)
class LocalProvider:
"""A provider that runs on this machine, and what it needs to do so."""
@@ -277,14 +322,12 @@ class LocalProvider:
#: in pyproject.toml can be checked against one another instead of drifting
#: apart in two files that never meet.
pip_package: str
- #: Model repository the bundle is fetched from. ``None`` for Whisper, whose
+ #: Bundle ids this provider needs on disk, in download order. Usually one;
+ #: a local TTS needs one voice PER LANGUAGE, because a Piper voice speaks
+ #: exactly one — and a provider that can only answer in German is not a
+ #: usable voice for a multilingual assistant. Empty for Whisper, whose
#: engine manages its own cache.
- hf_repo: str | None = None
- #: Files that must exist inside a sherpa bundle for it to count as complete.
- #: This ONE tuple is both the download list and the completeness check, so a
- #: bundle can never be declared ready against a shorter list than the one
- #: that was fetched. Empty for Whisper.
- required_files: tuple[str, ...] = ()
+ bundles: tuple[str, ...] = ()
#: The Whisper checkpoint the local voice-input card offers. ONE checkpoint, not
@@ -319,6 +362,94 @@ NEMOTRON_HF_REPO = (
"csukuangfj2/sherpa-onnx-nemotron-3.5-asr-streaming-0.6b-560ms-int8-2026-06-11"
)
+#: Where the sherpa-onnx project publishes its converted TTS voices.
+_PIPER_RELEASE = "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/"
+
+
+def _piper_bundle(name: str, *, label: str, language: str, gender: str) -> SherpaBundle:
+ """One Piper voice, named the way the upstream release names it.
+
+ Each archive carries its own copy of ``espeak-ng-data`` (the phoneme rules
+ Piper needs to turn text into sounds), which is why a 30 MB voice arrives as
+ a ~67 MB download.
+ """
+ voice = name.removeprefix("vits-piper-")
+ return SherpaBundle(
+ model_id=name,
+ label=label,
+ required_files=(f"{voice}.onnx", "tokens.txt", "espeak-ng-data"),
+ archive_url=f"{_PIPER_RELEASE}{name}.tar.bz2",
+ language=language,
+ gender=gender,
+ )
+
+
+#: Every model bundle the local providers can use, keyed by id.
+#:
+#: The voices are picked for CONSISTENCY across languages rather than one at a
+#: time: the same perceived speaker in German, English and Spanish, so switching
+#: language mid-conversation does not switch who is talking (BUG-086). A second,
+#: feminine set is listed so a user can change voice without losing that
+#: property — it is downloadable, not downloaded by default.
+SHERPA_BUNDLES: dict[str, SherpaBundle] = {
+ NEMOTRON_MODEL_ID: SherpaBundle(
+ model_id=NEMOTRON_MODEL_ID,
+ label="Nemotron 3.5 (streaming)",
+ required_files=(
+ "encoder.int8.onnx",
+ "decoder.int8.onnx",
+ "joiner.int8.onnx",
+ "tokens.txt",
+ ),
+ hf_repo=NEMOTRON_HF_REPO,
+ ),
+ "vits-piper-de_DE-thorsten-medium": _piper_bundle(
+ "vits-piper-de_DE-thorsten-medium",
+ label="Thorsten (German)",
+ language="de",
+ gender="masculine",
+ ),
+ "vits-piper-en_US-ryan-medium": _piper_bundle(
+ "vits-piper-en_US-ryan-medium",
+ label="Ryan (English)",
+ language="en",
+ gender="masculine",
+ ),
+ "vits-piper-es_ES-davefx-medium": _piper_bundle(
+ "vits-piper-es_ES-davefx-medium",
+ label="Dave (Spanish)",
+ language="es",
+ gender="masculine",
+ ),
+ "vits-piper-de_DE-ramona-low": _piper_bundle(
+ "vits-piper-de_DE-ramona-low",
+ label="Ramona (German)",
+ language="de",
+ gender="feminine",
+ ),
+ "vits-piper-en_US-amy-medium": _piper_bundle(
+ "vits-piper-en_US-amy-medium",
+ label="Amy (English)",
+ language="en",
+ gender="feminine",
+ ),
+ "vits-piper-es_ES-sharvard-medium": _piper_bundle(
+ "vits-piper-es_ES-sharvard-medium",
+ label="Sharvard (Spanish)",
+ language="es",
+ gender="feminine",
+ ),
+}
+
+#: The voices the local TTS install fetches — one per supported language, all
+#: the same gender. Anything less would leave the assistant mute in a language
+#: the rest of the app fully supports.
+PIPER_DEFAULT_VOICES: tuple[str, ...] = (
+ "vits-piper-de_DE-thorsten-medium",
+ "vits-piper-en_US-ryan-medium",
+ "vits-piper-es_ES-davefx-medium",
+)
+
LOCAL_PROVIDERS: tuple[LocalProvider, ...] = (
LocalProvider(
provider_id="faster-whisper",
@@ -337,13 +468,17 @@ LOCAL_PROVIDERS: tuple[LocalProvider, ...] = (
model_label="Nemotron 3.5 (streaming)",
download_size="about 690 MB",
pip_package=SHERPA_ONNX_PACKAGE,
- hf_repo=NEMOTRON_HF_REPO,
- required_files=(
- "encoder.int8.onnx",
- "decoder.int8.onnx",
- "joiner.int8.onnx",
- "tokens.txt",
- ),
+ bundles=(NEMOTRON_MODEL_ID,),
+ ),
+ LocalProvider(
+ provider_id="piper-local",
+ tier="tts",
+ runtime="sherpa-onnx",
+ model_id=PIPER_DEFAULT_VOICES[0],
+ model_label="Piper voices",
+ download_size="about 200 MB",
+ pip_package=SHERPA_ONNX_PACKAGE,
+ bundles=PIPER_DEFAULT_VOICES,
),
)
@@ -380,10 +515,9 @@ def local_status(
if entry.runtime == "faster-whisper":
return whisper_status(model_override or entry.model_id)
return sherpa_status(
- entry.model_id,
+ entry.bundles,
model_label=entry.model_label,
download_size=entry.download_size,
- required_files=entry.required_files,
data_dir=data_dir,
)
diff --git a/jarvis/speech/sherpa_models.py b/jarvis/speech/sherpa_models.py
index a00aae76ba..6183334637 100644
--- a/jarvis/speech/sherpa_models.py
+++ b/jarvis/speech/sherpa_models.py
@@ -58,6 +58,32 @@ def _download_file(url: str, target: Path, *, timeout_s: float = 60.0) -> None:
fh.write(chunk)
+def _extract_archive(archive: Path, staging: Path) -> None:
+ """Unpack a tar.bz2 into *staging*, stripping its single top-level directory.
+
+ The upstream archives wrap everything in a folder named after the model; the
+ rest of the app addresses bundles by their own directory, so the wrapper is
+ removed here rather than encoded into every path elsewhere.
+ """
+ import tarfile
+
+ unpacked = staging / "_unpacked"
+ unpacked.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(archive, mode="r:bz2") as tf:
+ # 'data' rejects absolute paths, parent traversal, links pointing out of
+ # the tree and device files — a downloaded archive is untrusted input,
+ # and without the filter a crafted one could write anywhere on disk.
+ try:
+ tf.extractall(unpacked, filter="data")
+ except TypeError: # pragma: no cover — Python without the filter arg
+ tf.extractall(unpacked) # noqa: S202
+ entries = [p for p in unpacked.iterdir() if not p.name.startswith(".")]
+ root = entries[0] if len(entries) == 1 and entries[0].is_dir() else unpacked
+ for item in list(root.iterdir()):
+ item.replace(staging / item.name)
+ shutil.rmtree(unpacked, ignore_errors=True)
+
+
def download_sherpa_model(
model_id: str,
*,
@@ -66,19 +92,21 @@ def download_sherpa_model(
) -> Path:
"""Fetch the bundle for *model_id* and return its directory.
- Raises ``LookupError`` for an unknown model (a catalog/caller mismatch, not
+ Raises ``LookupError`` for an unknown bundle (a catalog/caller mismatch, not
a network problem) and lets transport errors propagate — the caller turns
them into the retryable state the user sees.
"""
- entry = get_local_provider_for_model(model_id)
- if entry is None or not entry.hf_repo or not entry.required_files:
+ from jarvis.speech.local_models import SHERPA_BUNDLES
+
+ bundle = SHERPA_BUNDLES.get(model_id)
+ if bundle is None:
raise LookupError(
f"No downloadable model bundle is registered for '{model_id}'."
)
target_dir = sherpa_model_dir(model_id, data_dir=data_dir)
if target_dir.is_dir() and all(
- (target_dir / name).is_file() for name in entry.required_files
+ (target_dir / name).exists() for name in bundle.required_files
):
log.info("Local model %s is already complete at %s.", model_id, target_dir)
return target_dir
@@ -89,12 +117,29 @@ def download_sherpa_model(
# interrupted halfway.
staging = Path(tempfile.mkdtemp(prefix=f".{model_id}-", dir=target_dir.parent))
try:
- for index, name in enumerate(entry.required_files, start=1):
+ if bundle.archive_url:
+ if progress is not None:
+ progress(f"Downloading {bundle.label}…")
+ archive = staging / "bundle.tar.bz2"
+ _download_file(bundle.archive_url, archive)
if progress is not None:
- progress(f"Downloading {name} ({index}/{len(entry.required_files)})…")
- log.info("Fetching %s for local model %s", name, model_id)
- _download_file(
- _HF_FILE_URL.format(repo=entry.hf_repo, path=name), staging / name
+ progress(f"Unpacking {bundle.label}…")
+ _extract_archive(archive, staging)
+ archive.unlink(missing_ok=True)
+ else:
+ total = len(bundle.required_files)
+ for index, name in enumerate(bundle.required_files, start=1):
+ if progress is not None:
+ progress(f"Downloading {name} ({index}/{total})…")
+ log.info("Fetching %s for local model %s", name, model_id)
+ _download_file(
+ _HF_FILE_URL.format(repo=bundle.hf_repo, path=name),
+ staging / name,
+ )
+ missing = [n for n in bundle.required_files if not (staging / n).exists()]
+ if missing:
+ raise RuntimeError(
+ f"The download for '{model_id}' is missing {', '.join(missing)}."
)
# Replace any incomplete previous attempt, then move the finished set in.
if target_dir.exists():
@@ -106,30 +151,17 @@ def download_sherpa_model(
return target_dir
-def get_local_provider_for_model(model_id: str):
- """The catalog entry whose ``model_id`` is *model_id*, or None.
-
- The download route knows a model id; the catalog is keyed by provider id.
- This is the one place that bridges the two, so no caller has to keep a
- second mapping of its own.
- """
- from jarvis.speech.local_models import LOCAL_PROVIDERS
-
- for entry in LOCAL_PROVIDERS:
- if entry.model_id == model_id:
- return entry
- return None
-
-
def model_paths(model_id: str, *, data_dir: str | None = None) -> dict[str, Path]:
"""Absolute paths of a bundle's files, keyed by their filename.
Providers ask for this instead of composing paths themselves, so the
directory layout stays a fact of this module alone.
"""
- entry = get_local_provider_for_model(model_id)
+ from jarvis.speech.local_models import SHERPA_BUNDLES
+
+ bundle = SHERPA_BUNDLES.get(model_id)
directory = sherpa_model_dir(model_id, data_dir=data_dir)
- names = entry.required_files if entry is not None else ()
+ names = bundle.required_files if bundle is not None else ()
return {name: directory / name for name in names}
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index e1c714ddc7..2b7882acae 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -2841,6 +2841,12 @@ async def tts_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"Add its API key first."
),
)
+ # Same reasoning as the STT switch: a local provider has no credential to
+ # check, so readiness must be asked of the disk. Activating a voice whose
+ # files are missing would turn every spoken reply into silence.
+ local_state = _local_runtime_payload(spec)
+ if local_state is not None and not local_state["ready"]:
+ raise HTTPException(status_code=409, detail=local_state["detail"])
if body.persist:
try:
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index fff51e9d54..89f6c52ef0 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -619,6 +619,29 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"Diego/Lupita). Billed per character on your Inworld account."
),
),
+ # Local, keyless TTS. Same readiness contract as the local STT cards: the
+ # payload carries a real on-disk probe, and "ready" means one voice per
+ # SUPPORTED LANGUAGE is downloaded — a Piper voice speaks exactly one
+ # language, so a German-only install would leave the assistant mute the
+ # moment the conversation switches to English.
+ ProviderSpec(
+ id="piper-local",
+ label="Piper (on this machine)",
+ tier="tts",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ signup_url=None,
+ credential_help=(
+ "Speaks on this machine — no API key, no cloud account, nothing "
+ "sent anywhere. Piper is the established offline voice engine: "
+ "small neural voices that run faster than real time even without a "
+ "graphics card. The download is about 200 MB and brings one voice "
+ "each for German, English and Spanish. The voices sound good rather "
+ "than indistinguishable from a person; a hosted provider is still "
+ "the more natural-sounding option."
+ ),
+ ),
# ── STT ───────────────────────────────────────────────────────────────
ProviderSpec(
id="groq-api",
diff --git a/pyproject.toml b/pyproject.toml
index 94d4f1cd19..d4f9fdeee0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -474,6 +474,10 @@ openai-api = "jarvis.plugins.stt.openai_api:OpenAIWhisperAPI"
gemini-api = "jarvis.plugins.stt.gemini_api:GeminiSTT"
[project.entry-points."jarvis.tts"]
+# Local, keyless neural speech (Piper VITS voices via sherpa-onnx / ONNX
+# Runtime). The voices are plain ONNX files, deliberately NOT loaded through the
+# GPL-3 piper1-gpl library, so this MIT repo stays MIT.
+piper-local = "jarvis.plugins.tts.piper_local:PiperLocalTTS"
inworld = "jarvis.plugins.tts.inworld_tts:InworldTTS"
elevenlabs = "jarvis.plugins.tts.elevenlabs_tts:ElevenLabsTTS"
gemini-flash-tts = "jarvis.plugins.tts.gemini_flash_tts:GeminiFlashTTS"
diff --git a/tests/unit/plugins/tts/test_piper_local.py b/tests/unit/plugins/tts/test_piper_local.py
new file mode 100644
index 0000000000..eda83b2354
--- /dev/null
+++ b/tests/unit/plugins/tts/test_piper_local.py
@@ -0,0 +1,200 @@
+"""Guards for the on-device Piper voice.
+
+The properties worth pinning are the ones a cloud TTS gets for free and a local
+one does not: a Piper voice speaks exactly ONE language, so choosing the right
+file per turn IS the feature. Getting it wrong does not raise — it answers a
+German sentence in an English accent, which no test would notice unless it
+asks for this explicitly.
+"""
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import numpy as np
+import pytest
+
+from jarvis.plugins.tts import piper_local
+from jarvis.plugins.tts.piper_local import PiperLocalTTS
+
+
+class _FakeAudio:
+ def __init__(self, seconds: float = 0.5, sample_rate: int = 22_050) -> None:
+ self.samples = np.linspace(-0.5, 0.5, int(sample_rate * seconds), dtype=np.float32)
+ self.sample_rate = sample_rate
+
+
+class _FakeEngine:
+ """Records what was spoken, so the test can assert WHICH voice ran."""
+
+ def __init__(self, model_id: str) -> None:
+ self.model_id = model_id
+ self.spoken: list[str] = []
+
+ def generate(self, text: str, speaker_id: int, speed: float) -> _FakeAudio:
+ self.spoken.append(text)
+ return _FakeAudio()
+
+
+def all_voices_installed(monkeypatch: pytest.MonkeyPatch) -> dict[str, _FakeEngine]:
+ """Pretend every catalogued voice is downloaded, with fake engines."""
+ engines: dict[str, _FakeEngine] = {}
+
+ monkeypatch.setattr(
+ "jarvis.speech.local_models.bundle_present",
+ lambda model_id, **kw: True,
+ )
+
+ def _build(self: PiperLocalTTS, model_id: str) -> _FakeEngine:
+ engine = _FakeEngine(model_id)
+ engines[model_id] = engine
+ return engine
+
+ monkeypatch.setattr(PiperLocalTTS, "_build_engine", _build)
+ return engines
+
+
+async def _speak(tts: PiperLocalTTS, text: str, language_code: str | None) -> bytes:
+ pcm = b""
+ async for chunk in tts.synthesize(text, language_code=language_code):
+ pcm += chunk.pcm
+ return pcm
+
+
+def test_each_language_gets_its_own_voice(all_voices_installed) -> None:
+ """The core of a local TTS: one voice per language, picked per turn."""
+ tts = PiperLocalTTS()
+
+ asyncio.run(_speak(tts, "Guten Morgen", "de-DE"))
+ german = tts.last_voice
+ asyncio.run(_speak(tts, "Good morning", "en-US"))
+ english = tts.last_voice
+ asyncio.run(_speak(tts, "Buenos dias", "es-ES"))
+ spanish = tts.last_voice
+
+ assert german is not None and "de_DE" in german
+ assert english is not None and "en_US" in english
+ assert spanish is not None and "es_ES" in spanish
+
+
+def test_the_speaker_profile_survives_a_language_switch(all_voices_installed) -> None:
+ """Switching language must not switch WHO is speaking (BUG-086's shape)."""
+ from jarvis.speech.local_models import SHERPA_BUNDLES
+
+ tts = PiperLocalTTS(gender="feminine")
+
+ asyncio.run(_speak(tts, "Guten Morgen", "de-DE"))
+ german = tts.last_voice
+ asyncio.run(_speak(tts, "Good morning", "en-US"))
+ english = tts.last_voice
+
+ assert SHERPA_BUNDLES[german].gender == "feminine"
+ assert SHERPA_BUNDLES[english].gender == "feminine"
+
+
+def test_an_explicit_voice_request_wins(all_voices_installed) -> None:
+ tts = PiperLocalTTS()
+
+ asyncio.run(
+ tts.synthesize(
+ "Hello", voice="vits-piper-en_US-amy-medium", language_code="de-DE"
+ ).__anext__()
+ )
+
+ assert tts.last_voice == "vits-piper-en_US-amy-medium"
+
+
+def test_an_unsupported_language_still_speaks(all_voices_installed) -> None:
+ """Better an accent than silence — but the log has to say what happened."""
+ tts = PiperLocalTTS()
+
+ pcm = asyncio.run(_speak(tts, "Bonjour", "fr-FR"))
+
+ assert pcm, "a language with no local voice must not produce silence"
+ assert tts.last_voice is not None
+
+
+def test_no_downloaded_voice_raises_an_actionable_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Silence is the worst possible failure for a voice — say why instead."""
+ monkeypatch.setattr(
+ "jarvis.speech.local_models.bundle_present", lambda model_id, **kw: False
+ )
+ tts = PiperLocalTTS()
+
+ with pytest.raises(RuntimeError) as excinfo:
+ asyncio.run(_speak(tts, "Hallo", "de-DE"))
+
+ assert "API-Keys view" in str(excinfo.value)
+
+
+def test_only_downloaded_voices_are_offered(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Listing a voice that is not on disk would let the user pick silence."""
+ present = {"vits-piper-de_DE-thorsten-medium"}
+ monkeypatch.setattr(
+ "jarvis.speech.local_models.bundle_present",
+ lambda model_id, **kw: model_id in present,
+ )
+ tts = PiperLocalTTS()
+
+ assert tts.list_voices() == ["vits-piper-de_DE-thorsten-medium"]
+ assert tts.list_voices("en-US") == []
+
+
+def test_audio_is_int16_in_range(all_voices_installed) -> None:
+ """The pipeline plays int16; an unclipped float would wrap into loud noise."""
+ tts = PiperLocalTTS()
+
+ pcm = asyncio.run(_speak(tts, "Hallo", "de-DE"))
+ samples = np.frombuffer(pcm, dtype=np.int16)
+
+ assert samples.size > 0
+ assert samples.max() <= 32767
+ assert samples.min() >= -32768
+
+
+def test_empty_text_speaks_nothing_without_loading_a_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def _explode(self: PiperLocalTTS, model_id: str) -> Any:
+ raise AssertionError("empty text must not load a voice")
+
+ monkeypatch.setattr(PiperLocalTTS, "_build_engine", _explode)
+ tts = PiperLocalTTS()
+
+ assert asyncio.run(_speak(tts, " ", "de-DE")) == b""
+
+
+def test_declares_that_it_runs_on_device() -> None:
+ assert PiperLocalTTS.runs_on_device is True
+
+
+def test_voices_cover_every_supported_reply_language() -> None:
+ """The catalog must not leave a supported language mute.
+
+ ``[brain].reply_language`` offers de/en/es, and the resolver can land on any
+ of them per turn. A missing voice there is not a gap in a nice-to-have — it
+ is the assistant going silent mid-conversation.
+ """
+ from jarvis.speech.local_models import PIPER_DEFAULT_VOICES, SHERPA_BUNDLES
+
+ languages = {SHERPA_BUNDLES[v].language for v in PIPER_DEFAULT_VOICES}
+
+ assert {"de", "en", "es"} <= languages
+
+
+def test_default_voices_share_one_speaker_profile() -> None:
+ """All three defaults must be the same kind of speaker, per the test above."""
+ from jarvis.speech.local_models import PIPER_DEFAULT_VOICES, SHERPA_BUNDLES
+
+ genders = {SHERPA_BUNDLES[v].gender for v in PIPER_DEFAULT_VOICES}
+
+ assert len(genders) == 1
+
+
+def test_module_exposes_the_expected_provider_surface() -> None:
+ """Structural TTSProvider conformance — no inheritance, so assert it."""
+ for attribute in ("synthesize", "list_voices", "name", "supports_streaming"):
+ assert hasattr(piper_local.PiperLocalTTS, attribute)