File size: 74,248 Bytes
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
aaee816
5317ec3
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
c1665a6
5f12097
e89ef02
 
 
 
 
 
 
 
 
 
 
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1665a6
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
aaee816
 
 
e89ef02
 
 
 
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
aaee816
 
 
e89ef02
 
 
 
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
aaee816
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
e89ef02
5317ec3
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1665a6
 
 
 
e89ef02
 
c1665a6
 
 
e89ef02
 
c1665a6
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
c1665a6
e89ef02
 
c1665a6
e89ef02
 
c1665a6
e89ef02
c1665a6
 
 
e89ef02
c1665a6
 
e89ef02
 
 
 
 
 
c1665a6
 
 
 
 
e89ef02
c1665a6
 
 
 
e89ef02
c1665a6
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1665a6
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1665a6
e89ef02
 
 
 
 
 
 
 
5317ec3
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
e89ef02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f12097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaee816
 
 
 
 
 
 
 
e89ef02
 
 
 
 
5317ec3
e89ef02
5f12097
aaee816
 
 
e89ef02
 
 
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5317ec3
 
 
 
aaee816
5317ec3
 
 
 
aaee816
 
 
5317ec3
 
 
 
 
 
 
 
 
aaee816
5317ec3
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89ef02
 
 
 
 
 
 
 
5317ec3
5f12097
e89ef02
aaee816
 
 
 
e89ef02
 
