File size: 31,736 Bytes
93e3ef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f84cf20
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
#!/usr/bin/env python3
"""Assemble the published corpus from the per-source extraction outputs.

Input: directories holding, for every source group, `<source>.jsonl` (rows)
and `<source>.documents.jsonl` (one record per source document).  The
extraction scripts in this directory write them.

Steps:
  1. Validate every row and every documents file; drop and report violations.
  2. De-duplicate within each source.  Rows with identical `mathml` merge and
     their `count` adds up.  Rows that differ only in volatile attributes of
     the root element (VOLATILE below) are near-duplicates: the first row is
     kept unchanged and `duplicates` records how many rows were merged into
     it.  No `mathml` string is altered.
  3. Assign each document to `dev` or `test` by a hash of its `origin`.
  4. Draw the evaluation sample from `test`, stratified by source and
     producer, with a floor per stratum and a cap per producer.
  5. Write the data files, the documents file, ATTRIBUTION.md, LICENSES.md,
     the dataset card and a JSON report.

The output is a function of the inputs and the arguments: running the script
twice gives byte-identical files.  Memory use is bounded by the number of
distinct rows of one source (hashes only) and by the sample bookkeeping.

Usage:
  assemble.py --input DIR [--input DIR ...] --out DIR --template CARD_TEMPLATE
              [--expected EXPECTED_JSON] [--drop-violations]
"""
import argparse
import collections
import glob
import gzip
import hashlib
import json
import os
import re
import sys

PERMITTED = {
    "CC0-1.0", "CC-BY-2.0", "CC-BY-2.5", "CC-BY-3.0", "CC-BY-4.0",
    "CC-BY-SA-2.5", "CC-BY-SA-3.0", "CC-BY-SA-4.0",
    "MIT", "BSD-3-Clause", "Apache-2.0",
}
REQUIRED = ("id", "mathml", "source", "producer", "origin", "licence", "licence_url")
FIELDS = ("id", "mathml", "source", "producer", "origin", "licence", "licence_url",
          "context", "markup", "tex", "tex_kind", "count", "duplicates", "note", "split")
DOCUMENT_FIELDS = ("source", "origin", "split", "identifier", "title", "authors", "venue",
                   "publisher", "year", "licence", "licence_url", "licence_source",
                   "access_url", "retrieved", "formulas")

# Attributes of the root `math` element that identify the element in its
# document and carry no mathematics.  The list comes from a census of the
# root attributes of all sources: `id` and `xml:id` hold per-document
# element identifiers (`M12`, `d33e5766`, `S1.Ex13Xb.m3`), and `altimg`
# the file name of a per-formula bitmap (`si65.svg`).  Every other root
# attribute either repeats across a source (`xmlns`, `class`, `display`) or
# changes the formula (`alttext`, `data-latex`, `intent`).
VOLATILE = ("id", "xml:id", "altimg")

DEV_SHARE = 0.7
SPLIT_SALT = "mathconv-corpus-v1-split|"
SAMPLE_SALT = "mathconv-corpus-v1-sample|"

ROOT_TAG = re.compile(
    r"""<[^\s>/]+(?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*\s*/?>""")
ROOT_ATTRIBUTE = re.compile(
    r"""(?P<space>\s+)(?P<name>[^\s=>/]+)(?:\s*=\s*(?P<value>"[^"]*"|'[^']*'|[^\s>]+))?""")


def document_key(origin):
    """The document of a row origin: a row origin may end in a `#L<line>`
    anchor that points to the formula inside the document."""
    return re.sub(r"#L\d+(?:-L\d+)?$", "", origin)


def digest(text):
    return hashlib.sha256(text.encode("utf-8")).digest()[:16]


def row_id(mathml):
    return hashlib.sha256(mathml.encode("utf-8")).hexdigest()[:16]


def root_attributes(mathml):
    """Names and values of the attributes of the root start tag."""
    tag = ROOT_TAG.match(mathml.lstrip())
    if not tag:
        return None
    body = tag.group(0)
    name_end = re.match(r"<[^\s>/]+", body).end()
    return [(m.group("name"), m.group("value")) for m in ROOT_ATTRIBUTE.finditer(body, name_end)]


