discord-bot / vb_mathfmt.py
jay0826's picture
更新 2 個檔(vb_mathfmt.py、recent.npz)
535e99d verified
Raw History Blame
18.8 kB
# -*- coding: utf-8 -*-
"""回覆裡的 LaTeX 數學式 → Discord 看得懂、可以複製的 Unicode 文字。
★2026-11-15 主人貼圖:模型寫 `$3 \\times 28 = 84$`,Discord 不認得 LaTeX,整則都是 `$…\\times…$`。
提了「簡單的轉文字、複雜的畫成圖」,主人:「我不要圖 不能複製太爛了」→ 全部轉成文字。
結構(上下標、分數、根號、矩陣、\\left \\right、空白)自己處理;符號(\\alpha、\\leq、\\mathbb{R}…幾百個)
查 pylatexenc 的表,常用的先查內建表(pylatexenc 沒裝也能用)。
不碰:``` 程式碼區塊、`行內程式碼`、整份 HTML(/web 的網頁可能自己用 MathJax)、價錢那種 `$5 和 $10`。
"""
import re
from typing import Dict, List, Optional, Tuple
try:
from pylatexenc.latex2text import LatexNodes2Text
_L2T = LatexNodes2Text(math_mode="text")
except Exception: # 沒裝:只用內建表,其他的寫成名字本身
_L2T = None
SUP: Dict[str, str] = {
**dict(zip("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")), "+": "⁺", "-": "⁻", "−": "⁻", "=": "⁼", "(": "⁽", ")": "⁾",
"a": "ᵃ", "b": "ᵇ", "c": "ᶜ", "d": "ᵈ", "e": "ᵉ", "f": "ᶠ", "g": "ᵍ", "h": "ʰ", "i": "ⁱ", "j": "ʲ", "k": "ᵏ",
"l": "ˡ", "m": "ᵐ", "n": "ⁿ", "o": "ᵒ", "p": "ᵖ", "r": "ʳ", "s": "ˢ", "t": "ᵗ", "u": "ᵘ", "v": "ᵛ", "w": "ʷ",
"x": "ˣ", "y": "ʸ", "z": "ᶻ", "T": "ᵀ", "′": "′", "°": "°", "*": "*",
}
SUB: Dict[str, str] = {
**dict(zip("0123456789", "₀₁₂₃₄₅₆₇₈₉")), "+": "₊", "-": "₋", "−": "₋", "=": "₌", "(": "₍", ")": "₎",
"a": "ₐ", "e": "ₑ", "h": "ₕ", "i": "ᵢ", "j": "ⱼ", "k": "ₖ", "l": "ₗ", "m": "ₘ", "n": "ₙ", "o": "ₒ", "p": "ₚ",
"r": "ᵣ", "s": "ₛ", "t": "ₜ", "u": "ᵤ", "v": "ᵥ", "x": "ₓ",
}
# 二元運算、關係:前後各留一格(LaTeX 原始碼裡 \times 後面的空白會被吃掉,「3 ×(-28)」很難讀)
_OPS: Dict[str, str] = {
"times": "×", "cdot": "·", "pm": "±", "mp": "∓", "div": "÷", "ast": "∗", "star": "⋆",
"leq": "≤", "le": "≤", "geq": "≥", "ge": "≥", "neq": "≠", "ne": "≠", "approx": "≈", "equiv": "≡",
"sim": "∼", "simeq": "≃", "cong": "≅", "propto": "∝", "ll": "≪", "gg": "≫",
"to": "→", "rightarrow": "→", "leftarrow": "←", "Rightarrow": "⇒", "Leftarrow": "⇐", "implies": "⇒",
"leftrightarrow": "↔", "Leftrightarrow": "⇔", "iff": "⇔", "mapsto": "↦", "longrightarrow": "⟶",
"in": "∈", "notin": "∉", "ni": "∋", "subset": "⊂", "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇",
"cup": "∪", "cap": "∩", "setminus": "∖", "land": "∧", "wedge": "∧", "lor": "∨", "vee": "∨",
"oplus": "⊕", "otimes": "⊗", "perp": "⊥", "parallel": "∥", "mid": "∣",
}
# 常用符號(不加空白):pylatexenc 沒裝也要有
_SYM: Dict[str, str] = {
"alpha": "α", "beta": "β", "gamma": "γ", "delta": "δ", "epsilon": "ε", "varepsilon": "ε", "zeta": "ζ", "eta": "η",
"theta": "θ", "vartheta": "ϑ", "iota": "ι", "kappa": "κ", "lambda": "λ", "mu": "μ", "nu": "ν", "xi": "ξ", "pi": "π",
"rho": "ρ", "sigma": "σ", "tau": "τ", "upsilon": "υ", "phi": "φ", "varphi": "φ", "chi": "χ", "psi": "ψ", "omega": "ω",
"Gamma": "Γ", "Delta": "Δ", "Theta": "Θ", "Lambda": "Λ", "Xi": "Ξ", "Pi": "Π", "Sigma": "Σ", "Phi": "Φ",
"Psi": "Ψ", "Omega": "Ω", "infty": "∞", "partial": "∂", "nabla": "∇", "forall": "∀", "exists": "∃",
"neg": "¬", "lnot": "¬", "emptyset": "∅", "varnothing": "∅", "sum": "∑", "prod": "∏", "int": "∫", "iint": "∬",
"oint": "∮", "ldots": "…", "cdots": "⋯", "dots": "…", "vdots": "⋮", "ddots": "⋱", "circ": "∘", "angle": "∠",
"triangle": "△", "degree": "°", "prime": "′", "hbar": "ℏ", "ell": "ℓ", "Re": "ℜ", "Im": "ℑ", "aleph": "ℵ",
"therefore": "∴", "because": "∵", "checkmark": "✓", "lfloor": "⌊", "rfloor": "⌋", "lceil": "⌈", "rceil": "⌉",
"langle": "⟨", "rangle": "⟩", "{": "{", "}": "}", "%": "%", "$": "$", "&": "&", "#": "#", "_": "_",
"|": "‖", "lvert": "|", "rvert": "|", "vert": "|", "lVert": "‖", "rVert": "‖", "backslash": "\\",
"Box": "□", "square": "□", "blacksquare": "■", "qed": "∎", "bot": "⊥", "colon": ":", "bullet": "•",
}
_SPACE = {",": " ", ";": " ", ":": " ", ">": " ", "!": "", " ": " ", "quad": " ", "qquad": " ",
"enspace": " ", "thinspace": " ", "medspace": " ", "thickspace": " "}
_DROP = {"left", "right", "big", "Big", "bigg", "Bigg", "bigl", "bigr", "Bigl", "Bigr", "biggl", "biggr",
"displaystyle", "textstyle", "scriptstyle", "limits", "nolimits", "nonumber", "notag", "middle",
"hfill", "noindent", "medskip", "smallskip", "bigskip", "relax", "strut", "mathstrut", "nobreak", "allowbreak"}
_TEXT = {"text", "textrm", "textnormal", "mbox", "textup", "textsf", "texttt"} # 內容照字面
_STYLE = {"mathrm", "mathbf", "mathit", "mathsf", "mathtt", "boldsymbol", "bm", "textbf", "textit", "operatorname",
"mathnormal", "emph", "underline", "overline", "boxed", "pmb"} # 內容照樣轉、樣式不要
_FONT = {"mathbb", "mathcal", "mathfrak", "mathscr"} # 交給 pylatexenc(ℝ、ℒ…)
_ACCENT = {"hat", "bar", "vec", "dot", "ddot", "tilde", "widehat", "widetilde", "acute", "grave", "breve", "check"}
_FRAC = {"frac", "dfrac", "tfrac", "cfrac"}
_FUNCS = {"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "log", "ln",
"lg", "exp", "lim", "max", "min", "sup", "inf", "det", "gcd", "deg", "dim", "ker", "arg", "Pr", "mod", "bmod"}
_MATRIX = {"matrix": ("[", "]"), "pmatrix": ("(", ")"), "bmatrix": ("[", "]"), "Bmatrix": ("{", "}"),
"vmatrix": ("|", "|"), "Vmatrix": ("‖", "‖"), "smallmatrix": ("[", "]")}
_LINES = {"aligned", "align", "align*", "alignat", "gather", "gather*", "gathered", "split", "eqnarray", "eqnarray*",
"array", "multline", "equation", "equation*"}
_FUNC_PAREN = re.compile(r"(?<![A-Za-z])(%s) (?=[(\[])" % "|".join(sorted(_FUNCS, key=len, reverse=True)))
_cache: Dict[str, str] = {}
def _lookup(name: str) -> str:
"""沒在內建表的指令:問 pylatexenc;它也不認得就寫名字本身(不留反斜線)。"""
if name in _cache:
return _cache[name]
out = ""
if _L2T is not None:
try:
out = _L2T.latex_to_text("\\" + name).strip()
except Exception:
out = ""
_cache[name] = out or name
return _cache[name]
class _P:
def __init__(self, s: str):
self.s, self.i = s, 0
def peek(self) -> str:
return self.s[self.i] if self.i < len(self.s) else ""
def macro(self) -> str:
"""在反斜線上:讀出指令名(字母串,或單一符號)。"""
self.i += 1
m = re.match(r"[A-Za-z]+\*?", self.s[self.i:])
if m:
self.i += m.end()
return m.group(0)
ch = self.peek()
self.i += 1 if ch else 0
return ch
def skip_ws(self) -> None:
while self.peek() in (" ", "\t", "\n"):
self.i += 1
def group_raw(self) -> str:
"""讀一個 {…}(原文,不轉);不是 { 就讀一個字元/一個指令。"""
self.skip_ws()
if self.peek() == "{":
depth, start = 0, self.i
while self.i < len(self.s):
c = self.s[self.i]
if c == "\\":
self.i += 2
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
self.i += 1
return self.s[start + 1:self.i - 1]
self.i += 1
return self.s[start + 1:]
if self.peek() == "\\":
start = self.i
self.macro()
return self.s[start:self.i]
ch = self.peek()
self.i += 1 if ch else 0
return ch
def opt_raw(self) -> Optional[str]:
"""讀 [..](\\sqrt[3]{x} 的那個 3);沒有就 None。"""
self.skip_ws()
if self.peek() != "[":
return None
end = self.s.find("]", self.i)
if end < 0:
return None
out, self.i = self.s[self.i + 1:end], end + 1
return out
def _wrap(x: str, strict: bool = False) -> str:
"""分數、根號裡面不是單一個東西就加括號:(−b ± √(b² − 4ac))/(2a)。
strict=分母:只有純數字或單一個字(可帶上下標)才不加,「x/2a」會被讀成 (x/2)·a。"""
x = x.strip()
if strict:
if re.fullmatch(r"\d+(\.\d+)?|[^\W\d]?[⁰¹²³⁴⁵⁶⁷⁸⁹ⁿⁱ₀₁₂₃₄₅₆₇₈₉ᵢⱼₙ′]*|[πθαβγ∞][⁰¹²³⁴⁵⁶⁷⁸⁹]*", x) and x:
return x
return x if (x.startswith("(") and x.endswith(")") and x.count("(") == 1) else "(" + x + ")"
if re.fullmatch(r"[\w.′°⁰¹²³⁴⁵⁶⁷⁸⁹ⁿⁱ₀₁₂₃₄₅₆₇₈₉ᵢⱼₙ∞πθαβγ]+", x) or (x.startswith("(") and x.endswith(")")
and x.count("(") == 1):
return x
return "(" + x + ")"
def _script(x: str, table: Dict[str, str], mark: str) -> str:
x = x.strip()
if not x:
return ""
if all(c in table or c == " " for c in x):
return "".join(table.get(c, "") for c in x)
return mark + (x if len(x) == 1 else "(" + x + ")")
def _env(name: str, body: str) -> str:
rows = [r for r in re.split(r"\\\\(?:\[[^\]]*\])?", body) if r.strip() and not r.strip().startswith("\\hline")]
rows = [re.sub(r"\\hline", "", r) for r in rows]
if name in _MATRIX:
l, r = _MATRIX[name]
return l + "; ".join(", ".join(conv(c).strip() for c in row.split("&")) for row in rows) + r
if name == "cases":
return "{ " + "; ".join(",".join(conv(c).strip() for c in row.split("&") if c.strip()) for row in rows)
if name.startswith("array"):
body = re.sub(r"^\s*\{[^}]*\}", "", body) # 欄位格式 {cc|c}
rows = [r for r in re.split(r"\\\\", body) if r.strip()]
return "\n".join(" ".join(conv(c).strip() for c in row.split("&")) for row in rows)
def conv(src: str) -> str:
"""一段 LaTeX($ 裡面那段)→ Unicode 文字。"""
p = _P(src)
out: List[str] = []
def last_atom_pop() -> str:
return out.pop() if out else ""
while p.i < len(p.s):
c = p.peek()
if c in "^_":
p.i += 1
arg = p.group_raw()
inner = conv(arg) if arg.startswith("\\") or len(arg) > 1 else arg
if arg.strip() in ("\\prime", "'"):
inner = "′"
elif arg.strip() == "\\circ":
inner = "°"
base = last_atom_pop()
if base.endswith(" ") and (base.strip() in ("∑", "∏", "∫") or base.strip() in _FUNCS):
if c == "_" and base.strip() in ("lim", "max", "min", "sup", "inf") and not all(ch in SUB or ch == " " for ch in inner.strip()):
out.append(base.strip() + "(" + inner.strip() + ") ") # lim(x → ∞) 1/x
continue
base = base.rstrip()
sc = _script(inner, SUP if c == "^" else SUB, c)
out.append(base + sc + (" " if base.strip() in _FUNCS else ""))
continue
if c == "{":
out.append(conv(p.group_raw()))
continue
if c == "}":
p.i += 1
continue
if c == "'":
p.i += 1
out.append("′")
continue
if c == "~":
p.i += 1
out.append(" ")
continue
if c == "&":
p.i += 1
out.append(" ")
continue
if c != "\\":
p.i += 1
out.append(c)
continue
name = p.macro()
if name == "\\": # 換行
out.append("; ")
elif name in _SPACE:
out.append(_SPACE[name])
elif name in _DROP:
if name in ("left", "right", "middle") or name.startswith(("big", "Big")):
d = p.peek()
if d == ".":
p.i += 1
elif d == "\\":
nm = p.macro()
out.append({"{": "{", "}": "}", "|": "‖"}.get(nm, _SYM.get(nm) or _lookup(nm)))
elif d:
p.i += 1
out.append(d)
elif name in _FRAC:
a, b = conv(p.group_raw()), conv(p.group_raw())
out.append(_wrap(a) + "/" + _wrap(b, strict=True))
elif name == "binom":
a, b = conv(p.group_raw()), conv(p.group_raw())
out.append("C(" + a.strip() + ", " + b.strip() + ")")
elif name == "sqrt":
n = p.opt_raw()
a = conv(p.group_raw())
root = {"3": "∛", "4": "∜"}.get((n or "").strip()) or (_script(conv(n), SUP, "^") + "√" if n else "√")
out.append(root + _wrap(a))
elif name in _TEXT:
out.append(p.group_raw())
elif name in _STYLE:
out.append(conv(p.group_raw()))
elif name in _FONT:
arg = p.group_raw()
got = ""
if _L2T is not None:
try:
got = _L2T.latex_to_text("\\%s{%s}" % (name, arg)).strip()
except Exception:
got = ""
out.append(got or conv(arg))
elif name in _ACCENT:
arg = conv(p.group_raw()).strip()
mark = {"hat": "\u0302", "widehat": "\u0302", "bar": "\u0304", "vec": "\u20d7", "dot": "\u0307",
"ddot": "\u0308", "tilde": "\u0303", "widetilde": "\u0303", "acute": "\u0301", "grave": "\u0300",
"breve": "\u0306", "check": "\u030c"}[name]
out.append(arg + mark if len(arg) == 1 else arg)
elif name == "begin":
env = p.group_raw().strip()
end = re.search(r"\\end\s*\{" + re.escape(env) + r"\}", p.s[p.i:])
body = p.s[p.i:p.i + end.start()] if end else p.s[p.i:]
p.i = p.i + end.end() if end else len(p.s)
out.append(_env(env, body))
elif name == "end":
p.group_raw()
elif name in ("pmod", "pod"):
out.append(" (mod " + conv(p.group_raw()).strip() + ")")
elif name in ("bmod", "mod"):
out.append(" mod ")
elif name in _OPS:
out.append(" " + _OPS[name] + " ")
elif name in _FUNCS:
out.append(name + " ")
elif name in _SYM:
out.append(_SYM[name] + (" " if name in ("sum", "prod", "int", "iint", "oint") else ""))
if name.isalpha():
_i0 = p.i
p.skip_ws() # LaTeX 吃掉指令後面的空白:\pi r → πr
if p.i > _i0 and p.peek() and p.peek() in "=<>+-|,;:)]":
out.append(" ") # \Delta = 0 → Δ = 0(不是 Δ= 0)
elif name in ("not",):
nxt = p.macro() if p.peek() == "\\" else p.group_raw()
out.append(" " + {"=": "≠", "in": "∉", "subset": "⊄", "equiv": "≢"}.get(nxt, "¬" + nxt) + " ")
elif name in ("label", "tag", "hspace", "vspace", "phantom", "hphantom", "vphantom"):
p.group_raw()
else:
out.append(_lookup(name))
if name.isalpha():
p.skip_ws()
s = "".join(out)
s = _FUNC_PAREN.sub(r"\1", s) # \min(a,b) → min(a,b)(以前 min (a,b))
s = re.sub(r"[ \t]{2,}", " ", s)
s = re.sub(r"\(\s+", "(", s)
s = re.sub(r"\s+\)", ")", s)
return s.strip(" ") if "\n" not in s else "\n".join(x.strip() for x in s.split("\n"))
def _md_safe(s: str) -> str:
"""轉出來的字串裡的 * 與 _ 會被 Discord 當粗體/斜體 → 跳脫。"""
return s.replace("*", "\\*").replace("_", "\\_")
# 行內 $…$:照 pandoc 的規則認,價錢不會被當成數學——開頭 $ 後面不能是空白、結尾 $ 前面不能是空白、後面不能接數字
_INLINE = re.compile(r"(?<![\\$\w])\$(?!\s)([^$\n]{1,400}?)(?<![\s\\])\$(?![\d$])")
_DISPLAY = re.compile(r"\$\$(.+?)\$\$|\\\[(.+?)\\\]", re.S)
_PAREN = re.compile(r"\\\((.+?)\\\)")
_CODE = re.compile(r"```.*?(?:```|\Z)|`[^`\n]+`", re.S)
_HTML = re.compile(r"<!doctype|<html|<script|<body", re.I)
def _looks_math(x: str) -> bool:
"""$…$ 裡面看起來是數學才轉(有 LaTeX 指令、上下標、大括號,或只有數字字母和運算符號)。"""
if re.search(r"[\\^_{}]", x):
return True
return bool(re.fullmatch(r"[\w\s+\-*/=().,<>|!′'−\[\]~;:]+", x)) and not re.search(r"[\u4e00-\u9fff]", x)
_LOG: List[str] = [] # 這一則轉了哪些段(format_math 結束時印幾段,排查「轉壞了」用)
def _c(src: str) -> str:
out = _md_safe(conv(src))
if len(_LOG) < 6:
_LOG.append(f"{src[:70]!r}→{out[:70]!r}")
return out
def _fmt_plain(seg: str) -> str:
def disp(m: "re.Match") -> str:
body = m.group(1) if m.group(1) is not None else m.group(2)
return _c(body)
seg = _DISPLAY.sub(disp, seg)
seg = _PAREN.sub(lambda m: _c(m.group(1)), seg)
return _INLINE.sub(lambda m: _c(m.group(1)) if _looks_math(m.group(1)) else m.group(0), seg)
def format_math(text: str) -> str:
"""整則回覆:程式碼區塊與行內程式碼原樣保留,其他地方的 $…$、$$…$$、\\(…\\)、\\[…\\] 轉成 Unicode 文字。
整份 HTML(/web 的網頁)不動。任何例外都回原文(排版失敗不能讓回覆不見)。"""
if not text or ("$" not in text and "\\(" not in text and "\\[" not in text) or _HTML.search(text):
return text
_LOG.clear()
try:
out, last = [], 0
for m in _CODE.finditer(text):
out.append(_fmt_plain(text[last:m.start()]))
out.append(m.group(0))
last = m.end()
out.append(_fmt_plain(text[last:]))
if _LOG:
print("數學式:" + ";".join(_LOG), flush=True)
return "".join(out)
except Exception as e:
print(f"數學式轉換失敗、送原文:{str(e)[:80]}", flush=True)
return text