mathconv-corpus / scripts /arxiv_html.py
viktor-shcherb's picture
Publish version 1 of the corpus
93e3ef1 verified
Raw History Blame Contribute Delete
11.7 kB
#!/usr/bin/env python3
"""Extract MathML formulas from arXiv HTML (LaTeXML) pages.
Only papers whose arXiv licence is CC BY, CC BY-SA or CC0 are used. The
licence is read from the OAI-PMH service (``metadataPrefix=arXiv``, the
``<license>`` element); the record's datestamp and the version of the
HTML page that was fetched are stored with every document.
Stages, all resumable:
``select`` lists records of several subject sets for a series of
dates and keeps those with an accepted licence that were
first submitted on or after the date from which HTML is
generated (``--created-after``).
``extract`` fetches the HTML page of each candidate (one request every
15 seconds, the crawl delay in the site's robots.txt),
collects the ``math`` elements, samples at most 60
distinct formulas per paper and appends them to a
compressed store. Pages are never kept.
``build`` writes ``arxiv-html.jsonl`` and ``arxiv-html.documents.jsonl``.
The TeX of a formula is the ``application/x-tex`` annotation. LaTeXML
produces it from the author's source and normalises it, so it is
recorded with ``tex_kind`` ``normalised``.
Usage:
arxiv_html.py select --work DIR [--start 2023-12-15 --end 2026-11-15 --step-days 42]
[--sets math,cs] [--window-days 7]
arxiv_html.py extract --work DIR [--target 30000] [--max-docs N]
arxiv_html.py build --work DIR --out DIR
"""
import argparse
import datetime
import hashlib
import html
import json
import os
import re
import sys
import urllib.parse
import xml.etree.ElementTree as ET
import scholarly_common as sc
OAI = "https://oaipmh.arxiv.org/oai"
HTML_BASE = "https://arxiv.org/html/"
SEED = "mathconv-corpus-v1"
CAP_PER_DOCUMENT = 60
HTML_DELAY = 15.0 # seconds between page requests (robots.txt crawl delay)
OAI_DELAY = 5.0 # seconds between OAI-PMH requests
# Subject sets and their share of the formulas.
SETS = {"math": 0.20, "physics": 0.20, "cs": 0.20, "stat": 0.12,
"eess": 0.10, "q-bio": 0.10, "econ": 0.08}
LICENCES = {
"by": "CC-BY", "by-sa": "CC-BY-SA",
}
LICENCE_URL = re.compile(r"^https?://creativecommons\.org/(licenses/(by|by-sa)/(\d\.\d)|publicdomain/zero/(1\.0))/?$")
NS = {"o": "http://www.openarchives.org/OAI/2.0/", "a": "http://arxiv.org/OAI/arXiv/"}
LATEXML_RARE = sc.RARE_ELEMENTS - {"semantics"}
def spdx_of(url):
"""SPDX identifier for an accepted Creative Commons URL, else None."""
m = LICENCE_URL.match((url or "").strip())
if not m:
return None
if m.group(4):
return "CC0-1.0"
return f"{LICENCES[m.group(2)]}-{m.group(3)}"
def select(args):
"""List OAI-PMH records and write accepted candidates to candidates.jsonl."""
os.makedirs(args.work, exist_ok=True)
http = sc.HttpClient(OAI_DELAY)
done = sc.DoneList(os.path.join(args.work, "select.done"))
seen = set()
path = os.path.join(args.work, "candidates.jsonl")
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
seen = {json.loads(line)["id"] for line in f}
out = open(path, "a", encoding="utf-8")
day = datetime.date.fromisoformat(args.start)
end = datetime.date.fromisoformat(args.end)
step = datetime.timedelta(days=args.step_days)
try:
while day <= end:
for subject in (args.sets.split(",") if args.sets else SETS):
key = f"{subject}|{day}|{args.window_days}"
if key in done:
continue
query = urllib.parse.urlencode({
"verb": "ListRecords", "metadataPrefix": "arXiv", "set": subject,
"from": str(day),
"until": str(day + datetime.timedelta(days=args.window_days - 1))})
status, body, _ = http.get(f"{OAI}?{query}")
if status != 200:
sc.log("select failed", key, status)
continue
n_all, n_kept = 0, 0
root = ET.fromstring(body)
for rec in root.iter("{%s}record" % NS["o"]):
meta = rec.find("o:metadata/a:arXiv", NS)
if meta is None:
continue
n_all += 1
arxiv_id = meta.findtext("a:id", "", NS)
licence = meta.findtext("a:license", "", NS)
spdx = spdx_of(licence)
created = meta.findtext("a:created", "", NS)
if spdx is None or created < args.created_after or arxiv_id in seen:
continue
seen.add(arxiv_id)
n_kept += 1
authors = []
for au in meta.findall("a:authors/a:author", NS):
name = " ".join(x for x in (au.findtext("a:forenames", "", NS),
au.findtext("a:keyname", "", NS)) if x)
authors.append(name)
out.write(json.dumps({
"id": arxiv_id, "set": subject, "title": " ".join(meta.findtext("a:title", "", NS).split()),
"authors": "; ".join(authors), "categories": meta.findtext("a:categories", "", NS),
"created": created, "oai_datestamp": rec.findtext("o:header/o:datestamp", "", NS),
"licence": spdx, "licence_url": licence.strip()}, ensure_ascii=False) + "\n")
out.flush()
done.add(key)
sc.log("select", key, "records", n_all, "accepted", n_kept)
day += step
except sc.StopRequested as e:
sc.log("stopped:", e)
return 3
return 0
ANNOTATION_TEX = re.compile(
r"<annotation\b[^>]*encoding=[\"']application/x-tex[\"'][^>]*>(.*?)</annotation\s*>", re.S | re.I)
def extract_formulas(text):
"""Return ``(found, formulas)`` for an HTML page, one record per distinct math element."""
spans = sc.find_math_spans(text)
formulas = {}
for a, b in spans:
s = text[a:b]
rec = formulas.get(s)
if rec is None:
m = ANNOTATION_TEX.search(s)
tex = html.unescape(m.group(1)).strip() if m else None
if not tex:
tex = sc.root_attributes(s).get("alttext")
formulas[s] = {"n": 1, "context": sc.context_from_display(s), "tex": tex or None,
"tex_kind": "normalised" if tex else None, "markup": sc.classify_markup(s)}
else:
rec["n"] += 1
return len(spans), formulas
def load_queues(work):
queues = {s: [] for s in SETS}
with open(os.path.join(work, "candidates.jsonl"), encoding="utf-8") as f:
for line in f:
r = json.loads(line)
queues[r["set"]].append(r)
for q in queues.values():
q.sort(key=lambda r: hashlib.sha256((SEED + r["id"]).encode()).hexdigest())
return queues
def extract(args):
"""Fetch pages until the target number of distinct formulas is reached."""
http = sc.HttpClient(HTML_DELAY)
done = sc.DoneList(os.path.join(args.work, "extract.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")
queues = load_queues(args.work)
distinct, per_set = set(), {s: 0 for s in SETS}
for rec in store:
distinct.update(sc.formula_id(f["mathml"]) for f in rec["formulas"])
per_set[rec["doc"]["set"]] += len(rec["formulas"])
cursor = {s: 0 for s in SETS}
attempts = 0
try:
while len(distinct) < args.target and (not args.max_docs or attempts < args.max_docs):
open_sets = [s for s in SETS if cursor[s] < len(queues[s])]
if not open_sets:
break
subject = max(open_sets, key=lambda s: SETS[s] * args.target - per_set[s])
cand = queues[subject][cursor[subject]]
cursor[subject] += 1
if cand["id"] in done:
continue
attempts += 1
outcome = process(http, cand, store, distinct, per_set)
decisions.write(f"{cand['id']}\t{subject}\t{outcome}\n")
decisions.flush()
done.add(cand["id"])
if len(done.keys) % 10 == 0:
sc.log("done", len(done.keys), "distinct", len(distinct), per_set)
except sc.StopRequested as e:
sc.log("stopped:", e)
return 3
sc.log("finished, distinct", len(distinct))
return 0
def process(http, cand, store, distinct, per_set):
"""Fetch and store one paper. Returns a short outcome string."""
status, body, final = http.get(HTML_BASE + cand["id"])
if status != 200:
return f"skip: html status {status}"
text = body.decode("utf-8", "replace")
found, formulas = extract_formulas(text)
if not formulas:
return "skip: no MathML"
m = re.search(rf"arXiv:{re.escape(cand['id'])}(v\d+)", text)
version = m.group(1) if m else ""
chosen = sc.sample_formulas(formulas, CAP_PER_DOCUMENT, SEED, cand["id"], rare=LATEXML_RARE)
doc = {
"origin": f"https://arxiv.org/abs/{cand['id']}{version}", "arxiv_id": cand["id"],
"version": version, "title": cand["title"], "authors": cand["authors"],
"journal": "arXiv " + cand["categories"].split()[0], "categories": cand["categories"],
"year": ("20" + cand["id"][:2]) if re.match(r"\d{4}\.", cand["id"]) else cand["created"][:4], "publisher": "arXiv", "producer": "LaTeXML",
"set": cand["set"], "licence": cand["licence"], "licence_url": cand["licence_url"],
"licence_source": f"{OAI} (metadataPrefix=arXiv, license element)",
"oai_datestamp": cand["oai_datestamp"], "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)
per_set[cand["set"]] += len(chosen)
return f"kept {len(chosen)}/{len(formulas)}"
def build(args):
"""Merge the store into ``arxiv-html.jsonl`` and ``arxiv-html.documents.jsonl``."""
store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz"))
print(json.dumps(sc.build_outputs(store, "arxiv-html", args.out), indent=1))
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("select")
s.add_argument("--work", required=True)
s.add_argument("--start", default="2023-12-15")
s.add_argument("--end", default="2026-11-15")
s.add_argument("--step-days", type=int, default=42)
s.add_argument("--sets", default="", help="comma-separated subject sets (default: all)")
s.add_argument("--window-days", type=int, default=1, help="days of datestamps listed per request")
s.add_argument("--created-after", default="2023-12-01",
help="skip papers first submitted before this date (no HTML is generated for them)")
e = sub.add_parser("extract")
e.add_argument("--work", required=True)
e.add_argument("--target", type=int, default=30000)
e.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 {"select": select, "extract": extract, "build": build}[args.cmd](args)
if __name__ == "__main__":
sys.exit(main())