File size: 12,542 Bytes
93e3ef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
"""Generate MathML from openly licensed TeX with several converters.

Usage:
  generated.py TOOL --pool FILE --out DIR --work DIR [--node-modules DIR]
                     [--seed N] [--n N] [--error-sample N] [--jobs N]

TOOL is one of `katex`, `mathjax`, `temml`, `pandoc`, `latexml`,
`latexml-content`, `latex2mathml`, `wikipedia`.

The pool (`--pool`, made by wikipedia_tex.py, with its `.pages.jsonl`
sidecar) holds TeX formulas taken from Wikipedia wikitext (CC BY-SA 4.0).
A seeded random subset of `--n` formulas (a different subset for every
tool, and a prefix of the larger subset when `--n` is smaller) is converted.  The MathML takes the licence of the TeX: every row
carries the Wikipedia page and revision the TeX came from as `origin`, the
converter and its exact version as `producer`, and the TeX as `tex` with
`tex_kind` "author" (the wikitext TeX was written by a Wikipedia editor).

Formulas the converter rejects are counted in `<source>.stats.json` and
skipped.  Outputs in which the converter reports the error inside the
markup (`<merror>`, red text) are kept for a seeded sample of
`--error-sample` rows and carry a `note`.

Converters: KaTeX and Temml and MathJax run through tex_to_mathml.mjs
(Node.js, packages installed under `--node-modules`); pandoc and
latexmlmath are called as command-line programs; latex2mathml is a Python
package; `wikipedia` posts batches of `<math>` tags to the MediaWiki
`action=parse` API (one request per two seconds) and takes the MathML that
the Wikipedia renderer returns.  Intermediate results are cached in
`--work` so that an interrupted run resumes.
"""
import argparse
import concurrent.futures as cf
import html
import json
import os
import random
import re
import subprocess
import sys
import tempfile
from datetime import date

import corpus_common as cc

HERE = os.path.dirname(os.path.abspath(__file__))
SOURCE = {"katex": "generated-katex", "mathjax": "generated-mathjax", "temml": "generated-temml",
          "pandoc": "generated-pandoc", "latexml": "generated-latexml",
          "latexml-content": "generated-latexml-content", "latex2mathml": "generated-latex2mathml",
          "wikipedia": "wikipedia-render"}
MATH = re.compile(r"<math[\s>].*?</math>", re.S)


# ---------------------------------------------------------------- converters

def run_node(tool, modules, items, work):
    inp, outp = os.path.join(work, tool + ".in.jsonl"), os.path.join(work, tool + ".out.jsonl")
    with open(inp, "w", encoding="utf-8") as f:
        for i, tex, display in items:
            f.write(json.dumps({"i": i, "tex": tex, "display": display}) + "\n")
    subprocess.run(["node", os.path.join(HERE, "tex_to_mathml.mjs"), tool, modules, inp, outp], check=True)
    res, version = {}, None
    for line in open(outp, encoding="utf-8"):
        r = json.loads(line)
        version = r["version"]
        res[r["i"]] = r
    return res, version


def run_pandoc(items, work):
    version = subprocess.run(["pandoc", "--version"], capture_output=True, text=True).stdout.split("\n")[0]
    res = {}
    for b in range(0, len(items), 100):
        batch = items[b:b + 100]
        paras = []
        for i, tex, display in batch:
            t = " ".join(tex.split())
            paras.append("\\[%s\\]" % t if display else "\\(%s\\)" % t)
        src = "\n\n".join(paras) + "\n"
        out = subprocess.run(["pandoc", "-f", "latex", "-t", "html5", "--mathml"], input=src,
                             capture_output=True, text=True).stdout
        parts = re.findall(r"<p>(.*?)</p>", out, re.S)
        if len(parts) != len(batch):      # misaligned: convert one by one
            parts = []
            for i, tex, display in batch:
                t = " ".join(tex.split())
                s1 = "\\[%s\\]\n" % t if display else "\\(%s\\)\n" % t
                o = subprocess.run(["pandoc", "-f", "latex", "-t", "html5", "--mathml"], input=s1,
                                   capture_output=True, text=True).stdout
                m = re.findall(r"<p>(.*?)</p>", o, re.S)
                parts.append(m[0] if len(m) == 1 else "")
        for (i, tex, display), part in zip(batch, parts):
            m = MATH.search(part)
            res[i] = {"mathml": m.group(0)} if m else {"error": "pandoc kept the TeX unconverted"}
    return res, version


