File size: 7,078 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
#!/usr/bin/env python3
"""Extract MathML formulas from OpenStax CNXML books licensed CC BY.

Usage: openstax.py --work DIR --out DIR [--seed N] [--max-total N] [--max-module N]

Each book is a GitHub repository under github.com/openstax.  The script makes
a shallow sparse clone of the collection files and the modules into
`DIR/<repo>` (if absent), reads `md:license` in every collection and keeps a
book only when the licence is CC BY (not NC, not ND).  The `<m:math>` spans
of every module are copied as found (the `m:` prefix is bound by the CNXML
document, not by the span).

TeX: an annotation with encoding `application/x-tex` is kept as `tex`.  An
annotation in the custom encoding `application/vnd.katalysteducation.mathtex`
is kept only when it uses nothing but standard TeX and amsmath commands;
annotations with unit macros such as `\\SI` are left out.

Selection: at most `--max-module` distinct formulas per module and
`--max-total` overall, chosen with a seeded random sample.
"""
import argparse
import html
import os
import random
import re
import subprocess
import sys
from collections import OrderedDict, defaultdict
from datetime import date

import corpus_common as cc

BOOKS = ["osbooks-statistics", "osbooks-precalculo",
         "osbooks-introduccion-estadistica-bundle", "osbooks-fizyka-bundle"]

STANDARD = set("""frac text cdot mathrm pi lambda Delta vec sqrt theta epsilon hat
sin cos tan to int hbar omega nu psi mu gamma alpha beta delta Phi Psi rho tau sigma
infty begin end left right langle rangle leq geq le ge neq times pm mp approx
sim simeq cong propto ll gg ln log exp lim sum prod partial nabla bar overline
underline widetilde widehat dots ldots cdots dot ddot mathbf mathit mathcal mathbb
mathsf boldsymbol varphi phi chi eta kappa Kappa Sigma Lambda Omega Theta Xi Upsilon
iint iiint oint implies mid sinh cosh arcsin arccos arctan tg ctg operatorname
quad qquad tfrac dfrac binom degree circ in notin subset cup cap forall exists
neg vee wedge rightarrow leftarrow Rightarrow Leftrightarrow leftrightarrow
cos tanh ast star bullet prime ell Re Im Gamma Pi xi zeta iota""".split())

TEXCMD = re.compile(r"\\([A-Za-z]+)")


def plain_tex(math):
    for m in cc.ANNOTATION.finditer(math):
        attrs = dict((k.lower(), v.strip("\"'")) for k, v in cc.ATTR.findall(m.group(1)))
        enc = attrs.get("encoding", "")
        text = html.unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip()
        if enc == "application/x-tex":
            return text
        if enc == "application/vnd.katalysteducation.mathtex":
            if all(c in STANDARD for c in TEXCMD.findall(text)):
                return text
    return None


def clone(work, repo):
    dest = os.path.join(work, repo)
    if not os.path.isdir(dest):
        cc.sparse_clone("https://github.com/openstax/" + repo, dest,
                        ["/collections/", "/modules/*/index.cnxml", "/LICENSE*"])
    return dest, subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], capture_output=True,
                                text=True, check=True).stdout.strip()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--work", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--max-total", type=int, default=20000)
    ap.add_argument("--max-module", type=int, default=60)
    a = ap.parse_args()
    os.makedirs(a.work, exist_ok=True)
    today = date.today().isoformat()
    rng = random.Random(a.seed)

    occ = defaultdict(int)        # mathml -> occurrences over all modules
    cand = OrderedDict()          # mathml -> (module key, info)
    per_module = OrderedDict()    # module key -> list of mathml
    modinfo = {}
    found = 0
    for repo in BOOKS:
        dest, commit = clone(a.work, repo)
        coldir = os.path.join(dest, "collections")
        book_of = {}
        for fn in sorted(os.listdir(coldir)):
            text = open(os.path.join(coldir, fn), encoding="utf-8").read()
            lic = re.search(r'<md:license url="([^"]*)"', text)
            title = re.search(r"<md:title>([^<]*)</md:title>", text).group(1)
            auth = re.search(r'\bauthors="([^"]*)"', text)
            if not lic or not re.search(r"/by/\d", lic.group(1)):
                cc.log("skip non CC BY book", repo, fn, lic and lic.group(1))
                continue
            for mod in re.findall(r'<col:module document="([^"]+)"', text):
                book_of.setdefault(mod, (title, auth.group(1) if auth else "OpenStax",
                                         lic.group(1).replace("http://", "https://")))
        for mod in sorted(os.listdir(os.path.join(dest, "modules"))):
            if mod not in book_of:
                continue
            path = "modules/%s/index.cnxml" % mod
            text = open(os.path.join(dest, path), encoding="utf-8").read()
            spans = list(cc.find_spans(text))
            if not spans:
                continue
            key = (repo, mod)
            mt = re.search(r"<title>([^<]*)</title>", text)
            title, authors, lurl = book_of[mod]
            modinfo[key] = dict(
                origin="https://github.com/openstax/%s/blob/%s/%s" % (repo, commit, path),
                title="%s: %s" % (title, mt.group(1) if mt else mod),
                authors=authors, licence_url=lurl, repo=repo, commit=commit, found=len(spans))
            found += len(spans)
            lst = per_module.setdefault(key, [])
            for s, e in spans:
                m = text[s:e]
                occ[m] += 1
                if m not in cand:
                    cand[m] = key
                    lst.append(m)
    cc.log("formulas found", found, "distinct", len(cand))

    chosen = []
    for key, lst in per_module.items():
        pick = lst if len(lst) <= a.max_module else rng.sample(lst, a.max_module)
        chosen.extend(pick)
    if len(chosen) > a.max_total:
        chosen = rng.sample(chosen, a.max_total)
    chosen_set = set(chosen)

    w = cc.Writer("openstax")
    w.stats["formulas_found"] = found
    w.stats["distinct_found"] = len(cand)
    used = OrderedDict()
    for m in cand:
        if m not in chosen_set:
            continue
        key = cand[m]
        info = modinfo[key]
        tex = plain_tex(m)
        w.add(m, producer="OpenStax", origin=info["origin"], licence="CC-BY-4.0",
              licence_url=info["licence_url"], context=cc.context_of(m),
              tex=tex, tex_kind="author" if tex else None,
              markup=cc.classify_markup(m))
        w.rows[m]["count"] = occ[m]
        used[key] = info
    docs = [dict(origin=i["origin"], title=i["title"], authors=i["authors"],
                 licence="CC-BY-4.0", licence_url=i["licence_url"],
                 access_url=i["origin"].replace("/blob/", "/raw/"), retrieved=today,
                 formulas=i["found"])
            for i in used.values()]
    w.write(a.out, docs)
    cc.log("kept", len(w), "documents", len(docs))


if __name__ == "__main__":
    main()