Skip to content

A TTS that fits in your CPU (and pocket)

Python

Chunker: decimal commas, URLs/emails, titles; Rust port (#411)

manu-lm725e12c70520
diff --git a/pocket_tts/models/text_chunking.py b/pocket_tts/models/text_chunking.py
index 8f25410..79f33e4 100644
--- a/pocket_tts/models/text_chunking.py
+++ b/pocket_tts/models/text_chunking.py
@@ -54,8 +54,9 @@ def prepare_text_prompt(
_TERMINAL_PUNCTUATION = ".!?\u2026"
-# A segment ending on a decimal number, as in "... a fee of $822.95," or "... is 3.14."
-_ENDS_WITH_DECIMAL_NUMBER = re.compile(r"\d\.\d+\W*$")
+# A segment ending on a decimal number, as in "... a fee of $822.95,", "... is 3.14." or, with a
+# decimal comma, "... de 822,95 €,"
+_ENDS_WITH_DECIMAL_NUMBER = re.compile(r"\d[.,]\d+\W*$")
_WEAK_PUNCTUATION = ",;:-\u2013\u2014"
_CLOSERS = "\"'\u201d\u2019)]\u00bb"
@@ -81,32 +82,37 @@ def _ensure_terminal_punctuation(text: str) -> str:
return text + "."
-def _is_decimal_period_boundary(
+# Abbreviations that always precede a name or an example, never end a sentence.
+_TITLES = {"Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "Rev.", "vs.", "e.g.", "i.e."}
+
+
+def _is_inner_punctuation(
list_of_tokens: list[int], segment_start_idx: int, tokenizer: Tokenizer
) -> bool:
- """Return True when segment_start_idx begins right after a decimal period, as in "3.14".
+ """Return True when the punctuation right before segment_start_idx does not end a sentence or
+ clause: it is followed by a letter or digit without a space ("3.14", "3,14" with a decimal
+ comma, "1,000", "4 p.m.", "www.kyutai.org", "[email protected]"), or it ends a title that
+ precedes a name ("Dr. Miller", "e.g. this").
Only the tokens next to the boundary are decoded, so checking every sentence boundary
stays linear in the text length. Decoding the period together with the next token keeps
the space between them: in "I counted to 3. 14 people were there." the period ends a
sentence.
"""
- before = tokenizer.decode(list_of_tokens[max(0, segment_start_idx - 2) : segment_start_idx])
after = tokenizer.decode(list_of_tokens[segment_start_idx - 1 : segment_start_idx + 1])
- return (
- len(before) >= 2
- and before[-1] == "."
- and before[-2].isdigit()
- and len(after) >= 2
- and after[1].isdigit()
- )
+ if len(after) >= 2 and after[1].isalnum():
+ return True
+ window_start = max(0, segment_start_idx - 6)
+ words = tokenizer.decode(list_of_tokens[window_start:segment_start_idx]).split()
+ # The first word of the window may be cut, unless the window starts the text.
+ return bool(words) and words[-1] in _TITLES and (len(words) > 1 or window_start == 0)
def _find_boundary_indices(
list_of_tokens: list[int],
boundary_tokens: list[int],
tokenizer: Tokenizer | None = None,
- skip_decimal_periods: bool = False,
+ skip_inner_punctuation: bool = False,
) -> list[int]:
"""Find token indices where text should be split based on boundary tokens.
@@ -123,9 +129,9 @@ def _find_boundary_indices(
else:
if previous_was_boundary:
if (
- skip_decimal_periods
+ skip_inner_punctuation
and tokenizer is not None
- and _is_decimal_period_boundary(list_of_tokens, idx, tokenizer)
+ and _is_inner_punctuation(list_of_tokens, idx, tokenizer)
):
previous_was_boundary = False
continue
@@ -172,7 +178,7 @@ def split_into_best_sentences(
_, *end_of_sentence_tokens = tokenizer(".!...?")[0].tolist()
sentence_boundaries = _find_boundary_indices(
- list_of_tokens, end_of_sentence_tokens, tokenizer, skip_decimal_periods=True
+ list_of_tokens, end_of_sentence_tokens, tokenizer, skip_inner_punctuation=True
)
nb_tokens_and_sentences = _segments_from_boundaries(
list_of_tokens, sentence_boundaries, tokenizer
@@ -186,7 +192,9 @@ def split_into_best_sentences(
refined_segments.append((nb_tokens, text))
else:
sub_tokens = tokenizer(text.strip())[0].tolist()
- sub_boundaries = _find_boundary_indices(sub_tokens, fallback_tokens)
+ sub_boundaries = _find_boundary_indices(
+ sub_tokens, fallback_tokens, tokenizer, skip_inner_punctuation=True
+ )
sub_segments = _segments_from_boundaries(sub_tokens, sub_boundaries, tokenizer)
if len(sub_segments) > 1:
refined_segments.extend(sub_segments)
diff --git a/rust/src/text.rs b/rust/src/text.rs
index b2b30f7..3d157b4 100644
--- a/rust/src/text.rs
+++ b/rust/src/text.rs
@@ -154,21 +154,45 @@ fn ensure_terminal_punctuation(text: &str) -> String {
}
}
-/// Whether `segment_start_idx` begins right after a decimal period.
-fn is_decimal_period_boundary(
+/// Abbreviations that always precede a name or an example, never end a sentence.
+const TITLES: [&str; 9] = [
+ "Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "Rev.", "vs.", "e.g.", "i.e.",
+];
+
+/// Whether the punctuation right before `segment_start_idx` does not end a sentence or clause: it
+/// is followed by a letter or digit without a space ("3.14", "3,14" with a decimal comma,
+/// "1,000", "4 p.m.", "www.kyutai.org"), or it ends a title that precedes a name ("Dr. Miller").
+/// Only the tokens next to the boundary are decoded, as in Python.
+fn is_inner_punctuation(
tokens: &[u32],
segment_start_idx: usize,
tokenizer: &dyn TextTokenizer,
) -> Result<bool> {
- let prefix: Vec<char> = tokenizer
- .decode(&tokens[..segment_start_idx])?
+ let after: Vec<char> = tokenizer
+ .decode(&tokens[segment_start_idx - 1..=segment_start_idx])?
.chars()
.collect();
- let suffix = tokenizer.decode(&tokens[segment_start_idx..])?;
- Ok(prefix.len() >= 2
- && prefix[prefix.len() - 1] == '.'
- && prefix[prefix.len() - 2].is_numeric()
- && suffix.chars().next().is_some_and(char::is_numeric))
+ if after.len() >= 2 && after[1].is_alphanumeric() {
+ return Ok(true);
+ }
+ let window_start = segment_start_idx.saturating_sub(6);
+ let window = tokenizer.decode(&tokens[window_start..segment_start_idx])?;
+ let words: Vec<&str> = window.split_whitespace().collect();
+ // The first word of the window may be cut, unless the window starts the text.
+ Ok(words
+ .last()
+ .is_some_and(|w| TITLES.contains(w) && (words.len() > 1 || window_start == 0)))
+}
+
+/// Whether `text` ends on a decimal number, possibly followed by punctuation or symbols, as in
+/// "... a fee of $822.95," or "... de 822,95 €," (Python's `\d[.,]\d+\W*$`).
+fn ends_with_decimal_number(text: &str) -> bool {
+ let core = text.trim_end_matches(|c: char| !(c.is_alphanumeric() || c == '_'));
+ let decimals = core.trim_end_matches(|c: char| c.is_numeric());
+ let mut rest = decimals.chars().rev();
+ decimals.len() < core.len()
+ && matches!(rest.next(), Some('.' | ','))
+ && rest.next().is_some_and(char::is_numeric)
}
/// Token indices where the text should be split. Each consecutive pair of the result delimits a
@@ -176,7 +200,7 @@ fn is_decimal_period_boundary(
fn find_boundary_indices(
tokens: &[u32],
boundary_tokens: &[u32],
- decimal_tokenizer: Option<&dyn TextTokenizer>,
+ inner_tokenizer: Option<&dyn TextTokenizer>,
) -> Result<Vec<usize>> {
let boundary_set: HashSet<u32> = boundary_tokens.iter().copied().collect();
let mut indices = vec![0];
@@ -187,11 +211,11 @@ fn find_boundary_indices(
continue;
}
if previous_was_boundary {
- let is_decimal = match decimal_tokenizer {
- Some(tokenizer) => is_decimal_period_boundary(tokens, idx, tokenizer)?,
+ let is_inner = match inner_tokenizer {
+ Some(tokenizer) => is_inner_punctuation(tokens, idx, tokenizer)?,
None => false,
};
- if !is_decimal {
+ if !is_inner {
indices.push(idx);
}
}
@@ -241,7 +265,7 @@ pub fn split_into_best_sentences(
continue;
}
let sub_tokens = tokenizer.encode(sentence.trim())?;
- let sub_boundaries = find_boundary_indices(&sub_tokens, &fallback_tokens, None)?;
+ let sub_boundaries = find_boundary_indices(&sub_tokens, &fallback_tokens, Some(tokenizer))?;
let sub_segments = segments_from_boundaries(&sub_tokens, &sub_boundaries, tokenizer)?;
if sub_segments.len() > 1 {
refined_segments.extend(sub_segments);
@@ -250,6 +274,21 @@ pub fn split_into_best_sentences(
}
}
+ // Never end a chunk on a decimal number: "... $822.95," would become the chunk "... $822.95."
+ // and the model takes the decimal point for the sentence end, stopping before the decimals.
+ // Such a segment stays with the next one.
+ let mut glued_segments: Vec<(usize, String)> = Vec::new();
+ for (nb_tokens, text) in refined_segments {
+ match glued_segments.last_mut() {
+ Some((prev_tokens, prev_text)) if ends_with_decimal_number(prev_text) => {
+ *prev_tokens += nb_tokens;
+ *prev_text = format!("{} {}", prev_text.trim_end(), text.trim());
+ }
+ _ => glued_segments.push((nb_tokens, text)),
+ }
+ }
+ let refined_segments = glued_segments;
+
let mut chunks = Vec::new();
let mut current_chunk = String::new();
let mut current_nb_of_tokens = 0;
@@ -381,4 +420,62 @@ mod tests {
split_into_best_sentences(&CharTokenizer, "aaaa, bbbb, cccc.", 8, &options()).unwrap();
assert_eq!(chunks, ["Aaaa,", "bbbb,", "cccc."]);
}
+
+ #[test]
+ fn chunks_never_end_on_a_decimal_number() {
+ let o = options();
+ // Without the rule: ["A fee of 822.95,", "which is due."], then "A fee of 822.95." is read
+ // as ending at the decimal point.
+ let chunks =
+ split_into_best_sentences(&CharTokenizer, "A fee of 822.95, which is due.", 18, &o)
+ .unwrap();
+ assert_eq!(chunks, ["A fee of 822.95, which is due."]);
+ let chunks =
+ split_into_best_sentences(&CharTokenizer, "Une note de 822,95 €, à payer.", 18, &o)
+ .unwrap();
+ assert_eq!(chunks, ["Une note de 822,95 €, à payer."]);
+ let chunks =
+ split_into_best_sentences(&CharTokenizer, "It is 3.14. Next one. Last.", 12, &o)
+ .unwrap();
+ assert_eq!(chunks, ["It is 3.14. Next one.", "Last."]);
+ }
+
+ #[test]
+ fn commas_between_digits_do_not_split() {
+ let chunks = split_into_best_sentences(
+ &CharTokenizer,
+ "aaaa 1,500 bbbb, cccc 3,5 dd, eeee.",
+ 14,
+ &options(),
+ )
+ .unwrap();
+ assert_eq!(chunks, ["Aaaa 1,500 bbbb,", "cccc 3,5 dd,", "eeee."]);
+ }
+
+ #[test]
+ fn decimal_number_endings() {
+ for text in ["a 822.95,", "de 822,95 €,", "3.14.", "x 1,000"] {
+ assert!(ends_with_decimal_number(text), "{text}");
+ }
+ for text in ["in 2008.", "822.95 dollars,", "1.", ".5", "v2"] {
+ assert!(!ends_with_decimal_number(text), "{text}");
+ }
+ }
+
+ #[test]
+ fn punctuation_inside_words_and_titles_do_not_split() {
+ let o = options();
+ let chunks = split_into_best_sentences(
+ &CharTokenizer,
+ "Mail [email protected] at 4 p.m. Ask Dr. Who. Then go.",
+ 24,
+ &o,
+ )
+ .unwrap();
+ // Without the rule: ["Mail jo@mail.", "com at 4 p. m. Ask Dr.", "Who. Then go."].
+ assert_eq!(
+ chunks,
+ ["Mail [email protected] at 4 p.m.", "Ask Dr. Who. Then go."]
+ );
+ }
}
diff --git a/tests/test_split_sentences.py b/tests/test_split_sentences.py
index 28e9207..76679cb 100644
--- a/tests/test_split_sentences.py
+++ b/tests/test_split_sentences.py
@@ -321,6 +321,10 @@ REIMBURSEMENT = (
"will be a reimbursement of $822.95, which should be reflected in your account within "
"a few business days."
)
+DECIMAL_COMMA = (
+ "Le dossier a été transmis au service comptable de la région et le remboursement prévu "
+ "sera de 822,95 €, ce qui devrait apparaître sur votre compte dans quelques jours."
+)
SERVICE_FEE = (
"Sure, I can walk you through the procedure, the solution we typically offer includes "
"an onsite technician visit, and the standard service fee is $286.50, our team "
@@ -333,6 +337,7 @@ SERVICE_FEE = (
[
(REIMBURSEMENT, 50, "$822.95,"),
(SERVICE_FEE, 50, "$286.50,"),
+ (DECIMAL_COMMA, 50, "822,95 €,"),
(
"The value is 3.14. The next value is larger. And the third one is the largest.",
10,
@@ -374,3 +379,49 @@ def test_splits_without_decimal_numbers_are_unchanged(tokenizer: Tokenizer):
"It was raining.",
"The bus was late.",
]
+
+
+def test_commas_between_digits_do_not_split(tokenizer: Tokenizer):
+ """Splitting a long sentence on commas must not cut "1,994.42" or "3,5" (decimal comma)."""
+ text = (
+ "The technician reported that the centrifuge needs 1,994.42 kW and an extra 1,874 kW to "
+ "function on 06-30-2028 at 14 Lab Court, E8 5TT Manchester, MU9S 3VC, le taux est de 3,5 %"
+ )
+ chunks = _split(tokenizer, text, 20)
+ assert len(chunks) > 1
+ for number in ["1,994.42", "1,874", "3,5"]:
+ assert any(number in chunk for chunk in chunks), (number, chunks)
+
+
+URLS = (
+ "You can view the details of your consultation and of the invoice at www.actu.com/tech, "
+ "or send an email to [email protected], and we will reply before 4 p.m. on Monday."
+)
+TITLES = (
+ "Hi, I'm calling to follow up on your latest lab results, the ones we discussed with Dr. "
+ "Miller and Prof. Chen, the specialists in cardiology, and the general practitioner."
+)
+
+
+ "text, kept",
+ [
+ (URLS, ["www.actu.com/tech,", "[email protected],", "p.m."]),
+ (TITLES, ["Dr. Miller", "Prof. Chen"]),
+ ],
+)
+def test_no_cut_inside_words_or_after_titles(tokenizer: Tokenizer, text: str, kept: list[str]):
+ """A period followed by a letter (URLs, emails, "p.m.") or ending a title ("Dr.") is not a
+ sentence end: no chunk is cut there and no space is inserted ("icloud. com")."""
+ chunks = _split(tokenizer, text, 20)
+ assert len(chunks) > 1
+ for words in kept:
+ assert any(words in chunk for chunk in chunks), (words, chunks)
+ assert " ".join(chunks).split() == text.split()
+
+
+def test_sentence_ending_on_an_abbreviation_still_splits(tokenizer: Tokenizer):
+ assert _split(tokenizer, "We live in the U.S. It is big. Very big.", 8) == [
+ "We live in the U.S.",
+ "It is big. Very big.",
+ ]