File size: 53,646 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
"""Fetch and cache the language catalogues used by the FineWiki translation-resource audit.

Each source is downloaded once into ``cache/lang_audit/sources/<name>.json`` together with
its URL and fetch time, so the audit can be rebuilt without re-querying anybody's server.
Nothing here interprets the catalogues; ``lang_audit_build.py`` does the joining.
"""

from __future__ import annotations

import argparse
import csv
import io
import json
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
CACHE = ROOT / "cache" / "lang_audit" / "sources"
USER_AGENT = "gilaki-lang-audit/1.0 (research audit; https://huggingface.co/sigiranic)"
BROWSER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) gilaki-lang-audit/1.0"


# --------------------------------------------------------------------------- helpers


def _fetch(url: str, *, auth: bool = False, timeout: int = 180, agent: str = USER_AGENT) -> bytes:
    headers = {"User-Agent": agent}
    if auth:
        sys.path.insert(0, str(ROOT / "scripts"))
        from hf_publishing_auth import publishing_token

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


def _fetch_json(url: str, *, auth: bool = False, timeout: int = 180) -> dict | list:
    return json.loads(_fetch(url, auth=auth, timeout=timeout))


def _fetch_text(url: str, *, auth: bool = False, timeout: int = 180, agent: str = USER_AGENT) -> str:
    return _fetch(url, auth=auth, timeout=timeout, agent=agent).decode("utf-8", "replace")


def _retry(call, attempts: int = 4, delay: float = 2.0):
    last = None
    for attempt in range(attempts):
        try:
            return call()
        except Exception as error:  # noqa: BLE001 - transient network failures are expected
            last = error
            if attempt + 1 < attempts:
                time.sleep(delay * (attempt + 1))
    raise last


# --------------------------------------------------------------------------- sources


def source_finewiki() -> dict:
    """Article and byte counts for every FineWiki language config."""
    url = "https://datasets-server.huggingface.co/size?dataset=HuggingFaceFW%2Ffinewiki"
    payload = _fetch_json(url)
    if payload.get("partial"):
        raise RuntimeError("FineWiki size report is partial")
    configs = {}
    for entry in payload["size"]["configs"]:
        if entry["config"] == "default":
            continue
        configs[entry["config"]] = {
            "articles": int(entry["num_rows"]),
            "bytes_original": int(entry.get("num_bytes_original_files") or 0),
            "bytes_parquet": int(entry.get("num_bytes_parquet_files") or 0),
        }
    return {"url": url, "configs": configs, "config_count": len(configs)}


def source_wikimedia_sitematrix() -> dict:
    """Official Wikimedia language inventory: code, English name, autonym, site status."""
    url = "https://meta.wikimedia.org/w/api.php?action=sitematrix&format=json&smtype=language&smsiteprop=url|code|sitename|closed"
    payload = _fetch_json(url)
    languages = {}
    for key, entry in payload["sitematrix"].items():
        if not key.isdigit():
            continue
        wiki = None
        for site in entry.get("site", []):
            if site.get("code") == "wiki":
                wiki = site
                break
        languages[entry["code"]] = {
            "name": entry.get("name"),
            "localname": entry.get("localname"),
            "dir": entry.get("dir"),
            "has_wikipedia": wiki is not None,
            "wikipedia_closed": bool(wiki.get("closed")) if wiki else None,
            "wikipedia_url": wiki.get("url") if wiki else None,
        }
    return {"url": url, "languages": languages, "language_count": len(languages)}


def source_wikistats() -> dict:
    """Live per-wiki statistics (article count, edits, editors) from the Wikistats dump API."""
    url = "https://wikistats.wmcloud.org/api.php?action=dump&table=wikipedias&format=csv"
    text = _fetch_text(url, agent=BROWSER_AGENT)
    rows = {}
    reader = csv.DictReader(io.StringIO(text))
    for row in reader:
        prefix = (row.get("prefix") or "").strip()
        if not prefix:
            continue

        def number(field):
            value = (row.get(field) or "").strip()
            try:
                return int(value)
            except ValueError:
                return None

        rows[prefix] = {
            "articles": number("good"),
            "pages_total": number("total"),
            "edits": number("edits"),
            "registered_users": number("users"),
            "active_users": number("activeusers"),
            "admins": number("admins"),
            "local_name": (row.get("loclang") or "").strip() or None,
            "english_name": (row.get("lang") or "").strip() or None,
        }
    return {"url": url, "wikis": rows, "wiki_count": len(rows)}


def source_iso639_3() -> dict:
    """SIL ISO 639-3 code table, used to reconcile wiki prefixes with three-letter codes."""
    url = "https://iso639-3.sil.org/sites/iso639-3/files/downloads/iso-639-3.tab"
    text = _fetch_text(url, agent=BROWSER_AGENT)
    reader = csv.DictReader(io.StringIO(text), delimiter="\t")
    codes = {}
    part1 = {}
    for row in reader:
        code = (row.get("Id") or "").strip()
        if not code:
            continue
        entry = {
            "name": (row.get("Ref_Name") or "").strip(),
            "scope": (row.get("Scope") or "").strip(),
            "type": (row.get("Language_Type") or "").strip(),
            "part1": (row.get("Part1") or "").strip() or None,
            "part2b": (row.get("Part2b") or "").strip() or None,
        }
        codes[code] = entry
        if entry["part1"]:
            part1[entry["part1"]] = code
    return {"url": url, "codes": codes, "part1_to_part3": part1, "code_count": len(codes)}


def source_iso639_macrolanguages() -> dict:
    """ISO 639-3 macrolanguage membership.

    Needed because Wikipedia usually uses the macrolanguage (``fa``, ``ms``, ``ne``)
    while FLORES and NLLB use an individual member (``pes_Arab``, ``zsm_Latn``, ``npi_Deva``).
    """
    url = "https://iso639-3.sil.org/sites/iso639-3/files/downloads/iso-639-3-macrolanguages.tab"
    text = _fetch_text(url, agent=BROWSER_AGENT)
    reader = csv.DictReader(io.StringIO(text), delimiter="\t")
    members: dict[str, list[str]] = {}
    parents: dict[str, str] = {}
    for row in reader:
        macro = (row.get("M_Id") or "").strip()
        individual = (row.get("I_Id") or "").strip()
        if not macro or not individual:
            continue
        members.setdefault(macro, []).append(individual)
        parents[individual] = macro
    return {
        "url": url,
        "members": {k: sorted(v) for k, v in members.items()},
        "individual_to_macro": parents,
        "macrolanguage_count": len(members),
    }


