File size: 45,209 Bytes
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
f5a2109
 
 
 
 
 
 
675bd91
 
 
 
f5a2109
 
 
675bd91
 
 
 
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
675bd91
f5a2109
 
 
 
 
 
 
 
675bd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a2109
 
 
 
 
 
675bd91
f5a2109
 
 
675bd91
 
 
 
 
 
 
 
 
 
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
f5a2109
 
 
 
 
 
 
 
 
 
675bd91
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
 
 
 
f5a2109
675bd91
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
f5a2109
 
 
675bd91
f5a2109
 
675bd91
 
 
 
 
f5a2109
 
 
675bd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a2109
 
 
 
675bd91
 
 
f5a2109
675bd91
 
 
 
 
 
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a2109
 
 
675bd91
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
 
 
f5a2109
 
 
675bd91
 
 
 
 
 
f5a2109
 
 
 
675bd91
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
f5a2109
 
 
 
 
675bd91
f5a2109
675bd91
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
f5a2109
 
 
 
 
675bd91
f5a2109
 
675bd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a2109
 
 
 
675bd91
 
 
 
 
f5a2109
 
 
 
 
 
 
 
 
 
 
675bd91
 
f5a2109
 
 
 
 
675bd91
f5a2109
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
f5a2109
 
 
 
 
 
 
 
675bd91
 
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
f5a2109
 
675bd91
 
 
 
 
 
 
f5a2109
 
675bd91
 
f5a2109
675bd91
f5a2109
 
 
675bd91
f5a2109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675bd91
 
 
 
f5a2109
 
 
675bd91
 
 
 
 
 
 
 
 
f5a2109
 
 
 
675bd91
 
 
 
 
 
 
 
f5a2109
 
 
 
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
#!/usr/bin/env python
"""Build the HuggingFace repo: EmoTweetID unified under Ekman's seven universal emotions.

The pool is everything EmoTweetID's annotators labelled (2,243 tweets). Two provenances:

  * the five classes they already tagged that are Ekman universals - fear, disgust, sadness,
    surprise, joy - are carried over **unchanged** (their majority-vote human labels; `joy` is
    renamed to Ekman's own term `enjoyment`, the upstream name stays in `source_label`);
  * the `anger` pool is the only thing re-decided here: laya splits it into `anger` vs `contempt`
    against Ekman's definitions (out/anger_ekman_rows.csv, from label_anger.py).

Configs, each stratified 8:1:1 train/valid/test with seed 0 and duplicate-safe groups:
  full                   all Ekman-7 rows, natural imbalance
  balanced               Ekman-7 rows down-sampled to equal size per class (seed 0)  [default]
  anger_split            the anger pool only, two-class, with every evidence column
  anger_split_balanced   that pool at 1:1

Layout and card style mirror mahalisyarifuddin/goemotions-ekman.

Usage: python make_dataset.py [--dist dist] [--out-dir out] [--repo ns/name]
"""
import argparse
import json
import os
import re
import shutil

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

from ekman_questions import EKMAN7, BINARY
from split_exact import (FRACTIONS as SPLIT_FRACTIONS, apportion, assign_groups, ideal_targets,
                         sample_groups_per_class)

LABELS_EKMAN = EKMAN7
LABELS_BINARY = BINARY
# EmoTweetID's label names -> Ekman's universal-emotion names. Everything but joy is identity.
SOURCE_TO_EKMAN = {"joy": "enjoyment"}
SPLITS = ("train", "valid", "test")
CONFIGS = ("balanced", "full", "anger_split", "anger_split_balanced")
# `full` and `anger_split` ship the whole pool as a single `train` split; the two balanced configs
# are the ones that carry an exact 8b : 1b : 1b train/valid/test.
WHOLE_CONFIGS = ("full", "anger_split")
SPLIT_CONFIGS = ("balanced", "anger_split_balanced")
SEED = 0                      # the split seed the card promises; every run reads it from here
OUT_DIR = "out"               # label_anger.py --out
DATA_CSV, DATA_CSV_EN = "data/file1.csv", "data/file2.csv"
PREV_DIR = "out_prev"          # the previous revision's run artefacts (shipped for the comparison)
PREV_CACHE = os.path.join(PREV_DIR, "cache_id_core.json")
PREV_CSV = os.path.join(PREV_DIR, "anger_ekman_rows.csv")
SHIPPED = """README.template.md label_anger.py label_anger_id.py make_dataset.py fetch_source_data.py
               publish.py laya_opt.py ekman_questions.py ekman_questions_id.py zcsafe.py
               prepare_checkpoint.py probe_quality.py probe_quality_id.py probes.py probes_id.py
               split_exact.py test_split_exact.py
               bench_speedup.py bench_batch.py check_veto_and_speed.py sweep_config.py""".split()
REQUIRED = ["text", "text_en", "label", "label_idx", "source_label", "label_origin"]


def norm(s):
    return re.sub(r"\s+", " ", str(s)).strip()


