"""Punctuation-only sentence splitting for streaming TTS (language-agnostic). Same rule as the v1 bridge (``bridge/text_utils.py``), which is legacy and goes away with v2; the worker keeps its own copy so it does not depend on the v1 package. """ from __future__ import annotations import re # A boundary is a run of newlines, a run of CJK terminators (always a sentence end, CJK puts no space # after one), or a run of ASCII terminators that really ends a sentence: followed by whitespace, a # closing quote or bracket, or the end of the text. Dots inside tokens (17.5, v2.0, example.com) are # followed by a non-space character, so they never match. _BOUNDARY = re.compile( r""" (?P\n+) | (?P[。!?…]+) | (?P[.!?]+)(?=[)\]"'”’》」』]*(?:\s|$)) """, re.VERBOSE, ) def split_sentences(text: str | None, min_len: int = 5) -> list[str]: """Split ``text`` into sentence chunks; fragments under ``min_len`` characters join a neighbour.""" return _split(text, min_len, merge_short_tail=True) def _split(text: str | None, min_len: int, merge_short_tail: bool) -> list[str]: text = (text or "").strip() if not text: return [] chunks: list[str] = [] buf = "" last = 0 for m in _BOUNDARY.finditer(text): buf += text[last:m.end()] last = m.end() if len(buf.strip()) >= min_len: chunks.append(buf.strip()) buf = "" tail = (buf + text[last:]).strip() if tail: if merge_short_tail and chunks and len(tail) < min_len: chunks[-1] = chunks[-1] + " " + tail else: chunks.append(tail) return chunks class StreamingSplitter: """Feed text as it streams in; get back every sentence that is certainly complete.""" def __init__(self, min_len: int = 5): self.min_len = min_len self._buf = "" def feed(self, text: str) -> list[str]: self._buf += text # The tail may still grow, so it is not merged backwards here. chunks = _split(self._buf, self.min_len, merge_short_tail=False) if len(chunks) <= 1: return [] done = chunks[:-1] # Keep the raw text after the last emitted chunk, so spacing inside the tail is untouched. consumed = 0 for c in done: consumed = self._buf.index(c, consumed) + len(c) self._buf = self._buf[consumed:] return done def finish(self) -> list[str]: rest = self._buf.strip() self._buf = "" return [rest] if rest else []