def source_glottolog_languages() -> dict:
    """Glottolog languoids: glottocode, ISO 639-3, family, macroarea."""
    url = "https://raw.githubusercontent.com/glottolog/glottolog-cldf/master/cldf/languages.csv"
    text = _fetch_text(url)
    reader = csv.DictReader(io.StringIO(text))
    languoids = {}
    iso_index = {}
    for row in reader:
        glottocode = (row.get("Glottocode") or row.get("ID") or "").strip()
        if not glottocode:
            continue
        iso = (row.get("ISO639P3code") or "").strip() or None
        languoids[glottocode] = {
            "name": (row.get("Name") or "").strip(),
            "iso639_3": iso,
            "level": (row.get("Level") or "").strip(),
            "macroarea": (row.get("Macroarea") or "").strip() or None,
            "family_id": (row.get("Family_ID") or "").strip() or None,
            # For a dialect-level languoid this is the language it belongs to, whose
            # classification path exists even when the dialect's does not.
            "language_id": (row.get("Language_ID") or "").strip() or None,
            "is_isolate": (row.get("Is_Isolate") or "").strip().lower() in {"true", "1", "yes"},
            "latitude": (row.get("Latitude") or "").strip() or None,
            "longitude": (row.get("Longitude") or "").strip() or None,
        }
        if iso:
            iso_index[iso] = glottocode
    return {"url": url, "languoids": languoids, "iso_to_glottocode": iso_index,
            "languoid_count": len(languoids)}


_NEWICK_LABEL = re.compile(r"[A-Za-z0-9_\-.]+")


def _parse_newick_paths(newick: str) -> dict:
    """Map each node label in a Newick tree to its root-to-node ancestor path."""
    paths: dict[str, list[str]] = {}
    stack: list[list[str]] = []
    current: list[str] = []
    index = 0
    length = len(newick)
    while index < length:
        char = newick[index]
        if char == "(":
            stack.append(current)
            current = []
            index += 1
        elif char == ",":
            index += 1
        elif char == ")":
            children = current
            current = stack.pop() if stack else []
            index += 1
            match = _NEWICK_LABEL.match(newick, index)
            label = match.group(0) if match else ""
            if match:
                index = match.end()
            if newick[index : index + 1] == ":":
                index += 1
                skip = _NEWICK_LABEL.match(newick, index)
                if skip:
                    index = skip.end()
            node = {"label": label, "children": children}
            current.append(node)
        elif char in ";[]&R \n\t":
            index += 1
        else:
            match = _NEWICK_LABEL.match(newick, index)
            if not match:
                index += 1
                continue
            label = match.group(0)
            index = match.end()
            if newick[index : index + 1] == ":":
                index += 1
                skip = _NEWICK_LABEL.match(newick, index)
                if skip:
                    index = skip.end()
            current.append({"label": label, "children": []})

    def walk(node, ancestors):
        label = node["label"]
        chain = ancestors + ([label] if label else [])
        if label:
            paths[label] = chain
        for child in node["children"]:
            walk(child, chain)

    for node in current:
        walk(node, [])
    return paths


def source_glottolog_classification() -> dict:
    """Root-to-leaf Glottolog classification path for every languoid, from the CLDF Nexus tree."""
    url = "https://raw.githubusercontent.com/glottolog/glottolog-cldf/master/cldf/classification.nex"
    text = _fetch_text(url)
    paths: dict[str, list[str]] = {}
    trees = 0
    for line in text.splitlines():
        stripped = line.strip()
        if not stripped.upper().startswith("TREE "):
            continue
        _, _, body = stripped.partition("=")
        body = body.strip()
        if body.startswith("[&R]"):
            body = body[4:].strip()
        trees += 1
        paths.update(_parse_newick_paths(body))
    if trees == 0:
        raise RuntimeError("no classification trees parsed from Glottolog Nexus file")
    return {"url": url, "trees": trees, "paths": paths, "languoid_count": len(paths)}


def _fetch_tree(repo: str, *, auth: bool = False) -> list[dict]:
    """Every entry of a dataset repository's file tree, following the Hub's pagination.

    The tree endpoint caps a page at 1,000 entries and advertises the rest through a
    ``Link: <...>; rel="next"`` header, so a single call silently truncates a large
    repository.
    """
    url = (f"https://huggingface.co/api/datasets/{repo}/tree/main"
           "?recursive=1&expand=0")
    entries: list[dict] = []
    while url:
        headers = {"User-Agent": USER_AGENT}
        if auth:
            sys.path.insert(0, str(ROOT / "scripts"))
            from hf_publishing_auth import publishing_token

            headers["Authorization"] = "Bearer " + publishing_token()
        request = urllib.request.Request(url, headers=headers)
        with urllib.request.urlopen(request, timeout=180) as response:
            entries += json.loads(response.read())
            following = re.search(r'<([^>]+)>;\s*rel="next"',
                                  response.headers.get("Link") or "")
        url = following.group(1) if following else None
    return entries


def source_flores200() -> dict:
    """The 204 FLORES-200 / NLLB-200 evaluation codes with their English names."""
    url = "https://raw.githubusercontent.com/facebookresearch/flores/main/flores200/README.md"
    text = _fetch_text(url)
    section = text.split("## Languages in FLORES-200", 1)
    if len(section) != 2:
        raise RuntimeError("FLORES-200 language section not found")
    codes = {}
    for line in section[1].splitlines():
        if "|" not in line:
            continue
        name, _, code = line.rpartition("|")
        name = name.strip().strip("|").strip()
        code = code.strip()
        if not re.fullmatch(r"[a-z]{3}_[A-Za-z]{4}", code):
            continue
        codes[code] = name
    if len(codes) < 150:
        raise RuntimeError(f"FLORES-200 parse produced only {len(codes)} codes")
    return {"url": url, "codes": codes, "code_count": len(codes)}


