File size: 11,728 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
#!/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())