File size: 80,925 Bytes
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
 
 
 
 
 
 
 
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
"""Join the cached catalogues into one machine-readable translation-resource table.

One row per FineWiki language config. Scalar and boolean columns carry the sortable
state of each language; the ``*_json`` columns carry the detailed per-source dictionaries.
The same rows are also written as nested JSONL, where the dictionaries stay real objects.

The point of the table is to find languages that have a usable Wikipedia and a closely
related high-resource neighbour to mine comparable text from, but little or no existing
machine-translation support -- Gilaki, Mazandarani and Bavarian are the worked examples.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

import lang_audit_sources as sources  # noqa: E402

CACHE = ROOT / "cache" / "lang_audit"
DIST = ROOT / "dist" / "lang_audit"
SCHEMA_VERSION = 3

# Wikipedia prefixes that are not ISO 639-1/639-3 codes. Each entry records the
# three-letter code the wiki's content actually belongs to, plus why.
PREFIX_OVERRIDES = {
    "als": (
        "gsw",
        "Alemannic German. als.wikipedia.org was created before ISO 639-3 assigned 'als' to "
        "Tosk Albanian; Wikimedia files this wiki under 'gsw' and Albanian is at "
        "sq.wikipedia.org. See COLLIDING_PREFIXES.",
    ),
    "bat_smg": ("sgs", "Samogitian; 'bat-smg' is a retired collective prefix."),
    "bh": ("bho", "The 'bh' wiki is written in Bhojpuri; 'bh' is the Bihari collective code."),
    "cbk_zam": ("cbk", "Chavacano (Zamboanga)."),
    "eml": ("egl", "Emilian; the 'eml' wiki covers Emilian and Romagnol (egl/rgn)."),
    "fiu_vro": ("vro", "Voro; 'fiu-vro' is a retired collective prefix."),
    "map_bms": ("jav", "Banyumasan, a Javanese variety; no separate ISO 639-3 code."),
    "nah": (None, "Nahuatl is a collective ISO 639-5 code; the wiki mixes Nahuatl varieties."),
    "nds_nl": ("nds", "Dutch Low Saxon, written with Low German's ISO 639-3 code."),
    "roa_rup": ("rup", "Aromanian."),
    "roa_tara": ("nap", "Tarantino, a Neapolitan variety with no separate ISO 639-3 code."),
    "simple": ("eng", "Simple English Wikipedia; the language is English."),
    "zh_classical": ("lzh", "Literary Chinese."),
    "zh_min_nan": ("nan", "Southern Min / Hokkien."),
    "zh_yue": ("yue", "Cantonese."),
}

# Wikipedia prefixes that are themselves valid ISO 639-3 codes for a *different* language
# than the wiki is written in. For these the raw prefix must stay out of the alias set:
# the ISO-keyed catalogues (FLORES, NLLB, NTREX, sacreBLEU, Tatoeba, Google, Microsoft) use
# the string for the other language, so matching on it credits one language with another's
# resources. Catalogues keyed by Wikipedia prefix instead of ISO code are unaffected,
# because they are looked up by config name directly rather than through aliases.
#
# Derived from the Wikimedia sitematrix, which is authoritative for which language code each
# wikipedia.org subdomain belongs to; ``test_prefix_overrides_match_sitematrix`` re-checks
# this set against a fresh snapshot. ``als`` is currently the only such collision in the 325
# FineWiki configs.
COLLIDING_PREFIXES = {"als"}

# Glottolog has no languoid for an ISO 639-3 macrolanguage, so a wiki that uses one
# (``fa``, ``ar``, ``zh``) would carry no family or classification path at all. Each entry
# names the standard member variety whose place in the tree stands in for the macrolanguage.
MACROLANGUAGE_PROXIES = {
    "ara": ("arb", "Modern Standard Arabic"),
    "aze": ("azj", "North Azerbaijani"),
    "est": ("ekk", "Standard Estonian"),
    "fas": ("pes", "Iranian Persian"),
    "grn": ("gug", "Paraguayan Guarani"),
    "iku": ("ike", "Eastern Canadian Inuktitut"),
    "kon": ("kng", "Koongo"),
    "mlg": ("plt", "Plateau Malagasy"),
    "msa": ("zsm", "Standard Malay"),
    "ori": ("ory", "Odia"),
    "orm": ("gaz", "West Central Oromo"),
    "que": ("quy", "Ayacucho Quechua, the variety FLORES uses for Quechua"),
    "srd": ("src", "Logudorese Sardinian"),
    "swa": ("swh", "Coastal Swahili"),
    "yid": ("ydd", "Eastern Yiddish"),
    "zho": ("cmn", "Mandarin Chinese"),
}

# Rows that would distort a scarcity ranking because they are not a distinct language.
RANKING_EXCLUSIONS = {
    "simple": "Simple English Wikipedia is English, which is the best-resourced language.",
}

# A language counts as a high-resource anchor -- a candidate source of parallel text --
# when a commercial system translates it, a standard benchmark evaluates it, and its
# Wikipedia is large enough to mine.
ANCHOR_MIN_ARTICLES = 40_000

# Below this many FineWiki articles, a Wikipedia is too small to mine a worthwhile
# parallel corpus from, however under-served the language is otherwise. Relaxed from 20,000
# to admit mid-size wikis whose articles are concentrated in a close high-resource relative
# -- Neapolitan at ~15,000 articles shares 95% of them with Italian.
MIN_ARTICLES_FOR_MINING = 12_000

# Above this many FineWiki articles the language is not the under-served case this audit is
# looking for. A very large wiki means an active, visible community and, usually, a variety
# whose separation from its standard relative is already well recognised and already served
# -- Egyptian Arabic at 1.6M articles is the clear example. Mined data adds least there.
MAX_ARTICLES_FOR_MINING = 300_000

# Past this much public parallel training text, a newly mined corpus adds little: the
# language is already well supplied on the training side even if no product translates it.
# The value sits in the natural gap in the candidate distribution (1.0M to 2.0M).
TRAINING_SATURATION_SENTENCES = 2_000_000


def _normalise(code: str) -> str:
    return re.sub(r"[^a-z0-9]+", "_", (code or "").strip().lower())


# Catalogue codes whose script or region tag carries the language distinction, so that
# stripping it would attribute the entry to the wrong language. Each maps the full tagged
# code to the ISO 639-3 language it actually denotes.
#
# Without this, ``pa-Arab`` reduces to ``pa`` -- Eastern Punjabi in Gurmukhi -- and Google
# Translate's Shahmukhi Punjabi is credited to the wrong wiki while pnb.wikipedia, which is
# written in exactly that variety, is recorded as having no commercial support at all.
TAGGED_CODE_EQUIVALENCES = {
    # Google Translate still ships two languages under the ISO 639-1 codes that were
    # retired in 1989. Without these, Hebrew and Javanese are recorded as having no
    # commercial support at all, which also drops them from the high-resource anchor set
    # and so from every other language's pivot and closest-relative calculation.
    #
    # Only these two are mapped. Google also lists several macrolanguage codes whose wiki is
    # a single member variety ('chm' vs Meadow Mari 'mhr', 'bik' vs Central Bikol 'bcl',
    # 'rom' vs Vlax Romani 'rmy'); which variety the product actually serves is a judgement
    # rather than a documented alias, so those stay unmatched rather than guessed.
    "iw": ("heb", "Hebrew. Google Translate uses the retired ISO 639-1 code 'iw'."),
    "jw": ("jav", "Javanese. Google Translate uses the retired ISO 639-1 code 'jw'."),
    "fil_latn": (
        "tgl",
        "FLORES+ publishes the Tagalog set under the Filipino code 'fil_Latn'; FLORES-200 "
        "called the same set 'tgl_Latn'. tl.wikipedia.org is the Tagalog wiki.",
    ),
    "pa_arab": (
        "pnb",
        "Punjabi (Shahmukhi). Google Translate ships 'pa' (Gurmukhi) and 'pa-Arab' "
        "(Shahmukhi) as separate languages; the Shahmukhi variety is Western Punjabi, which "
        "is what pnb.wikipedia.org is written in.",
    ),
}


def _script_base(code: str) -> str:
    """'pes_Arab' -> 'pes'; 'eng' -> 'eng'; 'pt-BR' -> 'pt'.

    A code listed in ``TAGGED_CODE_EQUIVALENCES`` keeps the language its tag denotes instead
    of collapsing to its base subtag.
    """
    equivalent = TAGGED_CODE_EQUIVALENCES.get(_normalise(code))
    if equivalent:
        return equivalent[0]
    token = re.split(r"[-_]", (code or "").strip())[0]
    return token.lower()


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1 << 20), b""):
            digest.update(chunk)
    return digest.hexdigest()


# --------------------------------------------------------------------- code reconciliation


class CodeIndex:
    """Resolve a Wikipedia prefix to every code other catalogues might use for it."""

    def __init__(self, iso: dict, macro: dict, glottolog: dict):
        self.part1 = iso["part1_to_part3"]
        self.codes = iso["codes"]
        self.members = macro["members"]
        self.to_macro = macro["individual_to_macro"]
        self.iso_to_glottocode = glottolog["iso_to_glottocode"]

    def resolve(self, config: str) -> dict:
        note = None
        if config in PREFIX_OVERRIDES:
            iso3, note = PREFIX_OVERRIDES[config]
        elif config in self.part1:
            iso3 = self.part1[config]
        elif config in self.codes:
            iso3 = config
        else:
            iso3 = None
        entry = self.codes.get(iso3 or "", {})
        macro = self.to_macro.get(iso3) if iso3 else None
        members = self.members.get(iso3, []) if iso3 else []
        # Alias expansion is deliberately one-way. A macrolanguage wiki (``fa``) may claim
        # resources published for its member varieties (``pes_Arab``), because that is the
        # language it is written in. The reverse is false: a FLORES or Tatoeba set for
        # Modern Standard Arabic does not evaluate Egyptian Arabic, so an individual
        # language never inherits its macrolanguage's resources.
        # A colliding prefix denotes another language in the ISO-keyed catalogues, so it is
        # never an alias for this wiki's language.
        if config in COLLIDING_PREFIXES:
            aliases = set()
        else:
            aliases = {config, config.replace("_", "-")}
        if iso3:
            aliases.add(iso3)
            if entry.get("part1"):
                aliases.add(entry["part1"])
            if entry.get("part2b"):
                aliases.add(entry["part2b"])
        aliases.update(members)
        aliases = {_normalise(a) for a in aliases if a}

        # The macrolanguage's own codes, kept separate so that inherited support can be
        # disclosed as a flag without silently inflating any sentence count.
        macro_aliases = set()
        if macro:
            macro_aliases.add(macro)
            macro_entry = self.codes.get(macro, {})
            for field in ("part1", "part2b"):
                if macro_entry.get(field):
                    macro_aliases.add(macro_entry[field])
        macro_aliases = {_normalise(a) for a in macro_aliases if a} - aliases

        glottocode = self.iso_to_glottocode.get(iso3) if iso3 else None
        proxy_note = None
        if glottocode is None and iso3 in MACROLANGUAGE_PROXIES:
            proxy, description = MACROLANGUAGE_PROXIES[iso3]
            glottocode = self.iso_to_glottocode.get(proxy)
            if glottocode:
                proxy_note = (
                    f"Glottolog has no languoid for the macrolanguage {iso3}; "
                    f"genealogy is taken from {proxy} ({description})."
                )
        return {
            "iso639_3": iso3,
            "iso639_1": entry.get("part1"),
            "iso639_scope": entry.get("scope") or None,
            "iso639_name": entry.get("name") or None,
            "macrolanguage": macro,
            "macrolanguage_members": members,
            "glottocode": glottocode,
            "glottolog_proxy_note": proxy_note,
            "code_aliases": sorted(aliases),
            "macrolanguage_aliases": sorted(macro_aliases),
            "code_note": note,
        }


def _classification_path(glottocode, languoid, classification) -> tuple[list[str], str]:
    """Root-to-leaf Glottolog path, with documented fallbacks when the tree lacks the node.

    Dialect-level languoids are absent from the classification trees, so the path of the
    language they belong to is used and the dialect appended. Isolates and a few languoids
    have no tree at all; for those the family alone is better than nothing, and the source
    of the path is recorded so a shallow match can be recognised as shallow.
    """
    if not glottocode:
        return [], "none"
    direct = classification.get(glottocode)
    if direct:
        return direct, "classification_tree"
    parent = languoid.get("language_id")
    if parent and classification.get(parent):
        return classification[parent] + [glottocode], "via_parent_language"
    family = languoid.get("family_id")
    if family and classification.get(family):
        return classification[family] + [glottocode], "via_family"
    if family:
        return [family, glottocode], "family_only"
    return [glottocode], "self_only"


def _config_matches(config: str, aliases: set[str]) -> bool:
    """Does a benchmark config name refer to this language?

    Config names are either one language (``ace_Arab``) or a pair (``en-ar_EG``, ``af-en``),
    so every dash-separated token is checked after its script or region suffix is stripped.
    """
    for token in config.replace("__", "-").split("-"):
        if not token:
            continue
        if _normalise(_script_base(token)) in aliases or _normalise(token) in aliases:
            return True
    return False


def benchmark_table(aliases: set[str], benchmarks: dict, overrides: dict) -> dict:
    """Per-benchmark coverage, access status and sentence counts for one language.

    ``overrides`` lets a benchmark whose data files cannot be read take its coverage from a
    more authoritative source and its sentence counts from an open mirror, rather than
    guessing either.
    """
    table = {}
    for dataset, record in sorted(benchmarks.items()):
        # A mirror kept only for its sentence counts is not a resource in its own right, and
        # reporting it would double-count the release it mirrors.
        if record.get("reports_coverage") is False:
            continue
        entry = {
            "dataset": dataset,
            "url": record["url"],
            "role": record["role"],
            "access": record["declared_access"],
            "gated": record.get("gated"),
            "license": record.get("license"),
            "note": record["note"],
        }
        if record["coverage_mode"] == "configs":
            matched = sorted(c for c in record["configs"] if _config_matches(c, aliases))
            counts: dict[str, int] = {}
            for config in matched:
                for role, rows in record["configs"][config].items():
                    counts[role] = counts.get(role, 0) + int(rows)
            entry["covered"] = bool(matched)
            entry["configs"] = matched
            entry["sentences"] = counts
        else:
            codes = _match(aliases, record["card_languages"])
            entry["covered"] = bool(codes)
            entry["codes"] = codes
            entry["sentences"] = dict(record["per_language_rows"]) if codes else {}
            if not record["per_language_rows"]:
                entry["sentences_unavailable_reason"] = (
                    "gated repository" if record["declared_access"] == "gated_terms"
                    else "the datasets server cannot convert this repository"
                )
        override = overrides.get(dataset)
        if override:
            entry.update(override)
        table[dataset] = entry
    return table


def _match(aliases: set[str], catalogue_codes) -> list[str]:
    """Catalogue codes whose base code matches one of a language's aliases."""
    hits = []
    for code in catalogue_codes:
        base = _normalise(_script_base(code))
        if base in aliases or _normalise(code) in aliases:
            hits.append(code)
    return sorted(set(hits))


