File size: 3,896 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
#!/usr/bin/env python3
"""Extract `<math>` elements from the web-platform-tests `mathml/` directory.

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

Makes a shallow sparse clone of github.com/web-platform-tests/wpt limited to
`mathml/` and `LICENSE.md` (into `DIR/wpt` if absent).  The repository is
under the 3-Clause BSD License.  Every `<math>...</math>` span of every
text file is taken as written (HTML5 syntax, usually without a namespace).

Elements without any character data (for example `<math><mrow></mrow></math>`
used only to test layout of empty boxes) are skipped.  If more distinct elements remain than `--max-total`, a seeded
random sample is kept.
"""
import argparse
import os
import random
import re
import subprocess
from datetime import date

import corpus_common as cc

REPO = "https://github.com/web-platform-tests/wpt"
TEXT = re.compile(r">([^<>]*[^<>\s][^<>]*)<")
EXT = (".html", ".htm", ".xhtml", ".xht", ".xml", ".svg", ".mml", ".js")


def has_text(m):
    """True if the element holds character data or a Content MathML leaf."""
    return bool(TEXT.search(m)) or bool(re.search(r"<(mglyph|none|mspace|mprescripts)\b", m))


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=3000)
    a = ap.parse_args()
    dest = os.path.join(a.work, "wpt")
    if not os.path.isdir(dest):
        cc.sparse_clone(REPO, dest, ["/mathml/", "/LICENSE.md"])
    commit = subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], capture_output=True,
                            text=True, check=True).stdout.strip()
    lurl = "%s/blob/%s/LICENSE.md" % (REPO, commit)
    found, skipped = 0, 0
    first, occ, docs, found_in = {}, {}, {}, {}
    for root, _, files in sorted(os.walk(os.path.join(dest, "mathml"))):
        for fn in sorted(files):
            if not fn.endswith(EXT):
                continue
            path = os.path.relpath(os.path.join(root, fn), dest)
            try:
                src = open(os.path.join(root, fn), encoding="utf-8").read()
            except UnicodeDecodeError:
                continue
            for s, e in cc.find_spans(src):
                m = src[s:e]
                found += 1
                if not has_text(m):
                    skipped += 1
                    continue
                occ[m] = occ.get(m, 0) + 1
                found_in[path] = found_in.get(path, 0) + 1
                if m not in first:
                    first[m] = path
                    docs[path] = docs.get(path, 0) + 1
    keys = list(first)
    if len(keys) > a.max_total:
        pick = set(random.Random(a.seed).sample(keys, a.max_total))
        keys = [k for k in keys if k in pick]
    w = cc.Writer("wpt")
    w.stats["formulas_found"] = found
    used = {}
    for m in keys:
        path = first[m]
        w.add(m, producer="web-platform-tests", licence="BSD-3-Clause", licence_url=lurl,
              origin="%s/blob/%s/%s" % (REPO, commit, path),
              context=cc.context_of(m), markup=cc.classify_markup(m))
        w.rows[m]["count"] = occ[m]
        used[path] = used.get(path, 0) + 1
    w.stats.update(distinct_found=len(first), skipped_without_text=skipped)
    docs = [dict(origin="%s/blob/%s/%s" % (REPO, commit, p), title=p,
                 authors="web-platform-tests contributors", licence="BSD-3-Clause",
                 licence_url=lurl, access_url="%s/raw/%s/%s" % (REPO, commit, p),
                 retrieved=date.today().isoformat(), formulas=found_in[p]) for p, n in sorted(used.items())]
    w.write(a.out, docs)
    cc.log("wpt found", found, "skipped", skipped, "distinct", len(first), "kept", len(w), "files", len(docs))


if __name__ == "__main__":
    main()