Cutting a book into sentences for text-to-speech, in fourteen languages
A text-to-speech reader needs one thing before it can say a word: a list of sentences. Not as a nicety - in our reader that list is the index everything else keys on.
The voice's cursor, the "you stopped here" watermark, the cache key of the parallel translation and the sentence highlight all count in sentences. If two clients cut the same line differently, every one of those drifts apart. We have two clients, a web app and a native Android app, and books in fourteen languages.
This post walks through the splitter we ended up with, why each piece of the regex exists, and how one JSON fixture keeps the JavaScript and Kotlin copies cutting identically.
The naive version and where it breaks
The textbook splitter is "anything up to a run of .!?":
const naive = t => t.match(/[^.!?]+[.!?]+\s*/g);
Here is what it does with real-looking lines (output from running it in Node):
"„Wie lange?“ Er ging."naive:["„Wie lange?", "“ Er ging."]"Hoe gaat het?’ schreef ze."naive:["Hoe gaat het?", "’ schreef ze."]"« Le phare est resté vide. » Anne prit des notes."naive:["« Le phare est resté vide. ", "» Anne prit des notes."]"1. The Alarm"naive:["1. "]"D. Gajda. Não havia dúvida sobre as letras."naive:["D. ", "Gajda. ", "Não havia dúvida sobre as letras."]"He paused… Then spoke."naive:["He paused… Then spoke."]
Four separate failures:
- The closing quote goes to the wrong sentence. German closes
„…", Dutch writes’, French writes». The naive pattern stops at the?and hands the closing mark to the next sentence. A plain TTS engine then reads a lone“or starts the next sentence with a stray quote. - The ellipsis is not punctuation.
…is a single character (U+2026), not three dots, so"He paused… Then spoke."stays one sentence. - A numbered heading disappears.
"1. The Alarm"has no terminal punctuation after"The Alarm", so match returns only"1. "- the title itself is silently dropped. - An initial becomes a sentence.
"D."is read aloud as a sentence of its own.
The version that ships
This is the current function from web/reader-audio.js, unchanged:
function splitSentences(text) {
const raw = text.match(/[^.!?…]*[.!?…]+[”"')»’“«‘]*(?: »(?!\p{L}))?\s*|[^.!?…]+\s*$/gu) || [text];
const out = [];
let carry = "";
for (const part of raw) {
// "1. The Lost Kitten" is a heading, not a sentence called "1." - the number
// (or a single initial) joins what follows it instead of being read aloud.
if (/^\s*(?:\d{1,3}|[A-Za-z])[.)]\s*$/.test(part)) {
carry += part;
continue;
}
out.push(carry + part);
carry = "";
}
if (carry) out.push(carry);
return out.filter(x => x.trim());
}
Piece by piece:
[^.!?…]*[.!?…]+- a sentence runs to a run of terminal marks, with…added to the set.[”"')»’“«‘]*- then it takes every quote that closes in one of the languages we carry. That class looks odd until you notice that“and«are closers too: German and Czech write„…", Swedish writes»…«, and the nested Czech quote is‚…‘. The class is about what closes somewhere, not what closes in English.(?: »(?!\p{L}))?- the French exception, explained below.|[^.!?…]+\s*$- a final fragment without punctuation ("Just a fragment", or"The Alarm") is still a sentence. This alternative is what stops the heading from vanishing.- The carry loop - a part that is nothing but a number of up to three digits or a single Latin letter, followed by
.or), is glued to the next part instead of being emitted.
The same inputs through the shipped function:
"„Wie lange?“ Er ging."→["„Wie lange?“", "Er ging."]"Hoe gaat het?’ schreef ze."→["Hoe gaat het?’", "schreef ze."]"« Le phare est resté vide. » Anne prit des notes."→["« Le phare est resté vide. »", "Anne prit des notes."]"1. The Alarm"→["1. The Alarm"]"D. Gajda. Não havia dúvida sobre as letras."→["D. Gajda.", "Não havia dúvida sobre as letras."]"He paused… Then spoke."→["He paused…", "Then spoke."]"Es war 5. Dann ging er."→["Es war 5.", "Dann ging er."]
The last line is the price of the carry rule being narrow on purpose: "5." at the end of a part with text before it is not a bare number, so "Es war 5." stays a sentence.
The French space, and why Swedish cares
French puts a space before its closing guillemet: vide. ». Everywhere else, a quote separated from the full stop by a space is the next sentence opening: English He left. “Come back.”, Swedish dammig. »Tio kronor«.
Both shapes are a space followed by ». What tells them apart is the character after the guillemet. Swedish opens a quote, so a letter follows immediately: »Tio. French closes one, so a space or the end of the line follows: » Anne. Hence the lookahead (?!\p{L}) - take » only when the next character is not a letter. That needs the u flag for \p{L} to work at all.
Dropping the lookahead shows what it guards. With (?: »)? instead:
["Boken är dammig. »", "Tio kronor«, säger hon."]← Swedish, now wrong["« Le phare est resté vide. » ", "Anne prit des notes."]French still works, but the Swedish opening quote is torn off its sentence.
One fixture, two languages
Android cannot run that JavaScript; it has its own Sentences.kt with the same two patterns written as Kotlin Regex. To keep them from drifting, the cases live in a JSON file, server/tests/fixtures/sentences.json, read by both test suites.
An entry looks like this:
{ "in": "Il a dit : « Qui était cet homme ? » Elle insista.", "out": "Il a dit : « Qui était cet homme ? »|Elle insista." }
The file holds 25 split cases plus a list of headings that must come back as one sentence. On the Python side, server/tests/test_sentences.py extracts the shipped splitSentences source from web/reader-audio.js and runs it through Node rather than re-implementing it; on Android, SentencesFixtureTest (splitMatchesTheSharedFixture, noFragmentIsEmittedAsASentenceOfItsOwn, …) runs Sentences.split() against the same file.
A third check, test_both_clients_carry_the_same_two_patterns, looks for the same four regex fragments in both source files (backslashes stripped, since a JS literal and a Kotlin string escape differently), so a fix applied to one client and not the other fails CI before it reaches a reader.
Two details made the comparison workable:
- Trim before comparing. The web version keeps the trailing space inside each sentence, because it becomes the
<span>and that space is the visual gap between sentences. Kotlin trims. The fixture stores trimmed sentences and both sides trim before comparing. - No
|in the input. Expected output is|-separated to keep the file readable, so no case may contain one.
What we would tell someone starting this
- Define "sentence" by what your downstream consumer needs. Ours is a voice: a fragment it reads aloud as
“orD.is a bug, a slightly long sentence is not. - Build the closing-quote class from every language you ship, then add counter-examples for each mark: for every
»that closes, find where»opens. - Put the cases in data, not in either test suite. The fixture is the spec; the two implementations are just its two readers.
The same split also drives the public listen pages: each sentence is wrapped in its own span and lit up as the voice reaches it, which you can hear on any book from the English audiobooks with text shelf.
This article was drafted with AI assistance; we ran the code and checked every figure and claim before publishing.
Comments
No comments yet. Start the discussion.