#!/usr/bin/env python3 """Extract MathML formulas from PlanetMath encyclopedia entries. PlanetMath renders its entries with LaTeXML; each ``math`` element carries the TeX of the formula in its ``alttext`` attribute. The site states on its front page that entries are contributed under the Creative Commons Attribution-ShareAlike licence (version 2.5); entry pages carry no licence statement of their own, so the front page is fetched, checked for that statement, and cited as the licence source of every entry. Stages, all resumable: ``run`` reads the alphabetical index, orders the entries by a seeded hash, fetches them at one request per second, samples at most 60 distinct formulas per entry and appends them to a compressed store, until the target number of distinct formulas is reached. ``build`` writes ``planetmath.jsonl`` and ``planetmath.documents.jsonl``. Usage: planetmath.py run --work DIR [--target 3000] [--max-docs N] planetmath.py build --work DIR --out DIR """ import argparse import hashlib import html import json import os import re import sys import scholarly_common as sc SITE = "https://planetmath.org/" INDEX = SITE + "alphabetical.html" SEED = "mathconv-corpus-v1" CAP_PER_DOCUMENT = 60 LICENCE = "CC-BY-SA-2.5" LICENCE_URL = "https://creativecommons.org/licenses/by-sa/2.5/" ENTRY_LINK = re.compile(r'href="https?://planetmath\.org/([^"#/?]+)"') LATEXML_RARE = sc.RARE_ELEMENTS - {"semantics"} def extract_formulas(text): """Return ``(found, formulas)`` for an entry page.""" spans = sc.find_math_spans(text) formulas = {} for a, b in spans: s = text[a:b] rec = formulas.get(s) if rec is None: tex = sc.root_attributes(s).get("alttext") or None formulas[s] = {"n": 1, "context": sc.context_from_display(s), "tex": tex, "tex_kind": "normalised" if tex else None, "markup": sc.classify_markup(s)} else: rec["n"] += 1 return len(spans), formulas def run(args): """Fetch entries until the target number of distinct formulas is reached.""" os.makedirs(args.work, exist_ok=True) http = sc.HttpClient(1.0) done = sc.DoneList(os.path.join(args.work, "run.done")) store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz")) decisions = open(os.path.join(args.work, "decisions.tsv"), "a", encoding="utf-8") try: status, body, _ = http.get(SITE) front = body.decode("utf-8", "replace") if status != 200 or "creativecommons.org/licenses/by-sa/2.5/" not in front: sc.log("licence statement not found on the front page; stopping") return 2 status, body, _ = http.get(INDEX) slugs = sorted(set(ENTRY_LINK.findall(body.decode("utf-8", "replace")))) slugs.sort(key=lambda s: hashlib.sha256((SEED + s).encode()).hexdigest()) distinct = set() for rec in store: distinct.update(sc.formula_id(f["mathml"]) for f in rec["formulas"]) attempts = 0 for slug in slugs: if len(distinct) >= args.target or (args.max_docs and attempts >= args.max_docs): break if slug in done: continue attempts += 1 outcome = process(http, slug, store, distinct) decisions.write(f"{slug}\t{outcome}\n") decisions.flush() done.add(slug) if len(done.keys) % 25 == 0: sc.log("done", len(done.keys), "distinct", len(distinct)) except sc.StopRequested as e: sc.log("stopped:", e) return 3 sc.log("finished, distinct", len(distinct)) return 0 def process(http, slug, store, distinct): """Fetch and store one entry. Returns a short outcome string.""" url = SITE + slug status, body, final = http.get(url) if status != 200: return f"skip: status {status}" text = body.decode("utf-8", "replace") found, formulas = extract_formulas(text) if not formulas: return "skip: no MathML" title = re.search(r"(.*?)", text, re.S) rendered = re.search(r"Generated\s+on\s+\w+\s+\w+\s+\d+\s+[\d:]+\s+(\d{4})", text) chosen = sc.sample_formulas(formulas, CAP_PER_DOCUMENT, SEED, slug, rare=LATEXML_RARE) doc = { "origin": url, "title": " ".join(html.unescape(title.group(1)).split()) if title else slug, "authors": None, "journal": "PlanetMath", "year": rendered.group(1) if rendered else None, "year_kind": "rendered", "publisher": "PlanetMath", "producer": "LaTeXML", "licence": LICENCE, "licence_url": LICENCE_URL, "licence_source": SITE + " (front page statement for all entries)", "access_url": final, "retrieved": sc.today(), "formulas_found": found, "formulas_distinct": len(formulas), } store.append({"doc": doc, "formulas": [dict(mathml=s, **rec) for s, rec in chosen]}) distinct.update(sc.formula_id(s) for s, _ in chosen) return f"kept {len(chosen)}/{len(formulas)}" def build(args): """Merge the store into ``planetmath.jsonl`` and ``planetmath.documents.jsonl``.""" store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz")) print(json.dumps(sc.build_outputs(store, "planetmath", args.out), indent=1)) def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = p.add_subparsers(dest="cmd", required=True) r = sub.add_parser("run") r.add_argument("--work", required=True) r.add_argument("--target", type=int, default=3000) r.add_argument("--max-docs", type=int, default=0) b = sub.add_parser("build") b.add_argument("--work", required=True) b.add_argument("--out", required=True) args = p.parse_args() return {"run": run, "build": build}[args.cmd](args) if __name__ == "__main__": sys.exit(main())