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