def near_key(mathml):
    """The formula without the volatile attributes of its root element."""
    text = mathml.lstrip()
    tag = ROOT_TAG.match(text)
    if not tag:
        return text
    body = tag.group(0)
    name_end = re.match(r"<[^\s>/]+", body).end()
    out, last = [body[:name_end]], name_end
    for m in ROOT_ATTRIBUTE.finditer(body, name_end):
        if m.group("name") in VOLATILE:
            out.append(body[last:m.start()])
            last = m.end()
    out.append(body[last:])
    return "".join(out) + text[tag.end():]


def origin_family(origin):
    """Documents of one family are split with the same proportion."""
    m = re.match(r"https?://([^/]+)/?([^?#]*)", origin)
    if not m:
        return origin
    host, path = m.group(1), m.group(2).split("/")
    if host == "github.com":
        return host + "/" + "/".join(path[:2])
    if host == "doi.org":
        return host + "/" + path[0]
    return re.sub(r"^[a-z]{2,3}\.(wikipedia\.org)$", r"\1", host)


def assign_splits(origins):
    """Map every origin to `dev` or `test`.  The documents of a family (see
    `origin_family`) are ordered by a hash of the origin and the first 70
    percent go to `dev`, the rest to `test`, so each family appears in both
    splits.  A document has the same split in every source that uses it."""
    families = collections.defaultdict(list)
    for o in origins:
        families[origin_family(o)].append(o)
    # A family of one document would land on one side only; such documents
    # form a family together.
    singles = [m[0] for m in families.values() if len(m) == 1]
    families = {k: m for k, m in families.items() if len(m) > 1}
    if singles:
        families[""] = singles
    split = {}
    for members in families.values():
        members.sort(key=lambda o: hashlib.sha256((SPLIT_SALT + o).encode()).hexdigest())
        n = len(members)
        dev = n if n == 1 else max(1, min(n - 1, round(n * DEV_SHARE)))
        for i, o in enumerate(members):
            split[o] = "dev" if i < dev else "test"
    return split


