Datasets:
Translation-resource audit of 325 FineWiki languages (finewiki_audit_20261115T012342Z)
5317ec3 verified Download scripts/build_eval_corpus.py from sigiranic/language-status: direct link, hf CLI and curl.
- Browser
- Download file 74.2 kB
-
https://huggingface.co/datasets/sigiranic/language-status/resolve/main/scripts/build_eval_corpus.py
- Command line
-
hf download hf://datasets/sigiranic/language-status/scripts/build_eval_corpus.py
-
curl -L -o build_eval_corpus.py https://huggingface.co/datasets/sigiranic/language-status/resolve/main/scripts/build_eval_corpus.py
74.2 kB
"""Gather every human-created translation test set for the audit's shortlist languages.
One JSONL file per language in Google SMOL's ``smolsent`` shape, so that an existing SMOL
reader works unchanged:
{"sl": "en", "tl": "glk", "id": 0, "src": "...", "trg": "...", "is_src_orig": true}
with provenance fields added, because a record that cannot be traced back to its source and
licence is not usable evidence.
Only human-produced data is collected. Automatically mined or word-aligned material --
WikiMatrix, XLEnt, the projected training files shipped alongside xSID -- belongs in the
baseline training corpus, not in a test set.
Sources, each pinned to a revision and counted from the files themselves:
* Tatoeba Challenge ``data/test/<pair>/test.txt``, open, CC-BY-2.0-FR
* NTREX line-aligned references against the English source, open, CC-BY-SA-4.0
* xSID 0.6 manual translations of English voice-assistant utterances, CC-BY-SA-4.0
* NaLiBaSID extends xSID for Bavarian with MASSIVE translations, CC-BY-SA-4.0
* PARME English-Persian-X sentences for Middle Eastern languages, MIT
* SMOL (smolsent) professionally translated sentences, CC-BY-4.0
FLORES+ is deliberately *not* redistributed. Its access terms require agreeing "not to
re-host FLORES+ in places where it could be picked up by web crawlers", and a public dataset
repository is exactly such a place. Languages whose only test set is FLORES+ get
reference-only records: the language, split and row count, with the text withheld and a
pointer to the upstream repository. Keeping the rows makes the gap visible instead of making
those languages silently look untested.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import re
import sys
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ElementTree
import zipfile
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import shortlist_pivots as pivots # noqa: E402
from corpus_subsets import subset_name, write_subsets # noqa: E402
CACHE = ROOT / "cache" / "eval_corpus"
DIST = ROOT / "dist" / "eval_corpus"
USER_AGENT = "gilaki-eval-corpus/1.0 (+research use)"
TATOEBA_REVISION = "bd05f087e91e359a88594bd6d6c99a079e0ac621"
XSID_REVISION = "761d926c3f2e9f6bea13192d2f39cec1d04d9777"
NALIBASID_REVISION = "8d66b9021c06df1ab459636a925e119b2cff20fe"
NTREX_REVISION = "468c6b69c7f6a75d31d4743d9daba2af566cc18d"
PARME_REVISION = "6df9269acc75377ed6be3bf2f7966c8e238a62bd"
CODET_REVISION = "main"
DOLMA_BITEXT_REVISION = "main"
MAIBAAM_REVISION = "master"
UD_MEGRELIAN_REVISION = "dev"
NUSAX_REVISION = "main"
SHUD_REVISION = "master"
GIL1000_REVISION = "master"
# How freely a source may be passed on. The distinction is not cosmetic: a third of the
# resources found for these languages carry no licence at all, and several of the best ones
# are explicitly non-commercial or no-derivatives. Publishing them all under one licence
# field would misrepresent every tier but the first.
#
# 1 redistributable: a licence that permits republishing the text.
# 2 restricted: republishable only under a condition that limits reuse (non-commercial).
# 3 reference only: no licence stated, no-derivatives, or an explicit request not to
# redistribute. Ids and counts are published; the text is withheld.
TIER_REDISTRIBUTABLE, TIER_RESTRICTED, TIER_REFERENCE = 1, 2, 3
SOURCE_META = {
"tatoeba_challenge": {
"url": "https://github.com/Helsinki-NLP/Tatoeba-Challenge",
"revision": TATOEBA_REVISION, "licence": "CC-BY-2.0-FR",
"domain": "crowd_sentences",
"note": "Crowd-contributed sentences from Tatoeba, held out as the Challenge test split.",
},
"ntrex": {
"url": "https://github.com/MicrosoftTranslator/NTREX",
"revision": NTREX_REVISION, "licence": "CC-BY-SA-4.0", "domain": "news",
"note": "NTREX-128 news references, professionally translated out of English. The "
"Swiss German references live in NTREX-additional and are absent from the "
"mteb/NTREX mirror.",
},
"xsid": {
"url": "https://github.com/mainlp/xsid",
"revision": XSID_REVISION, "licence": "CC-BY-SA-4.0", "domain": "voice_assistant",
"note": "Manual translations of the same English digital-assistant utterances into "
"each language. Short imperative commands, not general prose.",
},
"nalibasid": {
"url": "https://github.com/mainlp/NaLiBaSID",
"revision": NALIBASID_REVISION, "licence": "CC-BY-SA-4.0", "domain": "voice_assistant",
"note": "Extends xSID for Bavarian with manual translations of part of MASSIVE. The "
"xMAS files are the de-duplicated union of both, so they are read instead of "
"the parts to avoid counting the same sentence twice.",
},
"parme": {
"url": "https://github.com/DOLMA-NLP/PARME",
"revision": PARME_REVISION, "licence": "MIT", "domain": "mixed",
"note": "Human English-Persian-X sentences for under-represented Middle Eastern "
"languages, with official held-out test and validation splits.",
},
"smol": {
"url": "https://huggingface.co/datasets/google/smol",
"revision": "main", "licence": "CC-BY-4.0", "domain": "mixed",
"note": "Professionally translated sentences. Released by Google as training data; "
"collected here as evaluation material by explicit choice, so scores on it "
"are not comparable with systems that trained on it.",
},
"flores_plus": {
"url": "https://huggingface.co/datasets/openlanguagedata/flores_plus",
"revision": "main", "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
"note": "Text withheld. Access requires agreeing not to re-host FLORES+ where web "
"crawlers could reach it, which a public dataset repository would do. Fetch "
"it from the upstream repository after accepting its terms.",
"tier": TIER_REFERENCE,
"restriction": "Terms forbid re-hosting where web crawlers could reach it.",
},
"bouquet": {
"url": "https://huggingface.co/datasets/facebook/bouquet",
"revision": "main", "licence": "CC-BY-4.0", "domain": "mixed",
"note": "Human-authored sentences and paragraphs, written in the source language "
"rather than translated from English, with official dev and test splits. "
"Carries paragraph ids, so it is the only source here with recoverable "
"document structure. Released for evaluation, not training.",
"tier": TIER_REDISTRIBUTABLE,
},
"codet": {
"url": "https://github.com/mahfuzibnalam/dialect_mt",
"revision": CODET_REVISION, "licence": "MIT", "domain": "elicited_syntax",
"note": "Italian Syntactic Atlas sentences elicited from speakers in 439 localities, "
"each file positionally aligned to the same 792 standard Italian sentences. "
"Sparsely filled, so a locality contributes only the lines it answered.",
"tier": TIER_REDISTRIBUTABLE,
},
"dolma_bitext": {
"url": "https://github.com/DOLMA-NLP/bitext-mining",
"revision": DOLMA_BITEXT_REVISION, "licence": "CC-BY-4.0", "domain": "mixed",
"note": "Manually aligned sentence pairs from published translations, by the group "
"behind PARME. The licence adds one term: the data must not be used to "
"reconstruct the original literary works, which sentence-level use satisfies.",
"tier": TIER_REDISTRIBUTABLE,
},
"nllb_seed": {
"url": "https://github.com/facebookresearch/flores/tree/main/nllb_seed",
"revision": "main", "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
"note": "Professionally translated seed sentences. A separate artefact from the "
"NLLB-200 mined bitext that the baseline corpus classifies as auto_mined.",
"tier": TIER_REDISTRIBUTABLE,
},
"nusax": {
"url": "https://github.com/IndoNLP/nusax",
"revision": NUSAX_REVISION, "licence": "CC-BY-SA-4.0", "domain": "mixed",
"note": "Twelve-way parallel sentences for Indonesian local languages, translated by "
"native speakers, with official train/valid/test splits.",
"tier": TIER_REDISTRIBUTABLE,
},
"maibaam": {
"url": "https://github.com/UniversalDependencies/UD_Bavarian-MaiBaam",
"revision": MAIBAAM_REVISION, "licence": "CC-BY-SA-4.0", "domain": "wiki_general",
"note": "English sentence translations carried as '# text_en' comments on part of "
"the Bavarian treebank. Only 59 of 1,070 sentences have one.",
"tier": TIER_REDISTRIBUTABLE,
},
"ud_shanghainese": {
"url": "https://github.com/UniversalDependencies/UD_Shanghainese-ShUD",
"revision": "master", "licence": "CC-BY-SA-4.0", "domain": "spoken",
"note": "Mandarin translations carried as '# text_cmn' on the Shanghainese treebank, "
"with official train/dev/test splits. The only Wu-Mandarin sentence "
"alignment found with splits; UD files Wu under 'Shanghainese'.",
"tier": TIER_REDISTRIBUTABLE,
},
"ud_megrelian": {
"url": "https://github.com/UniversalDependencies/UD_Megrelian-MLC",
"revision": UD_MEGRELIAN_REVISION, "licence": "CC-BY-SA-4.0", "domain": "mixed",
"note": "English translations carried as '# text_en' on the Megrelian treebank. Only "
"on the dev branch; the dependency columns are empty for every token, so it "
"is a translated morphology set rather than a usable treebank.",
"tier": TIER_REDISTRIBUTABLE,
},
"nsanku": {
"url": "https://github.com/GhanaNLP/nsanku",
"revision": "main", "licence": "none stated", "domain": "religious",
"note": "Human Dagbani-English reference pairs used as the evaluation set of Ghana "
"NLP's 43-language study. Text withheld: the repository ships no licence and "
"the underlying Bible translation is a Bible society copyright.",
"tier": TIER_REFERENCE,
"restriction": "No licence file in the repository; underlying text is copyrighted.",
},
"betthupferl": {
"url": "https://github.com/mainlp/betthupferl",
"revision": "main", "licence": "none stated", "domain": "narrative",
"note": "Human-transcribed and human-standardised Bavarian, Swabian and East "
"Franconian against Standard German. Text withheld: the archives are "
"password-protected and the authors ask that the data not be redistributed.",
"tier": TIER_REFERENCE,
"restriction": "Authors explicitly request no redistribution.",
},
"ladin_frontull": {
"url": "https://huggingface.co/sfrontull",
"revision": "main", "licence": "CC-BY-NC-SA-4.0", "domain": "mixed",
"note": "Italian-Ladin and intra-Ladin corpora. Non-commercial, so usable for "
"evaluation but not in a commercial system.",
"tier": TIER_RESTRICTED,
"restriction": "Non-commercial use only.",
},
"glotstorybook": {
"url": "https://huggingface.co/datasets/cis-lmu/GlotStoryBook",
"revision": "main", "licence": "CC-BY", "domain": "narrative",
"note": "African Storybook texts translated by named community translators, aligned "
"to English through each story's parallel id. Licensing is per row, so only "
"the plain CC-BY stories are taken.",
"tier": TIER_REDISTRIBUTABLE,
},
"gil1000": {
"url": "https://github.com/LordArma/Top-1000-Words-in-Gilaki",
"revision": GIL1000_REVISION, "licence": "GPL-3.0",
"domain": "dictionary_examples",
"note": "Example sentences from the Top 1000 Words in Gilaki project, also published "
"at https://gil1000.ir/. Each entry is written in Gilaki first and then "
"rendered in Persian and English, so the Gilaki side is the original. "
"Dictionary examples rather than running text, and the same sentences appear "
"in the lexicon corpus, so a score here is not comparable with a general "
"benchmark and is not independent of that corpus.",
"tier": TIER_RESTRICTED,
"restriction": "GPL-3.0: derived distributions inherit copyleft terms.",
},
"mlc": {
"url": "https://xmf.iliauni.edu.ge/",
"revision": "v1 (fieldwork 2022-2024)", "licence": "CC-BY-NC-SA-4.0",
"domain": "spoken",
"note": "Megrelian Language Corpus: oral texts recorded in Samegrelo and transcribed "
"in Georgian script, each phrase glossed into both Georgian and English. The "
"only source that pairs Megrelian with Georgian, its closest high-resource "
"relative, in any quantity. Cite Gersamia, R. and Lobzhanidze, I. (eds.), "
"Megrelian Language Corpus, Ilia State University.",
"tier": TIER_RESTRICTED,
"restriction": "Non-commercial use only, and derivatives inherit share-alike terms.",
},
"ladin_weather": {
"url": "https://huggingface.co/datasets/sfrontull/south-tyrol-weather-lld-deu",
"revision": "main", "licence": "CC-BY-SA-4.0", "domain": "weather",
"note": "South Tyrol meteorological office bulletins in Ladin and German, with an "
"official test split. The only Ladin set paired with German rather than "
"Italian.",
"tier": TIER_REDISTRIBUTABLE,
},
}
for _name, _meta in SOURCE_META.items():
_meta.setdefault("tier", TIER_REDISTRIBUTABLE)
_meta.setdefault("restriction", None)
# xSID ships automatically word-aligned projections next to the human translations; they are
# training material and must never enter a test set.
XSID_EXCLUDED = ("projectedTrain",)
# ------------------------------------------------------------------------------- fetching
def _get(url: str, *, auth: bool = False, timeout: int = 180) -> bytes:
headers = {"User-Agent": USER_AGENT}
if auth:
from hf_publishing_auth import publishing_token
headers["Authorization"] = f"Bearer {publishing_token()}"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.read()
def fetch(url: str, *, auth: bool = False, attempts: int = 4) -> bytes | None:
"""Download with a local cache; ``None`` when the file genuinely does not exist."""
key = hashlib.sha256(url.encode()).hexdigest()[:24]
path = CACHE / "raw" / key
marker = CACHE / "raw" / f"{key}.missing"
if path.exists():
return path.read_bytes()
if marker.exists():
return None
path.parent.mkdir(parents=True, exist_ok=True)
delay = 2.0
for attempt in range(attempts):
try:
payload = _get(url, auth=auth)
except urllib.error.HTTPError as error:
if error.code in (401, 403, 404):
marker.write_text(f"{error.code} {error.reason}\n{url}\n", encoding="utf-8")
return None
if attempt == attempts - 1:
raise
except Exception:
if attempt == attempts - 1:
raise
else:
path.write_bytes(payload)
return payload
time.sleep(delay)
delay *= 2
return None
# ------------------------------------------------------------------------------- parsing
def _clean(text: str) -> str:
# Collapses runs of whitespace only. ZWNJ (U+200C) is a format character, not
# whitespace, so Persian and Gilaki word-internal joins survive.
return re.sub(r"\s+", " ", (text or "").strip())
def norm_key(text: str) -> str:
"""Comparison key for de-duplication: case and punctuation-spacing insensitive."""
folded = unicodedata.normalize("NFKC", (text or "")).casefold()
return re.sub(r"[^\w]+", "", folded, flags=re.UNICODE)
def parse_conll_sentences(text: str) -> list[dict]:
"""Sentence records from an xSID or NaLiBaSID conll file.
The two projects use different separators for the same comment keys -- xSID writes
``# text = x`` and NaLiBaSID writes ``# text: x`` -- so both are accepted.
"""
out = []
current: dict[str, str] = {}
for line in text.splitlines():
if line.startswith("#"):
body = line[1:].strip()
match = re.match(r"([A-Za-z0-9_\-]+)\s*[:=]\s*(.*)$", body)
if match:
current[match.group(1).strip().lower()] = match.group(2).strip()
continue
if not line.strip():
if current:
out.append(current)
current = {}
if current:
out.append(current)
return [record for record in out if record.get("text")]
def parse_tatoeba_test(text: str) -> list[dict]:
"""Rows of a Tatoeba Challenge ``test.txt``: srclang, trglang, source, target."""
rows = []
for line in text.splitlines():
if not line.strip():
continue
parts = line.split("\t")
if len(parts) < 4:
continue
rows.append({
"src_lang": parts[0].strip(),
"trg_lang": parts[1].strip(),
"src": parts[2],
"trg": parts[3],
})
return rows
def parse_parme(text: str) -> list[dict]:
"""Rows of a PARME ``datasets/<LANG>-{test,val}.tsv``."""
reader = csv.DictReader(io.StringIO(text), delimiter="\t")
rows = []
for row in reader:
target = (row.get("translation") or "").strip()
if not target:
continue
rows.append({
"en": (row.get("en_sentence") or "").strip(),
"fa": (row.get("fa_sentence") or "").strip(),
"trg": target,
"variety": (row.get("variety (Western Gilaki|Eastern Gilaki)")
or row.get("variety") or "").strip() or None,
})
return rows
# ------------------------------------------------------------------------------- records
def make_record(*, pivot_config, target_config, src, trg, source, split,
is_src_orig=None, extra=None):
meta = SOURCE_META[source]
record = {
# SMOL smolsent keys, in SMOL's own order.
"sl": pivot_config,
"tl": target_config,
"id": None, # assigned once the language's records are ordered
"src": _clean(src),
"trg": _clean(trg),
}
if is_src_orig is not None:
record["is_src_orig"] = is_src_orig
record.update({
"split": split,
"source": source,
"source_revision": meta["revision"],
"licence": meta["licence"],
"domain": meta["domain"],
"licence_tier": meta["tier"],
"licence_restriction": meta["restriction"],
})
if extra:
record.update(extra)
if meta["tier"] == TIER_REFERENCE:
# Counted and attributable, but the text itself is not ours to pass on.
record["src"], record["trg"] = "", ""
record["text_withheld"] = True
return record
# ------------------------------------------------------------------------------ collectors
def collect_tatoeba(targets, rows, iso2cfg, pairs):
"""Tatoeba Challenge test splits for every acceptable pair of each target."""
out, skipped = [], []
for config in targets:
iso = rows[config]["iso639_3"]
if not iso:
continue
for pair in pairs:
left, _, right = pair.partition("-")
if iso not in (left, right):
continue
other = right if left == iso else left
if other == iso:
continue # same-language pair, not a translation direction
pivot_config = iso2cfg.get(other) or other
ok, _reason = pivots.acceptable_pivot(config, pivot_config, rows)
if not ok:
skipped.append({"target": config, "pair": pair, "reason": "pivot not acceptable"})
continue
url = ("https://raw.githubusercontent.com/Helsinki-NLP/Tatoeba-Challenge/"
f"{TATOEBA_REVISION}/data/test/{pair}/test.txt")
payload = fetch(url)
if not payload:
skipped.append({"target": config, "pair": pair, "reason": "test.txt not fetchable"})
continue
for row in parse_tatoeba_test(payload.decode("utf-8", "replace")):
# Columns are (src_lang, trg_lang, src, trg); orient so the target language
# is always on the target side.
if row["trg_lang"].split("_")[0] == iso:
src, trg = row["src"], row["trg"]
elif row["src_lang"].split("_")[0] == iso:
src, trg = row["trg"], row["src"]
else:
continue
if not src.strip() or not trg.strip():
continue
out.append(make_record(
pivot_config=pivot_config, target_config=config, src=src, trg=trg,
source="tatoeba_challenge", split="test",
extra={"source_pair": pair},
))
return out, skipped
def collect_ntrex(targets, rows):
"""NTREX references, line-aligned against the English source."""
base = f"https://raw.githubusercontent.com/MicrosoftTranslator/NTREX/{NTREX_REVISION}"
english = fetch(f"{base}/NTREX-128/newstest2019-src.eng.txt")
if not english:
return [], [{"reason": "NTREX English source not fetchable"}]
source_lines = english.decode("utf-8", "replace").splitlines()
out, skipped = [], []
for config in targets:
iso = rows[config]["iso639_3"]
if not iso or not rows[config]["in_ntrex"]:
continue
candidates = [f"NTREX-128/newstest2019-ref.{iso}.txt"]
# Some varieties are only in NTREX-additional, under a region-tagged name.
candidates += [f"NTREX-additional/newstest2019-ref.{iso}-{region}.txt"
for region in ("BE", "ZH", "CH", "AT")]
found = False
for relative in candidates:
payload = fetch(f"{base}/{relative}")
if not payload:
continue
found = True
variant = relative.rsplit("/", 1)[-1].removeprefix("newstest2019-ref.").removesuffix(".txt")
target_lines = payload.decode("utf-8", "replace").splitlines()
if len(target_lines) != len(source_lines):
skipped.append({"target": config, "file": relative,
"reason": f"line count {len(target_lines)} != "
f"English {len(source_lines)}"})
continue
for src, trg in zip(source_lines, target_lines):
if not src.strip() or not trg.strip():
continue
out.append(make_record(
pivot_config="en", target_config=config, src=src, trg=trg,
source="ntrex", split="test", is_src_orig=True,
extra={"variety": variant},
))
if not found:
skipped.append({"target": config, "reason": "no NTREX reference file found"})
return out, skipped
def _sid_records(text, target_config, source, split, pivot_keys):
"""Shared xSID/NaLiBaSID record extraction. ``pivot_keys`` maps comment key -> pivot."""
out = []
for record in parse_conll_sentences(text):
target = record.get("text")
if not target:
continue
for key, pivot_config in pivot_keys.items():
src = record.get(key)
if not src:
continue
out.append(make_record(
pivot_config=pivot_config, target_config=target_config, src=src, trg=target,
source=source, split=split, is_src_orig=(pivot_config == "en"),
))
return out
def collect_xsid(rows):
"""xSID 0.6 human translations for the varieties that map onto shortlist wikis."""
base = f"https://raw.githubusercontent.com/mainlp/xsid/{XSID_REVISION}/data/xSID-0.6"
# xSID's own language labels -> FineWiki config. de-st (South Tyrolean) has no wiki.
mapping = {"de-ba": "bar", "gsw": "als", "nap": "nap"}
out, skipped = [], []
for label, config in mapping.items():
if config not in rows:
continue
for upstream_split, split in (("test", "test"), ("valid", "dev")):
name = f"{label}.{upstream_split}.conll"
if any(token in name for token in XSID_EXCLUDED):
continue
payload = fetch(f"{base}/{name}")
if not payload:
skipped.append({"target": config, "file": name, "reason": "not fetchable"})
continue
out += _sid_records(
payload.decode("utf-8", "replace"), config, "xsid", split,
{"text-en": "en", "text-de": "de"},
)
return out, skipped
def collect_nalibasid(rows):
"""NaLiBaSID Bavarian translations, read from the de-duplicated xMAS union."""
base = (f"https://raw.githubusercontent.com/mainlp/NaLiBaSID/{NALIBASID_REVISION}/data")
out, skipped = [], []
if "bar" not in rows:
return out, skipped
for upstream_split, split in (("test", "test"), ("valid", "dev")):
name = f"de-ba.xMAS.{upstream_split}.conll"
payload = fetch(f"{base}/{name}")
if not payload:
skipped.append({"target": "bar", "file": name, "reason": "not fetchable"})
continue
out += _sid_records(
payload.decode("utf-8", "replace"), "bar", "nalibasid", split, {"text-en": "en"},
)
# de-ba.nat is speaker-produced with no English source, so it is not parallel data.
return out, skipped
def collect_parme(rows):
"""PARME test and validation splits, which carry both English and Persian sources."""
base = f"https://raw.githubusercontent.com/DOLMA-NLP/PARME/{PARME_REVISION}/datasets"
mapping = {"GLK": "glk", "MZN": "mzn"}
out, skipped = [], []
for label, config in mapping.items():
if config not in rows:
continue
for upstream_split, split in (("test", "test"), ("val", "dev")):
payload = fetch(f"{base}/{label}-{upstream_split}.tsv")
if not payload:
skipped.append({"target": config, "file": f"{label}-{upstream_split}.tsv",
"reason": "not fetchable"})
continue
for row in parse_parme(payload.decode("utf-8", "replace")):
for pivot_config, src in (("en", row["en"]), ("fa", row["fa"])):
if not src:
continue
ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
if not ok:
continue
out.append(make_record(
pivot_config=pivot_config, target_config=config, src=src,
trg=row["trg"], source="parme", split=split,
extra={"variety": row["variety"]},
))
return out, skipped
def collect_smol(targets, rows):
"""SMOL smolsent, already in the output shape."""
out, skipped = [], []
for config in targets:
if not rows[config]["in_smol_smolsent"]:
continue
iso = rows[config]["iso639_3"]
payload = fetch(
f"https://huggingface.co/datasets/google/smol/resolve/main/smolsent/en_{iso}.jsonl"
)
if not payload:
skipped.append({"target": config, "reason": f"smolsent/en_{iso}.jsonl not fetchable"})
continue
for line in payload.decode("utf-8", "replace").splitlines():
if not line.strip():
continue
row = json.loads(line)
if not row.get("src") or not row.get("trg"):
continue
out.append(make_record(
pivot_config="en", target_config=config, src=row["src"], trg=row["trg"],
source="smol", split="test", is_src_orig=row.get("is_src_orig"),
extra={"released_as": "training", "upstream_id": row.get("id")},
))
return out, skipped
def collect_flores_reference(targets, rows):
"""Reference-only rows for languages whose test set is the non-redistributable FLORES+."""
out = []
for config in targets:
if not rows[config]["in_flores_plus"]:
continue
iso = rows[config]["iso639_3"]
for split, count in (("dev", 997), ("test", 1012)):
# Built through make_record like every other source, so that withheld rows carry
# the same tier fields and the same empty-string convention as the others rather
# than a second, nearly-identical shape.
out.append(make_record(
pivot_config="en", target_config=config, src="", trg="",
source="flores_plus", split=split,
extra={"upstream_rows": count,
"upstream_file":
f"{'dev' if split == 'dev' else 'devtest'}/{iso}_*.jsonl"},
))
return out
# ------------------------------------------------------------------------------- assembly
# BOUQuET codes its languages with a script tag; these are the ones that matter here, both
# for our targets and for the pivots they are paired with.
BOUQUET_TARGETS = {"azb": "azb_Arab", "skr": "skr_Arab", "wuu": "wuu_Hans"}
BOUQUET_PIVOTS = {"eng_Latn": "en", "pes_Arab": "fa", "hin_Deva": "hi", "cmn_Hans": "zh"}
def collect_bouquet(targets, rows):
"""BOUQuET dev and test, at sentence and paragraph level.
The only source here that is not translated out of English: every passage was written in
one of the languages and then translated outwards. It also carries ``par_id``, so a
sentence can be traced back to the paragraph it came from -- the one piece of document
structure in the whole collection.
"""
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from hf_publishing_auth import publishing_token
out, skipped = [], []
token = publishing_token()
for config, tagged in BOUQUET_TARGETS.items():
if config not in targets:
continue
for pivot_tag, pivot_config in BOUQUET_PIVOTS.items():
ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
if not ok:
skipped.append({"target": config, "pair": f"{pivot_tag}-{tagged}",
"reason": "pivot not acceptable", "source": "bouquet"})
continue
for level in ("sentence_level", "paragraph_level"):
for upstream, split in (("dev", "dev"), ("test", "test")):
name = (f"benchmark_data/{level}/{upstream}/{pivot_tag}-{tagged}.parquet")
try:
path = hf_hub_download("facebook/bouquet", name,
repo_type="dataset", token=token)
except Exception as error: # noqa: BLE001 - absent pair or no access
skipped.append({"target": config, "pair": name,
"reason": f"{type(error).__name__}",
"source": "bouquet"})
continue
table = pq.read_table(
path, columns=["src_text", "tgt_text", "par_id", "domain", "register"]
)
for src, trg, par_id, domain, register in zip(
table.column("src_text").to_pylist(),
table.column("tgt_text").to_pylist(),
table.column("par_id").to_pylist(),
table.column("domain").to_pylist(),
table.column("register").to_pylist(),
):
if not (src or "").strip() or not (trg or "").strip():
continue
out.append(make_record(
pivot_config=pivot_config, target_config=config,
src=src, trg=trg, source="bouquet", split=split,
is_src_orig=None,
extra={"text_unit": level.replace("_level", ""),
"document_id": str(par_id) if par_id is not None else None,
"domain": domain,
"released_as": "evaluation"},
))
return out, skipped
# CODET publishes one file per locality, named for the place rather than the language, so the
# mapping from place to ISO code has to be stated. Only localities whose variety is one of our
# targets are listed; the atlas covers 439 in total.
CODET_LOCALITIES = {
"nap": ["Marcianise", "Montella", "Napoli", "Ariano%20Irpino", "Gragnano", "Salerno",
"Torre%20del%20Greco", "Carife", "Trevico", "Calitri", "Bagnoli%20Irpino",
"Montecalvo%20Irpino", "Scampitella", "Cardito1", "Cardito2", "Cardito3",
"Cardito4"],
"lld": ["Corvara", "Selva%20di%20Val%20Gardena", "Pozza%20di%20Fassa", "Ortisei"],
"pms": ["Torino", "Torino1", "Borgomanero", "Alba", "Mondovi", "Moncalieri", "Poirino",
"Novi%20Ligure", "Trecate", "Borgofranco%20d%27Ivrea", "Tollegno",
"Rivarossa%20Canavese"],
"eml": ["Bologna1", "Bologna2", "Carpi", "Ferrara1", "Mantova", "Bondeno",
"Bagnolo%20S.%20Vito", "Casalmaggiore", "Luzzara", "Redondesco", "Campagnola",
"Forli", "Forl%C3%AC", "Cesena2", "Rimini"],
}
def collect_codet(targets, rows):
"""CODET's Italian Syntactic Atlas files, aligned by line against standard Italian."""
base = ("https://raw.githubusercontent.com/mahfuzibnalam/dialect_mt/"
f"{CODET_REVISION}/Italian")
standard = fetch(f"{base}/Standard.ita")
out, skipped = [], []
if not standard:
return out, [{"target": None, "pair": "Standard.ita",
"reason": "not fetchable", "source": "codet"}]
reference = standard.decode("utf-8", "replace").splitlines()
ok, _why = pivots.acceptable_pivot("nap", "it", rows)
if not ok:
return out, [{"target": None, "pair": "it", "reason": "pivot not acceptable",
"source": "codet"}]
for config, localities in CODET_LOCALITIES.items():
if config not in targets:
continue
for locality in localities:
payload = fetch(f"{base}/{locality}.ita")
if not payload:
skipped.append({"target": config, "pair": f"{locality}.ita",
"reason": "not fetchable", "source": "codet"})
continue
lines = payload.decode("utf-8", "replace").splitlines()
if len(lines) != len(reference):
# Alignment here is purely positional, so a different length means the file
# cannot be trusted against the standard text at all.
skipped.append({"target": config, "pair": f"{locality}.ita",
"reason": f"{len(lines)} lines against "
f"{len(reference)} standard",
"source": "codet"})
continue
name = urllib.parse.unquote(locality)
for index, (dialect, italian) in enumerate(zip(lines, reference)):
if not dialect.strip() or not italian.strip():
continue
out.append(make_record(
pivot_config="it", target_config=config, src=italian, trg=dialect,
source="codet", split="test", is_src_orig=True,
extra={"variety": name, "upstream_id": index},
))
return out, skipped
def collect_dolma_bitext(targets, rows):
"""DOLMA-NLP's manually aligned pairs: the first human Gilaki sentence bitext."""
base = ("https://raw.githubusercontent.com/DOLMA-NLP/bitext-mining/"
f"{DOLMA_BITEXT_REVISION}/datasets/manually-aligned")
out, skipped = [], []
for config, filename in (("glk", "GLK-EN.tsv"), ("mzn", "MZN-EN.tsv")):
if config not in targets:
continue
payload = fetch(f"{base}/{filename}")
if not payload:
skipped.append({"target": config, "pair": filename,
"reason": "not fetchable", "source": "dolma_bitext"})
continue
ok, _why = pivots.acceptable_pivot(config, "en", rows)
if not ok:
continue
lines = payload.decode("utf-8", "replace").splitlines()
for index, line in enumerate(lines[1:]): # first line is the header
parts = line.split("\t")
if len(parts) < 2 or not parts[0].strip() or not parts[1].strip():
continue
out.append(make_record(
pivot_config="en", target_config=config, src=parts[0], trg=parts[1],
source="dolma_bitext", split="test", extra={"upstream_id": index},
))
return out, skipped
def collect_nllb_seed(targets, rows):
"""NLLB-Seed's professionally translated sentences, for Buginese."""
out, skipped = [], []
if "bug" not in targets:
return out, skipped
ok, _why = pivots.acceptable_pivot("bug", "en", rows)
if not ok:
return out, skipped
payload = fetch("https://dl.fbaipublicfiles.com/nllb/NLLB-Seed.zip")
if not payload:
return out, [{"target": "bug", "pair": "NLLB-Seed.zip",
"reason": "not fetchable", "source": "nllb_seed"}]
try:
archive = zipfile.ZipFile(io.BytesIO(payload))
except zipfile.BadZipFile:
return out, [{"target": "bug", "pair": "NLLB-Seed.zip",
"reason": "not a zip", "source": "nllb_seed"}]
names = archive.namelist()
left = next((n for n in names if n.endswith("/eng_Latn") and "bug_Latn" in n), None)
right = next((n for n in names if n.endswith("/bug_Latn")), None)
if not left or not right:
return out, [{"target": "bug", "pair": "NLLB-Seed",
"reason": f"no bug_Latn/eng_Latn members among {len(names)} entries",
"source": "nllb_seed"}]
src_lines = archive.read(left).decode("utf-8", "replace").splitlines()
trg_lines = archive.read(right).decode("utf-8", "replace").splitlines()
if len(src_lines) != len(trg_lines):
return out, [{"target": "bug", "pair": "NLLB-Seed",
"reason": f"{len(src_lines)} vs {len(trg_lines)} lines",
"source": "nllb_seed"}]
for index, (src, trg) in enumerate(zip(src_lines, trg_lines)):
if not src.strip() or not trg.strip():
continue
out.append(make_record(
pivot_config="en", target_config="bug", src=src, trg=trg,
source="nllb_seed", split="test", is_src_orig=True,
extra={"upstream_id": index},
))
return out, skipped
def collect_nusax(targets, rows):
"""NusaX-MT, twelve-way parallel with official splits. Buginese is the target here."""
out, skipped = [], []
if "bug" not in targets:
return out, skipped
base = f"https://raw.githubusercontent.com/IndoNLP/nusax/{NUSAX_REVISION}/datasets/mt"
# NusaX names its columns by language; Indonesian and English are the pivots we keep.
wanted = {"indonesian": "id", "english": "en"}
for upstream, split in (("test", "test"), ("valid", "dev")):
payload = fetch(f"{base}/{upstream}.csv")
if not payload:
skipped.append({"target": "bug", "pair": f"{upstream}.csv",
"reason": "not fetchable", "source": "nusax"})
continue
reader = csv.DictReader(io.StringIO(payload.decode("utf-8", "replace")))
for index, row in enumerate(reader):
target_text = (row.get("buginese") or "").strip()
if not target_text:
continue
for column, pivot_config in wanted.items():
src = (row.get(column) or "").strip()
if not src:
continue
ok, _why = pivots.acceptable_pivot("bug", pivot_config, rows)
if not ok:
continue
out.append(make_record(
pivot_config=pivot_config, target_config="bug",
src=src, trg=target_text, source="nusax", split=split,
extra={"upstream_id": index},
))
return out, skipped
# Treebanks that carry a free translation per sentence as a conll comment. The comment key
# differs: most use '# text_en', but the Shanghainese treebank pairs with Mandarin under
# '# text_cmn', which is the only Wu-Mandarin sentence alignment with official splits.
UD_BASE = "https://raw.githubusercontent.com/UniversalDependencies"
TREEBANK_TRANSLATIONS = {
"maibaam": {
"config": "bar", "comment": "text_en", "pivot": "en",
"files": [(f"{UD_BASE}/UD_Bavarian-MaiBaam/{MAIBAAM_REVISION}/"
"bar_maibaam-ud-test.conllu", "test")],
},
"ud_megrelian": {
"config": "xmf", "comment": "text_en", "pivot": "en",
"files": [(f"{UD_BASE}/UD_Megrelian-MLC/{UD_MEGRELIAN_REVISION}/"
"xmf_mlc_ud-test.conllu", "test")],
},
"ud_shanghainese": {
"config": "wuu", "comment": "text_cmn", "pivot": "zh",
"files": [
(f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-test.conllu",
"test"),
(f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-dev.conllu",
"dev"),
(f"{UD_BASE}/UD_Shanghainese-ShUD/{SHUD_REVISION}/wuu_shud-ud-train.conllu",
"train"),
],
},
}
def collect_treebank_translations(targets, rows):
"""Sentences from UD treebanks that ship a free translation as a comment."""
out, skipped = [], []
for source, spec in TREEBANK_TRANSLATIONS.items():
config, pivot_config = spec["config"], spec["pivot"]
if config not in targets:
continue
ok, _why = pivots.acceptable_pivot(config, pivot_config, rows)
if not ok:
skipped.append({"target": config, "pair": source,
"reason": f"pivot {pivot_config} not acceptable",
"source": source})
continue
text_prefix = "# text = "
pivot_prefix = f"# {spec['comment']} = "
for url, split in spec["files"]:
payload = fetch(url)
if not payload:
skipped.append({"target": config, "pair": url.rsplit("/", 1)[-1],
"reason": "not fetchable", "source": source})
continue
text, translation, kept = None, None, 0
def emit(text, translation, kept):
if not text or not translation:
return kept
out.append(make_record(
pivot_config=pivot_config, target_config=config,
src=translation, trg=text, source=source, split=split,
extra={"upstream_id": kept,
"upstream_file": url.rsplit("/", 1)[-1]},
))
return kept + 1
for line in payload.decode("utf-8", "replace").splitlines():
if line.startswith(text_prefix):
text = line[len(text_prefix):].strip()
elif line.startswith(pivot_prefix):
translation = line[len(pivot_prefix):].strip()
elif not line.strip():
kept = emit(text, translation, kept)
text, translation = None, None
emit(text, translation, kept)
return out, skipped
# Ladin corpora published by Simon Frontull. Only the two with a stated licence are taken;
# the three undated test sets on the same account state none and are left out rather than
# guessed at.
# Only the weather bulletins belong in a test set. The two big ``dizionar`` corpora are
# lexicographic example sentences harvested from a dictionary -- 37,422 of them, which would
# be a third of this release and would reward a model for reproducing dictionary glosses
# rather than translating. They go to the lexicon corpus instead, which is where a reader
# looking for dictionary material would expect them.
LADIN_SETS = [
("ladin_weather", "sfrontull/south-tyrol-weather-lld-deu", "de", "test"),
]
def ladin_keys(entry: dict) -> tuple[str | None, str | None]:
"""The Ladin side and the pivot side of one nested ``translation`` dict.
Repos on this account label the pivot either by ISO 639-3 ("deu", "ita") or by the
two-letter config code ("de", "it"), and the Ladin side either by variety
("lld_valbadia") or by the bare code. Matching only the three-letter spellings dropped
the whole weather set silently, so both are accepted here.
"""
target = next((k for k in entry if k.startswith("lld")), None)
pivot = next((k for k in entry
if k != target and k.startswith(("ita", "deu", "it", "de"))), None)
return target, pivot
def collect_ladin(targets, rows):
"""Italian-Ladin and German-Ladin corpora, including the non-commercial ones."""
out, skipped = [], []
if "lld" not in targets:
return out, skipped
import pyarrow.parquet as pq
from huggingface_hub import snapshot_download
from hf_publishing_auth import publishing_token
for source, repo, pivot_config, split in LADIN_SETS:
ok, _why = pivots.acceptable_pivot("lld", pivot_config, rows)
if not ok:
skipped.append({"target": "lld", "pair": repo,
"reason": "pivot not acceptable", "source": source})
continue
try:
local = snapshot_download(repo, repo_type="dataset",
token=publishing_token(),
allow_patterns=["*.parquet", "*.jsonl"])
except Exception as error: # noqa: BLE001 - gated or absent
skipped.append({"target": "lld", "pair": repo,
"reason": f"{type(error).__name__}", "source": source})
continue
found = 0
# Both the parquet and the jsonl releases wrap each pair in a single ``translation``
# column keyed by language, rather than one column per language.
pairs: list[dict] = []
for path in sorted(Path(local).rglob("*.parquet")):
table = pq.read_table(path)
if "translation" in table.schema.names:
pairs += table.column("translation").to_pylist()
for path in sorted(Path(local).rglob("*.jsonl")):
with path.open(encoding="utf-8") as handle:
for line in handle:
entry = json.loads(line).get("translation")
if isinstance(entry, dict):
pairs.append(entry)
for entry in pairs:
target_key, pivot_key = ladin_keys(entry)
if not target_key or not pivot_key:
continue
src, trg = entry.get(pivot_key) or "", entry.get(target_key) or ""
if not src.strip() or not trg.strip():
continue
out.append(make_record(
pivot_config=pivot_config, target_config="lld", src=src, trg=trg,
source=source, split=split,
extra={"variety": target_key, "upstream_id": found},
))
found += 1
if not found:
skipped.append({"target": "lld", "pair": repo,
"reason": "no recognisable column pair", "source": source})
return out, skipped
def collect_glotstorybook(targets, rows):
"""African Storybook texts, aligned to English through their parallel id.
Licensing is per row rather than per dataset, so only the plain CC-BY stories are taken;
the CC-BY-NC and CC-BY-NC-SA ones would silently impose a condition on the whole release.
"""
out, skipped = [], []
if "dag" not in targets:
return out, skipped
ok, _why = pivots.acceptable_pivot("dag", "en", rows)
if not ok:
return out, skipped
from huggingface_hub import hf_hub_download
from hf_publishing_auth import publishing_token
try:
path = hf_hub_download("cis-lmu/GlotStoryBook", "GlotStoryBook.csv",
repo_type="dataset", token=publishing_token())
except Exception as error: # noqa: BLE001
return out, [{"target": "dag", "pair": "GlotStoryBook.csv",
"reason": f"{type(error).__name__}", "source": "glotstorybook"}]
with open(path, encoding="utf-8") as handle:
entries = list(csv.DictReader(handle))
# Each story segment is identified by its parallel id plus its position in the story.
english = {
(row["Parallel ID"], row["Text Number"]): row["Text"]
for row in entries if row["ISO639-3"] == "eng"
}
for row in entries:
if row["ISO639-3"] != "dag":
continue
if (row.get("License") or "").strip().upper().replace(" ", "-") != "CC-BY":
skipped.append({"target": "dag", "pair": row.get("File Name"),
"reason": f"licence {row.get('License')!r} is not plain CC-BY",
"source": "glotstorybook"})
continue
key = (row["Parallel ID"], row["Text Number"])
src = english.get(key)
if not src or not (row.get("Text") or "").strip():
skipped.append({"target": "dag", "pair": row.get("File Name"),
"reason": "no English segment with the same parallel id",
"source": "glotstorybook"})
continue
out.append(make_record(
pivot_config="en", target_config="dag", src=src, trg=row["Text"],
source="glotstorybook", split="test",
extra={"document_id": row["Parallel ID"],
"upstream_id": int(row["Text Number"]) if
str(row["Text Number"]).isdigit() else None,
"variety": row.get("Story Category")},
))
return out, skipped
def collect_nsanku(targets, rows):
"""Ghana NLP's Dagbani-English reference pairs, counted but withheld.
Real human translation and already used as a published evaluation set, but the repository
ships no licence and the underlying text is a Bible society translation, so only the row
count and provenance are published.
"""
out, skipped = [], []
if "dag" not in targets:
return out, skipped
ok, _why = pivots.acceptable_pivot("dag", "en", rows)
if not ok:
return out, skipped
payload = fetch("https://raw.githubusercontent.com/GhanaNLP/nsanku/main/input/dag-eng.csv")
if not payload:
return out, [{"target": "dag", "pair": "input/dag-eng.csv",
"reason": "not fetchable", "source": "nsanku"}]
reader = csv.reader(io.StringIO(payload.decode("utf-8", "replace")))
rows_read = sum(1 for index, line in enumerate(reader) if index and any(line))
out.append(make_record(
pivot_config="en", target_config="dag", src="", trg="",
source="nsanku", split="test",
extra={"upstream_rows": rows_read, "upstream_file": "input/dag-eng.csv"},
))
return out, skipped
GIL1000_CSV = "CSV/Top 1000 Words in Gilaki (Full).csv"
# Each row carries the same illustrative sentence in all three languages, so one row yields a
# Gilaki-Persian pair and a Gilaki-English pair.
GIL1000_PIVOTS = [("fa", "fa_example"), ("en", "en_example")]
def collect_gil1000_sentences(targets, rows):
"""Sentence-level Gilaki-Persian and Gilaki-English pairs from the Top-1000 word list.
Published at https://gil1000.ir/ and in the repository below. Each of the 1,000 entries
carries one example sentence written in Gilaki, Persian and English, which makes it
sentence-aligned parallel text for a language that has almost none.
These are dictionary example sentences, not running text, and they are also present in the
lexicon corpus as ``entry_type: example_sentence``. Both facts limit what a score on them
means: the sentences were written to illustrate a headword, they are short, and a system
trained on the lexicon corpus has already seen them. ``domain`` says
``dictionary_examples`` so this cannot be mistaken for a general-purpose test set.
"""
out, skipped = [], []
if "glk" not in targets:
return out, skipped
url = ("https://raw.githubusercontent.com/LordArma/Top-1000-Words-in-Gilaki/"
f"{GIL1000_REVISION}/{urllib.parse.quote(GIL1000_CSV)}")
payload = fetch(url)
if not payload:
return out, [{"target": "glk", "pair": GIL1000_CSV,
"reason": "not fetchable", "source": "gil1000"}]
reader = csv.DictReader(io.StringIO(payload.decode("utf-8-sig", "replace")))
for index, line in enumerate(reader):
target = (line.get("glk_example") or "").strip()
if not target:
continue
for pivot_config, column in GIL1000_PIVOTS:
ok, why = pivots.acceptable_pivot("glk", pivot_config, rows)
if not ok:
skipped.append({"target": "glk", "pair": f"{pivot_config}-glk",
"reason": why, "source": "gil1000"})
continue
src = (line.get(column) or "").strip()
if not src:
continue
out.append(make_record(
pivot_config=pivot_config, target_config="glk", src=src, trg=target,
source="gil1000", split="test",
# The Gilaki sentence is the one that was written first; the other two are its
# translations, which is the opposite of every other source here.
is_src_orig=False,
# ``upstream_id`` is an integer column; the CSV hands back strings.
extra={"upstream_id": int(line.get("id") or index),
"upstream_file": GIL1000_CSV,
"headword": (line.get("glk_word") or "").strip()},
))
return out, skipped
# The script each target language is actually written in. A test set that mixes scripts for
# one language cannot be scored: chrF and BLEU compare characters, so a Georgian reference and
# a Latin transliteration of the same Megrelian sentence score as a total miss against each
# other. Tatoeba's Megrelian is 45 sentences in Georgian and 34 romanised by contributors, and
# nothing upstream distinguishes them.
#
# Latin is the default because most of these languages are written in it; only the five that
# are not need an entry.
EXPECTED_SCRIPT = {
"azb": {"ARABIC"}, # South Azerbaijani, Perso-Arabic
"glk": {"ARABIC"}, # Gilaki
"mzn": {"ARABIC"}, # Mazanderani
"skr": {"ARABIC"}, # Saraiki
"xmf": {"GEORGIAN"}, # Megrelian, Mkhedruli
"wuu": {"CJK", "BOPOMOFO"}, # Wu, Han characters
}
DEFAULT_SCRIPT = {"LATIN"}
# A fifth of the letters, not merely one. "sanchez_: <Chinese>" is 30% Han and genuinely Wu
# text, so a majority test would wrongly drop it; a romanised Megrelian sentence is 0%
# Georgian, so a one-character test would wrongly keep anything with a stray diacritic.
SCRIPT_SHARE = 0.2
def script_of(char: str) -> str | None:
"""The script a single character belongs to, or None if it is not a letter."""
if not char.isalpha():
return None
try:
name = unicodedata.name(char)
except ValueError:
return None
# Unicode names Han characters "CJK UNIFIED IDEOGRAPH-xxxx"; everything else leads with
# its script name.
return name.split()[0]
def script_share(text: str, expected: set[str]) -> float:
"""What fraction of a string's letters are written in the expected script."""
letters = [s for s in (script_of(c) for c in text or "") if s]
if not letters:
return 1.0 # no letters at all: nothing to judge, leave it to the caller
return sum(1 for s in letters if s in expected) / len(letters)
def drop_off_script(records: list[dict]) -> tuple[list[dict], list[dict]]:
"""Separate records whose target is not written in the language's own script."""
kept, dropped = [], []
for record in records:
if record.get("text_withheld") or not record.get("trg"):
kept.append(record)
continue
expected = EXPECTED_SCRIPT.get(record["tl"], DEFAULT_SCRIPT)
if script_share(record["trg"], expected) < SCRIPT_SHARE:
dropped.append(record)
continue
kept.append(record)
return kept, dropped
MLC_INDEX = "https://xmf.iliauni.edu.ge/corpus"
MLC_DOWNLOAD = "https://xmf.iliauni.edu.ge/download?file="
# The Megrelian phrase and the two glosses of it. The fourth phrase tier,
# ``A_phrase-gls-xmf-fonipa``, is an IPA transcription of the same Megrelian rather than a
# translation, so it is not collected.
MLC_TARGET_TIER = "A_phrase-txt-xmf"
MLC_GLOSS_TIERS = [("A_phrase-gls-ka-Brai", "ka"), ("A_phrase-gls-en", "en")]
def _eaf_root(payload: bytes):
"""Parse an ELAN file, recovering the one upstream file with invalid UTF-8 bytes."""
try:
return ElementTree.fromstring(payload)
except ElementTree.ParseError:
# 00138.eaf carries bytes that are not valid UTF-8. U+FFFD is itself valid XML, so
# re-encoding keeps every annotation except the damaged characters, rather than
# discarding a whole text.
return ElementTree.fromstring(payload.decode("utf-8", "replace").encode("utf-8"))
def _eaf_tier(root, tier_id: str) -> dict:
"""``{annotation_id: (text, referenced_annotation_id)}`` for one ELAN tier."""
found = {}
for tier in root.iter("TIER"):
if tier.get("TIER_ID") != tier_id:
continue
annotations = list(tier.iter("ALIGNABLE_ANNOTATION"))
annotations += list(tier.iter("REF_ANNOTATION"))
for annotation in annotations:
value = annotation.find("ANNOTATION_VALUE")
text = (value.text or "").strip() if value is not None else ""
found[annotation.get("ANNOTATION_ID")] = (text, annotation.get("ANNOTATION_REF"))
return found
def collect_mlc(targets, rows):
"""Megrelian oral texts with aligned Georgian and English glosses.
Each phrase is a separate ELAN annotation, and the two gloss tiers reference the
Megrelian annotation they gloss, so the alignment is the corpus's own rather than
positional.
"""
out, skipped = [], []
if "xmf" not in targets:
return out, skipped
index = fetch(MLC_INDEX)
if not index:
return out, [{"target": "xmf", "pair": "corpus", "reason": "index not fetchable",
"source": "mlc"}]
files = sorted(set(re.findall(r"download\?file=(data/[^'\"]+\.eaf)",
index.decode("utf-8", "replace"))))
if not files:
return out, [{"target": "xmf", "pair": "corpus",
"reason": "no ELAN files listed", "source": "mlc"}]
usable = []
for pivot_tier, pivot_config in MLC_GLOSS_TIERS:
ok, why = pivots.acceptable_pivot("xmf", pivot_config, rows)
if ok:
usable.append((pivot_tier, pivot_config))
else:
skipped.append({"target": "xmf", "pair": f"{pivot_config}-xmf",
"reason": why, "source": "mlc"})
for name in files:
payload = fetch(MLC_DOWNLOAD + name)
if not payload:
skipped.append({"target": "xmf", "pair": name, "reason": "not fetchable",
"source": "mlc"})
continue
root = _eaf_root(payload)
target_tier = _eaf_tier(root, MLC_TARGET_TIER)
document = name.rsplit("/", 1)[-1].removesuffix(".eaf")
for pivot_tier, pivot_config in usable:
glosses = _eaf_tier(root, pivot_tier)
by_reference = {reference: text for text, reference in glosses.values()
if reference}
for annotation_id, (target_text, _reference) in sorted(target_tier.items()):
pivot_text = by_reference.get(annotation_id) or ""
if not target_text.strip() or not pivot_text.strip():
continue
out.append(make_record(
pivot_config=pivot_config, target_config="xmf",
src=pivot_text, trg=target_text,
source="mlc", split="test",
# Recorded in Megrelian; both glosses were written from it.
is_src_orig=False,
extra={"document_id": document, "upstream_file": name,
"text_unit": "phrase"},
))
return out, skipped
def deduplicate(records, rows):
"""Collapse records that carry the same pair, keeping the most authoritative source.
NaLiBaSID republishes xSID's Bavarian sentences, so the same English-Bavarian pair
arrives twice; the same happens whenever two Tatoeba pairs share a sentence. Preference
order follows which release supersedes which, mirroring the ``supersedes`` declarations
in ``configs/community_benchmarks.json``.
"""
# Human-authored and manually aligned sources rank above translated-out-of-English ones,
# and anything redistributable ranks above a withheld duplicate of the same pair: keeping
# the withheld copy would lose text we are allowed to publish.
priority = {"bouquet": 0, "dolma_bitext": 1, "nalibasid": 2, "parme": 3, "codet": 4,
"nllb_seed": 5, "nusax": 6, "ntrex": 7, "ladin_weather": 8,
"ladin_frontull": 9, "ud_shanghainese": 9, "maibaam": 10, "mlc": 10, "ud_megrelian": 11, "xsid": 12,
"smol": 13, "tatoeba_challenge": 14,
"glotstorybook": 15, "gil1000": 16, "nsanku": 20, "betthupferl": 21, "flores_plus": 22}
best: dict[tuple, dict] = {}
dropped = []
for record in records:
if record.get("text_withheld"):
# Withheld rows have no text to compare, so they are keyed by what they stand
# for: one row per language, source and split.
best[("ref", record["tl"], record["source"], record["split"])] = record
continue
key = (record["tl"], record["sl"], norm_key(record["src"]), norm_key(record["trg"]))
incumbent = best.get(key)
if incumbent is None:
best[key] = record
continue
if priority.get(record["source"], 8) < priority.get(incumbent["source"], 8):
dropped.append({"kept": record["source"], "dropped": incumbent["source"],
"language": record["tl"]})
best[key] = record
else:
dropped.append({"kept": incumbent["source"], "dropped": record["source"],
"language": record["tl"]})
return list(best.values()), dropped
def write_release(records, skipped, dropped, selection, rows, release_id=None):
import pyarrow as pa
import pyarrow.parquet as pq
release_id = release_id or time.strftime("eval_%Y%m%dT%H%M%SZ", time.gmtime())
output = DIST / release_id
(output / "languages").mkdir(parents=True, exist_ok=True)
by_language: dict[str, list[dict]] = {}
for record in records:
by_language.setdefault(record["tl"], []).append(record)
# Only columns that bear on the translation itself, its provenance or its licence. Task
# annotations from the upstream releases (xSID intent labels, BOUQuET register codes) and
# columns derivable from another column (source_url from source, redistributable from
# licence_tier, withheld_reason from licence_restriction) are deliberately absent.
columns = ["sl", "tl", "id", "src", "trg", "is_src_orig", "split", "source",
"source_revision", "licence", "licence_tier", "licence_restriction",
"domain", "variety", "text_unit", "document_id", "released_as",
"source_pair", "upstream_id", "upstream_file",
"text_withheld", "upstream_rows"]
schema = pa.schema([
("sl", pa.string()), ("tl", pa.string()), ("id", pa.int64()),
("src", pa.string()), ("trg", pa.string()), ("is_src_orig", pa.bool_()),
("split", pa.string()), ("source", pa.string()),
("source_revision", pa.string()), ("licence", pa.string()),
# How freely each record may be passed on.
("licence_tier", pa.int64()), ("licence_restriction", pa.string()),
# What kind of text it is, and which variety of the language wrote it.
("domain", pa.string()), ("variety", pa.string()), ("text_unit", pa.string()),
("document_id", pa.string()), ("released_as", pa.string()),
# Where the row came from, precisely enough to find it upstream.
("source_pair", pa.string()), ("upstream_id", pa.int64()),
("upstream_file", pa.string()),
("text_withheld", pa.bool_()), ("upstream_rows", pa.int64()),
])
summary, flat = {}, []
for config in sorted(by_language):
items = by_language[config]
# Deterministic order: split, then source, then pivot, then the text itself.
items.sort(key=lambda r: (r["split"], r["source"], r["sl"], r["src"] or "",
r["trg"] or ""))
for index, record in enumerate(items):
record["id"] = index
path = output / "languages" / f"{config}.jsonl"
with path.open("w", encoding="utf-8") as handle:
for record in items:
handle.write(json.dumps(
{k: v for k, v in record.items() if v is not None},
ensure_ascii=False,
) + "\n")
flat += items
usable = [r for r in items if r.get("src")]
summary[config] = {
"language_name": rows[config]["language_name"],
"iso639_3": rows[config]["iso639_3"],
"opportunity_rank": rows[config]["opportunity_rank"],
"records": len(usable),
"withheld_records": len(items) - len(usable),
"test": sum(1 for r in usable if r["split"] == "test"),
"dev": sum(1 for r in usable if r["split"] == "dev"),
"sources": sorted({r["source"] for r in usable}),
"pivots": sorted({r["sl"] for r in usable}),
"by_source": {
source: sum(1 for r in usable if r["source"] == source)
for source in sorted({r["source"] for r in usable})
},
}
def as_table(items):
return pa.Table.from_pylist(
[{column: record.get(column) for column in columns} for record in items],
schema=schema,
)
pq.write_table(as_table(flat), output / "eval.parquet", compression="zstd")
# One subset per source and language: "<source>-<language>" says where the data came
# from and which language it is for -- nalibasid-bar, tatoeba-bar, parme-glk. The
# baseline corpus names its subsets the same way, so a name that appears in both
# identifies one body of data with its test split here and its training split there.
#
# Withheld FLORES+ rows carry no text, so they stay in the per-language JSONL as a
# record of the gap and are kept out of every subset, including 'all'. A subset is
# something you can score against; a row with no sentences is not.
usable = [r for r in flat if r.get("src")]
subsets = {"all": usable}
for source, language in sorted({(r["source"], r["tl"]) for r in usable}):
subsets[subset_name(source, language)] = [
r for r in usable if r["source"] == source and r["tl"] == language
]
subset_meta = write_subsets(
output, subsets, as_table, split_of=lambda record: record["split"]
)
manifest = {
"release_id": release_id,
"built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"audit_release": selection["release"],
"shortlist_count": selection["count"],
"languages_with_usable_records": sum(1 for s in summary.values() if s["records"]),
"languages_without_any_test_data": sorted(
c for c in selection["languages"] if not summary.get(c, {}).get("records")
),
"total_records": sum(s["records"] for s in summary.values()),
"withheld_records": sum(s["withheld_records"] for s in summary.values()),
"sources": SOURCE_META,
"licence": "CC-BY-SA-4.0",
"licence_note": (
"The collection is CC-BY-SA-4.0 because xSID, NaLiBaSID and NTREX are "
"share-alike; CC-BY-4.0 (SMOL), CC-BY-2.0-FR (Tatoeba) and MIT (PARME) are "
"compatible with that. Every record carries its own licence field."
),
"subsets": subset_meta,
"subset_note": (
"'all' is every record. The remaining subsets are one per source and "
"language, named '<source>-<language>': where the data came from, and which "
"language it is for. The baseline corpus names its subsets the same way, so a "
"name present in both identifies one body of data with its test split here and "
"its training split there. Withheld FLORES+ reference rows appear only in the "
"per-language JSONL files, not in any subset."
),
"languages": summary,
"skipped": skipped,
"duplicates_collapsed": len(dropped),
"columns": columns,
}
(output / "manifest.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
)
return output, manifest
def build(release_id=None):
selection = pivots.selection()
rows = pivots.load_rows(pivots.DIST / selection["release"])
targets = list(selection["languages"])
iso2cfg = pivots.iso_to_config(rows)
with (ROOT / "cache" / "lang_audit" / "sources" / "tatoeba_challenge.json").open(
encoding="utf-8"
) as handle:
tatoeba_pairs = json.load(handle)["data"]["test_pairs"]["pairs"]
records, skipped = [], []
for label, collector in (
("tatoeba_challenge", lambda: collect_tatoeba(targets, rows, iso2cfg, tatoeba_pairs)),
("ntrex", lambda: collect_ntrex(targets, rows)),
("xsid", lambda: collect_xsid(rows)),
("nalibasid", lambda: collect_nalibasid(rows)),
("parme", lambda: collect_parme(rows)),
("smol", lambda: collect_smol(targets, rows)),
("bouquet", lambda: collect_bouquet(targets, rows)),
("codet", lambda: collect_codet(targets, rows)),
("dolma_bitext", lambda: collect_dolma_bitext(targets, rows)),
("nllb_seed", lambda: collect_nllb_seed(targets, rows)),
("nusax", lambda: collect_nusax(targets, rows)),
("treebanks", lambda: collect_treebank_translations(targets, rows)),
("ladin", lambda: collect_ladin(targets, rows)),
("glotstorybook", lambda: collect_glotstorybook(targets, rows)),
("mlc", lambda: collect_mlc(targets, rows)),
("gil1000", lambda: collect_gil1000_sentences(targets, rows)),
("nsanku", lambda: collect_nsanku(targets, rows)),
):
got, missed = collector()
print(f" {label:<20} {len(got):>7,} records, {len(missed)} skipped", flush=True)
records += got
# Two labels cover more than one source, so the entry's own source wins.
skipped += [{"source": label, **entry} for entry in missed]
references = collect_flores_reference(targets, rows)
print(f" {'flores_plus (ref)':<20} {len(references):>7,} reference rows", flush=True)
records += references
records, off_script = drop_off_script(records)
if off_script:
counts = Counter((r["tl"], r["source"]) for r in off_script)
print(f" off-script: {len(off_script):,} records not in the language's own script")
for (language, source), count in sorted(counts.items()):
print(f" {language} {source}: {count:,}")
records, dropped = deduplicate(records, rows)
print(f" deduplicated: {len(dropped):,} collapsed -> {len(records):,} records")
output, manifest = write_release(records, skipped, dropped, selection, rows, release_id)
print(f"\nrelease: {output}")
return output, manifest
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--release-id", default=None)
args = parser.parse_args(argv)
output, manifest = build(args.release_id)
print(f"languages with test data: {manifest['languages_with_usable_records']}"
f"/{manifest['shortlist_count']}")
print(f"records: {manifest['total_records']:,} withheld: {manifest['withheld_records']}")
if manifest["languages_without_any_test_data"]:
print(f"no human test data: {manifest['languages_without_any_test_data']}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Gather every human-created translation test set for the audit's shortlist languages.
One JSONL file per language in Google SMOL's ``smolsent`` shape, so that an existing SMOL
reader works unchanged:
{"sl": "en", "tl": "glk", "id": 0, "src": "...", "trg": "...", "is_src_orig": true}
with provenance fields added, because a record that cannot be traced back to its source and
licence is not usable evidence.
Only human-produced data is collected. Automatically mined or word-aligned material --
WikiMatrix, XLEnt, the projected training files shipped alongside xSID -- belongs in the
baseline training corpus, not in a test set.
Sources, each pinned to a revision and counted from the files themselves:
* Tatoeba Challenge ``data/test/<pair>/test.txt``, open, CC-BY-2.0-FR
* NTREX line-aligned references against the English source, open, CC-BY-SA-4.0
* xSID 0.6 manual translations of English voice-assistant utterances, CC-BY-SA-4.0
* NaLiBaSID extends xSID for Bavarian with MASSIVE translations, CC-BY-SA-4.0
* PARME English-Persian-X sentences for Middle Eastern languages, MIT
* SMOL (smolsent) professionally translated sentences, CC-BY-4.0
FLORES+ is deliberately *not* redistributed. Its access terms require agreeing "not to
re-host FLORES+ in places where it could be picked up by web crawlers", and a public dataset
repository is exactly such a place. Languages whose only test set is FLORES+ get
reference-only records: the language, split and row count, with the text withheld and a
pointer to the upstream repository. Keeping the rows makes the gap visible instead of making
those languages silently look untested.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import re
import sys
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ElementTree
import zipfile
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import shortlist_pivots as pivots # noqa: E402
from corpus_subsets import subset_name, write_subsets # noqa: E402
CACHE = ROOT / "cache" / "eval_corpus"
DIST = ROOT / "dist" / "eval_corpus"
USER_AGENT = "gilaki-eval-corpus/1.0 (+research use)"
TATOEBA_REVISION = "bd05f087e91e359a88594bd6d6c99a079e0ac621"
XSID_REVISION = "761d926c3f2e9f6bea13192d2f39cec1d04d9777"
NALIBASID_REVISION = "8d66b9021c06df1ab459636a925e119b2cff20fe"
NTREX_REVISION = "468c6b69c7f6a75d31d4743d9daba2af566cc18d"
PARME_REVISION = "6df9269acc75377ed6be3bf2f7966c8e238a62bd"
CODET_REVISION = "main"
DOLMA_BITEXT_REVISION = "main"
MAIBAAM_REVISION = "master"
UD_MEGRELIAN_REVISION = "dev"
NUSAX_REVISION = "main"
SHUD_REVISION = "master"
GIL1000_REVISION = "master"
# How freely a source may be passed on. The distinction is not cosmetic: a third of the
# resources found for these languages carry no licence at all, and several of the best ones
# are explicitly non-commercial or no-derivatives. Publishing them all under one licence
# field would misrepresent every tier but the first.
#
# 1 redistributable: a licence that permits republishing the text.
# 2 restricted: republishable only under a condition that limits reuse (non-commercial).
# 3 reference only: no licence stated, no-derivatives, or an explicit request not to
# redistribute. Ids and counts are published; the text is withheld.
TIER_REDISTRIBUTABLE, TIER_RESTRICTED, TIER_REFERENCE = 1, 2, 3
SOURCE_META = {
"tatoeba_challenge": {
"url": "https://github.com/Helsinki-NLP/Tatoeba-Challenge",
"revision": TATOEBA_REVISION, "licence": "CC-BY-2.0-FR",
"domain": "crowd_sentences",
"note": "Crowd-contributed sentences from Tatoeba, held out as the Challenge test split.",
},
"ntrex": {
"url": "https://github.com/MicrosoftTranslator/NTREX",
"revision": NTREX_REVISION, "licence": "CC-BY-SA-4.0", "domain": "news",
"note": "NTREX-128 news references, professionally translated out of English. The "
"Swiss German references live in NTREX-additional and are absent from the "
"mteb/NTREX mirror.",
},
"xsid": {
"url": "https://github.com/mainlp/xsid",