# ------------------------------------------------------------------------------- building


def load_all() -> dict:
    names = [
        "finewiki", "wikimedia_sitematrix", "wikistats", "iso639_3",
        "iso639_macrolanguages", "glottolog_languages", "glottolog_classification",
        "flores_plus", "bouquet", "nllb200", "smol", "ntrex", "sacrebleu",
        "google_translate", "microsoft_translator", "madlad400", "glot500", "hplt2",
        "tatoeba_challenge", "community_benchmarks", "hf_benchmarks", "opus",
        "hub_datasets",
    ]
    data = {name: sources.load(name) for name in names}
    overlap_path = CACHE / "overlap.json"
    if not overlap_path.exists():
        raise RuntimeError(
            "cache/lang_audit/overlap.json is missing; run scripts/lang_audit_overlap.py first"
        )
    data["overlap"] = json.loads(overlap_path.read_text(encoding="utf-8"))

    # The JSON report keeps only each language's top partners. The full matrix gives exact
    # counts for any pair, which is what the closest-relative and pivot columns need.
    matrix_path = CACHE / "overlap_matrix.npz"
    if matrix_path.exists():
        import numpy as np

        archive = np.load(matrix_path, allow_pickle=True)
        order = [str(name) for name in archive["order"]]
        data["overlap_matrix"] = {
            "order": order,
            "index": {name: position for position, name in enumerate(order)},
            "shared": archive["shared"],
        }
    else:
        data["overlap_matrix"] = None

    coverage_path = CACHE / "coverage.json"
    if not coverage_path.exists():
        raise RuntimeError(
            "cache/lang_audit/coverage.json is missing; run "
            "scripts/lang_audit_coverage.py --all first"
        )
    data["coverage"] = json.loads(coverage_path.read_text(encoding="utf-8"))
    return data


def _sacrebleu_index(sacrebleu: dict) -> dict:
    """Map a normalised language code to the sacreBLEU test sets that cover it."""
    index: dict[str, set[str]] = {}
    for name, entry in sacrebleu["testsets"].items():
        for langpair in entry["langpairs"]:
            for side in langpair.split("-"):
                index.setdefault(_normalise(_script_base(side)), set()).add(name)
    return {k: sorted(v) for k, v in index.items()}


def _tatoeba_index(tatoeba: dict) -> dict:
    """Map a normalised language code to its Tatoeba Challenge test pairs and tier.

    Test availability comes from the repository's ``data/test`` listing, which is the only
    complete answer: the tier tables bucket pairs by *training* size and between them cover
    roughly a sixth of the release, so a pair with test data but little or no training data
    appears in none of them. Reading availability off the tiers reported "no test set" for
    languages that have one. The tiers are still used for ``tatoeba_tier`` itself, which is
    a statement about training size and is only meaningful for the English pair.
    """
    index: dict[str, dict] = {}

    def record_for(code: str) -> dict:
        return index.setdefault(
            _normalise(_script_base(code)),
            {"tiers": set(), "pairs": 0, "test_pairs": 0, "test_partners": set(),
             "english": None},
        )

    for pair in (tatoeba.get("test_pairs") or {}).get("pairs") or []:
        left, _, right = pair.partition("-")
        if not right:
            continue
        for side, other in ((left, right), (right, left)):
            if _script_base(side) == _script_base(other):
                continue  # same-language pair, not a translation direction
            entry = record_for(side)
            entry["test_pairs"] += 1
            entry["test_partners"].add(_normalise(_script_base(other)))

    for tier, payload in tatoeba["tiers"].items():
        for pair, counts in payload["pairs"].items():
            left, _, right = pair.partition("-")
            for side, other in ((left, right), (right, left)):
                entry = record_for(side)
                entry["tiers"].add(tier)
                entry["pairs"] += 1
                if _script_base(other) in {"eng", "en"}:
                    entry["english"] = {"pair": pair, "tier": tier, **counts}
    for entry in index.values():
        entry["tiers"] = sorted(entry["tiers"])
        entry["test_partners"] = sorted(entry["test_partners"])
    return index


