Datasets:

Modalities:
Text
Formats:
text
Size:
< 1K
Libraries:
Datasets
File size: 8,633 Bytes
400d310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
"""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  # noqa: E402
from huggingface_hub import HfApi  # noqa: E402

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",  # Hindi, Devanagari
    "ben_Beng",  # Bengali
    "tam_Taml",  # Tamil
    "rus_Cyrl",  # Russian, Cyrillic
    "arb_Arab",  # Arabic (MSA), RTL
    "heb_Hebr",  # Hebrew, RTL
    "jpn_Jpan",  # Japanese, mixed kanji/kana
    "kor_Hang",  # Korean, Hangul
    "cmn_Hani",  # Mandarin, Han
    "tha_Thai",  # Thai, no word separators
    "ell_Grek",  # Greek
    "kat_Geor",  # Georgian
    "amh_Ethi",  # Amharic, Ethiopic
]

# the-stack-smol would be preferable but is gated; these are pinned-SHA GitHub
# tarballs instead, read in memory only (never extracted to disk).
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"))

    # pins is filled while gen() runs; build() reads meta only after consuming docs
    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():
    # single-shard hf_hub_download instead of streaming: the 249MB shard's
    # range-reads time out on unauthenticated connections
    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())