aien-translate
aien-dev/aien-translate
Brought by drakestapleton
aien-translate / scripts / translate_latex.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Translate a LaTeX paper with a running aien-translate, one language per output folder. |
| 3 | |
| 4 | translate_latex.py paper.tex OUT_DIR --langs zh-CN,ja [--server http://127.0.0.1:18097] [--doi 10.5281/...] |
| 5 | |
| 6 | Writes OUT_DIR/<code>/paper.tex (and copies the files next to paper.tex), ready for |
| 7 | `tectonic -X compile`. The model sees plain sentences: math, citations, references, labels, |
| 8 | URLs and code become numbered markers (<x1/>), and formatting such as \\textit{...} or |
| 9 | \\section{...} becomes paired markers (<g1>...</g1>) whose contents are translated. The |
| 10 | guard in aien-translate requires every marker back; a piece whose markers break stays in |
| 11 | English. Diagram drawing code, display math and the reference list are kept as they are, |
| 12 | the way journals publish translations; labels inside diagrams are translated. A note under the title says the translation ran on |
| 13 | AIEN's own model and points to the English original. |
| 14 | """ |
| 15 | import argparse |
| 16 | import json |
| 17 | import time |
| 18 | import re |
| 19 | import shutil |
| 20 | import sys |
| 21 | import urllib.parse |
| 22 | import urllib.request |
| 23 | from pathlib import Path |
| 24 | |
| 25 | LANGS = { # code -> (aien-translate id, babel name or None for CJK, CJK font, names) |
| 26 | "zh-CN": ("chinese_simplified", None, "Noto Serif CJK SC", |
| 27 | dict(definition="定义", lemma="引理", abstract="摘要", refs="参考文献", fig="图", tab="表")), |
| 28 | "zh-TW": ("chinese_traditional", None, "Noto Serif CJK TC", |
| 29 | dict(definition="定義", lemma="引理", abstract="摘要", refs="參考文獻", fig="圖", tab="表")), |
| 30 | "ja": ("japanese", None, "Noto Serif CJK JP", |
| 31 | dict(definition="定義", lemma="補題", abstract="概要", refs="参考文献", fig="図", tab="表")), |
| 32 | "ko": ("korean", None, "Noto Serif CJK KR", |
| 33 | dict(definition="정의", lemma="보조정리", abstract="초록", refs="참고문헌", fig="그림", tab="표")), |
| 34 | "es": ("spanish", "spanish", None, dict(definition="Definición", lemma="Lema")), |
| 35 | "fr": ("french", "french", None, dict(definition="Définition", lemma="Lemme")), |
| 36 | "de": ("deutsch", "ngerman", None, dict(definition="Definition", lemma="Lemma")), |
| 37 | "pt": ("portuguese", "portuguese", None, dict(definition="Definição", lemma="Lema")), |
| 38 | "ru": ("russian", "russian", None, dict(definition="Определение", lemma="Лемма")), |
| 39 | } |
| 40 | |
| 41 | SKIP_ENVS = {"tikzpicture", "thebibliography", "equation", "equation*", "align", "align*", "gather", |
| 42 | "gather*", "multline", "multline*", "eqnarray", "eqnarray*", "displaymath", "math", "array", |
| 43 | "verbatim", "lstlisting", "minted"} |
| 44 | THEOREM_ENVS = {"definition", "lemma", "theorem", "proof", "corollary", "proposition", "remark", "example"} |
| 45 | SECTION_LIKE = {"section", "section*", "subsection", "subsection*", "subsubsection", "subsubsection*", |
| 46 | "paragraph", "paragraph*", "caption", "title", "date"} |
| 47 | PAIRED = SECTION_LIKE | {"textit", "textbf", "emph", "textsc", "textsl", "underline", "footnote", "uline"} |
| 48 | FONT_SWITCH = {"small", "footnotesize", "scriptsize", "tiny", "large", "Large", "normalsize", "bfseries", |
| 49 | "itshape", "em", "bf", "it", "sffamily", "rmfamily"} |
| 50 | LETTERS = re.compile(r"[^\W\d_]{2}") |
| 51 | MARK = re.compile(r"(<g\d+>|</g\d+>|<x\d+/>)") |
| 52 | ACCENT = {'"': "\u0308", "'": "\u0301", "`": "\u0300", "^": "\u0302", "~": "\u0303", "c": "\u0327", "v": "\u030c"} |
| 53 | ACCENT_RE = re.compile(r"\{?\\([\"'`^~]|c |v )\s*\{?([A-Za-z])\}?\}?") |
| 54 | |
| 55 | |
| 56 | # ---------- parsing a LaTeX fragment into text, atoms (x) and groups (g) ---------- |
| 57 | |
| 58 | class Node: |
| 59 | __slots__ = ("kind", "raw", "text", "open", "close", "kids") |
| 60 | |
| 61 | def __init__(self, kind, raw="", text="", open_="", close="", kids=None): |
| 62 | self.kind, self.raw, self.text, self.open, self.close, self.kids = kind, raw, text, open_, close, kids or [] |
| 63 | |
| 64 | |
| 65 | def match_brace(s, i, o="{", c="}"): |
| 66 | """s[i] == o; return index just past the matching c (escapes respected).""" |
| 67 | depth = 0 |
| 68 | j = i |
| 69 | while j < len(s): |
| 70 | ch = s[j] |
| 71 | if ch == "\\": |
| 72 | j += 2 |
| 73 | continue |
| 74 | if ch == o: |
| 75 | depth += 1 |
| 76 | elif ch == c: |
| 77 | depth -= 1 |
| 78 | if depth == 0: |
| 79 | return j + 1 |
| 80 | j += 1 |
| 81 | raise ValueError(f"unbalanced {o}{c} near: {s[i:i+80]!r}") |
| 82 | |
| 83 | |
| 84 | def find_end_env(s, i, env): |
| 85 | begin, end = "\\begin{" + env + "}", "\\end{" + env + "}" |
| 86 | depth = 1 |
| 87 | j = i |
| 88 | while depth: |
| 89 | nb, ne = s.find(begin, j), s.find(end, j) |
| 90 | if ne < 0: |
| 91 | raise ValueError(f"no \\end{{{env}}}") |
| 92 | if 0 <= nb < ne: |
| 93 | depth += 1 |
| 94 | j = nb + len(begin) |
| 95 | else: |
| 96 | depth -= 1 |
| 97 | j = ne + len(end) |
| 98 | return j |
| 99 | |
| 100 | |
| 101 | def adjacent_args(s, j): |
| 102 | """Consume {...} and [...] groups directly after a command (no spaces).""" |
| 103 | while j < len(s) and s[j] in "{[": |
| 104 | j = match_brace(s, j, s[j], "}" if s[j] == "{" else "]") |
| 105 | return j |
| 106 | |
| 107 | |
| 108 | def parse(s, i=0, stop=None): |
| 109 | nodes, buf, start = [], [], i |
| 110 | |
| 111 | def flush(): |
| 112 | if buf: |
| 113 | nodes.append(Node("t", raw="".join(r for r, _ in buf), text="".join(t for _, t in buf))) |
| 114 | buf.clear() |
| 115 | |
| 116 | def atom(raw): |
| 117 | flush() |
| 118 | nodes.append(Node("x", raw=raw)) |
| 119 | |
| 120 | while i < len(s): |
| 121 | ch = s[i] |
| 122 | if stop and ch == stop: |
| 123 | break |
| 124 | if ch == "%": |
| 125 | j = s.find("\n", i) |
| 126 | j = len(s) if j < 0 else j + 1 |
| 127 | atom(s[i:j]); i = j; continue |
| 128 | if ch == "$": |
| 129 | if s.startswith("$$", i): |
| 130 | j = s.index("$$", i + 2) + 2 |
| 131 | else: |
| 132 | j = i + 1 |
| 133 | while s[j] != "$" or s[j - 1] == "\\": |
| 134 | j += 1 |
| 135 | j += 1 |
| 136 | atom(s[i:j]); i = j; continue |
| 137 | if ch == "&": |
| 138 | atom("&"); i += 1; continue |
| 139 | if ch == "~": |
| 140 | atom("~"); i += 1; continue |
| 141 | am = ACCENT_RE.match(s, i) if ch in "{\\" else None |
| 142 | if am and (am.group(0).count("{") == am.group(0).count("}")): |
| 143 | import unicodedata |
| 144 | buf.append((am.group(0), unicodedata.normalize("NFC", am.group(2) + ACCENT[am.group(1).strip()]))) |
| 145 | i = am.end(); continue |
| 146 | if ch == "{": |
| 147 | j = match_brace(s, i) |
| 148 | inner = s[i + 1:j - 1] |
| 149 | m = re.match(r"\\([A-Za-z]+)\s*", inner) |
| 150 | if m and m.group(1) in FONT_SWITCH: |
| 151 | o = "{" + m.group(0) |
| 152 | kids = parse(inner, m.end())[0] |
| 153 | flush(); nodes.append(Node("g", raw=s[i:j], open_=o, close="}", kids=kids)) |
| 154 | elif inner.startswith("\\"): |
| 155 | atom(s[i:j]) |
| 156 | else: |
| 157 | flush(); nodes.append(Node("g", raw=s[i:j], open_="{", close="}", kids=parse(inner)[0])) |
| 158 | i = j; continue |
| 159 | if ch == "\\": |
| 160 | if i + 1 >= len(s): |
| 161 | atom("\\"); i += 1; continue |
| 162 | nxt = s[i + 1] |
| 163 | if nxt in "%&#_${}": |
| 164 | buf.append((s[i:i + 2], nxt)); i += 2; continue |
| 165 | if nxt == "(": |
| 166 | j = s.index("\\)", i) + 2; atom(s[i:j]); i = j; continue |
| 167 | if nxt == "[": |
| 168 | j = s.index("\\]", i) + 2; atom(s[i:j]); i = j; continue |
| 169 | if nxt == "\\": |
| 170 | j = i + 2 |
| 171 | if j < len(s) and s[j] == "*": |
| 172 | j += 1 |
| 173 | if j < len(s) and s[j] == "[": |
| 174 | j = match_brace(s, j, "[", "]") |
| 175 | atom(s[i:j]); i = j; continue |
| 176 | if not nxt.isalpha(): |
| 177 | atom(s[i:i + 2]); i += 2; continue |
| 178 | m = re.match(r"\\([A-Za-z]+\*?)", s[i:]) |
| 179 | name, j = m.group(1), i + m.end() |
| 180 | if name in ("begin", "end"): |
| 181 | k = match_brace(s, j) |
| 182 | env = s[j + 1:k - 1] |
| 183 | if name == "end": |
| 184 | atom(s[i:k]); i = k; continue |
| 185 | if env in SKIP_ENVS: |
| 186 | e = find_end_env(s, k, env); atom(s[i:e]); i = e; continue |
| 187 | if env in THEOREM_ENVS and k < len(s) and s[k] == "[": |
| 188 | e = match_brace(s, k, "[", "]") |
| 189 | atom(s[i:k]); flush() |
| 190 | nodes.append(Node("g", raw=s[k:e], open_="[", close="]", kids=parse(s[k + 1:e - 1])[0])) |
| 191 | i = e; continue |
| 192 | e = adjacent_args(s, k); atom(s[i:e]); i = e; continue |
| 193 | if name == "item": |
| 194 | if j < len(s) and s[j] == "[": |
| 195 | e = match_brace(s, j, "[", "]") |
| 196 | atom(s[i:j]); flush() |
| 197 | nodes.append(Node("g", raw=s[j:e], open_="[", close="]", kids=parse(s[j + 1:e - 1])[0])) |
| 198 | i = e; continue |
| 199 | atom(s[i:j]); i = j; continue |
| 200 | if name == "href" and j < len(s) and s[j] == "{": |
| 201 | k = match_brace(s, j) |
| 202 | if k < len(s) and s[k] == "{": |
| 203 | e = match_brace(s, k) |
| 204 | flush() |
| 205 | nodes.append(Node("g", raw=s[i:e], open_=s[i:k + 1], close="}", kids=parse(s[k + 1:e - 1])[0])) |
| 206 | i = e; continue |
| 207 | if name in PAIRED: |
| 208 | k = j |
| 209 | if k < len(s) and s[k] == "[": |
| 210 | k = match_brace(s, k, "[", "]") |
| 211 | if k < len(s) and s[k] == "{": |
| 212 | e = match_brace(s, k) |
| 213 | flush() |
| 214 | g = Node("g", raw=s[i:e], open_=s[i:k + 1], close="}", kids=parse(s[k + 1:e - 1])[0]) |
| 215 | g.text = name # remember the command, to split headings out on their own |
| 216 | nodes.append(g); i = e; continue |
| 217 | e = adjacent_args(s, j) |
| 218 | atom(s[i:e]); i = e; continue |
| 219 | buf.append((ch, ch)); i += 1 |
| 220 | flush() |
| 221 | return nodes, i |
| 222 | |
| 223 | |
| 224 | def raw_of(nodes): |
| 225 | return "".join(n.raw for n in nodes) |
| 226 | |
| 227 | |
| 228 | def has_words(nodes): |
| 229 | for n in nodes: |
| 230 | if n.kind == "t" and LETTERS.search(n.text): |
| 231 | return True |
| 232 | if n.kind == "g" and has_words(n.kids): |
| 233 | return True |
| 234 | return False |
| 235 | |
| 236 | |
| 237 | def breaking(n): |
| 238 | return n.kind == "x" and re.search(r"\\\\|^&$|\\item|\\begin|\\end|\\centering|\\maketitle|\\label|^%", n.raw) |
| 239 | |
| 240 | |
| 241 | LONG = 700 # characters; longer paragraphs go to the model a few sentences at a time |
| 242 | CHUNK = 450 |
| 243 | SENTENCE_END = re.compile(r"(?:(?<=[.!?])(?=\s+[A-Z(`\\])|(?<=;)(?=\s))(\s+)") |
| 244 | |
| 245 | |
| 246 | def unescape(raw): |
| 247 | return re.sub(r"\\([%&#_${}])", r"\1", raw) |
| 248 | |
| 249 | |
| 250 | def sentences(nodes): |
| 251 | """Split a long run at sentence ends that fall in its top-level text.""" |
| 252 | chunks, cur, size = [], [], 0 |
| 253 | for n in nodes: |
| 254 | if n.kind != "t": |
| 255 | cur.append(n); size += len(n.raw) if n.kind == "x" else len(raw_of(n.kids)); continue |
| 256 | parts = SENTENCE_END.split(n.raw) |
| 257 | for k, part in enumerate(parts): |
| 258 | if k % 2: # whitespace between sentences |
| 259 | cur.append(Node("t", raw=part, text=" ")) |
| 260 | if size >= CHUNK: |
| 261 | chunks.append(cur); cur, size = [], 0 |
| 262 | elif part: |
| 263 | cur.append(Node("t", raw=part, text=unescape(part))); size += len(part) |
| 264 | if cur: |
| 265 | chunks.append(cur) |
| 266 | return chunks |
| 267 | |
| 268 | |
| 269 | def tikz(raw): |
| 270 | """Translate the text of each `node {...}` in a diagram; keep the drawing code as it is.""" |
| 271 | out, pos = [], 0 |
| 272 | for m in re.finditer(r"\bnode\b", raw): |
| 273 | if m.start() < pos: |
| 274 | continue |
| 275 | j = m.end() |
| 276 | while j < len(raw): |
| 277 | if raw[j].isspace(): |
| 278 | j += 1 |
| 279 | elif raw[j] == "[": |
| 280 | j = match_brace(raw, j, "[", "]") |
| 281 | elif raw[j] == "(": |
| 282 | j = match_brace(raw, j, "(", ")") |
| 283 | elif raw.startswith("at", j): |
| 284 | j += 2 |
| 285 | else: |
| 286 | break |
| 287 | if j < len(raw) and raw[j] == "{": |
| 288 | e = match_brace(raw, j) |
| 289 | kids = parse(raw[j + 1:e - 1])[0] |
| 290 | out.append(("raw", raw[pos:j + 1])) |
| 291 | out.append(("piece", kids) if has_words(kids) else ("raw", raw[j + 1:e - 1])) |
| 292 | out.append(("raw", "}")) |
| 293 | pos = e |
| 294 | out.append(("raw", raw[pos:])) |
| 295 | return out |
| 296 | |
| 297 | |
| 298 | DISPLAY_MATH = re.compile(r"^(\\\[|\$\$|\\begin\{(equation|align|gather|multline|eqnarray|displaymath|array)\*?\})") |
| 299 | |
| 300 | |
| 301 | def math_text(raw): |
| 302 | """Translate multi-word \\text{...} phrases inside display math; keep the math itself.""" |
| 303 | out, pos = [], 0 |
| 304 | for m in re.finditer(r"\\text\{", raw): |
| 305 | if m.start() < pos: |
| 306 | continue |
| 307 | e = match_brace(raw, m.end() - 1) |
| 308 | inner = raw[m.end():e - 1] |
| 309 | kids = parse(inner)[0] |
| 310 | if re.search(r"[^\W\d_]{2,}\s+[^\W\d_]{2,}", "".join(n.text for n in kids if n.kind == "t")): |
| 311 | out.append(("raw", raw[pos:m.end()])) |
| 312 | out.append(("piece", kids)) |
| 313 | out.append(("raw", "}")) |
| 314 | pos = e |
| 315 | out.append(("raw", raw[pos:])) |
| 316 | return out |
| 317 | |
| 318 | |
| 319 | def runs(nodes): |
| 320 | """Split a fragment into pieces to translate (lists of nodes) and raw LaTeX to keep.""" |
| 321 | out, cur = [], [] |
| 322 | |
| 323 | def flush(): |
| 324 | if cur: |
| 325 | if not has_words(cur): |
| 326 | out.append(("raw", raw_of(cur))) |
| 327 | elif len(raw_of(cur)) > LONG: |
| 328 | for ch in sentences(cur): |
| 329 | out.append(("piece", ch) if has_words(ch) else ("raw", raw_of(ch))) |
| 330 | else: |
| 331 | out.append(("piece", list(cur))) |
| 332 | cur.clear() |
| 333 | |
| 334 | for n in nodes: |
| 335 | if n.kind == "x" and n.raw.startswith("\\begin{tikzpicture}"): |
| 336 | flush(); out.extend(tikz(n.raw)) |
| 337 | elif n.kind == "x" and DISPLAY_MATH.match(n.raw) and len(math_text(n.raw)) > 1: |
| 338 | flush(); out.extend(math_text(n.raw)) |
| 339 | elif breaking(n): |
| 340 | flush(); out.append(("raw", n.raw)) |
| 341 | elif n.kind == "g" and n.text in SECTION_LIKE: |
| 342 | flush(); out.append(("raw", n.open)); out.extend(runs(n.kids)); out.append(("raw", n.close)) |
| 343 | else: |
| 344 | cur.append(n) |
| 345 | flush() |
| 346 | return out |
| 347 | |
| 348 | |
| 349 | # ---------- encoding pieces for the model and decoding the answer ---------- |
| 350 | |
| 351 | DASHES = (("---", "\u2014"), ("--", "\u2013")) |
| 352 | |
| 353 | |
| 354 | def plain(t): |
| 355 | t = re.sub(r"\s+", " ", t) |
| 356 | t = t.replace("``", "\u201c").replace("''", "\u201d") |
| 357 | for a, b in DASHES: |
| 358 | t = t.replace(a, b) |
| 359 | return t |
| 360 | |
| 361 | |
| 362 | def encode(nodes): |
| 363 | table, counter = {}, [0] |
| 364 | |
| 365 | def enc(ns): |
| 366 | parts = [] |
| 367 | for n in ns: |
| 368 | if n.kind == "t": |
| 369 | parts.append(plain(n.text)) |
| 370 | else: |
| 371 | counter[0] += 1 |
| 372 | k = counter[0] |
| 373 | if n.kind == "x": |
| 374 | table[f"x{k}"] = n.raw |
| 375 | parts.append(f"<x{k}/>") |
| 376 | else: |
| 377 | table[f"g{k}"] = (n.open, n.close) |
| 378 | parts.append(f"<g{k}>{enc(n.kids)}</g{k}>") |
| 379 | return "".join(parts) |
| 380 | |
| 381 | return enc(nodes), table |
| 382 | |
| 383 | |
| 384 | ESC = {"\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "%": r"\%", "&": r"\&", "#": r"\#", |
| 385 | "_": r"\_", "$": r"\$", "^": r"\^{}", "~": r"\textasciitilde{}"} |
| 386 | |
| 387 | |
| 388 | def escape(t): |
| 389 | t = t.replace("<", "<").replace(">", ">").replace("&", "&") |
| 390 | return "".join(ESC.get(c, c) for c in t) |
| 391 | |
| 392 | |
| 393 | def no_dashes(t, code): |
| 394 | """Drake's writing uses no em or en dashes; keep translations to the same rule.""" |
| 395 | t = re.sub(r"(\d)\s*\u2013\s*(\d)", r"\1-\2", t) |
| 396 | if code in ("zh-CN", "zh-TW", "ja"): |
| 397 | return re.sub(r"\s*[\u2014\u2013]+\s*", "、" if code == "ja" else ",", t) |
| 398 | t = re.sub(r"\s+[\u2014\u2013]+\s+", ", ", t) |
| 399 | return t.replace("\u2014", ", ").replace("\u2013", "-") |
| 400 | |
| 401 | |
| 402 | def decode(translated, table, code): |
| 403 | out, stack, used = [], [], set() |
| 404 | for part in MARK.split(translated): |
| 405 | if not part: |
| 406 | continue |
| 407 | m = re.fullmatch(r"<(/?)([gx])(\d+)(/?)>", part) |
| 408 | if m: |
| 409 | key = f"{m.group(2)}{m.group(3)}" |
| 410 | if key not in table: |
| 411 | return None |
| 412 | if m.group(2) == "x": |
| 413 | if key in used: |
| 414 | return None |
| 415 | used.add(key); out.append(table[key]) |
| 416 | elif m.group(1): |
| 417 | if not stack or stack[-1] != key: |
| 418 | return None |
| 419 | stack.pop(); out.append(table[key][1]) |
| 420 | else: |
| 421 | if key in used: |
| 422 | return None |
| 423 | used.add(key); stack.append(key); out.append(table[key][0]) |
| 424 | continue |
| 425 | text = escape(no_dashes(part, code)) |
| 426 | if out and re.search(r"\\[A-Za-z]+\*?$", out[-1]) and text[:1].isalpha(): |
| 427 | text = "{}" + text # \ldots followed by a word must not glue into \ldotsword |
| 428 | out.append(text) |
| 429 | if stack or used != set(table): |
| 430 | return None |
| 431 | return "".join(out) |
| 432 | |
| 433 | |
| 434 | # ---------- the document ---------- |
| 435 | |
| 436 | def units(body): |
| 437 | """Blank-line separated blocks, never splitting inside a kept environment or a brace group.""" |
| 438 | blocks, cur = [], [] |
| 439 | for line in body.split("\n"): |
| 440 | cur.append(line) |
| 441 | text = "\n".join(cur) |
| 442 | if line.strip() == "" and balanced(text): |
| 443 | blocks.append(text + "\n"); cur = [] |
| 444 | if cur: |
| 445 | blocks.append("\n".join(cur)) |
| 446 | return blocks |
| 447 | |
| 448 | |
| 449 | def balanced(text): |
| 450 | try: |
| 451 | parse(text) |
| 452 | return True |
| 453 | except (ValueError, IndexError): |
| 454 | return False |
| 455 | |
| 456 | |
| 457 | def note(doi): |
| 458 | src = f"the English original (DOI {doi})" if doi else "the English original" |
| 459 | return ("\\begin{quote}\\small \\textbf{Translated on our own machine.} AIEN's own AI model translated this " |
| 460 | "paper on a single computer in our lab, not in a data center. The translation may have mistakes; " |
| 461 | f"{src} is the version of record.\\end{{quote}}\n") |
| 462 | |
| 463 | |
| 464 | def preamble_for(pre, code): |
| 465 | lang_id, babel, cjk, names = LANGS[code] |
| 466 | pre = re.sub(r"^\\usepackage\[utf8\]\{inputenc\}\n|^\\usepackage\[T1\]\{fontenc\}\n|^\\usepackage\{lmodern\}\n", |
| 467 | "", pre, flags=re.M) |
| 468 | setup = ["\\usepackage{fontspec}"] |
| 469 | if babel: |
| 470 | setup.append(f"\\usepackage[shorthands=off,{babel}]{{babel}}") |
| 471 | if code == "ru": |
| 472 | setup.append("\\setmainfont{cmunrm.otf}[BoldFont=cmunbx.otf,ItalicFont=cmunti.otf," |
| 473 | "BoldItalicFont=cmunbi.otf]") |
| 474 | else: |
| 475 | bold = cjk.replace("Serif", "Serif") + ":style=Bold" |
| 476 | setup.append("\\usepackage{xeCJK}") |
| 477 | setup.append(f"\\setCJKmainfont{{{cjk}}}[BoldFont={{{cjk} Bold}}]") |
| 478 | setup.append(f"\\setCJKsansfont{{{cjk.replace('Serif', 'Sans')}}}") |
| 479 | setup.append(f"\\setCJKmonofont{{{cjk.replace('Serif CJK', 'Sans Mono CJK')}}}") |
| 480 | if code == "ko": |
| 481 | setup.append("\\xeCJKsetup{CJKspace=true}") |
| 482 | setup.append(f"\\AtBeginDocument{{\\renewcommand{{\\abstractname}}{{{names['abstract']}}}" |
| 483 | f"\\renewcommand{{\\refname}}{{{names['refs']}}}" |
| 484 | f"\\renewcommand{{\\figurename}}{{{names['fig']}}}" |
| 485 | f"\\renewcommand{{\\tablename}}{{{names['tab']}}}}}") |
| 486 | pre = re.sub(r"(\\documentclass(\[[^\]]*\])?\{[^}]*\}\n)", lambda m: m.group(1) + "\n".join(setup) + "\n", |
| 487 | pre, count=1) |
| 488 | for env, word in (("definition", names["definition"]), ("lemma", names["lemma"])): |
| 489 | pre = re.sub(r"(\\newtheorem\{" + env + r"\}\{)[^}]*\}", lambda m: m.group(1) + word + "}", pre) |
| 490 | return pre |
| 491 | |
| 492 | |
| 493 | CHUNK_ITEMS, CHUNK_CHARS = 60, 12000 |
| 494 | |
| 495 | |
| 496 | def _ask(server, lang_id, batch): |
| 497 | body = urllib.parse.urlencode({"from": "english", "to": lang_id, "text": json.dumps(batch)}).encode() |
| 498 | req = urllib.request.Request(server.rstrip("/") + "/translate.json", body, |
| 499 | {"content-type": "application/x-www-form-urlencoded"}) |
| 500 | for attempt in range(73): |
| 501 | try: |
| 502 | with urllib.request.urlopen(req, timeout=7200) as r: |
| 503 | d = json.load(r) |
| 504 | except OSError as e: # aien-translate itself down or restarting |
| 505 | print(f" translator unreachable ({e}); retrying in 5 minutes", flush=True) |
| 506 | time.sleep(300); continue |
| 507 | if d.get("result") != 1: |
| 508 | raise SystemExit(f"server refused: {d.get('info')}") |
| 509 | a = d.get("aien") or {} |
| 510 | # A whole batch back untranslated means the model is down or being swapped, not that the |
| 511 | # text is untranslatable: wait and ask again instead of writing English into the output. |
| 512 | if a.get("kept_original", 0) and not a.get("translated", 0) and not a.get("from_cache", 0) and len(batch) > 1: |
| 513 | print(f" {lang_id}: whole batch failed ({a}); model down? retrying in 5 minutes", flush=True) |
| 514 | time.sleep(300); continue |
| 515 | return d |
| 516 | raise SystemExit(f"{lang_id}: the model stayed unavailable for 6 hours; stopping without writing") |
| 517 | |
| 518 | |
| 519 | def translate_all(server, lang_id, texts, chunk_items=None, chunk_chars=None): |
| 520 | chunk_items, chunk_chars = chunk_items or CHUNK_ITEMS, chunk_chars or CHUNK_CHARS |
| 521 | out, pending, i = {}, list(dict.fromkeys(t for t in texts if t)), 0 |
| 522 | while i < len(pending): |
| 523 | batch, chars = [], 0 |
| 524 | while i < len(pending) and (not batch or (len(batch) < chunk_items and chars + len(pending[i]) <= chunk_chars)): |
| 525 | batch.append(pending[i]); chars += len(pending[i]); i += 1 |
| 526 | d = _ask(server, lang_id, batch) |
| 527 | out.update(zip(batch, d["text"])) |
| 528 | print(f" {lang_id}: {i}/{len(pending)} pieces ({d.get('aien')})", flush=True) |
| 529 | # One more try for pieces that came back unchanged (a restart can fail part of a batch). |
| 530 | again = [t for t in pending if out.get(t) == t and re.search(r"[^\W\d_]{2}", t)] |
| 531 | for k in range(0, len(again), 20): |
| 532 | batch = again[k:k + 20] |
| 533 | d = _ask(server, lang_id, batch) |
| 534 | out.update((s, t) for s, t in zip(batch, d["text"]) if t != s) |
| 535 | if again: |
| 536 | left = sum(1 for t in again if out.get(t) == t) |
| 537 | print(f" {lang_id}: retried {len(again)} unchanged pieces, {left} still unchanged", flush=True) |
| 538 | return out |
| 539 | |
| 540 | |
| 541 | def build(tex, code, server, doi, dry=False): |
| 542 | lang_id = LANGS[code][0] |
| 543 | head, rest = tex.split("\\begin{document}", 1) |
| 544 | body, tail = rest.rsplit("\\end{document}", 1) |
| 545 | body = re.sub(r"(\\maketitle[^\n]*\n)", lambda m: m.group(1) + "\n" + note(doi) + "\n", body, count=1) |
| 546 | |
| 547 | # title and date live in the preamble; translate them as their own blocks |
| 548 | plan = [] # list of (where, items) |
| 549 | for m in re.finditer(r"\\(title|date)\{", head): |
| 550 | e = match_brace(head, m.end() - 1) |
| 551 | plan.append(("head", (m.start(), e), runs(parse(head[m.start():e])[0]))) |
| 552 | for blk in units(body): |
| 553 | plan.append(("body", blk, runs(parse(blk)[0]))) |
| 554 | |
| 555 | pieces = [(encode(nodes)) for _, _, items in plan for kind, nodes in items if kind == "piece"] |
| 556 | texts = [p[0] for p in pieces] |
| 557 | print(f"{code}: {len(texts)} pieces, {sum(map(len, texts))} characters", flush=True) |
| 558 | if dry: |
| 559 | return texts |
| 560 | done = translate_all(server, lang_id, texts) |
| 561 | |
| 562 | stats = {"translated": 0, "kept_english": 0} |
| 563 | kept = [] |
| 564 | |
| 565 | def render(items): |
| 566 | out = [] |
| 567 | for kind, val in items: |
| 568 | if kind == "raw": |
| 569 | out.append(val); continue |
| 570 | src, table = encode(val) |
| 571 | lead = re.match(r"\s*", raw_of(val)).group(0) |
| 572 | trail = re.search(r"\s*$", raw_of(val)).group(0) |
| 573 | res = done.get(src) |
| 574 | dec = decode(res, table, code) if res and res != src else None |
| 575 | if dec is None: |
| 576 | stats["kept_english"] += 1; kept.append(src); out.append(raw_of(val)) |
| 577 | else: |
| 578 | stats["translated"] += 1; out.append(lead + dec.strip() + trail) |
| 579 | return "".join(out) |
| 580 | |
| 581 | new_head, pos = [], 0 |
| 582 | for where, span, items in plan: |
| 583 | if where == "head": |
| 584 | new_head.append(head[pos:span[0]]); new_head.append(render(items)); pos = span[1] |
| 585 | new_head.append(head[pos:]) |
| 586 | head2 = preamble_for("".join(new_head), code) |
| 587 | body2 = "".join(render(items) for where, _, items in plan if where == "body") |
| 588 | print(f"{code}: {stats}", flush=True) |
| 589 | return head2 + "\\begin{document}" + body2 + "\\end{document}" + tail, stats, kept |
| 590 | |
| 591 | |
| 592 | def main(): |
| 593 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 594 | ap.add_argument("tex", type=Path) |
| 595 | ap.add_argument("out", type=Path) |
| 596 | ap.add_argument("--langs", default=",".join(LANGS)) |
| 597 | ap.add_argument("--server", default="http://127.0.0.1:18097") |
| 598 | ap.add_argument("--doi", default="") |
| 599 | ap.add_argument("--dry-run", action="store_true", help="print the pieces the model would see, translate nothing") |
| 600 | a = ap.parse_args() |
| 601 | tex = a.tex.read_text() |
| 602 | if a.dry_run: |
| 603 | for t in build(tex, "zh-CN", a.server, a.doi, dry=True): |
| 604 | print(json.dumps(t, ensure_ascii=False)) |
| 605 | return |
| 606 | for code in a.langs.split(","): |
| 607 | if code not in LANGS: |
| 608 | sys.exit(f"unknown language {code}; known: {', '.join(LANGS)}") |
| 609 | d = a.out / code |
| 610 | d.mkdir(parents=True, exist_ok=True) |
| 611 | for f in a.tex.parent.iterdir(): |
| 612 | if f.is_file() and f.suffix not in (".tex", ".pdf", ".html") and f.name != "SHA256SUMS": |
| 613 | shutil.copy2(f, d / f.name) |
| 614 | result, stats, kept = build(tex, code, a.server, a.doi) |
| 615 | (d / a.tex.name).write_text(result) |
| 616 | (d / "kept-english.json").write_text(json.dumps(kept, ensure_ascii=False, indent=1)) |
| 617 | if stats["kept_english"] > 0.05 * (stats["translated"] + stats["kept_english"]): |
| 618 | sys.exit(f"{code}: INCOMPLETE, {stats[kept_english]} pieces still in English (see kept-english.json)") |
| 619 | |
| 620 | |
| 621 | if __name__ == "__main__": |
| 622 | main() |