def read_jsonl(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            if line.strip():
                yield json.loads(line)


def groups(inputs):
    found = {}
    for d in inputs:
        for path in sorted(glob.glob(os.path.join(d, "*.jsonl"))):
            name = os.path.basename(path)
            if name.endswith(".documents.jsonl"):
                continue
            source = name[:-len(".jsonl")]
            docs = path[:-len(".jsonl")] + ".documents.jsonl"
            if not os.path.exists(docs):
                raise SystemExit(f"{path}: no documents file")
            found[source] = (path, docs)
    return [(s, *found[s]) for s in sorted(found)]


def validate_documents(source, docs_path):
    docs, problems = {}, collections.Counter()
    for d in read_jsonl(docs_path):
        o = d.get("origin")
        if not o:
            problems["document without origin"] += 1
            continue
        if o in docs:
            problems["document listed twice"] += 1
            continue
        for k in ("licence", "licence_url"):
            if not d.get(k):
                problems[f"document without {k}"] += 1
        if d.get("licence") not in PERMITTED:
            problems["document licence not permitted"] += 1
        docs[o] = d
    return docs, problems


def problem_of(row, docs):
    for k in REQUIRED:
        if not isinstance(row.get(k), str) or not row[k].strip():
            return f"missing or empty {k}"
    if row["licence"] not in PERMITTED:
        return "licence not permitted"
    if row["id"] != row_id(row["mathml"]):
        return "id is not the hash of mathml"
    d = docs.get(document_key(row["origin"]))
    if d is None:
        return "origin has no document record"
    if d.get("licence") != row["licence"]:
        return "row and document licences differ"
    return None


def scan(source, path, docs):
    """First pass over one group: validation and de-duplication decisions.
    Returns the indexes of the rows to keep with their counts and duplicate
    numbers, and the statistics."""
    exact, near = {}, {}
    keep, counts, dups = [], {}, collections.Counter()
    st = collections.Counter()
    violations = collections.Counter()
    attrs = collections.defaultdict(lambda: [0, set()])
    for i, row in enumerate(read_jsonl(path)):
        st["input"] += 1
        p = problem_of(row, docs)
        if p:
            violations[p] += 1
            continue
        c = row.get("count") or 1
        d = digest(row["mathml"])
        if d in exact:
            counts[exact[d]] += c
            st["exact"] += 1
            continue
        exact[d] = i
        counts[i] = c
        for name, value in root_attributes(row["mathml"]) or ():
            a = attrs[name]
            a[0] += 1
            if len(a[1]) < 1000:
                a[1].add(value)
        n = digest(near_key(row["mathml"]))
        if n in near:
            dups[near[n]] += 1
            st["near"] += 1
            continue
        near[n] = i
        keep.append(i)
    return keep, counts, dups, st, violations, attrs


def identifier_of(doc):
    if doc.get("pmcid"):
        return "pmcid:" + doc["pmcid"]
    if doc.get("arxiv_id"):
        return "arxiv:" + doc["arxiv_id"] + (doc.get("version") or "")
    if doc.get("revision_id"):
        return f"wikipedia:{doc.get('language')}:{doc['revision_id']}"
    o = doc["origin"]
    if o.startswith("https://doi.org/"):
        return "doi:" + o[len("https://doi.org/"):]
    return o


def venue_of(source, doc):
    if doc.get("journal"):
        return doc["journal"]
    if doc.get("language"):
        return f"Wikipedia ({doc['language']})"
    m = re.match(r"https://github\.com/([^/]+/[^/]+)/", doc["origin"])
    if m:
        return "github.com/" + m.group(1)
    return {"biomodels": "BioModels", "mdn": "MDN Web Docs"}.get(source)


def document_record(source, doc, formulas, split):
    publisher = doc.get("publisher") or None
    if publisher is None and doc.get("language"):
        publisher = "Wikipedia"
    year = doc.get("year")
    return {
        "source": source, "origin": doc["origin"], "split": split,
        "identifier": identifier_of(doc), "title": doc.get("title"),
        "authors": doc.get("authors") or None, "venue": venue_of(source, doc),
        "publisher": publisher, "year": str(year) if year else None,
        "licence": doc["licence"], "licence_url": doc["licence_url"],
        "licence_source": doc.get("licence_source"),
        "access_url": doc.get("access_url"), "retrieved": doc.get("retrieved"),
        "formulas": formulas}


class Gzip:
    """Deterministic gzip writer: no file name, modification time zero."""

    def __init__(self, path):
        self.raw = open(path, "wb")
        self.file = gzip.GzipFile(filename="", mode="wb", fileobj=self.raw, compresslevel=6, mtime=0)

    def write(self, text):
        self.file.write(text.encode("utf-8"))

    def close(self):
        self.file.close()
        self.raw.close()


def allocate(sizes, target, floor, cap):
    """Rows to draw from each (source, producer) stratum: proportional to its
    size with at least `floor` rows (or all of a smaller stratum), then
    reduced so that no producer exceeds `cap` rows.  `target` is met as
    closely as the cap allows."""
    def at(share):
        alloc = {k: min(n, max(floor, int(share * n))) for k, n in sizes.items()}
        by_producer = collections.defaultdict(list)
        for k in alloc:
            by_producer[k[1]].append(k)
        for keys in by_producer.values():
            total = sum(alloc[k] for k in keys)
            if total <= cap:
                continue
            base = {k: min(sizes[k], floor) for k in keys}
            spare = {k: alloc[k] - base[k] for k in keys}
            room = max(0, cap - sum(base.values()))
            for k in keys:
                alloc[k] = base[k] + (spare[k] * room // max(1, sum(spare.values())))
        return alloc
    low, high = 0.0, 1.0
    for _ in range(40):
        mid = (low + high) / 2
        if sum(at(mid).values()) > target:
            high = mid
        else:
            low = mid
    return at(low)


LICENCE_NAMES = {
    "CC0-1.0": "CC0 1.0", "CC-BY-2.0": "CC BY 2.0", "CC-BY-2.5": "CC BY 2.5",
    "CC-BY-3.0": "CC BY 3.0", "CC-BY-4.0": "CC BY 4.0", "CC-BY-SA-2.5": "CC BY-SA 2.5",
    "CC-BY-SA-3.0": "CC BY-SA 3.0", "CC-BY-SA-4.0": "CC BY-SA 4.0", "MIT": "MIT",
    "BSD-3-Clause": "BSD 3-Clause", "Apache-2.0": "Apache 2.0"}
LICENCE_TEXTS = {
    "CC0-1.0": "https://creativecommons.org/publicdomain/zero/1.0/",
    "CC-BY-2.0": "https://creativecommons.org/licenses/by/2.0/",
    "CC-BY-2.5": "https://creativecommons.org/licenses/by/2.5/",
    "CC-BY-3.0": "https://creativecommons.org/licenses/by/3.0/",
    "CC-BY-4.0": "https://creativecommons.org/licenses/by/4.0/",
    "CC-BY-SA-2.5": "https://creativecommons.org/licenses/by-sa/2.5/",
    "CC-BY-SA-3.0": "https://creativecommons.org/licenses/by-sa/3.0/",
    "CC-BY-SA-4.0": "https://creativecommons.org/licenses/by-sa/4.0/",
    "MIT": "https://opensource.org/license/mit",
    "BSD-3-Clause": "https://opensource.org/license/bsd-3-clause",
    "Apache-2.0": "https://www.apache.org/licenses/LICENSE-2.0"}


def table(header, rows, align=None):
    align = align or ["---"] * len(header)
    lines = ["| " + " | ".join(header) + " |", "| " + " | ".join(align) + " |"]
    lines += ["| " + " | ".join(str(c) for c in r) + " |" for r in rows]
    return "\n".join(lines)


def licences_text(counter):
    return ", ".join(f"{LICENCE_NAMES[k]} ({v:,})" for k, v in
                     sorted(counter.items(), key=lambda kv: (-kv[1], kv[0])))


def write_text(out, template_path, stats, documents, report):
    """Card, ATTRIBUTION.md and LICENSES.md from the statistics."""
    n = lambda x: f"{x:,}"
    total = collections.Counter()
    for st in stats.values():
        total.update(st["counts"])
    source_rows = []
    for source, st in stats.items():
        c = st["counts"]
        tex = c.get("tex_author", 0) + c.get("tex_normalised", 0)
        kinds = [k for k in ("author", "normalised") if c.get("tex_" + k)]
        share = f"{100 * tex / c['rows']:.0f}% ({'/'.join(kinds)})" if tex else "0%"
        names = sorted(st["producers"])
        producers = "; ".join(names) if len(names) <= 3 else f"{len(names)} publishers and publisher groups"
        source_rows.append((f"`{source}`", producers, n(c["documents"]), n(c["rows"]),
                            n(c.get("merged", 0)), share,
                            ", ".join(LICENCE_NAMES[k] for k in sorted(st["licences"]))))
    source_rows.append(("**all**", "", n(report["distinct_documents"]["all"]), n(total["rows"]),
                        n(total["merged"]), f"{100 * (total['tex_author'] + total['tex_normalised']) / total['rows']:.0f}%", ""))
    sources_table = table(
        ["source", "producer", "documents", "formulas", "near-duplicates merged", "with reference TeX", "licences"],
        source_rows, ["---", "---", "---:", "---:", "---:", "---:", "---"])
    split_rows = [(f"`{s}`", n(st["counts"]["dev_documents"]), n(st["counts"]["test_documents"]),
                   n(st["counts"].get("dev", 0)), n(st["counts"].get("test", 0)),
                   n(report["evaluation"]["by_source"].get(s, 0))) for s, st in stats.items()]
    split_rows.append(("**all**", n(report["distinct_documents"]["dev"]), n(report["distinct_documents"]["test"]),
                       n(total["dev"]), n(total["test"]), n(report["evaluation"]["rows"])))
    split_table = table(["source", "dev documents", "test documents", "dev formulas",
                         "test formulas", "evaluation sample"], split_rows,
                        ["---", "---:", "---:", "---:", "---:", "---:"])
    row_licences = collections.Counter()
    doc_licences = collections.Counter()
    for st in stats.values():
        row_licences.update(st["licences"])
    for d in documents:
        doc_licences[d["licence"]] += 1
    licence_table = table(["licence", "documents", "formulas", "text"],
                          [(LICENCE_NAMES[k], n(doc_licences[k]), n(row_licences[k]), LICENCE_TEXTS[k])
                           for k in sorted(row_licences, key=lambda k: -row_licences[k])],
                          ["---", "---:", "---:", "---"])
    ev = report["evaluation"]
    producers = collections.Counter()
    for st in stats.values():
        producers.update(st["producers"])
    top_producers = table(
        ["producer", "formulas", "share of the corpus"],
        [(p, n(v), f"{100 * v / total['rows']:.1f}%") for p, v in producers.most_common(8)],
        ["---", "---:", "---:"])
    producer_rows = [(p, n(v)) for p, v in list(ev["by_producer"].items())[:12]]
    values = {
        "{{TOTAL_ROWS}}": n(total["rows"]), "{{DEV_ROWS}}": n(total["dev"]),
        "{{TEST_ROWS}}": n(total["test"]), "{{EVAL_ROWS}}": n(ev["rows"]),
        "{{DOCUMENTS}}": n(report["distinct_documents"]["all"]),
        "{{DEV_DOCUMENTS}}": n(report["distinct_documents"]["dev"]),
        "{{TEST_DOCUMENTS}}": n(report["distinct_documents"]["test"]), "{{SOURCE_COUNT}}": str(len(stats)),
        "{{SOURCES_TABLE}}": sources_table, "{{SPLIT_TABLE}}": split_table,
        "{{LICENCE_TABLE}}": licence_table, "{{VOLATILE}}": ", ".join(f"`{v}`" for v in VOLATILE),
        "{{SAMPLE_FLOOR}}": str(ev["floor"]), "{{PRODUCER_CAP}}": n(ev["producer_cap"]),
        "{{MERGED}}": n(total["merged"]),
        "{{EVAL_PRODUCERS}}": table(["producer", "formulas in the sample"], producer_rows, ["---", "---:"]),
        "{{TOP_PRODUCERS}}": top_producers,
        "{{PMC_SHARE}}": f"{100 * stats['pmc']['counts']['rows'] / total['rows']:.0f}",
        "{{NO_TEX_SHARE}}": f"{100 * (total['rows'] - total['tex_author'] - total['tex_normalised']) / total['rows']:.0f}",
        "{{DEDUP_SHARE}}": f"{100 * total['merged'] / (total['merged'] + total['rows']):.0f}",
    }
    text = open(template_path, encoding="utf-8").read()
    for k, v in values.items():
        text = text.replace(k, v)
    left = re.findall(r"\{\{[A-Z_]+\}\}", text)
    if left:
        raise SystemExit(f"unfilled placeholders in the card: {left}")
    with open(os.path.join(out, "README.md"), "w", encoding="utf-8") as f:
        f.write(text)

    # ATTRIBUTION.md: summary per source; the machine-readable list is data/documents.jsonl.
    notes = ATTRIBUTION_NOTES
    lines = ["# Attribution", "",
             "Every formula in this dataset is an excerpt from one source document, published under the "
             "licence shown in the `licence` field of the row. The `origin` field of a row is the address of "
             "the document. `data/documents.jsonl` lists every source document with its identifier, "
             "title, authors where known, venue, publisher, year, licence and licence URL; this file "
             "summarises it by source.", "",
             "Credit the authors of a document when you reuse its formulas; follow the licence of the document "
             "(CC BY 4.0 and the other attribution licences require credit and a link to the licence, "
             "CC BY-SA licences also require sharing under the same terms).", ""]
    for source, st in stats.items():
        c = st["counts"]
        lines += [f"## {source}", "",
                  f"{n(c['documents'])} documents, {n(c['rows'])} formulas. Documents by licence: "
                  f"{licences_text(st['document_licences'])}.", "", notes.get(source, ""), ""]
    with open(os.path.join(out, "ATTRIBUTION.md"), "w", encoding="utf-8") as f:
        f.write("\n".join(lines).rstrip() + "\n")

    licences = ["# Licences", "",
                "The dataset is a collection of excerpts. Each formula is published under the licence of the "
                "document it was taken from, given in the `licence` and `licence_url` fields of its row. "
                "That field is the authority; the dataset as a whole has no single licence.", "",
                licence_table, "",
                "Filter on `licence` if you need only some of these, for example to exclude the share-alike "
                "licences. `ATTRIBUTION.md` and `data/documents.jsonl` say whom to credit.", "",
                "The scripts under `scripts/` are licensed under the MIT licence (`scripts/LICENSE`).", ""]
    with open(os.path.join(out, "LICENSES.md"), "w", encoding="utf-8") as f:
        f.write("\n".join(licences))


ATTRIBUTION_NOTES = {
    "pmc": "Articles of the PubMed Central open-access subset whose licence is CC BY (2.0, 2.5, 3.0, "
           "4.0) or CC0, confirmed per article from the metadata and from the licence URLs of the article XML. "
           "An article that names CC BY together with a CC0 dedication of its data counts as CC BY. "
           "`origin` is the DOI link of the article. The `producer` field names the publisher group.",
    "arxiv-html": "arXiv papers whose licence, read from the arXiv OAI-PMH record, is CC BY, CC BY-SA or CC0; "
                  "`origin` is the paper version page, `identifier` the arXiv identifier. The MathML is the "
                  "LaTeXML rendering on the arXiv HTML page.",
    "planetmath": "PlanetMath entries. The licence is the one the PlanetMath site states for all of its entries "
                  "(CC BY-SA 2.5); it was read from the site's front page and is not repeated on each entry. "
                  "The entry pages name no authors.",
    "copernicus-jats": "Articles published by Copernicus Publications under CC BY 4.0, taken from the article XML.",
    "crawl-focus": "Two web pages: an article page on acp.copernicus.org (CC BY 4.0) and a copy of a German "
                   "Wikipedia article on dewiki.de (CC BY-SA 3.0; the authors are the contributors of the "
                   "article, listed in its edit history).",
    "openstax": "Sections of OpenStax textbooks (CC BY 4.0). `origin` is the file in the book's GitHub repository "
                "at a fixed commit.",
    "mdn": "Pages of the MDN Web Docs content repository, which dedicates its examples to the public domain (CC0 1.0).",
    "mathcat-tests": "Test files of the MathCAT project (MIT licence).",
    "wpt": "Test files of the web-platform-tests project (BSD 3-Clause licence).",
    "mathjax-tests": "Test-suite snapshots of the MathJax project (Apache 2.0 licence).",
    "biomodels": "Models of the BioModels database whose own file carries the CC0 1.0 dedication.",
    "wikipedia-render": "Wikipedia articles (CC BY-SA 4.0), rendered to MathML by the Wikipedia math service. "
                        "`origin` is the permanent link to the article revision, whose history lists the authors.",
}
for _g in ("katex", "mathjax", "temml", "pandoc", "latexml", "latexml-content", "latex2mathml"):
    ATTRIBUTION_NOTES["generated-" + _g] = (
        "The TeX of Wikipedia articles (CC BY-SA 4.0) converted to MathML by the tool named in `producer`. "
        "The MathML inherits the licence of the TeX it was generated from. `origin` is the permanent link to the "
        "article revision, whose history lists the authors.")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--input", action="append", required=True, help="directory of group files")
    ap.add_argument("--out", required=True)
    ap.add_argument("--template", required=True, help="dataset card template")
    ap.add_argument("--expected", help="JSON file: source -> rows reported by the build")
    ap.add_argument("--drop-violations", action="store_true",
                    help="write the data although some rows violate the rules; they are dropped")
    ap.add_argument("--sample-size", type=int, default=20000)
    ap.add_argument("--sample-floor", type=int, default=100)
    ap.add_argument("--producer-cap", type=float, default=0.10)
    a = ap.parse_args()

    sources = groups(a.input)
    expected = json.load(open(a.expected)) if a.expected else {}
    os.makedirs(os.path.join(a.out, "data"), exist_ok=True)

    # Pass 1: validate and decide.
    plan, report = {}, {"sources": {}, "violations": {}, "root_attributes": {}}
    all_origins = set()
    unexplained = 0
    for source, rows_path, docs_path in sources:
        docs, doc_problems = validate_documents(source, docs_path)
        keep, counts, dups, st, violations, attrs = scan(source, rows_path, docs)
        violations.update(doc_problems)
        if violations:
            report["violations"][source] = dict(violations)
            unexplained += sum(violations.values())
        plan[source] = (rows_path, docs, set(keep), counts, dups)
        report["sources"][source] = {
            "input": st["input"], "exact_duplicates_merged": st["exact"],
            "near_duplicates_merged": st["near"], "kept": len(keep),
            "expected_input": expected.get(source)}
        report["root_attributes"][source] = {
            n: {"rows": v[0], "distinct_values": len(v[1])} for n, v in sorted(attrs.items())}
        for i, r in enumerate(read_jsonl(rows_path)):
            if i in plan[source][2]:
                all_origins.add(document_key(r["origin"]))
        print(f"{source}: {st['input']} rows, {st['exact']} exact and {st['near']} near duplicates, "
              f"{len(keep)} kept, {sum(violations.values())} violations", file=sys.stderr)
    if unexplained and not a.drop_violations:
        json.dump(report["violations"], sys.stderr, indent=1)
        raise SystemExit("violations found; fix the inputs or pass --drop-violations")
    mismatched = {s: (v["input"], v["expected_input"]) for s, v in report["sources"].items()
                  if v["expected_input"] is not None and v["input"] != v["expected_input"]}
    if mismatched:
        raise SystemExit(f"row counts differ from the build reports: {mismatched}")

    splits = assign_splits(sorted(all_origins))

    # Pass 2: write the split files and collect statistics.
    writers = {"dev": Gzip(os.path.join(a.out, "data/dev.jsonl.gz")),
               "test": Gzip(os.path.join(a.out, "data/test.jsonl.gz"))}
    stats = {}
    doc_rows = collections.defaultdict(collections.Counter)
    producer_splits = collections.defaultdict(set)
    test_pool = []  # (stratum, selection hash, id) of every test row
    for source, _, _ in sources:
        rows_path, docs, keep, counts, dups = plan[source]
        s = stats[source] = collections.Counter()
        s_producers, s_licences = collections.Counter(), collections.Counter()
        s_markup, s_docs = collections.Counter(), collections.defaultdict(set)
        for i, row in enumerate(read_jsonl(rows_path)):
            if i not in keep:
                continue
            key = document_key(row["origin"])
            split = splits[key]
            out = {k: row.get(k) for k in FIELDS}
            out["count"] = counts[i]
            out["duplicates"] = dups[i]
            out["split"] = split
            writers[split].write(json.dumps(out, ensure_ascii=False) + "\n")
            s["rows"] += 1
            s[split] += 1
            s["merged"] += dups[i]
            if row.get("tex"):
                s["tex_" + (row.get("tex_kind") or "unspecified")] += 1
            s_producers[row["producer"]] += 1
            s_licences[row["licence"]] += 1
            s_markup[row.get("markup")] += 1
            s_docs[split].add(key)
            producer_splits[row["producer"]].add(split)
            doc_rows[source][key] += 1
            if split == "test":
                key = hashlib.sha256((SAMPLE_SALT + source + "|" + row["id"]).encode()).hexdigest()
                test_pool.append(((source, row["producer"]), key, row["id"], source))
        s["documents"] = len(doc_rows[source])
        s["dev_documents"], s["test_documents"] = len(s_docs["dev"]), len(s_docs["test"])
        stats[source] = {
            "counts": dict(s), "producers": dict(s_producers), "licences": dict(s_licences),
            "markup": dict(s_markup),
            "document_licences": dict(collections.Counter(
                docs[o]["licence"] for o in doc_rows[source]))}
    for w in writers.values():
        w.close()

    # Documents file and attribution data.
    documents = []
    with open(os.path.join(a.out, "data/documents.jsonl"), "w", encoding="utf-8") as f:
        for source, _, _ in sources:
            docs = plan[source][1]
            for origin in sorted(doc_rows[source]):
                rec = document_record(source, docs[origin], doc_rows[source][origin],
                                      splits[origin])
                f.write(json.dumps({k: rec[k] for k in DOCUMENT_FIELDS}, ensure_ascii=False) + "\n")
                documents.append(rec)

    # Every source and producer appears in both splits.
    producer_documents = collections.defaultdict(set)
    for source, st in stats.items():
        for source_docs in (doc_rows[source],):
            for key in source_docs:
                producer_documents[plan[source][1][key].get("producer")].add(key)
    single = sorted(p for p, d in producer_documents.items() if len(d) == 1)
    report["single_document_producers"] = single
    for source, st in stats.items():
        for producer in st["producers"]:
            if len(producer_splits[producer]) < 2 and producer not in single:
                raise SystemExit(f"producer {producer!r} of {source} is missing from a split")
        if not (st["counts"].get("dev") and st["counts"].get("test")):
            raise SystemExit(f"{source} is missing from a split")

    # Evaluation sample.
    strata = collections.Counter(p[0] for p in test_pool)
    cap = int(a.producer_cap * a.sample_size)
    alloc = allocate(strata, a.sample_size, a.sample_floor, cap)
    by_stratum = collections.defaultdict(list)
    for key, h, rid, source in test_pool:
        by_stratum[key].append((h, rid))
    chosen, taken_ids = set(), set()
    for key in sorted(by_stratum):
        got = 0
        for h, rid in sorted(by_stratum[key]):
            if got == alloc[key]:
                break
            if rid in taken_ids:
                continue
            taken_ids.add(rid)
            chosen.add((key[0], rid))
            got += 1
        alloc[key] = got
    del test_pool, by_stratum
    sample = collections.Counter()
    with gzip.open(os.path.join(a.out, "data/test.jsonl.gz"), "rt", encoding="utf-8") as src, \
            open(os.path.join(a.out, "data/evaluation.jsonl"), "w", encoding="utf-8") as dst:
        for line in src:
            row = json.loads(line)
            if (row["source"], row["id"]) in chosen:
                dst.write(line)
                sample[(row["source"], row["producer"])] += 1
    report["evaluation"] = {
        "rows": sum(sample.values()), "floor": a.sample_floor, "producer_cap": cap,
        "target": a.sample_size,
        "by_source": dict(collections.Counter(
            {s: sum(v for (src, _), v in sample.items() if src == s) for s in stats})),
        "by_producer": dict(sorted(collections.Counter(
            {p: sum(v for (_, q), v in sample.items() if q == p)
             for p in {q for (_, q) in sample}}).items(), key=lambda kv: (-kv[1], kv[0])))}
    report["stats"] = stats
    report["distinct_documents"] = {
        "all": len(splits), "dev": sum(v == "dev" for v in splits.values()),
        "test": sum(v == "test" for v in splits.values())}
    report["volatile_attributes"] = list(VOLATILE)

    # Text files.
    write_text(a.out, a.template, stats, documents, report)
    with open(os.path.join(a.out, "report.json"), "w", encoding="utf-8") as f:
        json.dump(report, f, indent=1, sort_keys=True, ensure_ascii=False)
    print(json.dumps(report["evaluation"], indent=1)[:3000])


if __name__ == "__main__":
    main()