def load_pool(out_dir=OUT_DIR):
    """All annotated tweets, with laya's anger/contempt decision overlaid on the `anger` rows."""
    df = pd.read_csv(DATA_CSV)
    en = pd.read_csv(DATA_CSV_EN)
    df["text"] = df["tweet"].astype(str).map(norm)
    df["text_en"] = pd.Series(en["tweet_en"]).astype(str).map(norm).values
    df["row_src"] = df.index
    df["source_label"] = df["label"].astype(str).str.strip().str.lower()
    # human labels enter here unchanged; only `anger` is left for the model to split
    df["label"] = df["source_label"].map(lambda x: SOURCE_TO_EKMAN.get(x, x))
    lab = pd.read_csv(os.path.join(out_dir, "anger_ekman_rows.csv"))
    lab = lab[lab["source_label"] == "anger"]
    assert len(lab) == lab["row_src"].nunique(), "anger labels are not row-unique"
    assert set(lab["label"]) <= set(BINARY), f"unexpected labels in anger run: {set(lab['label'])}"
    keep = ["label_source", "ambiguous", "ekman_p_anger", "ekman_p_contempt",
            "ekman_confidence", "p_anger_id", "p_anger_swapped", "ekman_margin_id",
            "p_superiority", "p_blocked_or_unfair", "p_not_anger_or_contempt"]
    m = df.merge(lab[["row_src", "label"] + keep].rename(columns={"label": "ek_label"}),
                 on="row_src", how="left")
    anger = m["source_label"].eq("anger")
    # every anger row must have exactly one decision, and no other row may have one
    assert m["ek_label"].notna().eq(anger).all(), "the anger run does not cover the pool exactly"
    m["label"] = np.where(anger, m["ek_label"], m["label"])
    m["label_origin"] = np.where(anger, "laya_anger_split", "upstream_manual")
    m = m.drop(columns=["ek_label"])
    untouched = ~anger
    assert m.loc[untouched, "label"].eq(
        m.loc[untouched, "source_label"].map(lambda x: SOURCE_TO_EKMAN.get(x, x))).all(), \
        "a human label was changed"
    assert m["label"].isin(LABELS_EKMAN).all(), "a row ended up outside the Ekman-7 label set"
    return m, lab


def add_text_group(df):
    """Transitive text identity over both language columns -> split groups (see the leakage test).

    Rows are union-find'd when their Indonesian text matches or when their English translation
    matches: EmoTweetID's `tweet` column has repeats, and one translation can cover several
    different Indonesian tweets, which would otherwise land on both sides of a split.
    """
    parent = list(range(len(df)))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a, b):
        ra, rb = find(a), find(b)
        if ra != rb:
            parent[max(ra, rb)] = min(ra, rb)

    for col in ("text", "text_en"):
        first = {}
        for i, t in enumerate(df[col].tolist()):
            if t in first:
                union(i, first[t])
            else:
                first[t] = i
    roots, grp = {}, []
    for i in range(len(df)):
        r = find(i)
        roots.setdefault(r, len(roots))
        grp.append(roots[r])
    df["group"] = grp
    return df


def stratified_811_greedy(df, seed):
    """The splitter the *previous* revision shipped - kept so the card can compare against it.

    Shuffles each class's duplicate groups with `seed`, then hands them out greedily one at a time to
    the split with the largest remaining row deficit against 0.8/0.1/0.1.  Groups are the unit, so
    nothing leaks, but a class whose last group overshoots cannot be corrected, which is why it lands
    on 1794/226/223 rather than on whole-row 8:1:1.  `make_dataset.stratified_811` is the exact one.
    """
    rng = np.random.RandomState(seed)
    lab, grp = df["label"].to_numpy(), df["group"].to_numpy()
    sizes = pd.Series(grp).value_counts().reindex(range(grp.max() + 1), fill_value=0).to_numpy()
    modal = (pd.DataFrame({"g": grp, "l": lab}).groupby("g")["l"]
             .agg(lambda x: x.value_counts().index[0]))
    assign = {}
    for c in sorted(df["label"].unique()):
        gs = [g for g in modal.index if modal[g] == c]
        rng.shuffle(gs)
        gs.sort(key=lambda g: -sizes[g])
        target = np.array([0.8, 0.1, 0.1]) * sizes[gs].sum()
        cur = np.zeros(3)
        for g in gs:
            j = int(np.argmax(target - cur))
            assign[g] = SPLITS[j]
            cur[j] += sizes[g]
    out = df.copy()
    out["split"] = [assign[g] for g in grp]
    return out


def stratified_811(df, seed):
    """Exact 8:1:1 by row count, still group-aware - see split_exact.py for the how and the why.

    The row count of a config decides its column totals (`apportion`, i.e. largest remainder: 2,243
    rows -> 1,795/224/224, 475 rows -> 380/48/47), and the per-class-per-split counts are the integer
    solution closest to `n_class x 0.8 | 0.1 | 0.1` given those totals.  Groups are then placed by
    need and repaired by moving whole groups, so no wording straddles two splits and the split sizes
    come out exact rather than "to within a group".
    """
    sizes = df["label"].value_counts().to_dict()
    split_sizes = apportion(len(df), SPLIT_FRACTIONS)
    targets = ideal_targets(sizes, split_sizes)
    out = assign_groups(df, targets, seed)
    for s in SPLITS:
        g = out.loc[out["split"] == s, "group"]
        for other in SPLITS:
            if other != s:
                leak = int(g.isin(out.loc[out["split"] == other, "group"]).sum())
                assert leak == 0, f"group leaked between {s} and {other}: {leak} rows"
        assert int((out["split"] == s).sum()) == split_sizes[SPLITS.index(s)], "split size off target"
    return out


def balanced_pool(df, labels, seed=SEED):
    """Down-sample to `m` rows per class, whole groups, with `m` the largest multiple of ten that fits.

    The ten-row block has to be the unit if the split is to be exactly 8b : 1b : 1b, so a balanced
    config picks its per-class size accordingly - 186 eligible `contempt` rows become 180, i.e. 144
    train / 18 valid / 18 test per class and 1,008 / 126 / 126 overall (b = 126).  Nothing else about
    the sample changes: seed 0, whole duplicate groups, identical class counts.
    """
    counts = df["label"].value_counts()
    m = min(int(counts[c]) for c in labels) // 10 * 10
    assert m > 0, "no class reaches ten rows"
    sub, dropped = sample_groups_per_class(df, m, seed, labels=labels)
    return sub, m, dropped


def features(labels):
    from datasets import ClassLabel, Features, Value
    return Features({
        "text": Value("string"),
        "text_en": Value("string"),
        # `label` stays a readable string (a parquet opened in pandas/duckdb shows "contempt", not 1);
        # `label_idx` is the ClassLabel for training, and its names are the same list in the same order.
        "label": Value("string"),
        "label_idx": ClassLabel(names=list(labels)),
        "source_label": Value("string"),
        "label_origin": Value("string"),
        "label_source": Value("string"),
        "ambiguous": Value("bool"),
        "ekman_p_anger": Value("float32"),
        "ekman_p_contempt": Value("float32"),
        "ekman_confidence": Value("float32"),
        "p_anger_id": Value("float32"),
        "p_anger_swapped": Value("float32"),
        "ekman_margin_id": Value("float32"),
        "p_superiority": Value("float32"),
        "p_blocked_or_unfair": Value("float32"),
        "p_not_anger_or_contempt": Value("float32"),
        "row_src": Value("int32"),
    })


