#!/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, json, os, re, 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 sources import SOURCES, ADDED POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]") ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE) MIN_CHARS = 200 MIN_POLISH_RATIO = 0.005 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()), ]) _ENC = None # per-worker tiktoken encoder def _init_worker(): global _ENC import tiktoken _ENC = tiktoken.get_encoding("cl100k_base") def _polish_ratio(text): letters = ALPHA_RE.findall(text) return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0 def _process_chunk(args): """Worker: gate + tokenize a batch of raw lines. Returns (records, stats).""" is_ocr, created, lines = args kept, texts = [], [] st = [0, 0, 0, 0] # read, short, lang, ocr for line in lines: st[0] += 1 try: text = (json.loads(line).get("text") or "").strip() except Exception: continue if len(text) < MIN_CHARS: st[1] += 1; continue if _polish_ratio(text) < MIN_POLISH_RATIO: 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) toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else [] for t, tk in zip(texts, toks): kept.append((t, created, tk, hashlib.sha1(t.encode("utf-8")).digest())) 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} t0 = time.time() is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "") bid, btext, bcre, btok = [], [], [], [] 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()), ], schema=SCHEMA)) bid.clear(); btext.clear(); bcre.clear(); btok.clear() proc = subprocess.Popen(["zstd", "-dc", str(src_path)], stdout=subprocess.PIPE, bufsize=1 << 22) line_iter = (ln for ln in proc.stdout if ln.strip()) arg_iter = ((is_ocr, 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, h in kept: if h in seen: st["drop_dup"] += 1; continue seen.add(h) bid.append(f"{name}_{counter[0]}"); counter[0] += 1 btext.append(text); bcre.append(cre); btok.append(tok) st["chars"] += len(text); st["tokens"] += tok; st["kept"] += 1 if len(btext) >= 2000: flush() flush(); writer.close(); proc.stdout.close(); 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, "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()