mathconv-corpus / scripts /mathcat_tests.py
viktor-shcherb's picture
Publish version 1 of the corpus
93e3ef1 verified
Raw History Blame Contribute Delete
4.98 kB
#!/usr/bin/env python3
"""Extract MathML test inputs from the MathCAT test suite (MIT licence).
Usage: mathcat_tests.py --work DIR --out DIR
Makes a shallow sparse clone of github.com/NSoiffer/MathCAT limited to
`tests/` and `LICENSE` (into `DIR/mathcat` if absent). The tests are Rust
files whose MathML sits in string literals. A small tokenizer reads the
literals (normal strings with escapes, raw strings `r#"..."#`), skipping
comments and character literals, and every `<math>` element inside a
literal value is taken as written after the literal is unescaped.
Distinct elements are kept; `count` is the number of occurrences.
"""
import argparse
import os
import re
import subprocess
from datetime import date
import corpus_common as cc
REPO = "https://github.com/NSoiffer/MathCAT"
ESC = {"n": "\n", "t": "\t", "r": "\r", "0": "\0", "\\": "\\", '"': '"', "'": "'"}
def rust_strings(src):
"""Yield (value, line) for each string literal of a Rust source text."""
i, n, line = 0, len(src), 1
while i < n:
c = src[i]
if c == "\n":
line += 1
i += 1
elif src.startswith("//", i):
j = src.find("\n", i)
i = n if j < 0 else j
elif src.startswith("/*", i):
j = src.find("*/", i + 2)
j = n if j < 0 else j + 2
line += src.count("\n", i, j)
i = j
elif c == "r" and re.match(r'r#*"', src[i:i + 12]) and (i == 0 or not (src[i - 1].isalnum() or src[i - 1] == "_")):
hashes = re.match(r"r(#*)\"", src[i:i + 12]).group(1)
start = i + 2 + len(hashes)
end = src.find('"' + hashes, start)
if end < 0:
return
yield src[start:end], line
line += src.count("\n", i, end)
i = end + 1 + len(hashes)
elif c == '"':
j, out = i + 1, []
while j < n and src[j] != '"':
if src[j] == "\\":
nx = src[j + 1]
if nx == "\n": # line continuation: skip whitespace
j += 2
while j < n and src[j] in " \t\r\n":
j += 1
continue
if nx == "u":
k = src.index("}", j)
out.append(chr(int(src[j + 3:k], 16)))
j = k + 1
continue
if nx == "x":
out.append(chr(int(src[j + 2:j + 4], 16)))
j += 4
continue
out.append(ESC.get(nx, nx))
j += 2
else:
out.append(src[j])
j += 1
yield "".join(out), line
line += src.count("\n", i, j)
i = j + 1
elif c == "'":
m = re.match(r"'(\\.[^']*|[^\\'])'", src[i:i + 12])
i += m.end() if m else 1
else:
i += 1
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--work", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
dest = os.path.join(a.work, "mathcat")
if not os.path.isdir(dest):
cc.sparse_clone(REPO, dest, ["/tests/", "/LICENSE"])
commit = subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], capture_output=True,
text=True, check=True).stdout.strip()
lurl = "%s/blob/%s/LICENSE" % (REPO, commit)
w = cc.Writer("mathcat-tests")
docs, today = [], date.today().isoformat()
for root, _, files in sorted(os.walk(os.path.join(dest, "tests"))):
for fn in sorted(files):
if not fn.endswith(".rs"):
continue
path = os.path.relpath(os.path.join(root, fn), dest)
src = open(os.path.join(root, fn), encoding="utf-8").read()
n = 0
for value, line in rust_strings(src):
for s, e in cc.find_spans(value):
m = value[s:e]
n += 1
w.add(m, producer="MathCAT test suite", licence="MIT", licence_url=lurl,
origin="%s/blob/%s/%s#L%d" % (REPO, commit, path, line),
context=cc.context_of(m), markup=cc.classify_markup(m))
if n:
docs.append(dict(origin="%s/blob/%s/%s" % (REPO, commit, path), title=path,
authors="Neil Soiffer and MathCAT contributors",
licence="MIT", licence_url=lurl,
access_url="%s/raw/%s/%s" % (REPO, commit, path),
retrieved=today, formulas=n))
w.stats["distinct_found"] = len(w)
w.write(a.out, docs)
cc.log("mathcat rows", len(w), "found", w.found, "files", len(docs))
if __name__ == "__main__":
main()