aaee816
 
 
 
 
5317ec3
 
 
 
 
 
 
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
"""Gather every human-created translation test set for the audit's shortlist languages.

One JSONL file per language in Google SMOL's ``smolsent`` shape, so that an existing SMOL
reader works unchanged:

    {"sl": "en", "tl": "glk", "id": 0, "src": "...", "trg": "...", "is_src_orig": true}

with provenance fields added, because a record that cannot be traced back to its source and
licence is not usable evidence.

Only human-produced data is collected. Automatically mined or word-aligned material --
WikiMatrix, XLEnt, the projected training files shipped alongside xSID -- belongs in the
baseline training corpus, not in a test set.

Sources, each pinned to a revision and counted from the files themselves:

* Tatoeba Challenge   ``data/test/<pair>/test.txt``, open, CC-BY-2.0-FR
* NTREX               line-aligned references against the English source, open, CC-BY-SA-4.0
* xSID 0.6            manual translations of English voice-assistant utterances, CC-BY-SA-4.0
* NaLiBaSID           extends xSID for Bavarian with MASSIVE translations, CC-BY-SA-4.0
* PARME               English-Persian-X sentences for Middle Eastern languages, MIT
* SMOL (smolsent)     professionally translated sentences, CC-BY-4.0

FLORES+ is deliberately *not* redistributed. Its access terms require agreeing "not to
re-host FLORES+ in places where it could be picked up by web crawlers", and a public dataset
repository is exactly such a place. Languages whose only test set is FLORES+ get
reference-only records: the language, split and row count, with the text withheld and a
pointer to the upstream repository. Keeping the rows makes the gap visible instead of making
those languages silently look untested.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
import re
import sys
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ElementTree
import zipfile
from collections import Counter
from pathlib import Path

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

import shortlist_pivots as pivots  # noqa: E402
from corpus_subsets import subset_name, write_subsets  # noqa: E402

CACHE = ROOT / "cache" / "eval_corpus"
DIST = ROOT / "dist" / "eval_corpus"
USER_AGENT = "gilaki-eval-corpus/1.0 (+research use)"

TATOEBA_REVISION = "bd05f087e91e359a88594bd6d6c99a079e0ac621"
XSID_REVISION = "761d926c3f2e9f6bea13192d2f39cec1d04d9777"
NALIBASID_REVISION = "8d66b9021c06df1ab459636a925e119b2cff20fe"
NTREX_REVISION = "468c6b69c7f6a75d31d4743d9daba2af566cc18d"
PARME_REVISION = "6df9269acc75377ed6be3bf2f7966c8e238a62bd"
CODET_REVISION = "main"
DOLMA_BITEXT_REVISION = "main"
MAIBAAM_REVISION = "master"
UD_MEGRELIAN_REVISION = "dev"
NUSAX_REVISION = "main"
SHUD_REVISION = "master"
GIL1000_REVISION = "master"

# How freely a source may be passed on. The distinction is not cosmetic: a third of the
# resources found for these languages carry no licence at all, and several of the best ones
# are explicitly non-commercial or no-derivatives. Publishing them all under one licence
# field would misrepresent every tier but the first.
#
#   1  redistributable: a licence that permits republishing the text.
#   2  restricted: republishable only under a condition that limits reuse (non-commercial).
#   3  reference only: no licence stated, no-derivatives, or an explicit request not to
#      redistribute. Ids and counts are published; the text is withheld.
TIER_REDISTRIBUTABLE, TIER_RESTRICTED, TIER_REFERENCE = 1, 2, 3

SOURCE_META = {
    "tatoeba_challenge": {
        "url": "https://github.com/Helsinki-NLP/Tatoeba-Challenge",
        "revision": TATOEBA_REVISION, "licence": "CC-BY-2.0-FR",
        "domain": "crowd_sentences",
        "note": "Crowd-contributed sentences from Tatoeba, held out as the Challenge test split.",
    },
    "ntrex": {
        "url": "https://github.com/MicrosoftTranslator/NTREX",
        "revision": NTREX_REVISION, "licence": "CC-BY-SA-4.0", "domain": "news",
        "note": "NTREX-128 news references, professionally translated out of English. The "
                "Swiss German references live in NTREX-additional and are absent from the "
                "mteb/NTREX mirror.",
    },
    "xsid": {
        "url": "https://github.com/mainlp/xsid",
        "revision": XSID_REVISION, "licence": "CC-BY-SA-4.0", "domain": "voice_assistant",
        "note": "Manual translations of the same English digital-assistant utterances into "
                "each language. Short imperative commands, not general prose.",
    },
    "nalibasid": {
        "url": "https://github.com/mainlp/NaLiBaSID",
        "revision": NALIBASID_REVISION, "licence": "CC-BY-SA-4.0", "domain": "voice_assistant",
        "note": "Extends xSID for Bavarian with manual translations of part of MASSIVE. The "
                "xMAS files are the de-duplicated union of both, so they are read instead of "
                "the parts to avoid counting the same sentence twice.",
    },
    "parme": {
        "url": "https://github.com/DOLMA-NLP/PARME",
        "revision": PARME_REVISION, "licence": "MIT", "domain": "mixed",
        "note": "Human English-Persian-X sentences for under-represented Middle Eastern "
                "languages, with official held-out test and validation splits.",
    },
    "smol": {
        "url": "https://huggingface.co/datasets/google/smol",
        "revision": "main", "licence": "CC-BY-4.0", "domain": "mixed",
        "note": "Professionally translated sentences. Released by Google as training data; "
                "collected here as evaluation material by explicit choice, so scores on it "
                "are not comparable with systems that trained on it.",
    },
    "flores_plus": {
        "url": "https://huggingface.co/datasets/openlanguagedata/flores_plus",
        "revision": "main", "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
        "note": "Text withheld. Access requires agreeing not to re-host FLORES+ where web "
                "crawlers could reach it, which a public dataset repository would do. Fetch "
                "it from the upstream repository after accepting its terms.",
        "tier": TIER_REFERENCE,
        "restriction": "Terms forbid re-hosting where web crawlers could reach it.",
    },
    "bouquet": {
        "url": "https://huggingface.co/datasets/facebook/bouquet",
        "revision": "main", "licence": "CC-BY-4.0", "domain": "mixed",
        "note": "Human-authored sentences and paragraphs, written in the source language "
                "rather than translated from English, with official dev and test splits. "
                "Carries paragraph ids, so it is the only source here with recoverable "
                "document structure. Released for evaluation, not training.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "codet": {
        "url": "https://github.com/mahfuzibnalam/dialect_mt",
        "revision": CODET_REVISION, "licence": "MIT", "domain": "elicited_syntax",
        "note": "Italian Syntactic Atlas sentences elicited from speakers in 439 localities, "
                "each file positionally aligned to the same 792 standard Italian sentences. "
                "Sparsely filled, so a locality contributes only the lines it answered.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "dolma_bitext": {
        "url": "https://github.com/DOLMA-NLP/bitext-mining",
        "revision": DOLMA_BITEXT_REVISION, "licence": "CC-BY-4.0", "domain": "mixed",
        "note": "Manually aligned sentence pairs from published translations, by the group "
                "behind PARME. The licence adds one term: the data must not be used to "
                "reconstruct the original literary works, which sentence-level use satisfies.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "nllb_seed": {
        "url": "https://github.com/facebookresearch/flores/tree/main/nllb_seed",
        "revision": "main", "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
        "note": "Professionally translated seed sentences. A separate artefact from the "
                "NLLB-200 mined bitext that the baseline corpus classifies as auto_mined.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "nusax": {
        "url": "https://github.com/IndoNLP/nusax",
        "revision": NUSAX_REVISION, "licence": "CC-BY-SA-4.0", "domain": "mixed",
        "note": "Twelve-way parallel sentences for Indonesian local languages, translated by "
                "native speakers, with official train/valid/test splits.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "maibaam": {
        "url": "https://github.com/UniversalDependencies/UD_Bavarian-MaiBaam",
        "revision": MAIBAAM_REVISION, "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
        "note": "English sentence translations carried as '# text_en' comments on part of "
                "the Bavarian treebank. Only 59 of 1,070 sentences have one.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "ud_shanghainese": {
        "url": "https://github.com/UniversalDependencies/UD_Shanghainese-ShUD",
        "revision": "master", "licence": "CC-BY-SA-4.0", "domain": "spoken",
        "note": "Mandarin translations carried as '# text_cmn' on the Shanghainese treebank, "
                "with official train/dev/test splits. The only Wu-Mandarin sentence "
                "alignment found with splits; UD files Wu under 'Shanghainese'.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "ud_megrelian": {
        "url": "https://github.com/UniversalDependencies/UD_Megrelian-MLC",
        "revision": UD_MEGRELIAN_REVISION, "licence": "CC-BY-SA-4.0", "domain": "mixed",
        "note": "English translations carried as '# text_en' on the Megrelian treebank. Only "
                "on the dev branch; the dependency columns are empty for every token, so it "
                "is a translated morphology set rather than a usable treebank.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "nsanku": {
        "url": "https://github.com/GhanaNLP/nsanku",
        "revision": "main", "licence": "none stated", "domain": "religious",
        "note": "Human Dagbani-English reference pairs used as the evaluation set of Ghana "
                "NLP's 43-language study. Text withheld: the repository ships no licence and "
                "the underlying Bible translation is a Bible society copyright.",
        "tier": TIER_REFERENCE,
        "restriction": "No licence file in the repository; underlying text is copyrighted.",
    },
    "betthupferl": {
        "url": "https://github.com/mainlp/betthupferl",
        "revision": "main", "licence": "none stated", "domain": "narrative",
        "note": "Human-transcribed and human-standardised Bavarian, Swabian and East "
                "Franconian against Standard German. Text withheld: the archives are "
                "password-protected and the authors ask that the data not be redistributed.",
        "tier": TIER_REFERENCE,
        "restriction": "Authors explicitly request no redistribution.",
    },
    "ladin_frontull": {
        "url": "https://huggingface.co/sfrontull",
        "revision": "main", "licence": "CC-BY-NC-SA-4.0", "domain": "mixed",
        "note": "Italian-Ladin and intra-Ladin corpora. Non-commercial, so usable for "
                "evaluation but not in a commercial system.",
        "tier": TIER_RESTRICTED,
        "restriction": "Non-commercial use only.",
    },
    "glotstorybook": {
        "url": "https://huggingface.co/datasets/cis-lmu/GlotStoryBook",
        "revision": "main", "licence": "CC-BY", "domain": "narrative",
        "note": "African Storybook texts translated by named community translators, aligned "
                "to English through each story's parallel id. Licensing is per row, so only "
                "the plain CC-BY stories are taken.",
        "tier": TIER_REDISTRIBUTABLE,
    },
    "gil1000": {
        "url": "https://github.com/LordArma/Top-1000-Words-in-Gilaki",
        "revision": GIL1000_REVISION, "licence": "GPL-3.0",
        "domain": "dictionary_examples",
        "note": "Example sentences from the Top 1000 Words in Gilaki project, also published "
                "at https://gil1000.ir/. Each entry is written in Gilaki first and then "
                "rendered in Persian and English, so the Gilaki side is the original. "
                "Dictionary examples rather than running text, and the same sentences appear "
                "in the lexicon corpus, so a score here is not comparable with a general "
                "benchmark and is not independent of that corpus.",
        "tier": TIER_RESTRICTED,
        "restriction": "GPL-3.0: derived distributions inherit copyleft terms.",
    },
    "mlc": {
        "url": "https://xmf.iliauni.edu.ge/",
        "revision": "v1 (fieldwork 2022-2024)", "licence": "CC-BY-NC-SA-4.0",
        "domain": "spoken",
        "note": "Megrelian Language Corpus: oral texts recorded in Samegrelo and transcribed "
                "in Georgian script, each phrase glossed into both Georgian and English. The "
                "only source that pairs Megrelian with Georgian, its closest high-resource "
                "relative, in any quantity. Cite Gersamia, R. and Lobzhanidze, I. (eds.), "
                "Megrelian Language Corpus, Ilia State University.",
        "tier": TIER_RESTRICTED,
        "restriction": "Non-commercial use only, and derivatives inherit share-alike terms.",
    },
    "ladin_weather": {
        "url": "https://huggingface.co/datasets/sfrontull/south-tyrol-weather-lld-deu",
        "revision": "main", "licence": "CC-BY-SA-4.0", "domain": "weather",
        "note": "South Tyrol meteorological office bulletins in Ladin and German, with an "
                "official test split. The only Ladin set paired with German rather than "
                "Italian.",
        "tier": TIER_REDISTRIBUTABLE,
    },
}

for _name, _meta in SOURCE_META.items():
    _meta.setdefault("tier", TIER_REDISTRIBUTABLE)
    _meta.setdefault("restriction", None)

# xSID ships automatically word-aligned projections next to the human translations; they are
# training material and must never enter a test set.
XSID_EXCLUDED = ("projectedTrain",)


# ------------------------------------------------------------------------------- fetching


def _get(url: str, *, auth: bool = False, timeout: int = 180) -> bytes:
    headers = {"User-Agent": USER_AGENT}
    if auth:
        from hf_publishing_auth import publishing_token

        headers["Authorization"] = f"Bearer {publishing_token()}"
    request = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return response.read()


def fetch(url: str, *, auth: bool = False, attempts: int = 4) -> bytes | None:
    """Download with a local cache; ``None`` when the file genuinely does not exist."""
    key = hashlib.sha256(url.encode()).hexdigest()[:24]
    path = CACHE / "raw" / key
    marker = CACHE / "raw" / f"{key}.missing"
    if path.exists():
        return path.read_bytes()
    if marker.exists():
        return None
    path.parent.mkdir(parents=True, exist_ok=True)
    delay = 2.0
    for attempt in range(attempts):
        try:
            payload = _get(url, auth=auth)
        except urllib.error.HTTPError as error:
            if error.code in (401, 403, 404):
                marker.write_text(f"{error.code} {error.reason}\n{url}\n", encoding="utf-8")
                return None
            if attempt == attempts - 1:
                raise
        except Exception:
            if attempt == attempts - 1:
                raise
        else:
            path.write_bytes(payload)
            return payload
        time.sleep(delay)
        delay *= 2
    return None


# ------------------------------------------------------------------------------- parsing


def _clean(text: str) -> str:
    # Collapses runs of whitespace only. ZWNJ (U+200C) is a format character, not
    # whitespace, so Persian and Gilaki word-internal joins survive.
    return re.sub(r"\s+", " ", (text or "").strip())


def norm_key(text: str) -> str:
    """Comparison key for de-duplication: case and punctuation-spacing insensitive."""
    folded = unicodedata.normalize("NFKC", (text or "")).casefold()
    return re.sub(r"[^\w]+", "", folded, flags=re.UNICODE)


def parse_conll_sentences(text: str) -> list[dict]:
    """Sentence records from an xSID or NaLiBaSID conll file.

    The two projects use different separators for the same comment keys -- xSID writes
    ``# text = x`` and NaLiBaSID writes ``# text: x`` -- so both are accepted.
    """
    out = []
    current: dict[str, str] = {}
    for line in text.splitlines():
        if line.startswith("#"):
            body = line[1:].strip()
            match = re.match(r"([A-Za-z0-9_\-]+)\s*[:=]\s*(.*)$", body)
            if match:
                current[match.group(1).strip().lower()] = match.group(2).strip()
            continue
        if not line.strip():
            if current:
                out.append(current)
                current = {}
    if current:
        out.append(current)
    return [record for record in out if record.get("text")]


def parse_tatoeba_test(text: str) -> list[dict]:
    """Rows of a Tatoeba Challenge ``test.txt``: srclang, trglang, source, target."""
    rows = []
    for line in text.splitlines():
        if not line.strip():
            continue
        parts = line.split("\t")
        if len(parts) < 4:
            continue
        rows.append({
            "src_lang": parts[0].strip(),
            "trg_lang": parts[1].strip(),
            "src": parts[2],
            "trg": parts[3],
        })
    return rows


def parse_parme(text: str) -> list[dict]:
    """Rows of a PARME ``datasets/<LANG>-{test,val}.tsv``."""
    reader = csv.DictReader(io.StringIO(text), delimiter="\t")
    rows = []
    for row in reader:
        target = (row.get("translation") or "").strip()
        if not target:
            continue
        rows.append({
            "en": (row.get("en_sentence") or "").strip(),
            "fa": (row.get("fa_sentence") or "").strip(),
            "trg": target,
            "variety": (row.get("variety (Western Gilaki|Eastern Gilaki)")
                        or row.get("variety") or "").strip() or None,
        })
    return rows


# ------------------------------------------------------------------------------- records


def make_record(*, pivot_config, target_config, src, trg, source, split,
                is_src_orig=None, extra=None):
    meta = SOURCE_META[source]
    record = {
        # SMOL smolsent keys, in SMOL's own order.
        "sl": pivot_config,
        "tl": target_config,
        "id": None,            # assigned once the language's records are ordered
        "src": _clean(src),
        "trg": _clean(trg),
    }
    if is_src_orig is not None:
        record["is_src_orig"] = is_src_orig
    record.update({
        "split": split,
        "source": source,
        "source_revision": meta["revision"],
        "licence": meta["licence"],
        "domain": meta["domain"],
        "licence_tier": meta["tier"],
        "licence_restriction": meta["restriction"],
    })
    if extra:
        record.update(extra)
    if meta["tier"] == TIER_REFERENCE:
        # Counted and attributable, but the text itself is not ours to pass on.
        record["src"], record["trg"] = "", ""
        record["text_withheld"] = True
    return record


# ------------------------------------------------------------------------------ collectors


def collect_tatoeba(targets, rows, iso2cfg, pairs):
    """Tatoeba Challenge test splits for every acceptable pair of each target."""
    out, skipped = [], []
    for config in targets:
        iso = rows[config]["iso639_3"]
        if not iso:
            continue
        for pair in pairs:
            left, _, right = pair.partition("-")
            if iso not in (left, right):
                continue
            other = right if left == iso else left
            if other == iso:
                continue  # same-language pair, not a translation direction
            pivot_config = iso2cfg.get(other) or other
            ok, _reason = pivots.acceptable_pivot(config, pivot_config, rows)
            if not ok:
                skipped.append({"target": config, "pair": pair, "reason": "pivot not acceptable"})
                continue
            url = ("https://raw.githubusercontent.com/Helsinki-NLP/Tatoeba-Challenge/"
                   f"{TATOEBA_REVISION}/data/test/{pair}/test.txt")
            payload = fetch(url)
            if not payload:
                skipped.append({"target": config, "pair": pair, "reason": "test.txt not fetchable"})
                continue
            for row in parse_tatoeba_test(payload.decode("utf-8", "replace")):
                # Columns are (src_lang, trg_lang, src, trg); orient so the target language
                # is always on the target side.
                if row["trg_lang"].split("_")[0] == iso:
                    src, trg = row["src"], row["trg"]
                elif row["src_lang"].split("_")[0] == iso:
                    src, trg = row["trg"], row["src"]
                else:
                    continue
                if not src.strip() or not trg.strip():
                    continue
                out.append(make_record(
                    pivot_config=pivot_config, target_config=config, src=src, trg=trg,
                    source="tatoeba_challenge", split="test",
                    extra={"source_pair": pair},
                ))
    return out, skipped


def collect_ntrex(targets, rows):
    """NTREX references, line-aligned against the English source."""
    base = f"https://raw.githubusercontent.com/MicrosoftTranslator/NTREX/{NTREX_REVISION}"
    english = fetch(f"{base}/NTREX-128/newstest2019-src.eng.txt")
    if not english:
        return [], [{"reason": "NTREX English source not fetchable"}]
    source_lines = english.decode("utf-8", "replace").splitlines()
    out, skipped = [], []
    for config in targets:
        iso = rows[config]["iso639_3"]
        if not iso or not rows[config]["in_ntrex"]:
            continue
        candidates = [f"NTREX-128/newstest2019-ref.{iso}.txt"]
        # Some varieties are only in NTREX-additional, under a region-tagged name.
        candidates += [f"NTREX-additional/newstest2019-ref.{iso}-{region}.txt"
                       for region in ("BE", "ZH", "CH", "AT")]
        found = False
        for relative in candidates:
            payload = fetch(f"{base}/{relative}")
            if not payload:
                continue
            found = True
            variant = relative.rsplit("/", 1)[-1].removeprefix("newstest2019-ref.").removesuffix(".txt")
            target_lines = payload.decode("utf-8", "replace").splitlines()
            if len(target_lines) != len(source_lines):
                skipped.append({"target": config, "file": relative,
                                "reason": f"line count {len(target_lines)} != "
                                          f"English {len(source_lines)}"})
                continue
            for src, trg in zip(source_lines, target_lines):
                if not src.strip() or not trg.strip():
                    continue
                out.append(make_record(
                    pivot_config="en", target_config=config, src=src, trg=trg,
                    source="ntrex", split="test", is_src_orig=True,
                    extra={"variety": variant},
                ))
        if not found:
            skipped.append({"target": config, "reason": "no NTREX reference file found"})
    return out, skipped


def _sid_records(text, target_config, source, split, pivot_keys):
    """Shared xSID/NaLiBaSID record extraction. ``pivot_keys`` maps comment key -> pivot."""
    out = []
    for record in parse_conll_sentences(text):
        target = record.get("text")
        if not target:
            continue
        for key, pivot_config in pivot_keys.items():
            src = record.get(key)
            if not src:
                continue
            out.append(make_record(
                pivot_config=pivot_config, target_config=target_config, src=src, trg=target,
                source=source, split=split, is_src_orig=(pivot_config == "en"),

            ))
    return out


def collect_xsid(rows):
    """xSID 0.6 human translations for the varieties that map onto shortlist wikis."""
    base = f"https://raw.githubusercontent.com/mainlp/xsid/{XSID_REVISION}/data/xSID-0.6"
    # xSID's own language labels -> FineWiki config. de-st (South Tyrolean) has no wiki.
    mapping = {"de-ba": "bar", "gsw": "als", "nap": "nap"}
    out, skipped = [], []
    for label, config in mapping.items():
        if config not in rows:
            continue
        for upstream_split, split in (("test", "test"), ("valid", "dev")):
            name = f"{label}.{upstream_split}.conll"
            if any(token in name for token in XSID_EXCLUDED):
                continue
            payload = fetch(f"{base}/{name}")
            if not payload:
                skipped.append({"target": config, "file": name, "reason": "not fetchable"})
                continue
            out += _sid_records(
                payload.decode("utf-8", "replace"), config, "xsid", split,
                {"text-en": "en", "text-de": "de"},
            )
    return out, skipped


def collect_nalibasid(rows):
    """NaLiBaSID Bavarian translations, read from the de-duplicated xMAS union."""
    base = (f"https://raw.githubusercontent.com/mainlp/NaLiBaSID/{NALIBASID_REVISION}/data")
    out, skipped = [], []
    if "bar" not in rows:
        return out, skipped
    for upstream_split, split in (("test", "test"), ("valid", "dev")):
        name = f"de-ba.xMAS.{upstream_split}.conll"
        payload = fetch(f"{base}/{name}")
        if not payload:
            skipped.append({"target": "bar", "file": name, "reason": "not fetchable"})
            continue
        out += _sid_records(
            payload.decode("utf-8", "replace"), "bar", "nalibasid", split, {"text-en": "en"},
        )
    # de-ba.nat is speaker-produced with no English source, so it is not parallel data.
    return out, skipped


def collect_parme(rows):
    """PARME test and validation splits, which carry both English and Persian sources."""
    base = f"https://raw.githubusercontent.com/DOLMA-NLP/PARME/{PARME_REVISION}/datasets"
    mapping = {"GLK": "glk", "MZN": "mzn"}
    out, skipped = [], []
    for label, config in mapping.items():
        if config not in rows:
            continue
        for upstream_split, split in (("test", "test"), ("val", "dev")):
            payload = fetch(f"{base}/{label}-{upstream_split}.tsv")
            if not payload:
                skipped.append({"target": config, "file": f"{label}-{upstream_split}.tsv",
                                "reason": "not fetchable"})
                continue
            for row in parse_parme(payload.decode("utf-8", "replace")):
                for pivot_config, src in (("en", row["en"]), ("fa", row["fa"])):
                    if not src:
                        continue
                    ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
                    if not ok:
                        continue
                    out.append(make_record(
                        pivot_config=pivot_config, target_config=config, src=src,
                        trg=row["trg"], source="parme", split=split,
                        extra={"variety": row["variety"]},
                    ))
    return out, skipped


def collect_smol(targets, rows):
    """SMOL smolsent, already in the output shape."""
    out, skipped = [], []
    for config in targets:
        if not rows[config]["in_smol_smolsent"]:
            continue
        iso = rows[config]["iso639_3"]
        payload = fetch(
            f"https://huggingface.co/datasets/google/smol/resolve/main/smolsent/en_{iso}.jsonl"
        )
        if not payload:
            skipped.append({"target": config, "reason": f"smolsent/en_{iso}.jsonl not fetchable"})
            continue
        for line in payload.decode("utf-8", "replace").splitlines():
            if not line.strip():
                continue
            row = json.loads(line)
            if not row.get("src") or not row.get("trg"):
                continue
            out.append(make_record(
                pivot_config="en", target_config=config, src=row["src"], trg=row["trg"],
                source="smol", split="test", is_src_orig=row.get("is_src_orig"),
                extra={"released_as": "training", "upstream_id": row.get("id")},
            ))
    return out, skipped


def collect_flores_reference(targets, rows):
    """Reference-only rows for languages whose test set is the non-redistributable FLORES+."""
    out = []
    for config in targets:
        if not rows[config]["in_flores_plus"]:
            continue
        iso = rows[config]["iso639_3"]
        for split, count in (("dev", 997), ("test", 1012)):
            # Built through make_record like every other source, so that withheld rows carry
            # the same tier fields and the same empty-string convention as the others rather
            # than a second, nearly-identical shape.
            out.append(make_record(
                pivot_config="en", target_config=config, src="", trg="",
                source="flores_plus", split=split,
                extra={"upstream_rows": count,
                       "upstream_file":
                           f"{'dev' if split == 'dev' else 'devtest'}/{iso}_*.jsonl"},
            ))
    return out


# ------------------------------------------------------------------------------- assembly


# BOUQuET codes its languages with a script tag; these are the ones that matter here, both
# for our targets and for the pivots they are paired with.
BOUQUET_TARGETS = {"azb": "azb_Arab", "skr": "skr_Arab", "wuu": "wuu_Hans"}
BOUQUET_PIVOTS = {"eng_Latn": "en", "pes_Arab": "fa", "hin_Deva": "hi", "cmn_Hans": "zh"}


def collect_bouquet(targets, rows):
    """BOUQuET dev and test, at sentence and paragraph level.

    The only source here that is not translated out of English: every passage was written in
    one of the languages and then translated outwards. It also carries ``par_id``, so a
    sentence can be traced back to the paragraph it came from -- the one piece of document
    structure in the whole collection.
    """
    import pyarrow.parquet as pq
    from huggingface_hub import hf_hub_download
    from hf_publishing_auth import publishing_token

    out, skipped = [], []
    token = publishing_token()
    for config, tagged in BOUQUET_TARGETS.items():
        if config not in targets:
            continue
        for pivot_tag, pivot_config in BOUQUET_PIVOTS.items():
            ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
            if not ok:
                skipped.append({"target": config, "pair": f"{pivot_tag}-{tagged}",
                                "reason": "pivot not acceptable", "source": "bouquet"})
                continue
            for level in ("sentence_level", "paragraph_level"):
                for upstream, split in (("dev", "dev"), ("test", "test")):
                    name = (f"benchmark_data/{level}/{upstream}/{pivot_tag}-{tagged}.parquet")
                    try:
                        path = hf_hub_download("facebook/bouquet", name,
                                               repo_type="dataset", token=token)
                    except Exception as error:  # noqa: BLE001 - absent pair or no access
                        skipped.append({"target": config, "pair": name,
                                        "reason": f"{type(error).__name__}",
                                        "source": "bouquet"})
                        continue
                    table = pq.read_table(
                        path, columns=["src_text", "tgt_text", "par_id", "domain", "register"]
                    )
                    for src, trg, par_id, domain, register in zip(
                        table.column("src_text").to_pylist(),
                        table.column("tgt_text").to_pylist(),
                        table.column("par_id").to_pylist(),
                        table.column("domain").to_pylist(),
                        table.column("register").to_pylist(),
                    ):
                        if not (src or "").strip() or not (trg or "").strip():
                            continue
                        out.append(make_record(
                            pivot_config=pivot_config, target_config=config,
                            src=src, trg=trg, source="bouquet", split=split,
                            is_src_orig=None,
                            extra={"text_unit": level.replace("_level", ""),
                                   "document_id": str(par_id) if par_id is not None else None,
                                   "domain": domain,
                                   "released_as": "evaluation"},
                        ))
    return out, skipped


# CODET publishes one file per locality, named for the place rather than the language, so the
# mapping from place to ISO code has to be stated. Only localities whose variety is one of our
# targets are listed; the atlas covers 439 in total.
CODET_LOCALITIES = {
    "nap": ["Marcianise", "Montella", "Napoli", "Ariano%20Irpino", "Gragnano", "Salerno",
            "Torre%20del%20Greco", "Carife", "Trevico", "Calitri", "Bagnoli%20Irpino",
            "Montecalvo%20Irpino", "Scampitella", "Cardito1", "Cardito2", "Cardito3",
            "Cardito4"],
    "lld": ["Corvara", "Selva%20di%20Val%20Gardena", "Pozza%20di%20Fassa", "Ortisei"],
    "pms": ["Torino", "Torino1", "Borgomanero", "Alba", "Mondovi", "Moncalieri", "Poirino",
            "Novi%20Ligure", "Trecate", "Borgofranco%20d%27Ivrea", "Tollegno",
            "Rivarossa%20Canavese"],
    "eml": ["Bologna1", "Bologna2", "Carpi", "Ferrara1", "Mantova", "Bondeno",
            "Bagnolo%20S.%20Vito", "Casalmaggiore", "Luzzara", "Redondesco", "Campagnola",
            "Forli", "Forl%C3%AC", "Cesena2", "Rimini"],
}


def collect_codet(targets, rows):
    """CODET's Italian Syntactic Atlas files, aligned by line against standard Italian."""
    base = ("https://raw.githubusercontent.com/mahfuzibnalam/dialect_mt/"
            f"{CODET_REVISION}/Italian")
    standard = fetch(f"{base}/Standard.ita")
    out, skipped = [], []
    if not standard:
        return out, [{"target": None, "pair": "Standard.ita",
                      "reason": "not fetchable", "source": "codet"}]
    reference = standard.decode("utf-8", "replace").splitlines()
    ok, _why = pivots.acceptable_pivot("nap", "it", rows)
    if not ok:
        return out, [{"target": None, "pair": "it", "reason": "pivot not acceptable",
                      "source": "codet"}]
    for config, localities in CODET_LOCALITIES.items():
        if config not in targets:
            continue
        for locality in localities:
            payload = fetch(f"{base}/{locality}.ita")
            if not payload:
                skipped.append({"target": config, "pair": f"{locality}.ita",
                                "reason": "not fetchable", "source": "codet"})
                continue
            lines = payload.decode("utf-8", "replace").splitlines()
            if len(lines) != len(reference):
                # Alignment here is purely positional, so a different length means the file
                # cannot be trusted against the standard text at all.
                skipped.append({"target": config, "pair": f"{locality}.ita",
                                "reason": f"{len(lines)} lines against "
                                          f"{len(reference)} standard",
                                "source": "codet"})
                continue
            name = urllib.parse.unquote(locality)
            for index, (dialect, italian) in enumerate(zip(lines, reference)):
                if not dialect.strip() or not italian.strip():
                    continue
                out.append(make_record(
                    pivot_config="it", target_config=config, src=italian, trg=dialect,
                    source="codet", split="test", is_src_orig=True,
                    extra={"variety": name, "upstream_id": index},
                ))
    return out, skipped


