Datasets:
File size: 10,925 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 | """Shared helpers for the corpus extraction scripts.
Every script writes one JSON object per line (a "row") to
`<out>/<source>.jsonl` and one line per used document to
`<out>/<source>.documents.jsonl`. Rows with identical `mathml` are merged
and their `count` summed; the first occurrence supplies the other fields.
Row fields: id, mathml, source, producer, origin, licence, licence_url,
context, tex, tex_kind, markup, count, and an optional note.
"""
import hashlib
import html
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
USER_AGENT = "mathml-corpus-builder/0.1"
_last_request = {}
def polite_get(url, min_interval=1.0, retries=3, binary=False):
"""GET `url` with a generic client name, at most one request per
`min_interval` seconds per host. On HTTP 429 it waits (at least 30 s, or
the Retry-After time), doubles its interval and retries; after repeated
429s, or on HTTP 403, it raises so the run stops."""
host = url.split("/")[2]
for attempt in range(retries + 1):
wait = _last_request.get(host, 0) + min_interval - time.time()
if wait > 0:
time.sleep(wait)
_last_request[host] = time.time()
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(req, timeout=60) as r:
data = r.read()
return data if binary else data.decode("utf-8", "replace")
except urllib.error.HTTPError as e:
if e.code == 429 and attempt < retries:
# Back off for the time the server asks (at least 30 s), then retry.
try:
ra = int(e.headers.get("Retry-After", "0"))
except ValueError:
ra = 0
time.sleep(min(max(ra, 30) * (attempt + 1), 300))
min_interval = min_interval * 2
continue
if e.code in (429, 403):
raise RuntimeError("HTTP %d from %s: stop and back off" % (e.code, host))
if attempt == retries or 400 <= e.code < 500:
raise
time.sleep(2 * (attempt + 1))
except (urllib.error.URLError, TimeoutError):
if attempt == retries:
raise
time.sleep(2 * (attempt + 1))
def polite_post(url, fields, min_interval=1.0, retries=3):
"""POST form `fields` (dict) with the same politeness and back-off rules
as `polite_get`."""
import urllib.parse
host = url.split("/")[2]
body = urllib.parse.urlencode(fields).encode()
for attempt in range(retries + 1):
wait = _last_request.get(host, 0) + min_interval - time.time()
if wait > 0:
time.sleep(wait)
_last_request[host] = time.time()
req = urllib.request.Request(url, data=body, headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(req, timeout=120) as r:
return r.read().decode("utf-8", "replace")
except urllib.error.HTTPError as e:
if e.code == 429 and attempt < retries:
try:
ra = int(e.headers.get("Retry-After", "0"))
except ValueError:
ra = 0
time.sleep(min(max(ra, 30) * (attempt + 1), 300))
min_interval *= 2
continue
if e.code in (429, 403):
raise RuntimeError("HTTP %d from %s: stop and back off" % (e.code, host))
raise
def sparse_clone(repo_url, dest, paths, ref=None):
"""Shallow, blob-less, sparse clone of `repo_url` into `dest` limited to
`paths`. Returns the commit hash checked out."""
subprocess.run(["git", "clone", "--depth", "1", "--filter=blob:none",
"--sparse", repo_url, dest], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["git", "-C", dest, "sparse-checkout", "set", "--no-cone"] + paths,
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], check=True,
capture_output=True, text=True).stdout.strip()
MATH_OPEN = re.compile(r"<(?:[A-Za-z][\w.-]*:)?math(?=[\s>/])", re.I)
MATH_CLOSE = re.compile(r"</(?:[A-Za-z][\w.-]*:)?math\s*>", re.I)
ATTR = re.compile(r"""([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""")
TAG = re.compile(r"<(/?)(?:[A-Za-z][\w.-]*:)?([A-Za-z][\w.-]*)")
ANNOTATION = re.compile(
r"<(?:\w+:)?annotation\b([^>]*)>(.*?)</(?:\w+:)?annotation\s*>", re.S | re.I)
CONTENT_ELEMENTS = {
"apply", "ci", "cn", "csymbol", "bvar", "lambda", "piecewise", "piece",
"otherwise", "plus", "minus", "times", "divide", "power", "root", "eq",
"neq", "gt", "lt", "geq", "leq", "and", "or", "not", "exp", "ln", "log",
"sin", "cos", "tan", "sum", "int", "diff", "partialdiff", "factorial",
"abs", "floor", "ceiling", "max", "min", "rem", "quotient", "implies",
"xor", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "selector",
"vector", "matrix", "set", "list", "interval", "limit", "condition",
"lowlimit", "uplimit", "degree", "logbase", "domainofapplication",
"true", "false", "pi", "exponentiale", "notanumber", "infinity",
"cs", "cbytes", "declare", "forall", "exists", "in", "notin",
}
PRESENTATION_ELEMENTS = {
"mi", "mn", "mo", "mtext", "mspace", "ms", "mrow", "mfrac", "msqrt",
"mroot", "mstyle", "merror", "mpadded", "mphantom", "mfenced", "menclose",
"msub", "msup", "msubsup", "munder", "mover", "munderover",
"mmultiscripts", "mprescripts", "none", "mtable", "mtr", "mtd",
"mlabeledtr", "maction", "semantics", "annotation", "annotation-xml",
"mglyph", "malignmark", "maligngroup", "mlongdiv", "mscarries",
"mscarry", "msgroup", "msline", "msrow", "mstack",
}
def element_names(mathml):
"""Local names of all elements in a MathML string (lower case)."""
return {m.group(2).lower() for m in TAG.finditer(mathml) if not m.group(1)}
def classify_markup(mathml):
"""Return 'presentation', 'content' or 'mixed' from the element names."""
names = element_names(mathml)
has_c = bool(names & {"apply", "ci", "csymbol", "bvar", "lambda", "piecewise", "cn"}) \
or bool(names & CONTENT_ELEMENTS - {"set", "list", "in", "min", "max", "none"} - PRESENTATION_ELEMENTS)
has_p = bool(names & {"mi", "mo", "mrow", "mfrac", "msup", "msub", "mtext",
"mtable", "msqrt", "mover", "munder", "mspace", "ms"})
if "cn" in names and not has_p and "apply" not in names and "ci" not in names:
return "content"
if has_c and has_p:
return "mixed"
if has_c:
return "content"
return "presentation"
def find_spans(text):
"""Yield the (start, end) of each <math>..</math> span in `text`.
An empty `<math/>` is one span; an unclosed `<math>` followed by another
opening tag is skipped."""
pos = 0
while True:
m = MATH_OPEN.search(text, pos)
if not m:
return
gt = text.find(">", m.end())
if gt > 0 and text[gt - 1] == "/" and "<" not in text[m.end():gt]:
yield m.start(), gt + 1 # empty element <math/>
pos = gt + 1
continue
c = MATH_CLOSE.search(text, m.end())
if not c:
return
nxt = MATH_OPEN.search(text, m.end(), c.start())
if nxt: # unclosed element: restart at the inner one
pos = nxt.start()
continue
yield m.start(), c.end()
pos = c.end()
def root_attrs(mathml):
tag = re.match(r"<[^>]*>", mathml).group(0)
return {k.lower(): html.unescape(v.strip("\"'")) for k, v in ATTR.findall(tag)}
def context_of(mathml):
d = root_attrs(mathml).get("display", "").lower()
return {"inline": "inline", "block": "display"}.get(d, "unknown")
def plain_tex_annotation(mathml):
"""Text of an annotation whose encoding mentions TeX, else None."""
for m in ANNOTATION.finditer(mathml):
enc = dict((k.lower(), v.strip("\"'")) for k, v in ATTR.findall(m.group(1))).get("encoding", "")
if "tex" in enc.lower():
return html.unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip()
return None
def row_id(mathml):
return hashlib.sha256(mathml.encode("utf-8")).hexdigest()[:16]
class Writer:
"""Collects rows, merging identical `mathml`, and writes them sorted by
first appearance. `cap` limits distinct rows (None = unlimited)."""
def __init__(self, source):
self.source = source
self.rows = {}
self.found = 0
self.stats = {}
def add(self, mathml, **fields):
self.found += 1
if mathml in self.rows:
self.rows[mathml]["count"] += 1
return False
row = {"id": row_id(mathml), "mathml": mathml, "source": self.source}
row.update(fields)
row.setdefault("tex", None)
row.setdefault("tex_kind", None)
row["count"] = 1
self.rows[mathml] = row
return True
def __len__(self):
return len(self.rows)
def write(self, out_dir, documents=()):
os.makedirs(out_dir, exist_ok=True)
order = ["id", "mathml", "source", "producer", "origin", "licence",
"licence_url", "context", "tex", "tex_kind", "markup", "count", "note"]
with open(os.path.join(out_dir, self.source + ".jsonl"), "w", encoding="utf-8") as f:
for row in self.rows.values():
o = {k: row[k] for k in order if k in row}
f.write(json.dumps(o, ensure_ascii=False) + "\n")
by_origin = {}
producer = next(iter(self.rows.values()), {}).get("producer")
for r in self.rows.values():
o = r["origin"].split("#")[0]
by_origin[o] = by_origin.get(o, 0) + 1
docs = []
for d in documents:
d = dict(d)
d.setdefault("producer", producer)
if "formulas" in d:
d["formulas_found"] = d.pop("formulas")
d["formulas_sampled"] = by_origin.get(d["origin"], 0)
docs.append(d)
stats = dict(formulas_found=self.found, distinct_kept=len(self.rows))
stats.update(self.stats)
with open(os.path.join(out_dir, self.source + ".stats.json"), "w") as f:
json.dump(stats, f, indent=1, sort_keys=True)
with open(os.path.join(out_dir, self.source + ".documents.jsonl"), "w", encoding="utf-8") as f:
for d in docs:
f.write(json.dumps(d, ensure_ascii=False) + "\n")
def read_rows(path):
with open(path, encoding="utf-8") as f:
for line in f:
yield json.loads(line)
def log(*a):
print(*a, file=sys.stderr, flush=True)
|