From 6481cfd65801c4b96b3d37b9303b923ab3a2b8a4 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Fri, 20 Nov 2026 18:20:18 +0530 Subject: [PATCH 1/2] feat(subtitles): add cue builder and srt/vtt renderers --- .gitattributes | 3 + src/tts/subtitles/__init__.py | 1 + src/tts/subtitles/cues.py | 93 +++++++++++++++++++ src/tts/subtitles/srt.py | 25 +++++ src/tts/subtitles/vtt.py | 23 +++++ tests/fixtures/subtitles/basic.srt | 11 +++ tests/fixtures/subtitles/basic.vtt | 10 ++ tests/unit/test_subtitles_cues.py | 141 +++++++++++++++++++++++++++++ tests/unit/test_subtitles_srt.py | 41 +++++++++ tests/unit/test_subtitles_vtt.py | 41 +++++++++ 10 files changed, 389 insertions(+) create mode 100644 .gitattributes create mode 100644 src/tts/subtitles/__init__.py create mode 100644 src/tts/subtitles/cues.py create mode 100644 src/tts/subtitles/srt.py create mode 100644 src/tts/subtitles/vtt.py create mode 100644 tests/fixtures/subtitles/basic.srt create mode 100644 tests/fixtures/subtitles/basic.vtt create mode 100644 tests/unit/test_subtitles_cues.py create mode 100644 tests/unit/test_subtitles_srt.py create mode 100644 tests/unit/test_subtitles_vtt.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..2703d8c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Caption golden files must stay byte-identical across checkouts so the +# byte-for-byte renderer tests pass on Windows clones with core.autocrlf=true. +tests/fixtures/subtitles/** text eol=lf diff --git a/src/tts/subtitles/__init__.py b/src/tts/subtitles/__init__.py new file mode 100644 index 0000000..1530272 --- /dev/null +++ b/src/tts/subtitles/__init__.py @@ -0,0 +1 @@ +"""Subtitle cue derivation and caption format renderers.""" diff --git a/src/tts/subtitles/cues.py b/src/tts/subtitles/cues.py new file mode 100644 index 0000000..1a23ff5 --- /dev/null +++ b/src/tts/subtitles/cues.py @@ -0,0 +1,93 @@ +"""Derive sentence-level subtitle cues from word timings.""" + +from __future__ import annotations + +from tts.types import Cue, WordTiming + +MAX_CUE_CHARS = 84 +MAX_CUE_MS = 5_000 +MIN_CUE_MS = 1_200 + + +def build_cues( + words: list[WordTiming], + sentences: list[tuple[int, int, int]], + audio_duration_ms: int, +) -> list[Cue]: + """Group words into caption cues bounded by sentence, length, and duration. + + ``sentences`` holds ``(char_start, char_end, first_word_idx)`` triplets. The + character offsets are informational β€” cue text comes from the word timings β€” + while ``first_word_idx`` marks where each sentence starts. A cue never spans + two sentences, and each cue stays within :data:`MAX_CUE_CHARS` characters and + :data:`MAX_CUE_MS` milliseconds. Every cue is extended to at least + :data:`MIN_CUE_MS` without overlapping the following cue, and the final cue + is clamped to the audio duration. + """ + cues: list[Cue] = [] + for window in _sentence_windows(words, sentences): + for group in _split_window(window): + cues.append( + Cue( + index=len(cues) + 1, + start_ms=group[0].start_ms, + end_ms=group[-1].end_ms, + text=" ".join(word.text for word in group), + ) + ) + return _extend_short_cues(cues, audio_duration_ms) + + +def _sentence_windows( + words: list[WordTiming], sentences: list[tuple[int, int, int]] +) -> list[list[WordTiming]]: + """Slice ``words`` into one window per non-empty sentence.""" + windows: list[list[WordTiming]] = [] + for position, sentence in enumerate(sentences): + next_start = sentences[position + 1][2] if position + 1 < len(sentences) else len(words) + start = _clamp_index(sentence[2], len(words)) + end = _clamp_index(max(next_start, start), len(words)) + if end > start: + windows.append(words[start:end]) + return windows + + +def _clamp_index(index: int, limit: int) -> int: + return max(0, min(index, limit)) + + +def _split_window(window: list[WordTiming]) -> list[list[WordTiming]]: + """Split one sentence's words into cues that respect the size limits. + + A single word that exceeds a limit is kept whole: splitting it would alter + its text, which caption output must never do. + """ + groups: list[list[WordTiming]] = [] + current: list[WordTiming] = [] + for word in window: + if current: + candidate_chars = ( + sum(len(item.text) for item in current) + len(current) + len(word.text) + ) + candidate_ms = word.end_ms - current[0].start_ms + if candidate_chars > MAX_CUE_CHARS or candidate_ms > MAX_CUE_MS: + groups.append(current) + current = [] + current.append(word) + if current: + groups.append(current) + return groups + + +def _extend_short_cues(cues: list[Cue], audio_duration_ms: int) -> list[Cue]: + """Give every cue a readable minimum duration without overlapping the next cue.""" + extended: list[Cue] = [] + last = len(cues) - 1 + for position, cue in enumerate(cues): + start = cue.start_ms + end = max(start, min(cue.end_ms, audio_duration_ms)) if position == last else cue.end_ms + if end - start < MIN_CUE_MS: + limit = audio_duration_ms if position == last else cues[position + 1].start_ms + end = min(start + MIN_CUE_MS, max(limit, start)) + extended.append(Cue(index=cue.index, start_ms=start, end_ms=end, text=cue.text)) + return extended diff --git a/src/tts/subtitles/srt.py b/src/tts/subtitles/srt.py new file mode 100644 index 0000000..836e0ea --- /dev/null +++ b/src/tts/subtitles/srt.py @@ -0,0 +1,25 @@ +"""Render subtitle cues as SubRip (SRT) text.""" + +from __future__ import annotations + +from tts.types import Cue + + +def render_srt(cues: list[Cue]) -> str: + """Render cues as SRT blocks separated by blank lines.""" + if not cues: + return "" + blocks = [ + f"{cue.index}\n" + f"{_format_timestamp(cue.start_ms)} --> {_format_timestamp(cue.end_ms)}\n" + f"{cue.text}" + for cue in cues + ] + return "\n\n".join(blocks) + "\n" + + +def _format_timestamp(milliseconds: int) -> str: + hours, remainder = divmod(max(0, int(milliseconds)), 3_600_000) + minutes, remainder = divmod(remainder, 60_000) + seconds, millis = divmod(remainder, 1_000) + return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}" diff --git a/src/tts/subtitles/vtt.py b/src/tts/subtitles/vtt.py new file mode 100644 index 0000000..b782b40 --- /dev/null +++ b/src/tts/subtitles/vtt.py @@ -0,0 +1,23 @@ +"""Render subtitle cues as WebVTT text.""" + +from __future__ import annotations + +from tts.types import Cue + + +def render_vtt(cues: list[Cue]) -> str: + """Render cues as a WebVTT document with blank-line-separated blocks.""" + blocks = [ + f"{_format_timestamp(cue.start_ms)} --> {_format_timestamp(cue.end_ms)}\n{cue.text}" + for cue in cues + ] + if not blocks: + return "WEBVTT\n\n" + return "WEBVTT\n\n" + "\n\n".join(blocks) + "\n" + + +def _format_timestamp(milliseconds: int) -> str: + hours, remainder = divmod(max(0, int(milliseconds)), 3_600_000) + minutes, remainder = divmod(remainder, 60_000) + seconds, millis = divmod(remainder, 1_000) + return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{millis:03d}" diff --git a/tests/fixtures/subtitles/basic.srt b/tests/fixtures/subtitles/basic.srt new file mode 100644 index 0000000..bb41a24 --- /dev/null +++ b/tests/fixtures/subtitles/basic.srt @@ -0,0 +1,11 @@ +1 +00:00:00,000 --> 00:00:03,200 +Hello world, this is a test. + +2 +00:00:03,200 --> 00:00:06,100 +Second sentence with a longer line of text that still fits. + +3 +00:00:06,100 --> 00:00:09,504 +A third cue ends the file. diff --git a/tests/fixtures/subtitles/basic.vtt b/tests/fixtures/subtitles/basic.vtt new file mode 100644 index 0000000..f7720e5 --- /dev/null +++ b/tests/fixtures/subtitles/basic.vtt @@ -0,0 +1,10 @@ +WEBVTT + +00:00:00.000 --> 00:00:03.200 +Hello world, this is a test. + +00:00:03.200 --> 00:00:06.100 +Second sentence with a longer line of text that still fits. + +00:00:06.100 --> 00:00:09.504 +A third cue ends the file. diff --git a/tests/unit/test_subtitles_cues.py b/tests/unit/test_subtitles_cues.py new file mode 100644 index 0000000..e16341b --- /dev/null +++ b/tests/unit/test_subtitles_cues.py @@ -0,0 +1,141 @@ +"""Unit tests for the subtitle cue builder.""" + +from __future__ import annotations + +from tts.subtitles.cues import MAX_CUE_CHARS, MAX_CUE_MS, MIN_CUE_MS, build_cues +from tts.types import WordTiming + + +def _word(text: str, start_ms: int, end_ms: int, *, aligned: bool = True) -> WordTiming: + return WordTiming(text=text, start_ms=start_ms, end_ms=end_ms, aligned=aligned) + + +def _words(*specs: tuple[str, int, int]) -> list[WordTiming]: + return [_word(text, start, end) for text, start, end in specs] + + +def test_empty_input_yields_no_cues() -> None: + assert build_cues([], [], 0) == [] + + +def test_words_without_sentences_yield_no_cues() -> None: + words = _words(("Hello", 0, 400), ("world", 400, 900)) + + assert build_cues(words, [], 900) == [] + + +def test_cue_never_crosses_a_sentence_boundary() -> None: + words = _words( + ("Hello", 0, 400), + ("there.", 400, 900), + ("General", 1400, 1900), + ("Kenobi!", 1900, 2400), + ) + sentences = [(0, 12, 0), (13, 27, 2)] + + cues = build_cues(words, sentences, 2400) + + assert [cue.text for cue in cues] == ["Hello there.", "General Kenobi!"] + assert [cue.index for cue in cues] == [1, 2] + + +def test_empty_sentence_triplet_is_skipped() -> None: + words = _words(("Hello", 0, 400), ("world", 400, 900)) + sentences = [(0, 5, 0), (6, 11, 0)] + + cues = build_cues(words, sentences, 900) + + assert len(cues) == 1 + assert cues[0].text == "Hello world" + + +def test_sentence_index_beyond_word_count_is_ignored() -> None: + words = _words(("Hello", 0, 400)) + sentences = [(0, 5, 7)] + + assert build_cues(words, sentences, 400) == [] + + +def test_long_sentence_splits_at_word_boundaries_under_char_limit() -> None: + words = [_word(f"word{index:02d}", index * 200, index * 200 + 200) for index in range(14)] + sentences = [(0, 14 * 7, 0)] + + cues = build_cues(words, sentences, 2800) + + word_starts = {word.start_ms for word in words} + assert len(cues) > 1 + assert all(len(cue.text) <= MAX_CUE_CHARS for cue in cues) + assert " ".join(cue.text for cue in cues) == " ".join(word.text for word in words) + assert all(cue.start_ms in word_starts for cue in cues) + assert cues[0].start_ms == words[0].start_ms + assert cues[-1].end_ms == words[-1].end_ms + + +def test_long_sentence_splits_under_duration_limit() -> None: + words = [_word(f"word{index}", index * 1000, index * 1000 + 1000) for index in range(6)] + sentences = [(0, 30, 0)] + + cues = build_cues(words, sentences, 6000) + + assert len(cues) == 2 + assert all(cue.end_ms - cue.start_ms <= MAX_CUE_MS for cue in cues) + assert [cue.text for cue in cues] == ["word0 word1 word2 word3 word4", "word5"] + + +def test_short_cue_is_extended_to_minimum_duration() -> None: + words = _words(("Hi", 0, 200)) + + cues = build_cues(words, [(0, 2, 0)], 2000) + + assert cues[0].start_ms == 0 + assert cues[0].end_ms == MIN_CUE_MS + + +def test_extension_is_capped_at_next_cue_start() -> None: + words = _words(("Hi", 0, 200), ("there", 500, 900)) + sentences = [(0, 2, 0), (3, 8, 1)] + + cues = build_cues(words, sentences, 2000) + + assert cues[0].end_ms == 500 + assert cues[0].end_ms == cues[1].start_ms + + +def test_last_cue_is_capped_at_audio_duration() -> None: + words = _words(("Hi", 0, 900)) + + cues = build_cues(words, [(0, 2, 0)], 800) + + assert cues[0].start_ms == 0 + assert cues[0].end_ms == 800 + + +def test_last_cue_extension_is_capped_at_audio_duration() -> None: + words = _words(("Hi", 0, 900)) + + cues = build_cues(words, [(0, 2, 0)], 1000) + + assert cues[0].end_ms == 1000 + + +def test_oversized_single_word_is_not_split() -> None: + long_word = "x" * (MAX_CUE_CHARS + 20) + words = _words((long_word, 0, 6000)) + + cues = build_cues(words, [(0, len(long_word), 0)], 6000) + + assert len(cues) == 1 + assert cues[0].text == long_word + assert cues[0].end_ms == 6000 + + +def test_degraded_zero_width_words_are_kept_in_cue_text() -> None: + words = [ + _word("Hello", 0, 400), + _word("πŸ™‚", 400, 400, aligned=False), + _word("world", 400, 900, aligned=False), + ] + + cues = build_cues(words, [(0, 13, 0)], 900) + + assert cues[0].text == "Hello πŸ™‚ world" diff --git a/tests/unit/test_subtitles_srt.py b/tests/unit/test_subtitles_srt.py new file mode 100644 index 0000000..1fdc190 --- /dev/null +++ b/tests/unit/test_subtitles_srt.py @@ -0,0 +1,41 @@ +"""Unit tests for the SRT renderer.""" + +from __future__ import annotations + +from pathlib import Path + +from tts.subtitles.srt import render_srt +from tts.types import Cue + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "subtitles" + +CUES = [ + Cue(index=1, start_ms=0, end_ms=3200, text="Hello world, this is a test."), + Cue( + index=2, + start_ms=3200, + end_ms=6100, + text="Second sentence with a longer line of text that still fits.", + ), + Cue(index=3, start_ms=6100, end_ms=9504, text="A third cue ends the file."), +] + + +def test_render_srt_matches_golden_fixture_byte_for_byte() -> None: + assert render_srt(CUES).encode("utf-8") == (FIXTURES / "basic.srt").read_bytes() + + +def test_render_srt_empty_cue_list_renders_nothing() -> None: + assert render_srt([]) == "" + + +def test_render_srt_uses_hour_scale_timestamps() -> None: + cue = Cue(index=1, start_ms=3_723_004, end_ms=3_726_507, text="Later on.") + + assert render_srt([cue]) == ("1\n01:02:03,004 --> 01:02:06,507\nLater on.\n") + + +def test_render_srt_clamps_negative_timestamps_to_zero() -> None: + cue = Cue(index=1, start_ms=-500, end_ms=0, text="Start.") + + assert render_srt([cue]).startswith("1\n00:00:00,000 --> 00:00:00,000\n") diff --git a/tests/unit/test_subtitles_vtt.py b/tests/unit/test_subtitles_vtt.py new file mode 100644 index 0000000..d5bcb3c --- /dev/null +++ b/tests/unit/test_subtitles_vtt.py @@ -0,0 +1,41 @@ +"""Unit tests for the WebVTT renderer.""" + +from __future__ import annotations + +from pathlib import Path + +from tts.subtitles.vtt import render_vtt +from tts.types import Cue + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "subtitles" + +CUES = [ + Cue(index=1, start_ms=0, end_ms=3200, text="Hello world, this is a test."), + Cue( + index=2, + start_ms=3200, + end_ms=6100, + text="Second sentence with a longer line of text that still fits.", + ), + Cue(index=3, start_ms=6100, end_ms=9504, text="A third cue ends the file."), +] + + +def test_render_vtt_matches_golden_fixture_byte_for_byte() -> None: + assert render_vtt(CUES).encode("utf-8") == (FIXTURES / "basic.vtt").read_bytes() + + +def test_render_vtt_empty_cue_list_is_a_valid_empty_document() -> None: + assert render_vtt([]) == "WEBVTT\n\n" + + +def test_render_vtt_uses_hour_scale_timestamps() -> None: + cue = Cue(index=1, start_ms=3_723_004, end_ms=3_726_507, text="Later on.") + + assert render_vtt([cue]) == ("WEBVTT\n\n01:02:03.004 --> 01:02:06.507\nLater on.\n") + + +def test_render_vtt_clamps_negative_timestamps_to_zero() -> None: + cue = Cue(index=1, start_ms=-500, end_ms=0, text="Start.") + + assert render_vtt([cue]).startswith("WEBVTT\n\n00:00:00.000 --> 00:00:00.000\n") From 6d8844b96bfb50e5f1341dbe079e8f3ea6e7598f Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Fri, 20 Nov 2026 18:20:18 +0530 Subject: [PATCH 2/2] chore(tasks): record t1.4 in progress --- docs/TASKS.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index fd2fe85..2e956b2 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -25,7 +25,7 @@ Statuses: done (PR merged) Β· doing (branch open, pending review) Β· remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty β€” next up: T1.4 on branch `arch/tts/t1.4`, pending review)_ | | | | | +| T1.4 | Subtitles β€” cue builder + SRT/VTT renderers | `arch/tts/t1.4` | 87 unit tests (21 new); Ruff check/format; strict mypy; golden fixtures byte-exact; `git diff --check` | PR pending review | ## Remaining @@ -94,3 +94,7 @@ _All P0 tasks done._ - T1.3 decisions: `timing/` also ships an `__init__.py` (a package needs one; Β§6 lists only `reconcile.py`). `split_words` is exported so callers group text with the same whitespace tokenizer; because a sentence below threshold collapses to exactly one entry, T1.6 should take per-sentence entry counts by deriving on a single-sentence `SynthesisResult` rather than assuming one entry per token. Matching removes piper's `^`/`$`/`_` and espeak's `" "` from both sequences β€” the space removal is required because espeak expands numbers into several words (`42` β†’ `fΛˆΙ”ΛΙΉti tˈuː`) while punctuation-only tokens such as `β€”` phonemize to nothing. A word counts as aligned when the longest contiguous `difflib` match covers β‰₯ 60% of its phonemes; the sentence collapse threshold is the same 60% and is inclusive (`3/5` stays, `2/5` collapses). `aligned_word_ratio` counts every token, so a collapsed sentence contributes its token count as unaligned; `-1.0` is returned only when `SynthesisResult.supports_alignments` is false or there are no sentences, and in that case no phonemization is attempted. Timing is accumulated in exact milliseconds across sentences and rounded half-up per word, then clamped into `[previous_end, sentence_end]`, so integer rounding cannot break monotonicity. - T1.3 real-voice check: manual run on `en_US-lessac-medium` with "Emoji πŸ™‚ stays honest. Yes β€” indeed, the 42 dogs rest!" reconciled 10/11 tokens (ratio 0.909), monotonic; `β€”` produced the expected zero-width unaligned entry, and espeak expands πŸ™‚ into "slightly smiling face", which reconciles honestly. The emoji unit fixture uses a synthetic zero-phoneme voice because real espeak speaks emoji names. - T1.3 environment note: `.venv/pytest-tmp` became undeletable (`WinError 5`) on this machine, so verification used fresh `--basetemp .venv/ptmp-*` directories; the default system temp directory remains inaccessible (see T0.2). +- T1.4 decisions: `subtitles/__init__.py` added (a package needs one; Β§6 lists only the three modules). `build_cues` slices `words` into one window per non-empty sentence using `first_word_idx` ranges `[first_word_idx, next.first_word_idx)`; the triplet's char offsets are informational only (the interface supplies no source text), so cue text is the window's word texts joined by one space. A cue splits before a word that would push it past 84 chars or 5 000 ms; a single oversized word stays whole. Every cue is extended to β‰₯1 200 ms capped at the next cue's start, and the last cue's end is clamped (and its extension capped) at `audio_duration_ms`. Renderers match the shipped `frontend/src/api/mock.ts` format: SRT blocks separated by a blank line, VTT `WEBVTT` + blank line, one trailing newline each; an empty SRT renders `""` and an empty VTT renders `"WEBVTT\n\n"`. +- T1.4 shared-file addition: `.gitattributes` pins `tests/fixtures/subtitles/**` to LF, so the byte-exact golden tests also pass on Windows clones (`core.autocrlf=true`). Downstream tasks adding golden caption fixtures must put them in that directory or extend the rule. +- T1.4 follow-up for T4.1: `frontend/src/api/mock.ts:buildCues` does not implement sentence grouping, the 1 200 ms floor, or the audio-duration cap. T4.1's mock/live parity pass should either mirror `tts.subtitles.cues` or explicitly accept the mock-only simplification. +- T1.4 downstream contract: T1.6 must supply `build_cues` with `(char_start, char_end, first_word_idx)` per `SynthesisResult` sentence, where `first_word_idx` indexes the final word list; empty sentences can pass a repeated index and are skipped.