def collect_dolma_bitext(targets, rows):
    """DOLMA-NLP's manually aligned pairs: the first human Gilaki sentence bitext."""
    base = ("https://raw.githubusercontent.com/DOLMA-NLP/bitext-mining/"
            f"{DOLMA_BITEXT_REVISION}/datasets/manually-aligned")
    out, skipped = [], []
    for config, filename in (("glk", "GLK-EN.tsv"), ("mzn", "MZN-EN.tsv")):
        if config not in targets:
            continue
        payload = fetch(f"{base}/{filename}")
        if not payload:
            skipped.append({"target": config, "pair": filename,
                            "reason": "not fetchable", "source": "dolma_bitext"})
            continue
        ok, _why = pivots.acceptable_pivot(config, "en", rows)
        if not ok:
            continue
        lines = payload.decode("utf-8", "replace").splitlines()
        for index, line in enumerate(lines[1:]):      # first line is the header
            parts = line.split("\t")
            if len(parts) < 2 or not parts[0].strip() or not parts[1].strip():
                continue
            out.append(make_record(
                pivot_config="en", target_config=config, src=parts[0], trg=parts[1],
                source="dolma_bitext", split="test", extra={"upstream_id": index},
            ))
    return out, skipped


def collect_nllb_seed(targets, rows):
    """NLLB-Seed's professionally translated sentences, for Buginese."""
    out, skipped = [], []
    if "bug" not in targets:
        return out, skipped
    ok, _why = pivots.acceptable_pivot("bug", "en", rows)
    if not ok:
        return out, skipped
    payload = fetch("https://dl.fbaipublicfiles.com/nllb/NLLB-Seed.zip")
    if not payload:
        return out, [{"target": "bug", "pair": "NLLB-Seed.zip",
                      "reason": "not fetchable", "source": "nllb_seed"}]
    try:
        archive = zipfile.ZipFile(io.BytesIO(payload))
    except zipfile.BadZipFile:
        return out, [{"target": "bug", "pair": "NLLB-Seed.zip",
                      "reason": "not a zip", "source": "nllb_seed"}]
    names = archive.namelist()
    left = next((n for n in names if n.endswith("/eng_Latn") and "bug_Latn" in n), None)
    right = next((n for n in names if n.endswith("/bug_Latn")), None)
    if not left or not right:
        return out, [{"target": "bug", "pair": "NLLB-Seed",
                      "reason": f"no bug_Latn/eng_Latn members among {len(names)} entries",
                      "source": "nllb_seed"}]
    src_lines = archive.read(left).decode("utf-8", "replace").splitlines()
    trg_lines = archive.read(right).decode("utf-8", "replace").splitlines()
    if len(src_lines) != len(trg_lines):
        return out, [{"target": "bug", "pair": "NLLB-Seed",
                      "reason": f"{len(src_lines)} vs {len(trg_lines)} lines",
                      "source": "nllb_seed"}]
    for index, (src, trg) in enumerate(zip(src_lines, trg_lines)):
        if not src.strip() or not trg.strip():
            continue
        out.append(make_record(
            pivot_config="en", target_config="bug", src=src, trg=trg,
            source="nllb_seed", split="test", is_src_orig=True,
            extra={"upstream_id": index},
        ))
    return out, skipped


