"""Stream, clean, and subsample the ai4bharat/sangraha verified Hindi split. Streams shards rather than downloading the full dataset (100 parquet shards on the verified/hin split); stops once the target token budget is reached so we never pull more than the experiment needs. """ import hashlib import json from dataclasses import dataclass from pathlib import Path from datasets import load_dataset DATASET_NAME = "ai4bharat/sangraha" DATA_FILES_PATTERN = "verified/hin/data-*.parquet" @dataclass class CorpusStats: """Summary of a cleaned/deduplicated corpus build. Attributes: docs_seen: rows read from the source stream before filtering. docs_kept: rows kept after the min-length and dedup filters. duplicates_dropped: rows dropped because their normalized text was already seen. too_short_dropped: rows dropped for being under min_chars. token_count: whitespace-token count of the kept text (a fast proxy; not the model's actual tokenizer). """ docs_seen: int docs_kept: int duplicates_dropped: int too_short_dropped: int token_count: int def _normalize_for_dedup(text: str) -> str: """Collapse whitespace for a dedup key; does not alter the stored text.""" return " ".join(text.split()) def _hash_key(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def build_corpus(target_tokens: int, out_path: str, min_chars: int = 20) -> CorpusStats: """Stream, clean, dedup, and write the corpus to out_path (one JSON object per line). Stops consuming the source stream as soon as the running whitespace-token count of kept documents meets or exceeds target_tokens. """ ds = load_dataset(DATASET_NAME, data_files=DATA_FILES_PATTERN, split="train", streaming=True) out_file = Path(out_path) out_file.parent.mkdir(parents=True, exist_ok=True) seen_hashes = set() docs_seen = 0 docs_kept = 0 duplicates_dropped = 0 too_short_dropped = 0 token_count = 0 with out_file.open("w", encoding="utf-8") as f: for row in ds: docs_seen += 1 text = row["text"] if len(text) < min_chars: too_short_dropped += 1 continue normalized = _normalize_for_dedup(text) key = _hash_key(normalized) if key in seen_hashes: duplicates_dropped += 1 continue seen_hashes.add(key) n_tokens = len(text.split()) f.write(json.dumps({"text": text, "doc_id": row.get("doc_id")}, ensure_ascii=False) + "\n") docs_kept += 1 token_count += n_tokens if token_count >= target_tokens: break return CorpusStats( docs_seen=docs_seen, docs_kept=docs_kept, duplicates_dropped=duplicates_dropped, too_short_dropped=too_short_dropped, token_count=token_count, )