def _smol_index(smol: dict) -> dict:
    out: dict[str, set[str]] = {}
    for subset, languages in smol["subsets"].items():
        if subset == "other":
            continue
        for code in languages:
            out.setdefault(_normalise(_script_base(code)), set()).add(subset)
    return {k: sorted(v) for k, v in out.items()}


def build_rows(data: dict) -> list[dict]:
    finewiki = data["finewiki"]["configs"]
    sitematrix = data["wikimedia_sitematrix"]["languages"]
    wikistats = data["wikistats"]["wikis"]
    glottolog = data["glottolog_languages"]["languoids"]
    classification = data["glottolog_classification"]["paths"]
    overlap = data["overlap"]["per_language"]
    opus = data["opus"]["languages"]
    hub = data["hub_datasets"]["languages"]
    coverage = data["coverage"]["languages"]
    hf_benchmarks = data["hf_benchmarks"]["benchmarks"]
    # The registry in the fetcher decides which repositories are reported as coverage and
    # which are only count mirrors. Re-applying it here means a snapshot taken before a
    # registry change cannot silently reinstate a mirror as a resource of its own.
    for entry in sources.BENCHMARK_REGISTRY:
        record = hf_benchmarks.get(entry["id"])
        if record is not None:
            record["reports_coverage"] = entry.get("reports_coverage", True)
    community = data["community_benchmarks"]
    community_by_language = community["by_language"]
    community_detail = {b["id"]: b for b in community["benchmarks"]}

    index = CodeIndex(
        data["iso639_3"], data["iso639_macrolanguages"], data["glottolog_languages"]
    )
    sacrebleu_index = _sacrebleu_index(data["sacrebleu"])
    tatoeba_index = _tatoeba_index(data["tatoeba_challenge"])
    smol_index = _smol_index(data["smol"])

    flores_plus = data["flores_plus"]["dev_split_codes"]
    bouquet = data["bouquet"]
    nllb200 = data["nllb200"]["codes"]
    ntrex = data["ntrex"]["languages"]
    google_target = data["google_translate"]["target_languages"]
    google_source = data["google_translate"]["source_languages"]
    microsoft = data["microsoft_translator"]["translation"]
    madlad = data["madlad400"]["languages"]
    glot500 = data["glot500"]["languages"]
    hplt2 = data["hplt2"]["configs"]

    rows = []
    for config in sorted(finewiki):
        size = finewiki[config]
        hyphen = config.replace("_", "-")
        site = sitematrix.get(hyphen) or sitematrix.get(config) or {}
        stats = wikistats.get(hyphen) or wikistats.get(config) or {}
        codes = index.resolve(config)
        aliases = set(codes["code_aliases"])
        macro_aliases = set(codes["macrolanguage_aliases"])

        glottocode = codes["glottocode"]
        languoid = glottolog.get(glottocode or "", {})
        family = glottolog.get(languoid.get("family_id") or "", {})
        path, path_source = _classification_path(glottocode, languoid, classification)

        flores_plus_codes = _match(aliases, flores_plus)
        bouquet_codes = _match(aliases, bouquet["codes"])
        nllb_codes = _match(aliases, nllb200)
        ntrex_codes = _match(aliases, ntrex)
        smol_subsets = sorted({s for alias in aliases for s in smol_index.get(alias, [])})
        sacrebleu_sets = sorted({s for alias in aliases for s in sacrebleu_index.get(alias, [])})
        tatoeba = next((tatoeba_index[a] for a in sorted(aliases) if a in tatoeba_index), None)
        google_codes = sorted(
            {c for c in google_target if _normalise(c) in aliases or _normalise(_script_base(c)) in aliases}
        )
        microsoft_codes = sorted(
            {c for c in microsoft if _normalise(c) in aliases or _normalise(_script_base(c)) in aliases}
        )
        madlad_codes = _match(aliases, madlad)
        glot500_codes = _match(aliases, glot500)
        hplt_codes = _match(aliases, hplt2)

        community_ids = sorted({
            benchmark
            for alias in aliases
            for benchmark in community_by_language.get(alias, [])
        })
        hub_entry = hub.get(config) or {}
        cover = coverage.get(config) or {}
        # FLORES+ and the Tatoeba MT benchmark will not serve their data files, so their
        # coverage comes from the authoritative listings already gathered and their sentence
        # counts from open mirrors. Neither is guessed.
        tatoeba_english = ((tatoeba or {}).get("english") or {})
        benchmark_overrides = {
            "openlanguagedata/flores_plus": {
                "covered": bool(flores_plus_codes),
                "codes": flores_plus_codes,
                "sentences": dict(
                    (hf_benchmarks.get("mteb/flores") or {}).get("per_language_rows") or {}
                ) if flores_plus_codes else {},
                "counts_measured_from": "mteb/flores",
                "coverage_established_from": "dev split file listing in the gated repository",
            },
            "Helsinki-NLP/tatoeba_mt": {
                "covered": bool((tatoeba or {}).get("test_pairs")),
                "sentences": {
                    k: v for k, v in (
                        ("test", tatoeba_english.get("test")),
                        ("dev", tatoeba_english.get("dev")),
                        ("train", tatoeba_english.get("train")),
                    ) if v
                },
                "counts_measured_from": "Tatoeba Challenge release tables",
                "coverage_established_from": "Tatoeba Challenge subset tables",
            },
            "facebook/bouquet": {
                "covered": bool(bouquet_codes),
                "codes": bouquet_codes,
                # Counts would require reading the gated data files; coverage comes from the
                # public file listing, which anyone can reproduce without credentials.
                "sentences": {},
                "coverage_established_from": "benchmark_data file listing in the gated repository",
            },
            "mteb/NTREX": {
                "covered": bool(ntrex_codes),
                "codes": ntrex_codes,
                "sentences": {"test": 1997} if ntrex_codes else {},
                "coverage_established_from": "NTREX LANGUAGES.tsv",
            },
        }
        bench = benchmark_table(aliases, hf_benchmarks, benchmark_overrides)

        smol_counts = {
            subset: data["smol"]["subset_sentences"].get(subset, {}).get(alias)
            for subset in ("smolsent", "smoldoc")
            for alias in aliases
            if data["smol"]["subset_sentences"].get(subset, {}).get(alias)
        }
        bench["google/smol"] = {
            "dataset": "google/smol",
            "url": "https://huggingface.co/datasets/google/smol",
            "role": "professional_parallel",
            "access": "open",
            "gated": False,
            "covered": bool(smol_subsets),
            "subsets": smol_subsets,
            "sentences": {"professional": sum(smol_counts.values())} if smol_counts else {},
            "sentences_by_subset": smol_counts,
            "counts_measured_from": "line counts of the repository's own JSONL files",
            "note": "Professionally translated sentences and documents for under-represented "
                    "languages, released as training data rather than a held-out test set. "
                    "GATITOS is a word-level lexicon and contributes no sentence count.",
        }
        # One curated benchmark may republish another's sentences for some languages --
        # NaLiBaSID's Bavarian set contains xSID's. The superseded entry stays listed as
        # covering the language, but contributes no sentence count, so the same sentences
        # are never added twice.
        superseded = set()
        for benchmark in community_ids:
            for target, languages in (community_detail[benchmark].get("supersedes") or {}).items():
                if any(_normalise(code) in aliases for code in languages):
                    superseded.add(target)

        for benchmark in community_ids:
            meta = community_detail[benchmark]
            def measure(field: str):
                per_language = meta.get(field) or {}
                return next(
                    (per_language[a] for a in sorted(aliases) if a in per_language), None
                )

            counts = {}
            if benchmark not in superseded:
                for split, field in (("test", "test_sentences_by_language"),
                                     ("dev", "dev_sentences_by_language")):
                    value = measure(field)
                    if value:
                        counts[split] = value
            bench[f"community/{benchmark}"] = {
                "sentences_superseded_by": sorted(
                    other for other in community_ids
                    if benchmark in (community_detail[other].get("supersedes") or {})
                    and benchmark in superseded
                ) or None,
                "dataset": benchmark,
                "url": meta["url"],
                "role": "evaluation",
                "access": "open",
                "gated": False,
                "covered": True,
                "sentences": counts,
                "counts_measured_from": meta.get("counts_measured_from"),
                "note": meta["note"],
            }
        covering = [k for k, v in bench.items() if v.get("covered")]
        # Held-out sentences from resources meant for evaluation. This is what a method can
        # actually be measured against.
        evaluation_sentences = sum(
            (v["sentences"].get("test") or 0) + (v["sentences"].get("dev") or 0)
            for v in bench.values()
            if v.get("covered") and v["role"].startswith("evaluation")
        )
        # Small, human-translated sets released as training data. Usable either way, but not
        # a held-out test set, so they are counted apart from the evaluation sentences.
        professional_sentences = sum(
            (v["sentences"].get("professional") or 0) + (
                (v["sentences"].get("train") or 0) if v["role"] == "training" else 0
            )
            for v in bench.values() if v.get("covered")
        )
        benchmark_train_sentences = sum(
            (v["sentences"].get("train") or 0)
            for v in bench.values() if v.get("covered")
        )

        opus_entry = opus.get(config) or {}
        partner_pairs = opus_entry.get("partner_languages") or {}
        opus_corpora = opus_entry.get("corpora") or {}
        ov = overlap.get(config) or {}
        excluding_en = ov.get("top_partners_excluding_en") or []

        rows.append({
            # identity
            "finewiki_config": config,
            "wiki_prefix": hyphen,
            "language_name": site.get("name") or stats.get("english_name") or codes["iso639_name"],
            "autonym": site.get("localname") or stats.get("local_name"),
            "script_direction": site.get("dir"),
            "iso639_1": codes["iso639_1"],
            "iso639_3": codes["iso639_3"],
            "iso639_scope": codes["iso639_scope"],
            "macrolanguage": codes["macrolanguage"],
            "code_note": codes["code_note"],
            "code_aliases": codes["code_aliases"],
            # A commercial system may list only the macrolanguage; that is disclosed here
            # rather than counted as support for this variety.
            "macrolanguage_has_commercial_mt": bool(macro_aliases) and bool(
                [c for c in google_target
                 if _normalise(c) in macro_aliases or _normalise(_script_base(c)) in macro_aliases]
                or [c for c in microsoft
                    if _normalise(c) in macro_aliases
                    or _normalise(_script_base(c)) in macro_aliases]
            ),
            # genealogy
            "glottocode": glottocode,
            "glottolog_name": languoid.get("name"),
            "family_id": languoid.get("family_id"),
            "family_name": family.get("name"),
            "macroarea": languoid.get("macroarea"),
            "is_isolate": bool(languoid.get("is_isolate")),
            "classification_path": path,
            "classification_depth": len(path),
            "classification_path_source": path_source,
            "glottolog_proxy_note": codes["glottolog_proxy_note"],
            # wikipedia size
            "finewiki_articles": size["articles"],
            "finewiki_bytes_parquet": size["bytes_parquet"],
            "wikipedia_articles_live": stats.get("articles"),
            "wikipedia_total_pages": stats.get("pages_total"),
            "wikipedia_edits": stats.get("edits"),
            "wikipedia_active_editors": stats.get("active_users"),
            "wikipedia_closed": site.get("wikipedia_closed"),
            # cross-language article overlap
            "unique_wikidata_items": ov.get("unique_wikidata_items"),
            "languages_sharing_any_article": ov.get("languages_sharing_any_item"),
            "shared_articles_with_en": ov.get("shared_with_en"),
            "top_partner_1": (excluding_en[0]["language"] if len(excluding_en) > 0 else None),
            "top_partner_1_shared_articles": (
                excluding_en[0]["shared_items"] if len(excluding_en) > 0 else None
            ),
            "top_partner_2": (excluding_en[1]["language"] if len(excluding_en) > 1 else None),
            "top_partner_2_shared_articles": (
                excluding_en[1]["shared_items"] if len(excluding_en) > 1 else None
            ),
            "article_overlap": {
                "unique_wikidata_items": ov.get("unique_wikidata_items"),
                "languages_sharing_any_article": ov.get("languages_sharing_any_item"),
                "shared_with_en": ov.get("shared_with_en"),
                "top_partners": ov.get("top_partners") or [],
                "top_partners_excluding_en": excluding_en,
            },
            # Greedy set cover: which partner Wikipedias, together, reach the most of this
            # language's articles. Large wikis overlap heavily with each other, so a
            # partner's solo overlap overstates it; only its marginal gain counts.
            "coverage_best_partner": cover.get("best_partner"),
            "coverage_best_partner_items": cover.get("best_partner_items"),
            "coverage_material_partners": cover.get("material_partners") or [],
            "coverage_material_partner_count": cover.get("material_partner_count"),
            "coverage_material_items": cover.get("material_items"),
            "coverage_material_share": cover.get("material_share"),
            "coverage_ceiling_items": cover.get("ceiling_items"),
            "coverage_ceiling_share": cover.get("ceiling_share"),
            "coverage_items_unique_to_this_wiki": cover.get("items_unique_to_this_wiki"),
            "article_coverage": {
                "method": data["coverage"]["method"],
                "own_items": cover.get("own_items"),
                "material_gain_share_threshold": data["coverage"]["material_gain_share"],
                "material_partners": cover.get("material_partners") or [],
                "greedy_selection": cover.get("greedy_selection") or [],
                "ceiling_items": cover.get("ceiling_items"),
                "items_unique_to_this_wiki": cover.get("items_unique_to_this_wiki"),
            },
            # machine-translation support
            "in_google_translate": bool(google_codes),
            "in_microsoft_translator": bool(microsoft_codes),
            "in_nllb200": bool(nllb_codes),
            "in_madlad400": bool(madlad_codes),
            # evaluation benchmarks
            "in_flores_plus": bool(flores_plus_codes),
            "in_ntrex": bool(ntrex_codes),
            "in_smol_smoldoc": "smoldoc" in smol_subsets,
            "in_smol_smolsent": "smolsent" in smol_subsets,
            "in_gatitos": "gatitos" in smol_subsets,
            "in_sacrebleu": bool(sacrebleu_sets),
            # Any pair with a held-out test split counts; for many small languages the
            # Tatoeba test set pairs them with a neighbour rather than with English.
            "tatoeba_has_test_set": bool((tatoeba or {}).get("test_pairs")),
            "tatoeba_test_pairs": (tatoeba or {}).get("test_pairs") or 0,
            "tatoeba_test_partners": (tatoeba or {}).get("test_partners") or [],
            # The tier is reported only for the English pair, where it is comparable.
            "tatoeba_tier": ((tatoeba or {}).get("english") or {}).get("tier"),
            "in_community_benchmark": bool(community_ids),
            "community_benchmarks": community_ids,
            # Broader benchmark inventory: where each one lives, whether it is reachable,
            # and how many sentences it holds for this language.
            "benchmarks_covering_count": len(covering),
            "benchmarks_covering": sorted(covering),
            "evaluation_sentences_available": evaluation_sentences,
            "professional_parallel_sentences": professional_sentences,
            "benchmark_train_sentences": benchmark_train_sentences,
            # Has anyone published a dataset for this language on the Hub?
            "hub_datasets": hub_entry.get("dataset_count"),
            "hub_translation_datasets": hub_entry.get("translation_dataset_count"),
            "hub_focused_translation_datasets": hub_entry.get("focused_translation_dataset_count"),
            # corpora
            "in_glot500": bool(glot500_codes),
            "in_hplt2": bool(hplt_codes),
            "opus_corpora_count": len(opus_corpora),
            "opus_partner_languages": len(partner_pairs),
            "opus_sentence_pairs_total": opus_entry.get("total_alignment_pairs") or 0,
            "opus_sentence_pairs_with_en": int(partner_pairs.get("en", 0)),
            # detail dictionaries
            "machine_translation": {
                "google_translate": {
                    "supported": bool(google_codes),
                    "codes": google_codes,
                    "source_side": sorted(
                        c for c in google_source
                        if _normalise(c) in aliases or _normalise(_script_base(c)) in aliases
                    ),
                },
                "microsoft_translator": {"supported": bool(microsoft_codes), "codes": microsoft_codes},
                "nllb_200": {"supported": bool(nllb_codes), "codes": nllb_codes},
                "madlad_400": {"supported": bool(madlad_codes), "codes": madlad_codes},
            },
            "evaluation_sets": {
                "flores_plus": {"available": bool(flores_plus_codes), "codes": flores_plus_codes},
                "ntrex_128": {"available": bool(ntrex_codes), "codes": ntrex_codes},
                "smol": {
                    "smoldoc": "smoldoc" in smol_subsets,
                    "smolsent": "smolsent" in smol_subsets,
                    "gatitos": "gatitos" in smol_subsets,
                },
                "sacrebleu": {"available": bool(sacrebleu_sets), "testsets": sacrebleu_sets},
                "tatoeba_challenge": tatoeba or {},
                "community": {
                    "available": bool(community_ids),
                    "benchmarks": [
                        {
                            "id": benchmark,
                            "name": community_detail[benchmark]["name"],
                            "url": community_detail[benchmark]["url"],
                            "has_test_split": community_detail[benchmark]["has_test_split"],
                            "pivot_languages": community_detail[benchmark]["pivot_languages"],
                        }
                        for benchmark in community_ids
                    ],
                },
            },
            "benchmarks": bench,
            "hub_presence": {
                "aliases_queried": hub_entry.get("aliases_queried") or [],
                "dataset_count": hub_entry.get("dataset_count"),
                "dataset_count_capped": hub_entry.get("dataset_count_capped_at_100_per_alias"),
                "translation_datasets": hub_entry.get("translation_datasets") or [],
                "focused_translation_datasets": hub_entry.get("focused_translation_datasets") or [],
                "query_errors": hub_entry.get("errors") or [],
            },
            "parallel_corpora": {
                "opus": {
                    "queried_code": config,
                    "corpora": dict(list(opus_corpora.items())[:25]),
                    "corpus_count": len(opus_corpora),
                    "partner_languages": dict(list(partner_pairs.items())[:25]),
                    "partner_language_count": len(partner_pairs),
                    "sentence_pairs_total": opus_entry.get("total_alignment_pairs") or 0,
                    "error": opus_entry.get("error"),
                },
                "glot500": {"available": bool(glot500_codes), "codes": glot500_codes},
                "hplt_v2": {"available": bool(hplt_codes), "codes": hplt_codes},
            },
        })
    return rows