def collect_nusax(targets, rows):
    """NusaX-MT, twelve-way parallel with official splits. Buginese is the target here."""
    out, skipped = [], []
    if "bug" not in targets:
        return out, skipped
    base = f"https://raw.githubusercontent.com/IndoNLP/nusax/{NUSAX_REVISION}/datasets/mt"
    # NusaX names its columns by language; Indonesian and English are the pivots we keep.
    wanted = {"indonesian": "id", "english": "en"}
    for upstream, split in (("test", "test"), ("valid", "dev")):
        payload = fetch(f"{base}/{upstream}.csv")
        if not payload:
            skipped.append({"target": "bug", "pair": f"{upstream}.csv",
                            "reason": "not fetchable", "source": "nusax"})
            continue
        reader = csv.DictReader(io.StringIO(payload.decode("utf-8", "replace")))
        for index, row in enumerate(reader):
            target_text = (row.get("buginese") or "").strip()
            if not target_text:
                continue
            for column, pivot_config in wanted.items():
                src = (row.get(column) or "").strip()
                if not src:
                    continue
                ok, _why = pivots.acceptable_pivot("bug", pivot_config, rows)
                if not ok:
                    continue
                out.append(make_record(
                    pivot_config=pivot_config, target_config="bug",
                    src=src, trg=target_text, source="nusax", split=split,
                    extra={"upstream_id": index},
                ))
    return out, skipped


