#!/usr/bin/env python3 """Extract `` code examples from the MDN MathML documentation. Usage: mdn.py --work DIR --out DIR Makes a shallow sparse clone of github.com/mdn/content limited to `files/en-us/web/mathml/` (into `DIR/mdn` if absent). Code examples on MDN are in the public domain (CC0 1.0); the repository's LICENSE.md states this and is the recorded licence URL. Only `` elements inside fenced code blocks are taken; prose and inline code are not. Elements are copied as written (HTML5 syntax, no namespace declaration unless the example has one). """ import argparse import os import re import subprocess from datetime import date import corpus_common as cc REPO = "https://github.com/mdn/content" SUB = "files/en-us/web/mathml" FENCE = re.compile(r"^```[^\n]*\n(.*?)^```", re.S | re.M) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--work", required=True) ap.add_argument("--out", required=True) a = ap.parse_args() dest = os.path.join(a.work, "mdn") if not os.path.isdir(dest): cc.sparse_clone(REPO, dest, ["/%s/" % SUB, "/LICENSE.md"]) commit = subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() licence_url = "%s/blob/%s/LICENSE.md" % (REPO, commit) w = cc.Writer("mdn") docs = [] today = date.today().isoformat() for root, _, files in sorted(os.walk(os.path.join(dest, SUB))): for fn in sorted(files): if fn != "index.md": continue path = os.path.relpath(os.path.join(root, fn), dest) text = open(os.path.join(root, fn), encoding="utf-8").read() title = re.search(r"^title: (.*)$", text, re.M) slug = re.search(r"^slug: (.*)$", text, re.M) before = len(w.rows) n = 0 for block in FENCE.findall(text): for s, e in cc.find_spans(block): m = block[s:e] n += 1 w.add(m, producer="MDN", licence="CC0-1.0", licence_url=licence_url, origin="%s/blob/%s/%s" % (REPO, commit, path), context=cc.context_of(m), markup=cc.classify_markup(m)) if n: docs.append(dict( origin="%s/blob/%s/%s" % (REPO, commit, path), title=title.group(1).strip("'\"") if title else path, authors="MDN contributors", licence="CC0-1.0", licence_url=licence_url, access_url="https://developer.mozilla.org/en-US/docs/" + slug.group(1) if slug else None, retrieved=today, formulas=n)) w.stats["distinct_found"] = len(w) w.write(a.out, docs) cc.log("mdn rows", len(w), "found", w.found, "documents", len(docs)) if __name__ == "__main__": main()