# --------------------------------------------------------------------------- derived state


def add_derived(rows: list[dict], matrix: dict | None = None) -> dict:
    """Add anchor/pivot, tier and opportunity columns; return build-level statistics."""
    by_config = {row["finewiki_config"]: row for row in rows}
    articles = {c: (r["wikipedia_articles_live"] or r["finewiki_articles"]) for c, r in by_config.items()}

    anchors = {
        config
        for config, row in by_config.items()
        if row["in_google_translate"]
        and row["in_flores_plus"]
        and articles[config] >= ANCHOR_MIN_ARTICLES
    }

    def shared_articles(left: str, right: str, fallback: dict) -> int:
        """Exact shared-article count for a pair, or the truncated report's value."""
        if matrix and left in matrix["index"] and right in matrix["index"]:
            return int(matrix["shared"][matrix["index"][left]][matrix["index"][right]])
        return fallback.get(right, 0)

    for row in rows:
        config = row["finewiki_config"]
        row["is_high_resource_anchor"] = config in anchors

        # Genealogically closest anchor: the one sharing the longest Glottolog path prefix.
        path = row["classification_path"]
        best_relative, best_depth, best_shared = None, 0, 0
        overlap_counts = {
            entry["language"]: entry["shared_items"]
            for entry in row["article_overlap"]["top_partners"]
        }
        if path:
            for candidate in sorted(anchors):
                if candidate == config:
                    continue
                other = by_config[candidate]["classification_path"]
                depth = 0
                for left, right in zip(path, other):
                    if left != right:
                        break
                    depth += 1
                if depth == 0:
                    continue
                shared = shared_articles(config, candidate, overlap_counts)
                if (depth, shared) > (best_depth, best_shared):
                    best_relative, best_depth, best_shared = candidate, depth, shared
        row["closest_related_high_resource_language"] = best_relative
        row["closest_relative_shared_classification_nodes"] = best_depth or None
        row["closest_relative_shared_articles"] = best_shared if best_relative else None

        # Best practical pivot: the anchor sharing the most Wikipedia articles.
        pivot, pivot_shared = None, 0
        for candidate in sorted(anchors):
            if candidate == config:
                continue
            shared = shared_articles(config, candidate, overlap_counts)
            if shared > pivot_shared:
                pivot, pivot_shared = candidate, shared
        row["best_pivot_language"] = pivot
        row["best_pivot_shared_articles"] = pivot_shared or None

        # Held-out evaluation sets only. SMOL is professionally translated training data,
        # so it is tracked separately rather than counted as a test set.
        evidence = [
            row["in_flores_plus"], row["in_ntrex"],
            row["in_sacrebleu"], row["tatoeba_has_test_set"],
            row["in_community_benchmark"],
        ]
        has_eval = any(evidence)
        row["has_translation_test_set"] = has_eval
        row["translation_test_set_count"] = sum(evidence)
        # A focused Hub dataset is weaker evidence than a standard benchmark, but for some
        # languages it is the only place a test split exists at all.
        focused_hub = (row.get("hub_focused_translation_datasets") or 0) > 0
        row["has_focused_hub_translation_dataset"] = focused_hub
        professional = (row.get("professional_parallel_sentences") or 0) > 0
        row["has_professional_parallel_data"] = professional
        row["evaluation_evidence"] = (
            "benchmark_catalogue" if has_eval
            else "professional_parallel_only" if professional
            else "hub_dataset_only" if focused_hub
            else "none"
        )
        row["has_commercial_mt"] = row["in_google_translate"] or row["in_microsoft_translator"]
        row["has_parallel_corpus"] = row["opus_sentence_pairs_total"] > 0
        # Total public parallel training text. The more of this already exists, the less a
        # new mined corpus adds, so this is a penalty rather than a credit.
        row["training_sentences_public"] = (
            int(row["opus_sentence_pairs_total"] or 0)
            + int(row.get("benchmark_train_sentences") or 0)
            + int(row.get("professional_parallel_sentences") or 0)
        )
        # Measured on the FineWiki snapshot, because that is the corpus actually available
        # to mine, not the live wiki which may have grown since.
        row["meets_article_threshold"] = (
            MIN_ARTICLES_FOR_MINING <= row["finewiki_articles"] <= MAX_ARTICLES_FOR_MINING
        )
        row["articles_above_ceiling"] = (
            row["finewiki_articles"] > MAX_ARTICLES_FOR_MINING
        )
        row["training_data_saturated"] = (
            row["training_sentences_public"] > TRAINING_SATURATION_SENTENCES
        )

        if row["has_commercial_mt"] and has_eval and articles[config] >= 100_000:
            tier = "high"
        elif row["has_commercial_mt"] or row["in_nllb200"] or row["in_flores_plus"]:
            tier = "medium"
        elif has_eval or row["in_gatitos"] or row["opus_sentence_pairs_total"] >= 1000:
            tier = "low"
        else:
            tier = "very_low"
        row["resource_tier"] = tier

    # Opportunity score: a usable Wikipedia, a close well-resourced neighbour to mine
    # against, an existing test set to measure with, and little existing MT support.
    def log_scale(value, cap):
        return min(math.log10(1 + max(value or 0, 0)) / math.log10(1 + cap), 1.0)

    for row in rows:
        config = row["finewiki_config"]
        excluded = RANKING_EXCLUSIONS.get(config)
        row["excluded_from_ranking_reason"] = excluded
        wiki = log_scale(articles[config], 500_000)
        # The union reached by the material partner set, not the single best partner: for
        # most languages a second large wiki is pure redundancy and should not count twice.
        mineable = log_scale(row["coverage_material_items"], 200_000)
        relative = 1.0 if row["closest_relative_shared_classification_nodes"] else 0.0
        units = float(row["translation_test_set_count"] or 0)
        if units == 0 and row["has_focused_hub_translation_dataset"]:
            units = 0.5
        evaluation = min(units / 3.0, 1.0)
        # A small test set is enough to measure a method; a large one is not better here.
        if row["evaluation_sentences_available"] and evaluation < 1.0:
            evaluation = max(evaluation, 0.5)
        unmet = 0.0 if row["has_commercial_mt"] else 1.0
        scarcity = 1.0 - log_scale(row["training_sentences_public"], 5_000_000)
        in_article_band = 1.0 if row["meets_article_threshold"] else 0.0
        score = (
            0.20 * wiki
            + 0.18 * mineable
            + 0.08 * relative
            + 0.17 * evaluation
            + 0.15 * unmet
            + 0.18 * scarcity
            + 0.04 * in_article_band
        )
        row["opportunity_score"] = round(score, 4)
        row["opportunity_components"] = {
            "wikipedia_size": round(wiki, 4),
            "mineable_article_coverage": round(mineable, 4),
            "has_related_anchor": relative,
            "existing_test_sets": round(evaluation, 4),
            "no_commercial_mt": unmet,
            "training_data_scarcity": round(scarcity, 4),
            "meets_article_threshold": in_article_band,
        }

    ranked = sorted(
        (r for r in rows if not r["excluded_from_ranking_reason"]),
        key=lambda r: (-r["opportunity_score"], r["finewiki_config"]),
    )
    for position, row in enumerate(ranked, 1):
        row["opportunity_rank"] = position
    for row in rows:
        row.setdefault("opportunity_rank", None)

    by_size = sorted(rows, key=lambda r: -(articles[r["finewiki_config"]] or 0))
    for position, row in enumerate(by_size, 1):
        row["wikipedia_size_rank"] = position

    return {
        "high_resource_anchors": sorted(anchors),
        "high_resource_anchor_count": len(anchors),
        "anchor_definition": (
            "In Google Translate, present in FLORES-200 or FLORES+, and at least "
            f"{ANCHOR_MIN_ARTICLES:,} Wikipedia articles."
        ),
        "ranking_exclusions": RANKING_EXCLUSIONS,
    }


