A TTS that fits in your CPU (and pocket)
Python
Add a --default-voice option to the serve command (#271)
Gabriel de Marmiesse76c0f37559cf
diff --git a/docs/CLI Commands/serve.md b/docs/CLI Commands/serve.mdindex 956bb80..3871b5f 100644--- a/docs/CLI Commands/serve.md+++ b/docs/CLI Commands/serve.md@@ -19,6 +19,7 @@ This starts a server on `http://localhost:8000` with the default voice model.- `--reload`: Enable auto-reload for development- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english'`, `'french_24l'`, `'german_24l'`, `'portuguese_24l'`, `'italian_24l'`, `'spanish_24l'` (default: `english`, which is the same model as `'english_2026-04'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.- `--config`: Path to a custom config .yaml — a local path, an `https://` URL, or an `hf://` path. Incompatible with `--language`.+- `--default-voice`: Voice used by the requests that don't ask for one (default: the built-in voice of the language). It accepts anything the `generate --voice` option accepts: a built-in voice name, a local path to an audio file or to a `.safetensors` voice, an `https://` URL, or an `hf://` path. It is loaded at startup, so a voice that cannot be read fails the server immediately instead of the first request.- `--quantize`: Use int8 quantization for the model (default: False). This can reduce memory usage and increase speed, with minimal impact on audio quality.## Examples@@ -38,6 +39,30 @@ To select the default language model, pass `--language`:pocket-tts serve --language french_24l```+### Custom Default Voice++The voice served when a request doesn't specify one is the built-in voice of the language.+Use `--default-voice` to serve your own instead:++```bash+# A local audio file+pocket-tts serve --default-voice "./my_voice.wav"++# A voice exported with `export-voice`, which loads much faster than an audio file+pocket-tts serve --default-voice "./my_voice.safetensors"++# A voice hosted on the web or on the Hugging Face Hub+pocket-tts serve --default-voice "https://example.com/my_voice.wav"+pocket-tts serve --default-voice "hf://kyutai/tts-voices/alba-mackenna/casual.wav"++# Another built-in voice+pocket-tts serve --default-voice "marius"+```++Requests are free to ask for another voice: `--default-voice` only changes what is used when the+`voice_url` and `voice_wav` fields of `/tts` are both empty (in the web interface, when the voice+field is left empty).+### Custom Model ConfigIf you'd like to override the paths from which the models are loaded, you can provide a custom YAML configuration.diff --git a/pocket_tts/main.py b/pocket_tts/main.pyindex 64eb297..72b65df 100644--- a/pocket_tts/main.py+++ b/pocket_tts/main.py@@ -42,8 +42,9 @@ cli_app = typer.Typer(# Global model instancetts_model: TTSModel | None = None-# Voice served when a request doesn't specify one, resolved from the `serve` options.-default_voice: str | None = None+# State of the voice served when a request doesn't specify one. It is resolved once from the+# `serve` options, so that requests never pay for the encoding of the default voice.+default_voice_state: dict | None = Noneweb_app = FastAPI(title="Kyutai Pocket TTS API", description="Text-to-Speech generation API", version="1.0.0"@@ -137,9 +138,6 @@ def text_to_speech(if not text.strip():raise HTTPException(status_code=400, detail="Text cannot be empty")- if voice_url is None and voice_wav is None:- voice_url = default_voice-if voice_url is not None and voice_wav is not None:raise HTTPException(status_code=400, detail="Cannot provide both voice_url and voice_wav")@@ -170,8 +168,10 @@ def text_to_speech(model_state = tts_model.get_state_for_audio_prompt(Path(temp_file_path), truncate=True)finally:os.unlink(temp_file_path)+ elif default_voice_state is not None:+ model_state = default_voice_stateelse:- raise HTTPException(status_code=500, detail="This should never happen.")+ raise HTTPException(status_code=500, detail="The server has no default voice loaded.")return StreamingResponse(generate_data_with_state(text, model_state),@@ -204,15 +204,28 @@ def serve("Incompatible with the language argument. If not provided, will use the default English model."),] = None,+ default_voice: Annotated[+ str | None,+ typer.Option(+ help="Voice used by requests that don't ask for one: a built-in voice name, "+ "a local path to an audio file or to a .safetensors voice, an https:// URL, "+ "or an hf:// path. Defaults to the built-in voice of the language.",+ show_default=False,+ ),+ ] = None,quantize: Annotated[bool, typer.Option(help="Apply int8 quantization to reduce memory usage")] = False,):"""Start the FastAPI server."""- global tts_model, default_voice+ global tts_model, default_voice_statetts_model = TTSModel.load_model(language=language, config=config, quantize=quantize)- default_voice = get_default_voice_for_language(language, config)+ if default_voice is None:+ default_voice = get_default_voice_for_language(language, config)+ # Resolved before serving: a voice that cannot be loaded fails at startup instead of on+ # the first request, which would otherwise pay for the encoding of the audio file.+ default_voice_state = tts_model.get_state_for_audio_prompt(default_voice)uvicorn.run("pocket_tts.main:web_app", host=host, port=port, reload=reload)diff --git a/tests/test_serve_default_voice.py b/tests/test_serve_default_voice.pynew file mode 100644index 0000000..e7050b5--- /dev/null+++ b/tests/test_serve_default_voice.py@@ -0,0 +1,103 @@+"""Tests for the default voice of the `serve` command and of the /tts endpoint."""++from types import SimpleNamespace++import torch+from fastapi.testclient import TestClient+from typer.testing import CliRunner++from pocket_tts import main++runner = CliRunner()+++class FakeTTSModel:+ """Stand-in for TTSModel, recording which voices and states it was asked for."""++ def __init__(self):+ self.config = SimpleNamespace(mimi=SimpleNamespace(sample_rate=24000))+ self.voices_requested = []+ self.states_used = []++ def get_state_for_audio_prompt(self, audio_conditioning, truncate: bool = False) -> dict:+ self.voices_requested.append(audio_conditioning)+ return {"voice": audio_conditioning}++ def _cached_get_state_for_audio_prompt(+ self, audio_conditioning, truncate: bool = False+ ) -> dict:+ return self.get_state_for_audio_prompt(audio_conditioning, truncate)++ def generate_audio_stream(self, model_state: dict, text_to_generate: str):+ self.states_used.append(model_state)+ yield torch.zeros(2400)+++def make_serve_runnable(monkeypatch) -> FakeTTSModel:+ """Make `serve` return right before listening, with a fake model."""+ fake_model = FakeTTSModel()+ monkeypatch.setattr(main, "TTSModel", SimpleNamespace(load_model=lambda **kwargs: fake_model))+ monkeypatch.setattr(main.uvicorn, "run", lambda *args, **kwargs: None)+ monkeypatch.setattr(main, "tts_model", None)+ monkeypatch.setattr(main, "default_voice_state", None)+ return fake_model+++def test_serve_loads_the_voice_given_by_the_default_voice_option(monkeypatch):+ fake_model = make_serve_runnable(monkeypatch)++ result = runner.invoke(main.cli_app, ["serve", "--default-voice", "./my_voice.safetensors"])++ assert result.exit_code == 0, result.output+ assert fake_model.voices_requested == ["./my_voice.safetensors"]+ assert main.default_voice_state == {"voice": "./my_voice.safetensors"}+++def test_serve_falls_back_to_the_voice_of_the_language(monkeypatch):+ fake_model = make_serve_runnable(monkeypatch)++ result = runner.invoke(main.cli_app, ["serve", "--language", "french_24l"])++ assert result.exit_code == 0, result.output+ assert fake_model.voices_requested == ["estelle"]+ assert main.default_voice_state == {"voice": "estelle"}+++def test_tts_endpoint_uses_the_default_voice_when_the_request_has_none(monkeypatch):+ fake_model = FakeTTSModel()+ monkeypatch.setattr(main, "tts_model", fake_model)+ monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})++ response = TestClient(main.web_app).post("/tts", data={"text": "Hello world."})++ assert response.status_code == 200+ # The default voice is served as-is, without being encoded again.+ assert fake_model.voices_requested == []+ assert fake_model.states_used == [{"voice": "./my_voice.wav"}]+++def test_tts_endpoint_prefers_the_voice_of_the_request_over_the_default(monkeypatch):+ fake_model = FakeTTSModel()+ monkeypatch.setattr(main, "tts_model", fake_model)+ monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})++ response = TestClient(main.web_app).post(+ "/tts", data={"text": "Hello world.", "voice_url": "marius"}+ )++ assert response.status_code == 200+ assert fake_model.voices_requested == ["marius"]+ assert fake_model.states_used == [{"voice": "marius"}]+++def test_tts_endpoint_still_rejects_a_voice_url_that_is_not_a_voice(monkeypatch):+ fake_model = FakeTTSModel()+ monkeypatch.setattr(main, "tts_model", fake_model)+ monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})++ response = TestClient(main.web_app).post(+ "/tts", data={"text": "Hello world.", "voice_url": "./my_voice.wav"}+ )++ assert response.status_code == 400+ assert fake_model.states_used == []