Spoken-English math to Typst with a small from-scratch encoder-decoder Transformer, following the build guide: compile-checked synthetic data generator, shared BPE tokenizer, nn.Transformer model, training loop with an overfit sanity check, greedy decoding CLI, and evaluation on synthetic and hand-written test sets. ./run.sh runs the whole pipeline. Co-Authored-By: Claude Opus 5.5 <[email protected]>
58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
"""Check Typst math with the real `typst` CLI, so a renderer bug can never teach the model broken Typst.
|
|
|
|
compiles(math) -> bool for one equation (the guide's simple version)
|
|
compiles_many(maths) -> list[bool]; many equations per file, split in half on failure to find the bad ones
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pathlib
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
|
|
def _typst() -> str:
|
|
exe = shutil.which("typst")
|
|
if exe is None:
|
|
raise SystemExit("The `typst` CLI is not installed. Install it with: brew install typst")
|
|
return exe
|
|
|
|
|
|
def _safe(math: str) -> bool:
|
|
# a stray `$` would end the math block early and let arbitrary markup through
|
|
return math.strip() != "" and "$" not in math and "\n" not in math
|
|
|
|
|
|
def _compile(maths: list[str]) -> bool:
|
|
with tempfile.TemporaryDirectory() as d:
|
|
src = pathlib.Path(d) / "t.typ"
|
|
src.write_text("".join(f"${m}$\n\n" for m in maths))
|
|
return subprocess.run([_typst(), "compile", str(src)], capture_output=True, check=False).returncode == 0
|
|
|
|
|
|
def compiles(math: str) -> bool:
|
|
return _safe(math) and _compile([math])
|
|
|
|
|
|
def _bisect(maths: list[str]) -> list[bool]:
|
|
if _compile(maths):
|
|
return [True] * len(maths)
|
|
if len(maths) == 1:
|
|
return [False]
|
|
mid = len(maths) // 2
|
|
return _bisect(maths[:mid]) + _bisect(maths[mid:])
|
|
|
|
|
|
def compiles_many(maths: list[str], batch: int = 500, workers: int = 8) -> list[bool]:
|
|
_typst()
|
|
ok = [False] * len(maths)
|
|
idx = [i for i, m in enumerate(maths) if _safe(m)]
|
|
chunks = [idx[i : i + batch] for i in range(0, len(idx), batch)]
|
|
with ThreadPoolExecutor(workers) as ex:
|
|
for chunk, res in zip(chunks, ex.map(lambda c: _bisect([maths[i] for i in c]), chunks)):
|
|
for i, r in zip(chunk, res):
|
|
ok[i] = r
|
|
return ok
|