# ------------------------------------------------------------------------------- writing

FLAT_JSON_COLUMNS = {
    "article_overlap": "article_overlap_json",
    "machine_translation": "machine_translation_json",
    "evaluation_sets": "evaluation_sets_json",
    "parallel_corpora": "parallel_corpora_json",
    "opportunity_components": "opportunity_components_json",
    "hub_presence": "hub_presence_json",
    "benchmarks": "benchmarks_json",
    "article_coverage": "article_coverage_json",
}

LIST_COLUMNS = ("code_aliases", "classification_path", "community_benchmarks",
                "coverage_material_partners", "benchmarks_covering",
                "tatoeba_test_partners")

COLUMN_ORDER = [
    "finewiki_config", "wiki_prefix", "language_name", "autonym", "script_direction",
    "iso639_1", "iso639_3", "iso639_scope", "macrolanguage",
    "macrolanguage_has_commercial_mt", "code_note",
    "glottocode", "glottolog_name", "family_id", "family_name", "macroarea", "is_isolate",
    "classification_depth", "classification_path_source", "glottolog_proxy_note",
    "finewiki_articles", "wikipedia_articles_live", "wikipedia_total_pages",
    "wikipedia_edits", "wikipedia_active_editors", "wikipedia_closed",
    "finewiki_bytes_parquet", "wikipedia_size_rank",
    "unique_wikidata_items", "languages_sharing_any_article", "shared_articles_with_en",
    "top_partner_1", "top_partner_1_shared_articles",
    "top_partner_2", "top_partner_2_shared_articles",
    "coverage_best_partner", "coverage_best_partner_items",
    "coverage_material_partner_count", "coverage_material_items", "coverage_material_share",
    "coverage_ceiling_items", "coverage_ceiling_share",
    "coverage_items_unique_to_this_wiki",
    "best_pivot_language", "best_pivot_shared_articles",
    "closest_related_high_resource_language",
    "closest_relative_shared_classification_nodes", "closest_relative_shared_articles",
    "in_google_translate", "in_microsoft_translator", "in_nllb200", "in_madlad400",
    "in_flores_plus", "in_ntrex",
    "in_smol_smoldoc", "in_smol_smolsent", "in_gatitos",
    "in_sacrebleu", "tatoeba_has_test_set", "tatoeba_test_pairs", "tatoeba_tier",
    "tatoeba_test_partners",
    "in_community_benchmark",
    "benchmarks_covering_count", "evaluation_sentences_available",
    "professional_parallel_sentences", "benchmark_train_sentences",
    "training_sentences_public",
    "hub_datasets", "hub_translation_datasets", "hub_focused_translation_datasets",
    "in_glot500", "in_hplt2",
    "opus_corpora_count", "opus_partner_languages",
    "opus_sentence_pairs_total", "opus_sentence_pairs_with_en",
    "has_translation_test_set", "translation_test_set_count",
    "has_focused_hub_translation_dataset", "has_professional_parallel_data",
    "evaluation_evidence",
    "has_commercial_mt", "has_parallel_corpus", "meets_article_threshold",
    "articles_above_ceiling",
    "training_data_saturated",
    "is_high_resource_anchor", "resource_tier",
    "opportunity_score", "opportunity_rank", "excluded_from_ranking_reason",
    "code_aliases", "classification_path", "community_benchmarks",
    "coverage_material_partners", "benchmarks_covering",
    "article_overlap_json", "machine_translation_json", "evaluation_sets_json",
    "parallel_corpora_json", "hub_presence_json", "article_coverage_json",
    "benchmarks_json",
    "opportunity_components_json",
]


