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
5 changes: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ tts/
char_end: int
samples: "numpy.ndarray" # float32 PCM, mono
sample_rate: int
phoneme_alignments: list[tuple[str, int]] # (phoneme, num_samples), BOS/EOS/pad excluded
phoneme_alignments: list[tuple[str, int]] # (phoneme, num_samples) in audio order,
# boundary markers (^ $ _) included so the
# counts sum to len(samples); timing skips
# them for word matching
supports_alignments: bool # False → degraded mode

@dataclass(frozen=True)
Expand Down
2 changes: 2 additions & 0 deletions docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,5 @@ _All P4 tasks done._
- T5.1 results: 15/15 specs pass against the real `en_US-lessac-medium`, three consecutive runs (one from empty data dirs to prove voice seeding) at ~24 s each. AC11 runs on the fault server and proves the failed row has no `.wav`/`.part` while the main server's history total and a prior ready entry stay intact and restorable; AC12 cancels a 5,000-char slow-rate job and proves no partial file, no audio, no downloads; AC9/AC10 parse the downloaded WAV/SRT/VTT bytes (not API bodies) and cross-check download names, RIFF sizes, and cue timing; AC15 drives the whole flow with Tab/Enter/Space only.
- T5.1 browser finding (recorded, no production change): a native `<audio controls>` element absorbs several Tab presses inside its own shadow controls, and when a generation finishes the Generate button is replaced, so focus returns to the document and forward Tab skips ahead to the sentence cues. Keyboard users can still play from the main landmark with the documented Space shortcut; AC15 reaches that landmark through the skip link. This is existing UI behavior outside T5.1's owned files, noted for T5.2.
- T5.1 verification: 15/15 Playwright specs (three runs, one from empty data dirs); `npx tsc -p tests/e2e --noEmit`; 201 pytest unit; 16 integration (`TTS_DATA_DIR=.venv/tts-data`, `--basetemp .venv/ptmp-t51-int`); 111 Vitest; Ruff check/format; strict mypy; ESLint; frontend `tsc --noEmit`; Prettier (CRLF); `git diff --check`. PR CI must confirm the two-server topology on Linux.

- Timing fix (found by T5.3 measurement, merged before T5.3): `engine/piper_engine.py` dropped piper's `^`/`$`/`_` alignments entirely, discarding their sample counts, so `timing/reconcile.py` placed every word early by the sentence-leading silence (measured 60-320 ms on the two test voices, exceeding AC7's ±100 ms target). `_chunk_alignments` now keeps every entry; reconcile already skips boundary phonemes for word matching while still advancing its sample cursor by their durations. ARCHITECTURE §7.2's `SentenceAudio.phoneme_alignments` comment was updated in the same PR (shared-file protocol), and alignment counts now sum exactly to `len(samples)` as §14.5 point 1 asserts. Dependent tasks: T1.2, T1.3, T5.1 (AC7 tolerance and the AC10 spec, whose "first cue starts at zero" assertion became "first cue starts at or before the first audible word"), T5.3.
16 changes: 8 additions & 8 deletions src/tts/engine/piper_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@

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,
Expand Down Expand Up @@ -113,11 +109,15 @@ def _synthesize_segment(


def _chunk_alignments(chunk: AudioChunk) -> list[tuple[str, int]]:
"""Return a chunk's phoneme sample counts without BOS/EOS/pad entries."""
"""Return every phoneme sample count, boundary markers included.

Piper's BOS/EOS/pad entries carry the leading and trailing silence of a
sentence. ``timing/reconcile`` skips them when matching words but still
advances its sample cursor by their durations, so dropping them here would
shift every word of the sentence earlier by the leading silence.
"""
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
(alignment.phoneme, int(alignment.num_samples)) for alignment in chunk.phoneme_alignments
]
17 changes: 15 additions & 2 deletions tests/e2e/specs/ac10-subtitle-loads.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import { uniqueText } from "../support/run";
import { parseSrt, parseVtt } from "../support/subtitles";
import { generateInUi, openApp } from "../support/ui";

