Datasets:
Translation-resource audit of 325 FineWiki languages (finewiki_audit_20261114T182048Z)
8a1e1d9 verified Download scripts/publish_lang_audit.py from sigiranic/language-status: direct link, hf CLI and curl.
- Browser
- Download file 8.59 kB
-
https://huggingface.co/datasets/sigiranic/language-status/resolve/main/scripts/publish_lang_audit.py
- Command line
-
hf download hf://datasets/sigiranic/language-status/scripts/publish_lang_audit.py
-
curl -L -o publish_lang_audit.py https://huggingface.co/datasets/sigiranic/language-status/resolve/main/scripts/publish_lang_audit.py
8.59 kB
| """Publish the FineWiki translation-resource audit as a Hugging Face dataset. | |
| Validates the staged release, uploads it, then waits for the native Dataset Viewer to | |
| report the expected row count. The credential comes from ``hf_publishing_auth`` 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.error | |
| 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 | |
| DATASET_ID = "sigiranic/language-status" | |
| SECRET_PATTERN = re.compile(rb"hf_[A-Za-z0-9]{20,}") | |
| # Created by the Hub itself when a repository is initialised. | |
| HUB_GENERATED = {".gitattributes"} | |
| 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 staged_files(release: Path) -> list[Path]: | |
| return sorted(p for p in release.rglob("*") if p.is_file()) | |
| def validate_stage(release: Path, token: str | None = None) -> dict: | |
| """Check the staged release is complete, self-consistent and credential-free.""" | |
| manifest_path = release / "manifest.json" | |
| if not manifest_path.exists(): | |
| raise RuntimeError(f"no manifest.json in {release}") | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| files = staged_files(release) | |
| relative = {str(p.relative_to(release)) for p in files} | |
| required = {"README.md", "manifest.json", "languages.jsonl", "data/languages.parquet"} | |
| missing = required - relative | |
| if missing: | |
| raise RuntimeError(f"staged release is missing {sorted(missing)}") | |
| if not any(name.startswith("sources/") for name in relative): | |
| raise RuntimeError("staged release carries no sources/ snapshots") | |
| for name, expected in manifest["files"].items(): | |
| actual = _sha256(release / name) | |
| if actual != expected: | |
| raise RuntimeError(f"{name}: checksum {actual} does not match manifest {expected}") | |
| for path in files: | |
| blob = path.read_bytes() | |
| if SECRET_PATTERN.search(blob): | |
| raise RuntimeError(f"{path} contains a credential-like token; refusing to upload") | |
| if token and token.encode() in blob: | |
| raise RuntimeError(f"{path} contains the publishing credential") | |
| import pyarrow.parquet as pq | |
| table = pq.read_table(release / "data" / "languages.parquet") | |
| expected_rows = manifest["summary"]["languages"] | |
| if table.num_rows != expected_rows: | |
| raise RuntimeError(f"parquet has {table.num_rows} rows, manifest says {expected_rows}") | |
| jsonl_rows = sum(1 for _ in (release / "languages.jsonl").open(encoding="utf-8")) | |
| if jsonl_rows != expected_rows: | |
| raise RuntimeError(f"languages.jsonl has {jsonl_rows} rows, expected {expected_rows}") | |
| if list(table.schema.names) != manifest["columns"]: | |
| raise RuntimeError("parquet columns do not match the manifest column order") | |
| configs = table.column("finewiki_config").to_pylist() | |
| if len(set(configs)) != len(configs): | |
| raise RuntimeError("finewiki_config is not unique") | |
| return { | |
| "release": str(release), | |
| "files": len(files), | |
| "rows": table.num_rows, | |
| "columns": len(table.schema.names), | |
| "bytes": sum(p.stat().st_size for p in files), | |
| "manifest": manifest, | |
| } | |
| def publish(release: Path, dataset_id: str = DATASET_ID) -> dict: | |
| from huggingface_hub import HfApi | |
| token = publishing_token() | |
| report = validate_stage(release, token=token) | |
| api = HfApi(token=token) | |
| api.create_repo(dataset_id, repo_type="dataset", private=False, exist_ok=True) | |
| info = api.dataset_info(dataset_id) | |
| existing = {s.rfilename for s in info.siblings} - HUB_GENERATED | |
| staged = {str(p.relative_to(release)) for p in staged_files(release)} | |
| extra = existing - staged | |
| if extra: | |
| print(f"note: repository already holds files not in this release: {sorted(extra)[:10]}") | |
| commit = api.upload_folder( | |
| repo_id=dataset_id, | |
| repo_type="dataset", | |
| folder_path=str(release), | |
| commit_message=( | |
| f"Translation-resource audit of {report['rows']} FineWiki languages " | |
| f"({report['manifest']['release_id']})" | |
| ), | |
| ) | |
| report["dataset_url"] = f"https://huggingface.co/datasets/{dataset_id}" | |
| report["commit"] = getattr(commit, "oid", None) or str(commit) | |
| return report | |
| def _viewer(endpoint: str, dataset_id: str, timeout: int = 120, **params) -> dict: | |
| query = urllib.parse.urlencode({"dataset": dataset_id, **params}) | |
| url = f"https://datasets-server.huggingface.co/{endpoint}?{query}" | |
| request = urllib.request.Request(url, headers={"User-Agent": "gilaki-lang-audit/1.0"}) | |
| with urllib.request.urlopen(request, timeout=timeout) as response: | |
| return json.load(response) | |
| def verify_viewer(dataset_id: str, expected_rows: int, timeout: int = 900, interval: int = 20) -> dict: | |
| """Poll the public Dataset Viewer until it reports the expected rows, or give up.""" | |
| deadline = time.time() + timeout | |
| last = None | |
| while time.time() < deadline: | |
| try: | |
| splits = _viewer("splits", dataset_id) | |
| size = _viewer("size", dataset_id) | |
| if splits.get("pending") or splits.get("failed"): | |
| last = f"splits pending={splits.get('pending')} failed={splits.get('failed')}" | |
| elif size.get("partial"): | |
| last = "size report is partial" | |
| else: | |
| rows = sum(c["num_rows"] for c in size["size"]["configs"] | |
| if c["config"] != "default") | |
| if rows == expected_rows: | |
| config, split = ( | |
| splits["splits"][0]["config"], splits["splits"][0]["split"] | |
| ) | |
| first = _viewer("first-rows", dataset_id, config=config, split=split) | |
| valid = _viewer("is-valid", dataset_id) | |
| return { | |
| "status": "ok", | |
| "rows": rows, | |
| "splits": [(s["config"], s["split"]) for s in splits["splits"]], | |
| "columns": [f["name"] for f in first["features"]], | |
| "first_row_language": first["rows"][0]["row"].get("finewiki_config"), | |
| "viewer_enabled": valid.get("viewer"), | |
| "search_enabled": valid.get("search"), | |
| } | |
| last = f"viewer reports {rows} rows, expected {expected_rows}" | |
| except urllib.error.HTTPError as error: | |
| last = f"HTTP {error.code}" | |
| except Exception as error: # noqa: BLE001 - transient while the viewer indexes | |
| last = f"{type(error).__name__}: {error}" | |
| print(f" viewer not ready ({last}); retrying in {interval}s", flush=True) | |
| time.sleep(interval) | |
| return {"status": "timeout", "detail": last} | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("release", type=Path, help="staged release directory") | |
| parser.add_argument("--dataset-id", default=DATASET_ID) | |
| parser.add_argument("--check-only", action="store_true") | |
| parser.add_argument("--skip-verify", action="store_true") | |
| args = parser.parse_args(argv) | |
| if args.check_only: | |
| report = validate_stage(args.release) | |
| print(json.dumps({k: v for k, v in report.items() if k != "manifest"}, indent=2)) | |
| return 0 | |
| report = publish(args.release, args.dataset_id) | |
| print(f"uploaded commit {report['commit']} -> {report['dataset_url']}") | |
| if not args.skip_verify: | |
| verification = verify_viewer(args.dataset_id, report["rows"]) | |
| print(json.dumps(verification, indent=2)) | |
| results = ROOT / "results" / "publishing" / report["manifest"]["release_id"] | |
| results.mkdir(parents=True, exist_ok=True) | |
| (results / "lang_audit_publication.json").write_text( | |
| json.dumps( | |
| {k: v for k, v in report.items() if k != "manifest"} | {"viewer": verification}, | |
| ensure_ascii=False, indent=1, | |
| ) + "\n", | |
| encoding="utf-8", | |
| ) | |
| if verification["status"] != "ok": | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |