#!/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/` (if absent), reads `md:license` in every collection and keeps a book only when the licence is CC BY (not NC, not ND). The `` 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'([^<]*)", 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'([^<]*)", 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()