def flat_rows(rows: list[dict]) -> list[dict]:
    out = []
    for row in rows:
        flat = {k: v for k, v in row.items() if k not in FLAT_JSON_COLUMNS}
        for key, column in FLAT_JSON_COLUMNS.items():
            flat[column] = json.dumps(row[key], ensure_ascii=False, sort_keys=True)
        out.append({key: flat.get(key) for key in COLUMN_ORDER})
    return out


def arrow_schema():
    import pyarrow as pa

    string, boolean, int64, float64 = pa.string(), pa.bool_(), pa.int64(), pa.float64()
    types = {
        "is_isolate": boolean, "wikipedia_closed": boolean,
        "macrolanguage_has_commercial_mt": boolean,
        "in_google_translate": boolean, "in_microsoft_translator": boolean,
        "in_nllb200": boolean, "in_madlad400": boolean,
        "in_flores_plus": boolean, "in_ntrex": boolean,
        "in_smol_smoldoc": boolean, "in_smol_smolsent": boolean, "in_gatitos": boolean,
        "in_sacrebleu": boolean, "tatoeba_has_test_set": boolean,
        "tatoeba_test_pairs": int64,
        "tatoeba_test_partners": pa.list_(pa.string()),
        "in_community_benchmark": boolean,
        "benchmarks_covering_count": int64, "evaluation_sentences_available": int64,
        "professional_parallel_sentences": int64,
        "benchmark_train_sentences": int64, "training_sentences_public": int64,
        "meets_article_threshold": boolean, "articles_above_ceiling": boolean,
        "training_data_saturated": boolean,
        "hub_datasets": int64, "hub_translation_datasets": int64,
        "hub_focused_translation_datasets": int64,
        "in_glot500": boolean, "in_hplt2": boolean,
        "has_translation_test_set": boolean, "has_commercial_mt": boolean,
        "has_parallel_corpus": boolean, "is_high_resource_anchor": boolean,
        "has_focused_hub_translation_dataset": boolean,
        "has_professional_parallel_data": boolean,
        "classification_depth": int64, "finewiki_articles": int64,
        "wikipedia_articles_live": int64, "wikipedia_total_pages": int64,
        "wikipedia_edits": int64, "wikipedia_active_editors": int64,
        "finewiki_bytes_parquet": int64, "wikipedia_size_rank": int64,
        "unique_wikidata_items": int64, "languages_sharing_any_article": int64,
        "shared_articles_with_en": int64,
        "top_partner_1_shared_articles": int64, "top_partner_2_shared_articles": int64,
        "best_pivot_shared_articles": int64,
        "coverage_best_partner_items": int64, "coverage_material_partner_count": int64,
        "coverage_material_items": int64, "coverage_ceiling_items": int64,
        "coverage_items_unique_to_this_wiki": int64,
        "coverage_material_share": float64, "coverage_ceiling_share": float64,
        "closest_relative_shared_classification_nodes": int64,
        "closest_relative_shared_articles": int64,
        "opus_corpora_count": int64, "opus_partner_languages": int64,
        "opus_sentence_pairs_total": int64, "opus_sentence_pairs_with_en": int64,
        "translation_test_set_count": int64, "opportunity_rank": int64,
        "opportunity_score": float64,
        "code_aliases": pa.list_(string), "classification_path": pa.list_(string),
        "community_benchmarks": pa.list_(string),
        "coverage_material_partners": pa.list_(string),
        "benchmarks_covering": pa.list_(string),
    }
    return pa.schema([pa.field(name, types.get(name, string)) for name in COLUMN_ORDER])


