diff --git a/README.md b/README.md index 12a0b88..2e28d2c 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/stackvox/cli.py b/stackvox/cli.py index 6357a5e..705c1d9 100644 --- a/stackvox/cli.py +++ b/stackvox/cli.py @@ -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: @@ -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: @@ -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) @@ -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: @@ -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 @@ -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 diff --git a/stackvox/config.py b/stackvox/config.py index 8eb0bc9..c72a529 100644 --- a/stackvox/config.py +++ b/stackvox/config.py @@ -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. @@ -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.]`` 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 @@ -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__) @@ -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. @@ -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): @@ -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.]`` 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 = { = , ... } " + "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, + ) diff --git a/stackvox/daemon.py b/stackvox/daemon.py index 5d7dbbf..bca0c3c 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -27,6 +27,7 @@ import sys import threading import time +from collections.abc import Mapping from typing import Any import sounddevice as sd @@ -34,6 +35,7 @@ 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__) @@ -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) @@ -309,7 +313,12 @@ 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()})") @@ -317,7 +326,7 @@ def serve(voice: str = DEFAULT_VOICE, speed: float = DEFAULT_SPEED, lang: str = 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] diff --git a/stackvox/engine.py b/stackvox/engine.py index 9d07683..cc15433 100644 --- a/stackvox/engine.py +++ b/stackvox/engine.py @@ -8,6 +8,7 @@ import sys import threading import urllib.request +from collections.abc import Mapping from pathlib import Path import numpy as np @@ -15,6 +16,7 @@ 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__) @@ -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__( @@ -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() @@ -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. @@ -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, diff --git a/stackvox/voices.py b/stackvox/voices.py new file mode 100644 index 0000000..33346b1 --- /dev/null +++ b/stackvox/voices.py @@ -0,0 +1,89 @@ +"""Named voice mixes: Kokoro voices blended into a new voice. + +Each Kokoro voice is a style vector, so a weighted average of several gives a +voice somewhere between them. A mix also carries the lang and speed it was +tuned with, because a blend of an American and a British voice only sounds the +way it was picked when it gets the same phonemes (``en-gb`` rather than +``en-us``) at the same pace. + +Mixes are addressed by name anywhere a Kokoro voice id is accepted: the +library, ``--voice`` on the CLI, and the daemon's socket protocol. +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Mapping +from dataclasses import dataclass + +import numpy as np + + +@dataclass(frozen=True) +class VoiceMix: + """Kokoro voice ids and their weights, plus the lang and speed the blend was tuned with.""" + + mix: tuple[tuple[str, float], ...] + lang: str | None = None + speed: float | None = None + + +# Picked by ear for the StackOne newscast explainers: American delivery with +# British vowels, the transatlantic newsreader sound. +BUILTIN_VOICES: dict[str, VoiceMix] = { + "chip": VoiceMix(mix=(("am_liam", 0.6), ("bm_daniel", 0.4)), lang="en-gb", speed=1.0), + "ramona": VoiceMix(mix=(("af_aoede", 0.5), ("af_bella", 0.2), ("bf_emma", 0.3)), lang="en-gb", speed=1.0), +} + + +class UnknownVoiceError(ValueError): + """A voice mix names a Kokoro voice that isn't in the loaded voice pack.""" + + +@dataclass(frozen=True) +class VoiceParams: + """Fully resolved synthesis parameters.""" + + voice: str + speed: float + lang: str + + +def resolve( + voice: str | None, + speed: float | None, + lang: str | None, + *, + default_voice: str, + default_speed: float, + default_lang: str, + custom: Mapping[str, VoiceMix], +) -> VoiceParams: + """Fill in unset parameters: an explicit value first, then the mix's own, then the default. + + The mix beats the default so that ``--voice chip`` gets Chip's ``en-gb`` + even when the user's config sets ``lang = "en-us"`` for everything else. + """ + name = voice or default_voice + mix = custom.get(name) + if speed is None: + speed = mix.speed if mix is not None and mix.speed is not None else default_speed + if not lang: + lang = mix.lang if mix is not None and mix.lang else default_lang + return VoiceParams(voice=name, speed=speed, lang=lang) + + +def blend( + name: str, + mix: VoiceMix, + style_for: Callable[[str], np.ndarray], + available: Collection[str], +) -> np.ndarray: + """Weighted average of the mix's style vectors, normalised so weights needn't sum to 1.""" + missing = [voice for voice, _ in mix.mix if voice not in available] + if missing: + raise UnknownVoiceError( + f"voice mix {name!r} uses voices not in the Kokoro voice pack: {', '.join(missing)}" + ) + total = sum(weight for _, weight in mix.mix) + blended = sum(weight * style_for(voice) for voice, weight in mix.mix) / total + return np.asarray(blended, dtype=np.float32) diff --git a/tests/test_cli.py b/tests/test_cli.py index b764266..a355dd4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -7,6 +7,7 @@ import pytest from stackvox import cli +from stackvox.voices import BUILTIN_VOICES @pytest.fixture(autouse=True) @@ -19,6 +20,12 @@ def _stdin_is_a_tty(mocker): mocker.patch.object(cli.sys.stdin, "isatty", return_value=True) +@pytest.fixture(autouse=True) +def _no_user_config(monkeypatch, tmp_path): + """Point config at a missing file so a developer's own config never leaks into tests.""" + monkeypatch.setenv("STACKVOX_CONFIG", str(tmp_path / "absent.toml")) + + @pytest.fixture(autouse=True) def _no_network_update_check(mocker): """Block the PyPI update check from making real HTTP requests in tests. @@ -233,7 +240,13 @@ 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")) assert rc == 0 - serve.assert_called_once_with(voice="bf_emma", speed=1.1, lang="en-gb") + serve.assert_called_once_with(voice="bf_emma", speed=1.1, lang="en-gb", custom_voices=BUILTIN_VOICES) + + 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)) + 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")) @@ -582,3 +595,32 @@ def test_no_daemon_is_a_noop(self, mocker): cancel = mocker.patch.object(cli.daemon, "cancel") assert cli._cmd_cancel(_ns()) == 0 cancel.assert_not_called() + + +class TestVoiceParams: + def _config(self, monkeypatch, tmp_path, body): + path = tmp_path / "config.toml" + path.write_text(body, encoding="utf-8") + monkeypatch.setenv("STACKVOX_CONFIG", str(path)) + + def test_mix_lang_beats_config_lang(self, monkeypatch, tmp_path): + self._config(monkeypatch, tmp_path, '[defaults]\nlang = "en-us"\nspeed = 0.95\n') + params, _ = cli._voice_params(_ns(voice="chip", speed=None, lang=None)) + assert (params.voice, params.lang, params.speed) == ("chip", "en-gb", 1.0) + + def test_explicit_flags_beat_the_mix(self, monkeypatch, tmp_path): + self._config(monkeypatch, tmp_path, '[defaults]\nlang = "en-us"\n') + params, _ = cli._voice_params(_ns(voice="chip", speed=1.4, lang="en-us")) + assert (params.lang, params.speed) == ("en-us", 1.4) + + def test_plain_kokoro_voice_uses_config(self, monkeypatch, tmp_path): + self._config(monkeypatch, tmp_path, '[defaults]\nlang = "en-us"\nspeed = 0.95\n') + params, _ = cli._voice_params(_ns(voice="af_aoede", speed=None, lang=None)) + assert (params.lang, params.speed) == ("en-us", 0.95) + + def test_say_sends_the_resolved_mix_settings_to_the_daemon(self, mocker, monkeypatch, tmp_path): + self._config(monkeypatch, tmp_path, '[defaults]\nlang = "en-us"\n') + say = mocker.patch.object(cli.daemon, "say", return_value=(True, "ok")) + 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") diff --git a/tests/test_config.py b/tests/test_config.py index a93b477..594c59b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,7 @@ from stackvox import config from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE +from stackvox.voices import BUILTIN_VOICES, VoiceMix class TestConfigPath: @@ -91,9 +92,11 @@ def test_voice_default_comes_from_config(self, mocker, monkeypatch, tmp_path): assert cli.main() == 0 args = speak.call_args.args[0] assert args.voice == "bf_emma" - assert args.speed == 1.3 + # Speed and lang resolve per command, so a voice mix can sit between flag and config. + params, _ = cli._voice_params(args) + assert params.speed == 1.3 # Lang wasn't in config; should fall through to built-in default. - assert args.lang == DEFAULT_LANG + assert params.lang == DEFAULT_LANG def test_explicit_flag_overrides_config(self, mocker, monkeypatch, tmp_path): path = tmp_path / "config.toml" @@ -108,3 +111,46 @@ def test_explicit_flag_overrides_config(self, mocker, monkeypatch, tmp_path): assert cli.main() == 0 assert speak.call_args.args[0].voice == "af_sarah" + + +class TestLoadVoices: + def test_missing_file_returns_built_in_voices(self, tmp_path): + assert config.load_voices(tmp_path / "absent.toml") == BUILTIN_VOICES + + def test_table_adds_a_named_mix(self, tmp_path): + path = tmp_path / "config.toml" + path.write_text( + '[voices.narrator]\nmix = { am_michael = 0.6, bm_george = 0.4 }\nlang = "en-gb"\nspeed = 1\n', + encoding="utf-8", + ) + voices = config.load_voices(path) + assert voices["narrator"] == VoiceMix( + mix=(("am_michael", 0.6), ("bm_george", 0.4)), lang="en-gb", speed=1.0 + ) + assert voices["chip"] == BUILTIN_VOICES["chip"] + + def test_table_with_a_built_in_name_replaces_it(self, tmp_path): + path = tmp_path / "config.toml" + path.write_text("[voices.chip]\nmix = { am_adam = 1 }\n", encoding="utf-8") + assert config.load_voices(path)["chip"] == VoiceMix(mix=(("am_adam", 1.0),)) + + def test_invalid_table_is_skipped_with_a_warning(self, tmp_path, caplog): + path = tmp_path / "config.toml" + path.write_text( + '[voices.noweights]\nlang = "en-gb"\n[voices.negative]\nmix = { am_adam = -1 }\n' + "[voices.ok]\nmix = { am_adam = 1 }\n", + encoding="utf-8", + ) + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + voices = config.load_voices(path) + assert "noweights" not in voices + assert "negative" not in voices + assert "ok" in voices + assert "[voices.noweights]" in caplog.text + + def test_voices_section_must_be_a_table(self, tmp_path, caplog): + path = tmp_path / "config.toml" + path.write_text('voices = "chip"\n', encoding="utf-8") + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_voices(path) == BUILTIN_VOICES + assert "[voices] must be a table" in caplog.text diff --git a/tests/test_engine.py b/tests/test_engine.py index 0cfe097..c1625f1 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -15,6 +15,7 @@ import pytest from stackvox import engine +from stackvox.voices import UnknownVoiceError, VoiceMix @pytest.fixture @@ -224,9 +225,71 @@ def test_blank_text_yields_no_sentences(self): class TestVoices: def test_returns_sorted_voice_ids(self, fake_kokoro): fake_kokoro.return_value.get_voices.return_value = ["bf_emma", "af_sarah", "am_adam"] - tts = engine.Stackvox() + tts = engine.Stackvox(custom_voices={}) assert tts.voices() == ["af_sarah", "am_adam", "bf_emma"] + def test_includes_voice_mix_names(self, fake_kokoro): + fake_kokoro.return_value.get_voices.return_value = ["bf_emma", "am_adam"] + tts = engine.Stackvox() + assert tts.voices() == ["am_adam", "bf_emma", "chip", "ramona"] + + +class TestVoiceMixes: + MIX = {"duo": VoiceMix(mix=(("am_adam", 3.0), ("bf_emma", 1.0)), lang="en-gb", speed=0.9)} + + def _kokoro_with_styles(self, fake_kokoro): + styles = {"am_adam": np.full(4, 1.0, dtype=np.float32), "bf_emma": np.full(4, 5.0, dtype=np.float32)} + kokoro = fake_kokoro.return_value + kokoro.get_voices.return_value = list(styles) + kokoro.get_voice_style.side_effect = styles.__getitem__ + kokoro.create.return_value = (np.zeros(10, dtype=np.float32), 24000) + return kokoro + + def test_mix_is_blended_and_brings_its_own_lang_and_speed(self, fake_kokoro): + kokoro = self._kokoro_with_styles(fake_kokoro) + tts = engine.Stackvox(voice="duo", speed=1.3, lang="en-us", custom_voices=self.MIX) + + tts.synthesize("hi") + + kwargs = kokoro.create.call_args.kwargs + # 3:1 weights normalised: (3 * 1 + 1 * 5) / 4 + np.testing.assert_allclose(kwargs["voice"], np.full(4, 2.0)) + assert kwargs["lang"] == "en-gb" + assert kwargs["speed"] == 0.9 + + def test_per_call_lang_and_speed_beat_the_mix(self, fake_kokoro): + kokoro = self._kokoro_with_styles(fake_kokoro) + tts = engine.Stackvox(custom_voices=self.MIX) + + tts.synthesize("hi", voice="duo", lang="en-us", speed=1.2) + + assert kokoro.create.call_args.kwargs["lang"] == "en-us" + assert kokoro.create.call_args.kwargs["speed"] == 1.2 + + def test_blend_is_computed_once_per_mix(self, fake_kokoro): + kokoro = self._kokoro_with_styles(fake_kokoro) + tts = engine.Stackvox(voice="duo", custom_voices=self.MIX) + + tts.synthesize("one") + tts.synthesize("two") + + assert kokoro.get_voice_style.call_count == 2 + + def test_plain_kokoro_voice_passes_through_by_name(self, fake_kokoro): + kokoro = self._kokoro_with_styles(fake_kokoro) + tts = engine.Stackvox(custom_voices=self.MIX) + + tts.synthesize("hi", voice="am_adam") + + assert kokoro.create.call_args.kwargs["voice"] == "am_adam" + + def test_mix_naming_a_missing_kokoro_voice_raises(self, fake_kokoro): + self._kokoro_with_styles(fake_kokoro) + tts = engine.Stackvox(voice="bad", custom_voices={"bad": VoiceMix(mix=(("zz_nobody", 1.0),))}) + + with pytest.raises(UnknownVoiceError, match="zz_nobody"): + tts.synthesize("hi") + class TestSpeakSequence: def test_empty_lines_returns_early(self, fake_kokoro, fake_audio):