Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ dist/
*.bin
out/
*.wav
*.m4a
!docs/demo.wav
.DS_Store
.env
Expand Down
25 changes: 25 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -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
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,100 @@ 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 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

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:
Expand Down Expand Up @@ -281,4 +375,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.
7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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]]
Expand Down
111 changes: 99 additions & 12 deletions stackvox/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
;;
Expand All @@ -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
Expand All @@ -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") )
Expand Down Expand Up @@ -130,20 +136,25 @@ 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)")
_add_voice_args(p_speak, defaults)
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"
)
Expand All @@ -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")
Expand Down Expand Up @@ -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``.

Expand Down Expand Up @@ -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


Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Loading