def source_flores_plus() -> dict:
    """FLORES+ (Open Language Data Initiative) language inventory from the gated HF repo."""
    api = "https://huggingface.co/api/datasets/openlanguagedata/flores_plus"
    info = _fetch_json(api, auth=True)
    card_languages = sorted((info.get("cardData") or {}).get("language") or [])
    tree_url = api + "/tree/main/dev"
    try:
        tree = _fetch_json(tree_url, auth=True)
        files = [entry["path"].rsplit("/", 1)[-1] for entry in tree if entry.get("type") == "file"]
    except urllib.error.HTTPError:
        files = []
    codes = sorted({name.split(".", 1)[0] for name in files if name})
    return {
        "url": api,
        "gated": info.get("gated"),
        "card_languages": card_languages,
        "card_language_count": len(card_languages),
        "dev_split_codes": codes,
        "dev_split_code_count": len(codes),
    }


def source_bouquet() -> dict:
    """BOUQuET language and pair coverage, read from the public benchmark file listing.

    The data files are gated, but the file *names* are not, and each benchmark file is named
    ``<src>-<trg>.parquet`` under ``benchmark_data/<level>/<split>/``. So which languages are
    covered, at which level, in which split, and against which pivots can all be measured
    without credentials -- the same approach used for FLORES+, whose coverage also comes from
    a listing rather than from the data.

    Sentence counts are deliberately absent: they would require reading the gated files, and
    the audit records coverage that anyone can reproduce.
    """
    repo = "facebook/bouquet"
    api = f"https://huggingface.co/api/datasets/{repo}"
    info = _fetch_json(api + "?expand[]=cardData&expand[]=gated")
    card = (info.get("cardData") or {})
    card_languages = sorted(card.get("language") or [])
    entries = _fetch_tree(repo)
    pairs: dict[str, dict[str, list[str]]] = {}
    codes: set[str] = set()
    for entry in entries:
        path = entry.get("path", "")
        if entry.get("type") != "file" or not path.startswith("benchmark_data/"):
            continue
        parts = path.split("/")
        if len(parts) != 4 or not parts[3].endswith(".parquet"):
            continue
        _root, level, split, name = parts
        pair = name[: -len(".parquet")]
        if "-" not in pair:
            continue
        left, right = pair.split("-", 1)
        if not re.fullmatch(r"[a-z]{3}_[A-Za-z]{4}", left):
            continue
        if not re.fullmatch(r"[a-z]{3}_[A-Za-z]{4}", right):
            continue
        codes.update((left, right))
        pairs.setdefault(level, {}).setdefault(split, []).append(pair)
    if not codes:
        raise RuntimeError("no BOUQuET benchmark pairs parsed from the file listing")
    # One language appears under several scripts, so the bare ISO part is kept alongside the
    # full code: the audit joins on ISO 639-3.
    per_language: dict[str, list[str]] = {}
    for code in sorted(codes):
        per_language.setdefault(code.split("_", 1)[0], []).append(code)
    return {
        "url": f"https://huggingface.co/datasets/{repo}",
        "gated": info.get("gated"),
        "license": card.get("license"),
        "card_languages": card_languages,
        "card_language_count": len(card_languages),
        "codes": sorted(codes),
        "code_count": len(codes),
        "languages": per_language,
        "language_count": len(per_language),
        "levels": sorted(pairs),
        "splits": sorted({split for level in pairs.values() for split in level}),
        "pairs": {level: {split: sorted(found) for split, found in splits.items()}
                  for level, splits in pairs.items()},
        "pair_count": sum(len(found) for splits in pairs.values()
                          for found in splits.values()),
    }


def source_nllb200() -> dict:
    """NLLB-200 language tokens as shipped in the released model's tokenizer."""
    url = "https://huggingface.co/facebook/nllb-200-distilled-600M/raw/main/special_tokens_map.json"
    payload = _fetch_json(url)
    codes = [t for t in payload.get("additional_special_tokens", [])
             if re.fullmatch(r"[a-z]{3}_[A-Za-z]{4}", t)]
    return {"url": url, "codes": sorted(codes), "code_count": len(codes)}


# SMOL pairs every language with one of these as the other side of the pair.
SMOL_PIVOTS = {"en", "ar", "zh", "ru"}


def _smol_subset_sentences(counts: dict) -> dict:
    """Turn ``smolsent/en_glk.jsonl`` style counts into {subset: {language: sentences}}.

    Both directions of a pair are stored as separate files with the same number of lines,
    so the language is whichever side of the filename is not the pivot.
    """
    out: dict[str, dict[str, int]] = {}
    for path, total in counts.items():
        if total is None:
            continue
        subset, _, name = path.partition("/")
        stem = name.removesuffix(".jsonl")
        parts = stem.split("_")
        if len(parts) < 2:
            continue
        target = next((p for p in parts if p not in SMOL_PIVOTS), parts[-1])
        bucket = out.setdefault(subset, {})
        bucket[target] = max(bucket.get(target, 0), total)
    return out


