"""Publish the evaluation and baseline corpora as Hugging Face datasets. Mirrors ``publish_lang_audit.py``: validate the staged release, scan it for anything that looks like a credential, upload, then wait for the native Dataset Viewer to agree on the row count. The token comes from the local keychain helper and is never written into any uploaded file. """ from __future__ import annotations import argparse import hashlib import json import re import sys import time import urllib.parse import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) from hf_publishing_auth import publishing_token # noqa: E402 SECRET_PATTERN = re.compile(rb"hf_[A-Za-z0-9]{20,}") HUB_GENERATED = {".gitattributes"} TARGETS = { "eval": { "dataset_id": "sigiranic/underserved-translation-eval", "root": ROOT / "dist" / "eval_corpus", "glob": "eval_*", "parquet": "eval.parquet", "split": "test", "pretty": "Human translation test sets for under-served languages", "tags": ["machine-translation", "evaluation", "low-resource", "benchmark"], }, "baseline": { "dataset_id": "sigiranic/underserved-translation-baseline", "root": ROOT / "dist" / "baseline_corpus", "glob": "baseline_*", "parquet": "baseline.parquet", "split": "train", "pretty": "Existing parallel training data for under-served languages", "tags": ["machine-translation", "parallel-corpus", "low-resource", "baseline"], }, "lexicon": { "dataset_id": "sigiranic/underserved-translation-lexicons", "root": ROOT / "dist" / "lexicon_corpus", "glob": "lexicon_*", "parquet": "lexicon.parquet", "split": "lexicon", "pretty": "Lexicons, glossaries and glosses for under-served languages", "tags": ["machine-translation", "lexicon", "low-resource", "bilingual-dictionary"], }, } def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest() def latest(target: dict) -> Path: candidates = sorted( p for p in target["root"].glob(target["glob"]) if (p / "manifest.json").exists() ) if not candidates: raise FileNotFoundError(f"no release under {target['root']}") return candidates[-1] def config_block(manifest: dict) -> str: """The Hub ``configs`` front matter, one entry per subset. ``all`` is the default. The rest are one per translation direction, written ``-``, plus the baseline's by-production-method subsets. Both datasets use the same names, so a subset name identifies one language pair across both. """ lines = ["configs:"] for name, entry in sorted( manifest["subsets"].items(), key=lambda kv: (kv[0] != "all", kv[1].get("is_source_subset", False), kv[0]), ): lines.append(f"- config_name: {name}") if name == "all": lines.append(" default: true") lines.append(" data_files:") for split, info in sorted(entry["splits"].items()): lines.append(f" - split: {split}") lines.append(f" path: {info['path']}") return "\n".join(lines) def subset_table(manifest: dict, limit: int = 30) -> str: """A readable sample of the pair subsets; the full list is in the manifest.""" pairs = sorted( ((name, entry) for name, entry in manifest["subsets"].items() if entry.get("is_source_subset")), key=lambda kv: -kv[1]["records"], ) rows = "\n".join( f"| `{name}` | {entry['records']:,} | " + ", ".join(f"{split} {info['records']:,}" for split, info in sorted(entry["splits"].items())) + " |" for name, entry in pairs[:limit] ) return rows, len(pairs) def lexicon_card(manifest: dict, target: dict) -> str: subset_rows, subset_count = subset_table(manifest) languages = manifest["languages"] ranked = sorted(languages.items(), key=lambda kv: -kv[1]["entries"]) rows = "\n".join( f"| `{config}` | {entry['language_name']} | {entry['entries']:,} | " f"{entry['redistributable_entries']:,} | {', '.join(entry['pivots'])} | " f"{', '.join(entry['sources'])} |" for config, entry in ranked ) sources = "\n".join( f"| [{name}]({meta['url']}) | `{str(meta['revision'])[:12]}` | {meta['licence']} | " f"tier {meta['tier']} | {meta['note']} |" for name, meta in sorted(manifest["sources"].items()) ) types = "\n".join( f"| `{name}` | {description} |" for name, description in manifest["entry_types"].items() ) tiers = manifest["entries_by_licence_tier"] return f"""--- license: cc-by-sa-4.0 task_categories: - translation pretty_name: {target['pretty']} size_categories: - 100K-`: where the entries came from, and which language they are for. | subset | entries | splits | |---|--:|---| {subset_rows} ## Caveats - A dictionary headword is not a sentence. Training on `word` rows teaches vocabulary, not syntax; only the `example_sentence` and `token_gloss` rows carry structure. - Many entries reach this release through PanLex, so ChiKhaPo, GATITOS and Apertium overlap. Duplicates are collapsed on the normalised pair, keeping the most freely licensed copy. - Entry counts are not quality. A language with thousands of entries from one aggregated source may have had less human curation than one with a few hundred hand-written ones. - Gilaki is absent from ChiKhaPo entirely, so its entries come from a single GPL-3.0 source. That makes it the one language here with no tier-1 lexicon at all. Built by `scripts/build_lexicon_corpus.py`; release `{manifest['release_id']}`, derived from audit release `{manifest['audit_release']}`. """ def eval_card(manifest: dict, target: dict) -> str: pair_rows, pair_count = subset_table(manifest) languages = manifest["languages"] ranked = sorted(languages.items(), key=lambda kv: kv[1]["opportunity_rank"]) rows = "\n".join( f"| {entry['opportunity_rank']} | `{config}` | {entry['language_name']} | " f"{entry['records']:,} | {entry['test']:,} | {entry['dev']:,} | " f"{', '.join(entry['pivots'])} | {', '.join(entry['sources'])} |" for config, entry in ranked if entry["records"] ) sources = "\n".join( f"| [{name}]({meta['url']}) | `{meta['revision'][:12]}` | {meta['licence']} | " f"{meta['domain']} |" for name, meta in sorted(manifest["sources"].items()) ) missing = ", ".join(f"`{c}`" for c in manifest["languages_without_any_test_data"]) return f"""--- license: cc-by-sa-4.0 task_categories: - translation pretty_name: {target['pretty']} size_categories: - 10K-` — `{pair_count}` of them — each carrying whichever of `test` and `dev` it has. The companion baseline dataset uses **the same names**, so one subset name identifies a pair in both: ```python from datasets import load_dataset test = load_dataset("sigiranic/underserved-translation-eval", "glk-en") train = load_dataset("sigiranic/underserved-translation-baseline", "glk-en") ``` Largest subsets: | Subset | Pairs | Splits | |---|---|---| {pair_rows} The full list, with record counts, is in `manifest.json`. ## Sources | Source | Revision | Licence | Domain | |---|---|---|---| {sources} Counts were measured from the files themselves at the pinned revisions, not copied from documentation. ## Choices worth knowing about **FLORES+ text is not included.** Its access terms require agreeing not to re-host it where web crawlers could reach it, and a public dataset repository is exactly that. Languages whose only test set is FLORES+ carry reference-only rows — language, split and upstream row count, with `text_withheld: true` and no text — so the gap is visible rather than silently making those languages look untested. Fetch FLORES+ from upstream after accepting its terms. **SMOL is included as evaluation data** although Google releases it as *training* data. This was a deliberate choice. Scores on the SMOL portion are therefore **not comparable** with systems that trained on it; those records are flagged `released_as: "training"`. **xSID and NaLiBaSID overlap.** NaLiBaSID republishes xSID's Bavarian sentences, so the pair is de-duplicated with NaLiBaSID winning. Summing the two upstream releases would count the same sentences twice. **Voice-assistant domain.** The xSID and NaLiBaSID material is short spoken commands to a digital assistant, not general prose, so it measures a narrow slice of translation quality. **Only human-produced data.** Automatically mined or word-aligned material — WikiMatrix, XLEnt, the `projectedTrain` files shipped alongside xSID — is excluded, and lives in the companion baseline corpus instead. ## Companion dataset [sigiranic/underserved-translation-baseline](https://huggingface.co/datasets/sigiranic/underserved-translation-baseline) holds the parallel *training* data that already exists for the same languages and the same pivot directions. No pair appears in both: the baseline build removes any training record that reproduces an evaluation pair. ## Licence and attribution The collection is CC-BY-SA-4.0, forced by the share-alike terms of xSID, NaLiBaSID and NTREX; CC-BY-4.0 (SMOL), CC-BY-2.0-FR (Tatoeba) and MIT (PARME) are compatible with that. Each record carries its own `licence` field. Please cite the upstream releases listed above — this dataset only gathers and normalises their work. Built from audit release `{manifest['audit_release']}`. """ def baseline_card(manifest: dict, target: dict) -> str: pair_rows, pair_count = subset_table(manifest) languages = manifest["languages"] ranked = sorted(languages.items(), key=lambda kv: kv[1]["opportunity_rank"]) rows = "\n".join( f"| {entry['opportunity_rank']} | `{config}` | {entry['language_name']} | " f"{entry['records']:,} | {entry['human_records']:,} | {entry['human_share']:.1%} | " + ", ".join(f"{k} {v:,}" for k, v in list(entry["by_corpus_type"].items())[:3]) + " |" for config, entry in ranked ) types = "\n".join( f"| `{name}` | {description} | {'yes' if name in manifest['human_types'] else 'no'} |" for name, description in manifest["corpus_types"].items() ) return f"""--- license: cc-by-sa-4.0 task_categories: - translation pretty_name: {target['pretty']} size_categories: - 1M-` (`{pair_count}` of them): where the training data came from, and which language it is for. The evaluation dataset names its subsets the same way, so a name present in both holds that source's training split here and its test split there. ```python from datasets import load_dataset load_dataset("sigiranic/underserved-translation-baseline", "all") load_dataset("sigiranic/underserved-translation-baseline", "xlent-bar") # 167,258 load_dataset("sigiranic/underserved-translation-baseline", "wikimatrix-bar") # 93,840 load_dataset("sigiranic/underserved-translation-baseline", "tatoeba-bar") # 258 ``` The human/automatic distinction is the `corpus_type` **column**, not a subset, so it can be filtered without multiplying the subset list: ```python ds = load_dataset("sigiranic/underserved-translation-baseline", "all", split="train") human = ds.filter(lambda r: r["corpus_type"] in ("human_prose", "crowd_sentences", "religious", "subtitles")) ``` Largest subsets: | Subset | Records | Splits | |---|---|---| {pair_rows} ## Format Identical to the companion evaluation set, so the two can be read by the same code: ```json {{"sl": "en", "tl": "bar", "id": 0, "src": "...", "trg": "...", "split": "train", "source": "opus/WikiMatrix", "corpus": "WikiMatrix", "corpus_type": "auto_mined"}} ``` ## Languages | Rank | Config | Language | Pairs | Human | Human share | Largest types | |---|---|---|---|---|---|---| {rows} ## No overlap with the evaluation set {manifest['contaminated_records_removed']:,} training records that reproduced an evaluation pair were removed before publication, so a baseline trained on this cannot have seen its own test set. Tatoeba is the reason this check is necessary: its Challenge test and training splits come from the same pool, and OPUS ships the whole corpus. ## Provenance Everything is from [OPUS](https://opus.nlpl.eu/), downloaded per corpus and language pair at the versions recorded in each record's `source_revision`. Pivot directions match the evaluation set exactly. ## Licence Upstream licences are mixed; every record carries its own `licence` field and the OPUS corpus it came from. Consult the named OPUS corpus page before redistributing any single subset. The collection is offered as CC-BY-SA-4.0. Built from audit release `{manifest['audit_release']}` and evaluation release `{manifest['eval_release']}`. """ def stage(release: Path, target: dict, kind: str) -> dict: """Lay out the files to upload and the card, without touching the release directory.""" manifest = json.loads((release / "manifest.json").read_text(encoding="utf-8")) card = {"eval": eval_card, "baseline": baseline_card, "lexicon": lexicon_card}[kind](manifest, target) uploads = { f"data/{target['parquet']}": release / target["parquet"], "manifest.json": release / "manifest.json", } for path in sorted((release / "languages").glob("*.jsonl")): uploads[f"languages/{path.name}"] = path # Every subset's parquet, at the paths the configs front matter points to. for name, entry in manifest["subsets"].items(): for info in entry["splits"].values(): uploads[info["path"]] = release / info["path"] missing = [str(p) for p in uploads.values() if not p.exists()] if missing: raise SystemExit(f"missing staged files: {missing}") for path in uploads.values(): if SECRET_PATTERN.search(path.read_bytes()): raise SystemExit(f"refusing to upload {path}: looks like it contains a token") if SECRET_PATTERN.search(card.encode()): raise SystemExit("refusing to upload: card looks like it contains a token") return {"manifest": manifest, "card": card, "uploads": uploads} def expected_rows(release: Path, target: dict) -> int: import pyarrow.parquet as pq return pq.read_metadata(release / target["parquet"]).num_rows def publish(kind: str, release: Path | None = None, dry_run: bool = False) -> dict: from huggingface_hub import CommitOperationAdd, HfApi target = TARGETS[kind] release = release or latest(target) staged = stage(release, target, kind) rows = expected_rows(release, target) report = { "kind": kind, "release": release.name, "dataset_id": target["dataset_id"], "files": len(staged["uploads"]) + 1, "rows": rows, # The sentence corpora count "records"; the lexicon counts "entries". "records": staged["manifest"].get("total_records") or staged["manifest"]["total_entries"], "bytes": sum(p.stat().st_size for p in staged["uploads"].values()), "checksums": {name: _sha256(path)[:16] for name, path in staged["uploads"].items()}, } if dry_run: return report api = HfApi(token=publishing_token()) api.create_repo(target["dataset_id"], repo_type="dataset", exist_ok=True, private=False) operations = [ CommitOperationAdd(path_in_repo=name, path_or_fileobj=str(path)) for name, path in staged["uploads"].items() ] operations.append( CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=staged["card"].encode("utf-8")) ) info = api.create_commit( repo_id=target["dataset_id"], repo_type="dataset", operations=operations, commit_message=f"Publish {release.name}", commit_description=f"{report['records']:,} records from audit release " f"{staged['manifest']['audit_release']}.", ) report["commit"] = info.oid return report def _viewer(endpoint: str, dataset_id: str, timeout: int = 120, **params) -> dict: query = urllib.parse.urlencode({"dataset": dataset_id, **params}) request = urllib.request.Request( f"https://datasets-server.huggingface.co/{endpoint}?{query}", headers={"User-Agent": "gilaki-publisher/1.0"}, ) with urllib.request.urlopen(request, timeout=timeout) as response: return json.load(response) def verify_viewer(dataset_id: str, rows: int, timeout: int = 1800, interval: int = 25) -> dict: """Wait for the Viewer to serve the expected row count. The server re-indexes after every push and returns 500 while it does, sometimes for several minutes, so transient failures are retried rather than reported as errors. """ deadline = time.time() + timeout last = None while time.time() < deadline: try: size = _viewer("size", dataset_id, config="default") served = size["size"]["config"]["num_rows"] valid = _viewer("is-valid", dataset_id) if served == rows: return {"status": "ok", "rows": served, "is_valid": valid} last = f"viewer reports {served} rows, expected {rows}" except Exception as error: # noqa: BLE001 - transient indexing failures last = f"{type(error).__name__}: {error}" time.sleep(interval) return {"status": "timeout", "detail": last} def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("kind", choices=sorted(TARGETS)) parser.add_argument("--release", type=Path, default=None) parser.add_argument("--check-only", action="store_true") parser.add_argument("--skip-verify", action="store_true") args = parser.parse_args(argv) report = publish(args.kind, args.release, dry_run=args.check_only) print(json.dumps({k: v for k, v in report.items() if k != "checksums"}, indent=2)) if args.check_only: return 0 if not args.skip_verify: report["viewer"] = verify_viewer(report["dataset_id"], report["rows"]) print(json.dumps(report["viewer"], indent=2)[:600]) out = ROOT / "results" / "publishing" / report["release"] out.mkdir(parents=True, exist_ok=True) (out / "publication.json").write_text( json.dumps(report, ensure_ascii=False, indent=1) + "\n", encoding="utf-8" ) print(f"wrote {out / 'publication.json'}") return 0 if __name__ == "__main__": raise SystemExit(main())