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
mathtran/__init__.py ADDED
File without changes
mathtran/cli.py ADDED
@@ -0,0 +1,119 @@
1
+ """mathtran 命令列介面。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import typer
10
+
11
+ from .core import config, ocr, render
12
+ from .core.i18n import tr
13
+
14
+ app = typer.Typer(help="MathTran:圖片數學公式 → LaTeX,並匯出 SVG / PDF / LaTeX", no_args_is_help=True)
15
+
16
+
17
+ def _fail(e: Exception):
18
+ typer.secho(str(e), fg="red", err=True)
19
+ raise typer.Exit(1)
20
+
21
+
22
+ def _write(path: Path, latex: str):
23
+ ext = path.suffix.lower()
24
+ try:
25
+ if ext == ".pdf":
26
+ path.write_bytes(render.to_pdf(latex))
27
+ elif ext == ".svg":
28
+ path.write_text(render.to_svg(latex), encoding="utf-8")
29
+ else:
30
+ raise typer.BadParameter(tr("bad_ext"))
31
+ except render.RenderError as e:
32
+ _fail(e)
33
+ typer.echo(tr("out_written", path=path), err=True)
34
+
35
+
36
+ NO_CACHE = typer.Option(False, "--no-cache", help="忽略辨識快取,強制重新辨識")
37
+
38
+
39
+ @app.command("ocr")
40
+ def ocr_cmd(
41
+ image: Path = typer.Argument(..., exists=True, help="圖片路徑"),
42
+ no_cache: bool = NO_CACHE,
43
+ ):
44
+ """圖片 → 印出 LaTeX(辨識過的圖片會直接使用快取)。"""
45
+ try:
46
+ typer.echo(ocr.image_to_latex(image.read_bytes(), use_cache=not no_cache))
47
+ except ocr.OcrError as e:
48
+ _fail(e)
49
+
50
+
51
+ @app.command("cache")
52
+ def cache_cmd(clear: bool = typer.Option(False, "--clear", help="清除所有快取")):
53
+ """查看或清除辨識快取。"""
54
+ from .core import cache
55
+
56
+ if clear:
57
+ typer.echo(tr("cache_cleared", n=cache.clear()))
58
+ else:
59
+ s = cache.stats()
60
+ typer.echo(tr("cache_stats", count=s["count"], edited=s["edited"], kb=f"{s['bytes'] / 1024:.1f}", path=s["path"]))
61
+
62
+
63
+ @app.command("render")
64
+ def render_cmd(
65
+ latex: str = typer.Argument(..., help='LaTeX 公式,"-" 表示從 stdin 讀取'),
66
+ output: Path = typer.Option(..., "-o", "--output", help=".svg 或 .pdf"),
67
+ ):
68
+ """LaTeX → SVG / PDF。"""
69
+ _write(output, sys.stdin.read() if latex == "-" else latex)
70
+
71
+
72
+ @app.command("convert")
73
+ def convert_cmd(
74
+ image: Path = typer.Argument(..., exists=True),
75
+ output: Path = typer.Option(..., "-o", "--output", help=".svg 或 .pdf"),
76
+ no_cache: bool = NO_CACHE,
77
+ ):
78
+ """圖片 → LaTeX → SVG / PDF(一步完成)。"""
79
+ try:
80
+ latex = ocr.image_to_latex(image.read_bytes(), use_cache=not no_cache)
81
+ except ocr.OcrError as e:
82
+ _fail(e)
83
+ typer.echo(latex)
84
+ _write(output, latex)
85
+
86
+
87
+ @app.command("config")
88
+ def config_cmd(api_key: Optional[str] = typer.Option(None, "--api-key")):
89
+ """儲存 Anthropic API key。"""
90
+ if api_key:
91
+ config.save_api_key(api_key)
92
+ typer.echo(tr("config_saved", path=config.CONFIG_PATH))
93
+ else:
94
+ typer.echo(tr("key_set" if config.get_api_key() else "key_unset"))
95
+
96
+
97
+ @app.command("serve")
98
+ def serve_cmd(port: int = 8765, open_browser: bool = typer.Option(True, "--open/--no-open")):
99
+ """啟動 Web 介面。"""
100
+ import threading
101
+ import webbrowser
102
+
103
+ import uvicorn
104
+
105
+ if open_browser:
106
+ threading.Timer(1.0, lambda: webbrowser.open(f"http://127.0.0.1:{port}")).start()
107
+ uvicorn.run("mathtran.server:app", host="127.0.0.1", port=port, log_level="warning")
108
+
109
+
110
+ @app.command("gui")
111
+ def gui_cmd():
112
+ """啟動桌面視窗。"""
113
+ from .desktop import main
114
+
115
+ main()
116
+
117
+
118
+ if __name__ == "__main__":
119
+ app()
File without changes
mathtran/core/batch.py ADDED
@@ -0,0 +1,81 @@
1
+ """批次匯出:多個公式 × 多種格式 → 一個 zip。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import re
7
+ import zipfile
8
+ from dataclasses import dataclass, field
9
+
10
+ from . import render
11
+ from .i18n import tr
12
+
13
+ FORMATS = ("svg", "pdf", "tex")
14
+
15
+ _ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
16
+ _IMAGE_EXT = re.compile(r"\.(png|jpe?g|webp|gif|bmp)$", re.I)
17
+
18
+
19
+ def safe_stem(name: str, fallback: str = "formula") -> str:
20
+ """從圖檔名(可能含資料夾路徑)產生安全的檔名主體。"""
21
+ base = re.split(r"[\\/]", name.strip())[-1]
22
+ base = _IMAGE_EXT.sub("", base)
23
+ base = _ILLEGAL.sub("_", base).strip(" .")
24
+ return base[:80] or fallback
25
+
26
+
27
+ def unique_stems(stems: list[str]) -> list[str]:
28
+ """同名時加上 _2、_3…,比對時不分大小寫(Windows 檔名不分大小寫)。"""
29
+ seen: dict[str, int] = {}
30
+ out = []
31
+ for stem in stems:
32
+ key = stem.lower()
33
+ seen[key] = seen.get(key, 0) + 1
34
+ out.append(stem if seen[key] == 1 else f"{stem}_{seen[key]}")
35
+ return out
36
+
37
+
38
+ @dataclass
39
+ class BatchResult:
40
+ data: bytes
41
+ ok: int # 成功寫入的檔案數
42
+ failed: int # 失敗(或略過)的項目數
43
+ errors: list[str] = field(default_factory=list)
44
+
45
+
46
+ def export_zip(items: list[dict], formats: list[str]) -> BatchResult:
47
+ """items: [{"name": 圖檔名, "latex": LaTeX}];formats: svg / pdf / tex 的任意組合。
48
+
49
+ 每個項目最多編譯一次(svg 與 pdf 共用同一份 PDF)。個別失敗不會中斷整批:
50
+ 失敗原因寫進 zip 內的 errors.txt。純 tex 不需要 tectonic。
51
+ """
52
+ formats = [f for f in dict.fromkeys(formats)] # 去重、保留順序
53
+ if not formats or any(f not in FORMATS for f in formats):
54
+ raise ValueError("formats 必須是 svg / pdf / tex 的非空組合")
55
+ stems = unique_stems([safe_stem(it.get("name", "")) for it in items])
56
+ buf = io.BytesIO()
57
+ ok, errors = 0, []
58
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
59
+ for item, stem in zip(items, stems):
60
+ latex = (item.get("latex") or "").strip()
61
+ if not latex:
62
+ errors.append(tr("empty_skipped", name=stem))
63
+ continue
64
+ if "tex" in formats:
65
+ zf.writestr(f"{stem}.tex", render.to_tex(latex).encode("utf-8"))
66
+ ok += 1
67
+ if "pdf" in formats or "svg" in formats:
68
+ try:
69
+ pdf = render.to_pdf(latex)
70
+ except render.RenderError as e:
71
+ errors.append(f"{stem}: {e}")
72
+ continue
73
+ if "pdf" in formats:
74
+ zf.writestr(f"{stem}.pdf", pdf)
75
+ ok += 1
76
+ if "svg" in formats:
77
+ zf.writestr(f"{stem}.svg", render.pdf_to_svg(pdf).encode("utf-8"))
78
+ ok += 1
79
+ if errors:
80
+ zf.writestr("errors.txt", "\n\n".join(errors))
81
+ return BatchResult(buf.getvalue(), ok, len(errors), errors)
mathtran/core/cache.py ADDED
@@ -0,0 +1,127 @@
1
+ """辨識結果快取:以圖片內容的 SHA-256 為鍵,存在使用者目錄的 cache.json。
2
+
3
+ 只存 LaTeX 文字(以及模型名稱、是否被使用者手動修改),不存圖片本身。
4
+ CLI、網頁、桌面共用同一份快取。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from . import config
17
+
18
+ _lock = threading.Lock()
19
+
20
+
21
+ def cache_path() -> Path:
22
+ # 每次呼叫才計算,測試時可用 monkeypatch 改 config.CONFIG_PATH
23
+ return config.CONFIG_PATH.parent / "cache.json"
24
+
25
+
26
+ def sha256_hex(data: bytes) -> str:
27
+ return hashlib.sha256(data).hexdigest()
28
+
29
+
30
+ def _load() -> dict:
31
+ try:
32
+ data = json.loads(cache_path().read_text(encoding="utf-8"))
33
+ entries = data.get("entries")
34
+ return entries if isinstance(entries, dict) else {}
35
+ except (OSError, ValueError, AttributeError):
36
+ return {}
37
+
38
+
39
+ def _save(entries: dict) -> None:
40
+ path = cache_path()
41
+ path.parent.mkdir(parents=True, exist_ok=True)
42
+ tmp = path.with_suffix(".tmp")
43
+ tmp.write_text(
44
+ json.dumps({"version": 1, "entries": entries}, ensure_ascii=False), encoding="utf-8"
45
+ )
46
+ os.replace(tmp, path) # 原子替換,避免寫到一半損毀
47
+
48
+
49
+ def _valid(entry: dict, min_prompt: int) -> bool:
50
+ """使用者手動修改過的永遠有效;其餘要求是用不低於 min_prompt 版的提示詞辨識出來的。"""
51
+ return bool(entry.get("edited")) or entry.get("prompt", 0) >= min_prompt
52
+
53
+
54
+ def get(h: str, *, min_prompt: int = 0) -> dict | None:
55
+ """回傳 {"latex", "edited", "model", "prompt", "ts"};沒有或已過期則 None。"""
56
+ with _lock:
57
+ entry = _load().get(h)
58
+ return entry if entry and _valid(entry, min_prompt) else None
59
+
60
+
61
+ def lookup(hashes: list[str], *, min_prompt: int = 0) -> dict[str, dict]:
62
+ with _lock:
63
+ entries = _load()
64
+ return {h: entries[h] for h in hashes if h in entries and _valid(entries[h], min_prompt)}
65
+
66
+
67
+ def put(
68
+ h: str,
69
+ latex: str,
70
+ *,
71
+ model: str | None = None,
72
+ edited: bool = False,
73
+ prompt: int | None = None,
74
+ ) -> None:
75
+ """prompt:辨識時用的提示詞版本。手動修改(edited=True)時沿用舊值,不更新。"""
76
+ with _lock:
77
+ entries = _load()
78
+ old = entries.get(h, {})
79
+ entries[h] = {
80
+ "latex": latex,
81
+ "edited": edited,
82
+ "model": model or old.get("model"),
83
+ "prompt": prompt if prompt is not None else old.get("prompt", 0),
84
+ "ts": int(time.time()),
85
+ }
86
+ _save(entries)
87
+
88
+
89
+ def count() -> int:
90
+ with _lock:
91
+ return len(_load())
92
+
93
+
94
+ def stats() -> dict:
95
+ """{"count": 筆數, "edited": 其中手動修改過的筆數, "bytes": 檔案大小, "path": 檔案位置}。"""
96
+ with _lock:
97
+ entries = _load()
98
+ path = cache_path()
99
+ try:
100
+ size = path.stat().st_size
101
+ except OSError:
102
+ size = 0
103
+ return {
104
+ "count": len(entries),
105
+ "edited": sum(1 for e in entries.values() if e.get("edited")),
106
+ "bytes": size,
107
+ "path": str(path),
108
+ }
109
+
110
+
111
+ def remove(hashes: list[str]) -> int:
112
+ """刪除指定雜湊的快取,回傳實際刪掉幾筆。"""
113
+ with _lock:
114
+ entries = _load()
115
+ gone = [h for h in set(hashes) if h in entries]
116
+ for h in gone:
117
+ del entries[h]
118
+ if gone:
119
+ _save(entries)
120
+ return len(gone)
121
+
122
+
123
+ def clear() -> int:
124
+ with _lock:
125
+ n = len(_load())
126
+ _save({})
127
+ return n
@@ -0,0 +1,89 @@
1
+ """設定:API key 以環境變數優先,其次使用者設定檔;另外保存介面偏好(語系、配色…)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ CONFIG_PATH = Path.home() / ".mathtran" / "config.json"
10
+ DEFAULT_MODEL = "claude-sonnet-5-5"
11
+
12
+ # 介面偏好。存在伺服器端的設定檔,而不是瀏覽器的 localStorage:
13
+ # 桌面版每次啟動的本機埠號都不同,localStorage 以「來源(含埠號)」區分,重開就會遺失。
14
+ DEFAULT_SETTINGS: dict = {
15
+ "lang": "system", # system | zh-TW | en
16
+ "theme": "system", # system | light | dark
17
+ "thumb": 170, # 縮圖大小(px)
18
+ "formats": ["svg"], # 匯出格式(複選)
19
+ }
20
+ LANG_CHOICES = ("system", "zh-TW", "en")
21
+ THEME_CHOICES = ("system", "light", "dark")
22
+ FORMAT_CHOICES = ("svg", "pdf", "tex")
23
+ THUMB_RANGE = (100, 320)
24
+
25
+
26
+ def _load() -> dict:
27
+ try:
28
+ data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
29
+ return data if isinstance(data, dict) else {}
30
+ except (OSError, ValueError):
31
+ return {}
32
+
33
+
34
+ def _write(data: dict) -> None:
35
+ CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
36
+ CONFIG_PATH.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
37
+
38
+
39
+ def get_api_key() -> str | None:
40
+ return os.environ.get("ANTHROPIC_API_KEY") or _load().get("api_key")
41
+
42
+
43
+ def save_api_key(key: str) -> None:
44
+ data = _load()
45
+ data["api_key"] = key
46
+ _write(data)
47
+
48
+
49
+ def get_model() -> str:
50
+ return os.environ.get("MATHTRAN_MODEL") or _load().get("model") or DEFAULT_MODEL
51
+
52
+
53
+ def _clean_setting(key: str, value):
54
+ """驗證並正規化單一設定值;不合法就丟 ValueError(key)。"""
55
+ if key == "lang" and value in LANG_CHOICES:
56
+ return value
57
+ if key == "theme" and value in THEME_CHOICES:
58
+ return value
59
+ if key == "thumb" and isinstance(value, int) and not isinstance(value, bool) \
60
+ and THUMB_RANGE[0] <= value <= THUMB_RANGE[1]:
61
+ return value
62
+ if key == "formats" and isinstance(value, list) and value \
63
+ and all(v in FORMAT_CHOICES for v in value):
64
+ return [f for f in FORMAT_CHOICES if f in value] # 去重並固定順序
65
+ raise ValueError(key)
66
+
67
+
68
+ def get_settings() -> dict:
69
+ """已儲存的偏好;缺少或損毀的項目退回預設值(設定檔被手動改壞也不會讓程式出錯)。"""
70
+ out = {k: (list(v) if isinstance(v, list) else v) for k, v in DEFAULT_SETTINGS.items()}
71
+ saved = _load().get("settings")
72
+ if isinstance(saved, dict):
73
+ for key, value in saved.items():
74
+ try:
75
+ out[key] = _clean_setting(key, value)
76
+ except ValueError:
77
+ pass
78
+ return out
79
+
80
+
81
+ def update_settings(patch: dict) -> dict:
82
+ """只更新 patch 裡的項目(其餘保留);任何一項不合法就整批不寫入並丟 ValueError(key)。"""
83
+ cleaned = {k: _clean_setting(k, v) for k, v in patch.items()}
84
+ data = _load()
85
+ settings = data.get("settings") if isinstance(data.get("settings"), dict) else {}
86
+ settings.update(cleaned)
87
+ data["settings"] = settings
88
+ _write(data)
89
+ return get_settings()
mathtran/core/i18n.py ADDED
@@ -0,0 +1,134 @@
1
+ """後端訊息的多語系(繁體中文 / English)。
2
+
3
+ 前端每個請求都會帶 `X-Lang` 標頭(已解析好的 zh-TW 或 en),由 server 的 middleware 存進
4
+ contextvar,核心函式(ocr / render / batch)丟錯誤時用 tr() 取當下語言的訊息。
5
+ 沒有標頭(例如命令列)時,依序用環境變數 MATHTRAN_LANG、系統語言。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextvars
11
+ import locale
12
+ import os
13
+ import sys
14
+
15
+ LANGS = ("zh-TW", "en")
16
+
17
+ _current: contextvars.ContextVar[str | None] = contextvars.ContextVar("mathtran_lang", default=None)
18
+
19
+
20
+ def normalize(code: str | None) -> str | None:
21
+ """把 zh、zh-Hant、zh_TW、en-US… 對應到支援的語言;不認得則 None。"""
22
+ if not code:
23
+ return None
24
+ c = code.strip().replace("_", "-").lower()
25
+ if c.startswith("zh"):
26
+ return "zh-TW"
27
+ if c.startswith("en"):
28
+ return "en"
29
+ return None
30
+
31
+
32
+ def system_lang() -> str:
33
+ """作業系統的介面語言:中文系統 → zh-TW,其他 → en。"""
34
+ if sys.platform == "win32":
35
+ try:
36
+ import ctypes
37
+
38
+ lang_id = ctypes.windll.kernel32.GetUserDefaultUILanguage()
39
+ return "zh-TW" if (lang_id & 0xFF) == 0x04 else "en" # 0x04 = LANG_CHINESE
40
+ except Exception:
41
+ pass
42
+ for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
43
+ found = normalize(os.environ.get(var))
44
+ if found:
45
+ return found
46
+ try:
47
+ return normalize(locale.getlocale()[0]) or "en"
48
+ except Exception:
49
+ return "en"
50
+
51
+
52
+ def set_lang(code: str | None):
53
+ """設定目前請求的語言,回傳 token(用 reset_lang 還原)。不認得的語言會被忽略。"""
54
+ return _current.set(normalize(code))
55
+
56
+
57
+ def reset_lang(token) -> None:
58
+ _current.reset(token)
59
+
60
+
61
+ def _saved_lang() -> str | None:
62
+ """使用者在介面選的語言偏好(選「跟隨系統」時為 None)。"""
63
+ try:
64
+ from . import config
65
+
66
+ return normalize(config.get_settings().get("lang"))
67
+ except Exception:
68
+ return None
69
+
70
+
71
+ def current_lang() -> str:
72
+ """順序:請求標頭 → 環境變數 MATHTRAN_LANG → 介面偏好 → 系統語言。"""
73
+ return _current.get() or normalize(os.environ.get("MATHTRAN_LANG")) or _saved_lang() or system_lang()
74
+
75
+
76
+ MESSAGES: dict[str, dict[str, str]] = {
77
+ "zh-TW": {
78
+ # ocr
79
+ "api_key_missing": "未設定 API key:請設定環境變數 ANTHROPIC_API_KEY,或執行 mathtran config --api-key <KEY>",
80
+ "unsupported_image": "不支援的圖片格式(支援 PNG / JPEG / WebP / GIF)",
81
+ "api_failed": "Claude API 呼叫失敗:{err}",
82
+ # render
83
+ "tectonic_missing": "找不到 tectonic,請先執行:scoop install tectonic(macOS / Linux:brew install tectonic)",
84
+ "compile_failed": "LaTeX 編譯失敗:\n{log}",
85
+ "cjk_font_missing": "找不到中文字型「{font}」,請安裝該字型,或設定環境變數 MATHTRAN_CJK_FONT 指定其他字型名稱。\n",
86
+ "tex_cjk_note": "% 含中日韓字元:請以 XeLaTeX 編譯(xelatex),並確認系統有對應字型",
87
+ # batch
88
+ "empty_skipped": "{name}:沒有 LaTeX 內容,已略過",
89
+ # server
90
+ "bad_fmt": "fmt 必須是 svg、pdf 或 tex",
91
+ "bad_hash": "hash 格式不正確",
92
+ "bad_formats": "formats 必須是 svg / pdf / tex 的非空組合",
93
+ "no_items": "沒有要匯出的項目",
94
+ "all_failed": "全部匯出失敗:\n{details}",
95
+ "bad_setting": "設定值不正確:{key}",
96
+ # cli
97
+ "out_written": "已輸出 {path}",
98
+ "bad_ext": "輸出副檔名必須是 .svg 或 .pdf",
99
+ "config_saved": "已儲存至 {path}",
100
+ "key_set": "API key:已設定",
101
+ "key_unset": "API key:未設定",
102
+ "cache_cleared": "已清除 {n} 筆快取",
103
+ "cache_stats": "{count} 筆快取(其中 {edited} 筆為手動修改,{kb} KB):{path}",
104
+ },
105
+ "en": {
106
+ "api_key_missing": "No API key set: set the ANTHROPIC_API_KEY environment variable, or run mathtran config --api-key <KEY>",
107
+ "unsupported_image": "Unsupported image format (PNG / JPEG / WebP / GIF are supported)",
108
+ "api_failed": "Claude API call failed: {err}",
109
+ "tectonic_missing": "tectonic not found. Install it first: scoop install tectonic (macOS / Linux: brew install tectonic)",
110
+ "compile_failed": "LaTeX compilation failed:\n{log}",
111
+ "cjk_font_missing": "CJK font \"{font}\" not found. Install it, or set the MATHTRAN_CJK_FONT environment variable to another font name.\n",
112
+ "tex_cjk_note": "% Contains CJK characters: compile with XeLaTeX (xelatex) and make sure a matching font is installed",
113
+ "empty_skipped": "{name}: no LaTeX content, skipped",
114
+ "bad_fmt": "fmt must be svg, pdf or tex",
115
+ "bad_hash": "Invalid hash format",
116
+ "bad_formats": "formats must be a non-empty combination of svg / pdf / tex",
117
+ "no_items": "Nothing to export",
118
+ "all_failed": "All exports failed:\n{details}",
119
+ "bad_setting": "Invalid setting: {key}",
120
+ "out_written": "Wrote {path}",
121
+ "bad_ext": "Output extension must be .svg or .pdf",
122
+ "config_saved": "Saved to {path}",
123
+ "key_set": "API key: set",
124
+ "key_unset": "API key: not set",
125
+ "cache_cleared": "Cleared {n} cached result(s)",
126
+ "cache_stats": "{count} cached result(s) ({edited} hand-edited, {kb} KB): {path}",
127
+ },
128
+ }
129
+
130
+
131
+ def tr(message_id: str, /, **kw) -> str:
132
+ # message_id 是 positional-only:訊息裡的佔位符可以叫 key / name… 而不會跟參數名稱撞名
133
+ text = MESSAGES[current_lang()].get(message_id) or MESSAGES["zh-TW"][message_id]
134
+ return text.format(**kw) if kw else text
mathtran/core/ocr.py ADDED
@@ -0,0 +1,122 @@
1
+ """圖片 → LaTeX(Claude 視覺 API)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import re
7
+ from dataclasses import dataclass
8
+
9
+ import anthropic
10
+
11
+ from . import cache
12
+ from .config import get_api_key, get_model
13
+ from .i18n import tr
14
+
15
+ # 提示詞改版時要把 PROMPT_VERSION +1:舊版本辨識出的(未被使用者修改的)快取會視為過期。
16
+ # v1:只轉錄數學公式(會漏掉圖上的中文標題與說明文字)
17
+ # v2:連同圖上所有文字(含中文)一起轉錄
18
+ PROMPT_VERSION = 2
19
+ PROMPT = (
20
+ "Transcribe EVERYTHING written in this image into LaTeX: the mathematical formulas "
21
+ "AND all text, including Chinese (or any other language) titles, labels, captions "
22
+ "and notes. Do not skip, translate or summarize anything.\n"
23
+ "Rules:\n"
24
+ "- Put every piece of ordinary text (any language) inside \\text{...}, "
25
+ "e.g. \\text{正弦定理}. Keep the original characters exactly as written.\n"
26
+ "- Keep the original reading order (top to bottom, left to right). "
27
+ "Use one \\\\ line break per visual line and wrap the whole thing in an "
28
+ "aligned (or gathered) environment when there is more than one line.\n"
29
+ "- Output ONLY the raw LaTeX code: no explanation, no markdown fences, "
30
+ "no surrounding $ or \\[ \\] delimiters."
31
+ )
32
+
33
+
34
+ class OcrError(RuntimeError):
35
+ pass
36
+
37
+
38
+ def sniff_media_type(data: bytes) -> str:
39
+ if data.startswith(b"\x89PNG"):
40
+ return "image/png"
41
+ if data.startswith(b"\xff\xd8"):
42
+ return "image/jpeg"
43
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
44
+ return "image/webp"
45
+ if data[:3] == b"GIF":
46
+ return "image/gif"
47
+ raise OcrError(tr("unsupported_image"))
48
+
49
+
50
+ def clean_latex(text: str) -> str:
51
+ t = text.strip()
52
+ t = re.sub(r"^```(?:latex|tex)?\s*|\s*```$", "", t).strip()
53
+ for left, right in (("$$", "$$"), (r"\[", r"\]"), ("$", "$"), (r"\(", r"\)")):
54
+ if t.startswith(left) and t.endswith(right) and len(t) > len(left) + len(right):
55
+ t = t[len(left) : -len(right)].strip()
56
+ break
57
+ return t
58
+
59
+
60
+ @dataclass
61
+ class OcrResult:
62
+ latex: str
63
+ hash: str
64
+ cached: bool # True 表示直接取自快取,沒有呼叫 API
65
+
66
+
67
+ def recognize(
68
+ image: bytes,
69
+ *,
70
+ use_cache: bool = True,
71
+ client: anthropic.Anthropic | None = None,
72
+ ) -> OcrResult:
73
+ """辨識圖片;use_cache=True 時,已辨識過(或使用者修改過)的圖片直接回傳快取。"""
74
+ h = cache.sha256_hex(image)
75
+ if use_cache:
76
+ hit = cache.get(h, min_prompt=PROMPT_VERSION) # 舊提示詞辨識出的結果視為過期
77
+ if hit and hit.get("latex"):
78
+ return OcrResult(hit["latex"], h, True)
79
+ latex = _call_api(image, client)
80
+ # 重新辨識會覆蓋舊結果(含手動修改)
81
+ cache.put(h, latex, model=get_model(), prompt=PROMPT_VERSION)
82
+ return OcrResult(latex, h, False)
83
+
84
+
85
+ def image_to_latex(
86
+ image: bytes, client: anthropic.Anthropic | None = None, use_cache: bool = True
87
+ ) -> str:
88
+ return recognize(image, use_cache=use_cache, client=client).latex
89
+
90
+
91
+ def _call_api(image: bytes, client: anthropic.Anthropic | None) -> str:
92
+ if client is None:
93
+ key = get_api_key()
94
+ if not key:
95
+ raise OcrError(tr("api_key_missing"))
96
+ client = anthropic.Anthropic(api_key=key)
97
+ media_type = sniff_media_type(image)
98
+ try:
99
+ msg = client.messages.create(
100
+ model=get_model(),
101
+ max_tokens=2048,
102
+ messages=[
103
+ {
104
+ "role": "user",
105
+ "content": [
106
+ {
107
+ "type": "image",
108
+ "source": {
109
+ "type": "base64",
110
+ "media_type": media_type,
111
+ "data": base64.b64encode(image).decode(),
112
+ },
113
+ },
114
+ {"type": "text", "text": PROMPT},
115
+ ],
116
+ }
117
+ ],
118
+ )
119
+ except anthropic.APIError as e:
120
+ raise OcrError(tr("api_failed", err=e)) from e
121
+ text = "".join(b.text for b in msg.content if b.type == "text")
122
+ return clean_latex(text)