def source_smol(workers: int = 8) -> dict:
    """Google SMOL: GATITOS lexicons, SMOLDOC documents and SMOLSENT sentences per language.

    The size endpoint reports only a fraction of SMOL's configs, so the sentence counts come
    from the repository files themselves: one line per sentence or document. GATITOS is a
    word-level lexicon rather than a sentence set, so it is recorded as coverage only.
    """
    url = "https://datasets-server.huggingface.co/splits?dataset=google%2Fsmol"
    payload = _fetch_json(url)
    configs = sorted({entry["config"] for entry in payload["splits"]})

    from huggingface_hub import HfApi

    sys.path.insert(0, str(ROOT / "scripts"))
    from hf_publishing_auth import publishing_token

    token = publishing_token()
    api = HfApi(token=token)
    repo_files = [
        name for name in api.list_repo_files("google/smol", repo_type="dataset")
        if name.endswith(".jsonl") and name.split("/", 1)[0] in {"smolsent", "smoldoc"}
    ]

    def line_count(path: str) -> tuple[str, int | None]:
        target = (
            "https://huggingface.co/datasets/google/smol/resolve/main/"
            + urllib.parse.quote(path)
        )
        try:
            blob = _retry(lambda: _fetch(target, auth=True, timeout=180), attempts=3)
        except Exception:  # noqa: BLE001 - an unreadable file is reported as unknown
            return path, None
        return path, sum(1 for line in blob.splitlines() if line.strip())

    counts: dict[str, int | None] = {}
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for done, (path, total) in enumerate(pool.map(line_count, repo_files), 1):
            counts[path] = total
            if done % 100 == 0:
                print(f"  smol files {done}/{len(repo_files)}", flush=True)
    subsets: dict[str, list[str]] = {"gatitos": [], "smoldoc": [], "smolsent": [], "other": []}
    for config in configs:
        kind, _, pair = config.partition("__")
        target = pair.split("_", 1)[-1] if pair.startswith("en_") else pair
        if kind in subsets and pair:
            subsets[kind].append(target)
        else:
            subsets["other"].append(config)
    return {
        "url": url,
        "configs": configs,
        "config_count": len(configs),
        "file_sentence_counts": counts,
        "files_without_count": sorted(k for k, v in counts.items() if v is None),
        "subset_sentences": _smol_subset_sentences(counts),
        "subsets": {k: sorted(set(v)) for k, v in subsets.items()},
        "subset_counts": {k: len(set(v)) for k, v in subsets.items()},
    }


def source_ntrex() -> dict:
    """NTREX-128: human news references translated out of English."""
    url = "https://raw.githubusercontent.com/MicrosoftTranslator/NTREX/main/LANGUAGES.tsv"
    text = _fetch_text(url)
    languages = {}
    for line in text.splitlines():
        parts = line.split("\t") if "\t" in line else line.split(None, 1)
        if len(parts) < 2:
            continue
        code = parts[0].strip()
        if not code:
            continue
        languages[code] = parts[1].strip()
    core, additional = [], []
    for directory, bucket in (("NTREX-128", core), ("NTREX-additional", additional)):
        try:
            listing = _fetch_json(
                "https://api.github.com/repos/MicrosoftTranslator/NTREX/contents/" + directory
            )
        except Exception:  # noqa: BLE001 - listing is a refinement, the TSV is the inventory
            continue
        for entry in listing:
            match = re.fullmatch(r"newstest2019-ref\.(.+)\.txt", entry.get("name", ""))
            if match:
                bucket.append(match.group(1))
    return {
        "url": url,
        "languages": languages,
        "language_count": len(languages),
        "core_reference_codes": sorted(core),
        "additional_reference_codes": sorted(additional),
    }


def source_sacrebleu() -> dict:
    """Every test set shipped by sacreBLEU (WMT, IWSLT, FLORES, NTREX, MTEDx, ...)."""
    sys.path.insert(0, str(ROOT))
    from sacrebleu.dataset import DATASETS

    testsets = {}
    for name, dataset in DATASETS.items():
        testsets[name] = {
            "description": getattr(dataset, "description", None),
            "langpairs": sorted(dataset.langpairs),
        }
    return {
        "url": "https://github.com/mjpost/sacrebleu",
        "testsets": testsets,
        "testset_count": len(testsets),
    }


def source_google_translate() -> dict:
    """Languages offered by the public Google Translate web endpoint."""
    url = "https://translate.googleapis.com/translate_a/l?client=gtx"
    payload = _fetch_json(url)
    source = {k: v for k, v in (payload.get("sl") or {}).items() if k != "auto"}
    target = payload.get("tl") or {}
    return {
        "url": url,
        "source_languages": source,
        "target_languages": target,
        "source_count": len(source),
        "target_count": len(target),
    }


def source_microsoft_translator() -> dict:
    """Languages offered by Microsoft Translator's public language endpoint."""
    url = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation,transliteration"
    payload = _fetch_json(url)
    translation = payload.get("translation") or {}
    return {
        "url": url,
        "translation": {k: v.get("name") for k, v in translation.items()},
        "translation_count": len(translation),
        "transliteration": sorted((payload.get("transliteration") or {}).keys()),
    }


def _hf_card_languages(dataset: str) -> dict:
    url = f"https://huggingface.co/api/datasets/{dataset}?expand[]=cardData"
    payload = _fetch_json(url)
    languages = (payload.get("cardData") or {}).get("language") or []
    if isinstance(languages, str):
        languages = [languages]
    return {"url": url, "languages": sorted(languages), "language_count": len(languages)}


def source_madlad400() -> dict:
    """MADLAD-400: web-crawled monolingual coverage used to train the MADLAD MT models.

    The card carries no machine-readable language list, so the per-language data
    directories in the repository are the inventory.
    """
    url = "https://huggingface.co/api/datasets/allenai/MADLAD-400/tree/main/data"
    tree = _fetch_json(url)
    languages = sorted(
        entry["path"].rsplit("/", 1)[-1]
        for entry in tree
        if entry.get("type") == "directory"
    )
    return {"url": url, "languages": languages, "language_count": len(languages)}


def source_glot500() -> dict:
    """Glot500-c: corpora assembled for 500+ language representation learning."""
    return _hf_card_languages("cis-lmu/Glot500")


def source_hplt2() -> dict:
    """HPLT v2 cleaned monolingual web corpora, one config per language and script."""
    url = "https://datasets-server.huggingface.co/splits?dataset=HPLT%2FHPLT2.0_cleaned"
    payload = _fetch_json(url)
    configs = sorted({entry["config"] for entry in payload["splits"]})
    return {"url": url, "configs": configs, "config_count": len(configs)}


_TATOEBA_ROW = re.compile(r"\[([a-z]{2,3}(?:_[A-Za-z]{4})?)-([a-z]{2,3}(?:_[A-Za-z]{4})?)\]")