# Treebanks that carry a free translation per sentence as a conll comment. The comment key
# differs: most use '# text_en', but the Shanghainese treebank pairs with Mandarin under
# '# text_cmn', which is the only Wu-Mandarin sentence alignment with official splits.
UD_BASE = "https://raw.githubusercontent.com/UniversalDependencies"
TREEBANK_TRANSLATIONS = {
    "maibaam": {
        "config": "bar", "comment": "text_en", "pivot": "en",
        "files": [(f"{UD_BASE}/UD_Bavarian-MaiBaam/{MAIBAAM_REVISION}/"
                   "bar_maibaam-ud-test.conllu", "test")],
    },
    "ud_megrelian": {
        "config": "xmf", "comment": "text_en", "pivot": "en",
        "files": [(f"{UD_BASE}/UD_Megrelian-MLC/{UD_MEGRELIAN_REVISION}/"
                   "xmf_mlc_ud-test.conllu", "test")],
    },
    "ud_shanghainese": {
        "config": "wuu", "comment": "text_cmn", "pivot": "zh",
        "files": [
            (f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-test.conllu",
             "test"),
            (f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-dev.conllu",
             "dev"),
            (f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-train.conllu",
             "train"),
        ],
    },
}


def collect_treebank_translations(targets, rows):
    """Sentences from UD treebanks that ship a free translation as a comment."""
    out, skipped = [], []
    for source, spec in TREEBANK_TRANSLATIONS.items():
        config, pivot_config = spec["config"], spec["pivot"]
        if config not in targets:
            continue
        ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
        if not ok:
            skipped.append({"target": config, "pair": source,
                            "reason": f"pivot {pivot_config} not acceptable",
                            "source": source})
            continue
        text_prefix = "# text = "
        pivot_prefix = f"# {spec['comment']} = "
        for url, split in spec["files"]:
            payload = fetch(url)
            if not payload:
                skipped.append({"target": config, "pair": url.rsplit("/", 1)[-1],
                                "reason": "not fetchable", "source": source})
                continue
            text, translation, kept = None, None, 0

            def emit(text, translation, kept):
                if not text or not translation:
                    return kept
                out.append(make_record(
                    pivot_config=pivot_config, target_config=config,
                    src=translation, trg=text, source=source, split=split,
                    extra={"upstream_id": kept,
                           "upstream_file": url.rsplit("/", 1)[-1]},
                ))
                return kept + 1

            for line in payload.decode("utf-8", "replace").splitlines():
                if line.startswith(text_prefix):
                    text = line[len(text_prefix):].strip()
                elif line.startswith(pivot_prefix):
                    translation = line[len(pivot_prefix):].strip()
                elif not line.strip():
                    kept = emit(text, translation, kept)
                    text, translation = None, None
            emit(text, translation, kept)
    return out, skipped


# Ladin corpora published by Simon Frontull. Only the two with a stated licence are taken;
# the three undated test sets on the same account state none and are left out rather than
# guessed at.
# Only the weather bulletins belong in a test set. The two big ``dizionar`` corpora are
# lexicographic example sentences harvested from a dictionary -- 37,422 of them, which would
# be a third of this release and would reward a model for reproducing dictionary glosses
# rather than translating. They go to the lexicon corpus instead, which is where a reader
# looking for dictionary material would expect them.
LADIN_SETS = [
    ("ladin_weather", "sfrontull/south-tyrol-weather-lld-deu", "de", "test"),
]


def ladin_keys(entry: dict) -> tuple[str | None, str | None]:
    """The Ladin side and the pivot side of one nested ``translation`` dict.

    Repos on this account label the pivot either by ISO 639-3 ("deu", "ita") or by the
    two-letter config code ("de", "it"), and the Ladin side either by variety
    ("lld_valbadia") or by the bare code. Matching only the three-letter spellings dropped
    the whole weather set silently, so both are accepted here.
    """
    target = next((k for k in entry if k.startswith("lld")), None)
    pivot = next((k for k in entry
                  if k != target and k.startswith(("ita", "deu", "it", "de"))), None)
    return target, pivot


