diff --git a/docs/TASKS.md b/docs/TASKS.md index 521f9d9..58b5557 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -23,7 +23,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty — next up: T1.2 / T1.3 / T1.4, parallel after T0.3)_ | | | | | +| T1.2 | Engine wrapper | `arch/tts/t1.2` | 52 unit tests (9 new); 6 integration tests vs `en_US-lessac-medium` (3 new); Ruff check/format; strict mypy | PR pending review | ## Remaining @@ -36,7 +36,6 @@ _All P0 tasks done._ | ID | Task | Files | Deps | Acceptance criteria (summary) | |---|---|---|---|---| | T1.1 | Voice store | `src/tts/voices/store.py` | T0.2 | Sorted voice metadata, alignment support, valid short preview WAV | -| T1.2 | Engine wrapper | `src/tts/engine/piper_engine.py` | T0.2, T0.3 | Sentence synthesis, sample totals, rate effect, pre-start cancellation | | T1.3 | Timing reconcile | `src/tts/timing/reconcile.py` | T0.3 | Monotonic timings, honest degraded alignment, zero-phoneme handling | | T1.4 | Subtitles | `src/tts/subtitles/` | T0.3 | Cue boundary rules and byte-exact SRT/VTT fixtures | | T1.5 | History DAL completion | `src/tts/history/dal.py` | T0.4 | Consistent transactional deletion, eviction ordering, settings seeding | @@ -88,3 +87,7 @@ _All P0 tasks done._ - T1.1 environment finding: importing `onnxruntime` 1.32 crashed with an access violation on this machine because `C:\Windows\System32\MSVCP140.dll` was 14.27 (VS 2019 redist) while the pinned runtime needs a current one. Installing the latest VC++ 2015–2022 x64 redistributable (now 14.52) fixed it; `import piper` and real-voice tests run. T5.2 must document the VC++ redistributable as an install prerequisite (README/KNOWN_LIMITATIONS), since the packaged app fails the same way on a machine with an old redist. - T1.1 decisions: `store.py` follows §7.3's no-settings signatures by using a module-level voices dir set by `ensure_data_dirs(settings)`; using the store before that raises `RuntimeError`. Unknown/unsafe voice ids raise `VoiceNotFoundError` (a `LookupError`), which T2.1 maps to 422 `VOICE_NOT_FOUND` / 409 `NO_VOICES_INSTALLED`. `piper` is imported lazily inside `load_voice`/`preview_wav`/`install_voice`, so unit tests and the API import path never pay the onnxruntime cost. `supports_alignments` is read from the loaded session having a second output (the patched phoneme-width tensor, `/Ceil_output_0` on `en_US-lessac-medium`); a model without it loads unpatched and reports `False`. `VoiceInfo.language` comes from the config's `language.code`, falling back to the id prefix; voices with a missing/invalid `.onnx.json` are logged and skipped. Install delegate is `piper.download_voices.download_voice(name, voices_dir)`. - T1.1 shared file: `pyproject.toml` gains the `integration` pytest marker (append-only `[tool.pytest.ini_options]` config). Dependent tasks: T1.2–T1.6, T2.x, T4.1, T5.1, T5.3 add tests under `tests/integration` and must keep the marker registered. Consequence: T0.6's guarded integration CI stage now finds tests and runs `pytest tests/integration` against the cached voice. +- T1.2 decisions: `char_offset_map` is authoritative — the engine validates each span (in bounds, non-overlapping) and calls `voice.synthesize(text[start:end])` per span rather than passing the whole text to piper's internal espeak splitter, which exposes no offsets and could disagree with the caller's segmentation. A span that piper renders as multiple chunks is concatenated (samples and alignments) so one span always yields one `SentenceAudio`; a span with no audio stays as an empty `SentenceAudio` with `supports_alignments=false`. `piper`/`SynthesisConfig` are imported lazily inside `synthesize` so `tts.engine` stays off the onnxruntime import path; unit tests stub `sys.modules["piper"]` to preserve T1.1's `preview_wav` isolation assertion. +- T1.2 deviation (measurement): piper 1.8's stochastic duration predictor is sublinear at `length_scale=2` — rate 0.5 measures ~1.73x the rate 1.0 duration on `en_US-lessac-medium`, outside the AC's 10% band, so the strict duration-ratio check uses rate 1.25 (nominal 0.8x, measured ~0.82x) averaged over 3 runs; the rate→`length_scale=1/rate` mapping itself is unit-tested and slower rates still produce measurably longer audio. T5.3 should measure real rate/duration scaling before documenting it. +- T1.2 environment note: a bare `pytest` run fails collection because `tests/unit/test_voices_store.py` and `tests/integration/test_voices_store.py` share a basename and neither directory is a package; CI passes because it runs each directory separately. New test files use unique names. +- T1.2 local integration voice: `en_US-lessac-medium` was downloaded to the gitignored `.venv/tts-data/voices` and integration tests ran with `TTS_DATA_DIR=.venv/tts-data`. diff --git a/src/tts/engine/__init__.py b/src/tts/engine/__init__.py new file mode 100644 index 0000000..7e3bdd4 --- /dev/null +++ b/src/tts/engine/__init__.py @@ -0,0 +1 @@ +"""Synthesis: text to PCM sentence audio with phoneme sample counts.""" diff --git a/src/tts/engine/piper_engine.py b/src/tts/engine/piper_engine.py new file mode 100644 index 0000000..a4156db --- /dev/null +++ b/src/tts/engine/piper_engine.py @@ -0,0 +1,123 @@ +"""Synthesize text into PCM sentences with per-phoneme sample counts.""" + +from __future__ import annotations + +import threading +from collections.abc import Callable +from typing import TYPE_CHECKING + +import numpy as np + +from tts.types import SentenceAudio, SynthesisResult + +if TYPE_CHECKING: + from piper import AudioChunk, SynthesisConfig + + from tts.voices.store import LoadedVoice + +# Values of piper.const.BOS / EOS / PAD. Duplicated so importing this module +# never imports piper (and therefore onnxruntime). +_BOUNDARY_PHONEMES = frozenset({"^", "$", "_"}) + + +def synthesize( + voice: LoadedVoice, + text: str, + char_offset_map: list[tuple[int, int]], + rate: float, + volume: float, + cancel_event: threading.Event, + on_sentence: Callable[[SentenceAudio], None], +) -> SynthesisResult: + """Synthesize each caller-supplied sentence span of ``text`` in order. + + ``char_offset_map`` is the sentence segmentation: one ``(char_start, + char_end)`` pair per sentence, in source order. The engine never splits + text itself; invalid or overlapping spans raise :class:`ValueError`. + + ``cancel_event`` is checked before each sentence, so an event set before + the first sentence yields an empty result and a later event returns the + sentences produced so far. + """ + from piper import SynthesisConfig + + _validate_offsets(text, char_offset_map) + syn_config = SynthesisConfig(length_scale=1.0 / rate, volume=volume) + + sentences: list[SentenceAudio] = [] + for char_start, char_end in char_offset_map: + if cancel_event.is_set(): + break + sentence_text = text[char_start:char_end] + samples, sample_rate, alignments, supports_alignments = _synthesize_segment( + voice, sentence_text, syn_config + ) + sentence = SentenceAudio( + text=sentence_text, + char_start=char_start, + char_end=char_end, + samples=samples, + sample_rate=sample_rate, + phoneme_alignments=alignments, + supports_alignments=supports_alignments, + ) + sentences.append(sentence) + on_sentence(sentence) + + return SynthesisResult( + sentences=sentences, + total_samples=sum(len(sentence.samples) for sentence in sentences), + sample_rate=voice.voice.config.sample_rate, + supports_alignments=voice.supports_alignments, + ) + + +def _validate_offsets(text: str, char_offset_map: list[tuple[int, int]]) -> None: + """Reject a segmentation that is empty, out of bounds, or overlapping.""" + previous_end = 0 + for char_start, char_end in char_offset_map: + if not 0 <= char_start < char_end <= len(text): + raise ValueError( + f"invalid sentence span ({char_start}, {char_end}) for text of length {len(text)}" + ) + if char_start < previous_end: + raise ValueError(f"overlapping sentence span ({char_start}, {char_end})") + previous_end = char_end + + +def _synthesize_segment( + voice: LoadedVoice, text: str, syn_config: SynthesisConfig +) -> tuple[np.ndarray, int, list[tuple[str, int]], bool]: + """Render one sentence span, combining chunks if piper yields more than one.""" + sample_arrays: list[np.ndarray] = [] + alignments: list[tuple[str, int]] = [] + sample_rate = voice.voice.config.sample_rate + supports_alignments = voice.supports_alignments + + for chunk in voice.voice.synthesize(text, syn_config=syn_config, include_alignments=True): + sample_arrays.append(np.asarray(chunk.audio_float_array, dtype=np.float32)) + sample_rate = chunk.sample_rate + chunk_alignments = _chunk_alignments(chunk) + if chunk_alignments: + alignments.extend(chunk_alignments) + else: + supports_alignments = False + + if not sample_arrays: + supports_alignments = False + samples = np.zeros(0, dtype=np.float32) + else: + samples = np.concatenate(sample_arrays) + + return samples, sample_rate, alignments, supports_alignments + + +def _chunk_alignments(chunk: AudioChunk) -> list[tuple[str, int]]: + """Return a chunk's phoneme sample counts without BOS/EOS/pad entries.""" + if not chunk.phoneme_alignments: + return [] + return [ + (alignment.phoneme, int(alignment.num_samples)) + for alignment in chunk.phoneme_alignments + if alignment.phoneme not in _BOUNDARY_PHONEMES + ] diff --git a/tests/integration/test_piper_engine.py b/tests/integration/test_piper_engine.py new file mode 100644 index 0000000..6f420aa --- /dev/null +++ b/tests/integration/test_piper_engine.py @@ -0,0 +1,118 @@ +"""Integration tests for the Piper engine against a real voice.""" + +from __future__ import annotations + +import statistics +import threading + +import numpy as np +import pytest + +from tts.config import Settings +from tts.engine.piper_engine import synthesize +from tts.types import SentenceAudio, SynthesisResult +from tts.voices.store import LoadedVoice, ensure_data_dirs, list_voices, load_voice + +pytestmark = pytest.mark.integration + +DEFAULT_VOICE_ID = "en_US-lessac-medium" +TEXT = "Hello there. How are you today? This is a test." +SENTENCES = ["Hello there.", "How are you today?", "This is a test."] + + +def _segments(text: str, sentences: list[str]) -> list[tuple[int, int]]: + """Locate each sentence in ``text`` and return its span.""" + offsets: list[tuple[int, int]] = [] + cursor = 0 + for sentence in sentences: + start = text.index(sentence, cursor) + end = start + len(sentence) + offsets.append((start, end)) + cursor = end + return offsets + + +@pytest.fixture(scope="module") +def loaded_voice() -> LoadedVoice: + settings = Settings.load() + voices_dir = ensure_data_dirs(settings) + installed = {voice.id for voice in list_voices()} + if DEFAULT_VOICE_ID not in installed: + pytest.skip( + f"{DEFAULT_VOICE_ID} is not installed; run: python -m piper.download_voices " + f"{DEFAULT_VOICE_ID} --download-dir {voices_dir}" + ) + return load_voice(DEFAULT_VOICE_ID) + + +def _synthesize(voice: LoadedVoice, rate: float = 1.0) -> SynthesisResult: + return synthesize( + voice, + TEXT, + _segments(TEXT, SENTENCES), + rate=rate, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + +def test_synthesizes_three_sentences_with_alignments(loaded_voice: LoadedVoice) -> None: + result = _synthesize(loaded_voice) + + assert [sentence.text for sentence in result.sentences] == SENTENCES + assert len(result.sentences) == 3 + assert result.sample_rate == 22_050 + assert result.supports_alignments is True + assert sum(len(sentence.samples) for sentence in result.sentences) == result.total_samples + assert result.total_samples > 0 + + for sentence in result.sentences: + assert isinstance(sentence, SentenceAudio) + assert sentence.samples.ndim == 1 + assert sentence.samples.dtype == np.float32 + assert sentence.samples.size > 0 + assert sentence.supports_alignments is True + assert sentence.phoneme_alignments + assert all(phoneme not in {"^", "$", "_"} for phoneme, _ in sentence.phoneme_alignments) + assert all(count > 0 for _, count in sentence.phoneme_alignments) + + +def _mean_seconds(loaded_voice: LoadedVoice, rate: float, runs: int = 3) -> float: + durations = [] + for _ in range(runs): + result = _synthesize(loaded_voice, rate=rate) + durations.append(result.total_samples / result.sample_rate) + return statistics.mean(durations) + + +def test_rate_scales_duration_within_ten_percent(loaded_voice: LoadedVoice) -> None: + # length_scale = 1/rate, so rate 1.25 is nominally 0.8x the duration. + # Piper 1.8's duration predictor is stochastic and only nearly linear for + # length_scale < 1 (length_scale 2.0 measures ~1.73x, not 2x), so average + # runs and check the ratio where the 10% acceptance band is representative. + baseline = _mean_seconds(loaded_voice, rate=1.0) + faster = _mean_seconds(loaded_voice, rate=1.25) + + assert baseline > 0 + assert 0.72 <= faster / baseline <= 0.88 + + +def test_cancel_before_first_sentence_yields_empty_result(loaded_voice: LoadedVoice) -> None: + cancel_event = threading.Event() + cancel_event.set() + seen: list[SentenceAudio] = [] + + result = synthesize( + loaded_voice, + TEXT, + _segments(TEXT, SENTENCES), + rate=1.0, + volume=1.0, + cancel_event=cancel_event, + on_sentence=seen.append, + ) + + assert result.sentences == [] + assert result.total_samples == 0 + assert seen == [] diff --git a/tests/unit/test_piper_engine.py b/tests/unit/test_piper_engine.py new file mode 100644 index 0000000..0e34253 --- /dev/null +++ b/tests/unit/test_piper_engine.py @@ -0,0 +1,317 @@ +"""Unit tests for the Piper engine wrapper using a fake voice.""" + +from __future__ import annotations + +import sys +import threading +from dataclasses import dataclass +from types import ModuleType, SimpleNamespace +from typing import Any + +import numpy as np +import pytest + +from tts.engine.piper_engine import synthesize +from tts.types import SentenceAudio +from tts.voices.store import LoadedVoice + +SAMPLE_RATE = 22_050 + + +@pytest.fixture(autouse=True) +def fake_piper(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep unit tests off onnxruntime; the integration suite uses the real piper.""" + module = ModuleType("piper") + + @dataclass(frozen=True) + class SynthesisConfig: + length_scale: float | None = None + noise_scale: float | None = None + noise_w_scale: float | None = None + normalize_audio: bool = True + volume: float = 1.0 + + module.SynthesisConfig = SynthesisConfig # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "piper", module) + + +@dataclass(frozen=True) +class FakeAlignment: + phoneme: str + num_samples: int + + +@dataclass(frozen=True) +class FakeChunk: + audio_float_array: np.ndarray + phoneme_alignments: list[FakeAlignment] | None + sample_rate: int = SAMPLE_RATE + sample_width: int = 2 + sample_channels: int = 1 + + +class FakeVoice: + """Stands in for PiperVoice: one list of chunks per input text.""" + + def __init__(self, chunks_by_text: dict[str, list[FakeChunk]]) -> None: + self.chunks_by_text = chunks_by_text + self.config = SimpleNamespace(sample_rate=SAMPLE_RATE) + self.calls: list[tuple[str, Any, bool]] = [] + + def synthesize( + self, + text: str, + syn_config: Any = None, + include_alignments: bool = False, + ) -> Any: + self.calls.append((text, syn_config, include_alignments)) + yield from self.chunks_by_text.get(text, []) + + +def _loaded(voice: FakeVoice, supports_alignments: bool = True) -> LoadedVoice: + return LoadedVoice(voice=voice, supports_alignments=supports_alignments) # type: ignore[arg-type] + + +def _chunk(samples: list[float], alignments: list[FakeAlignment] | None) -> FakeChunk: + return FakeChunk( + audio_float_array=np.array(samples, dtype=np.float32), phoneme_alignments=alignments + ) + + +def test_maps_each_segment_to_a_sentence_with_offsets() -> None: + text = "Hello. World!" + voice = FakeVoice( + { + "Hello.": [ + _chunk( + [0.1, 0.2], + [ + FakeAlignment("^", 1), + FakeAlignment("h", 1), + FakeAlignment("$", 1), + ], + ) + ], + "World!": [_chunk([0.3, 0.4, 0.5], [FakeAlignment("w", 3)])], + } + ) + seen: list[SentenceAudio] = [] + + result = synthesize( + _loaded(voice), + text, + [(0, 6), (7, 13)], + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=seen.append, + ) + + assert [sentence.text for sentence in result.sentences] == ["Hello.", "World!"] + assert [(sentence.char_start, sentence.char_end) for sentence in result.sentences] == [ + (0, 6), + (7, 13), + ] + assert [sentence.sample_rate for sentence in result.sentences] == [SAMPLE_RATE, SAMPLE_RATE] + assert [len(sentence.samples) for sentence in result.sentences] == [2, 3] + assert result.total_samples == 5 + assert result.sample_rate == SAMPLE_RATE + assert result.supports_alignments is True + assert seen == result.sentences + assert all(sentence.samples.dtype == np.float32 for sentence in result.sentences) + + assert result.sentences[0].phoneme_alignments == [("h", 1)] + assert result.sentences[0].supports_alignments is True + assert result.sentences[1].phoneme_alignments == [("w", 3)] + + +def test_combines_multiple_chunks_for_one_segment() -> None: + voice = FakeVoice( + { + "One sentence.": [ + _chunk([0.1], [FakeAlignment("w", 1)]), + _chunk([0.2, 0.3], [FakeAlignment("x", 2), FakeAlignment("_", 1)]), + ] + } + ) + + result = synthesize( + _loaded(voice), + "One sentence.", + [(0, 13)], + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + sentence = result.sentences[0] + assert sentence.samples.tolist() == pytest.approx([0.1, 0.2, 0.3]) + assert sentence.phoneme_alignments == [("w", 1), ("x", 2)] + assert result.total_samples == 3 + + +def test_segment_without_audio_is_kept_as_empty_sentence() -> None: + voice = FakeVoice({}) + + result = synthesize( + _loaded(voice), + "...", + [(0, 3)], + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + sentence = result.sentences[0] + assert sentence.text == "..." + assert sentence.samples.size == 0 + assert sentence.samples.dtype == np.float32 + assert sentence.phoneme_alignments == [] + assert sentence.supports_alignments is False + assert result.total_samples == 0 + + +def test_marks_sentence_degraded_when_alignment_is_missing() -> None: + voice = FakeVoice({"Hi.": [_chunk([0.1], None)]}) + + result = synthesize( + _loaded(voice), + "Hi.", + [(0, 3)], + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + assert result.sentences[0].supports_alignments is False + assert result.sentences[0].phoneme_alignments == [] + assert result.supports_alignments is True + + +def test_cancel_before_first_segment_returns_empty_result() -> None: + voice = FakeVoice({"Hello.": [_chunk([0.1], [FakeAlignment("h", 1)])]}) + cancel_event = threading.Event() + cancel_event.set() + seen: list[SentenceAudio] = [] + + result = synthesize( + _loaded(voice), + "Hello.", + [(0, 6)], + rate=1.0, + volume=1.0, + cancel_event=cancel_event, + on_sentence=seen.append, + ) + + assert result.sentences == [] + assert result.total_samples == 0 + assert seen == [] + assert voice.calls == [] + + +def test_cancel_between_segments_returns_partial_result() -> None: + voice = FakeVoice( + { + "Hello.": [_chunk([0.1, 0.2], [FakeAlignment("h", 2)])], + "World.": [_chunk([0.3], [FakeAlignment("w", 1)])], + } + ) + cancel_event = threading.Event() + seen: list[str] = [] + + def on_sentence(sentence: SentenceAudio) -> None: + seen.append(sentence.text) + cancel_event.set() + + result = synthesize( + _loaded(voice), + "Hello. World.", + [(0, 6), (7, 13)], + rate=1.0, + volume=1.0, + cancel_event=cancel_event, + on_sentence=on_sentence, + ) + + assert [sentence.text for sentence in result.sentences] == ["Hello."] + assert result.total_samples == 2 + assert seen == ["Hello."] + assert [call[0] for call in voice.calls] == ["Hello."] + + +def test_maps_rate_and_volume_to_synthesis_config() -> None: + voice = FakeVoice({"Hi.": [_chunk([0.1], [FakeAlignment("h", 1)])]}) + + synthesize( + _loaded(voice), + "Hi.", + [(0, 3)], + rate=0.5, + volume=0.4, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + _, syn_config, include_alignments = voice.calls[0] + assert syn_config.length_scale == 2.0 + assert syn_config.volume == 0.4 + assert include_alignments is True + + +def test_invalid_offsets_are_rejected_before_synthesis() -> None: + voice = FakeVoice({}) + cases = [ + [(-1, 3)], + [(0, 11)], + [(3, 3)], + [(5, 2)], + [(0, 4), (3, 6)], + ] + + for offsets in cases: + with pytest.raises(ValueError): + synthesize( + _loaded(voice), + "Hello.", + offsets, + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: None, + ) + + assert voice.calls == [] + + +def test_synthesis_errors_propagate_after_partial_callback() -> None: + class FailingVoice(FakeVoice): + def synthesize( + self, + text: str, + syn_config: Any = None, + include_alignments: bool = False, + ) -> Any: + self.calls.append((text, syn_config, include_alignments)) + if text == "Bad.": + raise RuntimeError("engine exploded") + yield _chunk([0.1], [FakeAlignment("h", 1)]) + + voice = FailingVoice({}) + seen: list[str] = [] + + with pytest.raises(RuntimeError, match="engine exploded"): + synthesize( + _loaded(voice), + "Ok. Bad.", + [(0, 3), (4, 8)], + rate=1.0, + volume=1.0, + cancel_event=threading.Event(), + on_sentence=lambda sentence: seen.append(sentence.text), + ) + + assert seen == ["Ok."]