def _tatoeba_subset(name: str) -> dict:
    url = f"https://raw.githubusercontent.com/Helsinki-NLP/Tatoeba-Challenge/master/data/subsets/{name}"
    text = _fetch_text(url)
    pairs = {}
    for line in text.splitlines():
        if not line.startswith("|"):
            continue
        match = _TATOEBA_ROW.search(line)
        if not match:
            continue
        cells = [cell.strip() for cell in line.strip("|").split("|")]
        numbers = []
        for cell in cells[1:]:
            digits = re.search(r"(\d[\d,]*)", cell)
            numbers.append(int(digits.group(1).replace(",", "")) if digits else None)
        while len(numbers) < 3:
            numbers.append(None)
        pairs[f"{match.group(1)}-{match.group(2)}"] = {
            "test": numbers[0], "dev": numbers[1], "train": numbers[2],
        }
    return {"url": url, "pairs": pairs, "pair_count": len(pairs)}


# The Tatoeba Challenge release this audit reads. Pinned so the pair listing and the
# downloaded test files always describe the same release.
TATOEBA_CHALLENGE_REVISION = "bd05f087e91e359a88594bd6d6c99a079e0ac621"


def _tatoeba_test_pairs(revision: str = TATOEBA_CHALLENGE_REVISION) -> dict:
    """Every language pair that actually ships a test file, from the repository tree.

    The tier tables under ``data/subsets`` bucket pairs by *training* size and between them
    list only a fraction of the release, so they cannot answer "does this pair have a test
    set at all": a pair with test data but no training data may appear in none of them.
    ``data/test/<pair>/test.txt`` is the authoritative answer.
    """
    url = (
        "https://api.github.com/repos/Helsinki-NLP/Tatoeba-Challenge/git/trees/"
        f"{revision}?recursive=1"
    )
    tree = _fetch_json(url)
    pairs = sorted(
        entry["path"].split("/")[2]
        for entry in tree.get("tree", [])
        if entry.get("path", "").startswith("data/test/")
        and entry["path"].endswith("/test.txt")
    )
    return {
        "url": url,
        "revision": revision,
        "truncated": bool(tree.get("truncated")),
        "pairs": pairs,
        "pair_count": len(pairs),
    }


def source_tatoeba_challenge() -> dict:
    """Tatoeba Challenge test-set inventory, training-size tiers and no-test-data lists."""
    tiers = ["zero.md", "lowest.md", "lower.md", "medium.md", "higher.md", "highest.md"]
    out = {"tiers": {}, "no_test_data": {}}
    for name in tiers:
        out["tiers"][name.removesuffix(".md")] = _retry(lambda n=name: _tatoeba_subset(n))
    for name in ("NoTestData.md", "NoTestData-eng.md"):
        out["no_test_data"][name.removesuffix(".md")] = _retry(lambda n=name: _tatoeba_subset(n))
    out["test_pairs"] = _retry(_tatoeba_test_pairs)
    out["url"] = "https://github.com/Helsinki-NLP/Tatoeba-Challenge"
    return out


def source_opus(codes=None, workers: int = 8) -> dict:
    """OPUS parallel-corpus inventory for each audited language code."""
    if codes is None:
        finewiki = load("finewiki")["configs"]
        codes = sorted(finewiki)
    base = "https://opus.nlpl.eu/opusapi/"

    def one(code: str) -> tuple[str, dict]:
        query = urllib.parse.urlencode(
            {"source": code, "preprocessing": "moses", "version": "latest"}
        )
        try:
            payload = _retry(lambda: _fetch_json(base + "?" + query, timeout=120), attempts=3)
        except Exception as error:  # noqa: BLE001
            return code, {"error": f"{type(error).__name__}: {error}"}
        entries = payload.get("corpora") or []
        partners: dict[str, int] = {}
        corpora: dict[str, int] = {}
        total = 0
        for entry in entries:
            pairs = int(entry.get("alignment_pairs") or 0)
            other = entry["target"] if entry["source"] == code else entry["source"]
            partners[other] = partners.get(other, 0) + pairs
            corpora[entry["corpus"]] = corpora.get(entry["corpus"], 0) + pairs
            total += pairs
        return code, {
            "entries": len(entries),
            "corpora": dict(sorted(corpora.items(), key=lambda kv: -kv[1])),
            "partner_languages": dict(sorted(partners.items(), key=lambda kv: -kv[1])),
            "total_alignment_pairs": total,
        }

    results: dict[str, dict] = {}
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(one, code) for code in codes]
        for done, future in enumerate(as_completed(futures), 1):
            code, value = future.result()
            results[code] = value
            if done % 50 == 0:
                print(f"  opus {done}/{len(codes)}", flush=True)
    return {"url": base, "languages": results, "language_count": len(results),
            "failed": sorted(k for k, v in results.items() if "error" in v)}


# Multilingual umbrella corpora: present for hundreds of languages, so their presence says
# nothing about whether anyone built a resource for a particular language.
UMBRELLA_DATASET_PREFIXES = (
    "wikimedia/", "legacy-datasets/wikipedia", "olm/wikipedia", "reyoung/wikipedia",
    "livinNector/wikipedia", "HuggingFaceFW/", "oscar-corpus/", "uonlp/CulturaX",
    "allenai/MADLAD-400", "allenai/c4", "cis-lmu/Glot500", "cis-lmu/GlotCC",
    "statmt/cc100", "mc4", "google/fleurs", "facebook/flores", "openlanguagedata/flores",
    "unimelb-nlp/wikiann", "tner/wikiann", "MartinThoma/wili_2018", "papluca/language-identification",
    "HPLT/", "data-is-better-together/fineweb-c", "wikipedia", "graelo/wikipedia",
)
# A translation dataset declaring more languages than this is a broad multilingual release,
# not evidence that anyone built a resource for one particular language.
FOCUSED_LANGUAGE_LIMIT = 25


def source_community_benchmarks() -> dict:
    """Curated parallel corpora and test sets the big catalogues do not list."""
    path = ROOT / "configs" / "community_benchmarks.json"
    payload = json.loads(path.read_text(encoding="utf-8"))
    by_language: dict[str, list[str]] = {}
    for benchmark in payload["benchmarks"]:
        for code in benchmark["languages"]:
            by_language.setdefault(code, []).append(benchmark["id"])
    payload["by_language"] = {k: sorted(v) for k, v in by_language.items()}
    payload["url"] = "configs/community_benchmarks.json"
    payload["benchmark_count"] = len(payload["benchmarks"])
    return payload


