From 9f155074a62b69f50e0ada86a077f1c6c58965dd Mon Sep 17 00:00:00 2001 From: StuBehan Date: Fri, 25 Sep 2026 11:34:27 +0100 Subject: [PATCH 1/4] feat: add optional MLX Audio backend with model adapters --- .gitignore | 1 + NOTICE | 25 ++++ README.md | 94 ++++++++++++ pyproject.toml | 7 +- stackvox/cli.py | 111 ++++++++++++-- stackvox/daemon.py | 88 ++++++++++- stackvox/engine.py | 188 +++++++++++++++++++++-- stackvox/mlx_backend.py | 210 ++++++++++++++++++++++++++ tests/test_cli.py | 228 ++++++++++++++++++++++++++-- tests/test_daemon.py | 10 ++ tests/test_daemon_protocol.py | 30 ++++ tests/test_engine.py | 115 ++++++++++++++ tests/test_mlx_backend.py | 275 ++++++++++++++++++++++++++++++++++ 13 files changed, 1342 insertions(+), 40 deletions(-) create mode 100644 stackvox/mlx_backend.py create mode 100644 tests/test_mlx_backend.py diff --git a/.gitignore b/.gitignore index e757fe7..24df44c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ dist/ *.bin out/ *.wav +*.m4a !docs/demo.wav .DS_Store .env diff --git a/NOTICE b/NOTICE index a62ccbc..d7ab12d 100644 --- a/NOTICE +++ b/NOTICE @@ -60,3 +60,28 @@ phonemizer-fork runtime. Downstream users who distribute a combined work that includes phonemizer-fork should review GPL-3.0 obligations for their own distribution. + +-------------------------------------------------------------------------------- +Optional MLX backend (`stackvox[mlx]`) +-------------------------------------------------------------------------------- + +The components below are used only when the optional MLX backend is installed +and selected. stackvox does not download, bundle, modify, or redistribute any +MLX model; the user supplies a local model directory, and that model's own +license governs its use. + +mlx-audio + Copyright (c) 2024 Prince Canuma + Licensed under the MIT License + https://github.com/Blaizzy/mlx-audio + +mlx and mlx-lm + Copyright © 2023 Apple Inc. + Licensed under the MIT License + https://github.com/ml-explore/mlx + https://github.com/ml-explore/mlx-lm + +transformers + Copyright 2018- The Hugging Face team. All rights reserved. + Licensed under the Apache License, Version 2.0 + https://github.com/huggingface/transformers diff --git a/README.md b/README.md index a4351e3..5ff84a8 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,98 @@ if daemon.is_running(): daemon.stop() ``` +## Local MLX models (Apple Silicon) + +The optional `mlx` backend runs any text-to-speech model that +[MLX Audio](https://github.com/Blaizzy/mlx-audio) can load from a local +directory, including ones that support voice cloning and style instructions. +Kokoro (ONNX) remains the default backend and dependency set. + +```bash +pip install 'stackvox[mlx]' + +stackvox speak \ + --backend mlx \ + --model-dir /path/to/model \ + --reference-audio /path/to/reference.wav \ + --reference-text "The exact transcript of the reference audio." \ + --out cloned.wav \ + "Hello from a local MLX model." +``` + +> **Model licenses:** stackvox never downloads, bundles, or recommends MLX +> models. You supply the model directory, and its license (which may restrict +> commercial use) applies to your use of it. Some models also need their own +> extra Python packages; MLX Audio names them if they are missing. + +Keep a large model resident for repeated requests by selecting it when the +daemon starts. The backend and model cannot be changed without restarting the +daemon. Generation options given to `serve` become the daemon's defaults, and +any `say` request can override them: + +```bash +stackvox serve --backend mlx --model-dir /path/to/model + +stackvox say \ + --reference-audio /path/to/reference.wav \ + --reference-text "The exact transcript of the reference audio." \ + "This request uses the resident model." +``` + +Generation options (`--reference-audio`, `--reference-text`, `--instruct`, +`--temperature`, `--top-p`, `--top-k`) are forwarded only when set, so each +model's own defaults apply otherwise; which ones a model honours depends on +the model. They are rejected with an error unless the `mlx` backend is in use, +both by `speak` and by a daemon running Kokoro. `--voice` and `--lang` apply to +Kokoro only. Playback streams in sentence-packed chunks of up to ~400 +characters, so the first audio arrives once the first chunk is generated. + +### Model adapters + +Some models need custom loading, such as renamed weights, a codec path, or a +tokenizer quirk. Rather than carrying model-specific code, stackvox accepts an +adapter script that you write and keep locally, for example under +`~/.config/stackvox/adapters/`: + +```python +# my_adapter.py +from pathlib import Path +from stackvox.mlx_backend import swapped + + +def load(model_dir: Path, load_model): + # Patch whatever the model needs for the duration of the load, then + # delegate to MLX Audio's loader (or replace it entirely). + from some_library import SomeClass + + with swapped(SomeClass, "some_method", lambda *args, **kwargs: ...): + return load_model(model_dir) +``` + +```bash +stackvox speak --backend mlx --model-dir /path/to/model \ + --model-adapter ~/.config/stackvox/adapters/my_adapter.py "Hello" +``` + +`load(model_dir, load_model)` must return the loaded model. `swapped` patches +an attribute and restores it afterwards, even on error. Adapters run as normal +Python with your privileges and are only used when passed explicitly; nothing +is picked up from a model directory. + +The Python API uses the same waveform contract as Kokoro: + +```python +from pathlib import Path +from stackvox import Stackvox + +tts = Stackvox(backend="mlx", model_dir=Path("/path/to/model")) +samples, sample_rate = tts.synthesize( + "A calm and natural delivery.", + reference_audio=Path("reference.wav"), + reference_text="The reference transcript.", +) +``` + ## Voices Kokoro ships voices across several languages. Voice prefix encodes gender + language: @@ -281,4 +373,6 @@ stackvox itself is licensed under the **Apache License, Version 2.0** — see [` **Runtime dependencies.** [`kokoro-onnx`](https://github.com/thewh1teagle/kokoro-onnx) (MIT, © thewh1teagle), [`onnxruntime`](https://github.com/microsoft/onnxruntime) (MIT, © Microsoft), [`sounddevice`](https://python-sounddevice.readthedocs.io/) (MIT, © Matthias Geier), [`soundfile`](https://github.com/bastibe/python-soundfile) (BSD-3, © Bastian Bechtold), [`numpy`](https://numpy.org/) (BSD-3). +**Optional MLX backend.** `stackvox[mlx]` runs on [`mlx-audio`](https://github.com/Blaizzy/mlx-audio) (MIT, © Prince Canuma), [`mlx`](https://github.com/ml-explore/mlx) and [`mlx-lm`](https://github.com/ml-explore/mlx-lm) (MIT, © Apple), and [`transformers`](https://github.com/huggingface/transformers) (Apache 2.0, © Hugging Face). stackvox does not download, bundle, or redistribute any MLX model; the license of whichever model you supply governs your use of it. + **GPL note.** `kokoro-onnx` pulls in [`phonemizer-fork`](https://github.com/bootphon/phonemizer) as a transitive runtime dependency; it is licensed under **GPL-3.0**. stackvox does not bundle, modify, or statically link it — pip installs it alongside stackvox and the two communicate through phonemizer's published Python API at runtime. If you redistribute a combined work (e.g. a frozen binary, container image, or vendored wheel set) that includes phonemizer-fork, review GPL-3.0 obligations for that distribution. diff --git a/pyproject.toml b/pyproject.toml index d5c33df..1b7db03 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,11 @@ dependencies = [ ] [project.optional-dependencies] +# MLX Audio is pre-1.0, so cap at the next minor; the floor is the version +# verified end to end with stackvox's loader and generate() usage. +mlx = [ + "mlx-audio>=0.4.5,<0.5; platform_system=='Darwin' and platform_machine=='arm64'", +] dev = [ "pytest>=8.0", "pytest-mock>=3.12", @@ -125,7 +130,7 @@ disallow_untyped_defs = true [[tool.mypy.overrides]] # Third-party deps without inline type stubs (or, for `tomli`, a 3.10-only # fallback that's not installed on the typechecker's Python). -module = ["kokoro_onnx", "onnxruntime", "sounddevice", "soundfile", "tomli"] +module = ["kokoro_onnx", "mlx_audio.*", "onnxruntime", "sounddevice", "soundfile", "tomli"] ignore_missing_imports = true [[tool.mypy.overrides]] diff --git a/stackvox/cli.py b/stackvox/cli.py index 705c1d9..0727512 100644 --- a/stackvox/cli.py +++ b/stackvox/cli.py @@ -11,7 +11,8 @@ import soundfile as sf from stackvox import config, daemon, paths, updates -from stackvox.engine import Stackvox +from stackvox.engine import BACKENDS, DEFAULT_BACKEND, MLX_OPTIONS, Stackvox +from stackvox.mlx_backend import ModelLoadError from stackvox.text import normalize_for_speech from stackvox.voices import VoiceMix, VoiceParams, resolve @@ -58,11 +59,11 @@ def _configure_logging() -> None: fi case "$prev" in - --file|--out|--pronunciations) + --file|--out|--pronunciations|--reference-audio|--model-adapter) COMPREPLY=( $(compgen -f -- "$cur") ) return 0 ;; - --prefix) + --prefix|--model-dir) COMPREPLY=( $(compgen -d -- "$cur") ) return 0 ;; @@ -74,6 +75,10 @@ def _configure_logging() -> None: COMPREPLY=( $(compgen -W "en-us en-gb fr-fr it hi pt-br es ja zh" -- "$cur") ) return 0 ;; + --backend) + COMPREPLY=( $(compgen -W "kokoro mlx" -- "$cur") ) + return 0 + ;; --tables) COMPREPLY=( $(compgen -W "drop csv" -- "$cur") ) return 0 @@ -88,20 +93,21 @@ def _configure_logging() -> None: ;; esac + local gen_flags="--reference-audio --reference-text --instruct --temperature --top-p --top-k" local norm_flags="--no-markdown --no-dev-terms --no-abbreviations --no-filenames --pronunciations --no-expand-units --no-expand-numbers --no-pauses --tables --code-blocks --code-placeholder --strip-emoji --no-terminal-stops --locale" case "$subcommand" in speak) - COMPREPLY=( $(compgen -W "--voice --speed --lang --file --out --normalize $norm_flags --help" -- "$cur") ) + COMPREPLY=( $(compgen -W "--voice --speed --lang --file --out --backend --model-dir --model-adapter $gen_flags --normalize $norm_flags --help" -- "$cur") ) ;; say) - COMPREPLY=( $(compgen -W "--voice --speed --lang --file --fallback-say --normalize $norm_flags --help" -- "$cur") ) + COMPREPLY=( $(compgen -W "--voice --speed --lang --file $gen_flags --fallback-say --normalize $norm_flags --help" -- "$cur") ) ;; normalize) COMPREPLY=( $(compgen -W "--file $norm_flags --help" -- "$cur") ) ;; serve) - COMPREPLY=( $(compgen -W "--voice --speed --lang --help" -- "$cur") ) + COMPREPLY=( $(compgen -W "--voice --speed --lang --backend --model-dir --model-adapter $gen_flags --help" -- "$cur") ) ;; completion) COMPREPLY=( $(compgen -W "bash" -- "$cur") ) @@ -130,7 +136,9 @@ def _configure_logging() -> None: def _build_parser(defaults: config.Defaults | None = None) -> argparse.ArgumentParser: if defaults is None: defaults = config.Defaults() - parser = argparse.ArgumentParser(prog="stackvox", description="Kokoro-82M TTS") + parser = argparse.ArgumentParser( + prog="stackvox", description="Offline TTS with Kokoro or local MLX Audio models" + ) sub = parser.add_subparsers(dest="cmd") p_speak = sub.add_parser("speak", help="Synthesize and play in-process (loads model each run)") @@ -138,12 +146,15 @@ def _build_parser(defaults: config.Defaults | None = None) -> argparse.ArgumentP p_speak.add_argument("text", nargs="?") p_speak.add_argument("--file", type=Path) p_speak.add_argument("--out", type=Path, help="Write wav instead of playing") + _add_backend_args(p_speak) + _add_generation_args(p_speak) _add_normalize_args(p_speak, with_switch=True) p_say = sub.add_parser("say", help="Send text to daemon (fast; fails if daemon not running)") _add_voice_args(p_say, defaults) p_say.add_argument("text", nargs="?") p_say.add_argument("--file", type=Path) + _add_generation_args(p_say) p_say.add_argument( "--fallback-say", action="store_true", help="Shell out to macOS `say` if daemon unreachable" ) @@ -159,6 +170,8 @@ def _build_parser(defaults: config.Defaults | None = None) -> argparse.ArgumentP p_serve = sub.add_parser("serve", help="Run the daemon in the foreground") _add_voice_args(p_serve, defaults) + _add_backend_args(p_serve) + _add_generation_args(p_serve) sub.add_parser("stop", help="Stop the running daemon") sub.add_parser("cancel", help="Stop the current utterance without shutting down the daemon") @@ -212,6 +225,56 @@ def _voice_params(args: argparse.Namespace) -> tuple[VoiceParams, dict[str, Voic return params, custom +def _add_backend_args(parser: argparse.ArgumentParser) -> None: + parser.add_argument( + "--backend", + choices=BACKENDS, + default=DEFAULT_BACKEND, + help="TTS backend (default: %(default)s). --voice/--lang apply to kokoro only", + ) + parser.add_argument( + "--model-dir", type=Path, help="Local MLX Audio model directory (required for --backend mlx)" + ) + parser.add_argument( + "--model-adapter", + type=Path, + help="Python script defining load(model_dir, load_model) for models that need custom loading", + ) + + +def _add_generation_args(parser: argparse.ArgumentParser) -> None: + group = parser.add_argument_group("generation options (require --backend mlx; unset = model default)") + group.add_argument("--reference-audio", type=Path, help="Voice-cloning reference audio") + group.add_argument("--reference-text", help="Transcript of --reference-audio") + group.add_argument("--instruct", help="Global delivery/style instruction") + group.add_argument("--temperature", type=float, help="Sampling temperature") + group.add_argument("--top-p", type=float, help="Nucleus sampling cutoff") + group.add_argument("--top-k", type=int, help="Top-k sampling cutoff") + + +def _generation_kwargs(args: argparse.Namespace) -> dict: + """The generation options the user actually supplied, keyed as the engine expects.""" + values = {key: getattr(args, key, None) for key in MLX_OPTIONS} + return {key: value for key, value in values.items() if value is not None} + + +def _validate_backend_args(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: + """Fail fast on backend/option mismatches before loading a model. + + ``say`` has no ``--backend``: the daemon decides, and rejects generation options + itself when it is running Kokoro. + """ + backend = getattr(args, "backend", None) + if backend is None: + return + if backend == "mlx" and args.model_dir is None: + parser.error("--backend mlx requires --model-dir") + if backend != "mlx" and (_generation_kwargs(args) or args.model_adapter is not None): + parser.error( + "--model-adapter and generation options (--reference-audio, --instruct, ...) require --backend mlx" + ) + + def _add_normalize_args(parser: argparse.ArgumentParser, *, with_switch: bool) -> None: """Flags mapping one-to-one onto ``stackvox.text.normalize_for_speech``. @@ -383,13 +446,25 @@ def _cmd_speak(args: argparse.Namespace) -> int: if text is None: return 1 params, custom = _voice_params(args) - tts = Stackvox(voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom) + try: + tts = Stackvox( + voice=params.voice, + speed=params.speed, + lang=params.lang, + custom_voices=custom, + backend=args.backend, + model_dir=args.model_dir, + model_adapter=args.model_adapter, + ) + except ModelLoadError as exc: + print(f"[stackvox] {exc}", file=sys.stderr) + return 1 if args.out: - samples, sr = tts.synthesize(text) + samples, sr = tts.synthesize(text, **_generation_kwargs(args)) sf.write(args.out, samples, sr) print(f"Wrote {args.out}", file=sys.stderr) else: - tts.speak(text) + tts.speak(text, **_generation_kwargs(args)) return 0 @@ -403,7 +478,9 @@ def _cmd_say(args: argparse.Namespace) -> int: if text is None: return 1 params, _ = _voice_params(args) - ok, resp = daemon.say(text, voice=params.voice, speed=params.speed, lang=params.lang) + ok, resp = daemon.say( + text, voice=params.voice, speed=params.speed, lang=params.lang, **_generation_kwargs(args) + ) if ok: return 0 if args.fallback_say: @@ -432,7 +509,16 @@ def _cmd_normalize(args: argparse.Namespace) -> int: def _cmd_serve(args: argparse.Namespace) -> int: try: params, custom = _voice_params(args) - daemon.serve(voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom) + daemon.serve( + voice=params.voice, + speed=params.speed, + lang=params.lang, + custom_voices=custom, + backend=args.backend, + model_dir=args.model_dir, + model_adapter=args.model_adapter, + **_generation_kwargs(args), + ) except RuntimeError as exc: print(f"[stackvox] {exc}", file=sys.stderr) return 1 @@ -597,6 +683,7 @@ def main() -> int: parser = _build_parser(config.load_defaults()) args = parser.parse_args(argv) + _validate_backend_args(parser, args) if not args.cmd: parser.print_help() diff --git a/stackvox/daemon.py b/stackvox/daemon.py index 8cea416..f16263a 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -28,12 +28,20 @@ import threading import time from collections.abc import Mapping +from pathlib import Path from typing import Any import sounddevice as sd from stackvox import updates -from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE, Stackvox +from stackvox.engine import ( + DEFAULT_BACKEND, + DEFAULT_LANG, + DEFAULT_SPEED, + DEFAULT_VOICE, + MLX_OPTIONS, + Stackvox, +) from stackvox.paths import pid_path, socket_path from stackvox.voices import VoiceMix @@ -211,9 +219,26 @@ def _exit_wedged() -> None: class _DaemonState: def __init__( - self, voice: str, speed: float, lang: str, custom_voices: Mapping[str, VoiceMix] | None = None + self, + voice: str, + speed: float, + lang: str, + custom_voices: Mapping[str, VoiceMix] | None = None, + backend: str = DEFAULT_BACKEND, + model_dir: Path | None = None, + model_adapter: Path | None = None, + generation_defaults: dict | None = None, ) -> None: - self.tts = Stackvox(voice=voice, speed=speed, lang=lang, custom_voices=custom_voices) + self.tts = Stackvox( + voice=voice, + speed=speed, + lang=lang, + custom_voices=custom_voices, + backend=backend, + model_dir=model_dir, + model_adapter=model_adapter, + ) + self.generation_defaults = generation_defaults or {} self.queue: queue.Queue[dict] = queue.Queue(maxsize=MAX_QUEUE) self.stop_event = threading.Event() # Monotonic time by which the worker must finish its current request; @@ -237,11 +262,15 @@ def _worker(self) -> None: _refresh_audio_devices() _audio_dirty.clear() try: + generation_kwargs: dict[str, Any] = { + key: req.get(key, self.generation_defaults.get(key)) for key in MLX_OPTIONS + } self.tts.speak( req["text"], voice=req.get("voice"), speed=req.get("speed"), lang=req.get("lang"), + **generation_kwargs, ) except Exception: logger.exception("playback error") @@ -332,6 +361,12 @@ def handle(self) -> None: self.wfile.write(b"err: text must be a string\n") return + # Reject here rather than in the worker so the client sees the error + # instead of an "ok" followed by a failure only visible in the log. + if state.tts.backend != "mlx" and any(req.get(key) is not None for key in MLX_OPTIONS): + self.wfile.write(b"err: generation options require a daemon started with --backend mlx\n") + return + if state.submit(req): self.wfile.write(b"ok\n") else: @@ -387,6 +422,15 @@ def serve( speed: float = DEFAULT_SPEED, lang: str = DEFAULT_LANG, custom_voices: Mapping[str, VoiceMix] | None = None, + backend: str = DEFAULT_BACKEND, + model_dir: Path | None = None, + model_adapter: Path | None = None, + reference_audio: Path | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> None: if is_running(): raise RuntimeError(f"daemon already running (pid {PID_PATH.read_text().strip()})") @@ -395,7 +439,23 @@ def serve( if SOCKET_PATH.exists(): SOCKET_PATH.unlink() - state = _DaemonState(voice=voice, speed=speed, lang=lang, custom_voices=custom_voices) + state = _DaemonState( + voice=voice, + speed=speed, + lang=lang, + custom_voices=custom_voices, + backend=backend, + model_dir=model_dir, + model_adapter=model_adapter, + generation_defaults={ + "reference_audio": reference_audio, + "reference_text": reference_text, + "instruct": instruct, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + }, + ) server = _UnixServer(str(SOCKET_PATH), _Handler) server.state = state # type: ignore[attr-defined] @@ -434,7 +494,16 @@ def send(req: dict, timeout: float = CLIENT_TIMEOUT_SECONDS) -> tuple[bool, str] def say( - text: str, voice: str | None = None, speed: float | None = None, lang: str | None = None + text: str, + voice: str | None = None, + speed: float | None = None, + lang: str | None = None, + reference_audio: Path | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> tuple[bool, str]: req: dict = {"text": text} if voice is not None: @@ -443,6 +512,15 @@ def say( req["speed"] = speed if lang is not None: req["lang"] = lang + optional = { + "reference_audio": str(reference_audio) if reference_audio is not None else None, + "reference_text": reference_text, + "instruct": instruct, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + } + req.update({key: value for key, value in optional.items() if value is not None}) return send(req) diff --git a/stackvox/engine.py b/stackvox/engine.py index ee0c977..6aa266d 100644 --- a/stackvox/engine.py +++ b/stackvox/engine.py @@ -11,6 +11,7 @@ import urllib.request from collections.abc import Generator, Mapping from pathlib import Path +from typing import TYPE_CHECKING import numpy as np import onnxruntime as ort @@ -20,11 +21,19 @@ from stackvox.paths import cache_dir as _default_cache_dir from stackvox.voices import BUILTIN_VOICES, VoiceMix, blend, resolve +if TYPE_CHECKING: + from stackvox.mlx_backend import MlxBackend + logger = logging.getLogger(__name__) DEFAULT_VOICE = "af_sarah" DEFAULT_SPEED = 1.0 DEFAULT_LANG = "en-us" +DEFAULT_BACKEND = "kokoro" +BACKENDS = ("kokoro", "mlx") +# Per-request generation options only the MLX backend understands. Kokoro +# rejects them rather than silently dropping a voice-cloning request. +MLX_OPTIONS = ("reference_audio", "reference_text", "instruct", "temperature", "top_p", "top_k") # Streaming playback smoothing: play a touch of silence before the first word so # output-device warm-up (notably a Bluetooth codec/profile switch) lands during @@ -161,7 +170,8 @@ class Stackvox: ``threads`` caps the ONNX Runtime thread pools, which otherwise size themselves from the host's core count and oversubscribe inside a container with a CPU quota. ``session_options`` replaces it when some other ORT - setting is wanted; the two are mutually exclusive. + setting is wanted; the two are mutually exclusive, and both apply to the + kokoro backend only. """ def __init__( @@ -173,14 +183,33 @@ def __init__( custom_voices: Mapping[str, VoiceMix] | None = None, threads: int | None = None, session_options: ort.SessionOptions | None = None, + backend: str = DEFAULT_BACKEND, + model_dir: Path | None = None, + model_adapter: Path | None = None, ) -> None: self.voice = voice self.speed = speed self.lang = lang self.custom_voices = dict(BUILTIN_VOICES if custom_voices is None else custom_voices) self._blends: dict[str, np.ndarray] = {} - model_path, voices_path = _ensure_models(cache_dir or _default_cache_dir()) - self._kokoro = _load_kokoro(model_path, voices_path, threads, session_options) + self.backend = backend + self.model_dir = model_dir + self.model_adapter = model_adapter + self._kokoro: Kokoro | None = None + self._mlx: MlxBackend | None = None + if backend == "kokoro": + model_path, voices_path = _ensure_models(cache_dir or _default_cache_dir()) + self._kokoro = _load_kokoro(model_path, voices_path, threads, session_options) + elif backend == "mlx": + if model_dir is None: + raise ValueError("mlx backend requires model_dir") + if threads is not None or session_options is not None: + raise ValueError("threads and session_options require the kokoro backend") + from stackvox.mlx_backend import MlxBackend + + self._mlx = MlxBackend(model_dir, adapter=model_adapter) + else: + raise ValueError(f"unsupported backend: {backend}") self._stop_event = threading.Event() self._play_thread: threading.Thread | None = None self._stream: sd.OutputStream | None = None @@ -192,8 +221,37 @@ def synthesize( voice: str | None = None, speed: float | None = None, lang: str | None = None, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> tuple[np.ndarray, int]: """Return (samples, sample_rate) without playing.""" + if self._mlx is not None: + return self._mlx.synthesize( + text, + speed=speed if speed is not None else self.speed, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) + assert self._kokoro is not None + mlx_only = { + "reference_audio": reference_audio, + "reference_text": reference_text, + "instruct": instruct, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + } + unsupported = [name for name, value in mlx_only.items() if value is not None] + if unsupported: + raise ValueError(f"{', '.join(unsupported)} require the mlx backend") params = resolve( voice, speed, @@ -217,6 +275,12 @@ def synthesize_stream( voice: str | None = None, speed: float | None = None, lang: str | None = None, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> Generator[tuple[np.ndarray, int], None, None]: """Yield (samples, sample_rate) per sentence, as soon as each is synthesized. @@ -233,17 +297,32 @@ def synthesize_stream( Chunks are sentences, and Kokoro trims each one it is given, so the concatenated stream runs a few percent shorter than ``synthesize`` on the same text — the inter-sentence silence goes with the trim. This is - the audio ``speak`` has always produced. + the audio ``speak`` has always produced. With the mlx backend the chunks + are the sentence-packed spans ``_stream_chunks`` returns, and the + throughput and trim figures above are Kokoro's. The stream is independent of ``speak`` and ``stop``, which own the shared output device: a consumer cancels its own stream by abandoning the generator (``break``, or ``close()``), which shuts the synthesis thread down with it. """ - return self._synthesize_chunks(text, threading.Event(), voice=voice, speed=speed, lang=lang) + return self._synthesize_chunks( + text, + threading.Event(), + voice=voice, + speed=speed, + lang=lang, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) def _style(self, name: str) -> str | np.ndarray: """A Kokoro voice id passes straight through; a mix becomes its blended style vector.""" + assert self._kokoro is not None mix = self.custom_voices.get(name) if mix is None: return name @@ -273,6 +352,12 @@ def speak( speed: float | None = None, lang: str | None = None, blocking: bool = True, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> None: """Synthesize and play through the system default output device. @@ -286,12 +371,36 @@ def speak( stop_event = threading.Event() self._stop_event = stop_event if blocking: - self._stream_play(text, stop_event, voice=voice, speed=speed, lang=lang) + self._stream_play( + text, + stop_event, + voice=voice, + speed=speed, + lang=lang, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) return def _run() -> None: try: - self._stream_play(text, stop_event, voice=voice, speed=speed, lang=lang) + self._stream_play( + text, + stop_event, + voice=voice, + speed=speed, + lang=lang, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) except Exception: logger.exception("stackvox playback failed") @@ -305,8 +414,14 @@ def _synthesize_chunks( voice: str | None = None, speed: float | None = None, lang: str | None = None, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> Generator[tuple[np.ndarray, int], None, None]: - """Yield (samples, sample_rate) per sentence, synthesizing ahead of the consumer. + """Yield (samples, sample_rate) per ``_stream_chunks`` chunk, synthesizing ahead. Kokoro batches by phoneme count (~510), so a whole paragraph synthesizes as one blob before any audio — the source of the lead-in lag. Splitting @@ -321,7 +436,7 @@ def _synthesize_chunks( drains the queue until the producer exits, so abandoning a stream can never leave the synth thread parked on a put. """ - sentences = _split_sentences(text) + sentences = self._stream_chunks(text) if not sentences: return @@ -333,7 +448,20 @@ def _produce() -> None: for sentence in sentences: if stop_event.is_set(): break - chunks.put(self.synthesize(sentence, voice=voice, speed=speed, lang=lang)) + chunks.put( + self.synthesize( + sentence, + voice=voice, + speed=speed, + lang=lang, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) + ) except Exception as exc: # hand the failure to the consumer to re-raise chunks.put(exc) finally: @@ -370,6 +498,12 @@ def _stream_play( voice: str | None = None, speed: float | None = None, lang: str | None = None, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, ) -> None: """Play each sentence through the output device as it becomes available. @@ -378,7 +512,19 @@ def _stream_play( of the generator, so a blocking caller sees the error instead of silent success; ``stop_event`` cancels the stream. """ - chunks = self._synthesize_chunks(text, stop_event, voice=voice, speed=speed, lang=lang) + chunks = self._synthesize_chunks( + text, + stop_event, + voice=voice, + speed=speed, + lang=lang, + reference_audio=reference_audio, + reference_text=reference_text, + instruct=instruct, + temperature=temperature, + top_p=top_p, + top_k=top_k, + ) stream: sd.OutputStream | None = None try: for samples, sample_rate in chunks: @@ -417,6 +563,20 @@ def _stream_play( logger.debug("stream teardown failed", exc_info=True) chunks.close() + def _stream_chunks(self, text: str) -> list[str]: + """Units of text synthesized and played one at a time. + + Kokoro is cheap per call, so single sentences give the lowest latency. + MLX models often pay a fixed prompt cost (reference audio included) on + every generate call and keep prosody more natural across longer spans, + so they stream sentence-packed chunks instead. + """ + if self._mlx is not None: + from stackvox.mlx_backend import split_long_text + + return split_long_text(text) + return _split_sentences(text) + def stop(self) -> None: """Stop any in-progress playback started with blocking=False.""" self._stop_event.set() @@ -429,7 +589,9 @@ def stop(self) -> None: sd.stop() def voices(self) -> list[str]: - """Kokoro voice ids plus the names of custom voice mixes.""" + """Kokoro voice ids plus the names of custom voice mixes; the mlx backend names none.""" + if self._kokoro is None: + return [] return sorted(set(self._kokoro.get_voices()) | set(self.custom_voices)) def speak_sequence( @@ -452,7 +614,7 @@ def synth(line: dict) -> tuple[np.ndarray, int]: kwargs = {k: v for k, v in line.items() if k != "text"} return self.synthesize(line["text"], **kwargs) - if concurrent and len(lines) > 1: + if concurrent and len(lines) > 1 and self.backend == "kokoro": from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=len(lines)) as pool: diff --git a/stackvox/mlx_backend.py b/stackvox/mlx_backend.py new file mode 100644 index 0000000..1047271 --- /dev/null +++ b/stackvox/mlx_backend.py @@ -0,0 +1,210 @@ +"""Optional backend for local MLX Audio text-to-speech models. + +Any model MLX Audio can load natively works as-is. Models that need extra +handling (renamed weights, offline codec paths, tokenizer quirks) can be +adapted with a user-supplied adapter script, so stackvox itself carries no +model-specific code. See ``load_adapter`` for the adapter contract. +""" + +from __future__ import annotations + +import importlib.util +import re +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from pathlib import Path +from threading import Lock +from typing import Any, cast + +import numpy as np + +# Adapters typically swap class attributes on third-party modules, which is +# process-global; serialise loads so two engines can't interleave the swaps. +_LOAD_LOCK = Lock() +# Long inputs are generated in sentence-packed chunks this size or smaller: +# small enough to stay under typical per-call token limits and give prompt +# first audio when streaming, large enough to keep prosody natural. +CHUNK_CHARS = 400 +_SENTENCE_BOUNDARY = re.compile(r"(?<=[.!?])\s+|\n+") + +# Cap on how much of an underlying error is echoed; MLX Audio's messages can +# list hundreds of parameter names. +_ERROR_SUMMARY_CHARS = 200 + +LoadModel = Callable[[Path], Any] +Adapter = Callable[[Path, LoadModel], Any] + + +class ModelLoadError(RuntimeError): + """A local MLX model, or the adapter meant to load it, could not be loaded.""" + + +def _summarize(exc: BaseException) -> str: + first_line = next((line.strip() for line in str(exc).splitlines() if line.strip()), "") + if len(first_line) > _ERROR_SUMMARY_CHARS: + first_line = first_line[: _ERROR_SUMMARY_CHARS - 1] + "…" + return f"{type(exc).__name__}: {first_line}" if first_line else type(exc).__name__ + + +@contextmanager +def swapped(owner: type, name: str, value: Any) -> Iterator[None]: + """Replace ``owner.name`` for the duration of the block, restoring the + original descriptor (or the inherited lookup) afterwards. + + Public so adapter scripts can patch third-party classes during a load + without leaking the patch into the rest of the process. + """ + own = vars(owner) + had_own = name in own + original = own.get(name) + setattr(owner, name, value) + try: + yield + finally: + if had_own: + setattr(owner, name, original) + else: + delattr(owner, name) + + +def split_long_text(text: str, limit: int = CHUNK_CHARS) -> list[str]: + """Pack prose into sentence-aware chunks no longer than ``limit``.""" + sentences = [part.strip() for part in _SENTENCE_BOUNDARY.split(text) if part.strip()] + chunks: list[str] = [] + current = "" + for sentence in sentences: + pieces = [sentence] + if len(sentence) > limit: + words = sentence.split() + pieces = [] + piece = "" + for word in words: + candidate = f"{piece} {word}".strip() + if piece and len(candidate) > limit: + pieces.append(piece) + piece = word + else: + piece = candidate + if piece: + pieces.append(piece) + for piece in pieces: + candidate = f"{current} {piece}".strip() + if current and len(candidate) > limit: + chunks.append(current) + current = piece + else: + current = candidate + if current: + chunks.append(current) + return chunks + + +def load_adapter(path: Path) -> Adapter: + """Import an adapter script and return its ``load`` function. + + An adapter is a Python file defining:: + + def load(model_dir: Path, load_model: Callable[[Path], Any]) -> Any + + ``load_model`` is MLX Audio's own loader; the adapter may patch things + around it (see ``swapped``), call it, or replace it outright, and must + return the loaded model. The script runs with the caller's privileges, so + only point this at code you trust — it is never discovered implicitly. + """ + path = path.expanduser().resolve() + if not path.is_file(): + raise ModelLoadError(f"model adapter not found: {path}") + spec = importlib.util.spec_from_file_location(f"stackvox_adapter_{path.stem}", path) + if spec is None or spec.loader is None: + raise ModelLoadError(f"model adapter is not an importable Python file: {path}") + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + except Exception as exc: + raise ModelLoadError(f"model adapter {path} raised while importing ({_summarize(exc)})") from exc + adapter = getattr(module, "load", None) + if not callable(adapter): + raise ModelLoadError(f"model adapter {path} must define load(model_dir, load_model)") + return cast(Adapter, adapter) + + +def _load_model(model_dir: Path, adapter_path: Path | None) -> Any: + try: + from mlx_audio.tts.utils import load_model + except ImportError as exc: # pragma: no cover - depends on optional install + raise ModelLoadError( + "the mlx backend requires MLX Audio; install it with `pip install 'stackvox[mlx]'`" + ) from exc + if adapter_path is None: + with _LOAD_LOCK: + try: + return load_model(model_dir) + except Exception as exc: + raise ModelLoadError( + f"MLX Audio could not load the model in {model_dir} ({_summarize(exc)}). " + "If this model needs custom loading, pass a model adapter with --model-adapter " + "(see 'Model adapters' in the README)." + ) from exc + adapter = load_adapter(adapter_path) + with _LOAD_LOCK: + try: + return adapter(model_dir, load_model) + except Exception as exc: + raise ModelLoadError( + f"model adapter {adapter_path} failed to load the model in {model_dir} ({_summarize(exc)})" + ) from exc + + +def _load_audio(path: Path, sample_rate: int) -> Any: + from mlx_audio.utils import load_audio + + return load_audio(str(path), sample_rate=sample_rate) + + +class MlxBackend: + """Load one local MLX Audio model and expose stackvox's synthesis contract.""" + + def __init__(self, model_dir: Path, adapter: Path | None = None) -> None: + model_dir = model_dir.expanduser().resolve() + if not model_dir.is_dir(): + raise ModelLoadError(f"model directory not found: {model_dir}") + self.model_dir = model_dir + self._model: Any = _load_model(model_dir, adapter) + + def synthesize( + self, + text: str, + *, + speed: float = 1.0, + reference_audio: Path | str | None = None, + reference_text: str | None = None, + instruct: str | None = None, + temperature: float | None = None, + top_p: float | None = None, + top_k: int | None = None, + ) -> tuple[np.ndarray, int]: + """Generate audio, forwarding only the options the caller set so each + model's own defaults apply to the rest.""" + if (reference_audio is None) != (reference_text is None): + raise ValueError("voice cloning requires both reference_audio and reference_text") + + kwargs: dict[str, Any] = {"speed": speed, "verbose": False} + if reference_audio is not None: + audio_path = Path(reference_audio).expanduser().resolve() + if not audio_path.is_file(): + raise FileNotFoundError(f"reference audio not found: {audio_path}") + kwargs["ref_audio"] = _load_audio(audio_path, self._model.sample_rate) + kwargs["ref_text"] = reference_text + optional = {"instruct": instruct, "temperature": temperature, "top_p": top_p, "top_k": top_k} + kwargs.update({key: value for key, value in optional.items() if value is not None}) + + results = [] + for chunk in split_long_text(text): + results.extend(self._model.generate(text=chunk, **kwargs)) + if not results: + raise RuntimeError("model produced no audio") + sample_rates = {result.sample_rate for result in results} + if len(sample_rates) != 1: + raise RuntimeError("model returned segments with different sample rates") + segments = [np.asarray(result.audio, dtype=np.float32) for result in results] + return np.ascontiguousarray(np.concatenate(segments)), sample_rates.pop() diff --git a/tests/test_cli.py b/tests/test_cli.py index a355dd4..9cfd9c5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -154,7 +154,18 @@ def _norm_ns(text=None, file=None, **overrides): class TestCmdSpeak: def test_with_text_calls_engine_speak(self, fake_stackvox): - rc = cli._cmd_speak(_ns(voice="af_sarah", speed=1.0, lang="en-us", text="hello", out=None)) + rc = cli._cmd_speak( + _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + text="hello", + out=None, + ) + ) assert rc == 0 fake_stackvox.return_value.speak.assert_called_once_with("hello") @@ -168,27 +179,70 @@ def test_with_out_writes_wav_instead_of_playing(self, fake_stackvox, mocker, tmp sf_write = mocker.patch.object(cli.sf, "write") out = tmp_path / "out.wav" - rc = cli._cmd_speak(_ns(voice="af_sarah", speed=1.0, lang="en-us", text="hi", out=out)) + rc = cli._cmd_speak( + _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + text="hi", + out=out, + ) + ) assert rc == 0 sf_write.assert_called_once() fake_stackvox.return_value.speak.assert_not_called() def test_blank_input_returns_error(self, fake_stackvox, capsys): - rc = cli._cmd_speak(_ns(voice="af_sarah", speed=1.0, lang="en-us", text=" ", out=None)) + rc = cli._cmd_speak( + _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + text=" ", + out=None, + ) + ) assert rc == 1 assert "provide text" in capsys.readouterr().err fake_stackvox.return_value.speak.assert_not_called() def test_normalize_transforms_text_before_engine(self, fake_stackvox): - args = _norm_ns(text="# Heading", voice="af_sarah", speed=1.0, lang="en-us", out=None, normalize=True) + args = _norm_ns( + text="# Heading", + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + out=None, + normalize=True, + ) rc = cli._cmd_speak(args) assert rc == 0 fake_stackvox.return_value.speak.assert_called_once_with("Heading.") def test_no_normalize_leaves_text_untouched(self, fake_stackvox): # `normalize` absent from the namespace mirrors the flag being off. - rc = cli._cmd_speak(_ns(voice="af_sarah", speed=1.0, lang="en-us", text="# Heading", out=None)) + rc = cli._cmd_speak( + _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + text="# Heading", + out=None, + ) + ) assert rc == 0 fake_stackvox.return_value.speak.assert_called_once_with("# Heading") @@ -238,23 +292,136 @@ def test_normalize_transforms_text_before_daemon(self, mocker): class TestCmdServe: def test_propagates_serve_args(self, mocker): serve = mocker.patch.object(cli.daemon, "serve") - rc = cli._cmd_serve(_ns(voice="bf_emma", speed=1.1, lang="en-gb")) + rc = cli._cmd_serve( + _ns( + voice="bf_emma", speed=1.1, lang="en-gb", backend="kokoro", model_dir=None, model_adapter=None + ) + ) assert rc == 0 - serve.assert_called_once_with(voice="bf_emma", speed=1.1, lang="en-gb", custom_voices=BUILTIN_VOICES) + serve.assert_called_once_with( + voice="bf_emma", + speed=1.1, + lang="en-gb", + custom_voices=BUILTIN_VOICES, + backend="kokoro", + model_dir=None, + model_adapter=None, + ) def test_voice_mix_default_starts_daemon_with_its_lang(self, mocker): serve = mocker.patch.object(cli.daemon, "serve") - rc = cli._cmd_serve(_ns(voice="ramona", speed=None, lang=None)) + rc = cli._cmd_serve( + _ns(voice="ramona", speed=None, lang=None, backend="kokoro", model_dir=None, model_adapter=None) + ) assert rc == 0 assert serve.call_args.kwargs["lang"] == "en-gb" def test_returns_one_when_daemon_already_running(self, mocker, capsys): mocker.patch.object(cli.daemon, "serve", side_effect=RuntimeError("daemon already running")) - rc = cli._cmd_serve(_ns(voice="af_sarah", speed=1.0, lang="en-us")) + rc = cli._cmd_serve( + _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="kokoro", + model_dir=None, + model_adapter=None, + ) + ) assert rc == 1 assert "already running" in capsys.readouterr().err +class TestMlxCli: + def test_speak_passes_backend_and_generation_options(self, fake_stackvox, tmp_path): + args = _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="mlx", + model_dir=tmp_path, + model_adapter=None, + text="hello", + out=None, + reference_audio=tmp_path / "ref.wav", + reference_text="Ref.", + instruct=None, + temperature=0.5, + top_p=None, + top_k=None, + ) + + rc = cli._cmd_speak(args) + + assert rc == 0 + assert fake_stackvox.call_args.kwargs["backend"] == "mlx" + assert fake_stackvox.call_args.kwargs["model_dir"] == tmp_path + fake_stackvox.return_value.speak.assert_called_once_with( + "hello", reference_audio=tmp_path / "ref.wav", reference_text="Ref.", temperature=0.5 + ) + + def test_say_forwards_generation_options_to_daemon(self, mocker, tmp_path): + say = mocker.patch.object(cli.daemon, "say", return_value=(True, "ok")) + args = _ns( + voice=None, + speed=None, + lang=None, + text="hi", + fallback_say=False, + reference_audio=tmp_path / "ref.wav", + reference_text="Ref.", + instruct="Warmly.", + ) + + assert cli._cmd_say(args) == 0 + assert say.call_args.kwargs["reference_audio"] == tmp_path / "ref.wav" + assert say.call_args.kwargs["instruct"] == "Warmly." + + def test_serve_passes_backend_and_generation_defaults(self, mocker, tmp_path): + serve = mocker.patch.object(cli.daemon, "serve") + args = _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="mlx", + model_dir=tmp_path, + model_adapter=None, + top_k=12, + ) + + assert cli._cmd_serve(args) == 0 + serve.assert_called_once_with( + voice="af_sarah", + speed=1.0, + lang="en-us", + custom_voices=BUILTIN_VOICES, + backend="mlx", + model_dir=tmp_path, + model_adapter=None, + top_k=12, + ) + + def test_mlx_backend_without_model_dir_is_a_usage_error(self, mocker, capsys): + mocker.patch.object(cli.sys, "argv", ["stackvox", "speak", "--backend", "mlx", "hi"]) + with pytest.raises(SystemExit) as exc: + cli.main() + assert exc.value.code == 2 + assert "requires --model-dir" in capsys.readouterr().err + + def test_generation_options_on_kokoro_are_a_usage_error(self, mocker, capsys): + mocker.patch.object(cli.sys, "argv", ["stackvox", "serve", "--instruct", "Warmly."]) + with pytest.raises(SystemExit) as exc: + cli.main() + assert exc.value.code == 2 + assert "require --backend mlx" in capsys.readouterr().err + + def test_completion_lists_mlx_flags(self, capsys): + cli._cmd_completion(_ns(shell="bash")) + script = capsys.readouterr().out + assert "--backend" in script + assert "--reference-audio" in script + + class TestCmdStop: def test_returns_zero_when_daemon_already_stopped(self, mocker, capsys): mocker.patch.object(cli.daemon, "is_running", return_value=False) @@ -624,3 +791,46 @@ def test_say_sends_the_resolved_mix_settings_to_the_daemon(self, mocker, monkeyp rc = cli._cmd_say(_ns(voice="ramona", speed=1.1, lang=None, text="hi", fallback_say=False)) assert rc == 0 say.assert_called_once_with("hi", voice="ramona", speed=1.1, lang="en-gb") + + +class TestModelAdapterCli: + def test_speak_passes_adapter_to_engine(self, fake_stackvox, tmp_path): + adapter = tmp_path / "adapter.py" + args = _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="mlx", + model_dir=tmp_path, + model_adapter=adapter, + text="hi", + out=None, + ) + + assert cli._cmd_speak(args) == 0 + assert fake_stackvox.call_args.kwargs["model_adapter"] == adapter + + def test_model_load_error_prints_message_and_returns_one(self, fake_stackvox, capsys, tmp_path): + fake_stackvox.side_effect = cli.ModelLoadError("could not load; pass --model-adapter") + args = _ns( + voice="af_sarah", + speed=1.0, + lang="en-us", + backend="mlx", + model_dir=tmp_path, + model_adapter=None, + text="hi", + out=None, + ) + + rc = cli._cmd_speak(args) + + assert rc == 1 + assert capsys.readouterr().err == "[stackvox] could not load; pass --model-adapter\n" + + def test_adapter_on_kokoro_is_a_usage_error(self, mocker, capsys): + mocker.patch.object(cli.sys, "argv", ["stackvox", "speak", "--model-adapter", "a.py", "hi"]) + with pytest.raises(SystemExit) as exc: + cli.main() + assert exc.value.code == 2 + assert "require --backend mlx" in capsys.readouterr().err diff --git a/tests/test_daemon.py b/tests/test_daemon.py index f2e0c4d..4a7a76d 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -78,6 +78,16 @@ def test_say_without_overrides_passes_only_text(self, mocker): daemon.say("hi") assert send.call_args.args[0] == {"text": "hi"} + def test_say_serializes_generation_options(self, mocker, tmp_path): + send = mocker.patch.object(daemon, "send", return_value=(True, "ok")) + daemon.say("hi", reference_audio=tmp_path / "ref.wav", reference_text="Ref.", top_k=10) + assert send.call_args.args[0] == { + "text": "hi", + "reference_audio": str(tmp_path / "ref.wav"), + "reference_text": "Ref.", + "top_k": 10, + } + def test_stop_sends_command_stop(self, mocker): # _read_pid is mocked out so the wait-for-exit loop can't reach a real # daemon's pid file and block on a live process. diff --git a/tests/test_daemon_protocol.py b/tests/test_daemon_protocol.py index ad6d0a3..f172c09 100644 --- a/tests/test_daemon_protocol.py +++ b/tests/test_daemon_protocol.py @@ -122,6 +122,36 @@ def test_non_string_text_is_refused_and_the_worker_keeps_playing(server: ServerH assert server.tts.speak.call_args.args[0] == "hello" +def test_generation_options_rejected_by_kokoro_daemon(server: ServerHarness): + server.tts.backend = "kokoro" + reply = _roundtrip(server.sock, json.dumps({"text": "hi", "instruct": "Warmly."}) + "\n") + assert reply == "err: generation options require a daemon started with --backend mlx" + server.tts.speak.assert_not_called() + + +def test_generation_request_overrides_serve_defaults(server: ServerHarness): + import time + + server.tts.backend = "mlx" + server.state.generation_defaults = { + "reference_audio": "/default.wav", + "reference_text": "Default.", + "top_k": 20, + } + + reply = _roundtrip(server.sock, json.dumps({"text": "hi", "top_k": 5}) + "\n") + + assert reply == "ok" + deadline = time.monotonic() + 1.0 + while not server.tts.speak.call_args_list and time.monotonic() < deadline: + time.sleep(0.01) + kwargs = server.tts.speak.call_args.kwargs + assert kwargs["reference_audio"] == "/default.wav" + assert kwargs["reference_text"] == "Default." + assert kwargs["top_k"] == 5 + assert kwargs["instruct"] is None + + def test_full_queue_returns_busy(server: ServerHarness): from stackvox import daemon diff --git a/tests/test_engine.py b/tests/test_engine.py index 0849599..b1fc6c0 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -544,3 +544,118 @@ def test_downloads_only_missing_files(self, mocker, tmp_path): assert download.call_count == 1 url_arg, dest_arg = download.call_args.args assert dest_arg.name == "voices-v1.0.bin" + + +@pytest.fixture +def fake_mlx(mocker): + """Mock MlxBackend at its import site so no MLX model is loaded.""" + from stackvox import mlx_backend + + return mocker.patch.object(mlx_backend, "MlxBackend") + + +class TestMlxBackend: + def test_requires_model_dir(self): + with pytest.raises(ValueError, match="requires model_dir"): + engine.Stackvox(backend="mlx") + + def test_rejects_unknown_backend(self): + with pytest.raises(ValueError, match="unsupported backend"): + engine.Stackvox(backend="nope") + + def test_does_not_load_kokoro(self, fake_mlx, fake_ensure_models, tmp_path): + engine.Stackvox(backend="mlx", model_dir=tmp_path) + fake_ensure_models.assert_not_called() + fake_mlx.assert_called_once_with(tmp_path, adapter=None) + + def test_synthesize_routes_generation_options(self, fake_mlx, tmp_path): + fake_mlx.return_value.synthesize.return_value = (np.zeros(4, dtype=np.float32), 44100) + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path, speed=1.1) + + result = tts.synthesize("hi", reference_audio="ref.wav", reference_text="Ref.", top_k=10) + + assert result[1] == 44100 + fake_mlx.return_value.synthesize.assert_called_once_with( + "hi", + speed=1.1, + reference_audio="ref.wav", + reference_text="Ref.", + instruct=None, + temperature=None, + top_p=None, + top_k=10, + ) + + def test_voices_is_empty(self, fake_mlx, tmp_path): + assert engine.Stackvox(backend="mlx", model_dir=tmp_path).voices() == [] + + def test_streams_mlx_chunks_not_single_sentences(self, fake_mlx, fake_audio, tmp_path, mocker): + from stackvox import mlx_backend + + fake_mlx.return_value.synthesize.return_value = (np.zeros(4, dtype=np.float32), 44100) + mocker.patch.object(mlx_backend, "split_long_text", return_value=["chunk one.", "chunk two."]) + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path) + + tts.speak("One. Two. Three.") + + texts = [call.args[0] for call in fake_mlx.return_value.synthesize.call_args_list] + assert texts == ["chunk one.", "chunk two."] + + def test_speak_forwards_generation_options(self, fake_mlx, fake_audio, tmp_path): + fake_mlx.return_value.synthesize.return_value = (np.zeros(4, dtype=np.float32), 44100) + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path) + + tts.speak("One.", reference_audio="ref.wav", top_k=5) + + kwargs = fake_mlx.return_value.synthesize.call_args.kwargs + assert kwargs["reference_audio"] == "ref.wav" + assert kwargs["top_k"] == 5 + + def test_synthesize_stream_forwards_generation_options(self, fake_mlx, tmp_path): + fake_mlx.return_value.synthesize.return_value = (np.zeros(4, dtype=np.float32), 44100) + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path) + + list(tts.synthesize_stream("One.", instruct="Warmly.")) + + assert fake_mlx.return_value.synthesize.call_args.kwargs["instruct"] == "Warmly." + + @pytest.mark.parametrize("option", [{"threads": 2}, {"session_options": object()}]) + def test_rejects_kokoro_thread_options(self, fake_mlx, tmp_path, option): + with pytest.raises(ValueError, match="require the kokoro backend"): + engine.Stackvox(backend="mlx", model_dir=tmp_path, **option) + fake_mlx.assert_not_called() + + def test_speak_sequence_synthesizes_serially(self, fake_mlx, fake_audio, tmp_path, mocker): + fake_mlx.return_value.synthesize.return_value = (np.zeros(4, dtype=np.float32), 44100) + pool = mocker.patch("concurrent.futures.ThreadPoolExecutor") + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path) + + tts.speak_sequence([{"text": "a"}, {"text": "b"}]) + + pool.assert_not_called() + assert fake_mlx.return_value.synthesize.call_count == 2 + + +class TestKokoroRejectsGenerationOptions: + @pytest.mark.parametrize( + "option", + [ + {"reference_audio": "ref.wav"}, + {"reference_text": "Ref."}, + {"instruct": "Warmly."}, + {"temperature": 0.5}, + {"top_p": 0.5}, + {"top_k": 5}, + ], + ) + def test_synthesize_raises(self, fake_kokoro, option): + tts = engine.Stackvox() + with pytest.raises(ValueError, match="require the mlx backend"): + tts.synthesize("hi", **option) + fake_kokoro.return_value.create.assert_not_called() + + +def test_mlx_backend_receives_model_adapter(fake_mlx, tmp_path): + adapter = tmp_path / "adapter.py" + engine.Stackvox(backend="mlx", model_dir=tmp_path, model_adapter=adapter) + fake_mlx.assert_called_once_with(tmp_path, adapter=adapter) diff --git a/tests/test_mlx_backend.py b/tests/test_mlx_backend.py new file mode 100644 index 0000000..3c4b2a2 --- /dev/null +++ b/tests/test_mlx_backend.py @@ -0,0 +1,275 @@ +"""MLX backend tests with MLX Audio mocked at the package boundary.""" + +from __future__ import annotations + +import sys +from types import ModuleType, SimpleNamespace + +import numpy as np +import pytest + +from stackvox import mlx_backend + + +@pytest.fixture +def backend(mocker, tmp_path): + model_dir = tmp_path / "model" + model_dir.mkdir() + model = mocker.MagicMock() + mocker.patch.object(mlx_backend, "_load_model", return_value=model) + return mlx_backend.MlxBackend(model_dir), model + + +@pytest.fixture +def fake_mlx_audio(mocker): + """Install a stub `mlx_audio.tts.utils.load_model` so loading needs no MLX.""" + load_model = mocker.MagicMock(name="load_model") + utils = ModuleType("mlx_audio.tts.utils") + utils.load_model = load_model # type: ignore[attr-defined] + mocker.patch.dict( + sys.modules, + { + "mlx_audio": ModuleType("mlx_audio"), + "mlx_audio.tts": ModuleType("mlx_audio.tts"), + "mlx_audio.tts.utils": utils, + }, + ) + return load_model + + +def _write_adapter(tmp_path, body): + path = tmp_path / "adapter.py" + path.write_text(body) + return path + + +class TestLoading: + def test_loads_resolved_local_model(self, mocker, tmp_path): + model_dir = tmp_path / "model" + model_dir.mkdir() + load = mocker.patch.object(mlx_backend, "_load_model") + mlx_backend.MlxBackend(model_dir) + load.assert_called_once_with(model_dir.resolve(), None) + + def test_missing_model_directory_fails_before_import(self, tmp_path): + with pytest.raises(mlx_backend.ModelLoadError, match="model directory"): + mlx_backend.MlxBackend(tmp_path / "missing") + + def test_without_adapter_uses_mlx_audio_loader(self, fake_mlx_audio, tmp_path): + actual = mlx_backend._load_model(tmp_path, None) + fake_mlx_audio.assert_called_once_with(tmp_path) + assert actual is fake_mlx_audio.return_value + + def test_adapter_receives_model_dir_and_default_loader(self, fake_mlx_audio, tmp_path): + adapter = _write_adapter( + tmp_path, + "def load(model_dir, load_model):\n return ('adapted', model_dir, load_model(model_dir))\n", + ) + + actual = mlx_backend._load_model(tmp_path, adapter) + + assert actual == ("adapted", tmp_path, fake_mlx_audio.return_value) + + +class TestLoadErrors: + def test_native_failure_suggests_model_adapter(self, fake_mlx_audio, tmp_path): + fake_mlx_audio.side_effect = ValueError("Missing 358 parameters: \nlayer.0.weight,\nlayer.1.weight") + + with pytest.raises(mlx_backend.ModelLoadError) as exc: + mlx_backend._load_model(tmp_path, None) + + message = str(exc.value) + assert f"could not load the model in {tmp_path}" in message + assert "ValueError: Missing 358 parameters:" in message + assert "layer.0.weight" not in message + assert "--model-adapter" in message + assert isinstance(exc.value.__cause__, ValueError) + + def test_long_underlying_message_is_truncated(self, fake_mlx_audio, tmp_path): + fake_mlx_audio.side_effect = ValueError("x" * 1000) + + with pytest.raises(mlx_backend.ModelLoadError) as exc: + mlx_backend._load_model(tmp_path, None) + + assert "x" * (mlx_backend._ERROR_SUMMARY_CHARS - 1) + "…" in str(exc.value) + assert "x" * mlx_backend._ERROR_SUMMARY_CHARS not in str(exc.value) + + def test_adapter_failure_names_the_adapter_without_suggesting_one(self, fake_mlx_audio, tmp_path): + adapter = _write_adapter(tmp_path, "def load(model_dir, load_model):\n raise KeyError('codec')\n") + + with pytest.raises(mlx_backend.ModelLoadError) as exc: + mlx_backend._load_model(tmp_path, adapter) + + message = str(exc.value) + assert f"model adapter {adapter} failed to load" in message + assert "KeyError: 'codec'" in message + assert "--model-adapter" not in message + + def test_adapter_import_error_is_reported(self, tmp_path): + adapter = _write_adapter(tmp_path, "import not_a_real_module_xyz\n") + + with pytest.raises(mlx_backend.ModelLoadError, match="raised while importing.*ModuleNotFoundError"): + mlx_backend.load_adapter(adapter) + + +class TestLoadAdapter: + def test_returns_load_function(self, tmp_path): + adapter = _write_adapter(tmp_path, "def load(model_dir, load_model):\n return 42\n") + assert mlx_backend.load_adapter(adapter)(tmp_path, lambda model_dir: None) == 42 + + def test_missing_file_is_an_error(self, tmp_path): + with pytest.raises(mlx_backend.ModelLoadError, match="model adapter not found"): + mlx_backend.load_adapter(tmp_path / "nope.py") + + def test_script_without_load_is_an_error(self, tmp_path): + adapter = _write_adapter(tmp_path, "value = 1\n") + with pytest.raises(mlx_backend.ModelLoadError, match="must define load"): + mlx_backend.load_adapter(adapter) + + +class TestSynthesize: + def test_concatenates_generated_segments(self, backend): + engine, model = backend + model.generate.return_value = iter( + [ + SimpleNamespace(audio=np.array([0.1, 0.2]), sample_rate=44100), + SimpleNamespace(audio=np.array([0.3]), sample_rate=44100), + ] + ) + + samples, sample_rate = engine.synthesize("hello") + + np.testing.assert_allclose(samples, [0.1, 0.2, 0.3]) + assert samples.dtype == np.float32 + assert sample_rate == 44100 + + def test_passes_reference_and_sampling_options(self, backend, mocker, tmp_path): + engine, model = backend + loaded_audio = object() + load_audio = mocker.patch.object(mlx_backend, "_load_audio", return_value=loaded_audio) + reference = tmp_path / "voice.wav" + reference.touch() + model.generate.return_value = iter([SimpleNamespace(audio=np.zeros(2), sample_rate=44100)]) + + engine.synthesize( + "hello", + reference_audio=str(reference), + reference_text="Reference transcript.", + instruct="Speak warmly.", + temperature=0.8, + top_p=0.9, + top_k=20, + ) + + kwargs = model.generate.call_args.kwargs + load_audio.assert_called_once_with(reference.resolve(), model.sample_rate) + assert kwargs["ref_audio"] is loaded_audio + assert kwargs["ref_text"] == "Reference transcript." + assert kwargs["instruct"] == "Speak warmly." + assert kwargs["temperature"] == 0.8 + assert kwargs["top_p"] == 0.9 + assert kwargs["top_k"] == 20 + + def test_unset_options_are_left_to_model_defaults(self, backend): + engine, model = backend + model.generate.return_value = iter([SimpleNamespace(audio=np.zeros(2), sample_rate=44100)]) + + engine.synthesize("hello") + + assert set(model.generate.call_args.kwargs) == {"text", "speed", "verbose"} + + @pytest.mark.parametrize( + ("reference_audio", "reference_text"), + [("voice.wav", None), (None, "Transcript")], + ) + def test_reference_audio_and_text_are_required_together(self, backend, reference_audio, reference_text): + engine, _ = backend + with pytest.raises(ValueError, match="requires both"): + engine.synthesize("hello", reference_audio=reference_audio, reference_text=reference_text) + + def test_missing_reference_audio_file_is_an_error(self, backend, tmp_path): + engine, _ = backend + with pytest.raises(FileNotFoundError, match="reference audio"): + engine.synthesize("hello", reference_audio=tmp_path / "nope.wav", reference_text="Transcript") + + def test_empty_generation_is_an_error(self, backend): + engine, model = backend + model.generate.return_value = iter([]) + with pytest.raises(RuntimeError, match="produced no audio"): + engine.synthesize("hello") + + def test_mixed_sample_rates_are_an_error(self, backend): + engine, model = backend + model.generate.return_value = iter( + [ + SimpleNamespace(audio=np.zeros(1), sample_rate=24000), + SimpleNamespace(audio=np.zeros(1), sample_rate=44100), + ] + ) + with pytest.raises(RuntimeError, match="different sample rates"): + engine.synthesize("hello") + + def test_long_text_is_generated_in_multiple_sentence_chunks(self, backend): + engine, model = backend + model.generate.side_effect = lambda **kwargs: iter( + [SimpleNamespace(audio=np.ones(1), sample_rate=44100)] + ) + text = "First sentence. " * 80 + + samples, _ = engine.synthesize(text) + + assert model.generate.call_count > 1 + assert len(samples) == model.generate.call_count + assert all( + len(call.kwargs["text"]) <= mlx_backend.CHUNK_CHARS for call in model.generate.call_args_list + ) + + +class TestSwapped: + def test_restores_own_attribute(self): + class Owner: + @classmethod + def build(cls): + return "original" + + with mlx_backend.swapped(Owner, "build", lambda: "patched"): + assert Owner.build() == "patched" + + assert Owner.build() == "original" + assert isinstance(vars(Owner)["build"], classmethod) + + def test_removes_override_of_inherited_attribute(self): + class Base: + def run(self): + return "base" + + class Child(Base): + pass + + with mlx_backend.swapped(Child, "run", lambda self: "patched"): + assert Child().run() == "patched" + + assert "run" not in vars(Child) + assert Child().run() == "base" + + def test_restores_after_exception(self): + class Owner: + value = 1 + + with pytest.raises(RuntimeError), mlx_backend.swapped(Owner, "value", 2): + raise RuntimeError + + assert Owner.value == 1 + + +class TestSplitLongText: + def test_short_text_is_one_chunk(self): + assert mlx_backend.split_long_text("One. Two.") == ["One. Two."] + + def test_blank_text_yields_no_chunks(self): + assert mlx_backend.split_long_text(" \n ") == [] + + def test_overlong_sentence_splits_on_words(self): + chunks = mlx_backend.split_long_text("word " * 200, limit=50) + assert all(len(chunk) <= 50 for chunk in chunks) + assert " ".join(chunks).split() == ["word"] * 200 From d34da9e78c0d22f125b3534c1c317d0f655edfab Mon Sep 17 00:00:00 2001 From: StuBehan Date: Fri, 25 Sep 2026 23:40:59 +0100 Subject: [PATCH 2/4] fix: run MLX work on one thread and shrink chunks MLX binds GPU streams to threads, so a model loaded on one thread failed with "There is no Stream(gpu, 0) in current thread" when streaming playback or the daemon worker generated on another. Live `speak` and all daemon playback were broken; only `--out` worked. MlxBackend now owns a single daemon thread for load, reference decoding and generation. Also lower CHUNK_CHARS from 400 to 170: long prompts made autoregressive models skip or invent speech, losing a quarter to a third of the text in testing, while ~2-sentence chunks kept all of it. Co-Authored-By: Claude Opus 5.5 --- stackvox/mlx_backend.py | 71 +++++++++++++++++++++++++++++++++------ tests/test_mlx_backend.py | 60 +++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 10 deletions(-) diff --git a/stackvox/mlx_backend.py b/stackvox/mlx_backend.py index 1047271..3365add 100644 --- a/stackvox/mlx_backend.py +++ b/stackvox/mlx_backend.py @@ -9,22 +9,27 @@ from __future__ import annotations import importlib.util +import queue import re +import threading from collections.abc import Callable, Iterator +from concurrent.futures import Future from contextlib import contextmanager from pathlib import Path from threading import Lock -from typing import Any, cast +from typing import Any, TypeVar, cast import numpy as np # Adapters typically swap class attributes on third-party modules, which is # process-global; serialise loads so two engines can't interleave the swaps. _LOAD_LOCK = Lock() -# Long inputs are generated in sentence-packed chunks this size or smaller: -# small enough to stay under typical per-call token limits and give prompt -# first audio when streaming, large enough to keep prosody natural. -CHUNK_CHARS = 400 +# Long inputs are generated in sentence-packed chunks this size or smaller, +# roughly two sentences. Autoregressive TTS models tend to drift on long +# prompts, skipping or inventing speech; in testing, 400-char chunks lost a +# quarter to a third of the text while ~170 kept all of it. Smaller chunks also +# bring the first streamed audio forward. +CHUNK_CHARS = 170 _SENTENCE_BOUNDARY = re.compile(r"(?<=[.!?])\s+|\n+") # Cap on how much of an underlying error is echoed; MLX Audio's messages can @@ -33,6 +38,7 @@ LoadModel = Callable[[Path], Any] Adapter = Callable[[Path, LoadModel], Any] +_Result = TypeVar("_Result") class ModelLoadError(RuntimeError): @@ -161,15 +167,49 @@ def _load_audio(path: Path, sample_rate: int) -> Any: return load_audio(str(path), sample_rate=sample_rate) +class _MlxThread: + """A single daemon thread that runs every MLX call for one backend. + + MLX binds GPU streams to threads: a model loaded on one thread fails with + "There is no Stream(gpu, 0) in current thread" when it first generates on + another, which is exactly what streaming playback and the daemon worker do. + Funnelling load and generation through one thread avoids that and also + serialises access to a model that isn't safe to call concurrently. A daemon + thread (rather than an executor) never holds up interpreter exit. + """ + + def __init__(self) -> None: + self._jobs: queue.Queue[tuple[Callable[[], Any], Future[Any]]] = queue.Queue() + self.thread = threading.Thread(target=self._run, daemon=True, name="stackvox-mlx") + self.thread.start() + + def _run(self) -> None: + while True: + job, future = self._jobs.get() + try: + future.set_result(job()) + except BaseException as exc: # hand every failure back to the caller + future.set_exception(exc) + + def call(self, job: Callable[[], _Result]) -> _Result: + future: Future[_Result] = Future() + self._jobs.put((job, future)) + return future.result() + + class MlxBackend: - """Load one local MLX Audio model and expose stackvox's synthesis contract.""" + """Load one local MLX Audio model and expose stackvox's synthesis contract. + + Safe to call from any thread: all MLX work runs on the backend's own thread. + """ def __init__(self, model_dir: Path, adapter: Path | None = None) -> None: model_dir = model_dir.expanduser().resolve() if not model_dir.is_dir(): raise ModelLoadError(f"model directory not found: {model_dir}") self.model_dir = model_dir - self._model: Any = _load_model(model_dir, adapter) + self._mlx_thread = _MlxThread() + self._model: Any = self._mlx_thread.call(lambda: _load_model(model_dir, adapter)) def synthesize( self, @@ -188,16 +228,27 @@ def synthesize( if (reference_audio is None) != (reference_text is None): raise ValueError("voice cloning requires both reference_audio and reference_text") - kwargs: dict[str, Any] = {"speed": speed, "verbose": False} + audio_path = None if reference_audio is not None: audio_path = Path(reference_audio).expanduser().resolve() if not audio_path.is_file(): raise FileNotFoundError(f"reference audio not found: {audio_path}") - kwargs["ref_audio"] = _load_audio(audio_path, self._model.sample_rate) - kwargs["ref_text"] = reference_text optional = {"instruct": instruct, "temperature": temperature, "top_p": top_p, "top_k": top_k} + kwargs: dict[str, Any] = {"speed": speed, "verbose": False} kwargs.update({key: value for key, value in optional.items() if value is not None}) + return self._mlx_thread.call(lambda: self._generate(text, kwargs, audio_path, reference_text)) + def _generate( + self, text: str, kwargs: dict[str, Any], audio_path: Path | None, reference_text: str | None + ) -> tuple[np.ndarray, int]: + """Runs on the MLX thread: decoding the reference and converting results + to NumPy both evaluate MLX arrays, so they belong here too.""" + if audio_path is not None: + kwargs = { + **kwargs, + "ref_audio": _load_audio(audio_path, self._model.sample_rate), + "ref_text": reference_text, + } results = [] for chunk in split_long_text(text): results.extend(self._model.generate(text=chunk, **kwargs)) diff --git a/tests/test_mlx_backend.py b/tests/test_mlx_backend.py index 3c4b2a2..f147ef2 100644 --- a/tests/test_mlx_backend.py +++ b/tests/test_mlx_backend.py @@ -3,6 +3,7 @@ from __future__ import annotations import sys +import threading from types import ModuleType, SimpleNamespace import numpy as np @@ -273,3 +274,62 @@ def test_overlong_sentence_splits_on_words(self): chunks = mlx_backend.split_long_text("word " * 200, limit=50) assert all(len(chunk) <= 50 for chunk in chunks) assert " ".join(chunks).split() == ["word"] * 200 + + +class TestMlxThread: + def test_load_and_generation_share_one_thread_across_callers(self, mocker, tmp_path): + seen = [] + model = mocker.MagicMock(sample_rate=44100) + + def record(name): + def side_effect(*args, **kwargs): + seen.append((name, threading.current_thread().name)) + return model if name == "load" else object() + + return side_effect + + def generate(**kwargs): + seen.append(("generate", threading.current_thread().name)) + return iter([SimpleNamespace(audio=np.ones(1), sample_rate=44100)]) + + model.generate.side_effect = generate + mocker.patch.object(mlx_backend, "_load_model", side_effect=record("load")) + mocker.patch.object(mlx_backend, "_load_audio", side_effect=record("load_audio")) + reference = tmp_path / "voice.wav" + reference.touch() + model_dir = tmp_path / "model" + model_dir.mkdir() + engine = mlx_backend.MlxBackend(model_dir) + + callers = [ + threading.Thread( + target=engine.synthesize, + args=("hello",), + kwargs={"reference_audio": reference, "reference_text": "Ref."}, + ) + for _ in range(3) + ] + for caller in callers: + caller.start() + for caller in callers: + caller.join() + engine.synthesize("from the main thread") + + assert {thread for _, thread in seen} == {"stackvox-mlx"} + assert [name for name, _ in seen].count("generate") == 4 + + def test_generation_errors_reach_the_caller(self, backend): + engine, model = backend + model.generate.side_effect = RuntimeError("gpu fell over") + with pytest.raises(RuntimeError, match="gpu fell over"): + engine.synthesize("hello") + + def test_load_errors_reach_the_caller(self, mocker, tmp_path): + mocker.patch.object(mlx_backend, "_load_model", side_effect=mlx_backend.ModelLoadError("bad model")) + with pytest.raises(mlx_backend.ModelLoadError, match="bad model"): + mlx_backend.MlxBackend(tmp_path) + + def test_chunk_limit_keeps_about_two_sentences(self): + sentence = "This is sentence number one of a longer passage used to check chunking." + chunks = mlx_backend.split_long_text(" ".join([sentence] * 6)) + assert all(chunk.count(".") <= 2 for chunk in chunks) From f0313c3b7b170843535527847447a82737fed5ed Mon Sep 17 00:00:00 2001 From: StuBehan Date: Fri, 25 Sep 2026 23:42:32 +0100 Subject: [PATCH 3/4] docs: update mlx chunk size in README Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5ff84a8..4a897d3 100644 --- a/README.md +++ b/README.md @@ -213,8 +213,10 @@ Generation options (`--reference-audio`, `--reference-text`, `--instruct`, model's own defaults apply otherwise; which ones a model honours depends on the model. They are rejected with an error unless the `mlx` backend is in use, both by `speak` and by a daemon running Kokoro. `--voice` and `--lang` apply to -Kokoro only. Playback streams in sentence-packed chunks of up to ~400 -characters, so the first audio arrives once the first chunk is generated. +Kokoro only. Playback streams in chunks of about two sentences (up to ~170 +characters), so the first audio arrives once the first chunk is generated; +short chunks also stop models drifting off-script on long text. Models slower +than real time will pause between chunks. ### Model adapters From bed3c80eaa6c10efb0683dda8447b46c9c35056b Mon Sep 17 00:00:00 2001 From: StuBehan Date: Thu, 22 Oct 2026 00:26:49 +0100 Subject: [PATCH 4/4] fix: replace kokoro asserts with a raise --- stackvox/engine.py | 14 ++++++++++---- tests/test_engine.py | 6 ++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/stackvox/engine.py b/stackvox/engine.py index 6aa266d..964e6a1 100644 --- a/stackvox/engine.py +++ b/stackvox/engine.py @@ -240,7 +240,7 @@ def synthesize( top_p=top_p, top_k=top_k, ) - assert self._kokoro is not None + kokoro = self._require_kokoro() mlx_only = { "reference_audio": reference_audio, "reference_text": reference_text, @@ -261,7 +261,7 @@ def synthesize( default_lang=self.lang, custom=self.custom_voices, ) - samples, sample_rate = self._kokoro.create( + samples, sample_rate = kokoro.create( text, voice=self._style(params.voice), speed=params.speed, @@ -320,14 +320,20 @@ def synthesize_stream( top_k=top_k, ) + def _require_kokoro(self) -> Kokoro: + # A raise rather than an assert: asserts vanish under `python -O`. + if self._kokoro is None: + raise RuntimeError(f"the {self.backend} backend has no Kokoro engine") + return self._kokoro + def _style(self, name: str) -> str | np.ndarray: """A Kokoro voice id passes straight through; a mix becomes its blended style vector.""" - assert self._kokoro is not None + kokoro = self._require_kokoro() mix = self.custom_voices.get(name) if mix is None: return name if name not in self._blends: - self._blends[name] = blend(name, mix, self._kokoro.get_voice_style, self._kokoro.get_voices()) + self._blends[name] = blend(name, mix, kokoro.get_voice_style, kokoro.get_voices()) return self._blends[name] def _cancel_active(self) -> None: diff --git a/tests/test_engine.py b/tests/test_engine.py index b1fc6c0..18818f7 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -619,6 +619,12 @@ def test_synthesize_stream_forwards_generation_options(self, fake_mlx, tmp_path) assert fake_mlx.return_value.synthesize.call_args.kwargs["instruct"] == "Warmly." + def test_kokoro_only_path_raises_rather_than_asserting(self, fake_mlx, tmp_path): + tts = engine.Stackvox(backend="mlx", model_dir=tmp_path) + + with pytest.raises(RuntimeError, match="mlx backend has no Kokoro engine"): + tts._style("af_sarah") + @pytest.mark.parametrize("option", [{"threads": 2}, {"session_options": object()}]) def test_rejects_kokoro_thread_options(self, fake_mlx, tmp_path, option): with pytest.raises(ValueError, match="require the kokoro backend"):