Datasets:
File size: 13,374 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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | """Shared helpers for the scholarly-source MathML extraction scripts.
The scripts ``pmc.py``, ``arxiv_html.py`` and ``planetmath.py`` collect
individual MathML formulas from openly licensed scholarly sources. This
module holds what they share:
* a scanner that finds ``<math>`` elements as text spans, so a formula is
kept exactly as written in the source;
* a classifier for the element vocabulary (presentation, content, mixed);
* a per-document sampler that caps the formulas taken from one document
and prefers structural variety;
* resumable state: a done-list and a compressed per-document store;
* the final build that merges per-document records into one row per
distinct formula, plus an attribution file with one line per document;
* a rate-limited HTTP client that stops on 429 and 403 responses.
Only the Python standard library is used.
"""
import gzip
import hashlib
import html
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
USER_AGENT = "mathml-corpus-builder/0.1"
# Elements that are rare in running text. Formulas containing one of them
# are taken first (up to the per-document cap), then the rest is filled in.
RARE_ELEMENTS = frozenset(
"""mtable mfenced mmultiscripts menclose mpadded mphantom munderover
mlabeledtr semantics maction mglyph mstack mlongdiv mscarries
mprescripts merror""".split()
)
PRESENTATION_ELEMENTS = frozenset(
"""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 maligngroup
malignmark mglyph mlongdiv mscarries mscarry msgroup msline msrow
mstack maction""".split()
)
CONTENT_ELEMENTS = frozenset(
"""apply ci cn csymbol cs bvar lambda interval piecewise piece otherwise
plus minus times divide power root quotient rem factorial abs conjugate
eq neq leq geq lt gt approx and or not xor implies forall exists in
notin subset prsubset notsubset notprsubset union intersect setdiff
sin cos tan sec csc cot sinh cosh tanh arcsin arccos arctan ln log exp
diff partialdiff int sum product limit condition degree logbase
lowlimit uplimit domainofapplication set list vector matrix matrixrow
determinant transpose inverse compose ident domain codomain image
declare fn max min gcd lcm floor ceiling real imaginary arg card
scalarproduct outerproduct vectorproduct selector true false pi
exponentiale infinity notanumber""".split()
)
MATH_TOKEN = re.compile(r"<(/?)(?:[A-Za-z][\w.-]*:)?math(?=[\s>/])", re.I)
ELEMENT_NAME = re.compile(r"<(?:[A-Za-z][\w.-]*:)?([A-Za-z][\w.-]*)")
TAG_END = re.compile(r"[^>]*>")
def find_math_spans(text):
"""Return ``(start, end)`` offsets of every outermost math element.
Opening and closing tags are matched by nesting depth, so a math
element nested inside an annotation stays part of its parent. The
namespace prefix is ignored, so ``<mml:math>`` and ``<m:math>`` are
found. An element that is never closed is skipped.
"""
spans = []
depth = 0
start = 0
for m in MATH_TOKEN.finditer(text):
if m.group(1) != "/":
end = TAG_END.match(text, m.end())
if end is None:
break
if text[end.end() - 2] == "/": # self-closing, an empty element
if depth == 0:
spans.append((m.start(), end.end()))
continue
if depth == 0:
start = m.start()
depth += 1
elif depth:
depth -= 1
if depth == 0:
end = TAG_END.match(text, m.end())
spans.append((start, end.end() if end else m.end()))
return spans
def element_names(mathml):
"""Return the set of lower-case local element names in a MathML string."""
return {n.lower() for n in ELEMENT_NAME.findall(mathml)}
def classify_markup(mathml):
"""Return ``presentation``, ``content`` or ``mixed`` for a formula.
Elements inside ``semantics`` annotations count like any other
element. A formula with neither vocabulary is ``presentation``.
"""
names = element_names(mathml)
content = bool(names & CONTENT_ELEMENTS)
presentation = bool(names & PRESENTATION_ELEMENTS)
if content and presentation:
return "mixed"
return "content" if content else "presentation"
def formula_id(mathml):
"""First 16 hex characters of the SHA-256 of the MathML string."""
return hashlib.sha256(mathml.encode("utf-8")).hexdigest()[:16]
def root_attributes(mathml):
"""Return the attributes of the root ``math`` start tag as a dict."""
tag = TAG_END.match(mathml, 1)
text = mathml[: tag.end()] if tag else mathml
return {k.lower(): html.unescape(v.strip("\"'"))
for k, v in re.findall(r"""([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""", text)}
def context_from_display(mathml):
"""Context from the ``display`` attribute: inline, display or unknown."""
d = root_attributes(mathml).get("display", "").lower()
return {"inline": "inline", "block": "display"}.get(d, "unknown")
def tidy_tex(tex):
"""Strip delimiters and document boilerplate around a TeX formula.
Publisher TeX is often wrapped in a minimal document or in ``$``
delimiters. The body between them is returned; the formula text is
otherwise untouched.
"""
if tex is None:
return None
tex = tex.strip()
m = re.search(r"\\begin\{document\}(.*)\\end\{document\}", tex, re.S)
if m:
tex = m.group(1).strip()
for left, right in (("$$", "$$"), ("$", "$"), ("\\[", "\\]"), ("\\(", "\\)")):
if len(tex) > len(left) + len(right) and tex.startswith(left) and tex.endswith(right):
tex = tex[len(left):-len(right)].strip()
break
return tex or None
def sample_formulas(formulas, cap, seed, key, rare=RARE_ELEMENTS):
"""Choose at most ``cap`` distinct formulas of one document.
``formulas`` maps a MathML string to its record. Formulas that
contain a rare element are taken first; the remainder is filled from
the other formulas. Within each class the order is a deterministic
shuffle: strings are ordered by the SHA-256 of ``seed|key|mathml``,
so the same input always gives the same sample. ``rare`` is the set
of element names that mark a formula as structurally interesting; a
source in which every formula contains one of them (``semantics`` in
LaTeXML output) passes a smaller set. Returns a list of
``(mathml, record)`` in selection order.
"""
def order(s):
return hashlib.sha256(f"{seed}|{key}|{s}".encode("utf-8")).hexdigest()
rare_list, common = [], []
for s in formulas:
(rare_list if element_names(s) & rare else common).append(s)
rare_list.sort(key=order)
common.sort(key=order)
return [(s, formulas[s]) for s in (rare_list + common)[:cap]]
def today():
"""Retrieval date in ISO form (UTC)."""
return time.strftime("%Y-%m-%d", time.gmtime())
class DoneList:
"""A set of finished document keys, kept in a text file.
Each key is appended and flushed as soon as the document's record has
been stored, so an interrupted run resumes without repeating work.
"""
def __init__(self, path):
self.path = path
self.keys = set()
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
self.keys = {line.rstrip("\n") for line in f if line.strip()}
self._f = open(path, "a", encoding="utf-8")
def __contains__(self, key):
return key in self.keys
def add(self, key):
if key not in self.keys:
self.keys.add(key)
self._f.write(key + "\n")
self._f.flush()
class DocumentStore:
"""Append-only, gzip-compressed store with one JSON line per document.
A line holds ``{"doc": {...}, "formulas": [...]}``. Every append is a
complete gzip member, so a run that stops half way leaves a readable
file. A document is stored before its key is added to the done list;
a key without a record is processed again, and a duplicate record is
dropped when the store is read.
"""
def __init__(self, path):
self.path = path
def append(self, record):
data = (json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
with open(self.path, "ab") as f:
f.write(gzip.compress(data, 6))
f.flush()
def __iter__(self):
if not os.path.exists(self.path):
return
seen = set()
with gzip.open(self.path, "rt", encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line)
except ValueError:
continue
key = rec["doc"]["origin"]
if key in seen:
continue
seen.add(key)
yield rec
def build_outputs(store, source, out_dir):
"""Write ``<source>.jsonl`` and ``<source>.documents.jsonl``.
The store is read twice so that memory holds only formula ids: the
first pass sums occurrences per distinct formula, the second writes
each formula once, with the metadata of the first document that
contributed it. ``count`` is the number of occurrences of the exact
string in all documents that contributed it to the sample. Returns a
summary dict.
"""
counts = {}
for rec in store:
for fm in rec["formulas"]:
i = formula_id(fm["mathml"])
counts[i] = counts.get(i, 0) + fm["n"]
os.makedirs(out_dir, exist_ok=True)
rows_path = os.path.join(out_dir, f"{source}.jsonl")
docs_path = os.path.join(out_dir, f"{source}.documents.jsonl")
written = set()
n_docs = 0
with open(rows_path, "w", encoding="utf-8") as rows, \
open(docs_path, "w", encoding="utf-8") as docs:
for rec in store:
d = rec["doc"]
kept = 0
for fm in rec["formulas"]:
i = formula_id(fm["mathml"])
if i in written:
continue
written.add(i)
kept += 1
row = {
"id": i,
"mathml": fm["mathml"],
"source": source,
"producer": d["producer"],
"origin": d["origin"],
"licence": d["licence"],
"licence_url": d["licence_url"],
"context": fm["context"],
"tex": fm["tex"],
"tex_kind": fm["tex_kind"],
"markup": fm["markup"],
"count": counts[i],
}
rows.write(json.dumps(row, ensure_ascii=False) + "\n")
out = dict(d)
out["formulas_sampled"] = len(rec["formulas"])
out["formulas_first_seen_here"] = kept
docs.write(json.dumps(out, ensure_ascii=False) + "\n")
n_docs += 1
return {"documents": n_docs, "distinct": len(written),
"rows": rows_path, "documents_file": docs_path}
class StopRequested(Exception):
"""Raised when a service answers 429 or 403: the run must stop."""
class HttpClient:
"""A polite HTTP client: fixed spacing between requests, no parallelism.
``min_interval`` is the minimum number of seconds between the starts
of two requests made through this client. A 429 or 403 response is
never retried: the client raises ``StopRequested`` so the caller can
save its state and exit. Network errors and 5xx answers are retried
a few times with growing waits.
"""
def __init__(self, min_interval, user_agent=USER_AGENT):
self.min_interval = min_interval
self.user_agent = user_agent
self._last = 0.0
def get(self, url, timeout=60):
"""Return ``(status, body_bytes, final_url)``; 404 gives ``(404, b"", url)``."""
for attempt in range(4):
wait = self._last + self.min_interval - time.monotonic()
if wait > 0:
time.sleep(wait)
self._last = time.monotonic()
req = urllib.request.Request(
url, headers={"User-Agent": self.user_agent, "Accept-Encoding": "gzip"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
body = r.read()
if r.headers.get("Content-Encoding") == "gzip":
body = gzip.decompress(body)
return r.status, body, r.geturl()
except urllib.error.HTTPError as e:
if e.code in (429, 403):
raise StopRequested(f"HTTP {e.code} from {url}")
if e.code < 500:
return e.code, b"", url
except (urllib.error.URLError, TimeoutError, ConnectionError):
pass
time.sleep(5 * (attempt + 1) ** 2)
raise StopRequested(f"repeated failures for {url}")
def log(*args):
"""Print a time-stamped progress line to standard error."""
print(time.strftime("%H:%M:%S"), *args, file=sys.stderr, flush=True)
|