def source_hub_datasets(codes=None, workers: int = 10) -> dict:
    """Hugging Face Hub datasets tagged with each audited language.

    Answers whether anyone has published a dataset -- and specifically a
    translation dataset -- for a language, beyond the multilingual umbrella corpora.
    """
    if codes is None:
        finewiki = load("finewiki")["configs"]
        iso = load("iso639_3")
        aliases = {}
        for config in sorted(finewiki):
            candidates = {config, config.replace("_", "-")}
            three = iso["part1_to_part3"].get(config)
            if three:
                candidates.add(three)
            elif config in iso["codes"]:
                candidates.add(config)
                part1 = iso["codes"][config].get("part1")
                if part1:
                    candidates.add(part1)
            aliases[config] = sorted(c for c in candidates if 2 <= len(c) <= 8)
        codes = aliases
    base = "https://huggingface.co/api/datasets"

    def query(alias: str, translation_only: bool) -> tuple[list[str], str | None]:
        params = [("filter", f"language:{alias}"), ("limit", "100"), ("full", "false")]
        if translation_only:
            params.append(("filter", "task_categories:translation"))
        url = base + "?" + urllib.parse.urlencode(params)
        try:
            payload = _retry(lambda: _fetch_json(url, timeout=90), attempts=4)
        except Exception as error:  # noqa: BLE001 - distinguished from a genuine empty result
            return [], f"{type(error).__name__}: {error}"
        return [e["id"] for e in payload if isinstance(e, dict) and "id" in e], None

    def one(config: str, alias_list: list[str]) -> tuple[str, dict]:
        everything: set[str] = set()
        translation: set[str] = set()
        errors: list[str] = []
        for alias in alias_list:
            for translation_only, bucket in ((False, everything), (True, translation)):
                ids, error = query(alias, translation_only)
                bucket.update(ids)
                if error:
                    errors.append(f"language:{alias} translation={translation_only}: {error}")
        return config, {
            "aliases_queried": alias_list,
            "dataset_count": len(everything),
            "dataset_count_capped_at_100_per_alias": len(everything) >= 100,
            "translation_datasets": sorted(translation),
            "translation_dataset_count": len(translation),
            "errors": errors,
        }

    results: dict[str, dict] = {}
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(one, config, alias_list) for config, alias_list in codes.items()]
        for done, future in enumerate(as_completed(futures), 1):
            config, value = future.result()
            results[config] = value
            if done % 50 == 0:
                print(f"  hub {done}/{len(codes)}", flush=True)

    # A dataset that tags hundreds of languages says nothing about any one of them.
    # Classify each candidate once by how many languages its card declares.
    candidates = sorted({name for value in results.values() for name in value["translation_datasets"]})
    breadth: dict[str, int | None] = {}

    def language_breadth(dataset: str) -> tuple[str, int | None]:
        url = f"{base}/{dataset}?expand[]=cardData"
        try:
            payload = _retry(lambda: _fetch_json(url, timeout=90), attempts=3)
        except Exception:  # noqa: BLE001 - unknown breadth is recorded as None
            return dataset, None
        languages = (payload.get("cardData") or {}).get("language") or []
        if isinstance(languages, str):
            languages = [languages]
        return dataset, len(languages)

    print(f"  classifying {len(candidates)} candidate translation datasets", flush=True)
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for dataset, count in pool.map(language_breadth, candidates):
            breadth[dataset] = count

    for value in results.values():
        focused = sorted(
            name for name in value["translation_datasets"]
            if not name.startswith(UMBRELLA_DATASET_PREFIXES)
            and (breadth.get(name) is None or breadth[name] <= FOCUSED_LANGUAGE_LIMIT)
        )
        value["focused_translation_datasets"] = focused
        value["focused_translation_dataset_count"] = len(focused)

    failed = sorted(c for c, v in results.items() if v["errors"])
    return {
        "url": base,
        "umbrella_prefixes_excluded": list(UMBRELLA_DATASET_PREFIXES),
        "focused_language_limit": FOCUSED_LANGUAGE_LIMIT,
        "dataset_language_breadth": breadth,
        "languages": results,
        "language_count": len(results),
        "languages_with_errors": failed,
    }


