A TTS that fits in your CPU (and pocket)
Python
serve: teacher_force_previous_chunk form field on /tts (#429)
manu-lm736f4ce94378
diff --git a/docs/CLI Commands/serve.md b/docs/CLI Commands/serve.mdindex 9072e77..cc125e4 100644--- a/docs/CLI Commands/serve.md+++ b/docs/CLI Commands/serve.md@@ -63,6 +63,19 @@ Requests are free to ask for another voice: `--default-voice` only changes what`voice_url` and `voice_wav` fields of `/tts` are both empty (in the web interface, when the voicefield is left empty).+### Teacher Forcing Between Chunks++Long texts are generated in chunks. Set the `teacher_force_previous_chunk` form field of `/tts` to+`true` to generate each chunk as the continuation of the previous one instead of starting afresh+from the voice prompt (same as `--teacher-force-previous-chunk` of `generate`; default: `false`,+slightly slower):++```bash+curl -X POST http://localhost:8000/tts \+ -F "text=A long text, made of several sentences..." \+ -F "teacher_force_previous_chunk=true" -o output.wav+```+### 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 682e725..3832c31 100644--- a/pocket_tts/main.py+++ b/pocket_tts/main.py@@ -92,6 +92,7 @@ def write_to_queue(text_to_generate: str,model_state: ModelState,stop: threading.Event,+ teacher_force_previous_chunk: bool = False,):"""Allows writing to the StreamingResponse as if it were a file."""@@ -110,7 +111,10 @@ def write_to_queue(model = _loaded_model()audio_chunks = model.generate_audio_stream(- model_state=model_state, text_to_generate=text_to_generate, stop=stop+ model_state=model_state,+ text_to_generate=text_to_generate,+ stop=stop,+ teacher_force_previous_chunk=teacher_force_previous_chunk,)# FileLikeToQueue only implements the write/close subset that StreamingWAVWriter uses.stream_audio_chunks(@@ -119,14 +123,15 @@ def write_to_queue(def generate_data_with_state(- text_to_generate: str, model_state: ModelState+ text_to_generate: str, model_state: ModelState, teacher_force_previous_chunk: bool = False) -> Generator[bytes, None, None]:queue: Queue[bytes | None] = Queue()stop = threading.Event()# Run your function in a threadthread = threading.Thread(- target=write_to_queue, args=(queue, text_to_generate, model_state, stop)+ target=write_to_queue,+ args=(queue, text_to_generate, model_state, stop, teacher_force_previous_chunk),)thread.start()@@ -149,6 +154,7 @@ def text_to_speech(text: str = Form(...),voice_url: str | None = Form(None),voice_wav: UploadFile | None = File(None),+ teacher_force_previous_chunk: bool = Form(False),) -> StreamingResponse:"""Generate speech from text using the pre-loaded voice prompt or a custom voice.@@ -157,6 +163,8 @@ def text_to_speech(text: Text to convert to speechvoice_url: Optional built-in voice name (e.g., "alba"), or voice URL (http://, https://, or hf://)voice_wav: Optional uploaded voice file (mutually exclusive with voice_url)+ teacher_force_previous_chunk: Generate each chunk of a long text as the continuation+ of the previous one instead of starting afresh from the voice prompt"""if not text.strip():raise HTTPException(status_code=400, detail="Text cannot be empty")@@ -199,7 +207,7 @@ def text_to_speech(raise HTTPException(status_code=500, detail="The server has no default voice loaded.")return StreamingResponse(- generate_data_with_state(text, model_state),+ generate_data_with_state(text, model_state, teacher_force_previous_chunk),media_type="audio/wav",headers={"Content-Disposition": "attachment; filename=generated_speech.wav",diff --git a/tests/test_serve_default_voice.py b/tests/test_serve_default_voice.pyindex 516816e..0d6de22 100644--- a/tests/test_serve_default_voice.py+++ b/tests/test_serve_default_voice.py@@ -23,6 +23,7 @@ class FakeTTSModel:self.config = SimpleNamespace(mimi=SimpleNamespace(sample_rate=24000))self.voices_requested: list[Path | str | torch.Tensor] = []self.states_used: list[dict[str, Any]] = []+ self.teacher_forcing_used: list[bool] = []def get_state_for_audio_prompt(self, audio_conditioning: Path | str | torch.Tensor, truncate: bool = False@@ -40,8 +41,10 @@ class FakeTTSModel:model_state: dict[str, Any],text_to_generate: str,stop: threading.Event | None = None,+ teacher_force_previous_chunk: bool = False,) -> Iterator[torch.Tensor]:self.states_used.append(model_state)+ self.teacher_forcing_used.append(teacher_force_previous_chunk)yield torch.zeros(2400)@@ -119,3 +122,20 @@ def test_tts_endpoint_still_rejects_a_voice_url_that_is_not_a_voice(assert response.status_code == 400assert fake_model.states_used == []+++def test_tts_endpoint_passes_teacher_force_previous_chunk_to_the_model(+ monkeypatch: pytest.MonkeyPatch,+):+ fake_model = FakeTTSModel()+ monkeypatch.setattr(main, "tts_model", fake_model)+ monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})+ client = TestClient(main.web_app)++ assert client.post("/tts", data={"text": "Hello world."}).status_code == 200+ response = client.post(+ "/tts", data={"text": "Hello world.", "teacher_force_previous_chunk": "true"}+ )++ assert response.status_code == 200+ assert fake_model.teacher_forcing_used == [False, True]