| |
| """Build multilingual + modality text fixtures for tokenizer benchmarks. |
| |
| Streams a few MB of real text per language/modality from public Hugging Face |
| datasets and writes plain .txt files into lang/ and modalities/ next to this |
| script, plus a fixtures_manifest.json recording source dataset, config, |
| split, pinned revision SHA, and sizes. See FIXTURES.md for the |
| human-readable version. |
| |
| Usage: |
| uv run --python 3.12 --with 'datasets>=3.2' fetch_fixtures.py [name ...] |
| |
| With no args, builds every fixture. Names are file stems (e.g. hin_Deva). |
| |
| Safety: HF_DATASETS_TRUST_REMOTE_CODE is forced off — only parquet-native |
| datasets are read, no dataset loading scripts ever execute. Downloaded |
| content is treated strictly as text data. |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import os |
| import sys |
| import time |
| from pathlib import Path |
|
|
| os.environ["HF_DATASETS_TRUST_REMOTE_CODE"] = "0" |
|
|
| from datasets import load_dataset |
| from huggingface_hub import HfApi |
|
|
| HERE = Path(__file__).resolve().parent |
| MANIFEST = HERE / "fixtures_manifest.json" |
| MB = 1024 * 1024 |
| LANG_TARGET = 5 * MB |
|
|
| FINEWEB2 = "HuggingFaceFW/fineweb-2" |
| FINEWEB2_CONFIGS = [ |
| "hin_Deva", |
| "ben_Beng", |
| "tam_Taml", |
| "rus_Cyrl", |
| "arb_Arab", |
| "heb_Hebr", |
| "jpn_Jpan", |
| "kor_Hang", |
| "cmn_Hani", |
| "tha_Thai", |
| "ell_Grek", |
| "kat_Geor", |
| "amh_Ethi", |
| ] |
|
|
| |
| |
| CODE_REPOS = [ |
| ("python", "django/django", (".py",)), |
| ("javascript", "jquery/jquery", (".js",)), |
| ("typescript", "vuejs/core", (".ts",)), |
| ("rust", "tokio-rs/tokio", (".rs",)), |
| ("go", "caddyserver/caddy", (".go",)), |
| ("java", "junit-team/junit5", (".java",)), |
| ("c", "redis/redis", (".c", ".h")), |
| ("cpp", "fmtlib/fmt", (".cc", ".h")), |
| ] |
| CODE_SKIP_DIRS = ("deps/", "vendor/", "node_modules/", "third_party", "dist/") |
|
|
| _api = HfApi() |
| _shas: dict[str, str] = {} |
|
|
|
|
| def pinned_sha(repo: str) -> str: |
| if repo not in _shas: |
| _shas[repo] = _api.dataset_info(repo).sha |
| return _shas[repo] |
|
|
|
|
| def stream(repo: str, split: str = "train", **kw): |
| return load_dataset(repo, split=split, streaming=True, revision=pinned_sha(repo), **kw) |
|
|
|
|
| def fineweb2_docs(cfg: str): |
| try: |
| ds, split = stream(FINEWEB2, split="test", name=cfg), "test" |
| except Exception: |
| ds, split = stream(FINEWEB2, split="train", name=cfg), "train" |
| return (ex["text"] for ex in ds), {"config": cfg, "split": split} |
|
|
|
|
| def eng_docs(): |
| ds = stream("HuggingFaceFW/fineweb", name="sample-10BT") |
| return (ex["text"] for ex in ds), {"config": "sample-10BT", "split": "train"} |
|
|
|
|
| def code_docs(): |
| import tarfile |
| import urllib.request |
|
|
| per_lang = (6 * MB) // len(CODE_REPOS) |
| pins: dict[str, str] = {} |
|
|
| def head_sha(repo: str) -> str: |
| req = urllib.request.Request( |
| f"https://api.github.com/repos/{repo}/commits/HEAD", |
| headers={"Accept": "application/vnd.github.sha"}, |
| ) |
| with urllib.request.urlopen(req) as r: |
| return r.read().decode().strip() |
|
|
| def gen(): |
| for lang, repo, exts in CODE_REPOS: |
| sha = head_sha(repo) |
| pins[repo] = sha |
| url = f"https://codeload.github.com/{repo}/tar.gz/{sha}" |
| got = 0 |
| with urllib.request.urlopen(url) as r: |
| with tarfile.open(fileobj=r, mode="r|gz") as tar: |
| for member in tar: |
| if got >= per_lang: |
| break |
| path = member.name.lower() |
| if not member.isfile() or member.size > 200_000: |
| continue |
| if not path.endswith(exts) or any(d in path for d in CODE_SKIP_DIRS): |
| continue |
| text = tar.extractfile(member).read().decode("utf-8", errors="replace") |
| yield f"// {member.name}\n{text}" |
| got += len(text.encode("utf-8")) |
|
|
| |
| return gen(), {"revision": pins} |
|
|
|
|
| def math_docs(): |
| ds = stream("open-web-math/open-web-math") |
| return (ex["text"] for ex in ds), {"split": "train"} |
|
|
|
|
| def agentic_docs(): |
| |
| |
| import pyarrow.parquet as pq |
| from huggingface_hub import hf_hub_download |
|
|
| repo = "SWE-bench/SWE-smith-trajectories" |
| shard = "data/tool-00000-of-00008.parquet" |
| path = hf_hub_download(repo, shard, repo_type="dataset", revision=pinned_sha(repo)) |
|
|
| def rows(): |
| pf = pq.ParquetFile(path) |
| for batch in pf.iter_batches(columns=["messages"], batch_size=8): |
| yield from batch.column("messages").to_pylist() |
|
|
| def render(content): |
| if isinstance(content, str): |
| return content |
| if isinstance(content, list): |
| return "\n".join( |
| b.get("text", json.dumps(b, ensure_ascii=False)) if isinstance(b, dict) else str(b) |
| for b in content |
| ) |
| return json.dumps(content, ensure_ascii=False) |
|
|
| def gen(): |
| for raw in rows(): |
| parts = [] |
| for msg in json.loads(raw): |
| block = f"[{msg.get('role', '?')}]\n{render(msg.get('content', ''))}" |
| if msg.get("tool_calls"): |
| block += "\n" + json.dumps(msg["tool_calls"], ensure_ascii=False) |
| parts.append(block) |
| yield "\n\n".join(parts) |
|
|
| return gen(), {"split": "tool", "config": shard} |
|
|
|
|
| FIXTURES: dict[str, dict] = { |
| cfg: {"source": FINEWEB2, "docs": (lambda c=cfg: fineweb2_docs(c)), "target": LANG_TARGET, "dir": "lang"} |
| for cfg in FINEWEB2_CONFIGS |
| } |
| FIXTURES["eng_Latn"] = {"source": "HuggingFaceFW/fineweb", "docs": eng_docs, "target": LANG_TARGET, "dir": "lang"} |
| FIXTURES["code_mixed"] = {"source": "github.com (pinned repo tarballs)", "docs": code_docs, "target": 6 * MB, "dir": "modalities"} |
| FIXTURES["math_latex"] = {"source": "open-web-math/open-web-math", "docs": math_docs, "target": LANG_TARGET, "dir": "modalities"} |
| FIXTURES["agentic_swe"] = {"source": "SWE-bench/SWE-smith-trajectories", "docs": agentic_docs, "target": LANG_TARGET, "dir": "modalities"} |
|
|
|
|
| def build(name: str, spec: dict) -> dict: |
| docs, meta = spec["docs"]() |
| out = HERE / spec["dir"] / f"{name}.txt" |
| out.parent.mkdir(exist_ok=True) |
| written = n_docs = 0 |
| with open(out, "w", encoding="utf-8") as f: |
| for text in docs: |
| if not text or not text.strip(): |
| continue |
| chunk = text.replace("\0", "").rstrip("\n") + "\n\n" |
| f.write(chunk) |
| written += len(chunk.encode("utf-8")) |
| n_docs += 1 |
| if written >= spec["target"]: |
| break |
| if "revision" not in meta: |
| meta["revision"] = pinned_sha(spec["source"]) |
| return { |
| "file": f"{spec['dir']}/{out.name}", |
| "source": spec["source"], |
| **meta, |
| "bytes": written, |
| "docs": n_docs, |
| "built_at": time.strftime("%Y-%m-%d", time.gmtime()), |
| "builder": Path(__file__).name, |
| } |
|
|
|
|
| def main() -> int: |
| names = sys.argv[1:] or list(FIXTURES) |
| unknown = [n for n in names if n not in FIXTURES] |
| if unknown: |
| print(f"unknown fixtures: {unknown}\navailable: {list(FIXTURES)}", file=sys.stderr) |
| return 2 |
|
|
| manifest = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {} |
| failures = [] |
| for name in names: |
| print(f"building {name} ...", flush=True) |
| try: |
| entry = build(name, FIXTURES[name]) |
| except Exception as e: |
| print(f" FAILED {name}: {type(e).__name__}: {e}", file=sys.stderr, flush=True) |
| failures.append(name) |
| continue |
| manifest[name] = entry |
| MANIFEST.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") |
| print(f" {entry['bytes'] / MB:.1f} MB, {entry['docs']} docs", flush=True) |
|
|
| if failures: |
| print(f"failed: {failures}", file=sys.stderr) |
| return 1 if failures else 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|