# Translation and parallel-text benchmarks beyond the headline catalogues, including niche
# and regional ones. ``coverage`` says how a language's presence is established:
#   configs         - one config per language or language pair, matched on its codes
#   card_languages  - a single config; the card's language list establishes coverage and the
#                     split row counts give the per-language sentence count
#   none            - the server cannot read the repository (usually gated); access is
#                     recorded but coverage must come from another source
# ``splits`` maps the upstream split name to the role it actually plays, because some
# releases label an evaluation set "train".
BENCHMARK_REGISTRY = [
    {
        "id": "mteb/flores", "role": "evaluation", "access": "open",
        "coverage": "card_languages", "splits": {"dev": "dev", "devtest": "test"},
        # FLORES+ is the maintained continuation of FLORES-200 and carries the same dev and
        # devtest sentences, so reporting both would count one test set twice and double
        # every FLORES language's evaluation total. Only FLORES+ is reported as coverage;
        # this mirror is kept solely because it is the open source of those sentence counts.
        "reports_coverage": False,
        "note": "Open mirror of FLORES-200, retained only to supply the per-language "
                "sentence counts that the gated FLORES+ repository will not serve. Not "
                "reported as a resource in its own right: FLORES+ supersedes it and "
                "republishes the same sentences.",
    },
    {
        "id": "openlanguagedata/flores_plus", "role": "evaluation", "access": "gated_terms",
        "coverage": "none", "splits": {},
        "note": "Canonical FLORES+. Its language list comes from the dev file listing; the "
                "data files require accepting the repository terms.",
    },
    {
        "id": "facebook/bouquet", "role": "evaluation", "access": "gated_terms",
        "coverage": "none", "splits": {},
        "note": "BOUQuET: sentences and paragraphs written in the source language rather "
                "than translated out of English, with dev and test splits. Coverage comes "
                "from the public benchmark file listing, which names every language pair; "
                "the data files themselves are gated. The card claims more languages than "
                "the benchmark files cover, so the listing is the authority here.",
    },
    {
        "id": "mteb/NTREX", "role": "evaluation", "access": "open",
        "coverage": "card_languages", "splits": {"test": "test"},
        "note": "NTREX-128 news references translated out of English.",
    },
    {
        "id": "facebook/belebele", "role": "evaluation_parallel_non_mt", "access": "open",
        "coverage": "configs", "splits": {"test": "test"},
        "note": "Parallel reading-comprehension questions across 122 languages; parallel "
                "text usable for evaluation, though not an MT test set.",
    },
    {
        "id": "Davlan/sib200", "role": "evaluation_parallel_non_mt", "access": "open",
        "coverage": "configs",
        "splits": {"test": "test", "validation": "dev", "train": "train"},
        "note": "FLORES-derived topic classification in 205 languages; the sentences are "
                "parallel even though the task is not translation.",
    },
    {
        "id": "Helsinki-NLP/opus-100", "role": "mixed", "access": "open",
        "coverage": "configs",
        "splits": {"test": "test", "validation": "dev", "train": "train"},
        "note": "English-centric parallel corpus with official test and training splits.",
    },
    {
        "id": "gmnlp/tico19", "role": "evaluation", "access": "open", "coverage": "configs",
        "splits": {"test": "test", "validation": "dev"},
        "note": "TICO-19 public-health translation memories for 36 languages.",
    },
    {
        "id": "google/wmt24pp", "role": "evaluation", "access": "open", "coverage": "configs",
        "splits": {"train": "test"},
        "note": "WMT24++ human references for 55 English-source language and region pairs. "
                "The upstream split is labelled 'train' but the resource is an evaluation set.",
    },
    {
        "id": "openlanguagedata/oldi_seed", "role": "training", "access": "open",
        "coverage": "configs", "splits": {"train": "train"},
        "note": "OLDI seed corpus; professionally translated sentences intended as training "
                "seed data for new languages.",
    },
    {
        "id": "haoranxu/ALMA-Human-Parallel", "role": "training", "access": "open",
        "coverage": "configs", "splits": {"train": "train", "validation": "dev"},
        "note": "Human-written parallel data used to train the ALMA models.",
    },
    {
        "id": "bible-nlp/biblenlp-corpus", "role": "mixed", "access": "open",
        "coverage": "card_languages", "splits": {},
        "note": "Verse-aligned Bible translations in 800+ languages. The server cannot "
                "convert this repository, so sentence counts are not reported here.",
    },
    {
        "id": "Helsinki-NLP/tatoeba", "role": "mixed", "access": "open",
        "coverage": "card_languages", "splits": {},
        "note": "Raw Tatoeba sentence pairs. Per-pair counts come from the Tatoeba "
                "Challenge tables instead, which the server can read.",
    },
    {
        "id": "masakhane/mafand", "role": "mixed", "access": "open",
        "coverage": "card_languages", "splits": {},
        "note": "MAFAND-MT news translation for African languages.",
    },
    {
        "id": "indonlp/NusaX-MT", "role": "mixed", "access": "open",
        "coverage": "card_languages", "splits": {},
        "note": "NusaX parallel data for Indonesian regional languages.",
    },
    {
        "id": "Helsinki-NLP/tatoeba_mt", "role": "evaluation", "access": "gated_terms",
        "coverage": "none", "splits": {},
        "note": "Tatoeba MT benchmark. Requires accepting the repository terms; the "
                "Tatoeba Challenge tables provide the same per-pair test counts openly.",
    },
    {
        "id": "ai4bharat/IN22-Gen", "role": "evaluation", "access": "gated_terms",
        "coverage": "none", "splits": {},
        "note": "IN22 general-domain evaluation set for 22 Indian languages.",
    },
]


def source_hf_benchmarks(workers: int = 6) -> dict:
    """Location, access status and per-split sentence counts for each benchmark."""
    results = {}

    def one(entry: dict) -> tuple[str, dict]:
        dataset = entry["id"]
        record = {
            "id": dataset,
            "url": f"https://huggingface.co/datasets/{dataset}",
            "role": entry["role"],
            "declared_access": entry["access"],
            "coverage_mode": entry["coverage"],
            "split_roles": entry["splits"],
            # False when the repository is fetched only as a count mirror for another
            # release, so the audit must not report it as coverage of its own.
            "reports_coverage": entry.get("reports_coverage", True),
            "note": entry["note"],
            "configs": {},
            "card_languages": [],
            "per_language_rows": {},
            "errors": [],
        }
        try:
            info = _retry(
                lambda: _fetch_json(
                    f"https://huggingface.co/api/datasets/{dataset}"
                    "?expand[]=cardData&expand[]=gated&expand[]=private"
                ),
                attempts=3,
            )
            record["gated"] = info.get("gated")
            record["private"] = info.get("private")
            card = info.get("cardData") or {}
            languages = card.get("language") or []
            if isinstance(languages, str):
                languages = [languages]
            record["card_languages"] = sorted(languages)
            licence = card.get("license")
            record["license"] = licence[0] if isinstance(licence, list) and licence else licence
        except Exception as error:  # noqa: BLE001 - recorded, not fatal
            record["errors"].append(f"info: {type(error).__name__}: {error}")

        if entry["coverage"] != "none":
            query = urllib.parse.quote(dataset, safe="")
            try:
                size = _retry(
                    lambda: _fetch_json(
                        f"https://datasets-server.huggingface.co/size?dataset={query}",
                        timeout=120,
                    ),
                    attempts=3,
                )
                per_config: dict[str, dict] = {}
                for split in size["size"]["splits"]:
                    role = entry["splits"].get(split["split"])
                    if role is None:
                        continue
                    bucket = per_config.setdefault(split["config"], {})
                    bucket[role] = bucket.get(role, 0) + int(split["num_rows"])
                record["configs"] = per_config
                record["config_count"] = len(per_config)
                if entry["coverage"] == "card_languages":
                    totals: dict[str, int] = {}
                    for counts in per_config.values():
                        for role, rows in counts.items():
                            totals[role] = max(totals.get(role, 0), rows)
                    record["per_language_rows"] = totals
            except Exception as error:  # noqa: BLE001
                record["errors"].append(f"size: {type(error).__name__}: {error}")
        return dataset, record

    with ThreadPoolExecutor(max_workers=workers) as pool:
        for dataset, record in pool.map(one, BENCHMARK_REGISTRY):
            results[dataset] = record
    return {
        "url": "https://huggingface.co/datasets",
        "benchmarks": results,
        "benchmark_count": len(results),
        "unreadable": sorted(k for k, v in results.items() if v["errors"]),
    }