def to_frame(df, labels):
    """Column order like the schema; keep None for un-run evidence (NaN would round-trip badly)."""
    want = REQUIRED + ["label_source", "ambiguous", "ekman_p_anger", "ekman_p_contempt",
                       "ekman_confidence", "p_anger_id", "p_anger_swapped", "ekman_margin_id",
                       "p_superiority", "p_blocked_or_unfair", "p_not_anger_or_contempt", "row_src"]
    cols = {}
    for k in want:
        v = df[k] if k in df else pd.Series([None] * len(df))
        if k == "label":
            v = df["label"]
        elif k == "label_idx":
            v = pd.Series([labels.index(x) for x in df["label"]])
        cols[k] = [None if pd.isna(x) else x for x in v]
    return pd.DataFrame(cols, columns=want)


def write_parquet(df, labels, dist, config):
    from datasets import Dataset
    ds = Dataset.from_pandas(to_frame(df, labels), features=features(labels), preserve_index=False)
    out_dir = os.path.join(dist, config)
    os.makedirs(out_dir, exist_ok=True)
    present = [s for s in SPLITS if (df["split"] == s).any()]
    for f in os.listdir(out_dir):                 # a config that stops being split must not keep files
        if f.endswith(".parquet") and f[:-len(".parquet")] not in present:
            os.remove(os.path.join(out_dir, f))
    for s in present:
        sub = ds.select([i for i in range(len(ds)) if df["split"].iloc[i] == s])
        sub.to_parquet(os.path.join(out_dir, f"{s}.parquet"))
    return sorted(os.listdir(out_dir))


def class_table(df, labels):
    vc = df["label"].value_counts()
    mine = "split here: laya on the `anger` pool"
    return "\n".join(
        f"| `{c}` | {int(vc.get(c, 0))} | {100.0 * int(vc.get(c, 0)) / len(df):.1f}% | "
        f"{mine if c in ('anger', 'contempt') else 'EmoTweetID annotators, kept verbatim'} |"
        for c in labels if int(vc.get(c, 0)) > 0)


def checkpoint_facts(ckpt_dir="models/laya-ml/multilingual"):
    """Read the checkpoint's real size/config out of its safetensors header - no model load.

    Counts unique storages, so a tied/aliased weight is counted once (that is what makes the number
    differ from a naive `sum(v.numel() for v in state_dict.values())`).
    """
    import struct
    out = {"params": None, "params_enc": None, "params_heads": None, "tensors": None,
           "enc_name": "n/a", "model_type": "n/a", "vocab": "n/a", "ctx_default": "n/a",
           "amp": "n/a"}
    path = os.path.join(ckpt_dir, "model.safetensors")
    if not os.path.exists(path):
        return out
    with open(path, "rb") as f:
        hdr = json.loads(f.read(struct.unpack("<Q", f.read(8))[0]))
    seen, tot, enc = set(), 0, 0
    for k, v in hdr.items():
        if k == "__metadata__":
            continue
        o = tuple(v["data_offsets"])
        if o in seen:
            continue
        seen.add(o)
        n = int(np.prod(v["shape"])) if v["shape"] else 1
        tot += n
        if k.startswith("encoder."):
            enc += n
    cfg = json.load(open(os.path.join(ckpt_dir, "rl_agent_config.json")))
    out.update(params=tot, params_enc=enc, params_heads=tot - enc, tensors=len(seen),
               enc_name=cfg.get("encoder", "n/a"), ctx_default=cfg.get("max_len", "n/a"),
               amp=cfg.get("amp_dtype", "n/a"))
    ep = os.path.join(ckpt_dir, "encoder", "config.json")
    if os.path.exists(ep):
        ec = json.load(open(ep))
        out.update(model_type=ec.get("model_type", "n/a"), vocab=ec.get("vocab_size", "n/a"))
    return out