/**
* Piper pads each sentence with leading silence, so the first word - and the
* first cue derived from it - starts a little after the file begins. Anything
* beyond this bound would mean the cue is offset from the audio rather than
* tracking it.
*/
const MAX_FIRST_CUE_START_MS = 1000;

async function downloadText(
page: Page,
label: string,
Expand Down Expand Up @@ -68,9 +76,14 @@ test("AC10: downloaded SRT/VTT parse and match the audio timing", async ({
expect(vtt[index]?.text).toBe(cue.text);
}

// What a caption tool checks: starts at zero, monotonic, inside the audio.
// What a caption tool checks: begins at the start of the audio, monotonic,
// inside the audio. The first cue follows the first audible word rather than
// snapping to zero, so it may sit inside piper's leading silence.
for (const captions of [srt, vtt]) {
expect(captions[0]?.startMs).toBe(0);
expect(captions[0]?.startMs ?? -1).toBeGreaterThanOrEqual(0);
expect(captions[0]?.startMs ?? Infinity).toBeLessThanOrEqual(
MAX_FIRST_CUE_START_MS,
);
for (let index = 1; index < captions.length; index += 1) {
const previous = captions[index - 1];
const current = captions[index];
Expand Down
5 changes: 4 additions & 1 deletion tests/integration/test_piper_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ def test_synthesizes_three_sentences_with_alignments(loaded_voice: LoadedVoice)
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 any(phoneme in {"^", "$", "_"} for phoneme, _ in sentence.phoneme_alignments)
assert all(count > 0 for _, count in sentence.phoneme_alignments)
# Boundary markers carry the leading and trailing silence, so the whole
# alignment covers the sentence audio exactly.
assert sum(count for _, count in sentence.phoneme_alignments) == len(sentence.samples)


def _mean_seconds(loaded_voice: LoadedVoice, rate: float, runs: int = 7) -> float:
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/test_piper_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def test_maps_each_segment_to_a_sentence_with_offsets() -> None:
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].phoneme_alignments == [("^", 1), ("h", 1), ("$", 1)]
assert result.sentences[0].supports_alignments is True
assert result.sentences[1].phoneme_alignments == [("w", 3)]

Expand All @@ -147,7 +147,7 @@ def test_combines_multiple_chunks_for_one_segment() -> 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 sentence.phoneme_alignments == [("w", 1), ("x", 2), ("_", 1)]
assert result.total_samples == 3


Expand Down
34 changes: 34 additions & 0 deletions tests/unit/test_timing_reconcile.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,40 @@ def test_maps_words_to_their_phoneme_spans() -> None:
assert voice.calls == ["Hello", "world."]


def test_boundary_phonemes_offset_words_into_their_real_audio() -> None:
"""Piper's BOS/EOS silence must move word starts, not be discarded.

Regression: the engine used to drop ``^``/``$``/``_`` alignments, which
made every word of a sentence start early by the leading silence.
"""
voice = FakeVoice({"Hello": HELLO, "world.": WORLD})
sentence = _sentence(
"Hello world.",
[
("^", 150),
("h", 100),
("ə", 100),
("l", 100),
("ˈoʊ", 100),
(" ", 100),
("w", 100),
("ɜː", 100),
("l", 100),
("d", 100),
(".", 100),
("$", 100),
],
)

timings, ratio = derive_word_timings(_loaded(voice), _result([sentence]))

assert [(word.text, word.start_ms, word.end_ms, word.aligned) for word in timings] == [
("Hello", 150, 550, True),
("world.", 650, 1150, True),
]
assert ratio == pytest.approx(1.0)


def test_timings_stay_monotonic_across_sentences() -> None:
voice = FakeVoice({"Hello": HELLO, "world.": WORLD})
first = _sentence("Hello world.", _hello_world_alignments())
Expand Down
Loading