mathtran 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. mathtran/__init__.py +0 -0
  2. mathtran/cli.py +119 -0
  3. mathtran/core/__init__.py +0 -0
  4. mathtran/core/batch.py +81 -0
  5. mathtran/core/cache.py +127 -0
  6. mathtran/core/config.py +89 -0
  7. mathtran/core/i18n.py +134 -0
  8. mathtran/core/ocr.py +122 -0
  9. mathtran/core/render.py +168 -0
  10. mathtran/desktop.py +135 -0
  11. mathtran/icon.icns +0 -0
  12. mathtran/icon.ico +0 -0
  13. mathtran/selftest.py +107 -0
  14. mathtran/server.py +194 -0
  15. mathtran/web/icon.svg +21 -0
  16. mathtran/web/index.html +1007 -0
  17. mathtran/web/vendor/LICENSE-KaTeX.txt +21 -0
  18. mathtran/web/vendor/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  19. mathtran/web/vendor/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  20. mathtran/web/vendor/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  21. mathtran/web/vendor/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  22. mathtran/web/vendor/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  23. mathtran/web/vendor/fonts/KaTeX_Main-Bold.woff2 +0 -0
  24. mathtran/web/vendor/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  25. mathtran/web/vendor/fonts/KaTeX_Main-Italic.woff2 +0 -0
  26. mathtran/web/vendor/fonts/KaTeX_Main-Regular.woff2 +0 -0
  27. mathtran/web/vendor/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  28. mathtran/web/vendor/fonts/KaTeX_Math-Italic.woff2 +0 -0
  29. mathtran/web/vendor/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  30. mathtran/web/vendor/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  31. mathtran/web/vendor/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  32. mathtran/web/vendor/fonts/KaTeX_Script-Regular.woff2 +0 -0
  33. mathtran/web/vendor/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  34. mathtran/web/vendor/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  35. mathtran/web/vendor/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  36. mathtran/web/vendor/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  37. mathtran/web/vendor/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  38. mathtran/web/vendor/katex.min.css +1 -0
  39. mathtran/web/vendor/katex.min.js +1 -0
  40. mathtran-0.1.0.dist-info/METADATA +321 -0
  41. mathtran-0.1.0.dist-info/RECORD +45 -0
  42. mathtran-0.1.0.dist-info/WHEEL +4 -0
  43. mathtran-0.1.0.dist-info/entry_points.txt +3 -0
  44. mathtran-0.1.0.dist-info/licenses/LICENSE +675 -0
  45. mathtran-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +35 -0
