"""FineWeb-Edu documents about science (general educational English, keyword-filtered).""" from __future__ import annotations import json from collections.abc import Iterator from pathlib import Path import regex from zenith.data.sources._hf_parquet import read_jsonl, stream_to_jsonl from zenith.data.sources.base import Record NAME = "fineweb_sci" GROUP = "general" LICENSE = "ODC-By 1.0" REPO = "HuggingFaceFW/fineweb-edu" FILES = [f"sample/10BT/{i:03d}_00000.parquet" for i in range(14)] MAX_BYTES = 2_200_000_000 MIN_TERMS = 3 # The HADES project already streamed the first rows of file 000; reuse them read-only. HADES_COPY = Path.home() / "Documents/hades/data/raw/fineweb_edu/part-000.jsonl" SCIENCE_TERMS = frozenset(""" astronomy astronomer astrophysics atmosphere atom atomic axis biology black cell chemistry chemical climate comet comets constellation cosmic cosmology crater density diameter dwarf earthquake eclipse electric electricity electromagnetic electron element elements ellipse energy equation equator evolution experiment force formula frequency friction fusion galaxy galaxies gas geology gravitational gravity heat helium hemisphere hydrogen hypothesis infrared kinetic laboratory laser latitude light luminosity magnetic magnetism mass mathematics matter measurement meteor meteorite molecule molecules momentum moon moons nasa nebula neutron nuclear observatory orbit orbital orbits oxygen particle particles photon photosynthesis physics physicist planet planets planetary plasma pressure proton quantum radiation radioactive radius redshift relativity rocket satellite satellites science scientific scientist scientists solar spacecraft spectrum spectra speed star stars stellar sun supernova telescope temperature theory thermal universe velocity voltage volcano wavelength waves acceleration asteroid asteroids neutrino entropy thermodynamics """.split()) _WORD = regex.compile(r"[a-z]+") def is_science(text: str) -> bool: found = set() for w in _WORD.findall(text.lower()): if w in SCIENCE_TERMS: found.add(w.rstrip("s")) if len(found) >= MIN_TERMS: return True return False def _keep(row: dict) -> bool: return is_science(row["text"]) def fetch(raw_dir: Path, max_bytes: int = MAX_BYTES) -> None: d = Path(raw_dir) / NAME d.mkdir(parents=True, exist_ok=True) reused = 0 first = d / "part-000.jsonl" if HADES_COPY.exists() and not first.exists(): tmp = first.with_name(first.name + ".part") with open(tmp, "w") as out: for row in read_jsonl(HADES_COPY): if _keep(row): out.write(json.dumps({"id": row["id"], "text": row["text"]}, ensure_ascii=False) + "\n") tmp.replace(first) if first.exists(): reused = sum(len(r["text"].encode()) for r in read_jsonl(first)) # HADES read only from file 000, so new rows start at file 001 to avoid duplicates. files = FILES[1:] if first.exists() else FILES stream_to_jsonl(REPO, files, d / "part-001.jsonl", ["id", "text"], max(0, max_bytes - reused), keep=_keep) def iter_records(raw_dir: Path) -> Iterator[Record]: for path in sorted((Path(raw_dir) / NAME).glob("part-*.jsonl")): for row in read_jsonl(path): yield Record(NAME, row["id"], LICENSE, GROUP, row["text"])