LATEXML_VERSION = None


def latexml_one(tex, display, content):
    args = ["latexmlmath", "--preload=amsmath.sty", "--preload=amssymb.sty", "--quiet",
            "--cmml=-" if content else "--pmml=-"]
    try:
        p = subprocess.run(args + [" ".join(tex.split())], capture_output=True, text=True, timeout=60)
    except subprocess.TimeoutExpired:
        return {"error": "timeout"}
    m = MATH.search(p.stdout)
    if not m or p.returncode != 0:
        return {"error": (p.stderr.strip().splitlines() or ["no output"])[-1][:200]}
    r = {"mathml": m.group(0)}
    if "ltx_ERROR" in r["mathml"] or "<merror" in r["mathml"]:
        r["error_markup"] = True
    return r


def run_latexml(items, work, content, jobs):
    cache = os.path.join(work, ("latexml-content" if content else "latexml") + ".results.jsonl")
    res = {}
    if os.path.exists(cache):
        for line in open(cache, encoding="utf-8"):
            r = json.loads(line)
            res[r["i"]] = r
    todo = [it for it in items if it[0] not in res]
    version = subprocess.run(["latexmlmath", "--VERSION"], capture_output=True, text=True)
    version = (version.stdout + version.stderr).strip().splitlines()[0]
    version = re.sub(r"^.*LaTeXML version ", "", version.replace("(", "").replace(")", ""))
    with open(cache, "a", encoding="utf-8") as f, cf.ThreadPoolExecutor(jobs) as ex:
        futs = {ex.submit(latexml_one, tex, display, content): i for i, tex, display in todo}
        for n, fut in enumerate(cf.as_completed(futs)):
            r = fut.result()
            r["i"] = futs[fut]
            res[r["i"]] = r
            f.write(json.dumps(r) + "\n")
            f.flush()
            if n % 200 == 0:
                cc.log("latexml", n, "of", len(todo))
    return res, version


def run_latex2mathml(items):
    import latex2mathml.converter as conv
    from importlib.metadata import version
    res = {}
    for i, tex, display in items:
        try:
            m = conv.convert(tex, display="block" if display else "inline")
            res[i] = {"mathml": m}
            if "<merror" in m:
                res[i]["error_markup"] = True
        except Exception as e:                       # the package raises many exception types
            res[i] = {"error": "%s: %s" % (type(e).__name__, str(e)[:150])}
    return res, "latex2mathml " + version("latex2mathml")