def build_info(df, tables, splits, per_class, out_dir, info_path, dropped=None):
    """Numbers for the data card, from the built frames only (no model load)."""
    from collections import Counter
    import datasets, laya, torch, transformers
    ang = df[df["label_origin"] == "laya_anger_split"].copy()
    src = Counter(ang["label_source"])
    timings = json.load(open(os.path.join(out_dir, "timings.json")))
    veto_str = "not run"
    if "p_not_anger_or_contempt" in ang and ang["p_not_anger_or_contempt"].notna().any():
        v = ang["p_not_anger_or_contempt"].dropna()
        veto_str = (f"{int((v > 0.5).sum())} of {len(v)} rows above 0.5 (mean P(neither) {v.mean():.2f}) "
                    f"- Indonesian reading")
    stage_rows = timings.get("stage_rows", {})
    n_states = sum(stage_rows.values()) or (4 * len(ang) + int(timings["ambiguous_rows"]) * 3)

    # agreement with the previous revision: `id_core` is the *same* stage, on the same texts, as the
    # published out/cache_id_core.json (shipped here as out_prev/), so a re-run has to reproduce it
    repro_note = "the shipped `out/cache_id_core.json` is from that run"
    new_cache = os.path.join(out_dir, "cache_id_core.json")
    if os.path.exists(PREV_CACHE) and os.path.exists(new_cache):
        a, b = json.load(open(PREV_CACHE)), json.load(open(new_cache))
        common = sorted(set(a) & set(b))
        d = [abs(a[k]["ekman"]["probabilities"]["anger"] - b[k]["ekman"]["probabilities"]["anger"])
             for k in common]
        same = sum((a[k]["ekman"]["probabilities"]["anger"] >= 0.5)
                   == (b[k]["ekman"]["probabilities"]["anger"] >= 0.5) for k in common)
        repro_note = (f"the `id_core` stage matches the earlier two-language run's "
                      f"`out_prev/cache_id_core.json` (shipped here) to the last digit - "
                      f"{same}/{len(common)} unique texts on the same side of the decision line, "
                      f"mean |delta p(anger)| {sum(d) / len(d):.4f}, max {max(d):.4f}")
        if same != len(common):
            n_moved = len(common) - same
            repro_note += (f"; the {n_moved} row{'s' if n_moved > 1 else ''} that moved sit within "
                           f"0.05 of p=0.5")

    # the second run (reconfirm.py): stage-by-stage and row-by-row agreement with the shipped labels
    reconfirm_note = "a second run has not been compared against this one"
    rc = os.path.join(out_dir, "reconfirm.json")
    if os.path.exists(rc):
        r = json.load(open(rc))
        st = r.get("stages", {})
        lab = r.get("labels", {})
        drift = [k for k, v in st.items() if v["max_abs_diff"] > 0 or v["only_in_a"] or v["only_in_b"]]
        covers = ", ".join(sorted(st))
        if lab and not drift and not lab["flips"]:
            sec = (r.get("second_run") or {}).get("total_laya_seconds")
            reconfirm_note = (f"every stage ({covers}) matched row for row and reproduced **"
                              f"{lab['identical']}/{lab['rows']} labels**")
            reconfirm_note += (", down to a byte-identical `anger_ekman_rows.csv`"
                               if lab.get("identical_bytes") else "")
            reconfirm_note += (f", the largest probability difference anywhere being "
                               f"{lab['max_prob_abs_diff']:.6f}")
            if sec:
                reconfirm_note += (f" ({sec:,.1f} s of model time against {timings['total_laya_seconds']:,.1f} s"
                                   f" for the shipped run)")
        elif lab:
            reconfirm_note = (f"the stages agreed on {lab['identical']}/{lab['rows']} labels, with "
                              f"drift in {drift or 'no stage'} and flips "
                              f"{lab['flips'] or 'none'} (largest probability difference "
                              f"{lab['max_prob_abs_diff']:.6f})")
        else:
            reconfirm_note = f"the stages agree as follows: {st}"

    # what changed against the previous revision's shipped labels (English-pooled decision)
    prev_note, prev_stats = "not available", {}
    if os.path.exists(PREV_CSV):
        pv = pd.read_csv(PREV_CSV)[["row_src", "label", "ekman_confidence"]].rename(
            columns={"label": "label_prev", "ekman_confidence": "conf_prev"})
        ang = ang.merge(pv, on="row_src", how="left")
        j = ang[["row_src", "label", "label_prev"]].dropna(subset=["label_prev"])
        if len(j):
            n_flip = int((j["label"] != j["label_prev"]).sum())
            p_ang, p_con = int((j["label_prev"] == "anger").sum()), int((j["label_prev"] == "contempt").sum())
            c2a = int(((j["label_prev"] == "contempt") & (j["label"] == "anger")).sum())
            a2c = int(((j["label_prev"] == "anger") & (j["label"] == "contempt")).sum())
            prev_stats = {"prev_anger": p_ang, "prev_contempt": p_con, "flipped": n_flip,
                          "flip_to_anger": c2a, "flip_to_contempt": a2c,
                          "prev_share_contempt": round(100.0 * p_con / len(j), 1)}
            prev_note = (f"it labelled {p_ang} anger / {p_con} contempt; the labels here differ on "
                         f"{n_flip} of the {len(j)} rows, {a2c} of them anger -> contempt")

    # the corpus's own evidence: EmoTweetID sampled by emotion keyword, so a row that contains an
    # explicit Indonesian anger word carries an upstream hint that it is anger and not contempt.
    # How often does each revision overrule that hint?
    LEXICON = ("kesal", "marah", "murka", "benci", "jengkel", "geram", "tersinggung", "muak", "ngamuk")
    hint = ang["text"].str.lower().str.contains("|".join(LEXICON), regex=True)
    lex_stats = {"lexicon_rows": int(hint.sum()), "lexicon_contempt_new": None,
                 "lexicon_contempt_prev": None}
    if "label_prev" in ang:
        lex_stats["lexicon_contempt_new"] = int((ang.loc[hint, "label"] == "contempt").sum())
        lex_stats["lexicon_contempt_prev"] = int((ang.loc[hint, "label_prev"] == "contempt").sum())
        lex_stats["lexicon_note"] = (
            f"{int(hint.sum())} of the {len(ang)} pool rows contain an explicit Indonesian anger word "
            f"(`kesal`, `marah`, `murka`, `benci`, `jengkel`, `geram`, `tersinggung`, `muak`, `ngamuk`) "
            f"- which is how EmoTweetID's annotators sampled, so the word is upstream evidence for "
            f"anger. {int((ang.loc[hint, 'label'] == 'contempt').sum())} of those "
            f"{int(hint.sum())} rows ({100.0 * (ang.loc[hint, 'label'] == 'contempt').mean():.0f}%) "
            f"are labelled `contempt` here.")
    else:
        lex_stats["lexicon_note"] = (f"{int(hint.sum())} pool rows contain an explicit Indonesian anger "
                                     f"word; the Indonesian-only reading calls "
                                     f"{int((ang.loc[hint, 'label'] == 'contempt').sum())} of them contempt")

    # the one-reader audit of the flips (audit_flips.py), shipped as out/audit_flips.csv
    audit_stats = {}
    ap = os.path.join(out_dir, "audit_flips.csv")
    if os.path.exists(ap):
        au = pd.read_csv(ap)
        n = len(au)
        a_new = int((au["verdict"] == au["label"]).sum())
        a_prev = int((au["verdict"] == au["shipped_label"]).sum())
        other = int((au["verdict"] == "other").sum())
        moved = au[au["label"] != au["shipped_label"]]
        moved_c = int((moved["label"] == "contempt").sum())
        moved_c_ok = int(((moved["label"] == "contempt") & (moved["verdict"] == "contempt")).sum())
        audit_stats = {
            "audit_n": n, "audit_agree_new": a_new, "audit_agree_prev": a_prev, "audit_other": other,
            "audit_note": (
                f"A sample of {n} rows where the readings disagree was judged against the operational "
                f"boundary by one reader working from the tweet text alone, before seeing any "
                f"probability: {a_prev}/{n} of those judgements land on the two-language reading, "
                f"{a_new}/{n} on the label here, and {other}/{n} read as neither emotion. Of the "
                f"{moved_c} rows labelled `contempt` here and `anger` by the two-language reading, "
                f"{moved_c_ok} was accepted as contempt. The reader is a machine reader, not a human "
                f"annotator, and works on short code-mixed text - a signal, not gold labels."),
            "audit_caveat": ("one reader, unblinded to the hypothesis, and the pool is short, shouty, "
                             "code-mixed Indonesian - rerun this on a larger sample before quoting it"),
        }

    # how close to a coin flip each revision's reading ended, on the same scale (max P of the reading)
    conf_stats = {"conf_low_new": int((np.maximum(ang["p_anger_id"], 1 - ang["p_anger_id"]) < 0.6).sum())}
    if "conf_prev" in ang:
        conf_stats["conf_low_prev"] = int((ang["conf_prev"] < 0.6).sum())
        conf_stats["conf_note"] = (
            f"{conf_stats['conf_low_new']} of {len(ang)} rows land within 0.10 of a coin flip on the "
            f"primary reading (max probability of the two options under 0.60), and the mean max "
            f"probability across the pool is "
            f"{float(np.mean(np.maximum(ang['p_anger_id'], 1 - ang['p_anger_id']))):.3f}")
    else:
        conf_stats["conf_note"] = f"{conf_stats['conf_low_new']} rows land within 0.10 of a coin flip"
    conf_stats["lowconf_laya"] = int((ang["ekman_confidence"] < 0.6).sum())

    # the option-order control, on the rows this build labels
    order_stats = {"order_flip": "n/a", "order_shift": "n/a",
                   "order_note": "not measured - run label_anger_id.py without --no-swap"}
    if "p_anger_swapped" in ang and ang["p_anger_swapped"].notna().any():
        pa, psw = ang["p_anger_id"].to_numpy(), ang["p_anger_swapped"].to_numpy()
        flip, shift = float(np.mean((pa >= 0.5) != (psw >= 0.5))), float(np.mean(np.abs(pa - psw)))
        order_stats = {
            "order_flip": round(100 * flip, 1),
            "order_shift": round(shift, 3),
            "mean_p_anger_prompt": round(float(np.mean(pa)), 3),
            "mean_p_anger_swapped": round(float(np.mean(psw)), 3),
            "order_note": (f"Listing contempt first moved the argmax on {100 * flip:.1f}% of the pool "
                           f"(mean |delta p(anger)| {shift:.3f}; mean P(anger) {np.mean(pa):.3f} as "
                           f"prompted vs {np.mean(psw):.3f} with the options swapped), so the "
                           f"prompt's option order is worth roughly a third of the contempt shift"),
        }

    # fit-for-purpose probes, both languages (out/probe_quality_id.json, from probe_quality_id.py)
    probe = {}
    pq = os.path.join(out_dir, "probe_quality_id.json")
    if os.path.exists(pq):
        conds = json.load(open(pq))["conditions"]
        tag = {c["condition"].strip()[0]: c for c in conds}
        def fmt(c):
            return f"{c['correct']}/{c['n']} ({c['accuracy']:.3f})"
        probe = {k: fmt(tag[t]) for k, t in
                 (("probe_author", "Z"), ("probe_en", "A"), ("probe_id", "B"),
                  ("probe_id_idq", "C"), ("probe_en_idq", "D"), ("probe_id_swapped", "E")) if t in tag}
        b, a, c_, d_, e = (tag.get(x) for x in "BACDE")
        if a and b:
            probe["probe_gap"] = (f"The gap is {a['correct'] - b['correct']} items out of 16: the same "
                                  f"sentences are called correctly {a['correct']} times in English and "
                                  f"{b['correct']} times in Indonesian")
            probe["probe_mean_p"] = (
                f"Mean P(anger) on the anger probes {b['per_class']['anger']['mean_p_anger']:.2f} in "
                f"Indonesian vs {a['per_class']['anger']['mean_p_anger']:.2f} in English; on the "
                f"contempt probes {b['per_class']['contempt']['mean_p_anger']:.2f} vs "
                f"{a['per_class']['contempt']['mean_p_anger']:.2f}")
        if b and c_:
            probe["probe_lang_q"] = (f"with the question in Indonesian instead of English, the gap "
                                     f"closes only {b['correct']} -> {c_['correct']} items")
        if d_:
            probe["probe_en_q"] = f"English items with the Indonesian question: {fmt(d_)}"
        if b and e:
            probe["probe_order"] = (
                f"On the contempt items the mean P(anger) is {b['per_class']['contempt']['mean_p_anger']:.2f} "
                f"with anger listed first and {e['per_class']['contempt']['mean_p_anger']:.2f} with "
                f"contempt listed first - the order effect seen on the corpus")
    facts = checkpoint_facts()
    tbl = []
    for name in CONFIGS:
        d, labels = tables[name], (LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN)
        present = [s for s in SPLITS if (d["split"] == s).any()]
        for s in present:
            vc = d.loc[d["split"] == s, "label"].value_counts()
            per = " / ".join(f"{c} {int(vc.get(c, 0))}" for c in labels if int(vc.get(c, 0)) > 0)
            note = " (the whole pool, one split)" if len(present) == 1 else ""
            tbl.append(f"| `{name}` | {s} | {int((d['split'] == s).sum()):,} | {per}{note} |")
    # one-line summary of every config's split sizes, for the card
    split_note = ", ".join(
        ("%s %s of %s (b=%d)" % (name, " / ".join(str(splits[name][x]) for x in SPLITS),
                                 f"{sum(splits[name].values()):,}", sum(splits[name].values()) // 10))
        if name in SPLIT_CONFIGS else
        ("%s 1 split of %s" % (name, f"{sum(splits[name].values()):,}"))
        for name in CONFIGS)
    dup = int(df.duplicated("text").sum())
    g = df.groupby("text")["source_label"].nunique()
    conflict = int((g > 1).sum())
    info = {
        "dup_conflicts": conflict,
        "n_pool": f"{len(df):,}",
        "n_anger_pool": f"{len(ang):,}",
        "n_manual": f"{len(df) - len(ang):,}",
        "n_contempt": int((df["label"] == "contempt").sum()),
        "n_anger_kept": int((df["label"] == "anger").sum()),
        "share_contempt": round(100.0 * int((ang["label"] == "contempt").sum()) / len(ang), 1),
        "n_balanced": int(sum(splits["balanced"].values())),
        "per_class_balanced": per_class["balanced"],
        "per_class_anger_balanced": per_class["anger_split_balanced"],
        "n_full_pool": int(sum(splits["full"].values())),
        "n_anger_pool_rows": int(sum(splits["anger_split"].values())),
        "balanced_split": " / ".join(str(splits["balanced"][x]) for x in SPLITS),
        "anger_split_balanced_split": " / ".join(str(splits["anger_split_balanced"][x]) for x in SPLITS),
        "balanced_per_class_split": " / ".join(
            str(apportion(per_class["balanced"])[i]) for i in range(3)),
        "anger_balanced_per_class_split": " / ".join(
            str(apportion(per_class["anger_split_balanced"])[i]) for i in range(3)),
        "n_anger_balanced": int(sum(splits["anger_split_balanced"].values())),
        "balanced_b": int(sum(splits["balanced"].values()) // 10),
        "n_balanced_s": f"{int(sum(splits['balanced'].values())):,}",
        "n_anger_balanced_s": f"{int(sum(splits['anger_split_balanced'].values())):,}",
        "whole_note": ("`full` and `anger_split` are the complete pools in a single `train` split - "
                       "nothing is held out, and users who want their own validation split take it "
                       "from there. The two balanced configs are the ones that carry an exact "
                       "8:1:1 train/valid/test."),
        "class_table": class_table(df, LABELS_EKMAN),
        "split_table": "\n".join(tbl),
        "sources_str": ", ".join(f"`{k}` {v}" for k, v in src.most_common()),
        "noul_n": int(src.get("ekman_noul_tiebreak", 0)),
        "choice_n": int(src.get("ekman_choice_id", 0)),
        "orderavg_n": int(src.get("ekman_choice_order_avg", 0)),
        "kept_n": int(src.get("kept_original_label", 0)),
        "ambig": int(ang["ambiguous"].sum()),
        "offtopic": int((ang["p_not_anger_or_contempt"] > 0.5).sum()),
        "lowconf": int((ang["ekman_confidence"] < 0.6).sum()),
        "stages": ", ".join(f"{k.replace('_', ' ')} {float(v):.1f} s"
                            for k, v in timings["stages"].items()),
        "veto": veto_str,
        "laya_seconds": round(timings["total_laya_seconds"], 1),
        "max_len": timings["max_len"],
        "head_max_len": timings["head_max_len"],
        "budget": timings["token_budget"],
        "margin": timings["margin"],
        "scored_rows": n_states,
        "naive_rows": 4 * len(ang),
        "repro_note": repro_note,
        "reconfirm_note": reconfirm_note,
        "prev_note": prev_note,
        "split_exact_note": split_note,
        **prev_stats, **lex_stats, **conf_stats, **order_stats, **probe, **audit_stats,
        "splits": splits,
        "duplicates_note": (
            f"{dup} rows share an identical `text` string with another row (more, if you count pairs "
            f"whose English translation collides), and {conflict} of those repeated wordings repeat "
            "with *different* upstream labels - the annotators disagreed, and this dataset inherits "
            "that rather than re-judging it. Splitting is therefore **group-aware**: every member of a "
            "duplicate group lands in one split, so no wording appears in either side of a "
            "train/valid/test boundary (`verify()` fails the build if one does). The balanced "
            "configs sample whole groups as well, so a dropped row never orphans its duplicate."),
        "checkpoint": "convaiinnovations/laya (subfolder `multilingual/`)",
        "laya_v": laya.__version__, "datasets_v": datasets.__version__,
        "transformers_v": transformers.__version__, "torch_v": torch.__version__,
        "stageC": int(timings["ambiguous_rows"]),
        "stage_diag": int(stage_rows.get("id_diag", 2 * int(timings["ambiguous_rows"]))),
        "dup_conflicts": conflict,
        **{k: (f"{v / 1e6:.1f}M" if k.startswith("params") and isinstance(v, int) else v)
           for k, v in facts.items()},
    }
    with open(info_path, "w") as f:
        json.dump(info, f, indent=1, sort_keys=True)
    return info


def render_readme(info, template="README.template.md"):
    with open(template) as f:
        out = f.read()
    for k, v in info.items():
        out = out.replace("{{" + k + "}}", str(v))
    left = sorted(set(re.findall(r"\{\{(\w+)\}\}", out)))
    if left:
        raise SystemExit(f"unfilled README placeholders: {left}")
    return out


def verify(dist, out_dir=OUT_DIR):
    """Open the written parquet files and check labels, provenance, leakage and card numbers."""
    from datasets import Value, load_dataset
    info = json.load(open(os.path.join(dist, "build_info.json")))
    for name in CONFIGS:
        labels = LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN
        present = [s for s in SPLITS if os.path.exists(os.path.join(dist, name, f"{s}.parquet"))]
        ds = load_dataset("parquet", data_files={s: os.path.join(dist, name, f"{s}.parquet")
                                                 for s in present})
        assert list(ds[present[0]].features["label_idx"].names) == list(labels), f"{name}: label_idx"
        assert ds[present[0]].features["label"] == ds[present[0]].features["text"] == Value("string")
        for s in present:
            d = ds[s].to_pandas()
            assert len(d) > 0 and set(d["label"]) <= set(labels), f"{name}/{s}: bad labels"
            assert (d["text"].str.len() > 0).all() and (d["text_en"].str.len() > 0).all()
            ws = d["text"].str.replace(r"\s+", " ", regex=True).str.strip()
            assert (d["text"] == ws).all(), f"{name}/{s}: text not normalised"
            assert (d["label_idx"] == [labels.index(x) for x in d["label"]]).all(), f"{name}/{s}: idx"
            pool = d["label_origin"] == "laya_anger_split"
            assert set(d.loc[pool, "source_label"]) == {"anger"}, f"{name}: relabelled a non-anger row"
            kept = d.loc[~pool]
            assert (kept["label"] == kept["source_label"].map(
                lambda x: SOURCE_TO_EKMAN.get(x, x))).all(), f"{name}: changed a human label"
            if name.startswith("anger"):
                assert pool.all(), f"{name}: non-anger row inside the anger config"
                assert d["ekman_p_anger"].notna().all(), f"{name}: missing probabilities"
            else:
                assert d.loc[~pool, "ekman_p_anger"].isna().all(), f"{name}: stray evidence values"
            for other in present:
                if other == s:
                    continue
                o = ds[other].to_pandas()
                assert not set(d["text"]) & set(o["text"]), f"{name}: text leakage {s}/{other}"
                assert not set(d["text_en"]) & set(o["text_en"]), f"{name}: translated-text leakage"
        counts = {s: len(ds[s]) for s in present}
        assert counts == info["splits"][name], f"{name}: card counts {info['splits'][name]} != {counts}"
        tot = sum(counts.values())
        if len(present) == 1:
            assert present == ["train"], f"{name}: a single-split config must ship `train` only"
            assert tot == info["n_full_pool" if name == "full" else "n_anger_pool_rows"], \
                f"{name}: the whole pool must be in `train` ({tot} rows)"
            print(f"[verify] {name}: {tot} rows, one split (the whole pool, nothing held out)")
            continue
        want = apportion(tot)                        # exact 8b : 1b : 1b
        got = [counts[s] for s in SPLITS]
        assert got == want, f"{name}: split sizes {got} != 8b:b:b targets {want}"
        frac = [abs(counts[s] / tot - x) * 100 for s, x in zip(SPLITS, (0.8, 0.1, 0.1))]
        assert tot % 10 == 0 and tot - 2 * (tot // 10) == 8 * (tot // 10), f"{name}: 10 | N"
        print(f"[verify] {name}: {got} of {tot} rows, b={tot // 10}, off 8:1:1 by "
              f"{frac[0]:.2f}/{frac[1]:.2f}/{frac[2]:.2f} points, {tot // len(labels)} per class")
    # the balanced configs must be exact per class in every split, not just in the column totals
    for name in SPLIT_CONFIGS:
        labels = LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN
        per = info["per_class_" + ("anger_balanced" if name.startswith("anger") else "balanced")]
        want = apportion(per)
        for s in SPLITS:
            d = pd.read_parquet(os.path.join(dist, name, f"{s}.parquet"))
            vc = d["label"].value_counts()
            assert set(vc.values) == {want[SPLITS.index(s)]}, f"{name}/{s}: per-class {vc.to_dict()}"
        print(f"[verify] {name}: {per} rows per class, {want[0]} / {want[1]} / {want[2]} per class")
    # every shipped row still matches the upstream CSV, on top of the per-split checks
    src = pd.read_csv(DATA_CSV)
    src["text"] = src["tweet"].astype(str).map(norm)
    src["source_label"] = src["label"].astype(str).str.strip().str.lower()
    def _splits_on_disk(cfg):
        return [x for x in SPLITS if os.path.exists(os.path.join(dist, cfg, f"{x}.parquet"))]

    pool = pd.concat([pd.read_parquet(os.path.join(dist, "full", f"{s}.parquet"))
                      for s in _splits_on_disk("full")])
    assert len(pool) == len(src) == 2243, f"full config covers {len(pool)} of {len(src)}"
    # join on row_src, not on text: identical wordings are not the same row (and can disagree)
    src["row_src"] = src.index
    m = pool[["row_src", "text", "source_label", "label", "label_origin"]].merge(
        src[["row_src", "label", "tweet"]], on="row_src", how="outer", suffixes=("", "_src"))
    assert len(m) == len(src) and m["label_src"].notna().all(), "row_src coverage mismatch"
    assert (m["source_label"] == m["label_src"].str.strip().str.lower()).all(), \
        "source_label disagrees with upstream"
    assert (m["text"] == m["tweet"].astype(str).str.replace(r"\s+", " ", regex=True).str.strip()).all(), \
        "text is not the whitespace-normalised upstream tweet"
    ang = pd.concat([pd.read_parquet(os.path.join(dist, "anger_split", f"{s}.parquet"))
                     for s in _splits_on_disk("anger_split")])[["row_src", "label"]]
    raw = pd.read_csv(os.path.join(out_dir, "anger_ekman_rows.csv"))
    raw = raw[raw["source_label"] == "anger"][["row_src", "label"]]
    j = ang.merge(raw, on="row_src", suffixes=("", "_csv"))
    assert len(j) == len(ang) == len(raw) and (j["label"] == j["label_csv"]).all(), \
        "anger_split does not equal the labeller's CSV"
    print(f"[verify] provenance: {len(pool)} rows vs upstream CSV, {len(ang)} anger rows vs "
          f"{out_dir}/anger_ekman_rows.csv -> ok")
    # the card's YAML front matter is what huggingface.co parses into dataset configs: check that it
    # declares exactly the configs on disk, that its paths resolve, and that `label_idx` matches its
    # declared ClassLabel names
    import yaml
    txt = open(os.path.join(dist, "README.md")).read()
    fm = yaml.safe_load(txt[txt.index("---") + 3:txt.index("---", txt.index("---") + 3)])
    cfgs = {c["config_name"]: c for c in fm["configs"]}
    assert list(cfgs) == list(CONFIGS), f"card configs {list(cfgs)} != {list(CONFIGS)}"
    assert [n for n, c in cfgs.items() if c.get("default")] == ["balanced"], "default config"
    for name, c in cfgs.items():
        declared_splits = [d["split"] for d in c["data_files"]]
        on_disk = _splits_on_disk(name)
        assert sorted(declared_splits) == sorted(on_disk), \
            f"{name}: card declares {declared_splits} but disk has {on_disk}"
        for d in c["data_files"]:
            p = os.path.join(dist, d["path"])
            assert os.path.exists(p), f"card points at a missing file: {d['path']}"
            import pyarrow.parquet as pq
            names = pq.read_schema(p).field("label_idx").metadata
            declared = list(LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN)
            if names:
                assert json.loads(names.decode()).get("names") == declared, f"{d['path']}: ClassLabel names"
        n_total = sum(len(pd.read_parquet(os.path.join(dist, name, f"{s}.parquet")))
                      for s in _splits_on_disk(name))
        assert n_total == sum(info["splits"][name].values()), f"{name}: card/parquet row mismatch"
    print(f"[verify] card YAML: {len(cfgs)} configs, default=balanced, every declared path exists "
          f"and carries the right ClassLabel names")
    return True


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dist", default="dist")
    ap.add_argument("--out-dir", default=OUT_DIR, help="dir holding anger_ekman_rows.csv")
    ap.add_argument("--repo", default="mahalisyarifuddin/emotweetid-ekman7", help="recorded in build_info")
    a = ap.parse_args()
    os.makedirs(a.dist, exist_ok=True)
    df, _ = load_pool(a.out_dir)
    df = add_text_group(df)
    ang_pool = df[df["label_origin"] == "laya_anger_split"].reset_index(drop=True)
    tables, splits, per_class, dropped = {}, {}, {}, {}
    for name, labels in (("balanced", LABELS_EKMAN), ("full", LABELS_EKMAN),
                         ("anger_split", LABELS_BINARY), ("anger_split_balanced", LABELS_BINARY)):
        base = df if name in ("full", "balanced") else ang_pool
        if name in SPLIT_CONFIGS:
            base, per_class[name], dropped[name] = balanced_pool(base, labels)
            assert sum(base["label"].value_counts().values) % 10 == 0, "a split config needs 10 | N"
            sub = stratified_811(base, SEED)
            expected = apportion(len(sub))
            got = [int((sub["split"] == s).sum()) for s in SPLITS]
            assert got == expected, f"{name}: {got} != 8b:b:b {expected}"
        else:
            per_class[name] = int(base["label"].value_counts().min())
            sub = base.copy()
            sub["split"] = SPLITS[0]              # the whole pool, one split, nothing held out
        tables[name] = sub
        splits[name] = {s: int((sub["split"] == s).sum()) for s in SPLITS if (sub["split"] == s).any()}
        print(f"[build] {name}: {write_parquet(sub, labels, a.dist, name)} "
              f"({splits[name]}, per-class>={per_class[name]})")
    info = build_info(df, tables, splits, per_class, a.out_dir,
                      os.path.join(a.dist, "build_info.json"), dropped=dropped)
    info["repo"] = a.repo
    with open(os.path.join(a.dist, "README.md"), "w") as f:
        f.write(render_readme(info))
    with open(os.path.join(a.dist, ".gitattributes"), "w") as f:
        f.write("*.parquet filter=lfs diff=lfs merge=lfs -text\n")
    found = set()
    for f in sorted(os.listdir(".")):
        if f in SHIPPED:
            shutil.copy(f, os.path.join(a.dist, f))
            found.add(f)
    assert found == set(SHIPPED), f"not shipped: {sorted(set(SHIPPED) - found)}"
    if os.path.isdir("runs"):
        os.makedirs(os.path.join(a.dist, "runs"), exist_ok=True)
        for f in sorted(os.listdir("runs")):
            shutil.copy(os.path.join("runs", f), os.path.join(a.dist, "runs", f))
    os.makedirs(os.path.join(a.dist, "out"), exist_ok=True)
    for f in ("veto_check.json", "speedup.json", "timings.json", "anger_ekman_rows.csv",
              "probe_quality_id.json", "audit_flips.csv", "audit_summary.json",
              "reconfirm.json",
              "cache_id_core.json", "cache_id_core_swap.json",
              "cache_id_diag.json", "cache_id_veto.json"):
        p = os.path.join(a.out_dir, f)
        if os.path.exists(p):
            shutil.copy(p, os.path.join(a.dist, "out", f))
    # the previous revision's run artefacts, so the new-vs-old comparison in the card is reproducible
    if os.path.isdir(PREV_DIR) and os.path.abspath(PREV_DIR) != os.path.abspath(a.out_dir):
        prev_out = os.path.join(a.dist, "out_prev")
        os.makedirs(prev_out, exist_ok=True)
        for f in sorted(os.listdir(PREV_DIR)):
            src = os.path.join(PREV_DIR, f)
            if os.path.isfile(src):
                shutil.copy(src, os.path.join(prev_out, f))
        print("[write] out_prev/ = the previous revision's caches", sorted(os.listdir(prev_out)))
    with open(os.path.join(a.dist, "build_info.json"), "w") as f:   # now incl. repo
        json.dump(info, f, indent=1, sort_keys=True)
    print("[write] README.md,", json.dumps({k: info[k] for k in
                                            ("n_pool", "n_anger_pool", "n_contempt", "n_anger_kept",
                                             "share_contempt", "n_balanced", "laya_seconds")}))
    # nothing that is not part of the dataset may reach the published tree (working notes and the
    # build scratch dir are the two that have been tempting)
    forbidden = [f for f in os.listdir(a.dist)
                 if f.upper().startswith(("REVISION_NOTES", "NOTES", "TODO", "CHANGELOG"))
                 or f in ("build", "models", "data", "dist")]
    assert not forbidden, f"refusing to publish: {forbidden}"
    verify(a.dist, a.out_dir)


if __name__ == "__main__":
    main()