@@ -0,0 +1,168 @@
1
+ """LaTeX 公式 → PDF / SVG(使用 tectonic 編譯)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import sys
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ import pymupdf
14
+
15
+ from .i18n import tr
16
+
17
+ TEMPLATE = r"""\documentclass[border=4pt,varwidth=true]{standalone}
18
+ \usepackage{amsmath,amssymb,amsfonts,mathtools}
19
+ %s\begin{document}
20
+ %s
21
+ \end{document}
22
+ """
23
+
24
+ _CJK_RE = re.compile(r"[\u2e80-\u9fff\uf900-\ufaff\uff00-\uffef\u3000-\u303f]")
25
+
26
+ # tectonic 以字型名稱向系統查詢(用檔案路徑會失敗),依平台選預設 CJK 字型
27
+ _CJK_FONTS = {
28
+ "win32": "Microsoft JhengHei",
29
+ "darwin": "PingFang TC",
30
+ }
31
+
32
+
33
+ def cjk_font() -> str:
34
+ return os.environ.get("MATHTRAN_CJK_FONT") or _CJK_FONTS.get(sys.platform, "Noto Sans CJK TC")
35
+
36
+
37
+ _CJK_RUN_RE = re.compile(r"[\u2e80-\u9fff\uf900-\ufaff\uff00-\uffef\u3000-\u303f]+")
38
+ _TEXT_CMD_RE = re.compile(r"\\(?:text\w*|mbox|hbox)\s*\{")
39
+
40
+
41
+ def _in_text_cmd(prefix: str) -> bool:
42
+ """prefix 結尾處是否仍在 \\text{...} 之類的大括號內。"""
43
+ last = None
44
+ for last in _TEXT_CMD_RE.finditer(prefix):
45
+ pass
46
+ if last is None:
47
+ return False
48
+ return prefix[last.end() :].count("{") - prefix[last.end() :].count("}") >= 0
49
+
50
+
51
+ def wrap_cjk_in_text(latex: str) -> str:
52
+ """數學模式不會畫中文:把不在 \\text{} 內的中日韓字元包進 \\text{}。"""
53
+
54
+ def repl(m: re.Match) -> str:
55
+ if _in_text_cmd(latex[: m.start()]):
56
+ return m.group(0)
57
+ return "\\text{" + m.group(0) + "}"
58
+
59
+ return _CJK_RUN_RE.sub(repl, latex)
60
+
61
+
62
+ def _preamble(latex: str) -> str:
63
+ """內容含中日韓字元時才載入 xeCJK,避免沒有必要的字型相依。"""
64
+ if _CJK_RE.search(latex):
65
+ return "\\usepackage{xeCJK}\n\\setCJKmainfont{%s}\n" % cjk_font()
66
+ return ""
67
+
68
+
69
+ # 這些環境自帶數學模式,不能再包 \[ \];pmatrix、aligned 等需要外層包裹
70
+ _STANDALONE_ENV = re.compile(
71
+ r"\\begin\{(equation|align|alignat|gather|multline|flalign|eqnarray|displaymath|math)\*?\}"
72
+ )
73
+
74
+
75
+ class RenderError(RuntimeError):
76
+ pass
77
+
78
+
79
+ def _tectonic_name() -> str:
80
+ return "tectonic.exe" if sys.platform == "win32" else "tectonic"
81
+
82
+
83
+ def bundled_tectonic() -> str | None:
84
+ """安裝包(PyInstaller 打包版)會把 tectonic 放在應用程式旁邊,優先使用它。
85
+
86
+ onedir 版本放在可執行檔所在資料夾(macOS .app 是 Contents/MacOS),
87
+ 也一併找 PyInstaller 的暫存根目錄 sys._MEIPASS。
88
+ """
89
+ if not getattr(sys, "frozen", False):
90
+ return None
91
+ roots = [Path(sys.executable).resolve().parent]
92
+ if getattr(sys, "_MEIPASS", None):
93
+ roots.append(Path(sys._MEIPASS))
94
+ for root in roots:
95
+ candidate = root / _tectonic_name()
96
+ if candidate.is_file():
97
+ return str(candidate)
98
+ return None
99
+
100
+
101
+ def find_tectonic() -> str:
102
+ """找 tectonic:環境變數 MATHTRAN_TECTONIC → 安裝包附帶的 → PATH。"""
103
+ override = os.environ.get("MATHTRAN_TECTONIC")
104
+ if override and Path(override).is_file():
105
+ return override
106
+ path = bundled_tectonic() or shutil.which("tectonic")
107
+ if not path:
108
+ raise RenderError(tr("tectonic_missing"))
109
+ return path
110
+
111
+
112
+ def tectonic_available() -> bool:
113
+ try:
114
+ find_tectonic()
115
+ return True
116
+ except RenderError:
117
+ return False
118
+
119
+
120
+ def wrap_latex(latex: str) -> str:
121
+ """把公式包成可編譯的文件內容;已含數學環境者原樣使用。"""
122
+ s = latex.strip()
123
+ if s.startswith(("$", r"\[", r"\(")) or _STANDALONE_ENV.match(s):
124
+ body = s
125
+ else:
126
+ body = "\\[\n" + s + "\n\\]"
127
+ body = wrap_cjk_in_text(body)
128
+ return TEMPLATE % (_preamble(body), body)
129
+
130
+
131
+ def to_tex(latex: str) -> str:
132
+ """輸出完整、可自行編譯的 .tex 文件(不需要 tectonic)。含中文時註明要用 XeLaTeX。"""
133
+ doc = wrap_latex(latex)
134
+ header = "% Generated by MathTran\n"
135
+ if "xeCJK" in doc:
136
+ header += tr("tex_cjk_note") + "\n"
137
+ return header + doc
138
+
139
+
140
+ def to_pdf(latex: str) -> bytes:
141
+ exe = find_tectonic()
142
+ with tempfile.TemporaryDirectory() as tmp:
143
+ tex = Path(tmp) / "formula.tex"
144
+ tex.write_text(wrap_latex(latex), encoding="utf-8")
145
+ proc = subprocess.run(
146
+ [exe, "-X", "compile", "--untrusted", "formula.tex"],
147
+ cwd=tmp,
148
+ capture_output=True,
149
+ text=True,
150
+ encoding="utf-8",
151
+ errors="replace",
152
+ )
153
+ pdf = Path(tmp) / "formula.pdf"
154
+ if proc.returncode != 0 or not pdf.exists():
155
+ msg = (proc.stderr or proc.stdout)[-1500:]
156
+ if "cannot be found" in msg and "xeCJK" in tex.read_text(encoding="utf-8"):
157
+ msg = tr("cjk_font_missing", font=cjk_font()) + msg
158
+ raise RenderError(tr("compile_failed", log=msg))
159
+ return pdf.read_bytes()
160
+
161
+
162
+ def pdf_to_svg(pdf: bytes) -> str:
163
+ with pymupdf.open(stream=pdf, filetype="pdf") as doc:
164
+ return doc[0].get_svg_image(text_as_path=True)
165
+
166
+
167
+ def to_svg(latex: str) -> str:
168
+ return pdf_to_svg(to_pdf(latex))
mathtran/desktop.py ADDED
@@ -0,0 +1,135 @@
1
+ """桌面 App:pywebview 視窗載入本機 FastAPI。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import io
7
+ import socket
8
+ import sys
9
+ import threading
10
+ import time
11
+ import zipfile
12
+ from pathlib import Path
13
+
14
+ import uvicorn
15
+ import webview
16
+
17
+ from .server import app
18
+
19
+
20
+ def _free_port() -> int:
21
+ with socket.socket() as s:
22
+ s.bind(("127.0.0.1", 0))
23
+ return s.getsockname()[1]
24
+
25
+
26
+ def _unique_path(path: Path) -> Path:
27
+ """檔案已存在就改成「名稱 (2).副檔名」,避免覆蓋使用者的檔案。"""
28
+ if not path.exists():
29
+ return path
30
+ n = 2
31
+ while (candidate := path.with_name(f"{path.stem} ({n}){path.suffix}")).exists():
32
+ n += 1
33
+ return candidate
34
+
35
+
36
+ def extract_zip(data: bytes, folder: Path) -> list[str]:
37
+ """把 zip 內的檔案解到 folder,回傳實際寫入的檔名。
38
+
39
+ 只取檔名(避免 ../ 路徑穿越),已存在的檔案不覆蓋(改名為「名稱 (2)」)。
40
+ """
41
+ names = []
42
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
43
+ for member in zf.namelist():
44
+ name = Path(member).name
45
+ if not name:
46
+ continue
47
+ target = _unique_path(folder / name)
48
+ target.write_bytes(zf.read(member))
49
+ names.append(target.name)
50
+ return names
51
+
52
+
53
+ class Api:
54
+ """暴露給前端的桌面專用功能(pywebview 預設擋下載,所以改用另存新檔對話框)。
55
+
56
+ 注意:pywebview 會遞迴走訪這個物件所有「不以底線開頭」的屬性。
57
+ 若把 window 放成公開屬性,會走進 WinForms 原生控制項而間歇性卡死,
58
+ 所以必須用 _window。
59
+ """
60
+
61
+ def __init__(self) -> None:
62
+ self._window: webview.Window | None = None
63
+
64
+ def save_file(self, name: str, data_b64: str) -> str | None:
65
+ ext = Path(name).suffix.lstrip(".")
66
+ result = self._window.create_file_dialog(
67
+ webview.FileDialog.SAVE,
68
+ save_filename=name,
69
+ file_types=(f"{ext.upper()} (*.{ext})",),
70
+ )
71
+ if not result:
72
+ return None
73
+ path = Path(result if isinstance(result, str) else result[0])
74
+ path.write_bytes(base64.b64decode(data_b64))
75
+ return str(path)
76
+
77
+ def save_zip_to_folder(self, zip_b64: str) -> dict | None:
78
+ """批次匯出:讓使用者選資料夾,把 zip 內的檔案解開放進去(不覆蓋既有檔案)。"""
79
+ result = self._window.create_file_dialog(webview.FileDialog.FOLDER)
80
+ if not result:
81
+ return None
82
+ folder = Path(result if isinstance(result, str) else result[0])
83
+ names = extract_zip(base64.b64decode(zip_b64), folder)
84
+ return {"dir": str(folder), "count": len(names), "names": names}
85
+
86
+
87
+ TITLE = "MathTran"
88
+ ICON_PATH = Path(__file__).parent / "icon.ico"
89
+
90
+
91
+ def _set_window_icon() -> None:
92
+ """Windows:把標題列與工作列圖示換成 icon.ico(pywebview 沒有提供此參數)。"""
93
+ if sys.platform != "win32":
94
+ return
95
+ import ctypes
96
+
97
+ user32 = ctypes.windll.user32
98
+ user32.FindWindowW.restype = ctypes.c_void_p
99
+ user32.LoadImageW.restype = ctypes.c_void_p
100
+ user32.SendMessageW.argtypes = [
101
+ ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p,
102
+ ]
103
+ hwnd = None
104
+ for _ in range(50): # 等視窗建立,最多約 5 秒
105
+ hwnd = user32.FindWindowW(None, TITLE)
106
+ if hwnd:
107
+ break
108
+ time.sleep(0.1)
109
+ if not hwnd:
110
+ return
111
+ IMAGE_ICON, LR_LOADFROMFILE, WM_SETICON = 1, 0x10, 0x80
112
+ for kind, px in ((0, 16), (1, 32)): # ICON_SMALL, ICON_BIG
113
+ h = user32.LoadImageW(None, str(ICON_PATH), IMAGE_ICON, px, px, LR_LOADFROMFILE)
114
+ if h:
115
+ user32.SendMessageW(hwnd, WM_SETICON, kind, h)
116
+
117
+
118
+ def main() -> None:
119
+ port = _free_port()
120
+ server = uvicorn.Server(
121
+ uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning")
122
+ )
123
+ threading.Thread(target=server.run, daemon=True).start()
124
+ while not server.started:
125
+ time.sleep(0.05)
126
+ api = Api()
127
+ api._window = webview.create_window(
128
+ TITLE, f"http://127.0.0.1:{port}", width=1100, height=720, js_api=api
129
+ )
130
+ webview.start(_set_window_icon)
131
+ server.should_exit = True
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
mathtran/icon.icns ADDED
Binary file
mathtran/icon.ico ADDED
Binary file
mathtran/selftest.py ADDED
@@ -0,0 +1,107 @@
1
+ """打包版的自我檢查(給 CI 用):不開視窗,啟動內建伺服器並檢查主要功能。
2
+
3
+ 用法:
4
+ MATHTRAN_SELFTEST=<結果檔路徑> MathTran(.exe) # 打包版(packaging/app_entry.py 會呼叫)
5
+ uv run python -m mathtran.selftest <結果檔路徑> # 開發環境
6
+
7
+ 打包版在 Windows 是「無主控台」的程式,標準輸出看不到,所以結果寫進檔案(JSON),
8
+ 結束代碼 0 表示全部通過、1 表示有失敗。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import sys
15
+ import threading
16
+ import time
17
+ import urllib.error
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+
22
+ def _call(base: str, path: str, body: dict | None = None, timeout: int = 600) -> tuple[int, bytes]:
23
+ req = urllib.request.Request(
24
+ base + path,
25
+ data=json.dumps(body).encode() if body is not None else None,
26
+ headers={"Content-Type": "application/json", "X-Lang": "en"},
27
+ method="POST" if body is not None else "GET",
28
+ )
29
+ try:
30
+ with urllib.request.urlopen(req, timeout=timeout) as r: # 第一次編譯 tectonic 要下載套件,可能很久
31
+ return r.status, r.read()
32
+ except urllib.error.HTTPError as e:
33
+ return e.code, e.read()
34
+
35
+
36
+ def run(result_path: str | Path) -> int:
37
+ import uvicorn
38
+
39
+ from .core import render
40
+ from .desktop import _free_port
41
+ from .server import app
42
+
43
+ frozen = bool(getattr(sys, "frozen", False))
44
+ results: dict[str, object] = {}
45
+
46
+ def check(name: str, ok: bool, detail: str = "") -> None:
47
+ results[name] = {"ok": bool(ok), **({"detail": detail} if detail else {})}
48
+
49
+ port = _free_port()
50
+ server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
51
+ threading.Thread(target=server.run, daemon=True).start()
52
+ t0 = time.time()
53
+ while not server.started and time.time() - t0 < 30:
54
+ time.sleep(0.05)
55
+ base = f"http://127.0.0.1:{port}"
56
+ try:
57
+ check("server_started", server.started)
58
+
59
+ code, body = _call(base, "/api/health")
60
+ health = json.loads(body) if code == 200 else {}
61
+ check("health", code == 200 and health.get("tectonic") is True, f"HTTP {code} {health}")
62
+ if frozen: # 打包版必須用安裝包附帶的 tectonic,不能靠系統上剛好有裝
63
+ check("bundled_tectonic", render.bundled_tectonic() is not None, str(render.bundled_tectonic()))
64
+
65
+ code, body = _call(base, "/")
66
+ check("index_page", code == 200 and b"MathTran" in body and b'id="toolbar"' in body, f"HTTP {code}")
67
+ for path in ("/vendor/katex.min.js", "/vendor/katex.min.css",
68
+ "/vendor/fonts/KaTeX_Main-Regular.woff2", "/icon.svg"):
69
+ code, body = _call(base, path)
70
+ check(f"asset {path}", code == 200 and len(body) > 100, f"HTTP {code}")
71
+
72
+ code, body = _call(base, "/api/settings")
73
+ check("settings", code == 200 and {"lang", "theme", "thumb", "formats"} <= set(json.loads(body)), f"HTTP {code}")
74
+
75
+ code, body = _call(base, "/api/export/svg", {"latex": r"\int_0^1 x^2\,dx=\frac13"})
76
+ check("export_svg", code == 200 and b"<svg" in body, f"HTTP {code} {body[:120]!r}" if code != 200 else "")
77
+ code, body = _call(base, "/api/export/pdf", {"latex": r"\frac{a}{b}"})
78
+ check("export_pdf", code == 200 and body.startswith(b"%PDF"), f"HTTP {code}")
79
+ code, body = _call(base, "/api/export/tex", {"latex": "x^2"})
80
+ check("export_tex", code == 200 and b"\\documentclass" in body, f"HTTP {code}")
81
+
82
+ # 中文公式需要系統上有中文字型;CI 的 Windows 機器可能沒有,所以「找不到字型」只標記為略過,不算失敗
83
+ code, body = _call(base, "/api/export/pdf", {"latex": "x=答案"})
84
+ if code == 200:
85
+ check("export_cjk_pdf", body.startswith(b"%PDF"))
86
+ elif b"CJK font" in body:
87
+ results["export_cjk_pdf"] = {"ok": True, "skipped": "no CJK font installed on this machine"}
88
+ else:
89
+ check("export_cjk_pdf", False, f"HTTP {code} {body[:200]!r}")
90
+ except Exception as e: # 任何意外都記錄下來,不要讓自我檢查自己當掉
91
+ check("unexpected_error", False, repr(e))
92
+ finally:
93
+ server.should_exit = True
94
+
95
+ ok = all(v["ok"] for v in results.values())
96
+ Path(result_path).write_text(
97
+ json.dumps({"ok": ok, "frozen": frozen, "python": sys.version, "checks": results},
98
+ ensure_ascii=False, indent=2),
99
+ encoding="utf-8",
100
+ )
101
+ return 0 if ok else 1
102
+
103
+
104
+ if __name__ == "__main__":
105
+ if len(sys.argv) != 2:
106
+ raise SystemExit("用法:python -m mathtran.selftest <結果檔路徑>")
107
+ raise SystemExit(run(sys.argv[1]))
mathtran/server.py ADDED
@@ -0,0 +1,194 @@
1
+ """FastAPI 後端:提供 Web UI 與 OCR / 匯出 API。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ from fastapi import FastAPI, File, HTTPException, UploadFile
9
+ from fastapi.responses import FileResponse, Response
10
+ from fastapi.staticfiles import StaticFiles
11
+ from pydantic import BaseModel
12
+
13
+ from .core import batch, cache, config, i18n, ocr, render
14
+ from .core.i18n import tr
15
+
16
+ WEB_DIR = Path(__file__).parent / "web"
17
+
18
+ app = FastAPI(title="MathTran")
19
+
20
+
21
+ class LangMiddleware:
22
+ """讀取前端送來的 X-Lang 標頭(zh-TW / en),讓這個請求裡的錯誤訊息用該語言。
23
+
24
+ 寫成純 ASGI middleware(而不是 BaseHTTPMiddleware),contextvar 才能正確傳到
25
+ FastAPI 在執行緒池裡跑的同步端點。
26
+ """
27
+
28
+ def __init__(self, app):
29
+ self.app = app
30
+
31
+ async def __call__(self, scope, receive, send):
32
+ token = None
33
+ if scope["type"] == "http":
34
+ for key, value in scope["headers"]:
35
+ if key == b"x-lang":
36
+ token = i18n.set_lang(value.decode("latin-1"))
37
+ break
38
+ try:
39
+ await self.app(scope, receive, send)
40
+ finally:
41
+ if token is not None:
42
+ i18n.reset_lang(token)
43
+
44
+
45
+ app.add_middleware(LangMiddleware)
46
+
47
+
48
+ class LatexIn(BaseModel):
49
+ latex: str
50
+
51
+
52
+ class SettingsIn(BaseModel):
53
+ lang: str | None = None
54
+ theme: str | None = None
55
+ thumb: int | None = None
56
+ formats: list[str] | None = None
57
+
58
+
59
+ @app.get("/api/settings")
60
+ def get_settings():
61
+ return config.get_settings()
62
+
63
+
64
+ @app.put("/api/settings")
65
+ def put_settings(body: SettingsIn):
66
+ """部分更新介面偏好(語系、配色、縮圖大小、匯出格式);任何一項不合法就整批拒絕。"""
67
+ try:
68
+ return config.update_settings(body.model_dump(exclude_none=True))
69
+ except ValueError as e:
70
+ raise HTTPException(400, tr("bad_setting", key=e))
71
+
72
+
73
+ class KeyIn(BaseModel):
74
+ api_key: str
75
+
76
+
77
+ @app.get("/api/health")
78
+ def health():
79
+ return {
80
+ "api_key": bool(config.get_api_key()),
81
+ "tectonic": render.tectonic_available(), # 含安裝包附帶的 tectonic
82
+ }
83
+
84
+
85
+ @app.post("/api/config")
86
+ def set_key(body: KeyIn):
87
+ config.save_api_key(body.api_key.strip())
88
+ return {"ok": True}
89
+
90
+
91
+ @app.post("/api/ocr")
92
+ def api_ocr(file: UploadFile = File(...), force: bool = False):
93
+ """同步端點(跑在執行緒池),批次辨識時才能真正並行。force=true 忽略快取。"""
94
+ data = file.file.read()
95
+ try:
96
+ r = ocr.recognize(data, use_cache=not force)
97
+ except ocr.OcrError as e:
98
+ raise HTTPException(400, str(e))
99
+ return {"latex": r.latex, "hash": r.hash, "cached": r.cached}
100
+
101
+
102
+ class LookupIn(BaseModel):
103
+ hashes: list[str]
104
+
105
+
106
+ class CachePutIn(BaseModel):
107
+ latex: str
108
+
109
+
110
+ @app.post("/api/cache/lookup")
111
+ def cache_lookup(body: LookupIn):
112
+ """回傳 {hash: {latex, edited}},只含命中的項目。"""
113
+ hits = cache.lookup(body.hashes, min_prompt=ocr.PROMPT_VERSION) # 過期的(舊提示詞)不回傳
114
+ return {h: {"latex": e["latex"], "edited": bool(e.get("edited"))} for h, e in hits.items()}
115
+
116
+
117
+ @app.get("/api/cache")
118
+ def cache_stats():
119
+ return cache.stats()
120
+
121
+
122
+ @app.delete("/api/cache")
123
+ def cache_clear():
124
+ """清除所有快取(含手動修改的結果)。"""
125
+ return {"removed": cache.clear()}
126
+
127
+
128
+ @app.post("/api/cache/remove")
129
+ def cache_remove(body: LookupIn):
130
+ """只清除指定圖片(雜湊)的快取。"""
131
+ return {"removed": cache.remove(body.hashes)}
132
+
133
+
134
+ @app.put("/api/cache/{h}")
135
+ def cache_put(h: str, body: CachePutIn):
136
+ """使用者手動修改 LaTeX 後存回快取(標記為 edited)。"""
137
+ if not re.fullmatch(r"[0-9a-f]{64}", h):
138
+ raise HTTPException(400, tr("bad_hash"))
139
+ cache.put(h, body.latex, edited=True)
140
+ return {"ok": True}
141
+
142
+
143
+ class BatchItem(BaseModel):
144
+ name: str
145
+ latex: str
146
+
147
+
148
+ class BatchIn(BaseModel):
149
+ formats: list[str]
150
+ items: list[BatchItem]
151
+
152
+
153
+ @app.post("/api/export/batch") # 必須在 /api/export/{fmt} 之前註冊
154
+ def api_export_batch(body: BatchIn):
155
+ if not body.formats or any(f not in batch.FORMATS for f in body.formats):
156
+ raise HTTPException(400, tr("bad_formats"))
157
+ if not body.items:
158
+ raise HTTPException(400, tr("no_items"))
159
+ r = batch.export_zip([i.model_dump() for i in body.items], body.formats)
160
+ if r.ok == 0:
161
+ raise HTTPException(400, tr("all_failed", details="\n".join(r.errors)[:1500]))
162
+ return Response(
163
+ r.data,
164
+ media_type="application/zip",
165
+ headers={"X-Ok-Count": str(r.ok), "X-Fail-Count": str(r.failed)},
166
+ )
167
+
168
+
169
+ @app.post("/api/export/{fmt}")
170
+ def api_export(fmt: str, body: LatexIn):
171
+ if fmt not in batch.FORMATS:
172
+ raise HTTPException(404, tr("bad_fmt"))
173
+ if fmt == "tex":
174
+ return Response(render.to_tex(body.latex), media_type="text/plain; charset=utf-8")
175
+ try:
176
+ pdf = render.to_pdf(body.latex)
177
+ except render.RenderError as e:
178
+ raise HTTPException(400, str(e))
179
+ if fmt == "pdf":
180
+ return Response(pdf, media_type="application/pdf")
181
+ return Response(render.pdf_to_svg(pdf), media_type="image/svg+xml")
182
+
183
+
184
+ @app.get("/")
185
+ def index():
186
+ return FileResponse(WEB_DIR / "index.html")
187
+
188
+
189
+ @app.get("/icon.svg")
190
+ def icon():
191
+ return FileResponse(WEB_DIR / "icon.svg", media_type="image/svg+xml")
192
+
193
+
194
+ app.mount("/vendor", StaticFiles(directory=WEB_DIR / "vendor"), name="vendor")
mathtran/web/icon.svg ADDED
@@ -0,0 +1,21 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" width="256" height="256" viewBox="0 0 256 256">
2
+ <defs>
3
+ <path id="font_1_71" d="M.32798768 .44898988H.23599243L.2539978 .519989C.2789917 .61898806 .30899049 .6689911 .34498597 .6689911 .35499574 .6689911 .3619995 .6639862 .3619995 .6559906 .3619995 .6529999 .36099244 .651001 .35699464 .644989 .34899903 .6329956 .34599305 .6239929 .34599305 .6139984 .34599305 .58599856 .36698915 .5649872 .394989 .5649872 .4249878 .5649872 .44599916 .58699038 .44599916 .6179962 .44599916 .6669922 .4079895 .69799807 .34700013 .69799807 .29499818 .69799807 .24598694 .6759949 .21099854 .6369934 .16899109 .59098818 .1499939 .5499878 .12098694 .44898988H.04798889L.038986207 .40699769H.11199951C.06399536 .19699097 .0289917 .038986207 .023986817 .01499939-.007003784-.13301087-.026000977-.17401123-.06600952-.17401123-.07600403-.17401123-.08401489-.16900635-.08401489-.16300965-.08401489-.16101074-.08200073-.15800476-.08000183-.15400696-.072006229-.14201355-.06800842-.13101197-.06800842-.120010379-.06800842-.0960083-.0920105-.072006229-.118011478-.072006229-.14500427-.072006229-.16900635-.09701538-.16900635-.12600708-.16900635-.17401123-.13000489-.20500183-.070007327-.20500183-.028015137-.20500183 .008987427-.19100952 .039993287-.16200257 .07998657-.12600708 .10699463-.073013309 .13999939 .02999878 .1639862 .10899353 .1749878 .15499878 .22898865 .40699769H.31900025L.32798768 .44898988Z"/>
4
+ <path id="font_1_9" d="M.32598878 .68499758C.17399597 .57299807 .11399841 .5079956 .067993167 .4039917 .040985109 .34399415 .027999878 .2789917 .027999878 .20698548 .027999878 .069992069 .068984989-.041000368 .16999817-.17900086L.19299317-.16400147C.13798523-.06700134 .12199402-.006011963 .12199402 .10998535 .12199402 .23799134 .14698792 .36698915 .18998719 .46299745 .22599793 .54299929 .2630005 .59098818 .34399415 .6649933L.32598878 .68499758Z"/>
5
+ <path id="font_1_89" d="M.3999939 .12298584C.36099244 .07299805 .35099793 .06399536 .33299256 .06399536 .31399537 .06399536 .3039856 .07798767 .29599 .116989139L.2639923 .272995C.2669983 .2769928 .2679901 .2789917 .272995 .28599549 .30799867 .34399415 .33299256 .36799623 .35598756 .36799623 .3619995 .36799623 .36898805 .36499024 .3809967 .35899354 .394989 .34999085 .4019928 .34799195 .41299439 .34799195 .44299317 .34799195 .46899415 .37199403 .46899415 .40098573 .46899415 .43299867 .44198609 .46199037 .41099549 .46199037 .3639984 .46199037 .33299256 .43499757 .25299073 .32398988 .23498535 .41099549 .22698975 .43499757 .20799256 .46199037L.040985109 .43798829V.41099549C.05899048 .41299439 .06599426 .41299439 .07598877 .41299439 .10798645 .41299439 .12199402 .394989 .13198853 .34599305L.1619873 .19198609 .117996219 .12199402C.09799194 .08898926 .08799744 .08099365 .069992069 .08099365 .06399536 .08099365 .05899048 .08299255 .04899597 .08898926 .032989503 .09799194 .021987915 .101989749 .008987427 .101989749-.022003174 .101989749-.04600525 .07798767-.04600525 .04598999-.04600525 .010986328-.020004273-.013000488 .017990113-.013000488 .067993167-.013000488 .08999634 .0069885256 .14898682 .102996829L.17298889 .14199829C.19499207 .026992798 .21998596-.013000488 .269989-.013000488 .31799317-.013000488 .3600006 .020996094 .42099 .10899353L.3999939 .12298584Z"/>
6
+ <path id="font_1_10" d="M-.027008057-.17900086C.09098816-.09500122 .14099121-.04600525 .19198609 .032989503 .24499512 .11399841 .2709961 .20199585 .2709961 .29899598 .2709961 .37298585 .25498963 .45098878 .22399903 .5249939 .20098877 .5799866 .17999268 .6139984 .12799073 .68499758L.10499573 .66999819C.15899658 .5799866 .1769867 .5130005 .1769867 .39898683 .1769867 .2659912 .14498902 .11399841 .09498596 .01399231 .06298828-.05000305 .03199768-.08900452-.044006349-.15901184L-.027008057-.17900086Z"/>
7
+ <path id="font_2_49" d="M.22599793 .2599945H.41299439C.5469971 .2599945 .6329956 .35499574 .6329956 .5029907 .6329956 .6489868 .5499878 .72898867 .397995 .72898867H.07598877V0H.22599793V.2599945M.22599793 .3849945V.60398867H.3659973C.44599916 .60398867 .48298646 .56900027 .48298646 .49499513 .48298646 .41999818 .44599916 .3849945 .3659973 .3849945H.22599793Z"/>
8
+ <path id="font_2_37" d="M.07699585 0H.3619995C.47299195 0 .54299929 .025985718 .59298709 .084991458 .6499939 .15299988 .68099978 .25099183 .68099978 .36499024 .68099978 .47799684 .6499939 .57598879 .59298709 .644989 .54299929 .70399478 .47399903 .72898867 .3619995 .72898867H.07699585V0M.22698975 .125V.60398867H.3619995C.47499085 .60398867 .5309906 .5249939 .5309906 .3639984 .5309906 .20399475 .47499085 .125 .3619995 .125H.22698975Z"/>
9
+ <path id="font_2_39" d="M.22399903 .31399537H.54299929V.43899537H.22399903V.60398867H.58599856V.72898867H.07398987V0H.22399903V.31399537Z"/>
10
+ </defs>
11
+ <path transform="matrix(1,0,0,-1,0,256)" stroke-width="10" stroke-linecap="butt" stroke-miterlimit="10" stroke-linejoin="miter" fill="none" stroke="#2e70ed" d="M12 217.6V150.4C12 135.81967 23.81968 124 38.4 124H151.6C166.18032 124 178 135.81967 178 150.4V217.6C178 232.18032 166.18032 244 151.6 244H38.4C23.81968 244 12 232.18032 12 217.6Z"/>
12
+ <use data-text="f" xlink:href="#font_1_71" transform="matrix(78,0,0,-78,36.538999,90)" fill="#2e70ed"/>
13
+ <use data-text="(" xlink:href="#font_1_9" transform="matrix(78,0,0,-78,62.513,90)" fill="#2e70ed"/>
14
+ <use data-text="x" xlink:href="#font_1_89" transform="matrix(78,0,0,-78,88.487,90)" fill="#2e70ed"/>
15
+ <use data-text=")" xlink:href="#font_1_10" transform="matrix(78,0,0,-78,127.487,90)" fill="#2e70ed"/>
16
+ <path transform="matrix(1,0,0,-1,0,256)" d="M78 126.72V57.28C78 42.21367 90.21367 30 105.28 30H216.72C231.78633 30 244 42.21367 244 57.28V126.72C244 141.78633 231.78633 154 216.72 154H105.28C90.21367 154 78 141.78633 78 126.72Z" fill="#e63836"/>
17
+ <path transform="matrix(1,0,0,-1,0,256)" stroke-width="6" stroke-linecap="butt" stroke-miterlimit="10" stroke-linejoin="miter" fill="none" stroke="#ffffff" d="M78 126.72V57.28C78 42.21367 90.21367 30 105.28 30H216.72C231.78633 30 244 42.21367 244 57.28V126.72C244 141.78633 231.78633 154 216.72 154H105.28C90.21367 154 78 141.78633 78 126.72Z"/>
18
+ <use data-text="P" xlink:href="#font_2_49" transform="matrix(54,0,0,-54,107,183.44)" fill="#ffffff"/>
19
+ <use data-text="D" xlink:href="#font_2_37" transform="matrix(54,0,0,-54,143.018,183.44)" fill="#ffffff"/>
20
+ <use data-text="F" xlink:href="#font_2_39" transform="matrix(54,0,0,-54,182.00601,183.44)" fill="#ffffff"/>
21
+ </svg>