fix(tts): 清理 Markdown 斜体时保留标识符和乘号

成对的 _ 和 * 会把 get_current_time 读成 getcurrenttime,把 2*3*4 读成 234。斜体只去掉单词边界上的标记。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ting Zhang 2026-11-10 08:22:36 +08:00
parent 4b1a54a41c
commit 6c1d789cdf
2 changed files with 29 additions and 1 deletions

View file

@ -108,7 +108,10 @@ class MarkdownCleaner:
(re.compile(r'```.*?```', re.DOTALL), ''), # 代码块
(re.compile(r'^#+\s*', re.MULTILINE), ''), # 标题
(re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # 粗体
(re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\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'!\[.*?\]\(.*?\)'), ''), # 图片
(re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # 链接
(re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # 引用

View file

@ -0,0 +1,25 @@
"""MarkdownCleaner must drop real emphasis without eating identifiers or products."""
from core.utils.tts import MarkdownCleaner
def test_snake_case_is_not_read_as_italic():
assert (
MarkdownCleaner.clean_markdown("请调用 get_current_time 函数")
== "请调用 get_current_time 函数"
)
assert MarkdownCleaner.clean_markdown("a_b_c 结束") == "a_b_c 结束"
def test_multiplication_is_not_read_as_italic():
assert MarkdownCleaner.clean_markdown("结果是 2*3*4 等于 24") == "结果是 2*3*4 等于 24"
def test_numeric_underscores_are_still_removed():
# 数字里的下划线不是标识符,读出来应是连续数字
assert MarkdownCleaner.clean_markdown("价格是 1_000_000 元") == "价格是 1000000 元"
def test_emphasis_markers_are_still_removed():
assert MarkdownCleaner.clean_markdown("这是 *重点* 内容") == "这是 重点 内容"
assert MarkdownCleaner.clean_markdown("这是 **加粗** 内容") == "这是 加粗 内容"
assert MarkdownCleaner.clean_markdown("use _emphasis_ here") == "use emphasis here"