feat(voice): read elementary math aloud in Chinese

This commit is contained in:
windyovo
2026-11-29 20:23:45 +08:00
parent be2fe9104d
commit f9100e979d
5 changed files with 187 additions and 31 deletions

View File

@@ -54,7 +54,9 @@ async def synthesize_speech(
config.response_format = response_format
speak_math = _math_speak_from_settings() if math_speak is None else math_speak
prepared = (
strip_markdown_for_speech(text, max_chars=config.max_input_chars, math_speak=speak_math)
strip_markdown_for_speech(
text, max_chars=config.max_input_chars, math_speak=speak_math, language=config.language
)
if strip_markdown
else text.strip()
)

View File

@@ -192,7 +192,7 @@ _BOLD_UNDERS = re.compile(r"__(.+?)__", re.DOTALL)
_STRIKE = re.compile(r"~~(.+?)~~", re.DOTALL)
_ITALIC_STARS = re.compile(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)", re.DOTALL)
_ITALIC_UNDERS = re.compile(r"(?<!\w)_(?!_)(.+?)(?<!_)_(?!\w)", re.DOTALL)
_HTML_TAG = re.compile(r"<[^>]+>")
_HTML_TAG = re.compile(r"<(?=[!?/a-zA-Z])[^<>]+>")
_TABLE_PIPE = re.compile(r"^\s*\|.*\|\s*$", re.MULTILINE)
_WHITESPACE = re.compile(r"[ \t]+")
_BLANK_LINES = re.compile(r"\n{3,}")
@@ -216,7 +216,9 @@ def _unwrap_emphasis_for_speech(text: str) -> str:
return out
def strip_markdown_for_speech(text: str, *, max_chars: int = 0, math_speak: bool = True) -> str:
def strip_markdown_for_speech(
text: str, *, max_chars: int = 0, math_speak: bool = True, language: str | None = None
) -> str:
"""Reduce Markdown to plain prose suitable for TTS.
Drops code blocks and tables outright (they read terribly), unwraps links
@@ -244,6 +246,7 @@ def strip_markdown_for_speech(text: str, *, max_chars: int = 0, math_speak: bool
out = verbalize_latex_for_speech(
out,
math_speak=math_speak,
language=language,
prose_transform=_unwrap_emphasis_for_speech if not math_speak else None,
)
if math_speak:

View File

@@ -12,8 +12,9 @@ Scope is deliberately Pareto, not a full MathSpeak engine:
* High-frequency algebra is verbalized: fractions, roots, limits, Greek,
relations, trig/log, blackboard number sets.
* Structural TeX (``\\left``, braces, environments) is stripped.
* Function words are English; they are portable across OpenAI-compatible TTS
engines, including Chinese voices that already mix English math terms.
* Elementary arithmetic uses Chinese wording for Chinese TTS language settings
and recognizable Chinese worksheet text in automatic mode.
Other math vocabulary defaults to English.
"""
from __future__ import annotations
@@ -349,6 +350,64 @@ _LOOSE_TEX = re.compile(
)
_WINDOWS_PATH = re.compile(r"(?<![A-Za-z0-9])(?:[A-Za-z]:\\|\\\\)[^\s]*")
_ZH_WORDS = {
"times": "乘",
"divided by": "除以",
"less than or equal to": "小于等于",
"greater than or equal to": "大于等于",
"not equal to": "不等于",
"approximately": "约等于",
"plus or minus": "加或减",
"minus or plus": "减或加",
}
_ZH_OPERATORS = {key: _ZH_WORDS.get(word, word) for key, word in _OPERATORS.items()}
_ZH_SYMBOLS = str.maketrans(
{
"+": "加",
"-": "减",
"−": "减",
"/": "除以",
"*": "乘",
"=": "等于",
"<": "小于",
">": "大于",
"(": "左括号",
")": "右括号",
"(": "左括号",
")": "右括号",
**{
key: _ZH_WORDS[word.strip()]
for key, word in _UNICODE_MATH.items()
if word.strip() in _ZH_WORDS
},
}
)
_ZH_BLANK = re.compile(r"(?<![a-zA-Z0-9_])_+(?![a-zA-Z0-9_{])|□")
_ZH_TEX_BLANK = re.compile(r"\\(?:underline|overline|boxed)\s*\{(?:\s|\\qquad|\\quad)*\}")
_ZH_OPERAND = r"[((]*(?:[0-9]+(?:\.[0-9]+)?|_+|□)[))]*"
_ZH_ARITHMETIC = re.compile(
# Match URLs and dates as a whole before looking for unmarked arithmetic.
r"https?://[^\s]+|(?<![0-9])\d{4}[-/]\d{1,2}[-/]\d{1,2}(?![0-9])|"
rf"(?<![a-zA-Z0-9_./((-])(?P<expression>{_ZH_OPERAND}"
rf"(?:[ \t]*[+−×÷*/=<>≤≥≠≈±xX-][ \t]*{_ZH_OPERAND})+)(?![a-zA-Z0-9_/-]|\.[0-9])"
)
_ZH_WORKSHEET_CUE = re.compile(
r"算一算|填一填|比一比|填空|请计算|請計算|下列算式|算式中|是多少|等于|等於|分之"
)
_KANA_OR_HANGUL = re.compile(r"[\u3040-\u30ff\uff66-\uff9f\uac00-\ud7a3]")
def _chinese_arithmetic(text: str) -> str:
"""Speak numeric expressions in prose without translating variable names or words."""
def speak(match: re.Match[str]) -> str:
if match["expression"] is None:
return match.group()
expr = _ZH_BLANK.sub("空格", match.group())
return expr.replace("x", "乘").replace("X", "乘").translate(_ZH_SYMBOLS)
return _ZH_ARITHMETIC.sub(speak, text)
def _skip_ws(s: str, i: int) -> int:
n = len(s)
@@ -466,7 +525,14 @@ def _replace_blackboard_sets(text: str) -> str:
return re.sub(r"\\mathbb\s*\{([RNZQC])\}", repl, text)
def _replace_frac_once(text: str) -> str:
def _replace_frac_once(text: str, *, chinese: bool = False) -> str:
def speak_operand(source: str) -> str:
spoken = _verbalize_math(source, chinese=chinese)
if chinese and not _SIMPLE_OPERAND.fullmatch(source.strip()):
# Preserve grouping for compound operands and fractions inside fractions.
return f"左括号{spoken}右括号"
return _speak_operand(spoken)
out: list[str] = []
i = 0
n = len(text)
@@ -482,9 +548,9 @@ def _replace_frac_once(text: str) -> str:
den, i = _read_tex_token(text, i)
if num is None or den is None:
continue
num_s = _speak_operand(_verbalize_math(num))
den_s = _speak_operand(_verbalize_math(den))
out.append(f" {num_s} over {den_s} ")
num_s = speak_operand(num)
den_s = speak_operand(den)
out.append(f" {den_s}分之{num_s} " if chinese else f" {num_s} over {den_s} ")
return "".join(out)
@@ -620,7 +686,7 @@ def _speak_sup(inner: str) -> str:
return f" to the {token} "
def _verbalize_scripts(text: str) -> str:
def _verbalize_scripts(text: str, *, chinese: bool = False) -> str:
out: list[str] = []
i = 0
n = len(text)
@@ -634,10 +700,17 @@ def _verbalize_scripts(text: str) -> str:
continue
i = nxt
if kind == "^":
out.append(_speak_sup(token))
if chinese and token.strip() in {"2", "3"}:
out.append(" 的平方 " if token.strip() == "2" else " 的立方 ")
else:
out.append(_speak_sup(token))
else:
spoken = _verbalize_math(token).strip() if "\\" in token else token.strip()
out.append(f" sub {spoken} ")
spoken = (
_verbalize_math(token, chinese=chinese).strip()
if "\\" in token
else token.strip()
)
out.append(f" 下标 {spoken} " if chinese else f" sub {spoken} ")
continue
out.append(ch)
i += 1
@@ -697,39 +770,45 @@ def _drop_braces(text: str) -> str:
_DEGREE_SUPERSCRIPT = re.compile(r"\^\s*(?:\{\s*\\circ\s*\}|\\circ(?![a-zA-Z]))")
def _verbalize_math(text: str) -> str:
def _verbalize_math(text: str, *, chinese: bool = False) -> str:
"""Turn one math island's inner TeX into speakable words."""
if not text:
return ""
out = text.replace("&", " ")
if chinese:
out = _ZH_BLANK.sub("空格", _ZH_TEX_BLANK.sub("空格", out))
out = re.sub(r"\\underline(?![a-zA-Z])", r"\\text", out)
out = out.replace(r"\\", ", ")
out = _DEGREE_SUPERSCRIPT.sub(" degrees ", out)
out = _replace_blackboard_sets(out)
out = _until_stable(_unwrap_style_once, out)
out = _until_stable(_replace_frac_once, out)
out = _until_stable(lambda s: _replace_frac_once(s, chinese=chinese), out)
out = _until_stable(_replace_sqrt_once, out)
out = _until_stable(_replace_binom_once, out)
out = _until_stable(_replace_limits_once, out)
out = _replace_named_commands(out, {**_GREEK, **_OPERATORS, **_FUNCTIONS, **_SPACING_DROP})
out = _verbalize_scripts(out)
operators = _ZH_OPERATORS if chinese else _OPERATORS
out = _replace_named_commands(out, {**_GREEK, **operators, **_FUNCTIONS, **_SPACING_DROP})
out = _verbalize_scripts(out, chinese=chinese)
out = _drop_unknown_commands(out)
out = _drop_braces(out)
if chinese:
out = re.sub(r"(?<=[0-9)])\s*[xX]\s*(?=[0-9(])", "乘", out).translate(_ZH_SYMBOLS)
out = _PAD_PLUS_EQ.sub(r" \1 ", out)
out = _MULTI_SPACE.sub(" ", out)
return out.strip()
def _replace_unicode(text: str) -> str:
def _replace_unicode(text: str, *, chinese: bool = False) -> str:
if not text:
return text
out = text
for src, spoken in _UNICODE_MATH.items():
if src in out:
out = out.replace(src, spoken)
out = out.replace(src, _ZH_WORDS.get(spoken.strip(), spoken) if chinese else spoken)
return out
def _verbalize_loose_commands(text: str) -> str:
def _verbalize_loose_commands(text: str, *, chinese: bool = False) -> str:
"""Convert leftover TeX commands in prose; never touch bare ``_`` / ``^``.
Windows paths are passed through even when nearby prose contains TeX.
@@ -740,13 +819,14 @@ def _verbalize_loose_commands(text: str) -> str:
def speak(segment: str) -> str:
out = _replace_blackboard_sets(segment)
out = _until_stable(_unwrap_style_once, out)
out = _until_stable(_replace_frac_once, out)
out = _until_stable(lambda s: _replace_frac_once(s, chinese=chinese), out)
out = _until_stable(_replace_sqrt_once, out)
out = _until_stable(_replace_binom_once, out)
out = _until_stable(_replace_limits_once, out)
# Unknown commands in prose may be path segments or product names.
# Only an explicit math island is safe to clean up destructively.
return _replace_named_commands(out, {**_GREEK, **_OPERATORS, **_FUNCTIONS, **_SPACING_DROP})
operators = _ZH_OPERATORS if chinese else _OPERATORS
return _replace_named_commands(out, {**_GREEK, **operators, **_FUNCTIONS, **_SPACING_DROP})
parts: list[str] = []
offset = 0
@@ -758,12 +838,12 @@ def _verbalize_loose_commands(text: str) -> str:
return "".join(parts)
def _emit_island(inner: str, *, math_speak: bool) -> str:
return _verbalize_math(inner) if math_speak else inner
def verbalize_latex_for_speech(
text: str, *, math_speak: bool = True, prose_transform: Callable[[str], str] | None = None
text: str,
*,
math_speak: bool = True,
language: str | None = None,
prose_transform: Callable[[str], str] | None = None,
) -> str:
"""Replace math islands with speakable prose, or just unwrap delimiters.
@@ -777,8 +857,19 @@ def verbalize_latex_for_speech(
"""
if not text:
return ""
primary_language = (language or "").strip().lower().replace("_", "-").split("-")[0]
chinese = math_speak and (
primary_language in {"zh", "chinese"}
or (
primary_language in {"", "auto"}
and _ZH_WORKSHEET_CUE.search(text) is not None
and not _KANA_OR_HANGUL.search(text)
)
)
if "$" not in text and "\\" not in text:
spoken = _replace_unicode(text) if math_speak else text
if chinese:
text = _chinese_arithmetic(text)
spoken = _replace_unicode(text, chinese=chinese) if math_speak else text
return prose_transform(spoken) if prose_transform else spoken
out: list[str] = []
@@ -786,12 +877,14 @@ def verbalize_latex_for_speech(
def flush_prose() -> None:
segment = "".join(prose)
if chinese:
segment = _chinese_arithmetic(segment)
out.append(prose_transform(segment) if prose_transform else segment)
prose.clear()
def append_island(inner: str) -> None:
flush_prose()
out.extend((" ", _emit_island(inner, math_speak=math_speak), " "))
out.extend((" ", _verbalize_math(inner, chinese=chinese) if math_speak else inner, " "))
i = 0
n = len(text)
@@ -842,8 +935,8 @@ def verbalize_latex_for_speech(
flush_prose()
spoken = "".join(out)
if math_speak:
spoken = _verbalize_loose_commands(spoken)
spoken = _replace_unicode(spoken)
spoken = _verbalize_loose_commands(spoken, chinese=chinese)
spoken = _replace_unicode(spoken, chinese=chinese)
spoken = _LEFTOVER_DOLLAR.sub("", spoken)
return spoken

View File

@@ -41,6 +41,13 @@ Preserve distinct authentication, region/model, permission, rate-limit, timeout
and audio-download errors without exposing credential-bearing responses.
Retain cancellation and configured timeouts rather than adding unbounded retries.
## Reading elementary math in Chinese
Enable **Math speak** and select Chinese as the TTS model's language to hear
worksheet arithmetic and fractions in Chinese, including “四分之三” for `\frac{3}{4}`.
With the language set to Auto or left unset, a worksheet prompt such as “算一算”
also selects Chinese wording, while a formula alone keeps the default reading.
## Source map
| Responsibility | Implementation |

View File

@@ -861,6 +861,57 @@ async def test_synthesize_speech_facade_strips_markdown(monkeypatch: pytest.Monk
assert "^" not in spoken
@pytest.mark.asyncio
async def test_synthesize_speech_uses_catalog_language_for_math(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured = _capture_post(monkeypatch, httpx.Response(200, content=b"audio"))
catalog = _voice_catalog()
catalog["services"]["tts"]["profiles"][0]["models"][0]["language"] = "Chinese"
await synthesize_speech(r"$\frac{3}{4}$", catalog=catalog, math_speak=True)
assert captured["json"]["input"] == "4分之3"
@pytest.mark.parametrize(
("source", "spoken"),
[
("算一算3x4", "算一算3乘4"),
("6*(3+2)", "6乘左括号3加2右括号"),
("24÷6=4", "24除以6等于4"),
("24/6−2", "24除以6减2"),
("3<4>2", "3小于4大于2"),
("3≥2", "3大于等于2"),
("填空:3 + ____ = 7", "填空:3加空格等于7"),
("□+2=5", "空格加2等于5"),
(r"$3\times4 + \underline{\qquad}=15$", "3乘4加空格等于15"),
(r"$\underline{3+4}$", "3加4"),
(r"算一算:3\times4", "算一算:3乘4"),
(r"比较 $\frac{a}{b}\leq x_i^2$", "比较b分之a小于等于x下标i的平方"),
(r"\frac{3}{4}", "4分之3"),
(r"$\frac{1}{\frac{2}{3}}$", "左括号3分之2右括号分之1"),
("x≤2", "x小于等于2"),
],
)
def test_chinese_elementary_math(source: str, spoken: str) -> None:
assert strip_markdown_for_speech(source, language="zh-Hans").replace(" ", "") == spoken
def test_chinese_math_preserves_prose_and_respects_language_and_toggle() -> None:
prose = (
r"many times, file_name, X轴, x=3, 2026-10-02, https://example.org/?q=3+4 和 C:\times\notes"
)
assert strip_markdown_for_speech(prose, language="zh-CN") == prose
assert strip_markdown_for_speech("<em>算一算</em>3X4", language="zh") == "算一算3乘4"
assert strip_markdown_for_speech("3X4", max_chars=2, language="Chinese") == "3乘"
assert strip_markdown_for_speech("算式 $3×4$", language="zh", math_speak=False) == "算式 3×4"
for language in ("auto", None):
assert strip_markdown_for_speech("算一算:3X4", language=language) == "算一算:3乘4"
assert strip_markdown_for_speech("3×4", language=language) == "3 times 4"
assert strip_markdown_for_speech("算式中の3×4", language=language) == "算式中の3 times 4"
for language in ("en", "ja"):
assert strip_markdown_for_speech("算一算:3×4", language=language) == "算一算:3 times 4"
@pytest.mark.asyncio
async def test_synthesize_speech_math_speak_off_keeps_caret(
monkeypatch: pytest.MonkeyPatch,