"""Where documents come from. Two readers share one Source spec: - sample(): a spread sample through the Hugging Face dataset viewer API. No downloads, used by the hosted preview. - stream(): every document, through `datasets` streaming or local JSONL/Parquet files. Used by the runner on your own machines. """ from __future__ import annotations import glob import json import os import time import urllib.error import urllib.parse import urllib.request from dataclasses import asdict, dataclass, field from typing import Iterator VIEWER = "https://datasets-server.huggingface.co" KINDS = ("web", "educational", "textbook", "math", "code", "multilingual", "synthetic", "other") TEXT_FIELDS = ("text", "content", "markdown", "body", "document", "raw_content", "code", "problem", "question", "prompt") @dataclass class Source: """One dataset, registered as a source to curate or as a target that says what good looks like.""" name: str dataset: str = "" # Hugging Face id, e.g. HuggingFaceFW/fineweb-edu config: str = "default" split: str = "train" text_field: str = "text" files: str = "" # local glob instead of a hub id: /data/*.jsonl or /data/*.parquet kind: str = "web" role: str = "source" # source | target num_rows: int = 0 # filled by inspect(); 0 means unknown bytes: int = 0 extra: dict = field(default_factory=dict) def to_dict(self) -> dict: return {k: v for k, v in asdict(self).items() if v not in ("", 0, {}, None)} @staticmethod def from_dict(d: dict) -> "Source": keys = Source.__dataclass_fields__.keys() return Source(**{k: v for k, v in d.items() if k in keys}) def _get(path: str, params: dict, token: str = "", timeout: int = 60, retries: int = 7) -> dict: url = f"{VIEWER}/{path}?{urllib.parse.urlencode(params)}" headers = {"User-Agent": "DataInventor/1.0"} if token: headers["Authorization"] = "Bearer " + token for attempt in range(retries): try: return json.load(urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=timeout)) except urllib.error.HTTPError as e: if e.code not in (429, 500, 502, 503, 504) or attempt == retries - 1: raise time.sleep(min(30, 2 * 2 ** attempt)) except (TimeoutError, urllib.error.URLError): if attempt == retries - 1: raise time.sleep(2) raise RuntimeError("unreachable") def inspect(dataset: str, token: str = "") -> dict: """Configs, splits, string columns and sizes for a hub dataset, so the user can pick what to read.""" splits = _get("splits", {"dataset": dataset}, token).get("splits", []) if not splits: raise ValueError("The dataset viewer has no splits for that dataset. Check the id, or that it is public.") first = splits[0] cfg, spl = first["config"], first["split"] for s in splits: # prefer a train split of the default config if s["split"] == "train" and s["config"] in ("default", cfg): cfg, spl = s["config"], s["split"] break cols, sample = [], "" try: fr = _get("first-rows", {"dataset": dataset, "config": cfg, "split": spl}, token) cols = [f["name"] for f in fr.get("features", []) if (f.get("type") or {}).get("dtype") in ("string", "large_string")] if fr.get("rows"): sample = fr["rows"][0]["row"] except Exception: pass field_ = next((c for c in TEXT_FIELDS if c in cols), cols[0] if cols else "text") sizes = {} try: for c in _get("size", {"dataset": dataset}, token).get("size", {}).get("splits", []): sizes[(c["config"], c["split"])] = (c.get("num_rows", 0), c.get("num_bytes_parquet_files", 0)) except Exception: pass rows, nbytes = sizes.get((cfg, spl), (0, 0)) preview = str((sample or {}).get(field_, ""))[:4000] if isinstance(sample, dict) else "" return {"dataset": dataset, "config": cfg, "split": spl, "splits": [{"config": s["config"], "split": s["split"]} for s in splits][:40], "columns": cols, "text_field": field_, "num_rows": rows, "bytes": nbytes, "preview": preview, "kind": guess_kind(dataset)} def guess_kind(dataset: str) -> str: d = dataset.lower().split("/")[-1] # the owner name says nothing about the content if any(k in d for k in ("math", "gsm", "proof", "numina")): return "math" if any(k in d for k in ("stack", "code", "github")): return "code" if any(k in d for k in ("pdf", "textbook", "sutra", "cosmopedia", "wiki")): return "textbook" if "edu" in d: return "educational" if any(k in d for k in ("fineweb-2", "multiling", "culturax", "madlad", "hplt")): return "multilingual" return "web" def sample(src: Source, n: int, token: str = "", chunks: int = 4) -> list[dict]: """Up to n documents read from `chunks` evenly spaced offsets, so a sample is not just the first shard.""" if src.files: out = [] for d in stream(src): out.append(d) if len(out) >= n: break return out total = src.num_rows or 0 per = max(1, min(100, -(-n // chunks))) offsets = [0] if total <= n else [int(total * (i + 0.5) / chunks) for i in range(chunks)] out, seen = [], set() for off in offsets: try: got = _get("rows", {"dataset": src.dataset, "config": src.config, "split": src.split, "offset": off, "length": per}, token) except Exception as e: if not out and off == offsets[-1]: raise ValueError(f"Could not read rows from {src.dataset}: {e}") continue for r in got.get("rows", []): idx = r.get("row_idx", off) text = (r.get("row") or {}).get(src.text_field) if isinstance(text, str) and text.strip() and idx not in seen: seen.add(idx) out.append({"id": f"{src.name}:{idx}", "text": text, "source": src.name, "kind": src.kind}) if len(out) >= n: break return out[:n] def stream(src: Source, skip: int = 0) -> Iterator[dict]: """Every document in the source. Local files are read directly; hub datasets stream through `datasets`.""" if src.files: paths = sorted(glob.glob(os.path.expanduser(src.files))) if not paths: raise ValueError(f"No files match {src.files}") i = 0 for p in paths: for row in _read_file(p): text = row.get(src.text_field) if isinstance(text, str) and text.strip(): if i >= skip: yield {"id": f"{src.name}:{i}", "text": text, "source": src.name, "kind": src.kind} i += 1 return try: from datasets import load_dataset except ImportError as e: # pragma: no cover raise SystemExit("Reading a hub dataset in full needs `pip install datasets`.") from e ds = load_dataset(src.dataset, None if src.config == "default" else src.config, split=src.split, streaming=True) if skip: ds = ds.skip(skip) for i, row in enumerate(ds, start=skip): text = row.get(src.text_field) if isinstance(text, str) and text.strip(): yield {"id": f"{src.name}:{i}", "text": text, "source": src.name, "kind": src.kind} def _read_file(path: str) -> Iterator[dict]: if path.endswith((".jsonl", ".json")): with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: yield json.loads(line) except json.JSONDecodeError: continue elif path.endswith(".parquet"): import pyarrow.parquet as pq for batch in pq.ParquetFile(path).iter_batches(batch_size=2048): yield from batch.to_pylist() elif path.endswith(".txt"): with open(path, encoding="utf-8") as f: yield {"text": f.read()} else: raise ValueError(f"Unsupported file type: {path} (use .jsonl, .parquet or .txt)")