File size: 5,997 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
#!/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"<title>(.*?)</title>", 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())