mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-26 04:39:53 +01:00
Markdown 清理保留标识符与乘号,剥离残留标记
分句点取最早的合法句末
This commit is contained in:
parent
5c3e1d8a30
commit
ccccc64dd7
4 changed files with 185 additions and 43 deletions
|
|
@ -569,7 +569,6 @@ class TTSProviderBase(ABC):
|
|||
# 合并当前全部文本并处理未分割部分
|
||||
full_text = "".join(self.tts_text_buff)
|
||||
current_text = full_text[self.processed_chars :] # 从未处理的位置开始
|
||||
last_punct_pos = -1
|
||||
|
||||
# 根据是否是第一句话选择不同的标点符号集合
|
||||
punctuations_to_use = (
|
||||
|
|
@ -578,19 +577,19 @@ class TTSProviderBase(ABC):
|
|||
else self.punctuations
|
||||
)
|
||||
|
||||
# 取每种标点最后出现位置的最早者作为切分点(与逐个 rfind 再取最小值等价)
|
||||
last_seen = {}
|
||||
# 取最早的合法句末作为切分点
|
||||
first_punct_pos = -1
|
||||
for i, ch in enumerate(current_text):
|
||||
if ch in punctuations_to_use and not self._is_numeric_separator(
|
||||
current_text, i
|
||||
):
|
||||
last_seen[ch] = i
|
||||
last_punct_pos = min(last_seen.values(), default=-1)
|
||||
first_punct_pos = i
|
||||
break
|
||||
|
||||
cut_pos = -1
|
||||
if last_punct_pos != -1:
|
||||
if first_punct_pos != -1:
|
||||
cut_pos = self._quote_safe_cut(
|
||||
current_text, last_punct_pos, punctuations_to_use
|
||||
current_text, first_punct_pos, punctuations_to_use
|
||||
)
|
||||
if cut_pos != -1:
|
||||
segment_text_raw = current_text[: cut_pos + 1]
|
||||
|
|
|
|||
|
|
@ -102,28 +102,66 @@ class MarkdownCleaner:
|
|||
|
||||
return "\n".join(lines_for_tts) + "\n"
|
||||
|
||||
@staticmethod
|
||||
def _replace_emphasis(m: re.Match) -> str:
|
||||
"""* 斜体:内容是 ASCII 词字符/数字/运算符且左侧紧贴 ASCII 词字符时保留标记。
|
||||
|
||||
内容判定区分乘法与强调,左侧判定区分词内与独立强调。
|
||||
"""
|
||||
before = m.string[m.start() - 1] if m.start() > 0 else ""
|
||||
if not (before.isascii() and before.isalnum()):
|
||||
return m.group(m.re.groups)
|
||||
if not re.fullmatch(r"[A-Za-z0-9_+\-*/().\s]+", m.group(1)):
|
||||
return m.group(m.re.groups)
|
||||
return m.group(0)
|
||||
|
||||
@staticmethod
|
||||
def _replace_underscore(m: re.Match) -> str:
|
||||
"""_ 斜体:词内不生效(CommonMark),任一侧紧贴 ASCII 词字符即保留标记。"""
|
||||
before = m.string[m.start() - 1] if m.start() > 0 else ""
|
||||
after = m.string[m.end()] if m.end() < len(m.string) else ""
|
||||
before_word = before.isascii() and before.isalnum()
|
||||
after_word = after.isascii() and after.isalnum()
|
||||
if before_word or after_word:
|
||||
return m.group(0)
|
||||
return m.group(m.re.groups)
|
||||
|
||||
@staticmethod
|
||||
def _replace_lone_marker(m: re.Match) -> str:
|
||||
"""落单的 ** :左侧是词字符或参数列表分隔符时保留(幂运算/解包),否则剥掉。"""
|
||||
before = m.string[m.start() - 1] if m.start() > 0 else ""
|
||||
if before and (before.isascii() and before.isalnum() or before in "(,"):
|
||||
return m.group(0)
|
||||
return ""
|
||||
|
||||
# 预编译所有正则表达式(按执行频率排序)
|
||||
# 这里要把 replace_xxx 的静态方法放在最前定义,以便在列表里能正确引用它们。
|
||||
# replace_xxx 的静态方法必须定义在此列表之前,列表里统一取 __func__
|
||||
REGEXES = [
|
||||
(re.compile(r'```.*?```', re.DOTALL), ''), # 代码块
|
||||
(re.compile(r'^#+\s*', re.MULTILINE), ''), # 标题
|
||||
(re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # 粗体
|
||||
# 斜体只认成对的分隔符,且不能从字母或数字中间切开。
|
||||
# 否则 get_current_time 会被当成 _current_,2*3*4 会被当成 *3*。
|
||||
(re.compile(r'(?<![A-Za-z0-9])\*(?=\S)(.*?)(?<=\S)\*(?![A-Za-z0-9])'), r'\1'),
|
||||
(re.compile(r'(?<![A-Za-z_])_(?=\S)(.*?)(?<=\S)_(?![A-Za-z_])'), r'\1'),
|
||||
# 粗体
|
||||
(re.compile(r'\*\*(?=\S)(.+?)(?<=\S)\*\*'), r'\1'),
|
||||
(re.compile(r'__(?=\S)(.+?)(?<=\S)__'), r'\1'),
|
||||
# 千分位分组符(1_000_000 -> 1000000),整段数字须独立于标识符
|
||||
(re.compile(r'(?<![A-Za-z_])\d+(?:_\d{3})+(?![\dA-Za-z_])'), lambda m: m.group(0).replace("_", "")),
|
||||
# 斜体 * 和 _,内容允许内部空白
|
||||
(re.compile(r'(?<!\*)\*(?!\*)(?=\S)((?:[^*\s]|[ \t])+?)(?<=\S)\*'), _replace_emphasis.__func__),
|
||||
(re.compile(r'(?<!_)_(?!_)(?=\S)((?:[^_\s]|[ \t])+?)(?<=\S)_'), _replace_underscore.__func__),
|
||||
(re.compile(r'!\[.*?\]\(.*?\)'), ''), # 图片
|
||||
(re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # 链接
|
||||
(re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # 引用
|
||||
(
|
||||
re.compile(r'(?P<table_block>(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE),
|
||||
_replace_table_block
|
||||
_replace_table_block.__func__
|
||||
),
|
||||
(re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # 列表
|
||||
# 列表,排除 ** 形态
|
||||
(re.compile(r'^\s*(?!\*\*)[*+-]\s*', re.MULTILINE), '- '),
|
||||
# 落单的 **
|
||||
(re.compile(r'\*\*'), _replace_lone_marker.__func__),
|
||||
(re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # 块级公式
|
||||
(
|
||||
re.compile(r'(?<![A-Za-z0-9])\$([^\n$]+)\$(?![A-Za-z0-9])'),
|
||||
_replace_inline_dollar
|
||||
_replace_inline_dollar.__func__
|
||||
),
|
||||
(re.compile(r'\n{2,}'), '\n'), # 多余空行
|
||||
]
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
import pytest
|
||||
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
from core.utils import textUtils
|
||||
|
||||
|
||||
# 最小 stub:仅需满足抽象方法实例化要求;object.__new__ 会绕过
|
||||
|
|
@ -12,6 +13,11 @@ class _TTS(TTSProviderBase):
|
|||
|
||||
|
||||
def _segments(text, step, first_sentence=False):
|
||||
"""按 step 切片喂入,返回切出的各段。
|
||||
|
||||
与真实调用保持一致:每来一个 chunk 调用一次 _get_segment_text(切出一段),
|
||||
结束时剩余文本由 _process_remaining_text_stream 一次性发出。
|
||||
"""
|
||||
tts = object.__new__(_TTS)
|
||||
tts.punctuations = ("。", "?", "?", "!", "!", ";", ";", ":")
|
||||
tts.first_sentence_punctuations = (",", "~", "、", ",") + tts.punctuations
|
||||
|
|
@ -23,10 +29,13 @@ def _segments(text, step, first_sentence=False):
|
|||
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)
|
||||
# 剩余文本一次性发出,不再切分
|
||||
full_text = "".join(tts.tts_text_buff)
|
||||
remaining = full_text[tts.processed_chars:]
|
||||
if remaining:
|
||||
rest = textUtils.get_string_no_punctuation_or_emoji(remaining)
|
||||
if rest:
|
||||
out.append(rest)
|
||||
return out
|
||||
|
||||
|
||||
|
|
@ -58,8 +67,8 @@ def test_text_without_quotes_is_split_as_before(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!"']
|
||||
# 等待引号闭合,整句一次输出;flush 段尾部标点会被剥掉
|
||||
assert _segments('She said, "Hi!"', step) == ['She said, "Hi']
|
||||
|
||||
|
||||
_LQ, _RQ = "\u00ab", "\u00bb" # « » 法/俄语书名号式引号
|
||||
|
|
@ -70,7 +79,7 @@ _GOPEN, _GCLOSE = "\u201e", "\u201c" # „ “ 德语低引号
|
|||
def test_guillemets_are_not_split(step):
|
||||
# ! 位于 «» 内,须等右书名号闭合后在句尾标点处切分
|
||||
text = "Il a dit " + _LQ + "Bonjour ! " + _RQ + " puis est parti."
|
||||
assert _segments(text, step) == [text]
|
||||
assert _segments(text, step) == [text[:-1]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", [1, 4])
|
||||
|
|
@ -79,16 +88,16 @@ def test_german_low9_quotes_stay_whole(step):
|
|||
# 故 „…“ 闭合后依然判不平衡,无论后续有无句末标点(实测),
|
||||
# 德语只能整句 stop flush —— 这是字符冲突下的保守预期,非缺陷
|
||||
text = "Er sagte " + _GOPEN + "Hallo!" + _GCLOSE + " und ging."
|
||||
assert _segments(text, step) == [text]
|
||||
assert _segments(text, step) == [text[:-1]]
|
||||
# 闭合 + 中文句号同样整句 flush:正路径因 “ 双重语义不可达
|
||||
text2 = "Er sagte " + _GOPEN + "Hallo!" + _GCLOSE + "。Dann geht er。"
|
||||
assert _segments(text2, step) == [text2]
|
||||
assert _segments(text2, step) == [text2[:-1]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", [1, 4])
|
||||
def test_unterminated_quote_flushes_on_stop(step):
|
||||
# 单个引号符号(未闭合)不卡死:流式期间等待,stop 时整段 flush
|
||||
assert _segments('"Hi', step) == ['"Hi']
|
||||
# 单个引号符号(未闭合)不卡死;行首的 " 属于标点,flush 时会被剥掉
|
||||
assert _segments('"Hi', step) == ["Hi"]
|
||||
assert _segments("「わぁ", step) == ["「わぁ"]
|
||||
|
||||
|
||||
|
|
@ -111,16 +120,15 @@ def test_nested_mixed_quotes_stay_whole():
|
|||
|
||||
|
||||
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."]
|
||||
# 单引号有撇号歧义(don't),不得纳入平衡检查;flush 段尾部标点会被剥掉
|
||||
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] == "そっか"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", [1, 4])
|
||||
@pytest.mark.parametrize("step", range(1, 14))
|
||||
def test_thousands_separator_is_not_a_first_sentence_break(step):
|
||||
# 第一句会在逗号处切,但 1,280 / 1,280 里的逗号是数字的一部分
|
||||
assert _segments("一共1,280元,请查收。", step, first_sentence=True) == [
|
||||
|
|
@ -133,18 +141,37 @@ def test_thousands_separator_is_not_a_first_sentence_break(step):
|
|||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", [1, 3])
|
||||
@pytest.mark.parametrize("step", range(1, 14))
|
||||
def test_fullwidth_time_colon_stays_with_the_minutes(step):
|
||||
# : 在默认断句集里;15:30 不能切成「现在是15」和「30」
|
||||
expected = ["现在是15:30", "请出门"]
|
||||
assert _segments("现在是15:30。请出门。", step) == expected
|
||||
assert _segments("现在是15:30。请出门。", step, first_sentence=True) == expected
|
||||
assert _segments("现在是15:30。请出门。", step) == ["现在是15:30", "请出门"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", [1, 3])
|
||||
@pytest.mark.parametrize("step", range(1, 12))
|
||||
def test_fullwidth_colon_after_numeric_label_still_breaks(step):
|
||||
assert _segments("提示1:请出门。现在走。", step) == [
|
||||
"提示1",
|
||||
"请出门",
|
||||
"现在走",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", range(1, 27))
|
||||
def test_every_sentence_end_splits(step):
|
||||
# 切分点取最早的合法句末,任意分片粒度下都按句子边界切
|
||||
text = "第一句话讲完了。第二句话也讲完了。第三句话是最后一句。"
|
||||
assert _segments(text, step) == [
|
||||
"第一句话讲完了",
|
||||
"第二句话也讲完了",
|
||||
"第三句话是最后一句",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", range(1, 7))
|
||||
def test_colon_and_period_both_split(step):
|
||||
assert _segments("他说:好的。现在走。马上到。", step) == [
|
||||
"他说",
|
||||
"好的",
|
||||
"现在走",
|
||||
"马上到",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -2,24 +2,102 @@
|
|||
from core.utils.tts import MarkdownCleaner
|
||||
|
||||
|
||||
def test_snake_case_is_not_read_as_italic():
|
||||
def test_identifiers_keep_their_underscores():
|
||||
assert (
|
||||
MarkdownCleaner.clean_markdown("请调用 get_current_time 函数")
|
||||
== "请调用 get_current_time 函数"
|
||||
)
|
||||
assert MarkdownCleaner.clean_markdown("a_b_c 结束") == "a_b_c 结束"
|
||||
assert MarkdownCleaner.clean_markdown("a_1_b_2") == "a_1_b_2"
|
||||
assert MarkdownCleaner.clean_markdown("step_2_of_3") == "step_2_of_3"
|
||||
assert MarkdownCleaner.clean_markdown("use _em_text here") == "use _em_text here"
|
||||
|
||||
|
||||
def test_multiplication_is_not_read_as_italic():
|
||||
def test_multiplication_keeps_its_asterisks():
|
||||
assert MarkdownCleaner.clean_markdown("结果是 2*3*4 等于 24") == "结果是 2*3*4 等于 24"
|
||||
assert MarkdownCleaner.clean_markdown("a*b*c") == "a*b*c"
|
||||
assert MarkdownCleaner.clean_markdown("计算 2*3*(4+5)") == "计算 2*3*(4+5)"
|
||||
assert MarkdownCleaner.clean_markdown("计算 2*3*-4") == "计算 2*3*-4"
|
||||
assert MarkdownCleaner.clean_markdown("2*3* + 4") == "2*3* + 4"
|
||||
assert MarkdownCleaner.clean_markdown("共2*3*4元") == "共2*3*4元"
|
||||
assert MarkdownCleaner.clean_markdown("2*3*4米") == "2*3*4米"
|
||||
assert MarkdownCleaner.clean_markdown("2*3*元") == "2*3*元"
|
||||
assert MarkdownCleaner.clean_markdown("2*3*米") == "2*3*米"
|
||||
assert MarkdownCleaner.clean_markdown("3*4*(5)") == "3*4*(5)"
|
||||
assert MarkdownCleaner.clean_markdown("2*3*,") == "2*3*,"
|
||||
assert MarkdownCleaner.clean_markdown("2*3*。") == "2*3*。"
|
||||
assert MarkdownCleaner.clean_markdown("a*b*,然后") == "a*b*,然后"
|
||||
|
||||
|
||||
def test_numeric_underscores_are_still_removed():
|
||||
# 数字里的下划线不是标识符,读出来应是连续数字
|
||||
assert MarkdownCleaner.clean_markdown("价格是 1_000_000 元") == "价格是 1000000 元"
|
||||
def test_exponentiation_keeps_its_double_asterisks():
|
||||
assert MarkdownCleaner.clean_markdown("计算 2**3 的值") == "计算 2**3 的值"
|
||||
assert MarkdownCleaner.clean_markdown("价格 2**10 元") == "价格 2**10 元"
|
||||
assert MarkdownCleaner.clean_markdown("2**8") == "2**8"
|
||||
assert MarkdownCleaner.clean_markdown("计算 2**(3) 的值") == "计算 2**(3) 的值"
|
||||
assert MarkdownCleaner.clean_markdown("2**-3") == "2**-3"
|
||||
assert MarkdownCleaner.clean_markdown("10**-3") == "10**-3"
|
||||
assert MarkdownCleaner.clean_markdown("a**(b)") == "a**(b)"
|
||||
assert MarkdownCleaner.clean_markdown("2**[3]") == "2**[3]"
|
||||
assert MarkdownCleaner.clean_markdown("func(**kwargs)") == "func(**kwargs)"
|
||||
|
||||
|
||||
def test_emphasis_markers_are_still_removed():
|
||||
def test_emphasis_markers_are_removed():
|
||||
assert MarkdownCleaner.clean_markdown("这是 *重点* 内容") == "这是 重点 内容"
|
||||
assert MarkdownCleaner.clean_markdown("这是 **加粗** 内容") == "这是 加粗 内容"
|
||||
assert MarkdownCleaner.clean_markdown("use _emphasis_ here") == "use emphasis here"
|
||||
assert MarkdownCleaner.clean_markdown("这是 *重要 内容* 哦") == "这是 重要 内容 哦"
|
||||
assert MarkdownCleaner.clean_markdown("use *long phrase* here") == "use long phrase here"
|
||||
|
||||
|
||||
def test_emphasis_hugging_a_word_is_removed():
|
||||
assert MarkdownCleaner.clean_markdown("see *note*below") == "see notebelow"
|
||||
assert MarkdownCleaner.clean_markdown("这是*重点*1") == "这是重点1"
|
||||
assert MarkdownCleaner.clean_markdown("TTS*强调*") == "TTS强调"
|
||||
assert MarkdownCleaner.clean_markdown("a*重点*中文") == "a重点中文"
|
||||
|
||||
|
||||
def test_bold_markers_are_always_removed():
|
||||
# __ 与 ** 一律按强强调剥掉
|
||||
assert MarkdownCleaner.clean_markdown("a__b__c") == "abc"
|
||||
assert MarkdownCleaner.clean_markdown("a**b**c") == "abc"
|
||||
assert MarkdownCleaner.clean_markdown("调用 __init__ 方法") == "调用 init 方法"
|
||||
|
||||
|
||||
def test_lone_markers_are_stripped_and_do_not_become_fake_bullets():
|
||||
assert MarkdownCleaner.clean_markdown("**未闭合") == "未闭合"
|
||||
assert MarkdownCleaner.clean_markdown("**bold") == "bold"
|
||||
assert MarkdownCleaner.clean_markdown("**a *b* c") == "a b c"
|
||||
assert MarkdownCleaner.clean_markdown("*bold*text") == "boldtext"
|
||||
|
||||
|
||||
def test_list_bullets_are_kept():
|
||||
assert MarkdownCleaner.clean_markdown("* 第一项\n* 第二项") == "- 第一项- 第二项"
|
||||
assert MarkdownCleaner.clean_markdown("+ 第一项") == "- 第一项"
|
||||
|
||||
|
||||
def test_asterisk_inside_chinese_text_is_kept():
|
||||
assert MarkdownCleaner.clean_markdown("请按*键") == "请按*键"
|
||||
assert MarkdownCleaner.clean_markdown("中文*中文") == "中文*中文"
|
||||
|
||||
|
||||
def test_thousands_separators_are_folded():
|
||||
assert MarkdownCleaner.clean_markdown("价格是 1_000_000 元") == "价格是 1000000 元"
|
||||
assert MarkdownCleaner.clean_markdown("价格是 1_000_000_000 元") == "价格是 1000000000 元"
|
||||
assert (
|
||||
MarkdownCleaner.clean_markdown("价格 1_000 元 和 2_000_000 元")
|
||||
== "价格 1000 元 和 2000000 元"
|
||||
)
|
||||
assert MarkdownCleaner.clean_markdown("12_000") == "12000"
|
||||
|
||||
|
||||
def test_numbers_outside_thousands_groups_are_kept():
|
||||
# 分组必须是完整的 3 位
|
||||
assert MarkdownCleaner.clean_markdown("Python 3_10") == "Python 3_10"
|
||||
assert MarkdownCleaner.clean_markdown("版本 v2_0 beta") == "版本 v2_0 beta"
|
||||
assert MarkdownCleaner.clean_markdown("1_2_3") == "1_2_3"
|
||||
assert MarkdownCleaner.clean_markdown("甲1_0000乙") == "甲1_0000乙"
|
||||
assert MarkdownCleaner.clean_markdown("甲1_000_0000乙") == "甲1_000_0000乙"
|
||||
assert MarkdownCleaner.clean_markdown("1_000_00") == "1_000_00"
|
||||
# 千分位折叠要求整段数字独立于标识符
|
||||
assert MarkdownCleaner.clean_markdown("sensor_2_001") == "sensor_2_001"
|
||||
assert MarkdownCleaner.clean_markdown("v1_000") == "v1_000"
|
||||
assert MarkdownCleaner.clean_markdown("price_1_000") == "price_1_000"
|
||||
|
|
|
|||
Loading…
Reference in a new issue