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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ Exit codes: `0` ok, `2` daemon unreachable (unless `--fallback-say` was given).
## Python library

```python
from stackvox import Stackvox, speak, synthesize
from stackvox import Stackvox, speak, synthesize, synthesize_stream

# One-shot — model loads on first call, reused for subsequent calls.
speak("Hello world")
Expand All @@ -144,6 +144,11 @@ tts.stop()
# Raw samples for custom processing.
samples, sr = tts.synthesize("give me the array")

# Streaming: one chunk per sentence, yielded as soon as it is synthesized, so
# a caller encoding audio itself waits one sentence rather than the whole text.
for chunk, sr in tts.synthesize_stream("First sentence. Second sentence."):
encode_and_send(chunk, sr)

# Gapless multi-line playback with concurrent synthesis.
tts.speak_sequence([
{"text": "Hello", "voice": "af_heart", "lang": "en-us"},
Expand Down
4 changes: 2 additions & 2 deletions stackvox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from importlib.metadata import version as _pkg_version

from stackvox import daemon
from stackvox.engine import Stackvox, speak, synthesize
from stackvox.engine import Stackvox, speak, synthesize, synthesize_stream
from stackvox.text import normalize_for_speech

try:
Expand All @@ -14,4 +14,4 @@
# bootstrap before `pip install -e .` has completed).
__version__ = "0.0.0+unknown"

__all__ = ["Stackvox", "daemon", "normalize_for_speech", "speak", "synthesize"]
__all__ = ["Stackvox", "daemon", "normalize_for_speech", "speak", "synthesize", "synthesize_stream"]
115 changes: 91 additions & 24 deletions stackvox/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import sys
import threading
import urllib.request
from collections.abc import Mapping
from collections.abc import Generator, Mapping
from pathlib import Path

import numpy as np
Expand Down Expand Up @@ -158,6 +158,37 @@ def synthesize(
)
return samples, sample_rate

def synthesize_stream(
self,
text: str,
voice: str | None = None,
speed: float | None = None,
lang: str | None = None,
) -> Generator[tuple[np.ndarray, int], None, None]:
"""Yield (samples, sample_rate) per sentence, as soon as each is synthesized.

The streaming counterpart to ``synthesize``: time to first chunk is one
sentence rather than the whole text, which is what a caller encoding and
sending audio as it arrives (an HTTP speech endpoint, say) wants. The
samples are raw. The lead-in silence and fade-in that ``speak`` applies
are smoothing for a physical output device, not part of the audio.

Per-sentence batching costs total throughput — roughly 50% more wall
clock over the whole text than one ``synthesize`` call — so this is the
right call only when time to first chunk is what matters.

Chunks are sentences, and Kokoro trims each one it is given, so the
concatenated stream runs a few percent shorter than ``synthesize`` on
the same text — the inter-sentence silence goes with the trim. This is
the audio ``speak`` has always produced.

The stream is independent of ``speak`` and ``stop``, which own the shared
output device: a consumer cancels its own stream by abandoning the
generator (``break``, or ``close()``), which shuts the synthesis thread
down with it.
"""
return self._synthesize_chunks(text, threading.Event(), voice=voice, speed=speed, lang=lang)

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)
Expand Down Expand Up @@ -214,26 +245,28 @@ def _run() -> None:
self._play_thread = threading.Thread(target=_run, daemon=True, name="stackvox-play")
self._play_thread.start()

def _stream_play(
def _synthesize_chunks(
self,
text: str,
stop_event: threading.Event,
voice: str | None = None,
speed: float | None = None,
lang: str | None = None,
) -> None:
"""Synthesize sentence by sentence and play each as it is ready.
) -> Generator[tuple[np.ndarray, int], None, None]:
"""Yield (samples, sample_rate) per sentence, synthesizing ahead of the consumer.

Kokoro batches by phoneme count (~510), so a whole paragraph synthesizes
as one blob before any audio — the source of the lead-in lag. Splitting
into sentences ourselves means the first sentence (~0.2s to synthesize)
plays almost immediately. A producer thread synthesizes ahead into a
bounded queue while this thread plays, so later sentences are usually
ready by the time the previous one finishes.

A synthesis failure is re-raised rather than swallowed, so a blocking
caller sees the error instead of silent success; ``stop_event`` cancels
the stream between sentences.
into sentences ourselves means the first chunk (~0.2s to synthesize) is
ready almost immediately. A producer thread synthesizes ahead into a
bounded queue while the consumer works through what is already done, so
later sentences are usually ready by the time they are asked for.

A synthesis failure is re-raised into the consumer rather than swallowed,
so a caller sees the error instead of a stream that just stops early;
``stop_event`` cancels between sentences. Closing the generator early
drains the queue until the producer exits, so abandoning a stream can
never leave the synth thread parked on a put.
"""
sentences = _split_sentences(text)
if not sentences:
Expand All @@ -256,7 +289,6 @@ def _produce() -> None:
producer = threading.Thread(target=_produce, daemon=True, name="stackvox-synth")
producer.start()
error: Exception | None = None
stream: sd.OutputStream | None = None
try:
while not stop_event.is_set():
item = chunks.get()
Expand All @@ -265,7 +297,38 @@ def _produce() -> None:
if isinstance(item, Exception):
error = item
break
samples, sample_rate = item
yield item
finally:
# Stop the producer and keep draining so it can never stay parked on
# a full queue — that's what guarantees the synth thread always exits.
stop_event.set()
while producer.is_alive():
try:
chunks.get_nowait()
except queue.Empty:
producer.join(timeout=0.05)
if error is not None:
raise error

def _stream_play(
self,
text: str,
stop_event: threading.Event,
voice: str | None = None,
speed: float | None = None,
lang: str | None = None,
) -> None:
"""Play each sentence through the output device as it becomes available.

Consuming ``_synthesize_chunks`` is what makes the first sentence play
while the rest are still synthesizing. A synthesis failure propagates out
of the generator, so a blocking caller sees the error instead of silent
success; ``stop_event`` cancels the stream.
"""
chunks = self._synthesize_chunks(text, stop_event, voice=voice, speed=speed, lang=lang)
stream: sd.OutputStream | None = None
try:
for samples, sample_rate in chunks:
samples = np.ascontiguousarray(samples, dtype="float32")
if stream is None:
# One stream for the whole utterance: writing chunks into it is
Expand All @@ -288,6 +351,9 @@ def _produce() -> None:
break # aborted by stop(); expected
raise
finally:
# Release the output device before draining the synth thread, so a
# stop() doesn't hold the device open for however long the in-flight
# sentence still takes to synthesize.
with self._stream_lock:
self._stream = None
if stream is not None:
Expand All @@ -296,16 +362,7 @@ def _produce() -> None:
stream.close()
except Exception:
logger.debug("stream teardown failed", exc_info=True)
# Stop the producer and keep draining so it can never stay parked on
# a full queue — that's what guarantees the synth thread always exits.
stop_event.set()
while producer.is_alive():
try:
chunks.get_nowait()
except queue.Empty:
producer.join(timeout=0.05)
if error is not None:
raise error
chunks.close()

def stop(self) -> None:
"""Stop any in-progress playback started with blocking=False."""
Expand Down Expand Up @@ -402,3 +459,13 @@ def synthesize(
) -> tuple[np.ndarray, int]:
"""One-shot synthesis. Returns (samples, sample_rate)."""
return _get_default().synthesize(text, voice=voice, speed=speed, lang=lang)


def synthesize_stream(
text: str,
voice: str = DEFAULT_VOICE,
speed: float = DEFAULT_SPEED,
lang: str = DEFAULT_LANG,
) -> Generator[tuple[np.ndarray, int], None, None]:
"""One-shot streaming synthesis. Yields (samples, sample_rate) per sentence."""
return _get_default().synthesize_stream(text, voice=voice, speed=speed, lang=lang)
78 changes: 78 additions & 0 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,78 @@ def test_speed_zero_override_is_respected(self, fake_kokoro):
assert kwargs["speed"] == 0.5


class TestSynthesizeStream:
def test_yields_one_chunk_per_sentence_in_order(self, fake_kokoro):
per_sentence = [
(np.full(3, 1.0, dtype=np.float32), 24000),
(np.full(3, 2.0, dtype=np.float32), 24000),
(np.full(3, 3.0, dtype=np.float32), 24000),
]
fake_kokoro.return_value.create.side_effect = per_sentence

chunks = list(engine.Stackvox().synthesize_stream("One. Two. Three."))

assert [sample_rate for _, sample_rate in chunks] == [24000, 24000, 24000]
assert [samples[0] for samples, _ in chunks] == [1.0, 2.0, 3.0]

def test_yields_raw_samples_without_playback_smoothing(self, fake_kokoro, fake_audio):
# The prime silence and fade-in are for a physical output device; a
# caller encoding the audio itself must get the samples untouched.
fake_kokoro.return_value.create.return_value = (np.ones(1000, dtype=np.float32), 24000)

samples, _ = next(engine.Stackvox().synthesize_stream("hello"))

assert samples[0] == 1.0
engine.sd.OutputStream.assert_not_called()

def test_blank_text_yields_nothing(self, fake_kokoro):
assert list(engine.Stackvox().synthesize_stream(" \n ")) == []

def test_per_call_overrides_take_priority(self, fake_kokoro):
fake_kokoro.return_value.create.return_value = (np.zeros(4, dtype=np.float32), 24000)
tts = engine.Stackvox(voice="af_sarah", speed=1.0, lang="en-us")

list(tts.synthesize_stream("hi", voice="bf_emma", speed=1.5, lang="en-gb"))

fake_kokoro.return_value.create.assert_called_once_with(
"hi", voice="bf_emma", speed=1.5, lang="en-gb"
)

def test_surfaces_synthesis_errors_to_the_consumer(self, fake_kokoro):
# The producer runs on its own thread, so a failure there has to be
# handed back rather than ending the stream as if it were complete.
fake_kokoro.return_value.create.side_effect = RuntimeError("boom")
tts = engine.Stackvox()

with pytest.raises(RuntimeError, match="boom"):
list(tts.synthesize_stream("hello there"))

def test_abandoning_the_stream_stops_the_synth_thread(self, fake_kokoro):
# More sentences than the queue holds, so the producer is parked on a
# full put when the consumer walks away. Closing has to drain it.
fake_kokoro.return_value.create.return_value = (np.zeros(4, dtype=np.float32), 24000)
text = " ".join(f"Sentence {n}." for n in range(40))
before = set(threading.enumerate())

stream = engine.Stackvox().synthesize_stream(text)
next(stream)
producers = [t for t in threading.enumerate() if t not in before and t.name == "stackvox-synth"]
assert len(producers) == 1

stream.close()

assert not producers[0].is_alive()

def test_is_independent_of_playback_cancellation(self, fake_kokoro, fake_audio):
# stop() cancels playback on the shared output device; it must not
# truncate an unrelated caller's stream.
fake_kokoro.return_value.create.return_value = (np.zeros(4, dtype=np.float32), 24000)
tts = engine.Stackvox()
tts.stop()

assert len(list(tts.synthesize_stream("One. Two. Three."))) == 3


class TestSpeak:
def test_blocking_synthesizes_and_plays_each_sentence(self, fake_kokoro, fake_audio):
fake_kokoro.return_value.create.return_value = (np.zeros(10, dtype=np.float32), 24000)
Expand Down Expand Up @@ -327,6 +399,12 @@ def test_synthesize_reuses_module_singleton(self, fake_kokoro):
engine.synthesize("second")
assert fake_kokoro.call_count == 1

def test_synthesize_stream_reuses_module_singleton(self, fake_kokoro):
fake_kokoro.return_value.create.return_value = (np.zeros(10), 24000)
list(engine.synthesize_stream("first"))
list(engine.synthesize_stream("second"))
assert fake_kokoro.call_count == 1

def test_get_default_is_thread_safe(self, fake_kokoro):
"""Concurrent first calls must not double-instantiate Stackvox.

Expand Down
Loading