def dataset_card(manifest: dict) -> str:
    counts = manifest["summary"]
    examples = manifest["worked_examples"]
    lines = [
        "---",
        "license: cc-by-4.0",
        "language_bcp47: []",
        "task_categories:",
        "- translation",
        "pretty_name: FineWiki translation-resource state per language",
        "size_categories:",
        "- n<1K",
        "tags:",
        "- machine-translation",
        "- low-resource",
        "- wikipedia",
        "- language-resources",
        "configs:",
        "- config_name: languages",
        "  default: true",
        "  data_files:",
        "  - split: audit",
        "    path: data/languages.parquet",
        "---",
        "",
        "# FineWiki translation-resource state per language",
        "",
        f"One row for each of the {counts['languages']} language configs in "
        "[HuggingFaceFW/finewiki](https://huggingface.co/datasets/HuggingFaceFW/finewiki), "
        "recording how large that Wikipedia is, which other Wikipedias it shares articles "
        "with, and which machine-translation systems, benchmarks and parallel corpora "
        "currently cover it.",
        "",
        "The table exists to answer one question: **which languages have enough Wikipedia "
        "text and a close enough well-resourced neighbour to build high-quality parallel "
        "data, while also having some existing test set to measure quality against?**",
        "",
        "## What is in the table",
        "",
        "| Group | Columns |",
        "|---|---|",
        "| Identity | `finewiki_config`, `wiki_prefix`, `language_name`, `autonym`, "
        "`iso639_1`, `iso639_3`, `macrolanguage`, `code_note` |",
        "| Genealogy | `glottocode`, `family_name`, `macroarea`, `is_isolate`, "
        "`classification_path` |",
        "| Wikipedia size | `finewiki_articles`, `wikipedia_articles_live`, "
        "`wikipedia_edits`, `wikipedia_active_editors`, `wikipedia_size_rank` |",
        "| Partner coverage (greedy set cover) | `coverage_best_partner`, "
        "`coverage_material_partners`, `coverage_material_partner_count`, "
        "`coverage_material_items`, `coverage_material_share`, `coverage_ceiling_share`, "
        "`coverage_items_unique_to_this_wiki` |",
        "| Cross-language articles | `shared_articles_with_en`, `top_partner_1`, "
        "`top_partner_1_shared_articles`, `top_partner_2`, `top_partner_2_shared_articles`, "
        "`best_pivot_language`, `closest_related_high_resource_language` |",
        "| MT support | `in_google_translate`, `in_microsoft_translator`, `in_nllb200`, "
        "`in_madlad400`, `has_commercial_mt` |",
        "| Test sets | `in_flores_plus`, `in_ntrex`, `in_smol_smoldoc`, "
        "`in_smol_smolsent`, `in_gatitos`, `in_sacrebleu`, `tatoeba_has_test_set`, "
        "`in_community_benchmark`, `has_translation_test_set`, "
        "`translation_test_set_count` |",
        "| Benchmark inventory | `benchmarks_covering`, `benchmarks_covering_count`, "
        "`test_sentences_available`, `benchmark_train_sentences` |",
        "| Existing parallel data | `training_sentences_public`, "
        "`training_data_saturated`, `opus_sentence_pairs_total`, "
        "`opus_sentence_pairs_with_en` |",
        "| Has anyone built anything | `hub_datasets`, `hub_translation_datasets`, "
        "`hub_focused_translation_datasets` |",
        "| Parallel data | `opus_corpora_count`, `opus_sentence_pairs_total`, "
        "`opus_sentence_pairs_with_en`, `in_glot500`, `in_hplt2` |",
        "| Derived state | `resource_tier`, `is_high_resource_anchor`, "
        "`opportunity_score`, `opportunity_rank` |",
        "| Detail dictionaries | `article_overlap_json`, `machine_translation_json`, "
        "`evaluation_sets_json`, `parallel_corpora_json`, `hub_presence_json`, "
        "`article_coverage_json`, `benchmarks_json`, `opportunity_components_json` |",
        "",
        "The eight `*_json` columns hold the per-source dictionaries as JSON strings so the "
        "Dataset Viewer stays flat and sortable. `languages.jsonl` in this repository carries "
        "the same rows with those fields as real nested objects.",
        "",
        "## Cross-language article overlap",
        "",
        "Every FineWiki row carries a `wikidata_id`. Two articles in different Wikipedias "
        "that share a Wikidata item describe the same concept, so the number of shared items "
        "bounds how many concept-aligned (comparable) article pairs a language pair can "
        f"supply. Counted over {manifest['overlap']['distinct_wikidata_items_total']:,} "
        f"distinct Wikidata items across {manifest['overlap']['configs_counted']} Wikipedias.",
        "",
        "`shared_articles_with_en` is the count against English; `top_partner_1` and "
        "`top_partner_2` are the two non-English Wikipedias that share the most articles "
        "with this one, with their counts. `article_overlap_json` holds the top ten both "
        "with and without English.",
        "",
        "## Which partners together cover the most",
        "",
        "A partner's solo overlap overstates its usefulness, because large Wikipedias "
        "overlap heavily with each other. For Gilaki, Spanish shares 32,928 articles but "
        "adds only 8 that English does not already cover, while Persian shares less than "
        "half as many and adds 134 on top of English and Mazandarani. So the columns report "
        "a **greedy maximum set cover**: at each rank, the partner that adds the most "
        "previously uncovered Wikidata items.",
        "",
        "`coverage_material_partners` is the sorted list of partners that each add more than "
        "one percent of the language's own article count -- the ones worth actually using. "
        "`coverage_material_items` is how many articles that set reaches together, and "
        "`coverage_ceiling_share` is what *all* audited Wikipedias reach combined. "
        "`coverage_items_unique_to_this_wiki` counts articles no other audited Wikipedia "
        "has at all, which no cross-lingual method can reach. The full ranked table, with "
        "each partner's marginal gain, is in `article_coverage_json`.",
        "",
        "## Benchmark inventory",
        "",
        "`benchmarks_json` lists every benchmark the audit checked, for this language: where "
        "it lives, whether it is reachable, its licence, and how many sentences it holds per "
        "split. Three of them will not serve their data files, so their coverage is taken "
        "from an authoritative listing and their sentence counts from an open mirror; each "
        "such entry records `coverage_established_from` and `counts_measured_from` rather "
        "than guessing.",
        "",
        "| Benchmark | Role | Access |",
        "|---|---|---|",
    ] + [
        f"| [{meta['id']}]({meta['url']}) | {meta['role'].replace('_', ' ')} | "
        f"{meta['declared_access'].replace('_', ' ')} |"
        for meta in sorted(
            manifest["benchmark_registry"].values(), key=lambda m: (m["role"], m["id"])
        )
    ] + [
        "",
        "`test_sentences_available` sums the test and dev sentences across every reachable "
        "benchmark; `training_sentences_public` sums public parallel *training* sentences "
        "(OPUS plus benchmark train splits) and is what the scarcity component penalises.",
        "",
        "## Resource tiers",
        "",
        "| Tier | Rule | Languages |",
        "|---|---|---|",
    ]
    for tier in ("high", "medium", "low", "very_low"):
        lines.append(
            f"| `{tier}` | {manifest['tier_rules'][tier]} | {counts['resource_tier'].get(tier, 0)} |"
        )
    lines += [
        "",
        "## Opportunity ranking",
        "",
        "`opportunity_score` combines a usable Wikipedia, a well-resourced neighbour with "
        "many shared articles, an existing test set, and the absence of commercial MT "
        "coverage. `opportunity_rank` is that score in descending order.",
        "",
        "| Component | Weight | Meaning |",
        "|---|---|---|",
        "| `wikipedia_size` | 0.28 | log-scaled article count |",
        "| `mineable_article_coverage` | 0.22 | log-scaled articles reachable from the "
        "material partner set |",
        "| `existing_test_sets` | 0.20 | how many public test sets cover the language; a focused Hub dataset alone counts as half of one |",
        "| `no_commercial_mt` | 0.12 | no Google or Microsoft support |",
        "| `parallel_data_scarcity` | 0.10 | inverse log-scaled OPUS sentence pairs |",
        "| `has_related_anchor` | 0.08 | shares a Glottolog family with an anchor |",
        "",
        f"{manifest['derived']['anchor_definition']} "
        f"{manifest['derived']['high_resource_anchor_count']} languages qualify as anchors.",
        "",
        "Simple English (`simple`) is excluded from the ranking because it is English.",
        "",
        f"`shortlist.json` applies the audit's own filter and keeps the "
        f"{manifest['shortlist_count']} languages that have at least 1,000 articles and at "
        "least one public test set -- or, failing that, a focused Hub translation dataset -- but no Google or Microsoft Translator support. `evaluation_evidence` says which of the two applies.",
        "",
        "## Worked examples",
        "",
        "| Language | Articles | Shared with `en` | Top non-English partners | Test sets | "
        "Commercial MT | Rank |",
        "|---|---|---|---|---|---|---|",
    ]
    for row in examples:
        partners = ", ".join(
            f"`{row[f'top_partner_{i}']}` {row[f'top_partner_{i}_shared_articles']:,}"
            for i in (1, 2)
            if row.get(f"top_partner_{i}")
        )
        lines.append(
            f"| {row['language_name']} (`{row['finewiki_config']}`) | "
            f"{row['finewiki_articles']:,} | {row['shared_articles_with_en']:,} | {partners} | "
            f"{row['translation_test_set_count']} | "
            f"{'yes' if row['has_commercial_mt'] else 'no'} | {row['opportunity_rank']} |"
        )
    lines += [
        "",
        "## Sources",
        "",
        "`sources/` holds the raw catalogue snapshot each column was derived from, one JSON "
        "file per source, each with its URL and fetch time. Those files are not part of the "
        "viewer config.",
        "",
        "| Source | What it contributes | Snapshot |",
        "|---|---|---|",
    ]
    for name, meta in sorted(manifest["sources"].items()):
        lines.append(
            f"| [{name}]({meta['url']}) | {meta['contributes']} | `sources/{name}.json` |"
        )
    lines += [
        "",
        "## Caveats",
        "",
        "- Alias expansion is one-way. A macrolanguage wiki such as `fa` claims resources "
        "published for its member varieties (`pes_Arab`), because that is the language it is "
        "written in; an individual language never inherits its macrolanguage's resources, "
        "because a Modern Standard Arabic test set does not evaluate Egyptian Arabic. Where "
        "a commercial system lists only the macrolanguage, "
        "`macrolanguage_has_commercial_mt` says so instead. For a macrolanguage wiki, "
        "counts are summed across its member varieties.",
        "- Catalogue membership is matched on language codes (ISO 639-1/639-3, "
        "macrolanguage members, script-suffixed FLORES codes). A language whose wiki uses a "
        "collective or retired prefix carries a `code_note`; `nah` has no usable "
        "three-letter code and therefore matches nothing.",
        "- Presence in a catalogue says nothing about quality. `in_google_translate` means "
        "the public endpoint lists the language, not that output is good.",
        "- OPUS figures were queried with the wiki prefix as the source code and are the "
        "latest version of each corpus; corpora under other code spellings may be missed.",
        "- FLORES+ membership comes from the gated "
        "`openlanguagedata/flores_plus` repository's `dev` split file list.",
        "- Coverage counts topics, not prose. A shared Wikidata item means both wikis have "
        "an article on it, not that either has enough text to align; the audit does not "
        "measure article length, so a stub and a full article count the same.",
        "- Shared Wikidata items measure comparable, not parallel, text. Wikipedia articles "
        "on the same topic are rarely translations of each other.",
        "- `hub_datasets` counts are capped at 100 per queried code, so a large number means "
        "\"many\", not an exact total. `hub_focused_translation_datasets` excludes umbrella "
        "corpora and any translation dataset whose card declares more than "
        f"{sources.FOCUSED_LANGUAGE_LIMIT} languages, because a release covering hundreds of "
        "languages is not evidence that anyone worked on one of them.",
        "- `in_community_benchmark` comes from `sources/community_benchmarks.json`, a curated "
        "list added only from first-hand inspection. It is deliberately incomplete: absence "
        "means the audit has not verified a resource, not that none exists.",
        "",
        "## Rebuilding",
        "",
        "```bash",
        "python scripts/lang_audit_sources.py      # snapshot every catalogue",
        "python scripts/lang_audit_overlap.py      # shared Wikidata items per language pair",
        "python scripts/lang_audit_build.py        # join into data/languages.parquet",
        "```",
        "",
        f"Schema version {manifest['schema_version']}; built {manifest['built_at']}.",
        "",
    ]
    return "\n".join(lines)


