"""用用户给的 13 条参考公式验证识别/预处理/渲染覆盖率。""" import io import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from PIL import Image # noqa: E402 from app.services import formula # noqa: E402 SAMPLES = [ ("1 欧拉恒等式", r"\[e^{i\pi} + 1 = 0\]"), ("2 高斯积分", r"\[\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}\]"), ("3 巴塞尔问题", r"\[\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}\]"), ("4 傅里叶变换", r"\[\hat{f}(\xi) = \int_{-\infty}^{\infty} f(x) e^{-2\pi i x \xi}\,dx\]"), ("5 质能方程", r"\[E = mc^2\]"), ("6 万有引力", r"\[F = G \frac{m_1 m_2}{r^2}\]"), ("7 薛定谔方程", "\\[i\\hbar \\frac{\\partial}{\\partial t}\\Psi(\\mathbf{r},t)\n" "= -\\frac{\\hbar^2}{2m}\\nabla^2 \\Psi(\\mathbf{r},t)\n" "+ V(\\mathbf{r},t)\\Psi(\\mathbf{r},t)\\]"), ("8 麦克斯韦方程组", "\\[\\begin{aligned}\n\\nabla \\cdot \\mathbf{E} &= \\frac{\\rho}{\\varepsilon_0}, &\n" "\\nabla \\cdot \\mathbf{B} &= 0, \\\\\n\\nabla \\times \\mathbf{E} &= -\\frac{\\partial \\mathbf{B}}{\\partial t}, &\n" "\\nabla \\times \\mathbf{B} &= \\mu_0 \\mathbf{J}\n+ \\mu_0 \\varepsilon_0 \\frac{\\partial \\mathbf{E}}{\\partial t}.\n\\end{aligned}\\]"), ("9 热力学第一定律", r"\[\Delta U = Q - W\]"), ("10 氢气燃烧", r"\[\ce{2H2 + O2 -> 2H2O}\]"), ("11 合成氨", r"\[\ce{N2(g) + 3H2(g) <=> 2NH3(g)} \qquad \Delta H < 0\]"), ("12 平衡常数", r"\[K_c = \frac{[\ce{NH3}]^2}{[\ce{N2}][\ce{H2}]^3}\]"), ("13 理想气体", r"\[PV = nRT\]"), ] # 端上识别(JS)会先把分隔符剥掉,这里模拟同样的输入 def strip_delim(s): t = s.strip() for a, b in (("\\[", "\\]"), ("$$", "$$"), ("\\(", "\\)")): if t.startswith(a) and t.endswith(b): return t[len(a):len(t) - len(b)].strip() return t ok = bad = 0 for name, raw in SAMPLES: body = strip_delim(raw) lines = formula.normalize_latex(body) info = formula.render(body, fs=16) if info: ok += 1 img = Image.open(io.BytesIO(info["png"])) print("[OK ] %-16s %d 行 png=%dx%d design=%sx%s %5dB %s" % ( name, len(lines or []), img.size[0], img.size[1], info["w"], info["h"], info["bytes"], img.mode)) with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "_ref_%s.png" % name.split()[0]), "wb") as fp: fp.write(info["png"]) else: bad += 1 print("[FAIL] %-16s %s" % (name, "normalize 返回 None" if not lines else "渲染失败")) print("\n合计 %d 条:成功 %d / 失败 %d" % (len(SAMPLES), ok, bad))