def collect_ladin(targets, rows):
    """Italian-Ladin and German-Ladin corpora, including the non-commercial ones."""
    out, skipped = [], []
    if "lld" not in targets:
        return out, skipped
    import pyarrow.parquet as pq
    from huggingface_hub import snapshot_download
    from hf_publishing_auth import publishing_token

    for source, repo, pivot_config, split in LADIN_SETS:
        ok, _why = pivots.acceptable_pivot("lld", pivot_config, rows)
        if not ok:
            skipped.append({"target": "lld", "pair": repo,
                            "reason": "pivot not acceptable", "source": source})
            continue
        try:
            local = snapshot_download(repo, repo_type="dataset",
                                      token=publishing_token(),
                                      allow_patterns=["*.parquet", "*.jsonl"])
        except Exception as error:  # noqa: BLE001 - gated or absent
            skipped.append({"target": "lld", "pair": repo,
                            "reason": f"{type(error).__name__}", "source": source})
            continue
        found = 0
        # Both the parquet and the jsonl releases wrap each pair in a single ``translation``
        # column keyed by language, rather than one column per language.
        pairs: list[dict] = []
        for path in sorted(Path(local).rglob("*.parquet")):
            table = pq.read_table(path)
            if "translation" in table.schema.names:
                pairs += table.column("translation").to_pylist()
        for path in sorted(Path(local).rglob("*.jsonl")):
            with path.open(encoding="utf-8") as handle:
                for line in handle:
                    entry = json.loads(line).get("translation")
                    if isinstance(entry, dict):
                        pairs.append(entry)
        for entry in pairs:
            target_key, pivot_key = ladin_keys(entry)
            if not target_key or not pivot_key:
                continue
            src, trg = entry.get(pivot_key) or "", entry.get(target_key) or ""
            if not src.strip() or not trg.strip():
                continue
            out.append(make_record(
                pivot_config=pivot_config, target_config="lld", src=src, trg=trg,
                source=source, split=split,
                extra={"variety": target_key, "upstream_id": found},
            ))
            found += 1
        if not found:
            skipped.append({"target": "lld", "pair": repo,
                            "reason": "no recognisable column pair", "source": source})
    return out, skipped


def collect_glotstorybook(targets, rows):
    """African Storybook texts, aligned to English through their parallel id.

    Licensing is per row rather than per dataset, so only the plain CC-BY stories are taken;
    the CC-BY-NC and CC-BY-NC-SA ones would silently impose a condition on the whole release.
    """
    out, skipped = [], []
    if "dag" not in targets:
        return out, skipped
    ok, _why = pivots.acceptable_pivot("dag", "en", rows)
    if not ok:
        return out, skipped
    from huggingface_hub import hf_hub_download
    from hf_publishing_auth import publishing_token

    try:
        path = hf_hub_download("cis-lmu/GlotStoryBook", "GlotStoryBook.csv",
                               repo_type="dataset", token=publishing_token())
    except Exception as error:  # noqa: BLE001
        return out, [{"target": "dag", "pair": "GlotStoryBook.csv",
                      "reason": f"{type(error).__name__}", "source": "glotstorybook"}]

    with open(path, encoding="utf-8") as handle:
        entries = list(csv.DictReader(handle))
    # Each story segment is identified by its parallel id plus its position in the story.
    english = {
        (row["Parallel ID"], row["Text Number"]): row["Text"]
        for row in entries if row["ISO639-3"] == "eng"
    }
    for row in entries:
        if row["ISO639-3"] != "dag":
            continue
        if (row.get("License") or "").strip().upper().replace(" ", "-") != "CC-BY":
            skipped.append({"target": "dag", "pair": row.get("File Name"),
                            "reason": f"licence {row.get('License')!r} is not plain CC-BY",
                            "source": "glotstorybook"})
            continue
        key = (row["Parallel ID"], row["Text Number"])
        src = english.get(key)
        if not src or not (row.get("Text") or "").strip():
            skipped.append({"target": "dag", "pair": row.get("File Name"),
                            "reason": "no English segment with the same parallel id",
                            "source": "glotstorybook"})
            continue
        out.append(make_record(
            pivot_config="en", target_config="dag", src=src, trg=row["Text"],
            source="glotstorybook", split="test",
            extra={"document_id": row["Parallel ID"],
                   "upstream_id": int(row["Text Number"]) if
                   str(row["Text Number"]).isdigit() else None,
                   "variety": row.get("Story Category")},
        ))
    return out, skipped


def collect_nsanku(targets, rows):
    """Ghana NLP's Dagbani-English reference pairs, counted but withheld.

    Real human translation and already used as a published evaluation set, but the repository
    ships no licence and the underlying text is a Bible society translation, so only the row
    count and provenance are published.
    """
    out, skipped = [], []
    if "dag" not in targets:
        return out, skipped
    ok, _why = pivots.acceptable_pivot("dag", "en", rows)
    if not ok:
        return out, skipped
    payload = fetch("https://raw.githubusercontent.com/GhanaNLP/nsanku/main/input/dag-eng.csv")
    if not payload:
        return out, [{"target": "dag", "pair": "input/dag-eng.csv",
                      "reason": "not fetchable", "source": "nsanku"}]
    reader = csv.reader(io.StringIO(payload.decode("utf-8", "replace")))
    rows_read = sum(1 for index, line in enumerate(reader) if index and any(line))
    out.append(make_record(
        pivot_config="en", target_config="dag", src="", trg="",
        source="nsanku", split="test",
        extra={"upstream_rows": rows_read, "upstream_file": "input/dag-eng.csv"},
    ))
    return out, skipped


GIL1000_CSV = "CSV/Top 1000 Words in Gilaki (Full).csv"
# Each row carries the same illustrative sentence in all three languages, so one row yields a
# Gilaki-Persian pair and a Gilaki-English pair.
GIL1000_PIVOTS = [("fa", "fa_example"), ("en", "en_example")]


def collect_gil1000_sentences(targets, rows):
    """Sentence-level Gilaki-Persian and Gilaki-English pairs from the Top-1000 word list.

    Published at https://gil1000.ir/ and in the repository below. Each of the 1,000 entries
    carries one example sentence written in Gilaki, Persian and English, which makes it
    sentence-aligned parallel text for a language that has almost none.

    These are dictionary example sentences, not running text, and they are also present in the
    lexicon corpus as ``entry_type: example_sentence``. Both facts limit what a score on them
    means: the sentences were written to illustrate a headword, they are short, and a system
    trained on the lexicon corpus has already seen them. ``domain`` says
    ``dictionary_examples`` so this cannot be mistaken for a general-purpose test set.
    """
    out, skipped = [], []
    if "glk" not in targets:
        return out, skipped
    url = ("https://raw.githubusercontent.com/LordArma/Top-1000-Words-in-Gilaki/"
           f"{GIL1000_REVISION}/{urllib.parse.quote(GIL1000_CSV)}")
    payload = fetch(url)
    if not payload:
        return out, [{"target": "glk", "pair": GIL1000_CSV,
                      "reason": "not fetchable", "source": "gil1000"}]
    reader = csv.DictReader(io.StringIO(payload.decode("utf-8-sig", "replace")))
    for index, line in enumerate(reader):
        target = (line.get("glk_example") or "").strip()
        if not target:
            continue
        for pivot_config, column in GIL1000_PIVOTS:
            ok, why = pivots.acceptable_pivot("glk", pivot_config, rows)
            if not ok:
                skipped.append({"target": "glk", "pair": f"{pivot_config}-glk",
                                "reason": why, "source": "gil1000"})
                continue
            src = (line.get(column) or "").strip()
            if not src:
                continue
            out.append(make_record(
                pivot_config=pivot_config, target_config="glk", src=src, trg=target,
                source="gil1000", split="test",
                # The Gilaki sentence is the one that was written first; the other two are its
                # translations, which is the opposite of every other source here.
                is_src_orig=False,
                # ``upstream_id`` is an integer column; the CSV hands back strings.
                extra={"upstream_id": int(line.get("id") or index),
                       "upstream_file": GIL1000_CSV,
                       "headword": (line.get("glk_word") or "").strip()},
            ))
    return out, skipped


