File size: 7,909 Bytes
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4f2b0d
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4f2b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfe406c
 
a4f2b0d
cfe406c
 
a4f2b0d
cfe406c
 
 
a4f2b0d
 
cfe406c
 
 
 
 
 
 
 
 
 
 
a4f2b0d
 
 
 
cfe406c
a4f2b0d
 
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4f2b0d
 
cfe406c
 
a4f2b0d
 
cfe406c
 
 
 
 
 
 
 
a4f2b0d
cfe406c
a4f2b0d
cfe406c
 
 
 
a4f2b0d
cfe406c
 
 
a4f2b0d
cfe406c
 
 
 
 
a4f2b0d
cfe406c
a4f2b0d
 
 
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/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()),
    ("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 _polish_ratio(text):
    letters = ALPHA_RE.findall(text)
    return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0


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, created, default_license, 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 _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)
        metas.append((
            _meta_value(row, ("license", "licence", "rights", "edm:rights"), default_license),
            _meta_value(row, ("author", "authors", "creator", "creators")),
        ))
    toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else []
    for t, (license_value, author), tk in zip(texts, metas, toks):
        kept.append((t, created, tk, license_value, author, 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,
          "licenses": {}, "authors_with_value": 0}
    t0 = time.time()
    is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "")
    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 = 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, default_license, 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 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)
            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(); 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 <names> 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()