A small sentence splitter for text streams
Maintained. Last release 5 weeks ago, commits in 2 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install sentence-streamSentence Stream
A small sentence splitter for text streams.
Sentences come out as soon as their boundary is certain, so a stream of text chunks — from an LLM, say — can be handed to a text-to-speech engine a sentence at a time instead of waiting for the whole response.
Install
pip install sentence-stream
Example
from sentence_stream import stream_to_sentences
text_chunks = [
"Text chunks that a",
"re not on",
" word or se",
"ntence boundarie",
"s. But, they w",
"ill sti",
"ll get sp",
"lit right",
"!!! Goo",
"d",
]
assert list(stream_to_sentences(text_chunks)) == [
"Text chunks that are not on word or sentence boundaries.",
"But, they will still get split right!!!",
"Good",
]
Where the chunk boundaries fall never changes the result: the same text split
into different chunks always produces the same sentences. A single complete
string works too — stream_to_sentences("First sentence. Second sentence.") —
for when there is nothing to stream.
For async streams, use async_stream_to_sentences:
from sentence_stream import async_stream_to_sentences
async def main(text_stream):
async for sentence in async_stream_to_sentences(text_stream):
print(sentence)
Pushing chunks yourself
SentenceBoundaryDetector is the same logic without the iterator, for when text
arrives by callback rather than from something you can loop over. add_chunk
returns the sentences that are now complete, and finish returns whatever text
is left over — an empty string if there is none.
from sentence_stream import SentenceBoundaryDetector
detector = SentenceBoundaryDetector()
for sentence in detector.add_chunk("Hello world. Goodbye"):
print(sentence) # Hello world.
if final_sentence := detector.finish():
print(final_sentence) # Goodbye
A detector resets itself in finish, so it can be reused for the next stream.
What counts as a boundary
- Terminators followed by whitespace and a capital letter:
.!?… - CJK terminators, which need no whitespace after them:
。!?。, along with trailing closers such as」』)》