def run_wikipedia(items, work):
    """Render formulas with the Wikipedia math renderer (MediaWiki parse API)."""
    cache = os.path.join(work, "wikipedia-render.results.jsonl")
    res = {}
    if os.path.exists(cache):
        for line in open(cache, encoding="utf-8"):
            r = json.loads(line)
            res[r["i"]] = r
    todo = [it for it in items if it[0] not in res]
    with open(cache, "a", encoding="utf-8") as f:
        for b in range(0, len(todo), 12):
            batch = todo[b:b + 12]
            lines = []
            for i, tex, display in batch:
                t = " ".join(tex.split())
                lines.append('* <math%s>%s</math>' % (' display="block"' if display else "", t))
            body = cc.polite_post("https://en.wikipedia.org/w/api.php", {
                "action": "parse", "contentmodel": "wikitext", "prop": "text", "disablelimitreport": "1",
                "format": "json", "formatversion": "2", "text": "\n".join(lines)}, min_interval=2.0)
            htmltxt = json.loads(body)["parse"]["text"]
            items_html = re.findall(r"<li>(.*?)</li>", htmltxt, re.S)
            if len(items_html) != len(batch):
                items_html = [""] * len(batch)
            for (i, tex, display), h in zip(batch, items_html):
                m = MATH.search(h)
                if m and "texerror" not in h:
                    r = {"i": i, "mathml": m.group(0)}
                else:
                    r = {"i": i, "error": re.sub(r"<[^>]+>", "", h)[:200] or "no output"}
                res[i] = r
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
            f.flush()
            if (b // 12) % 20 == 0:
                cc.log("wikipedia", b, "of", len(todo))
    return res, "Wikipedia renderer (MediaWiki action=parse, retrieved %s)" % date.today().isoformat()


# ---------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("tool", choices=sorted(SOURCE))
    ap.add_argument("--pool", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--work", required=True)
    ap.add_argument("--node-modules")
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--n", type=int, default=8000)
    ap.add_argument("--error-sample", type=int, default=100)
    ap.add_argument("--jobs", type=int, default=3)
    a = ap.parse_args()
    tool = a.tool
    source = SOURCE[tool]
    work = os.path.join(a.work, source)
    os.makedirs(work, exist_ok=True)

    pool = [json.loads(l) for l in open(a.pool, encoding="utf-8")]
    pages = {(p["lang"], p["title"]): p for p in map(json.loads, open(a.pool + ".pages.jsonl", encoding="utf-8"))}
    rng = random.Random("%s/%d" % (source, a.seed))
    # A seeded shuffle of the pool; `--n` takes its prefix, so a smaller `--n`
    # always selects a subset of a larger one and converts in the same order.
    chosen = rng.sample(range(len(pool)), len(pool))[:a.n]
    items = [(i, pool[i]["tex"], pool[i]["context"] == "display") for i in chosen]

    if tool in ("katex", "mathjax", "temml"):
        res, version = run_node(tool, a.node_modules, items, work)
    elif tool == "pandoc":
        res, version = run_pandoc(items, work)
    elif tool in ("latexml", "latexml-content"):
        res, version = run_latexml(items, work, tool == "latexml-content", a.jobs)
        version = "LaTeXML " + version
    elif tool == "latex2mathml":
        res, version = run_latex2mathml(items)
    else:
        res, version = run_wikipedia(items, work)
    if tool == "pandoc":
        version = version.replace("pandoc ", "pandoc ")

    ok = [i for i, _, _ in items if "mathml" in res.get(i, {}) and not res[i].get("error_markup")]
    err_markup = [i for i, _, _ in items if res.get(i, {}).get("error_markup")]
    rejected = [i for i, _, _ in items if "mathml" not in res.get(i, {})]
    keep_err = set(rng.sample(err_markup, min(a.error_sample, len(err_markup))))
    w = cc.Writer(source)
    w.stats["formulas_found"] = len(items)
    per_page = {}
    for i, _, _ in items:
        k = (pool[i]["lang"], pool[i]["title"])
        per_page[k] = per_page.get(k, 0) + 1
    used = {}
    for i, tex, display in items:
        r = res.get(i)
        if not r or "mathml" not in r or (r.get("error_markup") and i not in keep_err):
            continue
        p = pool[i]
        page = pages[(p["lang"], p["title"])]
        m = r["mathml"]
        fields = dict(producer=version, origin=page["origin"], licence="CC-BY-SA-4.0",
                      licence_url=page["licence_url"], context=cc.context_of(m) if cc.context_of(m) != "unknown"
                      else ("display" if display else "inline"), tex=tex, tex_kind="author", markup=cc.classify_markup(m))
        if r.get("error_markup"):
            fields["note"] = "converter error output (error reported inside the markup)"
        w.add(m, **fields)
        used[(p["lang"], p["title"])] = page
    w.stats.update(tool=version, tex_in=len(items), rejected=len(rejected),
                   error_markup_total=len(err_markup), error_markup_kept=len(keep_err),
                   pool_size=len(pool))
    docs = [dict(formulas=per_page[k], origin=p["origin"], title=p["title"], language=p["lang"], revision_id=p["revid"],
                 authors="Wikipedia contributors, see " + p["history_url"], history_url=p["history_url"],
                 licence="CC-BY-SA-4.0", licence_url=p["licence_url"], access_url=p["origin"],
                 retrieved=p["retrieved"]) for k, p in used.items()]
    w.write(a.out, docs)
    cc.log(source, "input", len(items), "kept", len(w), "rejected", len(rejected),
           "error-markup", len(err_markup), version)


if __name__ == "__main__":
    main()