SOURCE_NOTES = {
    "finewiki": "Article and byte counts per language config.",
    "wikimedia_sitematrix": "English names, autonyms, text direction, wiki status.",
    "wikistats": "Live article counts, edits and active editors.",
    "iso639_3": "ISO 639-1/639-3 code reconciliation.",
    "iso639_macrolanguages": "Macrolanguage membership for code matching.",
    "glottolog_languages": "Glottocode, family, macroarea.",
    "glottolog_classification": "Root-to-leaf classification path, used for closest relatives.",
    "flores_plus": "FLORES+ language inventory.",
    "nllb200": "NLLB-200 supported language tokens.",
    "smol": "SMOLDOC, SMOLSENT and GATITOS language lists.",
    "ntrex": "NTREX-128 reference languages.",
    "sacrebleu": "WMT, IWSLT and other test sets with their language pairs.",
    "google_translate": "Languages the public Google Translate endpoint lists.",
    "microsoft_translator": "Languages the Microsoft Translator endpoint lists.",
    "madlad400": "MADLAD-400 language coverage.",
    "glot500": "Glot500-c corpus coverage.",
    "hplt2": "HPLT v2 cleaned web corpora coverage.",
    "tatoeba_challenge": "Training-size tiers and test-set availability per pair.",
    "community_benchmarks": "Curated parallel corpora the big catalogues do not list.",
    "hf_benchmarks": "Benchmark locations, access status and per-split sentence counts.",
    "opus": "Parallel corpora, partner languages and sentence-pair counts.",
    "hub_datasets": "Hugging Face Hub datasets tagged with the language.",
}


def write_release(rows: list[dict], derived: dict, data: dict, release_id: str) -> Path:
    import pyarrow as pa
    import pyarrow.parquet as pq

    output = DIST / release_id
    (output / "data").mkdir(parents=True, exist_ok=True)
    (output / "sources").mkdir(parents=True, exist_ok=True)

    flat = flat_rows(rows)
    table = pa.Table.from_pylist(flat, schema=arrow_schema())
    parquet_path = output / "data" / "languages.parquet"
    pq.write_table(table, parquet_path, compression="zstd")

    jsonl_path = output / "languages.jsonl"
    with jsonl_path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")

    source_files = {}
    for name in SOURCE_NOTES:
        payload = json.loads(sources.path_for(name).read_text(encoding="utf-8"))
        target = output / "sources" / f"{name}.json"
        target.write_text(
            json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
        )
        source_files[name] = {
            "url": payload["data"].get("url") or payload["data"].get("source") or "",
            "fetched_at": payload["fetched_at"],
            "contributes": SOURCE_NOTES[name],
            "sha256": _sha256(target),
        }
    overlap_target = output / "sources" / "finewiki_article_overlap.json"
    overlap_target.write_text(
        json.dumps(data["overlap"], ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )
    coverage_target = output / "sources" / "finewiki_article_coverage.json"
    coverage_target.write_text(
        json.dumps(data["coverage"], ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )

    # A ready-to-use candidate list for the audit's own purpose: a Wikipedia worth mining,
    # a related well-resourced neighbour, an existing test set, and no commercial MT.
    shortlist = [
        {
            key: row[key]
            for key in (
                "finewiki_config", "language_name", "iso639_3", "family_name",
                "finewiki_articles", "wikipedia_articles_live",
                "shared_articles_with_en",
                "top_partner_1", "top_partner_1_shared_articles",
                "top_partner_2", "top_partner_2_shared_articles",
                "coverage_best_partner", "coverage_best_partner_items",
                "coverage_material_partners", "coverage_material_partner_count",
                "coverage_material_items", "coverage_material_share",
                "coverage_ceiling_share", "coverage_items_unique_to_this_wiki",
                "best_pivot_language", "best_pivot_shared_articles",
                "closest_related_high_resource_language",
                "closest_relative_shared_articles",
                "translation_test_set_count", "evaluation_evidence",
                "benchmarks_covering", "benchmarks_covering_count",
                "evaluation_sentences_available", "professional_parallel_sentences",
                "training_sentences_public",
                "has_commercial_mt", "training_data_saturated", "in_flores_plus",
                "in_ntrex", "in_gatitos", "in_smol_smolsent", "tatoeba_has_test_set",
                "in_community_benchmark", "community_benchmarks",
                "hub_focused_translation_datasets",
                "opus_sentence_pairs_total", "resource_tier",
                "opportunity_score", "opportunity_rank",
            )
        }
        for row in sorted(
            (r for r in rows if r["opportunity_rank"]), key=lambda r: r["opportunity_rank"]
        )
        if not row["has_commercial_mt"]
        and row["evaluation_evidence"] != "none"
        and row["meets_article_threshold"]
        and not row["training_data_saturated"]
    ]
    shortlist_path = output / "shortlist.json"
    shortlist_path.write_text(
        json.dumps(
            {
                "description": (
                    f"FineWiki languages with between {MIN_ARTICLES_FOR_MINING:,} and "
                    f"{MAX_ARTICLES_FOR_MINING:,} articles and at least one reachable "
                    "translation test set, but no Google or Microsoft Translator support "
                    f"and no more than {TRAINING_SATURATION_SENTENCES:,} public parallel "
                    "training sentences, ordered by opportunity_rank."
                ),
                "count": len(shortlist),
                "languages": shortlist,
            },
            ensure_ascii=False, indent=1,
        ) + "\n",
        encoding="utf-8",
    )

    tier_counts: dict[str, int] = {}
    for row in rows:
        tier_counts[row["resource_tier"]] = tier_counts.get(row["resource_tier"], 0) + 1
    examples = [
        row for row in flat if row["finewiki_config"] in ("glk", "mzn", "bar")
    ]

    manifest = {
        "schema_version": SCHEMA_VERSION,
        "release_id": release_id,
        "built_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "summary": {
            "languages": len(rows),
            "finewiki_articles_total": sum(r["finewiki_articles"] for r in rows),
            "resource_tier": tier_counts,
            "with_translation_test_set": sum(1 for r in rows if r["has_translation_test_set"]),
            "with_commercial_mt": sum(1 for r in rows if r["has_commercial_mt"]),
            "with_any_parallel_corpus": sum(1 for r in rows if r["has_parallel_corpus"]),
            "in_flores_plus": sum(1 for r in rows if r["in_flores_plus"]),
            "in_google_translate": sum(1 for r in rows if r["in_google_translate"]),
        },
        "tier_rules": {
            "high": "Commercial MT, a public test set, and 100,000+ Wikipedia articles.",
            "medium": "Commercial MT, or in NLLB-200, or in FLORES+.",
            "low": "Some public test set, GATITOS, or 1,000+ OPUS sentence pairs.",
            "very_low": "None of the above; a Wikipedia and little else.",
        },
        "derived": derived,
        "benchmark_registry": {
            dataset: {
                "id": dataset,
                "url": record["url"],
                "role": record["role"],
                "declared_access": record["declared_access"],
                "gated": record.get("gated"),
                "license": record.get("license"),
                "coverage_mode": record["coverage_mode"],
                "config_count": record.get("config_count", 0),
                "card_language_count": len(record["card_languages"]),
                "note": record["note"],
                "errors": record["errors"],
            }
            for dataset, record in data["hf_benchmarks"]["benchmarks"].items()
        },
        "min_articles_for_mining": MIN_ARTICLES_FOR_MINING,
        "max_articles_for_mining": MAX_ARTICLES_FOR_MINING,
        "overlap": {
            "configs_counted": data["overlap"]["configs_counted"],
            "distinct_wikidata_items_total": data["overlap"]["distinct_wikidata_items_total"],
            "file_failures": data["overlap"]["file_failures"],
        },
        "sources": source_files,
        "worked_examples": examples,
        "shortlist_count": len(shortlist),
        "files": {
            "data/languages.parquet": _sha256(parquet_path),
            "languages.jsonl": _sha256(jsonl_path),
            "shortlist.json": _sha256(shortlist_path),
            "sources/finewiki_article_overlap.json": _sha256(overlap_target),
            "sources/finewiki_article_coverage.json": _sha256(coverage_target),
        },
        "columns": COLUMN_ORDER,
    }
    (output / "manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )
    (output / "README.md").write_text(dataset_card(manifest), encoding="utf-8")
    return output


def build(release_id: str | None = None) -> Path:
    data = load_all()
    rows = build_rows(data)
    derived = add_derived(rows, matrix=data.get("overlap_matrix"))
    release_id = release_id or datetime.now(timezone.utc).strftime("finewiki_audit_%Y%m%dT%H%M%SZ")
    output = write_release(rows, derived, data, release_id)
    print(f"languages: {len(rows)}")
    print(f"release:   {output}")
    return output


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release-id", default=None)
    args = parser.parse_args(argv)
    build(args.release_id)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())