A TTS that fits in your CPU (and pocket)
Python
Keep closing quotes and brackets with their sentence when chunking (#415)
quetion667f6104b50e3b9
diff --git a/pocket_tts/models/text_chunking.py b/pocket_tts/models/text_chunking.pyindex 79f33e4..6a4b02a 100644--- a/pocket_tts/models/text_chunking.py+++ b/pocket_tts/models/text_chunking.py@@ -108,6 +108,34 @@ def _is_inner_punctuation(return bool(words) and words[-1] in _TITLES and (len(words) > 1 or window_start == 0)+# A closing quote can span several byte tokens; bound the lookahead so the check stays linear.+_MAX_CLOSER_TOKENS = 8+# Characters allowed after the punctuation while skipping closers: U+FFFD is an incomplete closer.+_CLOSERS_OR_PARTIAL = _CLOSERS + "\ufffd"+++def _skip_closers(list_of_tokens: list[int], segment_start_idx: int, tokenizer: Tokenizer) -> int:+ """Return where the segment starting at segment_start_idx should really start: after the+ closing quotes and brackets that directly follow the punctuation, as in "“Stop.”" or+ "(quietly.)", so that they stay with their sentence instead of starting the next segment.++ A closer like the curly quote is made of byte tokens that decode to U+FFFD on their own, so+ the tokens are decoded together with the punctuation and the start only moves past complete+ closers. A closer preceded by a space opens the next sentence and is left alone.+ """+ punctuation = tokenizer.decode(list_of_tokens[segment_start_idx - 1 : segment_start_idx])+ start = segment_start_idx+ stop = min(len(list_of_tokens), segment_start_idx + _MAX_CLOSER_TOKENS)+ for end in range(segment_start_idx + 1, stop + 1):+ window = tokenizer.decode(list_of_tokens[segment_start_idx - 1 : end])+ after = window[len(punctuation) :]+ if not after or any(c not in _CLOSERS_OR_PARTIAL for c in after):+ break+ if "\ufffd" not in after:+ start = end+ return start++def _find_boundary_indices(list_of_tokens: list[int],boundary_tokens: list[int],@@ -135,7 +163,9 @@ def _find_boundary_indices():previous_was_boundary = Falsecontinue- indices.append(idx)+ start = idx if tokenizer is None else _skip_closers(list_of_tokens, idx, tokenizer)+ if start < len(list_of_tokens):+ indices.append(start)previous_was_boundary = Falseindices.append(len(list_of_tokens))return indicesdiff --git a/rust/src/text.rs b/rust/src/text.rsindex 3d157b4..27c5c4a 100644--- a/rust/src/text.rs+++ b/rust/src/text.rs@@ -195,6 +195,41 @@ fn ends_with_decimal_number(text: &str) -> bool {&& rest.next().is_some_and(char::is_numeric)}+/// A closing quote can span several byte tokens; bound the lookahead so the check stays linear.+const MAX_CLOSER_TOKENS: usize = 8;++/// Where the segment starting at `segment_start_idx` should really start: after the closing quotes+/// and brackets that directly follow the punctuation, as in "“Stop.”" or "(quietly.)", so that+/// they stay with their sentence. A closer made of byte tokens only counts once it decodes+/// completely; a closer preceded by a space opens the next sentence and is left alone.+fn skip_closers(+ tokens: &[u32],+ segment_start_idx: usize,+ tokenizer: &dyn TextTokenizer,+) -> Result<usize> {+ let punctuation = tokenizer.decode(&tokens[segment_start_idx - 1..segment_start_idx])?;+ let mut start = segment_start_idx;+ let stop = tokens.len().min(segment_start_idx + MAX_CLOSER_TOKENS);+ for end in segment_start_idx + 1..=stop {+ // A partial UTF-8 sequence may fail to decode: the closer is not complete yet.+ let Ok(window) = tokenizer.decode(&tokens[segment_start_idx - 1..end]) else {+ continue;+ };+ let after = window.get(punctuation.len()..).unwrap_or("");+ if after.is_empty()+ || after+ .chars()+ .any(|c| !(CLOSERS.contains(c) || c == '\u{fffd}'))+ {+ break;+ }+ if !after.contains('\u{fffd}') {+ start = end;+ }+ }+ Ok(start)+}+/// Token indices where the text should be split. Each consecutive pair of the result delimits a/// segment, the first is always 0 and the last `tokens.len()`.fn find_boundary_indices(@@ -216,7 +251,13 @@ fn find_boundary_indices(None => false,};if !is_inner {- indices.push(idx);+ let start = match inner_tokenizer {+ Some(tokenizer) => skip_closers(tokens, idx, tokenizer)?,+ None => idx,+ };+ if start < tokens.len() {+ indices.push(start);+ }}}previous_was_boundary = false;@@ -440,6 +481,28 @@ mod tests {assert_eq!(chunks, ["It is 3.14. Next one.", "Last."]);}+ #[test]+ fn closing_quotes_and_brackets_stay_with_their_sentence() {+ let o = options();+ let split = |text, max_tokens| {+ split_into_best_sentences(&CharTokenizer, text, max_tokens, &o).unwrap()+ };+ assert_eq!(split("He said “Stop.”", 100), ["He said “Stop.”"]);+ assert_eq!(+ split("He said “Stop.” Then he left.", 16),+ ["He said “Stop.”", "Then he left."]+ );+ assert_eq!(+ split("(quietly.) Okay then.", 11),+ ["(quietly.)", "Okay then."]+ );+ // A quote after a space opens the next sentence.+ assert_eq!(+ split("He left. “Hi.” Bye.", 8),+ ["He left.", "“Hi.”", "Bye."]+ );+ }+#[test]fn commas_between_digits_do_not_split() {let chunks = split_into_best_sentences(diff --git a/tests/test_split_sentences.py b/tests/test_split_sentences.pyindex 76679cb..47d5c35 100644--- a/tests/test_split_sentences.py+++ b/tests/test_split_sentences.py@@ -425,3 +425,35 @@ def test_sentence_ending_on_an_abbreviation_still_splits(tokenizer: Tokenizer):"We live in the U.S.","It is big. Very big.",]+++ "text, max_tokens, expected",+ [+ ("He said “Stop.”", 50, ["He said “Stop.”"]),+ ("He said “Stop.” Then he left.", 8, ["He said “Stop.”", "Then he left."]),+ (+ "A long first sentence goes right here. He said “Stop.”",+ 9,+ ["A long first sentence goes right here.", "He said “Stop.”"],+ ),+ ("He said 'Stop.' Then he left.", 8, ["He said 'Stop.'", "Then he left."]),+ ("(quietly.) Okay then.", 4, ["(quietly.)", "Okay then."]),+ ("He said (“Stop.”) Then he left.", 8, ["He said (“Stop.”)", "Then he left."]),+ (+ "“Stop,” he said, and then he left the room very quietly.",+ 8,+ ["“Stop,”", "he said,", "and then he left the room very quietly."],+ ),+ ],+)+def test_closing_quotes_and_brackets_stay_with_their_sentence(+ tokenizer: Tokenizer, text: str, max_tokens: int, expected: list[str]+):+ """A closer right after the punctuation ends that sentence or clause: it must not start the+ next chunk, become a chunk of its own, or get a space inserted before it ("Stop. ”")."""+ assert _split(tokenizer, text, max_tokens) == expected+++def test_opening_quote_of_the_next_sentence_is_not_moved(tokenizer: Tokenizer):+ assert _split(tokenizer, "He left. “Hi.” Bye.", 4) == ["He left.", "“Hi.”", "Bye."]