Skip to content

A TTS that fits in your CPU (and pocket)

Python

Stop generation when nobody is listening anymore (#228)

Bright Fultondfff26e27258
diff --git a/docs/API Reference/python-api.md b/docs/API Reference/python-api.md
index e07a2ef..c29e38c 100644
--- a/docs/API Reference/python-api.md
+++ b/docs/API Reference/python-api.md
@@ -157,7 +157,8 @@ print(f"Audio duration: {audio.shape[-1] / model.sample_rate:.2f} seconds")
Generate audio streaming chunks from text input.
-**Parameters:** Same as `generate_audio()`
+**Parameters:** Same as `generate_audio()`, plus:
+- `stop` (threading.Event | None): Optional event for cancelling the generation. Once set, no new frames are generated and the stream ends early.
**Yields:**
- `torch.Tensor`: Audio chunks with shape [samples]
diff --git a/pocket_tts/main.py b/pocket_tts/main.py
index 9e1ed29..a328906 100644
--- a/pocket_tts/main.py
+++ b/pocket_tts/main.py
@@ -4,7 +4,7 @@ import os
import sys
import tempfile
import threading
-from collections.abc import Iterator
+from collections.abc import Generator
from pathlib import Path
from queue import Queue
from typing import Annotated, BinaryIO, cast
@@ -87,7 +87,12 @@ async def health() -> dict[str, str]:
return {"status": "healthy"}
-def write_to_queue(queue: Queue[bytes | None], text_to_generate: str, model_state: ModelState):
+def write_to_queue(
+ queue: Queue[bytes | None],
+ text_to_generate: str,
+ model_state: ModelState,
+ stop: threading.Event,
+):
"""Allows writing to the StreamingResponse as if it were a file."""
class FileLikeToQueue(io.IOBase):
@@ -105,7 +110,7 @@ def write_to_queue(queue: Queue[bytes | None], text_to_generate: str, model_stat
model = _loaded_model()
audio_chunks = model.generate_audio_stream(
- model_state=model_state, text_to_generate=text_to_generate
+ model_state=model_state, text_to_generate=text_to_generate, stop=stop
)
# FileLikeToQueue only implements the write/close subset that StreamingWAVWriter uses.
stream_audio_chunks(
@@ -113,23 +118,30 @@ def write_to_queue(queue: Queue[bytes | None], text_to_generate: str, model_stat
)
-def generate_data_with_state(text_to_generate: str, model_state: ModelState) -> Iterator[bytes]:
+def generate_data_with_state(
+ text_to_generate: str, model_state: ModelState
+) -> Generator[bytes, None, None]:
queue: Queue[bytes | None] = Queue()
+ stop = threading.Event()
# Run your function in a thread
- thread = threading.Thread(target=write_to_queue, args=(queue, text_to_generate, model_state))
+ thread = threading.Thread(
+ target=write_to_queue, args=(queue, text_to_generate, model_state, stop)
+ )
thread.start()
- # Yield data as it becomes available
- i = 0
- while True:
- data = queue.get()
- if data is None:
- break
- i += 1
- yield data
-
- thread.join()
+ try:
+ # Yield data as it becomes available
+ while True:
+ data = queue.get()
+ if data is None:
+ break
+ yield data
+ finally:
+ # Also runs when the client disconnects: stop the generation instead of
+ # finishing it for nobody, and make sure the worker is done with the model.
+ stop.set()
+ thread.join()
@web_app.post("/tts")
diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.py
index 2fb434c..bee6b66 100644
--- a/pocket_tts/models/tts_model.py
+++ b/pocket_tts/models/tts_model.py
@@ -637,6 +637,7 @@ class TTSModel(nn.Module):
max_tokens: int = MAX_TOKEN_PER_CHUNK,
frames_after_eos: int | None = None,
copy_state: bool = True,
+ stop: threading.Event | None = None,
) -> Iterator[torch.Tensor]:
"""Generate audio streaming chunks from text input.
@@ -659,6 +660,9 @@ class TTSModel(nn.Module):
copy_state: Whether to create a deep copy of the model state before
generation. If True, preserves the original state for reuse.
If False, modifies the input state in-place. Defaults to True.
+ stop: Optional event for cancelling the generation, for instance
+ when the user interrupts the playback. Once set, no new frames
+ are generated and the stream ends early.
Yields:
torch.Tensor: Audio chunks with shape [samples] at the model's
@@ -690,6 +694,8 @@ class TTSModel(nn.Module):
"""
if frames_after_eos is None:
frames_after_eos = self.model_recommended_frames_after_eos
+ if stop is None:
+ stop = threading.Event()
# This is a very simplistic way of handling long texts. We could do much better
# by using teacher forcing, but it would be a bit slower.
@@ -706,6 +712,8 @@ class TTSModel(nn.Module):
)
for chunk in chunks:
+ if stop.is_set():
+ break
text_to_generate, frames_after_eos_guess = prepare_text_prompt(
chunk,
self.pad_with_spaces_for_short_inputs,
@@ -722,6 +730,7 @@ class TTSModel(nn.Module):
text_to_generate=text_to_generate,
frames_after_eos=effective_frames,
copy_state=copy_state,
+ stop=stop,
)
@torch.no_grad
@@ -731,6 +740,7 @@ class TTSModel(nn.Module):
text_to_generate: str,
frames_after_eos: int,
copy_state: bool,
+ stop: threading.Event,
) -> Iterator[torch.Tensor]:
if copy_state:
model_state = copy.deepcopy(model_state)
@@ -763,6 +773,7 @@ class TTSModel(nn.Module):
frames_after_eos=frames_after_eos,
latents_queue=latents_queue,
result_queue=result_queue,
+ stop=stop,
)
# Stream audio chunks as they become available
@@ -811,6 +822,7 @@ class TTSModel(nn.Module):
frames_after_eos: int,
latents_queue: LatentQueue,
result_queue: ResultQueue,
+ stop: threading.Event,
):
token_count = prepared.shape[1]
current_end = self._flow_lm_current_end(model_state)
@@ -823,7 +835,7 @@ class TTSModel(nn.Module):
def run_generation():
try:
self._autoregressive_generation(
- model_state, max_gen_len, frames_after_eos, latents_queue
+ model_state, max_gen_len, frames_after_eos, latents_queue, stop
)
except Exception as e:
logger.error(f"Error in autoregressive generation: {e}")
@@ -845,6 +857,7 @@ class TTSModel(nn.Module):
max_gen_len: int,
frames_after_eos: int,
latents_queue: LatentQueue,
+ stop: threading.Event,
):
backbone_input = torch.full(
(1, 1, self.flow_lm.ldim),
@@ -855,6 +868,8 @@ class TTSModel(nn.Module):
steps_times = []
eos_step = None
for generation_step in range(max_gen_len):
+ if stop.is_set():
+ break
with display_execution_time("Generating latent", print_output=False) as timer:
next_latent, is_eos = self._run_flow_lm_and_increment_step(
model_state=model_state, backbone_input_latents=backbone_input
@@ -878,7 +893,8 @@ class TTSModel(nn.Module):
# Add sentinel value to signal end of generation
latents_queue.put(None)
- logger.info("Average generation step time: %d ms", int(statistics.mean(steps_times)))
+ if steps_times:
+ logger.info("Average generation step time: %d ms", int(statistics.mean(steps_times)))
@lru_cache(maxsize=2)
def _cached_get_state_for_audio_prompt(
diff --git a/tests/test_generation_regressions.py b/tests/test_generation_regressions.py
index 24c7bed..2238709 100644
--- a/tests/test_generation_regressions.py
+++ b/tests/test_generation_regressions.py
@@ -1,4 +1,5 @@
import queue
+import threading
from collections.abc import Iterator
from types import SimpleNamespace
from typing import NoReturn, cast
@@ -83,6 +84,7 @@ def test_generate_reports_autoregressive_errors_before_decoder_done():
frames_after_eos=1,
latents_queue=latents_queue,
result_queue=result_queue,
+ stop=threading.Event(),
)
kind, value = result_queue.get(timeout=1)
diff --git a/tests/test_serve_default_voice.py b/tests/test_serve_default_voice.py
index 24732eb..516816e 100644
--- a/tests/test_serve_default_voice.py
+++ b/tests/test_serve_default_voice.py
@@ -1,5 +1,6 @@
"""Tests for the default voice of the `serve` command and of the /tts endpoint."""
+import threading
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
@@ -35,7 +36,10 @@ class FakeTTSModel:
return self.get_state_for_audio_prompt(audio_conditioning, truncate)
def generate_audio_stream(
- self, model_state: dict[str, Any], text_to_generate: str
+ self,
+ model_state: dict[str, Any],
+ text_to_generate: str,
+ stop: threading.Event | None = None,
) -> Iterator[torch.Tensor]:
self.states_used.append(model_state)
yield torch.zeros(2400)
diff --git a/tests/test_streaming_cancellation.py b/tests/test_streaming_cancellation.py
new file mode 100644
index 0000000..6de82f2
--- /dev/null
+++ b/tests/test_streaming_cancellation.py
@@ -0,0 +1,75 @@
+"""Tests that cancelling a stream stops the generation."""
+
+import threading
+from collections.abc import Callable
+from typing import ParamSpec, TypeVar
+
+import pytest
+
+import pocket_tts.main
+from pocket_tts import TTSModel
+
+# A single sentence, short enough to stay in one chunk but long enough that its
+# generation is still running when we cancel it.
+TEXT = "This sentence takes a while to generate, which leaves time to cancel it early."
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+
+def _record_calling_thread(record: list[threading.Thread], fn: Callable[P, R]) -> Callable[P, R]:
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ record.append(threading.current_thread())
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+
+def count_generation_steps(
+ model: TTSModel, monkeypatch: pytest.MonkeyPatch
+) -> list[threading.Thread]:
+ """Make the model record the thread of each generation step in the returned list."""
+ generation_steps: list[threading.Thread] = []
+ monkeypatch.setattr(
+ model,
+ "_run_flow_lm_and_increment_step",
+ _record_calling_thread(generation_steps, model._run_flow_lm_and_increment_step),
+ )
+ return generation_steps
+
+
+def test_setting_the_stop_event_stops_the_generation(monkeypatch: pytest.MonkeyPatch):
+ model = TTSModel.load_model()
+ voice_state = model.get_state_for_audio_prompt("alba")
+ generation_steps = count_generation_steps(model, monkeypatch)
+
+ stop = threading.Event()
+ stream = model.generate_audio_stream(voice_state, TEXT, stop=stop)
+ next(stream)
+ stop.set()
+ steps_when_stopped = len(generation_steps)
+ for _ in stream: # the stream ends early instead of generating the whole sentence
+ pass
+
+ # At most the step that was already running when the event was set finished.
+ assert len(generation_steps) <= steps_when_stopped + 1
+
+
+def test_client_disconnect_stops_the_generation(monkeypatch: pytest.MonkeyPatch):
+ model = TTSModel.load_model()
+ monkeypatch.setattr(pocket_tts.main, "tts_model", model)
+ voice_state = model.get_state_for_audio_prompt("alba")
+ generation_steps = count_generation_steps(model, monkeypatch)
+
+ stream = pocket_tts.main.generate_data_with_state(TEXT, voice_state)
+ next(stream)
+ # This is what the server does with the response when the client disconnects.
+ stream.close()
+ request_threads = set(generation_steps)
+ steps_when_disconnected = len(generation_steps)
+
+ # The next request has the model to itself: while it generates, the
+ # disconnected request's threads never run another step.
+ model.generate_audio(voice_state, TEXT)
+ leftover_steps = generation_steps[steps_when_disconnected:]
+ assert not request_threads & set(leftover_steps)