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
31 changes: 29 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ speed = 1.1
lang = "en-gb"
```

CLI flags always win over config values, and config values always win over the built-in defaults. A missing file is fine — built-ins apply. A malformed file logs a warning and is ignored.
CLI flags always win over config values, and config values always win over the built-in defaults. The one thing between a flag and the config is a [voice mix](#voice-mixes)'s own `lang` and `speed`, so `--voice chip` stays transatlantic even when `[defaults]` sets `lang = "en-us"`. A missing file is fine — built-ins apply. A malformed file logs a warning and is ignored.

## Daemon mode

Expand Down Expand Up @@ -177,7 +177,34 @@ Kokoro ships voices across several languages. Voice prefix encodes gender + lang
| `jf_*`, `jm_*` | Japanese | `jf_alpha` |
| `zf_*`, `zm_*` | Mandarin Chinese | `zf_xiaoxiao` |

Run `stackvox voices` for the authoritative list.
Run `stackvox voices` for the authoritative list, which includes the voice mixes below.

### Voice mixes

Each Kokoro voice is a style vector, so a weighted blend of several makes a new voice between them. A mix is named, and the name works anywhere a voice id does: `--voice`, `Stackvox(voice=...)`, and the daemon's socket protocol. It also carries the `lang` and `speed` it was tuned with, which apply unless you pass your own.

Two ship built in, a transatlantic newsreader pair (American delivery, British vowels):

| Name | Mix | lang | speed |
| -------- | ----------------------------------------------------- | ------- | ----- |
| `chip` | `am_liam` 0.6, `bm_daniel` 0.4 | `en-gb` | 1.0 |
| `ramona` | `af_aoede` 0.5, `af_bella` 0.2, `bf_emma` 0.3 | `en-gb` | 1.0 |

```bash
stackvox speak --voice chip "Good evening, and welcome to the news."
stackvox say --voice ramona "Thanks Chip."
```

Define your own in the config file. Weights needn't sum to 1, and a table named after a built-in replaces it:

```toml
[voices.narrator]
mix = { am_michael = 0.6, bm_george = 0.4 }
lang = "en-gb" # optional
speed = 1.0 # optional
```

The daemon reads mixes when it starts, so restart it (`stackvox stop`, then `stackvox serve`) after editing them.

## Architecture

Expand Down
37 changes: 31 additions & 6 deletions stackvox/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from stackvox import config, daemon, paths, updates
from stackvox.engine import Stackvox
from stackvox.text import normalize_for_speech
from stackvox.voices import VoiceMix, VoiceParams, resolve


def _configure_logging() -> None:
Expand Down Expand Up @@ -185,9 +186,30 @@ def _build_parser(defaults: config.Defaults | None = None) -> argparse.ArgumentP


def _add_voice_args(parser: argparse.ArgumentParser, defaults: config.Defaults) -> None:
# Speed and lang default to None rather than the config value so a voice
# mix's own lang/speed can sit between an explicit flag and the config;
# handlers fill them in with _voice_params.
parser.add_argument("--voice", default=defaults.voice)
parser.add_argument("--speed", type=float, default=defaults.speed)
parser.add_argument("--lang", default=defaults.lang)
parser.add_argument(
"--speed", type=float, default=None, help="default: the voice mix's speed, then config"
)
parser.add_argument("--lang", default=None, help="default: the voice mix's lang, then config")


def _voice_params(args: argparse.Namespace) -> tuple[VoiceParams, dict[str, VoiceMix]]:
"""Resolve voice/speed/lang for a command, plus the voice mixes the engine should know."""
defaults = config.load_defaults()
custom = config.load_voices()
params = resolve(
args.voice,
args.speed,
args.lang,
default_voice=defaults.voice,
default_speed=defaults.speed,
default_lang=defaults.lang,
custom=custom,
)
return params, custom


def _add_normalize_args(parser: argparse.ArgumentParser, *, with_switch: bool) -> None:
Expand Down Expand Up @@ -360,7 +382,8 @@ def _cmd_speak(args: argparse.Namespace) -> int:
text = _resolve_normalized(text, args)
if text is None:
return 1
tts = Stackvox(voice=args.voice, speed=args.speed, lang=args.lang)
params, custom = _voice_params(args)
tts = Stackvox(voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom)
if args.out:
samples, sr = tts.synthesize(text)
sf.write(args.out, samples, sr)
Expand All @@ -379,7 +402,8 @@ def _cmd_say(args: argparse.Namespace) -> int:
text = _resolve_normalized(text, args)
if text is None:
return 1
ok, resp = daemon.say(text, voice=args.voice, speed=args.speed, lang=args.lang)
params, _ = _voice_params(args)
ok, resp = daemon.say(text, voice=params.voice, speed=params.speed, lang=params.lang)
if ok:
return 0
if args.fallback_say:
Expand Down Expand Up @@ -407,7 +431,8 @@ def _cmd_normalize(args: argparse.Namespace) -> int:

def _cmd_serve(args: argparse.Namespace) -> int:
try:
daemon.serve(voice=args.voice, speed=args.speed, lang=args.lang)
params, custom = _voice_params(args)
daemon.serve(voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom)
except RuntimeError as exc:
print(f"[stackvox] {exc}", file=sys.stderr)
return 1
Expand Down Expand Up @@ -468,7 +493,7 @@ def _cmd_status(_: argparse.Namespace) -> int:


def _cmd_voices(args: argparse.Namespace) -> int:
tts = Stackvox()
tts = Stackvox(custom_voices=config.load_voices())
for name in tts.voices():
print(name)
return 0
Expand Down
84 changes: 77 additions & 7 deletions stackvox/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""User config file: per-user defaults for voice / speed / lang.
"""User config file: per-user defaults for voice / speed / lang, and voice mixes.

Lives at `$XDG_CONFIG_HOME/stackvox/config.toml` (falling back to
`~/.config/stackvox/config.toml`), or wherever `STACKVOX_CONFIG` points if set.
Expand All @@ -11,6 +11,15 @@
voice = "bf_emma"
speed = 1.1
lang = "en-gb"

[voices.narrator]
mix = { am_michael = 0.6, bm_george = 0.4 }
lang = "en-gb"
speed = 1.0

Each ``[voices.<name>]`` table defines a Kokoro voice mix addressable by that
name, alongside the built-in ones in ``stackvox.voices``. A table with a
built-in's name replaces it.
"""

from __future__ import annotations
Expand All @@ -27,6 +36,7 @@
import tomli as tomllib

from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE
from stackvox.voices import BUILTIN_VOICES, VoiceMix

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -54,6 +64,17 @@ def config_path() -> Path:
return base / "stackvox" / "config.toml"


def _read(path: Path) -> dict | None:
"""Parse the config file, or None when it is missing or malformed (the latter logged)."""
if not path.is_file():
return None
try:
return tomllib.loads(path.read_text(encoding="utf-8"))
except (OSError, tomllib.TOMLDecodeError) as exc:
logger.warning("ignoring malformed stackvox config at %s: %s", path, exc)
return None


def load_defaults(path: Path | None = None) -> Defaults:
"""Read the config file and return resolved defaults.

Expand All @@ -62,12 +83,8 @@ def load_defaults(path: Path | None = None) -> Defaults:
`voice` keeps the built-in `speed` and `lang`.
"""
p = path or config_path()
if not p.is_file():
return Defaults()
try:
data = tomllib.loads(p.read_text(encoding="utf-8"))
except (OSError, tomllib.TOMLDecodeError) as exc:
logger.warning("ignoring malformed stackvox config at %s: %s", p, exc)
data = _read(p)
if data is None:
return Defaults()
section = data.get("defaults", {})
if not isinstance(section, dict):
Expand All @@ -78,3 +95,56 @@ def load_defaults(path: Path | None = None) -> Defaults:
speed=float(section.get("speed", DEFAULT_SPEED)),
lang=str(section.get("lang", DEFAULT_LANG)),
)


def load_voices(path: Path | None = None) -> dict[str, VoiceMix]:
"""Built-in voice mixes, overlaid with any ``[voices.<name>]`` tables in the config.

An invalid table is logged and skipped rather than failing the whole
config, matching how ``load_defaults`` treats a bad ``[defaults]``.
"""
voices = dict(BUILTIN_VOICES)
p = path or config_path()
data = _read(p)
if data is None:
return voices
section = data.get("voices", {})
if not isinstance(section, dict):
logger.warning("config %s: [voices] must be a table; ignoring", p)
return voices
for name, table in section.items():
mix = _parse_mix(table)
if mix is None:
logger.warning(
"config %s: [voices.%s] needs mix = { <kokoro voice> = <weight>, ... } "
"with positive weights, and optional string lang / numeric speed; ignoring",
p,
name,
)
continue
voices[name] = mix
return voices


def _parse_mix(table: object) -> VoiceMix | None:
if not isinstance(table, dict):
return None
weights = table.get("mix")
if not isinstance(weights, dict) or not weights:
return None
if not all(
isinstance(weight, (int, float)) and not isinstance(weight, bool) and weight > 0
for weight in weights.values()
):
return None
lang = table.get("lang")
speed = table.get("speed")
if lang is not None and not isinstance(lang, str):
return None
if speed is not None and (isinstance(speed, bool) or not isinstance(speed, (int, float))):
return None
return VoiceMix(
mix=tuple((str(voice), float(weight)) for voice, weight in weights.items()),
lang=lang,
speed=float(speed) if speed is not None else None,
)
17 changes: 13 additions & 4 deletions stackvox/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@
import sys
import threading
import time
from collections.abc import Mapping
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.paths import pid_path, socket_path
from stackvox.voices import VoiceMix

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -170,8 +172,10 @@ def _on_device_change(obj_id: int, n: int, addrs: Any, data: Any) -> int:


class _DaemonState:
def __init__(self, voice: str, speed: float, lang: str) -> None:
self.tts = Stackvox(voice=voice, speed=speed, lang=lang)
def __init__(
self, voice: str, speed: float, lang: str, custom_voices: Mapping[str, VoiceMix] | None = None
) -> None:
self.tts = Stackvox(voice=voice, speed=speed, lang=lang, custom_voices=custom_voices)
self.queue: queue.Queue[dict] = queue.Queue(maxsize=MAX_QUEUE)
self.stop_event = threading.Event()
self.worker = threading.Thread(target=self._worker, daemon=True)
Expand Down Expand Up @@ -309,15 +313,20 @@ def _worker() -> None:
threading.Thread(target=_worker, daemon=True, name="update-check").start()


def serve(voice: str = DEFAULT_VOICE, speed: float = DEFAULT_SPEED, lang: str = DEFAULT_LANG) -> None:
def serve(
voice: str = DEFAULT_VOICE,
speed: float = DEFAULT_SPEED,
lang: str = DEFAULT_LANG,
custom_voices: Mapping[str, VoiceMix] | None = None,
) -> None:
if is_running():
raise RuntimeError(f"daemon already running (pid {PID_PATH.read_text().strip()})")

SOCKET_PATH.parent.mkdir(parents=True, exist_ok=True)
if SOCKET_PATH.exists():
SOCKET_PATH.unlink()

state = _DaemonState(voice=voice, speed=speed, lang=lang)
state = _DaemonState(voice=voice, speed=speed, lang=lang, custom_voices=custom_voices)
server = _UnixServer(str(SOCKET_PATH), _Handler)
server.state = state # type: ignore[attr-defined]

Expand Down
37 changes: 33 additions & 4 deletions stackvox/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
import sys
import threading
import urllib.request
from collections.abc import Mapping
from pathlib import Path

import numpy as np
import sounddevice as sd
from kokoro_onnx import Kokoro

from stackvox.paths import cache_dir as _default_cache_dir
from stackvox.voices import BUILTIN_VOICES, VoiceMix, blend, resolve

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -104,6 +106,11 @@ class Stackvox:
Example:
tts = Stackvox(voice="af_bella")
tts.speak("Hello world")

``custom_voices`` maps names to Kokoro voice mixes (see ``stackvox.voices``)
and defaults to the built-in ones. A mix's own lang and speed beat the
``lang`` and ``speed`` given here, which act as defaults; pass them per call
to override a mix.
"""

def __init__(
Expand All @@ -112,10 +119,13 @@ def __init__(
speed: float = DEFAULT_SPEED,
lang: str = DEFAULT_LANG,
cache_dir: Path | None = None,
custom_voices: Mapping[str, VoiceMix] | 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 = Kokoro(str(model_path), str(voices_path))
self._stop_event = threading.Event()
Expand All @@ -131,14 +141,32 @@ def synthesize(
lang: str | None = None,
) -> tuple[np.ndarray, int]:
"""Return (samples, sample_rate) without playing."""
params = resolve(
voice,
speed,
lang,
default_voice=self.voice,
default_speed=self.speed,
default_lang=self.lang,
custom=self.custom_voices,
)
samples, sample_rate = self._kokoro.create(
text,
voice=voice or self.voice,
speed=speed if speed is not None else self.speed,
lang=lang or self.lang,
voice=self._style(params.voice),
speed=params.speed,
lang=params.lang,
)
return samples, sample_rate

def _style(self, name: str) -> str | np.ndarray:
"""A Kokoro voice id passes straight through; a mix becomes its blended style vector."""
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())
return self._blends[name]

def _cancel_active(self) -> None:
"""Supersede any in-progress stream so a new ``speak`` starts clean.

Expand Down Expand Up @@ -291,7 +319,8 @@ def stop(self) -> None:
sd.stop()

def voices(self) -> list[str]:
return sorted(self._kokoro.get_voices())
"""Kokoro voice ids plus the names of custom voice mixes."""
return sorted(set(self._kokoro.get_voices()) | set(self.custom_voices))

def speak_sequence(
self,
Expand Down
Loading
Loading