language-status / scripts /lang_audit_sources.py
nafisehNik's picture
Translation-resource audit of 325 FineWiki languages (finewiki_audit_20261115T012342Z)
5f12097 verified
Raw History Blame Contribute Delete
53.6 kB
"""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())
"""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"),