# The script each target language is actually written in. A test set that mixes scripts for
# one language cannot be scored: chrF and BLEU compare characters, so a Georgian reference and
# a Latin transliteration of the same Megrelian sentence score as a total miss against each
# other. Tatoeba's Megrelian is 45 sentences in Georgian and 34 romanised by contributors, and
# nothing upstream distinguishes them.
#
# Latin is the default because most of these languages are written in it; only the five that
# are not need an entry.
EXPECTED_SCRIPT = {
    "azb": {"ARABIC"},      # South Azerbaijani, Perso-Arabic
    "glk": {"ARABIC"},      # Gilaki
    "mzn": {"ARABIC"},      # Mazanderani
    "skr": {"ARABIC"},      # Saraiki
    "xmf": {"GEORGIAN"},    # Megrelian, Mkhedruli
    "wuu": {"CJK", "BOPOMOFO"},  # Wu, Han characters
}
DEFAULT_SCRIPT = {"LATIN"}
# A fifth of the letters, not merely one. "sanchez_: <Chinese>" is 30% Han and genuinely Wu
# text, so a majority test would wrongly drop it; a romanised Megrelian sentence is 0%
# Georgian, so a one-character test would wrongly keep anything with a stray diacritic.
SCRIPT_SHARE = 0.2


def script_of(char: str) -> str | None:
    """The script a single character belongs to, or None if it is not a letter."""
    if not char.isalpha():
        return None
    try:
        name = unicodedata.name(char)
    except ValueError:
        return None
    # Unicode names Han characters "CJK UNIFIED IDEOGRAPH-xxxx"; everything else leads with
    # its script name.
    return name.split()[0]


def script_share(text: str, expected: set[str]) -> float:
    """What fraction of a string's letters are written in the expected script."""
    letters = [s for s in (script_of(c) for c in text or "") if s]
    if not letters:
        return 1.0        # no letters at all: nothing to judge, leave it to the caller
    return sum(1 for s in letters if s in expected) / len(letters)


def drop_off_script(records: list[dict]) -> tuple[list[dict], list[dict]]:
    """Separate records whose target is not written in the language's own script."""
    kept, dropped = [], []
    for record in records:
        if record.get("text_withheld") or not record.get("trg"):
            kept.append(record)
            continue
        expected = EXPECTED_SCRIPT.get(record["tl"], DEFAULT_SCRIPT)
        if script_share(record["trg"], expected) < SCRIPT_SHARE:
            dropped.append(record)
            continue
        kept.append(record)
    return kept, dropped


MLC_INDEX = "https://xmf.iliauni.edu.ge/corpus"
MLC_DOWNLOAD = "https://xmf.iliauni.edu.ge/download?file="
# The Megrelian phrase and the two glosses of it. The fourth phrase tier,
# ``A_phrase-gls-xmf-fonipa``, is an IPA transcription of the same Megrelian rather than a
# translation, so it is not collected.
MLC_TARGET_TIER = "A_phrase-txt-xmf"
MLC_GLOSS_TIERS = [("A_phrase-gls-ka-Brai", "ka"), ("A_phrase-gls-en", "en")]


def _eaf_root(payload: bytes):
    """Parse an ELAN file, recovering the one upstream file with invalid UTF-8 bytes."""
    try:
        return ElementTree.fromstring(payload)
    except ElementTree.ParseError:
        # 00138.eaf carries bytes that are not valid UTF-8. U+FFFD is itself valid XML, so
        # re-encoding keeps every annotation except the damaged characters, rather than
        # discarding a whole text.
        return ElementTree.fromstring(payload.decode("utf-8", "replace").encode("utf-8"))


def _eaf_tier(root, tier_id: str) -> dict:
    """``{annotation_id: (text, referenced_annotation_id)}`` for one ELAN tier."""
    found = {}
    for tier in root.iter("TIER"):
        if tier.get("TIER_ID") != tier_id:
            continue
        annotations = list(tier.iter("ALIGNABLE_ANNOTATION"))
        annotations += list(tier.iter("REF_ANNOTATION"))
        for annotation in annotations:
            value = annotation.find("ANNOTATION_VALUE")
            text = (value.text or "").strip() if value is not None else ""
            found[annotation.get("ANNOTATION_ID")] = (text, annotation.get("ANNOTATION_REF"))
    return found


def collect_mlc(targets, rows):
    """Megrelian oral texts with aligned Georgian and English glosses.

    Each phrase is a separate ELAN annotation, and the two gloss tiers reference the
    Megrelian annotation they gloss, so the alignment is the corpus's own rather than
    positional.
    """
    out, skipped = [], []
    if "xmf" not in targets:
        return out, skipped
    index = fetch(MLC_INDEX)
    if not index:
        return out, [{"target": "xmf", "pair": "corpus", "reason": "index not fetchable",
                      "source": "mlc"}]
    files = sorted(set(re.findall(r"download\?file=(data/[^'\"]+\.eaf)",
                                  index.decode("utf-8", "replace"))))
    if not files:
        return out, [{"target": "xmf", "pair": "corpus",
                      "reason": "no ELAN files listed", "source": "mlc"}]
    usable = []
    for pivot_tier, pivot_config in MLC_GLOSS_TIERS:
        ok, why = pivots.acceptable_pivot("xmf", pivot_config, rows)
        if ok:
            usable.append((pivot_tier, pivot_config))
        else:
            skipped.append({"target": "xmf", "pair": f"{pivot_config}-xmf",
                            "reason": why, "source": "mlc"})
    for name in files:
        payload = fetch(MLC_DOWNLOAD + name)
        if not payload:
            skipped.append({"target": "xmf", "pair": name, "reason": "not fetchable",
                            "source": "mlc"})
            continue
        root = _eaf_root(payload)
        target_tier = _eaf_tier(root, MLC_TARGET_TIER)
        document = name.rsplit("/", 1)[-1].removesuffix(".eaf")
        for pivot_tier, pivot_config in usable:
            glosses = _eaf_tier(root, pivot_tier)
            by_reference = {reference: text for text, reference in glosses.values()
                            if reference}
            for annotation_id, (target_text, _reference) in sorted(target_tier.items()):
                pivot_text = by_reference.get(annotation_id) or ""
                if not target_text.strip() or not pivot_text.strip():
                    continue
                out.append(make_record(
                    pivot_config=pivot_config, target_config="xmf",
                    src=pivot_text, trg=target_text,
                    source="mlc", split="test",
                    # Recorded in Megrelian; both glosses were written from it.
                    is_src_orig=False,
                    extra={"document_id": document, "upstream_file": name,
                           "text_unit": "phrase"},
                ))
    return out, skipped


def deduplicate(records, rows):
    """Collapse records that carry the same pair, keeping the most authoritative source.

    NaLiBaSID republishes xSID's Bavarian sentences, so the same English-Bavarian pair
    arrives twice; the same happens whenever two Tatoeba pairs share a sentence. Preference
    order follows which release supersedes which, mirroring the ``supersedes`` declarations
    in ``configs/community_benchmarks.json``.
    """
    # Human-authored and manually aligned sources rank above translated-out-of-English ones,
    # and anything redistributable ranks above a withheld duplicate of the same pair: keeping
    # the withheld copy would lose text we are allowed to publish.
    priority = {"bouquet": 0, "dolma_bitext": 1, "nalibasid": 2, "parme": 3, "codet": 4,
                "nllb_seed": 5, "nusax": 6, "ntrex": 7, "ladin_weather": 8,
                "ladin_frontull": 9, "ud_shanghainese": 9, "maibaam": 10, "mlc": 10, "ud_megrelian": 11, "xsid": 12,
                "smol": 13, "tatoeba_challenge": 14,
                "glotstorybook": 15, "gil1000": 16, "nsanku": 20, "betthupferl": 21, "flores_plus": 22}
    best: dict[tuple, dict] = {}
    dropped = []
    for record in records:
        if record.get("text_withheld"):
            # Withheld rows have no text to compare, so they are keyed by what they stand
            # for: one row per language, source and split.
            best[("ref", record["tl"], record["source"], record["split"])] = record
            continue
        key = (record["tl"], record["sl"], norm_key(record["src"]), norm_key(record["trg"]))
        incumbent = best.get(key)
        if incumbent is None:
            best[key] = record
            continue
        if priority.get(record["source"], 8) < priority.get(incumbent["source"], 8):
            dropped.append({"kept": record["source"], "dropped": incumbent["source"],
                            "language": record["tl"]})
            best[key] = record
        else:
            dropped.append({"kept": incumbent["source"], "dropped": record["source"],
                            "language": record["tl"]})
    return list(best.values()), dropped


