From 70ab19d23fcdd7c676a0fdcbb88b2caa89546940 Mon Sep 17 00:00:00 2001 From: korexil <289361616+korexil@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:26:40 +0900 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20TTS=20=E5=88=86=E5=8F=A5=E5=9C=A8?= =?UTF-8?q?=E5=BC=95=E5=8F=B7=E5=86=85=E5=88=87=E5=BC=80=E5=8F=A5=E5=AD=90?= =?UTF-8?q?=20(#3413)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _get_segment_text 会在引号内的标点处切分(如「わぁ!」って、“好!”然后), 把引号拆到两段里,或留下只有「。」的片段。新增 _quote_safe_cut:切分点后的 右引号与句末标点一并带走;位于未闭合引号内或右引号后句子仍在继续时,顺延到 下一个标点。不含引号的文本切分结果不变。 --- .../xiaozhi-server/core/providers/tts/base.py | 35 +++++++++++ .../tests/core/providers/__init__.py | 0 .../tests/core/providers/tts/__init__.py | 0 .../providers/tts/test_quote_safe_segment.py | 58 +++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 main/xiaozhi-server/tests/core/providers/__init__.py create mode 100644 main/xiaozhi-server/tests/core/providers/tts/__init__.py create mode 100644 main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 2ff779c03..7c2feb4ff 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -483,6 +483,37 @@ class TTSProviderBase(ABC): if hasattr(self, "ws") and self.ws: await self.ws.close() + # 右引号/右括号,以及它们对应的左侧符号 + _QUOTE_PAIRS = (("「", "」"), ("『", "』"), ("“", "”"), ("(", ")"), ("《", "》")) + _CLOSERS = "」』”)》" + + @classmethod + def _quote_safe_cut(cls, text, pos, punctuations): + """避免在引号内切分(如 「わぁ!」って / “好!”他说)。 + + 候选位置之后紧跟的右引号和句末标点一并带走;若候选位于未闭合的引号内, + 或右引号后句子还在继续,则顺延到下一个标点;都不安全时返回 -1,等待更多文本。 + """ + 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 + ): + carried_closer = carried_closer or text[end] in cls._CLOSERS + end += 1 + segment = text[:end] + if any(segment.count(o) > segment.count(c) for o, c in cls._QUOTE_PAIRS): + continue + if carried_closer and (end == len(text) or not text[end].isspace()): + # 右引号之后句子还在继续(「…」って、“…”他说),或暂时看不到后文 + continue + return end - 1 + return -1 + def _get_segment_text(self): # 合并当前全部文本并处理未分割部分 full_text = "".join(self.tts_text_buff) @@ -503,6 +534,10 @@ class TTSProviderBase(ABC): ): last_punct_pos = pos + if last_punct_pos != -1: + last_punct_pos = self._quote_safe_cut( + current_text, last_punct_pos, punctuations_to_use + ) if last_punct_pos != -1: segment_text_raw = current_text[: last_punct_pos + 1] segment_text = textUtils.get_string_no_punctuation_or_emoji( diff --git a/main/xiaozhi-server/tests/core/providers/__init__.py b/main/xiaozhi-server/tests/core/providers/__init__.py new file mode 100644 index 000000000..e69de29bb 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..0e6927e7c --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py @@ -0,0 +1,58 @@ +"""TTSProviderBase._get_segment_text must not cut sentences inside quotes.""" +import pytest + +from core.providers.tts.base import TTSProviderBase + + +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) == ["普通の文", "次の文", "最後"] + + +def test_first_sentence_still_splits_at_comma(): + assert _segments("そっか、実習で疲れたんだね。", 1, first_sentence=True)[0] == "そっか" From a5e47f2c4e74a1d612d7e09fd5d61766f2f399c0 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Tue, 13 Oct 2026 15:29:28 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E8=A1=A5=E5=85=85=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=EF=BC=8C=E8=B0=83=E6=95=B4=E5=AD=97=E7=AC=A6=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xiaozhi-server/core/providers/tts/base.py | 63 ++++++++++++++----- .../providers/tts/test_quote_safe_segment.py | 55 ++++++++++++++++ 2 files changed, 101 insertions(+), 17 deletions(-) diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 7c2feb4ff..e309922a9 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 @@ -484,16 +483,33 @@ class TTSProviderBase(ABC): await self.ws.close() # 右引号/右括号,以及它们对应的左侧符号 - _QUOTE_PAIRS = (("「", "」"), ("『", "』"), ("“", "”"), ("(", ")"), ("《", "》")) - _CLOSERS = "」』”)》" + _QUOTE_PAIRS = ( + ("「", "」"), + ("『", "』"), + ("“", "”"), + ('"', '"'), + ("(", ")"), + ("《", "》"), + ("«", "»"), + ("„", "“"), + ("【", "】"), + ("〈", "〉"), + ("[", "]"), + ("[", "]"), + ) + _CLOSERS = '」』”》)"»“】〉]]' + _QUOTE_CHARS = "".join(ch for pair in _QUOTE_PAIRS for ch in pair) @classmethod - def _quote_safe_cut(cls, text, pos, punctuations): + 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 ] @@ -503,10 +519,22 @@ class TTSProviderBase(ABC): while end < len(text) and ( text[end] in cls._CLOSERS or text[end] in punctuations ): - carried_closer = carried_closer or text[end] in cls._CLOSERS + if text[end] in cls._CLOSERS: + carried_closer = True end += 1 segment = text[:end] - if any(segment.count(o) > segment.count(c) for o, c in cls._QUOTE_PAIRS): + # 前后配对的引号(「」等)用计数差检测;前后同符的引号(")用奇偶检测 + 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()): # 右引号之后句子还在继续(「…」って、“…”他说),或暂时看不到后文 @@ -514,7 +542,7 @@ class TTSProviderBase(ABC): return end - 1 return -1 - def _get_segment_text(self): + def _get_segment_text(self) -> Optional[str]: # 合并当前全部文本并处理未分割部分 full_text = "".join(self.tts_text_buff) current_text = full_text[self.processed_chars :] # 从未处理的位置开始 @@ -527,19 +555,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: - last_punct_pos = self._quote_safe_cut( + cut_pos = self._quote_safe_cut( current_text, last_punct_pos, punctuations_to_use ) - if last_punct_pos != -1: - segment_text_raw = current_text[: last_punct_pos + 1] + 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/test_quote_safe_segment.py b/main/xiaozhi-server/tests/core/providers/tts/test_quote_safe_segment.py index 0e6927e7c..35059f350 100644 --- 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 @@ -54,5 +54,60 @@ 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): + # „…“ 的闭合符 “ 是中文引号的开引号,整句在 stop flush 时输出 + text = "Er sagte " + _GOPEN + "Hallo!" + _GCLOSE + " und ging." + assert _segments(text, step) == [text] + + +@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] == "そっか" From 932962e8d3bac067d6b6409c08a7fa989ad1ff6a Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Wed, 14 Oct 2026 10:10:28 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=EF=BC=8C=E8=B0=83=E6=95=B4=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E6=A0=B7=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/core/providers/tts/base.py | 3 +++ .../tests/core/providers/tts/test_quote_safe_segment.py | 9 ++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index e309922a9..34b20a626 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -497,6 +497,9 @@ class TTSProviderBase(ABC): ("[", "]"), ("[", "]"), ) + # 注意:“(U+201C)有双重语义:中文里是开引号(对应 ”), + # 德语 „…“ 里是闭引号;二者冲突时计数法无法兼顾, + # 德语句子的切分只能靠“不平衡就顺延”保守处理(最终由 flush 兜底)。 _CLOSERS = '」』”》)"»“】〉]]' _QUOTE_CHARS = "".join(ch for pair in _QUOTE_PAIRS for ch in pair) 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 index 35059f350..e34348222 100644 --- 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 @@ -4,6 +4,8 @@ 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 @@ -73,9 +75,14 @@ def test_guillemets_are_not_split(step): @pytest.mark.parametrize("step", [1, 4]) def test_german_low9_quotes_stay_whole(step): - # „…“ 的闭合符 “ 是中文引号的开引号,整句在 stop flush 时输出 + # „…“ 的闭合符 “ 是中文引号的开引号:“ 总被 (“”, ””) 对计为 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])