DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(voice): verbalize LaTeX in TTS with a Math speak setting
Anthony044c0e7598dd
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 487fa30f4..c9384eb74 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -120,6 +120,9 @@ DEFAULT_UI_SETTINGS = {# preference (not catalog); the chat surface also keeps a per-session# override on top of this global default."voice_autoplay": False,+ # When true, TTS verbalizes LaTeX into spoken math. When false, formulas+ # are unwrapped from $ / $$ only. Default true (matches INTERFACE_DEFAULTS).+ "voice_math_speak": True,# Seconds the chat UI waits for any turn event before declaring the# connection timed out. Bumped from 60 → 180 so slow tools (image/video# generation) don't trip it; user-adjustable in Settings > Network.@@ -175,6 +178,10 @@ class VoiceAutoplayUpdate(BaseModel):voice_autoplay: bool+class VoiceMathSpeakUpdate(BaseModel):+ voice_math_speak: bool++class ChatResponseTimeoutUpdate(BaseModel):chat_response_timeout: int = Field(ge=CHAT_RESPONSE_TIMEOUT_MIN, le=CHAT_RESPONSE_TIMEOUT_MAX)@@ -1893,6 +1900,18 @@ async def update_voice_autoplay(update: VoiceAutoplayUpdate):return {"voice_autoplay": update.voice_autoplay}[email protected]("/voice-math-speak")+async def update_voice_math_speak(update: VoiceMathSpeakUpdate):+ """Persist whether TTS verbalizes LaTeX as spoken math.++ A personal UI preference (any authenticated user). The voice router reads+ this on each synthesis call; chat does not send a per-request override.+ Dollar-sign delimiters are stripped even when this is off.+ """+ patch_ui_settings(voice_math_speak=update.voice_math_speak)+ return {"voice_math_speak": update.voice_math_speak}++@router.put("/chat-response-timeout")async def update_chat_response_timeout(update: ChatResponseTimeoutUpdate):"""Persist how long the chat UI waits for a turn event before timing out.diff --git a/deeptutor/services/settings/interface_settings.py b/deeptutor/services/settings/interface_settings.pyindex 54dc2425f..ddbb4df05 100644--- a/deeptutor/services/settings/interface_settings.py+++ b/deeptutor/services/settings/interface_settings.py@@ -23,6 +23,9 @@ DEFAULT_UI_SETTINGS: dict[str, Any] = {"theme": "snow","language": "en","response_language": "en",+ # When true, TTS verbalizes LaTeX (fractions, powers, Greek). Dollar+ # delimiters are stripped either way so the voice never says "dollar".+ "voice_math_speak": True,}diff --git a/deeptutor/services/voice/__init__.py b/deeptutor/services/voice/__init__.pyindex 9cd8bf673..c7ac7bc10 100644--- a/deeptutor/services/voice/__init__.py+++ b/deeptutor/services/voice/__init__.py@@ -19,6 +19,16 @@ from deeptutor.services.voice.base import (from deeptutor.services.voice.config import STTConfig, TTSConfig+def _math_speak_from_settings() -> bool:+ """Read the Math Speak UI preference; default on if settings are unavailable."""+ try:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ return bool(get_ui_settings().get("voice_math_speak", True))+ except Exception:+ return True++async def synthesize_speech(text: str,*,@@ -26,11 +36,13 @@ async def synthesize_speech(voice: str | None = None,response_format: str | None = None,strip_markdown: bool = True,+ math_speak: bool | None = None,) -> tuple[bytes, str]:"""Synthesize ``text`` using the active TTS catalog selection.Returns ``(audio_bytes, content_type)``. ``voice`` / ``response_format``- override the catalog defaults for this call.+ override the catalog defaults for this call. ``math_speak`` defaults to+ the Settings › Text-to-Speech preference (on)."""from deeptutor.services.config.provider_runtime import resolve_tts_runtime_config@@ -39,8 +51,11 @@ async def synthesize_speech(config.voice = voiceif response_format:config.response_format = response_format+ speak_math = _math_speak_from_settings() if math_speak is None else math_speakprepared = (- strip_markdown_for_speech(text, max_chars=config.max_input_chars)+ strip_markdown_for_speech(+ text, max_chars=config.max_input_chars, math_speak=speak_math+ )if strip_markdownelse text.strip())diff --git a/deeptutor/services/voice/base.py b/deeptutor/services/voice/base.pyindex 1cbfd9f27..7c22eae8f 100644--- a/deeptutor/services/voice/base.py+++ b/deeptutor/services/voice/base.py@@ -13,6 +13,7 @@ from deeptutor.services.voice.config import (STTConfig,TTSConfig,)+from deeptutor.services.voice.speech_text import verbalize_latex_for_speechlogger = logging.getLogger(__name__)@@ -151,12 +152,18 @@ _WHITESPACE = re.compile(r"[ \t]+")_BLANK_LINES = re.compile(r"\n{3,}")-def strip_markdown_for_speech(text: str, *, max_chars: int = 0) -> str:+def strip_markdown_for_speech(+ text: str, *, max_chars: int = 0, math_speak: bool = True+) -> str:"""Reduce Markdown to plain prose suitable for TTS.Drops code blocks and tables outright (they read terribly), unwraps links- and emphasis to their visible text, and removes structural markers. This is+ and emphasis to their visible text, verbalizes LaTeX math so delimiters+ and commands are not read aloud, and removes structural markers. This isdeliberately lossy — the goal is natural speech, not faithful rendering.++ ``math_speak=False`` still strips ``$`` wrappers but leaves inner TeX+ (``\\frac``, ``^2``) for the voice model to handle itself."""if not text:return ""@@ -168,8 +175,12 @@ def strip_markdown_for_speech(text: str, *, max_chars: int = 0) -> str:out = _HEADING.sub("", out)out = _BLOCKQUOTE.sub("", out)out = _LIST_MARKER.sub("", out)- out = _EMPHASIS.sub(r"\2", out)out = _HTML_TAG.sub("", out)+ # Math before emphasis: TeX uses `_` / `*` as scripts and products, and+ # the emphasis regex would otherwise pair a prose underscore with one+ # inside `$x_i$`.+ out = verbalize_latex_for_speech(out, math_speak=math_speak)+ out = _EMPHASIS.sub(r"\2", out)out = _WHITESPACE.sub(" ", out)out = _BLANK_LINES.sub("\n\n", out).strip()if max_chars and len(out) > max_chars:diff --git a/deeptutor/services/voice/speech_text.py b/deeptutor/services/voice/speech_text.pynew file mode 100644index 000000000..baa061d85--- /dev/null+++ b/deeptutor/services/voice/speech_text.py@@ -0,0 +1,807 @@+"""LaTeX/math verbalizer for the TTS pre-layer.++``strip_markdown_for_speech`` already drops Markdown structure. This module+turns the remaining math into words a voice model can read without saying+"dollar", "backslash", "caret", or "underscore".++Scope is deliberately Pareto, not a full MathSpeak engine:++* Only math islands (``$…$``, ``$$…$$``, ``\\(…\\)``, ``\\[…\\]``,+ ``\\begin{equation|align|…}``) get script handling (``^`` / ``_``), so+ snake_case prose is left alone.+* 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.+"""++from __future__ import annotations++import re++# ── lexicons ──────────────────────────────────────────────────────────────++_GREEK = {+ "alpha": "alpha",+ "beta": "beta",+ "gamma": "gamma",+ "delta": "delta",+ "epsilon": "epsilon",+ "varepsilon": "epsilon",+ "zeta": "zeta",+ "eta": "eta",+ "theta": "theta",+ "vartheta": "theta",+ "iota": "iota",+ "kappa": "kappa",+ "lambda": "lambda",+ "mu": "mu",+ "nu": "nu",+ "xi": "xi",+ "pi": "pi",+ "varpi": "pi",+ "rho": "rho",+ "sigma": "sigma",+ "varsigma": "sigma",+ "tau": "tau",+ "upsilon": "upsilon",+ "phi": "phi",+ "varphi": "phi",+ "chi": "chi",+ "psi": "psi",+ "omega": "omega",+ "Alpha": "capital alpha",+ "Beta": "capital beta",+ "Gamma": "capital gamma",+ "Delta": "capital delta",+ "Theta": "capital theta",+ "Lambda": "capital lambda",+ "Xi": "capital xi",+ "Pi": "capital pi",+ "Sigma": "capital sigma",+ "Phi": "capital phi",+ "Psi": "capital psi",+ "Omega": "capital omega",+}++_FUNCTIONS = {+ "arcsin": "arcsine",+ "arccos": "arccosine",+ "arctan": "arctangent",+ "sinh": "hyperbolic sine",+ "cosh": "hyperbolic cosine",+ "tanh": "hyperbolic tangent",+ "sin": "sine",+ "cos": "cosine",+ "tan": "tangent",+ "cot": "cotangent",+ "sec": "secant",+ "csc": "cosecant",+ "log": "log",+ "ln": "natural log",+ "lg": "log",+ "exp": "exponential",+ "min": "min",+ "max": "max",+ "inf": "infimum",+ "sup": "supremum",+ "det": "determinant",+ "dim": "dimension",+ "ker": "kernel",+ "deg": "degree",+ "gcd": "GCD",+ "lcm": "LCM",+ "arg": "arg",+ "Pr": "probability",+}++_OPERATORS = {+ "leqslant": "less than or equal to",+ "geqslant": "greater than or equal to",+ "subseteq": "subset of or equal to",+ "supseteq": "superset of or equal to",+ "leftrightarrow": "if and only if",+ "Leftrightarrow": "if and only if",+ "rightarrow": "to",+ "Rightarrow": "implies",+ "leftarrow": "from",+ "Leftarrow": "implied by",+ "longrightarrow": "to",+ "infty": "infinity",+ "emptyset": "empty set",+ "varnothing": "empty set",+ "partial": "partial",+ "nabla": "del",+ "cdots": "dot dot dot",+ "ldots": "dot dot dot",+ "dots": "dot dot dot",+ "cdot": "times",+ "times": "times",+ "star": "star",+ "ast": "times",+ "div": "divided by",+ "pm": "plus or minus",+ "mp": "minus or plus",+ "leq": "less than or equal to",+ "geq": "greater than or equal to",+ "neq": "not equal to",+ "ne": "not equal to",+ "approx": "approximately",+ "equiv": "equivalent to",+ "sim": "similar to",+ "propto": "proportional to",+ "cong": "congruent to",+ "forall": "for all",+ "exists": "there exists",+ "notin": "not in",+ "subset": "subset of",+ "supset": "superset of",+ "cup": "union",+ "cap": "intersection",+ "vee": "or",+ "wedge": "and",+ "oplus": "plus",+ "otimes": "tensor",+ "land": "and",+ "lor": "or",+ "lnot": "not",+ "neg": "not",+ "to": "to",+ "gets": "from",+ "implies": "implies",+ "iff": "if and only if",+ "in": "in",+ "ni": "contains",+ "le": "less than or equal to",+ "ge": "greater than or equal to",+ "ll": "much less than",+ "gg": "much greater than",+ "mid": "given",+ "parallel": "parallel to",+ "perp": "perpendicular to",+ "degree": "degrees",+ "circ": "compose",+ "bullet": "times",+ "prime": "prime",+ "ell": "l",+ "hbar": "h bar",+ "Re": "real part",+ "Im": "imaginary part",+}++_SPACING_DROP = {+ "qquad": " ",+ "quad": " ",+ "hspace": "",+ "vspace": "",+ "phantom": "",+ "mathstrut": "",+ "displaystyle": "",+ "textstyle": "",+ "scriptstyle": "",+ "left": "",+ "right": "",+ "bigl": "",+ "bigr": "",+ "Bigl": "",+ "Bigr": "",+ "biggl": "",+ "biggr": "",+ "Biggl": "",+ "Biggr": "",+ "big": "",+ "Big": "",+ "bigg": "",+ "Bigg": "",+ "nolimits": "",+ "limits": "",+ "notag": "",+ "tag": "",+ "label": "",+ "quad": " ",+}++_BLACKBOARD = {+ "R": "the reals",+ "N": "the naturals",+ "Z": "the integers",+ "Q": "the rationals",+ "C": "the complexes",+}++_MATH_ENVS = frozenset(+ {+ "equation",+ "equation*",+ "align",+ "align*",+ "aligned",+ "gather",+ "gather*",+ "displaymath",+ "math",+ "cases",+ "array",+ "matrix",+ "pmatrix",+ "bmatrix",+ "vmatrix",+ "Vmatrix",+ "multline",+ "split",+ }+)++_UNICODE_MATH = {+ "≤": " less than or equal to ",+ "≥": " greater than or equal to ",+ "≠": " not equal to ",+ "≈": " approximately ",+ "≡": " equivalent to ",+ "∞": " infinity ",+ "×": " times ",+ "÷": " divided by ",+ "±": " plus or minus ",+ "→": " to ",+ "←": " from ",+ "⇒": " implies ",+ "⇔": " if and only if ",+ "∈": " in ",+ "∉": " not in ",+ "⊂": " subset of ",+ "⊆": " subset of or equal to ",+ "∪": " union ",+ "∩": " intersection ",+ "∀": " for all ",+ "∃": " there exists ",+ "∂": " partial ",+ "∇": " del ",+ "√": " square root of ",+ "∑": " sum ",+ "∏": " product ",+ "∫": " integral ",+ "°": " degrees ",+ "·": " times ",+ "⋅": " times ",+}++_STYLE_NAMES = (+ "operatorname",+ "boldsymbol",+ "mathbf",+ "mathbb",+ "mathcal",+ "mathit",+ "mathsf",+ "mathtt",+ "textrm",+ "textbf",+ "textit",+ "mathrm",+ "text",+ "mbox",+ "overline",+ "underline",+ "widehat",+ "widetilde",+ "hat",+ "bar",+ "vec",+ "dot",+ "tilde",+ "check",+ "acute",+ "grave",+ "breve",+)++_ACCENT_SPEAK = {+ "overline": "{inner} bar",+ "underline": "{inner} underline",+ "widehat": "{inner} hat",+ "widetilde": "{inner} tilde",+ "hat": "{inner} hat",+ "bar": "{inner} bar",+ "vec": "{inner} vector",+ "dot": "{inner} dot",+ "tilde": "{inner} tilde",+ "check": "{inner} check",+}++_LIMIT_HEAD = {+ "oint": "contour integral",+ "int": "integral",+ "sum": "sum",+ "prod": "product",+ "lim": "limit",+}++_FRAC_NAMES = ("dfrac", "tfrac", "cfrac", "frac")+_SIMPLE_OPERAND = re.compile(r"^[\w.]+$", re.UNICODE)+_COMMAND = re.compile(r"\\(?:[a-zA-Z]+|.)")+_BEGIN_ENV = re.compile(r"\\begin\{([^}]+)\}")+_LEFTOVER_DOLLAR = re.compile(r"\$+")+_PAD_PLUS_EQ = re.compile(r"\s*([+=])\s*")+_MULTI_SPACE = re.compile(r"[ \t]{2,}")+_LOOSE_TEX = re.compile(+ r"\\(?:"+ + "|".join(+ re.escape(name)+ for name in sorted(+ {+ *_GREEK,+ *_OPERATORS,+ *_FUNCTIONS,+ *_SPACING_DROP,+ *_FRAC_NAMES,+ *_STYLE_NAMES,+ *_LIMIT_HEAD,+ "sqrt",+ "binom",+ "mathbb",+ },+ key=len,+ reverse=True,+ )+ )+ + r")(?![a-zA-Z])"+)+++def _skip_ws(s: str, i: int) -> int:+ n = len(s)+ while i < n and s[i].isspace():+ i += 1+ return i+++def _is_escaped(s: str, i: int) -> bool:+ bs = 0+ j = i - 1+ while j >= 0 and s[j] == "\\":+ bs += 1+ j -= 1+ return bs % 2 == 1+++def _read_group(s: str, i: int) -> tuple[str, int] | None:+ """Read a ``{…}`` group starting at ``i``. Returns ``(inner, after)``."""+ if i >= len(s) or s[i] != "{":+ return None+ depth = 0+ j = i+ n = len(s)+ while j < n:+ ch = s[j]+ if ch == "\\" and j + 1 < n:+ j += 2+ continue+ if ch == "{":+ depth += 1+ elif ch == "}":+ depth -= 1+ if depth == 0:+ return s[i + 1 : j], j + 1+ j += 1+ return None+++def _read_tex_token(s: str, i: int) -> tuple[str | None, int]:+ """Read one TeX token: a ``{group}``, a ``\\command``, or one character."""+ i = _skip_ws(s, i)+ if i >= len(s):+ return None, i+ if s[i] == "{":+ grp = _read_group(s, i)+ if grp is None:+ return s[i], i + 1+ inner, end = grp+ return inner, end+ match = _COMMAND.match(s, i)+ if match:+ return match.group(0), match.end()+ return s[i], i + 1+++def _until_stable(fn, text: str, *, limit: int = 8) -> str:+ for _ in range(limit):+ nxt = fn(text)+ if nxt == text:+ return nxt+ text = nxt+ return text+++def _speak_operand(piece: str) -> str:+ piece = piece.strip()+ if not piece:+ return ""+ if _SIMPLE_OPERAND.fullmatch(piece):+ return piece+ return f"({piece})"+++def _replace_named_commands(text: str, mapping: dict[str, str]) -> str:+ if not mapping:+ return text+ keys = sorted(mapping, key=len, reverse=True)+ pattern = re.compile(r"\\(" + "|".join(re.escape(k) for k in keys) + r")(?![a-zA-Z])")+ return pattern.sub(lambda m: f" {mapping[m.group(1)]} ", text)+++def _unwrap_style_once(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ names = "|".join(re.escape(name) for name in _STYLE_NAMES)+ opener = re.compile(r"\\(" + names + r")(?![a-zA-Z])")+ while i < n:+ match = opener.search(text, i)+ if not match:+ out.append(text[i:])+ break+ out.append(text[i : match.start()])+ i = _skip_ws(text, match.end())+ inner, end = _read_tex_token(text, i)+ name = match.group(1)+ if inner is None:+ i = match.end()+ continue+ spoken = _ACCENT_SPEAK.get(name)+ if spoken:+ out.append(" " + spoken.format(inner=inner.strip()) + " ")+ else:+ out.append(inner)+ i = end+ return "".join(out)+++def _replace_blackboard_sets(text: str) -> str:+ def repl(match: re.Match[str]) -> str:+ letter = match.group(1)+ return f" {_BLACKBOARD.get(letter, letter)} "++ return re.sub(r"\\mathbb\s*\{([RNZQC])\}", repl, text)+++def _replace_frac_once(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ opener = re.compile(r"\\(?:" + "|".join(_FRAC_NAMES) + r")(?![a-zA-Z])")+ while i < n:+ match = opener.search(text, i)+ if not match:+ out.append(text[i:])+ break+ out.append(text[i : match.start()])+ i = match.end()+ num, i = _read_tex_token(text, i)+ 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} ")+ return "".join(out)+++def _replace_sqrt_once(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ j = text.find(r"\sqrt", i)+ if j == -1 or (j + 5 < n and text[j + 5].isalpha()):+ if j == -1:+ out.append(text[i:])+ break+ out.append(text[i : j + 5])+ i = j + 5+ continue+ out.append(text[i:j])+ i = j + 5+ i = _skip_ws(text, i)+ root: str | None = None+ if i < n and text[i] == "[":+ close = text.find("]", i + 1)+ if close != -1:+ root = text[i + 1 : close]+ i = close + 1+ i = _skip_ws(text, i)+ inner, i = _read_tex_token(text, i)+ if inner is None:+ continue+ spoken = _speak_operand(_verbalize_math(inner))+ if root is None or root.strip() in {"", "2"}:+ out.append(f" square root of {spoken} ")+ elif root.strip() == "3":+ out.append(f" cube root of {spoken} ")+ else:+ root_s = _speak_operand(_verbalize_math(root))+ out.append(f" {root_s} root of {spoken} ")+ return "".join(out)+++def _replace_binom_once(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ opener = re.compile(r"\\binom(?![a-zA-Z])")+ while i < n:+ match = opener.search(text, i)+ if not match:+ out.append(text[i:])+ break+ out.append(text[i : match.start()])+ i = match.end()+ top, i = _read_tex_token(text, i)+ bot, i = _read_tex_token(text, i)+ if top is None or bot is None:+ continue+ out.append(+ f" {_speak_operand(_verbalize_math(top))} choose "+ f"{_speak_operand(_verbalize_math(bot))} "+ )+ return "".join(out)+++def _replace_limits_once(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ opener = re.compile(r"\\(" + "|".join(_LIMIT_HEAD) + r")(?![a-zA-Z])")+ while i < n:+ match = opener.search(text, i)+ if not match:+ out.append(text[i:])+ break+ out.append(text[i : match.start()])+ i = match.end()+ i = _skip_ws(text, i)+ sub = None+ sup = None+ if i < n and text[i] == "_":+ sub, i = _read_tex_token(text, i + 1)+ i = _skip_ws(text, i)+ if i < n and text[i] == "^":+ sup, i = _read_tex_token(text, i + 1)+ head = _LIMIT_HEAD[match.group(1)]+ parts = [head]+ if match.group(1) == "lim":+ if sub:+ parts.append("as")+ parts.append(_verbalize_math(sub).strip())+ if sup:+ parts.append("to")+ parts.append(_verbalize_math(sup).strip())+ else:+ if sub:+ parts.append("from")+ parts.append(_verbalize_math(sub).strip())+ if sup:+ parts.append("to")+ parts.append(_verbalize_math(sup).strip())+ out.append(" " + " ".join(p for p in parts if p) + " ")+ return "".join(out)+++def _speak_sup(inner: str) -> str:+ token = inner.strip()+ token = _replace_named_commands(token, {**_GREEK, **_OPERATORS, **_FUNCTIONS})+ token = token.strip()+ if token in {"2"}:+ return " squared "+ if token in {"3"}:+ return " cubed "+ if token in {"-1"}:+ return " inverse "+ if token in {"T", "t", "top", "intercal"}:+ return " transpose "+ if token in {"prime", "'"}:+ return " prime "+ if token in {"circ", "o", "\\circ"}:+ return " degrees "+ if token in {"*"}:+ return " star "+ return f" to the {token} "+++def _verbalize_scripts(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ ch = text[i]+ if ch in "^_" and not _is_escaped(text, i):+ kind = ch+ token, nxt = _read_tex_token(text, i + 1)+ if token is None:+ i += 1+ continue+ i = nxt+ if kind == "^":+ out.append(_speak_sup(token))+ else:+ spoken = _verbalize_math(token).strip() if "\\" in token else token.strip()+ out.append(f" sub {spoken} ")+ continue+ out.append(ch)+ i += 1+ return "".join(out)+++def _drop_unknown_commands(text: str) -> str:+ out: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ if text[i] == "\\" and i + 1 < n:+ match = re.match(r"\\[a-zA-Z]+", text[i:])+ if match:+ i += match.end()+ i = _skip_ws(text, i)+ if i < n and text[i] == "{":+ grp = _read_group(text, i)+ if grp is not None:+ inner, i = grp+ out.append(inner)+ continue+ nxt = text[i + 1]+ if nxt in "{}":+ i += 2+ continue+ if nxt in "[]()|,.;!":+ out.append(nxt)+ i += 2+ continue+ if nxt in ",;! \\":+ out.append(" ")+ i += 2+ continue+ i += 2+ continue+ out.append(text[i])+ i += 1+ return "".join(out)+++def _drop_braces(text: str) -> str:+ return text.replace("{", " ").replace("}", " ")+++def _verbalize_math(text: str) -> str:+ """Turn one math island's inner TeX into speakable words."""+ if not text:+ return ""+ out = text.replace("&", " ")+ out = out.replace(r"\\", ", ")+ out = _replace_blackboard_sets(out)+ out = _until_stable(_unwrap_style_once, out)+ out = _until_stable(_replace_frac_once, 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)+ out = _drop_unknown_commands(out)+ out = _drop_braces(out)+ out = _PAD_PLUS_EQ.sub(r" \1 ", out)+ out = _MULTI_SPACE.sub(" ", out)+ return out.strip()+++def _replace_unicode(text: str) -> str:+ if not text:+ return text+ out = text+ for src, spoken in _UNICODE_MATH.items():+ if src in out:+ out = out.replace(src, spoken)+ return out+++def _verbalize_loose_commands(text: str) -> str:+ """Convert leftover TeX commands in prose; never touch bare ``_`` / ``^``.++ Gated on known TeX names so Windows paths like ``C:\\Users`` stay intact.+ """+ if "\\" not in text or not _LOOSE_TEX.search(text):+ return text+ out = _replace_blackboard_sets(text)+ out = _until_stable(_unwrap_style_once, out)+ out = _until_stable(_replace_frac_once, 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 = _drop_unknown_commands(out)+ return out+++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) -> str:+ """Replace math islands with speakable prose, or just unwrap delimiters.++ ``math_speak=True`` (default) verbalizes fractions, powers, Greek, and+ operators. ``math_speak=False`` still strips ``$`` / ``$$`` / ``\\(``+ wrappers so TTS never says "dollar", but leaves the inner TeX as-is.++ Bare underscores outside math are preserved (``file_name`` stays intact).+ Leftover ``$`` from broken markup is dropped.+ """+ if not text:+ return ""+ if "$" not in text and "\\" not in text:+ return _replace_unicode(text) if math_speak else text++ out: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ if text.startswith("$$", i) and not _is_escaped(text, i):+ end = text.find("$$", i + 2)+ if end != -1:+ out.append(" ")+ out.append(_emit_island(text[i + 2 : end], math_speak=math_speak))+ out.append(" ")+ i = end + 2+ continue+ if text.startswith("\\[", i):+ end = text.find("\\]", i + 2)+ if end != -1:+ out.append(" ")+ out.append(_emit_island(text[i + 2 : end], math_speak=math_speak))+ out.append(" ")+ i = end + 2+ continue+ if text.startswith("\\(", i):+ end = text.find("\\)", i + 2)+ if end != -1:+ out.append(" ")+ out.append(_emit_island(text[i + 2 : end], math_speak=math_speak))+ out.append(" ")+ i = end + 2+ continue+ begin = _BEGIN_ENV.match(text, i)+ if begin and begin.group(1) in _MATH_ENVS:+ env = begin.group(1)+ end_tag = f"\\end{{{env}}}"+ end = text.find(end_tag, begin.end())+ if end != -1:+ out.append(" ")+ out.append(_emit_island(text[begin.end() : end], math_speak=math_speak))+ out.append(" ")+ i = end + len(end_tag)+ continue+ if text[i] == "$" and not _is_escaped(text, i):+ j = i + 1+ while j < n:+ if text[j] == "\n":+ j = -1+ break+ if text[j] == "$" and not _is_escaped(text, j):+ break+ j += 1+ if j > i:+ out.append(" ")+ out.append(_emit_island(text[i + 1 : j], math_speak=math_speak))+ out.append(" ")+ i = j + 1+ continue+ out.append(text[i])+ i += 1++ spoken = "".join(out)+ if math_speak:+ spoken = _verbalize_loose_commands(spoken)+ spoken = _replace_unicode(spoken)+ spoken = _LEFTOVER_DOLLAR.sub("", spoken)+ return spoken+++__all__ = ["verbalize_latex_for_speech"]diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex cc4f09b33..9217407f5 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -1790,3 +1790,22 @@ async def test_ui_endpoints_do_not_freeze_defaults_into_the_file(assert stored == {"theme": "dark"}, f"only the changed field belongs on disk: {stored}"# The read path still reports the full picture.assert settings_router.load_ui_settings()["language"] == "en"+++async def test_voice_math_speak_persists_without_freezing_defaults(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ settings_file = tmp_path / "interface.json"+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)++ response = await settings_router.update_voice_math_speak(+ settings_router.VoiceMathSpeakUpdate(voice_math_speak=False)+ )++ assert response == {"voice_math_speak": False}+ stored = json.loads(settings_file.read_text(encoding="utf-8"))+ assert stored == {"voice_math_speak": False}+ loaded = settings_router.load_ui_settings()+ assert loaded["voice_math_speak"] is False+ assert loaded["voice_autoplay"] is Falsediff --git a/tests/services/test_voice.py b/tests/services/test_voice.pyindex 0af517674..cf3b2d695 100644--- a/tests/services/test_voice.py+++ b/tests/services/test_voice.py@@ -123,6 +123,88 @@ def test_strip_markdown_truncates_on_boundary() -> None:assert out.endswith(".")+def test_strip_markdown_unwraps_latex_dollars() -> None:+ out = strip_markdown_for_speech("The identity is $E = mc^2$ and $$\\int x dx$$.")+ assert "$" not in out+ assert "\\" not in out+ assert "E = mc squared" in out+ assert "integral x dx" in out+++def test_strip_markdown_unwraps_latex_parens_and_brackets() -> None:+ out = strip_markdown_for_speech(r"See \(a + b\) and \[c + d\].")+ assert "a + b" in out+ assert "c + d" in out+ assert "\\(" not in out+ assert "\\[" not in out+++def test_strip_markdown_drops_unpaired_dollars() -> None:+ out = strip_markdown_for_speech("A leftover $ delimiter should not be spoken.")+ assert "$" not in out+ assert "leftover" in out+ assert "delimiter" in out+++def test_strip_markdown_verbalizes_fractions_roots_and_greek() -> None:+ out = strip_markdown_for_speech(+ r"Take $\frac{1}{2}$ of $\sqrt{x}$ and $\alpha + \beta$."+ )+ assert "$" not in out+ assert "\\" not in out+ assert "{" not in out and "}" not in out+ assert "1 over 2" in out+ assert "square root of x" in out+ cube = strip_markdown_for_speech(r"$\sqrt[3]{x}$")+ assert "cube root of x" in cube+ assert "alpha" in out+ assert "beta" in out+++def test_strip_markdown_verbalizes_nested_fraction() -> None:+ out = strip_markdown_for_speech(r"$\frac{1}{\frac{2}{3}}$")+ assert "1 over (2 over 3)" in out+ assert "\\frac" not in out+++def test_strip_markdown_verbalizes_sum_limits() -> None:+ out = strip_markdown_for_speech(r"$$\sum_{i=1}^{n} i$$")+ assert "sum from i = 1 to n" in out+ assert "_" not in out+ assert "^" not in out+++def test_strip_markdown_preserves_snake_case_outside_math() -> None:+ out = strip_markdown_for_speech("See file_name and $x_i$.")+ assert "file_name" in out+ assert "x sub i" in out+ assert "$" not in out+++def test_strip_markdown_verbalizes_trig_and_inequality() -> None:+ out = strip_markdown_for_speech(r"If $\sin \theta \leq 1$ then done.")+ assert "sine" in out+ assert "theta" in out+ assert "less than or equal to 1" in out+++def test_strip_markdown_leaves_windows_paths_alone() -> None:+ out = strip_markdown_for_speech(r"Saved at C:\Users\antmi\notes.md")+ assert r"C:\Users\antmi\notes.md" in out+++def test_strip_markdown_math_speak_off_keeps_inner_tex() -> None:+ out = strip_markdown_for_speech(+ r"The identity is $E = mc^2$ and $\frac{1}{2}$.",+ math_speak=False,+ )+ assert "$" not in out+ assert "E = mc^2" in out+ assert r"\frac{1}{2}" in out+ assert "squared" not in out+ assert "over" not in out++def test_join_audio_path_appends_and_preserves_full_url() -> None:assert join_audio_path("https://api.openai.com/v1", "audio/speech").endswith("/v1/audio/speech")full = "https://r.azure.com/openai/deployments/tts/audio/speech?api-version=2025"@@ -538,9 +620,49 @@ def test_resolve_tts_config_raises_without_model() -> None:async def test_synthesize_speech_facade_strips_markdown(monkeypatch: pytest.MonkeyPatch) -> None:resp = httpx.Response(200, content=b"audio", headers={"content-type": "audio/wav"})captured = _capture_post(monkeypatch, resp)- audio, ctype = await synthesize_speech("# Hi\n\n**bold**", catalog=_voice_catalog())+ audio, ctype = await synthesize_speech(+ "# Hi\n\n**bold** $x^2$",+ catalog=_voice_catalog(),+ math_speak=True,+ )assert audio == b"audio"- assert captured["json"]["input"] == "Hi\n\nbold" # markdown stripped+ spoken = captured["json"]["input"]+ assert spoken.startswith("Hi")+ assert "bold" in spoken+ assert "x squared" in spoken+ assert "$" not in spoken+ assert "^" not in spoken+++async def test_synthesize_speech_math_speak_off_keeps_caret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ resp = httpx.Response(200, content=b"audio", headers={"content-type": "audio/wav"})+ captured = _capture_post(monkeypatch, resp)+ await synthesize_speech(+ "$x^2$",+ catalog=_voice_catalog(),+ math_speak=False,+ )+ spoken = captured["json"]["input"]+ assert "$" not in spoken+ assert "x^2" in spoken+ assert "squared" not in spoken+++async def test_synthesize_speech_reads_math_speak_from_ui_settings(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.services.settings import interface_settings++ monkeypatch.setattr(interface_settings, "get_ui_settings", lambda: {"voice_math_speak": False})+ resp = httpx.Response(200, content=b"audio", headers={"content-type": "audio/wav"})+ captured = _capture_post(monkeypatch, resp)+ await synthesize_speech("$x^2$", catalog=_voice_catalog())+ assert "x^2" in captured["json"]["input"]+ assert "squared" not in captured["json"]["input"]@pytest.mark.asynciodiff --git a/web/features/settings/sections/models/TtsSettingsSection.tsx b/web/features/settings/sections/models/TtsSettingsSection.tsxindex db1f04f49..90ee87dc6 100644--- a/web/features/settings/sections/models/TtsSettingsSection.tsx+++ b/web/features/settings/sections/models/TtsSettingsSection.tsx@@ -2,6 +2,7 @@import { useTranslation } from "react-i18next";import { ModelsWorkspace } from "@/components/settings/ModelsWorkspace";import { SettingsPageHeader } from "@/components/settings/shared";+import { VoicePlaybackPrefs } from "./VoicePlaybackPrefs";export default function TtsSettingsPage() {const { t } = useTranslation();return (@@ -12,6 +13,7 @@ export default function TtsSettingsPage() {"Manage speech synthesis and transcription models using saved providers.",)}/>+ <VoicePlaybackPrefs /><ModelsWorkspace page="voice" initialService="tts" /></div>);diff --git a/web/features/settings/sections/models/VoicePlaybackPrefs.tsx b/web/features/settings/sections/models/VoicePlaybackPrefs.tsxnew file mode 100644index 000000000..f395626aa--- /dev/null+++ b/web/features/settings/sections/models/VoicePlaybackPrefs.tsx@@ -0,0 +1,88 @@+"use client";++import { useTranslation } from "react-i18next";++import { useVoiceAutoplayPreference } from "@/hooks/useVoiceAutoplay";+import { useVoiceMathSpeakPreference } from "@/hooks/useVoiceMathSpeak";++function PlaybackToggle({+ label,+ description,+ value,+ loading,+ onChange,+}: {+ label: string;+ description: string;+ value: boolean;+ loading: boolean;+ onChange: (next: boolean) => void;+}) {+ return (+ <div className="flex items-start justify-between gap-6 rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40 px-5 py-4">+ <div className="min-w-0 flex-1">+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">+ {label}+ </div>+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {description}+ </p>+ </div>+ <button+ type="button"+ role="switch"+ aria-checked={value}+ disabled={loading}+ onClick={() => onChange(!value)}+ className={`relative mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${+ value ? "bg-[var(--foreground)]" : "bg-[var(--border)]"+ }`}+ aria-label={label}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-[var(--background)] shadow-sm transition-transform ${+ value ? "translate-x-4" : "translate-x-0.5"+ }`}+ />+ </button>+ </div>+ );+}++export function VoicePlaybackPrefs() {+ const { t } = useTranslation();+ const autoplay = useVoiceAutoplayPreference();+ const mathSpeak = useVoiceMathSpeakPreference();+ return (+ <section className="mb-8">+ <div className="mb-3">+ <h2 className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">+ {t("Playback")}+ </h2>+ <p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t("How spoken replies behave in chat.")}+ </p>+ </div>+ <div className="space-y-3">+ <PlaybackToggle+ label={t("Auto-play replies")}+ description={t(+ "Read each assistant reply aloud automatically. You can also toggle this per conversation from the speaker button.",+ )}+ value={autoplay.value}+ loading={autoplay.loading}+ onChange={autoplay.setValue}+ />+ <PlaybackToggle+ label={t("Math speak")}+ description={t(+ "Read LaTeX as words — fractions, powers, and Greek letters. Turn this off to keep formulas closer to the written math. Dollar signs are never spoken.",+ )}+ value={mathSpeak.value}+ loading={mathSpeak.loading}+ onChange={mathSpeak.setValue}+ />+ </div>+ </section>+ );+}diff --git a/web/features/settings/sections/models/VoiceSettingsSection.tsx b/web/features/settings/sections/models/VoiceSettingsSection.tsxindex c0321722f..9931f98a0 100644--- a/web/features/settings/sections/models/VoiceSettingsSection.tsx+++ b/web/features/settings/sections/models/VoiceSettingsSection.tsx@@ -2,6 +2,7 @@import { useTranslation } from "react-i18next";import { ModelsWorkspace } from "@/components/settings/ModelsWorkspace";import { SettingsPageHeader } from "@/components/settings/shared";+import { VoicePlaybackPrefs } from "./VoicePlaybackPrefs";export default function VoiceSettingsPage() {const { t } = useTranslation();return (@@ -12,6 +13,7 @@ export default function VoiceSettingsPage() {"Manage speech synthesis and transcription models using saved providers.",)}/>+ <VoicePlaybackPrefs /><ModelsWorkspace page="voice" /></div>);diff --git a/web/hooks/useVoiceMathSpeak.ts b/web/hooks/useVoiceMathSpeak.tsnew file mode 100644index 000000000..56b5156d5--- /dev/null+++ b/web/hooks/useVoiceMathSpeak.ts@@ -0,0 +1,74 @@+"use client";++import { useCallback, useEffect, useState } from "react";++import { apiFetch, apiUrl } from "@/lib/api";++const GLOBAL_EVENT = "deeptutor:voice-math-speak";++let cached: boolean | null = null;+let inflight: Promise<boolean> | null = null;++function fetchPreference(): Promise<boolean> {+ if (cached !== null) return Promise.resolve(cached);+ if (!inflight) {+ inflight = apiFetch(apiUrl("/api/settings"))+ .then((r) => (r.ok ? r.json() : null))+ .then((payload) => {+ const next = payload?.ui?.voice_math_speak !== false;+ cached = next;+ return next;+ })+ .catch(() => {+ cached = true;+ return true;+ })+ .finally(() => {+ inflight = null;+ });+ }+ return inflight;+}++/**+ * Settings-page hook: read/write whether TTS verbalizes LaTeX as spoken math.+ * Default is on. The server applies this on every /tts call.+ */+export function useVoiceMathSpeakPreference() {+ const [value, setVal] = useState<boolean>(cached ?? true);+ const [loading, setLoading] = useState<boolean>(cached === null);++ useEffect(() => {+ let active = true;+ fetchPreference().then((v) => {+ if (active) {+ setVal(v);+ setLoading(false);+ }+ });+ const onGlobal = (e: Event) =>+ setVal(Boolean((e as CustomEvent).detail?.value));+ window.addEventListener(GLOBAL_EVENT, onGlobal);+ return () => {+ active = false;+ window.removeEventListener(GLOBAL_EVENT, onGlobal);+ };+ }, []);++ const setValue = useCallback(async (next: boolean) => {+ setVal(next);+ cached = next;+ if (typeof window !== "undefined") {+ window.dispatchEvent(+ new CustomEvent(GLOBAL_EVENT, { detail: { value: next } }),+ );+ }+ await apiFetch(apiUrl("/api/settings/voice-math-speak"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ voice_math_speak: next }),+ });+ }, []);++ return { value, setValue, loading };+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex b9fdaa84d..88c5589dc 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -242,6 +242,8 @@"Playback": "Playback","How spoken replies behave in chat.": "How spoken replies behave in chat.","Auto-play replies": "Auto-play replies",+ "Math speak": "Math speak",+ "Read LaTeX as words — fractions, powers, and Greek letters. Turn this off to keep formulas closer to the written math. Dollar signs are never spoken.": "Read LaTeX as words — fractions, powers, and Greek letters. Turn this off to keep formulas closer to the written math. Dollar signs are never spoken.","Breadcrumb": "Breadcrumb","Saved to": "Saved to","Network changes take effect after restart.": "Network changes take effect after restart.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 3e68611ad..47701d803 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -242,6 +242,8 @@"Playback": "播放","How spoken replies behave in chat.": "语音回复在聊天中的行为。","Auto-play replies": "自动朗读回复",+ "Math speak": "数学朗读",+ "Read LaTeX as words — fractions, powers, and Greek letters. Turn this off to keep formulas closer to the written math. Dollar signs are never spoken.": "把 LaTeX 读成自然语言(分数、乘方、希腊字母)。关闭后更接近书面公式;仍不会读出美元符号。","Breadcrumb": "导航路径","Saved to": "保存于","Network changes take effect after restart.": "网络改动重启后生效。",