diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 2ff779c03..34b20a626 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -6,12 +6,11 @@ import queue import asyncio import threading import traceback -import concurrent.futures from core.utils import p3 from datetime import datetime from core.utils import textUtils -from typing import Callable, Any +from typing import Callable, Any, Optional from abc import ABC, abstractmethod from config.logger import setup_logging from core.utils import opus_encoder_utils @@ -483,7 +482,70 @@ class TTSProviderBase(ABC): if hasattr(self, "ws") and self.ws: await self.ws.close() - def _get_segment_text(self): + # 右引号/右括号,以及它们对应的左侧符号 + _QUOTE_PAIRS = ( + ("「", "」"), + ("『", "』"), + ("“", "”"), + ('"', '"'), + ("(", ")"), + ("《", "》"), + ("«", "»"), + ("„", "“"), + ("【", "】"), + ("〈", "〉"), + ("[", "]"), + ("[", "]"), + ) + # 注意:“(U+201C)有双重语义:中文里是开引号(对应 ”), + # 德语 „…“ 里是闭引号;二者冲突时计数法无法兼顾, + # 德语句子的切分只能靠“不平衡就顺延”保守处理(最终由 flush 兜底)。 + _CLOSERS = '」』”》)"»“】〉]]' + _QUOTE_CHARS = "".join(ch for pair in _QUOTE_PAIRS for ch in pair) + + @classmethod + def _quote_safe_cut(cls, text: str, pos: int, punctuations) -> int: + """避免在引号内切分(如 「わぁ!」って / “好!”他说)。 + + 候选位置之后紧跟的右引号和句末标点一并带走;若候选位于未闭合的引号内, + 或右引号后句子还在继续,则顺延到下一个标点;都不安全时返回 -1,等待更多文本。 + """ + if not any(ch in cls._QUOTE_CHARS for ch in text): + # 全文不含引号/括号:不存在未闭合引号,右引号也无需携带,候选位置必然安全 + return pos + candidates = [pos] + [ + i for i, ch in enumerate(text) if i > pos and ch in punctuations + ] + for candidate in candidates: + end = candidate + 1 + carried_closer = False + while end < len(text) and ( + text[end] in cls._CLOSERS or text[end] in punctuations + ): + if text[end] in cls._CLOSERS: + carried_closer = True + end += 1 + segment = text[:end] + # 前后配对的引号(「」等)用计数差检测;前后同符的引号(")用奇偶检测 + balanced = True + for opener, closer in cls._QUOTE_PAIRS: + n_open = segment.count(opener) + if opener == closer: + if n_open % 2: + balanced = False + break + elif n_open > segment.count(closer): + balanced = False + break + if not balanced: + continue + if carried_closer and (end == len(text) or not text[end].isspace()): + # 右引号之后句子还在继续(「…」って、“…”他说),或暂时看不到后文 + continue + return end - 1 + return -1 + + def _get_segment_text(self) -> Optional[str]: # 合并当前全部文本并处理未分割部分 full_text = "".join(self.tts_text_buff) current_text = full_text[self.processed_chars :] # 从未处理的位置开始 @@ -496,15 +558,20 @@ class TTSProviderBase(ABC): else self.punctuations ) - for punct in punctuations_to_use: - pos = current_text.rfind(punct) - if (pos != -1 and last_punct_pos == -1) or ( - pos != -1 and pos < last_punct_pos - ): - last_punct_pos = pos + # 取每种标点最后出现位置的最早者作为切分点(与逐个 rfind 再取最小值等价) + last_seen = {} + for i, ch in enumerate(current_text): + if ch in punctuations_to_use: + last_seen[ch] = i + last_punct_pos = min(last_seen.values(), default=-1) + cut_pos = -1 if last_punct_pos != -1: - segment_text_raw = current_text[: last_punct_pos + 1] + cut_pos = self._quote_safe_cut( + current_text, last_punct_pos, punctuations_to_use + ) + if cut_pos != -1: + segment_text_raw = current_text[: cut_pos + 1] segment_text = textUtils.get_string_no_punctuation_or_emoji( segment_text_raw ) diff --git a/main/xiaozhi-server/tests/core/providers/tts/__init__.py b/main/xiaozhi-server/tests/core/providers/tts/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py b/main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py new file mode 100644 index 000000000..e34348222 --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py @@ -0,0 +1,120 @@ +"""TTSProviderBase._get_segment_text must not cut sentences inside quotes.""" +import pytest + +from core.providers.tts.base import TTSProviderBase + + +# 最小 stub:仅需满足抽象方法实例化要求;object.__new__ 会绕过 +# abstractmethod 检查,若基类新增抽象方法这里不会自动报错,属预期(测试不调用) +class _TTS(TTSProviderBase): + async def text_to_speak(self, text, output_file): + return None + + +def _segments(text, step, first_sentence=False): + tts = object.__new__(_TTS) + tts.punctuations = ("。", "?", "?", "!", "!", ";", ";", ":") + tts.first_sentence_punctuations = (",", "~", "、", ",") + tts.punctuations + tts.tts_text_buff, tts.processed_chars = [], 0 + tts.is_first_sentence, tts.tts_stop_request = first_sentence, False + out = [] + for i in range(0, len(text), step): + tts.tts_text_buff.append(text[i:i + step]) + segment = tts._get_segment_text() + if segment: + out.append(segment) + tts.tts_stop_request = True + rest = tts._get_segment_text() + if rest: + out.append(rest) + return out + + +@pytest.mark.parametrize("step", [1, 3, 7]) +def test_japanese_quote_followed_by_tte_stays_whole(step): + assert _segments("思わず「わぁ!」って声が出たんだ。きみは?", step) == [ + "思わず「わぁ!」って声が出たんだ", + "きみは?", + ] + + +@pytest.mark.parametrize("step", [1, 4]) +def test_chinese_quote_followed_by_speaker_stays_whole(step): + segments = _segments("他大声说:“好!”然后笑了。", step) + assert not any(seg.startswith("”") for seg in segments) + # the leading “ is stripped by textUtils, the closing ” must stay with its sentence + assert any("好!”然后笑了" in seg for seg in segments) + + +@pytest.mark.parametrize("step", [1, 5]) +def test_closing_quote_then_period_is_not_left_alone(step): + assert _segments("「すごい!」。次はね、雨!", step) == ["「すごい!」", "次はね、雨"] + + +@pytest.mark.parametrize("step", [1, 5]) +def test_text_without_quotes_is_split_as_before(step): + assert _segments("普通の文。次の文!最後", step) == ["普通の文", "次の文", "最後"] + + +@pytest.mark.parametrize("step", [1, 4]) +def test_ascii_quote_at_stream_end_stays_whole(step): + # 旧逻辑在 ! 处切开,把孤立的 " 留给下一段首;现在等待引号闭合,整句一次输出 + assert _segments('She said, "Hi!"', step) == ['She said, "Hi!"'] + + +_LQ, _RQ = "\u00ab", "\u00bb" # « » 法/俄语书名号式引号 +_GOPEN, _GCLOSE = "\u201e", "\u201c" # „ “ 德语低引号 + + +@pytest.mark.parametrize("step", [1, 4]) +def test_guillemets_are_not_split(step): + # ! 位于 «» 内,须等右书名号闭合后在句尾标点处切分 + text = "Il a dit " + _LQ + "Bonjour ! " + _RQ + " puis est parti." + assert _segments(text, step) == [text] + + +@pytest.mark.parametrize("step", [1, 4]) +def test_german_low9_quotes_stay_whole(step): + # „…“ 的闭合符 “ 是中文引号的开引号:“ 总被 (“”, ””) 对计为 opener, + # 故 „…“ 闭合后依然判不平衡,无论后续有无句末标点(实测), + # 德语只能整句 stop flush —— 这是字符冲突下的保守预期,非缺陷 + text = "Er sagte " + _GOPEN + "Hallo!" + _GCLOSE + " und ging." + assert _segments(text, step) == [text] + # 闭合 + 中文句号同样整句 flush:正路径因 “ 双重语义不可达 + text2 = "Er sagte " + _GOPEN + "Hallo!" + _GCLOSE + "。Dann geht er。" + assert _segments(text2, step) == [text2] + + +@pytest.mark.parametrize("step", [1, 4]) +def test_unterminated_quote_flushes_on_stop(step): + # 单个引号符号(未闭合)不卡死:流式期间等待,stop 时整段 flush + assert _segments('"Hi', step) == ['"Hi'] + assert _segments("「わぁ", step) == ["「わぁ"] + + +_LB, _RB = "\u3010", "\u3011" # 【】 + + +@pytest.mark.parametrize("step", [1, 4]) +def test_brackets_with_punct_inside_are_not_split(step): + # !位于【】内不得切开(切开时第一段只到“他说【重要”), + # 应等右括号闭合后在句尾标点切分 + assert _segments("他说" + _LB + "重要!步骤" + _RB + "。然后走了。", step) == [ + "他说" + _LB + "重要!步骤", + "然后走了", + ] + + +def test_nested_mixed_quotes_stay_whole(): + # 嵌套引号逐对独立计数,互不干扰 + assert _segments("“他说『好』了。”然后离开。", 1) == ["他说『好』了。”然后离开"] + + +def test_apostrophes_do_not_block_splitting(): + # 单引号有撇号歧义(don't),不得纳入平衡检查导致整句延迟 + # 注:flush 段(stop 时剩余文本)原样输出,不做 strip + assert _segments("don't! It's fine.", 1) == ["don't", " It's fine."] + + +def test_first_sentence_still_splits_at_comma(): + assert _segments("そっか、実習で疲れたんだね。", 1, first_sentence=True)[0] == "そっか"