#!/usr/bin/env python3 """Build Polish DynaWord parquet shards from SpeakLeash .jsonl.zst sources. Parallel pipeline (uses all cores). Per source (paper 2508.02271, minimal gates): stream jsonl.zst -> [workers: parse + Polish-lang check + drop-short + OCR alpha-ratio + tiktoken token_count + sha1] -> [main: cross-source exact dedup + id + parquet write]. Sources processed in priority order so earlier sources win duplicates (wikipedia > wikisource > ...). Heavy quality filtering + mix-weighting are downstream (CPT), not here. token_count is a fast tiktoken proxy (~1% off Llama-3); canonical Llama-3 recount happens at release. Usage: python3 src/build_dynaword.py --all --speakleash-dir ~/speakleash --out ~/dynaword python3 src/build_dynaword.py --sources gutenberg --jobs 16 """ from __future__ import annotations import argparse, hashlib, io, json, os, shutil, subprocess, sys, time from itertools import islice import multiprocessing as mp from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq sys.path.insert(0, str(Path(__file__).resolve().parent)) from language_gate import ALPHA_RE, GATE, is_polish from sources import SOURCES, ADDED MIN_CHARS = 200 MIN_ALPHA_RATIO = 0.70 SCHEMA = pa.schema([ ("id", pa.string()), ("text", pa.string()), ("source", pa.string()), ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()), ("license", pa.string()), ("author", pa.string()), ]) _ENC = None # per-worker tiktoken encoder def _init_worker(): global _ENC import tiktoken _ENC = tiktoken.get_encoding("cl100k_base") def _first_text(value) -> str: if value is None: return "" if isinstance(value, list): return "; ".join(str(item).strip() for item in value if str(item).strip()) return str(value).strip() def _meta_value(row: dict, keys: tuple[str, ...], default: str = "") -> str: for key in keys: value = _first_text(row.get(key)) if value: return value return default def _process_chunk(args): """Worker: gate + tokenize a batch of raw lines. Returns (records, stats).""" is_ocr, lang_gate, created, default_license, preserve_created, lines = args kept, texts = [], [] st = [0, 0, 0, 0] # read, short, lang, ocr metas = [] for line in lines: st[0] += 1 try: row = json.loads(line) text = (row.get("text") or "").strip() except Exception: continue if len(text) < MIN_CHARS: st[1] += 1; continue if lang_gate and not is_polish(text): st[2] += 1; continue if is_ocr: ar = len(ALPHA_RE.findall(text)) / len(text) if text else 0.0 if ar < MIN_ALPHA_RATIO: st[3] += 1; continue texts.append(text) metas.append(( _meta_value(row, ("created", "date", "published", "publication_date"), created) if preserve_created else created, _meta_value(row, ("license", "licence", "rights", "edm:rights"), default_license), _meta_value(row, ("author", "authors", "creator", "creators")), _meta_value(row, ("id", "record_id")), )) toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else [] for t, (created_value, license_value, author, record_id), tk in zip(texts, metas, toks): kept.append(( t, created_value, tk, license_value, author, hashlib.sha1(t.encode("utf-8")).digest(), record_id, )) return kept, st def _chunks(iterable, n): it = iter(iterable) while batch := list(islice(it, n)): yield batch def build_source(name, cfg, sl_dir, out_root, pool, seen, counter): src_path = sl_dir / f"{cfg.get('file_key', cfg.get('speakleash_key'))}.jsonl.zst" if not src_path.exists(): print(f" ! missing {src_path}"); return None out_dir = out_root / "data" / name out_dir.mkdir(parents=True, exist_ok=True) writer = pq.ParquetWriter(out_dir / f"{name}.parquet", SCHEMA, compression="zstd") st = {"read": 0, "kept": 0, "drop_short": 0, "drop_lang": 0, "drop_dup": 0, "drop_ocr": 0, "chars": 0, "tokens": 0, "licenses": {}, "authors_with_value": 0} t0 = time.time() is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "") added = cfg.get("added", ADDED) # the registry date; ADDED only for a source without one lang_gate = not cfg.get("polish_by_origin") preserve_id = bool(cfg.get("preserve_id")) preserve_created = bool(cfg.get("preserve_created")) used_ids = set() default_license = cfg.get("license", "") bid, btext, bcre, btok, blic, baut = [], [], [], [], [], [] def flush(): if not btext: return n = len(btext) writer.write(pa.record_batch([ pa.array(bid), pa.array(btext), pa.array([name] * n), pa.array([added] * n), pa.array(bcre), pa.array(btok, pa.int64()), pa.array(blic), pa.array(baut), ], schema=SCHEMA)) bid.clear(); btext.clear(); bcre.clear(); btok.clear(); blic.clear(); baut.clear() proc = None stream = None compressed = None executable = shutil.which("zstd") if executable: proc = subprocess.Popen([executable, "-dc", str(src_path)], stdout=subprocess.PIPE, bufsize=1 << 22) stream = proc.stdout else: try: import zstandard except ImportError as exc: raise RuntimeError( "reading .zst requires zstd or Python zstandard: pip install zstandard" ) from exc compressed = src_path.open("rb") stream = io.TextIOWrapper( zstandard.ZstdDecompressor().stream_reader(compressed), encoding="utf-8" ) line_iter = (ln for ln in stream if ln.strip()) arg_iter = ((is_ocr, lang_gate, created, default_license, preserve_created, ch) for ch in _chunks(line_iter, 2000)) for kept, cst in pool.imap_unordered(_process_chunk, arg_iter, chunksize=1): st["read"] += cst[0]; st["drop_short"] += cst[1] st["drop_lang"] += cst[2]; st["drop_ocr"] += cst[3] for text, cre, tok, license_value, author, h, record_id in kept: if h in seen: st["drop_dup"] += 1; continue seen.add(h) output_id = record_id if preserve_id and record_id else f"{name}_{counter[0]}" if output_id in used_ids: raise ValueError(f"duplicate record id in {name}: {output_id}") used_ids.add(output_id) bid.append(output_id); counter[0] += 1 btext.append(text); bcre.append(cre); btok.append(tok) blic.append(license_value); baut.append(author) st["chars"] += len(text); st["tokens"] += tok; st["kept"] += 1 st["licenses"][license_value] = st["licenses"].get(license_value, 0) + 1 if author: st["authors_with_value"] += 1 if len(btext) >= 2000: flush() flush(); writer.close(); stream.close() if compressed is not None: compressed.close() if proc is not None: proc.wait() st["secs"] = round(time.time() - t0, 1) print(f" {name}: read {st['read']:,} kept {st['kept']:,} | -short {st['drop_short']:,} " f"-lang {st['drop_lang']:,} -dup {st['drop_dup']:,} -ocr {st['drop_ocr']:,} | " f"{st['chars']/1e6:.0f}M chars, {st['tokens']/1e6:.1f}M tok | {st['secs']}s", flush=True) (out_dir / f"{name}.stats.json").write_text(json.dumps( {**st, "lang_gate": GATE if lang_gate else None, "license": cfg["license"]}, indent=2)) return st def main(): ap = argparse.ArgumentParser() ap.add_argument("--sources", nargs="*", default=None) ap.add_argument("--all", action="store_true") ap.add_argument("--speakleash-dir", default="~/speakleash") ap.add_argument("--out", default=".") ap.add_argument("--jobs", type=int, default=os.cpu_count()) args = ap.parse_args() names = list(SOURCES) if args.all else (args.sources or []) if not names: print("specify --sources or --all"); return sl_dir = Path(args.speakleash_dir).expanduser().resolve() out_root = Path(args.out).expanduser().resolve() print(f"jobs={args.jobs} | speakleash={sl_dir} | out={out_root} | sources={names}", flush=True) seen, counter, totals = set(), [0], [] t0 = time.time() with mp.Pool(args.jobs, initializer=_init_worker) as pool: for name in names: if name not in SOURCES: print(f" ? unknown {name}"); continue print(f"[{name}]", flush=True) st = build_source(name, SOURCES[name], sl_dir, out_root, pool, seen, counter) if st: totals.append((name, st)) tt = sum(s["tokens"] for _, s in totals) td = sum(s["kept"] for _, s in totals) print(f"\nTOTAL: {td:,} docs, {tt/1e9:.2f}B tok (tiktoken proxy), " f"{len(seen):,} unique | wall {round(time.time()-t0,1)}s", flush=True) if __name__ == "__main__": main()