Datasets:
Download scripts/scholarly_common.py from viktor-shcherb/mathconv-corpus: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/viktor-shcherb/mathconv-corpus/resolve/main/scripts/scholarly_common.py
- Command line
-
hf download hf://datasets/viktor-shcherb/mathconv-corpus/scripts/scholarly_common.py
-
curl -L -o scholarly_common.py https://huggingface.co/datasets/viktor-shcherb/mathconv-corpus/resolve/main/scripts/scholarly_common.py
13.4 kB
| """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) | |