Datasets:
File size: 6,790 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 | #!/usr/bin/env python3
"""Summarise the corpus files of one or more sources as Markdown tables.
For every source file ``<source>.jsonl`` (and its ``<source>.documents.jsonl``)
in a directory, and for every publisher group inside it, the report gives:
* documents used, formulas found, distinct formulas kept;
* the share of formulas with TeX, split by TeX kind;
* the licence breakdown;
* context and markup-vocabulary shares;
* the element census: the share of distinct formulas containing each
element;
* markup habits: namespace prefix, attributes on ``math``, redundant
``mrow`` wrappers, invisible operators, character references,
``mathvariant`` values, and one short example formula.
Usage:
corpus_report.py DIR SOURCE [SOURCE ...] > report.md
"""
import collections
import json
import os
import re
import sys
ELEMENT = re.compile(r"<(?:[A-Za-z][\w.-]*:)?([A-Za-z][\w.-]*)")
PREFIX = re.compile(r"<([A-Za-z][\w.-]*):math\b")
ATTR = re.compile(r"""([A-Za-z:_][\w:.-]*)\s*=\s*(?:"[^"]*"|'[^']*')""")
INVISIBLE = {"": "function application U+2061", "": "invisible times U+2062",
"": "invisible separator U+2063", "": "invisible plus U+2064",
"": "zero width space U+200B"}
REDUNDANT_MROW = re.compile(r"<(?:\w+:)?mrow>(<(?:\w+:)?(?:mi|mn|mo)\b[^>]*>[^<]*</(?:\w+:)?(?:mi|mn|mo)>)</(?:\w+:)?mrow>")
def pct(n, d):
return f"{100 * n / d:.1f}%" if d else "n/a"
def read(path):
with open(path, encoding="utf-8") as f:
for line in f:
yield json.loads(line)
def census(rows):
c = collections.Counter()
for r in rows:
c.update({n.lower() for n in ELEMENT.findall(r["mathml"])})
return c
def habits(rows):
n = len(rows)
prefix = collections.Counter()
attrs = collections.Counter()
mathvariants = collections.Counter()
invis = collections.Counter()
c = collections.Counter()
for r in rows:
s = r["mathml"]
m = PREFIX.match(s)
prefix[m.group(1) if m else "(none)"] += 1
root = s[: s.index(">") + 1]
attrs.update(set(a.lower() for a in ATTR.findall(root)))
mathvariants.update(set(re.findall(r'mathvariant="([^"]*)"', s)))
invis.update({INVISIBLE[ch] for ch in INVISIBLE if ch in s})
if REDUNDANT_MROW.search(s):
c["redundant mrow around one token"] += 1
if re.search(r"&#x?[0-9A-Fa-f]+;", s):
c["numeric character references"] += 1
if re.search(r"&[A-Za-z]+;", s):
c["named entities"] += 1
if re.search(r"[^\x00-\x7f]", s):
c["literal non-ASCII characters"] += 1
if re.search(r"<(?:\w+:)?mo\b[^>]*\b(?:lspace|rspace)=", s):
c["spacing attributes on mo"] += 1
if re.search(r"<(?:\w+:)?mo\b[^>]*\b(?:stretchy|fence|separator|form)=", s):
c["operator-form attributes on mo"] += 1
if "\n" in s:
c["line breaks inside the element"] += 1
return n, prefix, attrs, mathvariants, invis, c
def example(rows):
cand = [r for r in rows if 120 <= len(r["mathml"]) <= 330 and "mfrac" in r["mathml"]] or \
[r for r in rows if 80 <= len(r["mathml"]) <= 330] or rows
return min(cand, key=lambda r: (abs(len(r["mathml"]) - 220), r["id"]))
def section(title, rows, docs):
out = [f"### {title}", ""]
n = len(rows)
found = sum(d.get("formulas_found", 0) for d in docs)
tex = collections.Counter(r["tex_kind"] for r in rows)
lic = collections.Counter((r["licence"]) for r in rows)
dlic = collections.Counter(d["licence"] for d in docs)
ctx = collections.Counter(r["context"] for r in rows)
mk = collections.Counter(r["markup"] for r in rows)
out.append(f"- documents used: {len(docs)}; formulas found in those documents: {found}; "
f"formulas sampled: {sum(d['formulas_sampled'] for d in docs)}; distinct formulas kept: {n}")
out.append(f"- with TeX: {pct(sum(v for k, v in tex.items() if k), n)} "
f"({', '.join(f'{k}: {v}' for k, v in tex.items() if k) or 'none'})")
out.append(f"- licences, documents: {', '.join(f'{k}: {v}' for k, v in sorted(dlic.items()))}; "
f"rows: {', '.join(f'{k}: {v}' for k, v in sorted(lic.items()))}")
out.append(f"- context: {', '.join(f'{k} {pct(v, n)}' for k, v in sorted(ctx.items()))}; "
f"markup: {', '.join(f'{k} {pct(v, n)}' for k, v in sorted(mk.items()))}")
cen = census(rows)
out.append("- element census (share of distinct formulas containing the element): " +
", ".join(f"`{e}` {pct(v, n)}" for e, v in cen.most_common(40)))
_, prefix, attrs, mv, invis, c = habits(rows)
out.append("- namespace prefix on math: " + ", ".join(f"`{k}` {pct(v, n)}" for k, v in prefix.most_common(4)))
out.append("- attributes on the math element: " + ", ".join(f"`{k}` {pct(v, n)}" for k, v in attrs.most_common(8)))
out.append("- mathvariant values: " + (", ".join(f"`{k}` {pct(v, n)}" for k, v in mv.most_common(6)) or "none"))
out.append("- invisible characters: " + (", ".join(f"{k} {pct(v, n)}" for k, v in invis.most_common()) or "none"))
out.append("- other habits: " + ", ".join(f"{k} {pct(v, n)}" for k, v in c.most_common()))
ex = example(rows)
out.append("")
out.append("Example (" + ex["origin"] + "):")
out.append("")
out.append("```xml")
out.append(ex["mathml"])
out.append("```")
if ex["tex"]:
out.append("")
out.append("TeX: `" + ex["tex"].replace("\n", " ") + "`")
out.append("")
return out
def main():
directory, sources = sys.argv[1], sys.argv[2:]
print("## Per-source and per-group statistics\n")
for source in sources:
rows = list(read(os.path.join(directory, f"{source}.jsonl")))
docs = list(read(os.path.join(directory, f"{source}.documents.jsonl")))
print("\n".join(section(f"{source} (all)", rows, docs)))
by_group = collections.defaultdict(list)
group_of = {d["producer"]: d.get("group", d["producer"]) for d in docs}
for r in rows:
by_group[group_of[r["producer"]]].append(r)
if len(by_group) > 1:
for g, grows in sorted(by_group.items()):
gdocs = [d for d in docs if d.get("group", d["producer"]) == g]
print("\n".join(section(f"{source}: group {g}", grows, gdocs)))
for p in sorted({r["producer"] for r in rows if group_of[r["producer"]] == "other"}):
prow = [r for r in rows if r["producer"] == p]
if len(prow) >= 100:
pdocs = [d for d in docs if d["producer"] == p]
print("\n".join(section(f"{source}: other publisher {p}", prow, pdocs)))
if __name__ == "__main__":
main()
|