def repair_hub_datasets(workers: int = 4) -> dict:
    """Re-query only the languages and datasets the Hub pass failed to resolve.

    The Hub API rate-limits, so a first pass run alongside other downloads leaves holes.
    This fills them in place without re-querying what already succeeded.
    """
    record = json.loads(path_for("hub_datasets").read_text(encoding="utf-8"))
    data = record["data"]
    languages = data["languages"]
    breadth = data["dataset_language_breadth"]
    base = data["url"]

    broken = sorted(c for c, v in languages.items() if v.get("errors"))
    print(f"languages to re-query: {len(broken)}", flush=True)
    if broken:
        subset = {config: languages[config]["aliases_queried"] for config in broken}
        refreshed = source_hub_datasets(codes=subset, workers=workers)
        for config, value in refreshed["languages"].items():
            languages[config] = value
        breadth.update(
            {k: v for k, v in refreshed["dataset_language_breadth"].items() if v is not None}
        )

    unknown = sorted(k for k, v in breadth.items() if v is None)
    print(f"datasets with unresolved language breadth: {len(unknown)}", flush=True)

    def one(dataset: str):
        url = f"{base}/{dataset}?expand[]=cardData"
        try:
            payload = _retry(lambda: _fetch_json(url, timeout=120), attempts=4, delay=4.0)
        except Exception:  # noqa: BLE001 - still unknown; treated as not focused below
            return dataset, None
        value = (payload.get("cardData") or {}).get("language") or []
        if isinstance(value, str):
            value = [value]
        return dataset, len(value)

    if unknown:
        with ThreadPoolExecutor(max_workers=workers) as pool:
            for done, (dataset, count) in enumerate(pool.map(one, unknown), 1):
                breadth[dataset] = count
                if done % 100 == 0:
                    print(f"  breadth {done}/{len(unknown)}", flush=True)

    # Unknown breadth is treated as broad, so an unresolved card cannot inflate the
    # "somebody built this for one language" signal.
    for value in languages.values():
        focused = sorted(
            name for name in value["translation_datasets"]
            if not name.startswith(UMBRELLA_DATASET_PREFIXES)
            and breadth.get(name) is not None
            and breadth[name] <= FOCUSED_LANGUAGE_LIMIT
        )
        value["focused_translation_datasets"] = focused
        value["focused_translation_dataset_count"] = len(focused)

    data["dataset_language_breadth"] = breadth
    data["languages_with_errors"] = sorted(c for c, v in languages.items() if v.get("errors"))
    data["unresolved_dataset_breadth"] = sorted(k for k, v in breadth.items() if v is None)
    record["repaired_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
    path_for("hub_datasets").write_text(
        json.dumps(record, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )
    print(
        f"languages still failing: {len(data['languages_with_errors'])}  "
        f"breadth still unknown: {len(data['unresolved_dataset_breadth'])}",
        flush=True,
    )
    return data


SOURCES = {
    "finewiki": source_finewiki,
    "wikimedia_sitematrix": source_wikimedia_sitematrix,
    "wikistats": source_wikistats,
    "iso639_3": source_iso639_3,
    "iso639_macrolanguages": source_iso639_macrolanguages,
    "glottolog_languages": source_glottolog_languages,
    "glottolog_classification": source_glottolog_classification,
    "flores200": source_flores200,
    "flores_plus": source_flores_plus,
    "bouquet": source_bouquet,
    "nllb200": source_nllb200,
    "smol": source_smol,
    "ntrex": source_ntrex,
    "sacrebleu": source_sacrebleu,
    "google_translate": source_google_translate,
    "microsoft_translator": source_microsoft_translator,
    "madlad400": source_madlad400,
    "glot500": source_glot500,
    "hplt2": source_hplt2,
    "tatoeba_challenge": source_tatoeba_challenge,
    "community_benchmarks": source_community_benchmarks,
    "hf_benchmarks": source_hf_benchmarks,
    "opus": source_opus,
    "hub_datasets": source_hub_datasets,
}

# ``opus`` and ``hub_datasets`` need the FineWiki config list, so they run last.
DEFERRED = ("opus", "hub_datasets")
ORDER = [name for name in SOURCES if name not in DEFERRED] + list(DEFERRED)


def path_for(name: str) -> Path:
    return CACHE / f"{name}.json"


def load(name: str) -> dict:
    payload = json.loads(path_for(name).read_text(encoding="utf-8"))
    return payload["data"]


def fetch(name: str, *, refresh: bool = False) -> dict:
    CACHE.mkdir(parents=True, exist_ok=True)
    target = path_for(name)
    if target.exists() and not refresh:
        return json.loads(target.read_text(encoding="utf-8"))
    started = time.time()
    data = _retry(SOURCES[name])
    record = {
        "source": name,
        "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "seconds": round(time.time() - started, 1),
        "data": data,
    }
    target.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    return record


def fetch_all(names=None, refresh: bool = False) -> dict:
    summary = {}
    for name in names or ORDER:
        try:
            record = fetch(name, refresh=refresh)
            data = record["data"]
            counts = {k: v for k, v in data.items() if k.endswith("_count")}
            summary[name] = counts or {"keys": sorted(data)[:6]}
            print(f"[ok]  {name:26s} {counts or ''}", flush=True)
        except Exception as error:  # noqa: BLE001 - reported, not fatal for the other sources
            summary[name] = {"error": f"{type(error).__name__}: {error}"}
            print(f"[ERR] {name:26s} {error}", flush=True)
    return summary


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--only", action="append", choices=sorted(SOURCES), default=None)
    parser.add_argument("--refresh", action="store_true")
    parser.add_argument(
        "--repair-hub", action="store_true",
        help="re-query only the Hub languages and datasets a previous pass failed on",
    )
    args = parser.parse_args(argv)
    if args.repair_hub:
        repair_hub_datasets()
        return 0
    fetch_all(args.only, refresh=args.refresh)
    return 0


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