def write_release(records, skipped, dropped, selection, rows, release_id=None):
    import pyarrow as pa
    import pyarrow.parquet as pq

    release_id = release_id or time.strftime("eval_%Y%m%dT%H%M%SZ", time.gmtime())
    output = DIST / release_id
    (output / "languages").mkdir(parents=True, exist_ok=True)

    by_language: dict[str, list[dict]] = {}
    for record in records:
        by_language.setdefault(record["tl"], []).append(record)

    # Only columns that bear on the translation itself, its provenance or its licence. Task
    # annotations from the upstream releases (xSID intent labels, BOUQuET register codes) and
    # columns derivable from another column (source_url from source, redistributable from
    # licence_tier, withheld_reason from licence_restriction) are deliberately absent.
    columns = ["sl", "tl", "id", "src", "trg", "is_src_orig", "split", "source",
               "source_revision", "licence", "licence_tier", "licence_restriction",
               "domain", "variety", "text_unit", "document_id", "released_as",
               "source_pair", "upstream_id", "upstream_file",
               "text_withheld", "upstream_rows"]
    schema = pa.schema([
        ("sl", pa.string()), ("tl", pa.string()), ("id", pa.int64()),
        ("src", pa.string()), ("trg", pa.string()), ("is_src_orig", pa.bool_()),
        ("split", pa.string()), ("source", pa.string()),
        ("source_revision", pa.string()), ("licence", pa.string()),
        # How freely each record may be passed on.
        ("licence_tier", pa.int64()), ("licence_restriction", pa.string()),
        # What kind of text it is, and which variety of the language wrote it.
        ("domain", pa.string()), ("variety", pa.string()), ("text_unit", pa.string()),
        ("document_id", pa.string()), ("released_as", pa.string()),
        # Where the row came from, precisely enough to find it upstream.
        ("source_pair", pa.string()), ("upstream_id", pa.int64()),
        ("upstream_file", pa.string()),
        ("text_withheld", pa.bool_()), ("upstream_rows", pa.int64()),
    ])

    summary, flat = {}, []
    for config in sorted(by_language):
        items = by_language[config]
        # Deterministic order: split, then source, then pivot, then the text itself.
        items.sort(key=lambda r: (r["split"], r["source"], r["sl"], r["src"] or "",
                                  r["trg"] or ""))
        for index, record in enumerate(items):
            record["id"] = index
        path = output / "languages" / f"{config}.jsonl"
        with path.open("w", encoding="utf-8") as handle:
            for record in items:
                handle.write(json.dumps(
                    {k: v for k, v in record.items() if v is not None},
                    ensure_ascii=False,
                ) + "\n")
        flat += items
        usable = [r for r in items if r.get("src")]
        summary[config] = {
            "language_name": rows[config]["language_name"],
            "iso639_3": rows[config]["iso639_3"],
            "opportunity_rank": rows[config]["opportunity_rank"],
            "records": len(usable),
            "withheld_records": len(items) - len(usable),
            "test": sum(1 for r in usable if r["split"] == "test"),
            "dev": sum(1 for r in usable if r["split"] == "dev"),
            "sources": sorted({r["source"] for r in usable}),
            "pivots": sorted({r["sl"] for r in usable}),
            "by_source": {
                source: sum(1 for r in usable if r["source"] == source)
                for source in sorted({r["source"] for r in usable})
            },
        }

    def as_table(items):
        return pa.Table.from_pylist(
            [{column: record.get(column) for column in columns} for record in items],
            schema=schema,
        )

    pq.write_table(as_table(flat), output / "eval.parquet", compression="zstd")

    # One subset per source and language: "<source>-<language>" says where the data came
    # from and which language it is for -- nalibasid-bar, tatoeba-bar, parme-glk. The
    # baseline corpus names its subsets the same way, so a name that appears in both
    # identifies one body of data with its test split here and its training split there.
    #
    # Withheld FLORES+ rows carry no text, so they stay in the per-language JSONL as a
    # record of the gap and are kept out of every subset, including 'all'. A subset is
    # something you can score against; a row with no sentences is not.
    usable = [r for r in flat if r.get("src")]
    subsets = {"all": usable}
    for source, language in sorted({(r["source"], r["tl"]) for r in usable}):
        subsets[subset_name(source, language)] = [
            r for r in usable if r["source"] == source and r["tl"] == language
        ]
    subset_meta = write_subsets(
        output, subsets, as_table, split_of=lambda record: record["split"]
    )

    manifest = {
        "release_id": release_id,
        "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "audit_release": selection["release"],
        "shortlist_count": selection["count"],
        "languages_with_usable_records": sum(1 for s in summary.values() if s["records"]),
        "languages_without_any_test_data": sorted(
            c for c in selection["languages"] if not summary.get(c, {}).get("records")
        ),
        "total_records": sum(s["records"] for s in summary.values()),
        "withheld_records": sum(s["withheld_records"] for s in summary.values()),
        "sources": SOURCE_META,
        "licence": "CC-BY-SA-4.0",
        "licence_note": (
            "The collection is CC-BY-SA-4.0 because xSID, NaLiBaSID and NTREX are "
            "share-alike; CC-BY-4.0 (SMOL), CC-BY-2.0-FR (Tatoeba) and MIT (PARME) are "
            "compatible with that. Every record carries its own licence field."
        ),
        "subsets": subset_meta,
        "subset_note": (
            "'all' is every record. The remaining subsets are one per source and "
            "language, named '<source>-<language>': where the data came from, and which "
            "language it is for. The baseline corpus names its subsets the same way, so a "
            "name present in both identifies one body of data with its test split here and "
            "its training split there. Withheld FLORES+ reference rows appear only in the "
            "per-language JSONL files, not in any subset."
        ),
        "languages": summary,
        "skipped": skipped,
        "duplicates_collapsed": len(dropped),
        "columns": columns,
    }
    (output / "manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )
    return output, manifest


def build(release_id=None):
    selection = pivots.selection()
    rows = pivots.load_rows(pivots.DIST / selection["release"])
    targets = list(selection["languages"])
    iso2cfg = pivots.iso_to_config(rows)

    with (ROOT / "cache" / "lang_audit" / "sources" / "tatoeba_challenge.json").open(
        encoding="utf-8"
    ) as handle:
        tatoeba_pairs = json.load(handle)["data"]["test_pairs"]["pairs"]

    records, skipped = [], []
    for label, collector in (
        ("tatoeba_challenge", lambda: collect_tatoeba(targets, rows, iso2cfg, tatoeba_pairs)),
        ("ntrex", lambda: collect_ntrex(targets, rows)),
        ("xsid", lambda: collect_xsid(rows)),
        ("nalibasid", lambda: collect_nalibasid(rows)),
        ("parme", lambda: collect_parme(rows)),
        ("smol", lambda: collect_smol(targets, rows)),
        ("bouquet", lambda: collect_bouquet(targets, rows)),
        ("codet", lambda: collect_codet(targets, rows)),
        ("dolma_bitext", lambda: collect_dolma_bitext(targets, rows)),
        ("nllb_seed", lambda: collect_nllb_seed(targets, rows)),
        ("nusax", lambda: collect_nusax(targets, rows)),
        ("treebanks", lambda: collect_treebank_translations(targets, rows)),
        ("ladin", lambda: collect_ladin(targets, rows)),
        ("glotstorybook", lambda: collect_glotstorybook(targets, rows)),
        ("mlc", lambda: collect_mlc(targets, rows)),
        ("gil1000", lambda: collect_gil1000_sentences(targets, rows)),
        ("nsanku", lambda: collect_nsanku(targets, rows)),
    ):
        got, missed = collector()
        print(f"  {label:<20} {len(got):>7,} records, {len(missed)} skipped", flush=True)
        records += got
        # Two labels cover more than one source, so the entry's own source wins.
        skipped += [{"source": label, **entry} for entry in missed]

    references = collect_flores_reference(targets, rows)
    print(f"  {'flores_plus (ref)':<20} {len(references):>7,} reference rows", flush=True)
    records += references

    records, off_script = drop_off_script(records)
    if off_script:
        counts = Counter((r["tl"], r["source"]) for r in off_script)
        print(f"  off-script:   {len(off_script):,} records not in the language's own script")
        for (language, source), count in sorted(counts.items()):
            print(f"                  {language} {source}: {count:,}")

    records, dropped = deduplicate(records, rows)
    print(f"  deduplicated: {len(dropped):,} collapsed -> {len(records):,} records")
    output, manifest = write_release(records, skipped, dropped, selection, rows, release_id)
    print(f"\nrelease: {output}")
    return output, manifest


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release-id", default=None)
    args = parser.parse_args(argv)
    output, manifest = build(args.release_id)
    print(f"languages with test data: {manifest['languages_with_usable_records']}"
          f"/{manifest['shortlist_count']}")
    print(f"records: {manifest['total_records']:,}  withheld: {manifest['withheld_records']}")
    if manifest["languages_without_any_test_data"]:
        print(f"no human test data: {manifest['languages_without_any_test_data']}")
    return 0


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