kacperwikiel commited on
Commit
cfe406c
·
0 Parent(s):

Squash: collapse LFS history to reclaim private storage

Browse files
.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
BLOGPOST.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to Train: a 100% openly-licensed Polish LLM stack
2
+
3
+ *Draft — Slayer Labs. Doubles as the skeleton for a short tech report.*
4
+
5
+ ## TL;DR
6
+
7
+ - We built **Polish DynaWord**, a Polish pre-training corpus where **every single token is openly licensed for model training**, with a documented legal basis per source.
8
+ - **5.64B tokens · 2.38M documents · 6 sources** — larger than Danish Dynaword (4.8B), the reference edition in the family.
9
+ - We trained a **dedicated 32k Polish BPE** that encodes Polish **1.75× tighter than Bielik's tokenizer** and **1.58× tighter than Llama-3** — at a quarter of Llama-3's vocabulary.
10
+ - We are training a small LM **from scratch on this corpus** with a modern stack (modded-nanogpt: Muon, RoPE, RMSNorm, QK-norm, SwiGLU). The result is a model whose **entire provenance — data, tokenizer, and training — is legally defensible end-to-end.**
11
+ - Everything is released: corpus, tokenizer, and reproducible build scripts.
12
+
13
+ ---
14
+
15
+ ## 1. The problem: clean data is the hard part
16
+
17
+ Most "open" pre-training datasets ride on Common Crawl, whose underlying content carries ambiguous rights. That ambiguity is not academic: projects have been pulled or never released over exactly this (the Dynaword paper, [arXiv:2508.02271](https://arxiv.org/abs/2508.02271), cites a shut-down music generator, a withdrawn Danish encoder, and the never-released Nordic Pile).
18
+
19
+ For Polish specifically, there was no openly-licensed, traceable, continuously-maintained corpus in the [Dynaword](https://huggingface.co/datasets/danish-foundation-models/danish-dynaword) family. Danish, Norwegian, Swedish, Icelandic — yes. Polish — no. That gap is the project.
20
+
21
+ The interesting work is **not** downloading text. It is the licensing, deduplication, decontamination, and provenance — putting each source in the right place with the right paper trail. That is what takes time; the bytes are commodity.
22
+
23
+ ## 2. The corpus
24
+
25
+ We follow the Dynaword guidelines literally:
26
+
27
+ 1. **Open & traceable licensing.** Not "this is public domain" but *why* — statutory basis or upstream license, documented per source.
28
+ 2. **Reproducibility.** A single script rebuilds the corpus from sources.
29
+ 3. **Documented.** A datasheet per source.
30
+ 4. **Extensibility.** Versioned; new sources by contribution.
31
+
32
+ **Sources (v0.1):**
33
+
34
+ | source | license | documents | tokens |
35
+ |---|---|---:|---:|
36
+ | Legal & official (EU law + parliamentary) | CC-BY-4.0 / official documents (art. 4) | 567k | 4.0B |
37
+ | Encyclopedic & reference (Wikipedia + Wikisource) | CC-BY-SA-3.0 | 1.80M | 1.5B |
38
+ | Literature & books (public-domain collections) | CC-BY-SA-4.0 / public domain | 6k | 0.1B |
39
+ | **total** | | **2.38M** | **5.64B** |
40
+
41
+ Only **human-authored** text — no synthetic, machine-translated, or auto-transcribed data. Gates are deliberately minimal (drop short docs, non-Polish, exact duplicates, OCR garble); heavy quality filtering and mix-weighting belong downstream, in training, not in the released corpus.
42
+
43
+ **What we excluded, and why** (transparency matters as much as inclusion):
44
+
45
+ - **Movie/TV subtitles** — derivative of copyrighted dialogue; mostly unlicensed uploads. This is the exact lesson Danish Gigaword learned with OpenSubtitles. Out.
46
+ - **A large cultural-heritage aggregate** — mixed per-record rights (public-domain *and* rights-reserved in one bucket). Needs per-record rights filtering before any inclusion.
47
+ - **A "novels" corpus** — labelled permissive, but likely contains in-copyright contemporary works. Pending title-level verification.
48
+
49
+ The data itself comes from an open redistribution of these upstream sources; the redistributor is credited, and each upstream license/attribution is preserved.
50
+
51
+ ### Sidebar: the download was its own little puzzle
52
+
53
+ The source host caps throughput at **~1.5 MB/s per IP** (confirmed identical across three machines — it is per-IP policing, not our link). Single-stream TCP collapsed under packet loss; parallel connections plateaued at the per-IP ceiling. The fix was simply **more IPs**: we sharded the corpus — and byte-range-split the 8.9 GB long-pole file — across three machines in parallel, reassembling on the target box. A reminder that the ceiling is rarely where you first think it is.
54
+
55
+ ## 3. The tokenizer: a Polish BPE that beats Bielik
56
+
57
+ nanoGPT-style stacks default to GPT-2's byte-level BPE — which is terrible on Polish. So we trained a **32k byte-level Polish BPE** on a domain-balanced ~1 GB sample (capping the 71%-legal skew so the tokenizer doesn't overfit to legalese). Training took **51 seconds**.
58
+
59
+ Then we measured **fertility** (tokens per word) on held-out Polish, against the obvious baselines:
60
+
61
+ ![tokenizer fertility](polish_tokenizer_fertility.png)
62
+
63
+ | tokenizer | vocab | tok/word | vs ours |
64
+ |---|---:|---:|---:|
65
+ | **Polish-32k (ours)** | 32,768 | **1.74** | 1.00× |
66
+ | Llama-3 | 128,000 | 2.74 | 1.58× worse |
67
+ | Bielik-11B-v3 | 32,000 | 3.04 | **1.75× worse** |
68
+ | GPT-2 | 50,257 | 3.66 | 2.10× worse |
69
+
70
+ The headline: **our 32k Polish BPE encodes Polish 1.75× more efficiently than Bielik's** — at the *same* vocabulary size. And Bielik is *worse than Llama-3*, despite Llama having a 4× larger vocab.
71
+
72
+ Why? **Bielik-11B-v3 is built on Mistral and inherited Mistral's tokenizer** — a general multilingual 32k vocab, never trained on Polish. It never got a Polish-native tokenizer. A dedicated Polish BPE sees the same text roughly twice as densely.
73
+
74
+ Practically this means: ~2× more text per context window, and the same FLOPs train on ~2× more Polish. (Caveat for the rigorous: the held-out sample is in-domain Wikipedia; all four tokenizers see identical text, and the 1.75× gap is too large to be a domain artifact, but a fully out-of-domain re-test strengthens the published number.)
75
+
76
+ ## 4. The model: clean provenance, end to end
77
+
78
+ A model is only as "open" as its *entire* lineage. Continually pre-training someone else's checkpoint inherits that checkpoint's data-provenance questions. So we train **from scratch** on the clean corpus.
79
+
80
+ We use **modded-nanogpt** (Keller Jordan's speedrun stack — Muon optimizer, RoPE, RMSNorm, QK-norm, SwiGLU, fp8): a modern 124M-scale architecture, already validated, far more FLOP-efficient than vanilla GPT-2. We swap in our Polish BPE and retokenize the corpus into training shards.
81
+
82
+ Target: a 124M (and later ~350M) Polish LM trained entirely on openly-licensed data, in ~one night on a single H100.
83
+
84
+ > **[Results pending]** — loss curves, held-out perplexity, and a Polish eval (PolNative) to go here. The claim we are validating, à la the Dynaword paper's training experiments: clean, openly-licensed data is enough to train a capable Polish LM.
85
+
86
+ ## 5. Why it matters
87
+
88
+ Put together, this is a Polish language-model stack where you can point at **every** component — the data, the tokenizer, the training run — and trace it to a license that permits the use. No scraped text of unknown rights. No copyrighted media. That is the spirit of the Open Source AI definition, applied end-to-end, for a language that didn't have it.
89
+
90
+ ## 6. Release
91
+
92
+ - **Corpus:** `SlayerLab/polish-dynaword` (HF dataset, CC-BY-SA-4.0; per-source datasheets).
93
+ - **Tokenizer:** `polish_bpe_32k.json`.
94
+ - **Code:** reproducible build + tokenization + training scripts.
95
+
96
+ *Built on the shoulders of the Dynaword guidelines (Enevoldsen et al., 2025) and the open-data communities behind every source.*
CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## v0.2.0 (2026-06-15)
4
+
5
+ - Initial release: 11 openly-licensed sources, 2,490,773 docs, 6.22B tokens (tiktoken proxy).
6
+ - Sources: eurlex, parliamentary, wikisource, wikipedia, dziennik_ustaw, wolne_lektury, wikiquote, eltec_pol, wikivoyage, wikibooks, wikinews.
7
+ - Excluded (see README): open_subtitles_corpus, europeana_eu_pl_corpus, 1000_novels_corpus_CLARIN-PL, project_gutenberg_pl_corpus.
LICENSE ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Polish DynaWord is released under Creative Commons Attribution-ShareAlike 4.0
2
+ International (CC-BY-SA-4.0): https://creativecommons.org/licenses/by-sa/4.0/
3
+
4
+ Per-source upstream licenses and attribution are documented in each
5
+ data/<source>/<source>.md datasheet.
PAPER.md ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Polish DynaWord: An Openly-Licensed, Traceable, Continuously-Developed Pretraining Corpus for Polish
2
+
3
+ **Kacper Wikieł**
4
+ SlayerLab · `k.wikiel@gmail.com`
5
+
6
+ ---
7
+
8
+ ## Abstract
9
+
10
+ We present **Polish DynaWord**, an openly-licensed, human-authored text corpus for
11
+ Polish, built as a Polish edition of the *Dynaword* family (Enevoldsen et al.,
12
+ 2025, arXiv:2508.02271). The corpus follows four principles inherited from
13
+ Dynaword — **open and traceable licensing, reproducibility, per-source
14
+ documentation, and versioned extensibility** — and explicitly treats *curation*,
15
+ not raw text collection, as its contribution. Version 0.2.0 comprises **2,490,773
16
+ documents and ≈6.22 billion tokens** (tiktoken `cl100k` proxy) drawn from eleven
17
+ openly-licensed Polish sources, each vetted for a *documented* legal basis rather
18
+ than a vague "public domain" claim. Five sources are openly-licensed corpora
19
+ redistributed via SpeakLeash; the remaining six are fetched *directly* from
20
+ upstream — Polish primary legislation (Dziennik Ustaw / Monitor Polski) via the
21
+ Sejm ELI API, four Wikimedia sibling projects (Wikinews, Wikivoyage, Wikibooks,
22
+ Wikiquote) via the official dumps, and the ELTeC-pol literary collection via
23
+ GitHub — each with full per-document provenance. Beyond scale, this broadens the
24
+ *register* coverage from encyclopedic/legal/literary-classic text toward
25
+ news, travel, instructional and quotation prose. We report the construction
26
+ pipeline, the per-source legal review (including the sources we deliberately
27
+ *exclude* and why), and the dataset statistics. The corpus exceeds the 4.8B-token
28
+ Danish Dynaword in scale while maintaining a comparably conservative licensing
29
+ posture.
30
+
31
+ ---
32
+
33
+ ## 1. Introduction
34
+
35
+ Large-language-model pretraining for languages other than English is constrained
36
+ less by modeling technique than by the availability of **legally clean** text.
37
+ Many widely-used corpora are assembled from web crawls of uncertain provenance,
38
+ mixing public-domain works, openly-licensed material, and in-copyright content
39
+ without per-document accounting. The *Dynaword* project (Enevoldsen et al., 2025)
40
+ proposed an alternative: a continuously-developed corpus where every source is
41
+ *openly licensed* and that license is *traceable* to a documented legal basis,
42
+ with the whole pipeline reproducible and each source individually documented as a
43
+ datasheet (Gebru et al., 2021).
44
+
45
+ Polish is comparatively well-served for raw text — the SpeakLeash project has
46
+ aggregated 800+ Polish datasets — but most of that material carries "conditional"
47
+ licensing (web-crawl or non-commercial terms) that is unsuitable for an
48
+ openly-licensed release. **Polish DynaWord** addresses this gap. Its contribution
49
+ is not the collection of new text but the *curation*: a per-source license
50
+ review, a uniform minimal-filtering pipeline, transparent documentation of both
51
+ included and excluded sources, and a reproducible build.
52
+
53
+ ## 2. Related work
54
+
55
+ **Dynaword and the Danish lineage.** Polish DynaWord directly adapts the Danish
56
+ Dynaword (Enevoldsen et al., 2025), itself a successor to the Danish Gigaword
57
+ project. A key lesson carried over is the treatment of *derivative* content: the
58
+ Danish effort excluded OpenSubtitles because subtitle text is a derivative work of
59
+ copyrighted film/TV dialogue. We apply the same reasoning (§6).
60
+
61
+ **SpeakLeash / Bielik.** SpeakLeash is the principal open aggregator of Polish
62
+ text and the redistribution channel for most of our included sources. We use
63
+ SpeakLeash as an *intermediate aggregator* and preserve upstream
64
+ license/attribution; SpeakLeash is credited accordingly. Crucially, SpeakLeash's
65
+ redistribution does not itself confer a license — the right to redistribute flows
66
+ from each source's upstream license, which we document per source.
67
+
68
+ **Datasheets for Datasets.** Following Gebru et al. (2021), each source ships a
69
+ datasheet recording provenance, licensing basis, domain, time range, and the
70
+ filters applied.
71
+
72
+ ## 3. Design principles
73
+
74
+ 1. **Open & traceable licensing.** Every source must be openly licensed *and*
75
+ carry a documented legal basis (statutory exemption or explicit upstream
76
+ license), not an unexplained "public domain" assertion.
77
+ 2. **Reproducibility.** A single command rebuilds the corpus from source archives
78
+ (`src/build_dynaword.py`).
79
+ 3. **Documented.** One datasheet per source; aggregate statistics in the dataset
80
+ card.
81
+ 4. **Extensibility.** Versioned; new sources and removals are tracked in a
82
+ changelog, and sources can be added via native fetchers (§8).
83
+
84
+ ## 4. Sources and licensing
85
+
86
+ Version 0.2.0 includes eleven sources. For each we record the upstream origin and
87
+ the *traceable basis* for its license.
88
+
89
+ | Source | Domain | License | Traceable basis |
90
+ |---|---|---|---|
91
+ | Polish Wikipedia | encyclopedic | CC-BY-SA-3.0 | Wikimedia dumps released under CC-BY-SA 3.0; attribution + share-alike preserved |
92
+ | Polish Wikisource | source texts | CC-BY-SA-3.0 | Wikimedia dumps; underlying works public-domain, community-transcribed |
93
+ | EUR-Lex (PL) | EU legislation | CC-BY-4.0 | Commission Decision 2011/833/EU; normative acts outside copyright (PL art. 4 *pr. aut.*) |
94
+ | Polish Parliamentary Corpus (Sejm/Senat) | political/spoken | public-domain / CC-BY-4.0 | Official documents outside copyright (PL art. 4 *pr. aut.*); redistributed by IPI PAN |
95
+ | Wolne Lektury | literature | CC-BY-SA-4.0 / Wolna Sztuka 1.3 | Published under CC-BY-SA 4.0 or Free Art License; PD classics + cleared works |
96
+ | Polish Wikinews | news | CC-BY-2.5 | Wikinews released under CC-BY 2.5; attribution preserved |
97
+ | Polish Wikivoyage | travel | CC-BY-SA-3.0 | Wikivoyage released under CC-BY-SA 3.0 |
98
+ | Polish Wikibooks | instructional | CC-BY-SA-3.0 | Wikibooks released under CC-BY-SA 3.0 |
99
+ | Polish Wikiquote | quotations | CC-BY-SA-3.0 | Wikiquote released under CC-BY-SA 3.0 |
100
+ | ELTeC-pol | literature (1840–1920) | CC-BY-4.0 | COST Action CA16204 release under CC-BY 4.0 |
101
+ | Dziennik Ustaw + Monitor Polski | national legislation | public-domain (CC0) | Normative acts not subject to copyright (PL art. 4 *pr. aut.*); fetched directly from the Sejm ELI API |
102
+
103
+ Because two included sources (Wikipedia/Wikisource, Wolne Lektury) are
104
+ share-alike, the **aggregate corpus is released under CC-BY-SA-4.0**, with
105
+ attribution due to each upstream source and to SpeakLeash as the aggregator.
106
+
107
+ ## 5. Construction methodology
108
+
109
+ **Provenance.** Source archives are obtained from SpeakLeash's public
110
+ redistribution bucket (`speakleash-ds-pub`) in `jsonl.zst` form. The build streams
111
+ each archive, applies gates, and writes one Parquet file per source.
112
+
113
+ **Filters (intentionally minimal).** Consistent with Dynaword guidelines, heavy
114
+ quality filtering and mixture-weighting are deferred to downstream training; the
115
+ build applies only:
116
+
117
+ - drop documents shorter than 200 characters;
118
+ - drop non-Polish text (diacritic-to-letter ratio threshold);
119
+ - exact cross-source deduplication (SHA-1 over normalized text), with earlier
120
+ sources winning duplicates;
121
+ - for OCR-bearing sources, an alpha-character-ratio gate against OCR garble.
122
+
123
+ **Schema.** Every document is stored as
124
+ `(id, text, source, added, created, token_count)`. Token counts are a fast
125
+ tiktoken `cl100k` proxy (within ≈1% of a Llama-3 tokenizer); a canonical Llama-3
126
+ recount is planned for a tagged release.
127
+
128
+ ## 6. Statistics
129
+
130
+ | Source | Documents | Characters | Tokens (proxy) |
131
+ |---|---:|---:|---:|
132
+ | Polish Wikipedia | 1,171,897 | 1.85 B | 707.2 M |
133
+ | Polish Wikisource | 632,005 | 1.97 B | 801.9 M |
134
+ | EUR-Lex (PL) | 243,060 | 5.98 B | 2,378.1 M |
135
+ | Polish Parliamentary Corpus | 324,622 | 4.49 B | 1,646.8 M |
136
+ | Wolne Lektury | 6,141 | 0.26 B | 103.0 M |
137
+ | Polish Wikinews | 24,386 | 0.03 B | 12.1 M |
138
+ | Polish Wikivoyage | 13,645 | 0.05 B | 17.1 M |
139
+ | Polish Wikibooks | 9,112 | 0.04 B | 15.6 M |
140
+ | Polish Wikiquote | 30,363 | 0.08 B | 31.9 M |
141
+ | ELTeC-pol | 100 | 0.05 B | 21.5 M |
142
+ | Dziennik Ustaw + Monitor Polski | 35,442 | 1.23 B | 486.1 M |
143
+ | **Total (v0.2.0)** | **2,490,773** | **16.0 B** | **6.22 B** |
144
+
145
+ For comparison, the Danish Dynaword reports ≈4.8 B tokens; Polish DynaWord v0.2.0
146
+ is larger while remaining within a strictly openly-licensed source set. The full
147
+ build completes in ≈4 minutes on 14 CPU cores. The five sources added in v0.2.0
148
+ contribute modest volume (≈98 M tokens) but broaden register coverage — news,
149
+ travel, instructional, quotation and modern literary prose — addressing the
150
+ encyclopedic/legal skew of the earlier versions.
151
+
152
+ ## 7. Excluded sources (curation as contribution)
153
+
154
+ Transparency about what is *left out* is part of the editorial contribution. Each
155
+ exclusion records a stated legal reason:
156
+
157
+ - **OpenSubtitles (PL)** — subtitle text is a derivative work of copyrighted
158
+ film/TV dialogue and largely unlicensed; excluded on the Danish Gigaword
159
+ precedent.
160
+ - **Europeana (PL)** — an aggregation of items with *mixed per-record rights*
161
+ (PD / CC-BY-NC / rights-reserved). The SpeakLeash redistribution does not carry
162
+ the `edm:rights` field, so per-record filtering is impossible without external
163
+ enrichment; excluded pending that work (≈203k docs / ≈5.2B tokens forgone).
164
+ - **1000 Novels (CLARIN-PL)** — labelled CC-BY-4.0, but the collection likely
165
+ includes in-copyright contemporary works; excluded pending per-title verification.
166
+ - **Project Gutenberg (PL)** — only 31 Polish books (4.3 MB), near-redundant with
167
+ Wikisource/Wolne Lektury, and claiming public domain *in the US only*; dropped
168
+ to avoid a per-work PD-in-EU check for negligible token gain.
169
+
170
+ ## 8. Native sources fetched directly from upstream
171
+
172
+ Beyond the SpeakLeash-redistributed corpora, six sources are fetched *directly*
173
+ from their publishers. Direct sourcing strengthens provenance (each document
174
+ records its upstream URL/identifier), keeps the data fresh, and distinguishes the
175
+ corpus from a mirror of any single aggregator. Each is implemented as a small,
176
+ reproducible fetcher under `src/`.
177
+
178
+ **Polish primary legislation** (`src/fetch_eli.py`). We fetch **Dziennik Ustaw**
179
+ and **Monitor Polski** from the Sejm ELI API (`api.sejm.gov.pl/eli/acts`),
180
+ retrieving each act's HTML and converting it to plain text. For v0.2.0 we include
181
+ acts marked in force over 1990–2025: **35,442 documents (≈486 M tokens)**.
182
+ Normative acts and their official drafts are **not subject to copyright** under
183
+ Polish law (art. 4 of the Act on Copyright and Related Rights). This adds Polish
184
+ *national* law, complementing the EU law present via EUR-Lex.
185
+
186
+ **Wikimedia sibling projects** (`src/fetch_wikimedia.py`). We fetch the Polish
187
+ **Wikinews**, **Wikivoyage**, **Wikibooks** and **Wikiquote** from the official
188
+ Wikimedia dumps, keeping mainspace pages and stripping wikitext to plain text with
189
+ `mwparserfromhell`. These contribute the **news, travel, instructional and
190
+ quotation** registers (≈77 k documents, ≈77 M tokens combined) under CC-BY /
191
+ CC-BY-SA, compatible with the aggregate license.
192
+
193
+ **ELTeC-pol** (`src/fetch_eltec.py`). We fetch the Polish part of the European
194
+ Literary Text Collection (COST Action CA16204) from GitHub — **100 novels**
195
+ (1840–1920, ≈21.5 M tokens) released CC-BY-4.0 — adding modern narrative literary
196
+ prose distinct from the older texts in Wikisource and Wolne Lektury.
197
+
198
+ ## 9. Ethics, licensing and limitations
199
+
200
+ **Personal data.** The corpus contains only text its sources already published
201
+ openly or as official record; it therefore includes names and statements of
202
+ public figures acting in a public capacity (parliamentary speakers, authorities
203
+ named in legislation, people described in encyclopedic articles). No private,
204
+ non-public personal data is collected. A notice-and-takedown procedure allows
205
+ data subjects and rightsholders to request removal from subsequent versions.
206
+
207
+ **License compliance.** The release is CC-BY-SA-4.0; downstream users must satisfy
208
+ attribution and share-alike obligations for derivatives, and attribute the
209
+ upstream sources and SpeakLeash. Per-source licenses are reproduced in good faith
210
+ as documented by upstream and by SpeakLeash; we make no independent legal warranty
211
+ about any individual document's copyright status.
212
+
213
+ **Limitations.** (i) Token counts are a tiktoken proxy pending a canonical Llama-3
214
+ recount. (ii) Evaluation-set decontamination (n-gram overlap against Polish
215
+ benchmarks) is *not yet applied* and is required before the corpus is used to
216
+ train models reported on those benchmarks. (iii) Deduplication is exact-match
217
+ only; near-duplicate removal is left to downstream use. (iv) Gutenberg-style
218
+ PD-in-EU edge cases are handled by exclusion rather than per-work adjudication.
219
+
220
+ ## 10. Availability
221
+
222
+ The dataset, per-source datasheets, build/fetch code, and documentation are
223
+ released at `huggingface.co/datasets/SlayerLab/polish-dynaword` (CC-BY-SA-4.0).
224
+ The corpus is versioned; this paper describes v0.2.0.
225
+
226
+ ## References
227
+
228
+ - Enevoldsen, K. et al. (2025). *Dynaword: A Continuously Developed, Openly
229
+ Licensed Corpus.* arXiv:2508.02271.
230
+ - Gebru, T. et al. (2021). *Datasheets for Datasets.* Communications of the ACM.
231
+ - SpeakLeash / Bielik project. *Open Polish text datasets.* speakleash.org.
232
+ - Strømberg-Derczynski, L. et al. (2021). *The Danish Gigaword Corpus.* NoDaLiDa.
233
+ - Sejm RP. *ELI API — Internetowy System Aktów Prawnych.* api.sejm.gov.pl/eli.
234
+ - Ustawa z dnia 4 lutego 1994 r. o prawie autorskim i prawach pokrewnych, art. 4.
235
+
236
+ ---
237
+
238
+ *Draft — generated alongside the v0.2.0 corpus release. Numbers reflect the
239
+ eleven-source build (five SpeakLeash-redistributed + six fetched directly from
240
+ upstream). Evaluation-set decontamination (§9) is still pending.*
README.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-sa-4.0
3
+ language:
4
+ - pl
5
+ pretty_name: Polish DynaWord
6
+ task_categories:
7
+ - text-generation
8
+ size_categories:
9
+ - 1M<n<10M
10
+ tags:
11
+ - polish
12
+ - pretraining
13
+ - dynaword
14
+ ---
15
+
16
+ # Polish DynaWord
17
+
18
+ A continuously developed, **openly-licensed**, human-text Polish corpus — a Polish
19
+ edition in the [Dynaword](https://huggingface.co/datasets/danish-foundation-models/danish-dynaword)
20
+ family (Enevoldsen et al., [arXiv:2508.02271](https://arxiv.org/abs/2508.02271)).
21
+
22
+ > **v0.2.0** · 2,490,773 documents · **6.22B tokens** (tiktoken proxy;
23
+ > canonical Llama-3 count at release) · 11 sources
24
+
25
+ ## What this dataset contributes
26
+ The raw texts come from existing open corpora (redistributed via SpeakLeash and,
27
+ where applicable, fetched from upstream). **The value added here is the curation,
28
+ not the bytes**, following the Dynaword methodology:
29
+
30
+ 1. **License review per source** — each source vetted for an *openly-licensed,
31
+ traceable* legal basis (documented in its datasheet); sources that fail the
32
+ review are **excluded with a stated reason** (see table below), not silently
33
+ kept. This is the core editorial work.
34
+ 2. **Filtering & normalization** — minimal, reproducible gates (short-doc,
35
+ non-Polish, exact cross-source dedup, OCR garble) applied uniformly to one
36
+ clean schema: `id, text, source, added, created, token_count`.
37
+ 3. **Documentation** — a datasheet per source (Gebru et al. 2021) + this card,
38
+ so provenance and licensing are auditable rather than assumed.
39
+ 4. **Reproducibility & versioning** — `src/` rebuilds the corpus from sources;
40
+ new sources and removals are tracked in the CHANGELOG.
41
+
42
+ Credit for the underlying texts belongs to the upstream sources and to SpeakLeash
43
+ as the redistributing aggregator; this release does not claim ownership of them
44
+ (see Disclaimer).
45
+
46
+ ## Guiding principles
47
+ 1. **Open & traceable licensing** — every source is *openly licensed* with a documented
48
+ legal basis (see each datasheet's "traceable basis"), not a vague "public domain".
49
+ 2. **Reproducibility** — `src/build_dynaword.py` rebuilds the corpus from sources.
50
+ 3. **Documented** — a datasheet per source under `data/<source>/`.
51
+ 4. **Extensibility** — versioned; new sources via PR.
52
+
53
+ ## Sources
54
+ | source | description | license | documents | tokens |
55
+ |---|---|---|---:|---:|
56
+ | [eurlex](data/eurlex/eurlex.md) | EUR-Lex (EU legal acts, Polish) | `CC-BY-4.0` | 243,060 | 2,378.1M |
57
+ | [parliamentary](data/parliamentary/parliamentary.md) | Polish Parliamentary Corpus (Sejm/Senat) | `public-domain (official documents)` | 324,622 | 1,646.8M |
58
+ | [wikisource](data/wikisource/wikisource.md) | Polish Wikisource | `CC-BY-SA-3.0` | 632,005 | 801.9M |
59
+ | [wikipedia](data/wikipedia/wikipedia.md) | Polish Wikipedia | `CC-BY-SA-3.0` | 1,171,897 | 707.2M |
60
+ | [dziennik_ustaw](data/dziennik_ustaw/dziennik_ustaw.md) | Dziennik Ustaw + Monitor Polski (Polish primary legislation) | `public-domain (official documents)` | 35,442 | 486.1M |
61
+ | [wolne_lektury](data/wolne_lektury/wolne_lektury.md) | Wolne Lektury (school readings) | `CC-BY-SA-4.0 / Wolna Sztuka 1.3` | 6,141 | 103.0M |
62
+ | [wikiquote](data/wikiquote/wikiquote.md) | Polish Wikiquote (quotations) | `CC-BY-SA-3.0` | 30,363 | 31.9M |
63
+ | [eltec_pol](data/eltec_pol/eltec_pol.md) | ELTeC-pol (European Literary Text Collection, Polish) | `CC-BY-4.0` | 100 | 21.5M |
64
+ | [wikivoyage](data/wikivoyage/wikivoyage.md) | Polish Wikivoyage (travel guides) | `CC-BY-SA-3.0` | 13,645 | 17.1M |
65
+ | [wikibooks](data/wikibooks/wikibooks.md) | Polish Wikibooks (open textbooks) | `CC-BY-SA-3.0` | 9,112 | 15.6M |
66
+ | [wikinews](data/wikinews/wikinews.md) | Polish Wikinews | `CC-BY-2.5` | 24,386 | 12.1M |
67
+ | **total** | | | **2,490,773** | **6,221.4M** |
68
+
69
+ ## Method
70
+ Only **human-authored** text — no synthetic, machine-translated, or auto-transcribed
71
+ data. Gates are intentionally minimal (drop short docs, non-Polish, exact duplicates,
72
+ OCR garble); heavy quality filtering and mix-weighting are left to downstream training.
73
+ Evaluation-set decontamination is applied/marked separately. Schema:
74
+ `id, text, source, added, created, token_count`.
75
+
76
+ ## Excluded sources (transparency)
77
+ Sources we reviewed and **deliberately left out** — part of the curation:
78
+
79
+ | source | reason |
80
+ |---|---|
81
+ | `open_subtitles_corpus` | Derivative of copyrighted film/TV dialogue; OpenSubtitles uploads largely unlicensed. Same copyright lesson as Danish Gigaword's OpenSubtitles (paper 2508.02271). Not openly licensed. |
82
+ | `europeana_eu_pl_corpus` | Aggregated items with mixed per-record rights (PD / CC-BY-NC / rights-reserved). Needs per-record edm:rights filter before any inclusion. |
83
+ | `1000_novels_corpus_CLARIN-PL` | CC-BY-4.0 label, but 'novels' likely include in-copyright contemporary works; verify titles/years on CLARIN handle 11321/312 before inclusion. |
84
+ | `project_gutenberg_pl_corpus` | Only 31 PL books (4.3MB) — PG is ~99% English; Polish PD literature already covered by wolne_lektury + wikisource (so near-redundant after dedup). Dropped to avoid the PD-in-EU per-work check (PG claims PD-in-US only) for negligible token gain. |
85
+
86
+ ## Personal & sensitive data
87
+ This corpus contains **only** text that its upstream sources already published
88
+ under open licenses or as official public-domain record. It therefore includes
89
+ names and statements of **public figures acting in a public capacity** — e.g.
90
+ parliamentary speakers (PPC), authorities named in legal acts (EUR-Lex), and
91
+ people described in encyclopedic articles (Wikipedia/Wikisource). No private,
92
+ non-public personal data was collected or added. If you are a data subject and
93
+ want content concerning you removed, contact **k.wikiel@gmail.com** — it will be dropped
94
+ from the next version (see retroactive-removal policy below).
95
+
96
+ ## Disclaimer & legal
97
+ - **Provenance in good faith.** Per-source licenses are reproduced *as documented
98
+ by the upstream sources and by SpeakLeash* (the intermediate aggregator), to the
99
+ best of our knowledge. We make no independent legal warranty about the copyright
100
+ status of any individual document.
101
+ - **No ownership claim.** This release is a *curated, license-reviewed, documented
102
+ aggregation*. We claim no ownership of the underlying texts; rights remain with
103
+ the original authors/rightsholders under their respective licenses.
104
+ - **Provided "as is"**, without warranty of any kind, express or implied. This is
105
+ not legal advice.
106
+ - **Your compliance is yours.** Downstream users must satisfy each upstream
107
+ license themselves — in particular **CC-BY-SA-4.0 attribution and share-alike**
108
+ for derivatives of this dataset, and attribution to the upstream sources and to
109
+ SpeakLeash.
110
+ - **Notice-and-takedown.** Any source or rightsholder raising a substantiated
111
+ objection can have material removed: contact **k.wikiel@gmail.com**; it is dropped from
112
+ the next version and recorded in the CHANGELOG. Removal is retroactive
113
+ going-forward (prior immutable snapshots/commits may persist).
114
+
115
+ ## License & attribution
116
+ Released under **CC-BY-SA-4.0** (copyleft inherited from CC-BY-SA sources such as
117
+ Wikipedia/Wikisource/Wolne Lektury). Attribution due to each upstream (see datasheets)
118
+ and to **SpeakLeash** as the intermediate aggregator. Retroactive-removal policy: a
119
+ source that raises an objection is dropped from subsequent versions, recorded in the
120
+ CHANGELOG.
121
+
122
+ ## Reproduce
123
+ ```bash
124
+ python3 src/build_dynaword.py --all --speakleash-dir <speakleash_zst_dir> --out .
125
+ python3 src/make_docs.py
126
+ ```
data/dziennik_ustaw/dziennik_ustaw.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dziennik_ustaw
2
+
3
+ Dziennik Ustaw + Monitor Polski (Polish primary legislation)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://api.sejm.gov.pl/eli/acts
7
+ - **Domain:** legal
8
+ - **Language:** Polish (pl)
9
+ - **License:** `public-domain (official documents)`
10
+ - **Created (range):** 1918-01-01, 2025-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Normative acts and their official drafts are not subject to copyright (PL art. 4 ustawy o prawie autorskim). Published by the state; reuse unrestricted.
15
+
16
+ ## Provenance
17
+ Fetched directly from the Sejm ELI API (text.html per act) by src/fetch_eli.py — a native source, not redistributed via SpeakLeash. Full provenance: each act's `meta.url` is its ELI address, resolvable on api.sejm.gov.pl.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 35,442 | 1,226,137,838 | 486,126,575 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **0**
28
+ - exact cross-source dedup (sha1): **0**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 35,442 → kept 35,442
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/dziennik_ustaw/dziennik_ustaw.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cf60c3d3298390bd46e4feadd7b581d79141a1b99ff0ea06645012bbc096b65
3
+ size 313228363
data/dziennik_ustaw/dziennik_ustaw.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 35442,
3
+ "kept": 35442,
4
+ "drop_short": 0,
5
+ "drop_lang": 0,
6
+ "drop_dup": 0,
7
+ "drop_ocr": 0,
8
+ "chars": 1226137838,
9
+ "tokens": 486126575,
10
+ "secs": 17.8,
11
+ "license": "public-domain (official documents)"
12
+ }
data/eltec_pol/eltec_pol.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # eltec_pol
2
+
3
+ ELTeC-pol (European Literary Text Collection, Polish)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://github.com/COST-ELTeC/ELTeC-pol
7
+ - **Domain:** literature
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-4.0`
10
+ - **Created (range):** 1840-01-01, 1920-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ ELTeC corpora are released under CC-BY 4.0 by the COST Action 'Distant Reading for European Literary History' (CA16204).
15
+
16
+ ## Provenance
17
+ Fetched directly from the COST-ELTeC/ELTeC-pol GitHub repository (level1 TEI) by src/fetch_eltec.py; reading text extracted from TEI <body> paragraphs.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 100 | 54,369,249 | 21,486,720 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **0**
28
+ - exact cross-source dedup (sha1): **0**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 100 → kept 100
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/eurlex/eurlex.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # eurlex
2
+
3
+ EUR-Lex (EU legal acts, Polish)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://eur-lex.europa.eu
7
+ - **Domain:** legal
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-4.0`
10
+ - **Created (range):** 1952-01-01, 2024-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ EU documents reusable under Commission Decision 2011/833/EU; normative acts fall outside copyright (PL art. 4 pr. aut.). Reuse authorised with source acknowledgement.
15
+
16
+ ## Provenance
17
+ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `eurlex_corpus`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 243,060 | 5,976,949,249 | 2,378,055,718 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **1,390**
28
+ - exact cross-source dedup (sha1): **1,825**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 246,275 → kept 243,060
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/eurlex/eurlex.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9da0ff96941150af85960497e1aab0188f7956d485e41f7170fa402346961fb1
3
+ size 1692243551
data/eurlex/eurlex.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 246275,
3
+ "kept": 243060,
4
+ "drop_short": 0,
5
+ "drop_lang": 1390,
6
+ "drop_dup": 1825,
7
+ "drop_ocr": 0,
8
+ "chars": 5976949249,
9
+ "tokens": 2378055718,
10
+ "secs": 69.8,
11
+ "license": "CC-BY-4.0"
12
+ }
data/parliamentary/parliamentary.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parliamentary
2
+
3
+ Polish Parliamentary Corpus (Sejm/Senat)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** http://clip.ipipan.waw.pl/PPC
7
+ - **Domain:** political/spoken
8
+ - **Language:** Polish (pl)
9
+ - **License:** `public-domain (official documents)`
10
+ - **Created (range):** 1991-01-01, 2019-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Parliamentary proceedings are official documents outside copyright (PL art. 4 pr. aut.); PPC redistributed by IPI PAN under CC-BY-4.0.
15
+
16
+ ## Provenance
17
+ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `PPC_corpus`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 324,622 | 4,492,746,014 | 1,646,835,986 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **583**
27
+ - drop non-Polish (diacritic ratio): **0**
28
+ - exact cross-source dedup (sha1): **18,592**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 343,797 → kept 324,622
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/parliamentary/parliamentary.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c5cc1c90ba06f250dbb272ae472d1cb7da9fe101ca8fdd3ea3dcba14c4eebef
3
+ size 1732860869
data/parliamentary/parliamentary.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 343797,
3
+ "kept": 324622,
4
+ "drop_short": 583,
5
+ "drop_lang": 0,
6
+ "drop_dup": 18592,
7
+ "drop_ocr": 0,
8
+ "chars": 4492746014,
9
+ "tokens": 1646835986,
10
+ "secs": 48.8,
11
+ "license": "public-domain (official documents)"
12
+ }
data/wikibooks/wikibooks.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikibooks
2
+
3
+ Polish Wikibooks (open textbooks)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://pl.wikibooks.org/
7
+ - **Domain:** instructional
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2004-01-01, 2025-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikibooks content is released under CC-BY-SA 3.0; attribution + share-alike preserved.
15
+
16
+ ## Provenance
17
+ Fetched directly from the official Wikimedia dump (plwikibooks-latest-pages-articles) by src/fetch_wikimedia.py; mainspace only, wikitext stripped via mwparserfromhell.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 9,112 | 38,892,589 | 15,571,295 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **539**
28
+ - exact cross-source dedup (sha1): **15**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 9,666 → kept 9,112
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wikinews/wikinews.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikinews
2
+
3
+ Polish Wikinews
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://pl.wikinews.org/
7
+ - **Domain:** news
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-2.5`
10
+ - **Created (range):** 2005-01-01, 2025-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikinews content is released under CC-BY 2.5; attribution to contributors preserved.
15
+
16
+ ## Provenance
17
+ Fetched directly from the official Wikimedia dump (plwikinews-latest-pages-articles) by src/fetch_wikimedia.py; mainspace only, wikitext stripped via mwparserfromhell.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 24,386 | 32,524,646 | 12,141,355 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **6**
28
+ - exact cross-source dedup (sha1): **0**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 24,392 → kept 24,386
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wikipedia/wikipedia.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikipedia
2
+
3
+ Polish Wikipedia
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://dumps.wikimedia.org/plwiki/latest/
7
+ - **Domain:** encyclopedic
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2001-01-15, 2026-06-14
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikimedia dumps explicitly released under CC-BY-SA 3.0; attribution to contributors + share-alike preserved.
15
+
16
+ ## Provenance
17
+ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `plwiki`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 1,171,897 | 1,844,707,761 | 707,194,207 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **296,738**
27
+ - drop non-Polish (diacritic ratio): **1,172**
28
+ - exact cross-source dedup (sha1): **113**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 1,469,920 → kept 1,171,897
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wikipedia/wikipedia.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f66fac8b3c4da41ff8ccbe7c568e38ca710ae42f85d409a9702503eb99dd8185
3
+ size 866297438
data/wikipedia/wikipedia.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 1469920,
3
+ "kept": 1171897,
4
+ "drop_short": 296738,
5
+ "drop_lang": 1172,
6
+ "drop_dup": 113,
7
+ "drop_ocr": 0,
8
+ "chars": 1844707761,
9
+ "tokens": 707194207,
10
+ "secs": 20.6,
11
+ "license": "CC-BY-SA-3.0"
12
+ }
data/wikiquote/wikiquote.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikiquote
2
+
3
+ Polish Wikiquote (quotations)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://pl.wikiquote.org/
7
+ - **Domain:** quotations
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2005-01-01, 2025-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikiquote content is released under CC-BY-SA 3.0; attribution + share-alike preserved.
15
+
16
+ ## Provenance
17
+ Fetched directly from the official Wikimedia dump (plwikiquote-latest-pages-articles) by src/fetch_wikimedia.py; mainspace only, wikitext stripped via mwparserfromhell.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 30,363 | 82,338,997 | 31,896,591 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **11**
28
+ - exact cross-source dedup (sha1): **2**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 30,376 → kept 30,363
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wikisource/wikisource.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikisource
2
+
3
+ Polish Wikisource
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://dumps.wikimedia.org/plwikisource/latest/
7
+ - **Domain:** books/source-texts
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2005-01-01, 2026-06-14
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikimedia dumps under CC-BY-SA 3.0; underlying texts are public-domain works transcribed by the community.
15
+
16
+ ## Provenance
17
+ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `plwikisource`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 632,005 | 1,974,249,746 | 801,947,427 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **15**
28
+ - exact cross-source dedup (sha1): **0**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 632,020 → kept 632,005
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wikisource/wikisource.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e066d5e43c84f0d70376e4162ff97f544b4e6122906458727277aa562efbff0
3
+ size 984212691
data/wikisource/wikisource.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 632020,
3
+ "kept": 632005,
4
+ "drop_short": 0,
5
+ "drop_lang": 15,
6
+ "drop_dup": 0,
7
+ "drop_ocr": 0,
8
+ "chars": 1974249746,
9
+ "tokens": 801947427,
10
+ "secs": 62.0,
11
+ "license": "CC-BY-SA-3.0"
12
+ }
data/wikivoyage/wikivoyage.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wikivoyage
2
+
3
+ Polish Wikivoyage (travel guides)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://pl.wikivoyage.org/
7
+ - **Domain:** travel
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2012-01-01, 2025-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wikivoyage content is released under CC-BY-SA 3.0; attribution + share-alike preserved.
15
+
16
+ ## Provenance
17
+ Fetched directly from the official Wikimedia dump (plwikivoyage-latest-pages-articles) by src/fetch_wikimedia.py; mainspace only, wikitext stripped via mwparserfromhell.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 13,645 | 45,184,300 | 17,128,200 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **0**
27
+ - drop non-Polish (diacritic ratio): **9**
28
+ - exact cross-source dedup (sha1): **1**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 13,655 → kept 13,645
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wolne_lektury/wolne_lektury.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wolne_lektury
2
+
3
+ Wolne Lektury (school readings)
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://wolnelektury.pl/api/books/
7
+ - **Domain:** literature
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-4.0 / Wolna Sztuka 1.3`
10
+ - **Created (range):** 1500-01-01, 2024-12-31
11
+ - **Added:** 2026-06-15
12
+
13
+ ## Licensing — traceable basis
14
+ Wolne Lektury publishes under CC-BY-SA 4.0 or Free Art License; texts are public-domain classics + cleared works.
15
+
16
+ ## Provenance
17
+ Pulled from SpeakLeash's public redistribution (`speakleash-ds-pub`, key `wolne_lektury_corpus`) of the upstream source above. SpeakLeash credited as intermediate aggregator; upstream license/attribution preserved.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 6,141 | 261,892,000 | 103,009,797 |
23
+
24
+ ## Filters applied (build_dynaword.py)
25
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
26
+ - drop documents < 200 chars: **471**
27
+ - drop non-Polish (diacritic ratio): **2**
28
+ - exact cross-source dedup (sha1): **5**
29
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
30
+ - read 6,619 → kept 6,141
31
+
32
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
33
+ Llama-3 count is computed at release.
data/wolne_lektury/wolne_lektury.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:157556cc790b7909afbc544803af9fa18f8b4ed8b334f03cc65b36867c51e79d
3
+ size 128537253
data/wolne_lektury/wolne_lektury.stats.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 6619,
3
+ "kept": 6141,
4
+ "drop_short": 471,
5
+ "drop_lang": 2,
6
+ "drop_dup": 5,
7
+ "drop_ocr": 0,
8
+ "chars": 261892000,
9
+ "tokens": 103009797,
10
+ "secs": 10.8,
11
+ "license": "CC-BY-SA-4.0 / Wolna Sztuka 1.3"
12
+ }
src/build_dynaword.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build Polish DynaWord parquet shards from SpeakLeash .jsonl.zst sources.
3
+
4
+ Parallel pipeline (uses all cores). Per source (paper 2508.02271, minimal gates):
5
+ stream jsonl.zst -> [workers: parse + Polish-lang check + drop-short +
6
+ OCR alpha-ratio + tiktoken token_count + sha1] -> [main: cross-source exact
7
+ dedup + id + parquet write].
8
+
9
+ Sources processed in priority order so earlier sources win duplicates
10
+ (wikipedia > wikisource > ...). Heavy quality filtering + mix-weighting are
11
+ downstream (CPT), not here. token_count is a fast tiktoken proxy (~1% off
12
+ Llama-3); canonical Llama-3 recount happens at release.
13
+
14
+ Usage:
15
+ python3 src/build_dynaword.py --all --speakleash-dir ~/speakleash --out ~/dynaword
16
+ python3 src/build_dynaword.py --sources gutenberg --jobs 16
17
+ """
18
+ from __future__ import annotations
19
+ import argparse, hashlib, json, os, re, subprocess, sys, time
20
+ from itertools import islice
21
+ import multiprocessing as mp
22
+ from pathlib import Path
23
+ import pyarrow as pa
24
+ import pyarrow.parquet as pq
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
27
+ from sources import SOURCES, ADDED
28
+
29
+ POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]")
30
+ ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
31
+ MIN_CHARS = 200
32
+ MIN_POLISH_RATIO = 0.005
33
+ MIN_ALPHA_RATIO = 0.70
34
+
35
+ SCHEMA = pa.schema([
36
+ ("id", pa.string()), ("text", pa.string()), ("source", pa.string()),
37
+ ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()),
38
+ ])
39
+
40
+ _ENC = None # per-worker tiktoken encoder
41
+
42
+
43
+ def _init_worker():
44
+ global _ENC
45
+ import tiktoken
46
+ _ENC = tiktoken.get_encoding("cl100k_base")
47
+
48
+
49
+ def _polish_ratio(text):
50
+ letters = ALPHA_RE.findall(text)
51
+ return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
52
+
53
+
54
+ def _process_chunk(args):
55
+ """Worker: gate + tokenize a batch of raw lines. Returns (records, stats)."""
56
+ is_ocr, created, lines = args
57
+ kept, texts = [], []
58
+ st = [0, 0, 0, 0] # read, short, lang, ocr
59
+ for line in lines:
60
+ st[0] += 1
61
+ try:
62
+ text = (json.loads(line).get("text") or "").strip()
63
+ except Exception:
64
+ continue
65
+ if len(text) < MIN_CHARS:
66
+ st[1] += 1; continue
67
+ if _polish_ratio(text) < MIN_POLISH_RATIO:
68
+ st[2] += 1; continue
69
+ if is_ocr:
70
+ ar = len(ALPHA_RE.findall(text)) / len(text) if text else 0.0
71
+ if ar < MIN_ALPHA_RATIO:
72
+ st[3] += 1; continue
73
+ texts.append(text)
74
+ toks = [len(t) for t in _ENC.encode_ordinary_batch(texts, num_threads=1)] if texts else []
75
+ for t, tk in zip(texts, toks):
76
+ kept.append((t, created, tk, hashlib.sha1(t.encode("utf-8")).digest()))
77
+ return kept, st
78
+
79
+
80
+ def _chunks(iterable, n):
81
+ it = iter(iterable)
82
+ while batch := list(islice(it, n)):
83
+ yield batch
84
+
85
+
86
+ def build_source(name, cfg, sl_dir, out_root, pool, seen, counter):
87
+ src_path = sl_dir / f"{cfg.get('file_key', cfg.get('speakleash_key'))}.jsonl.zst"
88
+ if not src_path.exists():
89
+ print(f" ! missing {src_path}"); return None
90
+ out_dir = out_root / "data" / name
91
+ out_dir.mkdir(parents=True, exist_ok=True)
92
+ writer = pq.ParquetWriter(out_dir / f"{name}.parquet", SCHEMA, compression="zstd")
93
+ st = {"read": 0, "kept": 0, "drop_short": 0, "drop_lang": 0,
94
+ "drop_dup": 0, "drop_ocr": 0, "chars": 0, "tokens": 0}
95
+ t0 = time.time()
96
+ is_ocr, created = bool(cfg.get("is_ocr")), cfg.get("created", "")
97
+ bid, btext, bcre, btok = [], [], [], []
98
+
99
+ def flush():
100
+ if not btext:
101
+ return
102
+ n = len(btext)
103
+ writer.write(pa.record_batch([
104
+ pa.array(bid), pa.array(btext), pa.array([name] * n),
105
+ pa.array([ADDED] * n), pa.array(bcre), pa.array(btok, pa.int64()),
106
+ ], schema=SCHEMA))
107
+ bid.clear(); btext.clear(); bcre.clear(); btok.clear()
108
+
109
+ proc = subprocess.Popen(["zstd", "-dc", str(src_path)],
110
+ stdout=subprocess.PIPE, bufsize=1 << 22)
111
+ line_iter = (ln for ln in proc.stdout if ln.strip())
112
+ arg_iter = ((is_ocr, created, ch) for ch in _chunks(line_iter, 2000))
113
+ for kept, cst in pool.imap_unordered(_process_chunk, arg_iter, chunksize=1):
114
+ st["read"] += cst[0]; st["drop_short"] += cst[1]
115
+ st["drop_lang"] += cst[2]; st["drop_ocr"] += cst[3]
116
+ for text, cre, tok, h in kept:
117
+ if h in seen:
118
+ st["drop_dup"] += 1; continue
119
+ seen.add(h)
120
+ bid.append(f"{name}_{counter[0]}"); counter[0] += 1
121
+ btext.append(text); bcre.append(cre); btok.append(tok)
122
+ st["chars"] += len(text); st["tokens"] += tok; st["kept"] += 1
123
+ if len(btext) >= 2000:
124
+ flush()
125
+ flush(); writer.close(); proc.stdout.close(); proc.wait()
126
+ st["secs"] = round(time.time() - t0, 1)
127
+ print(f" {name}: read {st['read']:,} kept {st['kept']:,} | -short {st['drop_short']:,} "
128
+ f"-lang {st['drop_lang']:,} -dup {st['drop_dup']:,} -ocr {st['drop_ocr']:,} | "
129
+ f"{st['chars']/1e6:.0f}M chars, {st['tokens']/1e6:.1f}M tok | {st['secs']}s", flush=True)
130
+ (out_dir / f"{name}.stats.json").write_text(json.dumps({**st, "license": cfg["license"]}, indent=2))
131
+ return st
132
+
133
+
134
+ def main():
135
+ ap = argparse.ArgumentParser()
136
+ ap.add_argument("--sources", nargs="*", default=None)
137
+ ap.add_argument("--all", action="store_true")
138
+ ap.add_argument("--speakleash-dir", default="~/speakleash")
139
+ ap.add_argument("--out", default=".")
140
+ ap.add_argument("--jobs", type=int, default=os.cpu_count())
141
+ args = ap.parse_args()
142
+
143
+ names = list(SOURCES) if args.all else (args.sources or [])
144
+ if not names:
145
+ print("specify --sources <names> or --all"); return
146
+ sl_dir = Path(args.speakleash_dir).expanduser().resolve()
147
+ out_root = Path(args.out).expanduser().resolve()
148
+ print(f"jobs={args.jobs} | speakleash={sl_dir} | out={out_root} | sources={names}", flush=True)
149
+
150
+ seen, counter, totals = set(), [0], []
151
+ t0 = time.time()
152
+ with mp.Pool(args.jobs, initializer=_init_worker) as pool:
153
+ for name in names:
154
+ if name not in SOURCES:
155
+ print(f" ? unknown {name}"); continue
156
+ print(f"[{name}]", flush=True)
157
+ st = build_source(name, SOURCES[name], sl_dir, out_root, pool, seen, counter)
158
+ if st:
159
+ totals.append((name, st))
160
+ tt = sum(s["tokens"] for _, s in totals)
161
+ td = sum(s["kept"] for _, s in totals)
162
+ print(f"\nTOTAL: {td:,} docs, {tt/1e9:.2f}B tok (tiktoken proxy), "
163
+ f"{len(seen):,} unique | wall {round(time.time()-t0,1)}s", flush=True)
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
src/compare_tokenizers.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare fertility of our Polish BPE vs Bielik / Llama-3 / GPT-2 on the same
3
+ held-out Polish sample."""
4
+ import pyarrow.parquet as pq
5
+ from tokenizers import Tokenizer
6
+ import tiktoken
7
+
8
+ DATA = "/home/ubuntu/dynaword/data"
9
+ sample = []
10
+ for b in pq.ParquetFile(f"{DATA}/wikipedia/wikipedia.parquet").iter_batches(columns=["text"], batch_size=1000):
11
+ for x in b.column("text"):
12
+ sample.append(x.as_py())
13
+ if len(sample) >= 6000:
14
+ break
15
+ sample = sample[4000:6000]
16
+ words = sum(len(s.split()) for s in sample)
17
+ chars = sum(len(s) for s in sample)
18
+ print(f"held-out: {len(sample)} docs, {words:,} words, {chars:,} chars\n")
19
+
20
+ rows = []
21
+
22
+ def add(name, vocab, ntok):
23
+ rows.append((name, vocab, ntok / words, ntok / chars))
24
+
25
+ ours = Tokenizer.from_file("/home/ubuntu/dynaword/polish_bpe_32k.json")
26
+ add("polish-32k (ours)", ours.get_vocab_size(),
27
+ sum(len(e.ids) for e in ours.encode_batch(sample)))
28
+
29
+ g2 = tiktoken.get_encoding("gpt2")
30
+ add("gpt2-50k", 50257, sum(len(x) for x in g2.encode_ordinary_batch(sample)))
31
+
32
+ from transformers import AutoTokenizer
33
+ for label, repo in [("Bielik-11B-v3", "speakleash/Bielik-11B-v3.0-Instruct"),
34
+ ("Llama-3", "NousResearch/Meta-Llama-3-8B")]:
35
+ try:
36
+ t = AutoTokenizer.from_pretrained(repo)
37
+ enc = t(sample, add_special_tokens=False)["input_ids"]
38
+ add(label, t.vocab_size, sum(len(x) for x in enc))
39
+ except Exception as e:
40
+ print(f" {label}: FAILED {str(e)[:140]}")
41
+
42
+ rows.sort(key=lambda r: r[2])
43
+ base = next(r[2] for r in rows if r[0].startswith("polish-32k"))
44
+ print(f"{'tokenizer':<22}{'vocab':>8}{'tok/word':>11}{'tok/char':>11}{'vs ours':>10}")
45
+ for name, vocab, tpw, tpc in rows:
46
+ print(f"{name:<22}{vocab:>8}{tpw:>11.3f}{tpc:>11.3f}{tpw/base:>9.2f}x")
src/count_vocab.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-corpus unique word count. Streams parquet batches into a set.
2
+
3
+ ponytail: lowercased surface forms (Polish is heavily inflected, so this is
4
+ 'distinct word forms', not lemmas). Counts total words too.
5
+ """
6
+ import re
7
+ import pyarrow.parquet as pq
8
+
9
+ SOURCES = ["eurlex", "parliamentary", "wikisource", "wikipedia",
10
+ "dziennik_ustaw", "wolne_lektury"]
11
+ WORD = re.compile(r"[^\W\d_]+", re.UNICODE) # unicode letters, no digits/punct
12
+
13
+ total_vocab = set()
14
+ total_words = 0
15
+ print(f"{'source':<16} {'words':>14} {'uniq forms':>13}")
16
+ for s in SOURCES:
17
+ pf = pq.ParquetFile(f"data/{s}/{s}.parquet")
18
+ src_vocab = set()
19
+ src_words = 0
20
+ for batch in pf.iter_batches(columns=["text"], batch_size=2000):
21
+ for t in batch.column("text").to_pylist():
22
+ if not t:
23
+ continue
24
+ w = WORD.findall(t.lower())
25
+ src_words += len(w)
26
+ src_vocab.update(w)
27
+ total_words += src_words
28
+ total_vocab |= src_vocab
29
+ print(f"{s:<16} {src_words:>14,} {len(src_vocab):>13,}", flush=True)
30
+
31
+ print(f"\n{'TOTAL (deduped)':<16} {total_words:>14,} {len(total_vocab):>13,}")
32
+ print(f"type/token ratio: {len(total_vocab)/total_words:.5f}")
src/eval_bpb.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert modded-nanogpt's validation loss into paper-ready, tokenizer-agnostic
3
+ metrics: perplexity and bits-per-byte (bpb).
4
+
5
+ Perplexity depends on the tokenizer, so it is NOT comparable across models with
6
+ different vocabularies. Bits-per-byte normalises by raw UTF-8 bytes and IS
7
+ comparable (this is what to report against Bielik / Llama-based models).
8
+
9
+ bpb = val_loss[nats/token] / ln(2) * (tokens / bytes)
10
+
11
+ Usage:
12
+ python3 src/eval_bpb.py --val-loss 3.21 # val loss from the training log
13
+ """
14
+ import argparse, struct
15
+ import numpy as np
16
+ from tokenizers import Tokenizer
17
+
18
+ VAL = "/home/ubuntu/dynaword/shards/polish_val_000000.bin"
19
+ TOK = "/home/ubuntu/dynaword/polish_bpe_32k.json"
20
+
21
+ def load_shard(path):
22
+ with open(path, "rb") as f:
23
+ header = np.frombuffer(f.read(256 * 4), dtype=np.int32)
24
+ assert header[0] == 20240520 and header[1] == 1, "bad shard header"
25
+ ntok = int(header[2])
26
+ toks = np.frombuffer(f.read(ntok * 2), dtype=np.uint16)
27
+ return toks
28
+
29
+ def main():
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--val-loss", type=float, required=True, help="nats/token from training log")
32
+ ap.add_argument("--vocab", type=int, default=32768)
33
+ args = ap.parse_args()
34
+
35
+ toks = load_shard(VAL)
36
+ tok = Tokenizer.from_file(TOK)
37
+ # decode in chunks -> UTF-8 bytes (held-out reconstructs to the original text)
38
+ nbytes = 0
39
+ step = 1_000_000
40
+ for i in range(0, len(toks), step):
41
+ nbytes += len(tok.decode(toks[i:i+step].tolist()).encode("utf-8"))
42
+ ntok = len(toks)
43
+
44
+ ln2 = np.log(2)
45
+ ppl = float(np.exp(args.val_loss))
46
+ bpb = args.val_loss / ln2 * (ntok / nbytes)
47
+ bpt = nbytes / ntok
48
+ rand_bpb = np.log(args.vocab) / ln2 * (ntok / nbytes) # uniform baseline
49
+
50
+ print(f"held-out val: {ntok:,} tokens | {nbytes:,} bytes | {bpt:.3f} bytes/token")
51
+ print(f"val loss : {args.val_loss:.4f} nats/token")
52
+ print(f"perplexity : {ppl:.2f} (tokenizer-specific; NOT cross-model comparable)")
53
+ print(f"bits-per-byte: {bpb:.4f} (tokenizer-AGNOSTIC; report this)")
54
+ print(f" (uniform-{args.vocab} baseline bpb = {rand_bpb:.3f})")
55
+
56
+ if __name__ == "__main__":
57
+ main()
src/fetch_eli.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch Polish primary legislation from the Sejm ELI API into a SpeakLeash-style
3
+ .jsonl.zst, so build_dynaword.py consumes it unchanged (native source, not via
4
+ SpeakLeash). Acts of law are public domain by statute (art. 4 ustawy o prawie
5
+ autorskim — normative acts are not subject to copyright).
6
+
7
+ API: https://api.sejm.gov.pl/eli/acts/{DU|MP}/{year} -> list
8
+ https://api.sejm.gov.pl/eli/acts/{pub}/{year}/{pos}/text.html -> text
9
+
10
+ Resumable: appends to <out>/<key>.jsonl, skips addresses already present, then
11
+ compresses to <key>.jsonl.zst at the end of a run.
12
+
13
+ Usage:
14
+ python3 src/fetch_eli.py --out ~/Local/Ventures/Slayer/data/speakleash \
15
+ --publishers DU MP --years 1990-2025 --in-force-only --workers 8
16
+ """
17
+ from __future__ import annotations
18
+ import argparse, json, re, subprocess, sys, time
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from html.parser import HTMLParser
21
+ from pathlib import Path
22
+ from urllib.request import urlopen, Request
23
+ from urllib.error import URLError, HTTPError
24
+
25
+ API = "https://api.sejm.gov.pl/eli/acts"
26
+ KEY = "dziennik_ustaw" # file stem; build_dynaword reads <KEY>.jsonl.zst
27
+ UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"}
28
+
29
+
30
+ def _get(url, tries=4, raw=False):
31
+ for i in range(tries):
32
+ try:
33
+ with urlopen(Request(url, headers=UA), timeout=30) as r:
34
+ data = r.read()
35
+ return data if raw else json.loads(data)
36
+ except (HTTPError, URLError, TimeoutError) as e:
37
+ if isinstance(e, HTTPError) and e.code == 404:
38
+ return None
39
+ time.sleep(1.5 * (i + 1)) # ponytail: linear backoff, fine at this scale
40
+ return None
41
+
42
+
43
+ class _Text(HTMLParser):
44
+ _SKIP = {"script", "style", "head"}
45
+
46
+ def __init__(self):
47
+ super().__init__()
48
+ self.buf, self._skip = [], 0
49
+
50
+ def handle_starttag(self, tag, attrs):
51
+ if tag in self._SKIP:
52
+ self._skip += 1
53
+
54
+ def handle_endtag(self, tag):
55
+ if tag in self._SKIP and self._skip:
56
+ self._skip -= 1
57
+
58
+ def handle_data(self, data):
59
+ if not self._skip and data.strip():
60
+ self.buf.append(data)
61
+
62
+
63
+ def html_to_text(html_bytes):
64
+ p = _Text()
65
+ p.feed(html_bytes.decode("utf-8", "replace"))
66
+ return re.sub(r"\n{3,}", "\n\n", re.sub(r"[ \t]+", " ", "\n".join(p.buf))).strip()
67
+
68
+
69
+ def list_acts(pub, year, in_force_only):
70
+ d = _get(f"{API}/{pub}/{year}")
71
+ items = (d or {}).get("items", []) if isinstance(d, dict) else []
72
+ out = []
73
+ for it in items:
74
+ if not it.get("textHTML"):
75
+ continue
76
+ if in_force_only and it.get("inForce") not in (None, "IN_FORCE"):
77
+ continue
78
+ out.append(it)
79
+ return out
80
+
81
+
82
+ def fetch_one(it):
83
+ pub, year, pos = it["publisher"], it["address"], it["pos"]
84
+ yr = it.get("year") or int(re.search(r"(\d{4})", it["address"]).group(1))
85
+ html = _get(f"{API}/{it['publisher']}/{yr}/{it['pos']}/text.html", raw=True)
86
+ if not html:
87
+ return None
88
+ text = html_to_text(html)
89
+ if len(text) < 200:
90
+ return None
91
+ return {
92
+ "text": text,
93
+ "meta": {
94
+ "url": f"{API}/{it['publisher']}/{yr}/{it['pos']}",
95
+ "title": it.get("title", ""),
96
+ "address": it["address"], "publisher": it["publisher"],
97
+ "year": yr, "pos": it["pos"], "type": it.get("type", ""),
98
+ "status": it.get("status", ""),
99
+ "announcementDate": it.get("announcementDate", ""),
100
+ },
101
+ }
102
+
103
+
104
+ def parse_years(s):
105
+ if "-" in s:
106
+ a, b = s.split("-"); return range(int(a), int(b) + 1)
107
+ return [int(s)]
108
+
109
+
110
+ def main():
111
+ ap = argparse.ArgumentParser()
112
+ ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash")
113
+ ap.add_argument("--publishers", nargs="+", default=["DU", "MP"])
114
+ ap.add_argument("--years", default="1990-2025")
115
+ ap.add_argument("--in-force-only", action="store_true")
116
+ ap.add_argument("--workers", type=int, default=8)
117
+ args = ap.parse_args()
118
+
119
+ out_dir = Path(args.out).expanduser(); out_dir.mkdir(parents=True, exist_ok=True)
120
+ jsonl = out_dir / f"{KEY}.jsonl"
121
+ done = set()
122
+ if jsonl.exists():
123
+ for ln in jsonl.open(encoding="utf-8"):
124
+ try: done.add(json.loads(ln)["meta"]["address"])
125
+ except Exception: pass
126
+ print(f"resume: {len(done):,} already fetched")
127
+
128
+ years = parse_years(args.years)
129
+ todo = []
130
+ for pub in args.publishers:
131
+ for y in years:
132
+ for it in list_acts(pub, y, args.in_force_only):
133
+ if it["address"] not in done:
134
+ todo.append(it)
135
+ print(f" listed {pub} {y} | queue={len(todo):,}", flush=True)
136
+ print(f"to fetch: {len(todo):,}", flush=True)
137
+
138
+ kept = 0; t0 = time.time()
139
+ with jsonl.open("a", encoding="utf-8") as fo, \
140
+ ThreadPoolExecutor(max_workers=args.workers) as ex:
141
+ for i, rec in enumerate(ex.map(fetch_one, todo), 1):
142
+ if rec:
143
+ fo.write(json.dumps(rec, ensure_ascii=False) + "\n"); kept += 1
144
+ if i % 500 == 0:
145
+ print(f" {i:,}/{len(todo):,} | kept {kept:,} | {i/(time.time()-t0):.1f}/s", flush=True)
146
+
147
+ print(f"fetched {kept:,} new | total file lines below; compressing...", flush=True)
148
+ subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl), "-o",
149
+ str(out_dir / f"{KEY}.jsonl.zst")], check=True)
150
+ print(f"wrote {out_dir / (KEY + '.jsonl.zst')} in {round(time.time()-t0)}s")
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
src/fetch_eltec.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch the Polish ELTeC corpus (European Literary Text Collection, COST Action
3
+ 'Distant Reading') into a SpeakLeash-style .jsonl.zst. ~100 Polish novels
4
+ (1840-1920), level-1 TEI XML, released CC-BY. Directly sourced from GitHub.
5
+
6
+ Usage:
7
+ python3 src/fetch_eltec.py --out ~/Local/Ventures/Slayer/data/speakleash
8
+ """
9
+ from __future__ import annotations
10
+ import argparse, json, re, subprocess, time
11
+ from pathlib import Path
12
+ from urllib.request import urlopen, Request
13
+
14
+ API = "https://api.github.com/repos/COST-ELTeC/ELTeC-pol/contents/level1"
15
+ TEI = "{http://www.tei-c.org/ns/1.0}"
16
+ UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"}
17
+ KEY = "eltec_pol"
18
+ MIN_CHARS = 200
19
+
20
+
21
+ def _get(url, raw=False, tries=4):
22
+ for i in range(tries):
23
+ try:
24
+ with urlopen(Request(url, headers=UA), timeout=60) as r:
25
+ data = r.read()
26
+ return data if raw else json.loads(data)
27
+ except Exception:
28
+ time.sleep(1.5 * (i + 1))
29
+ return None
30
+
31
+
32
+ def tei_to_text(xml_bytes):
33
+ """Extract reading text (title + body paragraphs) from a TEI file."""
34
+ from xml.etree.ElementTree import fromstring
35
+ root = fromstring(xml_bytes)
36
+ title_el = root.find(f".//{TEI}titleStmt/{TEI}title")
37
+ title = (title_el.text or "").strip() if title_el is not None else ""
38
+ body = root.find(f".//{TEI}text/{TEI}body")
39
+ if body is None:
40
+ return title, ""
41
+ parts = []
42
+ for p in body.iter(f"{TEI}p"):
43
+ txt = " ".join(p.itertext())
44
+ txt = re.sub(r"\s+", " ", txt).strip()
45
+ if txt:
46
+ parts.append(txt)
47
+ return title, "\n\n".join(parts)
48
+
49
+
50
+ def main():
51
+ ap = argparse.ArgumentParser()
52
+ ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash")
53
+ args = ap.parse_args()
54
+ out_dir = Path(args.out).expanduser(); out_dir.mkdir(parents=True, exist_ok=True)
55
+
56
+ listing = _get(API) or []
57
+ files = [f for f in listing if f["name"].endswith(".xml")]
58
+ print(f"ELTeC-pol: {len(files)} TEI files", flush=True)
59
+
60
+ jsonl = out_dir / f"{KEY}.jsonl"; kept = 0; t0 = time.time()
61
+ with jsonl.open("w", encoding="utf-8") as fo:
62
+ for i, f in enumerate(files, 1):
63
+ xml = _get(f["download_url"], raw=True)
64
+ if not xml:
65
+ print(f" ! skip {f['name']}"); continue
66
+ title, text = tei_to_text(xml)
67
+ if len(text) < MIN_CHARS:
68
+ continue
69
+ fo.write(json.dumps({
70
+ "text": text,
71
+ "meta": {"url": f["html_url"], "title": title,
72
+ "file": f["name"], "domain": "literature"},
73
+ }, ensure_ascii=False) + "\n")
74
+ kept += 1
75
+ if i % 20 == 0:
76
+ print(f" {i}/{len(files)} | kept {kept}", flush=True)
77
+ subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl),
78
+ "-o", str(out_dir / f"{KEY}.jsonl.zst")], check=True)
79
+ print(f"{KEY}: {kept} novels in {round(time.time()-t0)}s -> {KEY}.jsonl.zst")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
src/fetch_wikimedia.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch Polish Wikimedia sibling projects (Wikinews/Wikivoyage/Wikibooks/Wikiquote)
3
+ from the official dumps into SpeakLeash-style .jsonl.zst, so build_dynaword.py
4
+ consumes them unchanged. All are CC-BY-SA (same basis as Wikipedia/Wikisource).
5
+
6
+ Mainspace (ns=0) only; redirects and empty pages dropped. Wikitext -> plaintext
7
+ via mwparserfromhell.
8
+
9
+ Usage:
10
+ python3 src/fetch_wikimedia.py --out ~/Local/Ventures/Slayer/data/speakleash \
11
+ --wikis plwikinews plwikivoyage plwikibooks plwikiquote
12
+ """
13
+ from __future__ import annotations
14
+ import argparse, bz2, json, subprocess, time
15
+ from pathlib import Path
16
+ from urllib.request import urlopen, Request
17
+ from xml.etree.ElementTree import iterparse
18
+ import mwparserfromhell
19
+
20
+ DUMP = "https://dumps.wikimedia.org/{w}/latest/{w}-latest-pages-articles.xml.bz2"
21
+ UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"}
22
+ MIN_CHARS = 200
23
+ # wiki -> (file stem used by build_dynaword, human URL)
24
+ SITE = {
25
+ "plwikinews": ("https://pl.wikinews.org/wiki/", "news"),
26
+ "plwikivoyage": ("https://pl.wikivoyage.org/wiki/", "travel"),
27
+ "plwikibooks": ("https://pl.wikibooks.org/wiki/", "howto"),
28
+ "plwikiquote": ("https://pl.wikiquote.org/wiki/", "quotes"),
29
+ }
30
+
31
+
32
+ def _local(tag): # strip {namespace}
33
+ return tag.rsplit("}", 1)[-1]
34
+
35
+
36
+ def download(w, cache):
37
+ dst = cache / f"{w}.xml.bz2"
38
+ if dst.exists() and dst.stat().st_size > 0:
39
+ print(f" cached {dst.name}"); return dst
40
+ url = DUMP.format(w=w)
41
+ print(f" downloading {url}", flush=True)
42
+ with urlopen(Request(url, headers=UA), timeout=120) as r, dst.open("wb") as f:
43
+ while chunk := r.read(1 << 20):
44
+ f.write(chunk)
45
+ return dst
46
+
47
+
48
+ def pages(bz2_path):
49
+ """Yield (title, wikitext) for mainspace, non-redirect pages."""
50
+ with bz2.open(bz2_path, "rb") as fh:
51
+ title = ns = text = None; redirect = False
52
+ for ev, el in iterparse(fh, events=("end",)):
53
+ t = _local(el.tag)
54
+ if t == "title": title = el.text
55
+ elif t == "ns": ns = el.text
56
+ elif t == "redirect": redirect = True
57
+ elif t == "text": text = el.text
58
+ elif t == "page":
59
+ if ns == "0" and not redirect and text:
60
+ yield title, text
61
+ title = ns = text = None; redirect = False
62
+ el.clear()
63
+
64
+
65
+ def strip(wikitext):
66
+ try:
67
+ return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()
68
+ except Exception:
69
+ return ""
70
+
71
+
72
+ def main():
73
+ ap = argparse.ArgumentParser()
74
+ ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash")
75
+ ap.add_argument("--wikis", nargs="+", default=list(SITE))
76
+ args = ap.parse_args()
77
+ out_dir = Path(args.out).expanduser(); out_dir.mkdir(parents=True, exist_ok=True)
78
+ cache = out_dir / "_wikimedia_dumps"; cache.mkdir(exist_ok=True)
79
+
80
+ for w in args.wikis:
81
+ base_url, domain = SITE[w]
82
+ print(f"[{w}] ({domain})", flush=True)
83
+ src = download(w, cache)
84
+ jsonl = out_dir / f"{w}.jsonl"
85
+ kept = 0; t0 = time.time()
86
+ with jsonl.open("w", encoding="utf-8") as fo:
87
+ for title, wt in pages(src):
88
+ text = strip(wt)
89
+ if len(text) < MIN_CHARS:
90
+ continue
91
+ fo.write(json.dumps({
92
+ "text": text,
93
+ "meta": {"url": base_url + (title or "").replace(" ", "_"),
94
+ "title": title, "wiki": w, "domain": domain},
95
+ }, ensure_ascii=False) + "\n")
96
+ kept += 1
97
+ if kept % 2000 == 0:
98
+ print(f" {kept:,} kept | {kept/(time.time()-t0):.0f}/s", flush=True)
99
+ subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl),
100
+ "-o", str(out_dir / f"{w}.jsonl.zst")], check=True)
101
+ print(f" {w}: {kept:,} docs in {round(time.time()-t0)}s -> {w}.jsonl.zst", flush=True)
102
+
103
+
104
+ if __name__ == "__main__":
105
+ main()
src/make_docs.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate Dynaword documentation: per-source datasheets + README + CHANGELOG + LICENSE.
3
+
4
+ Reads sources.py + data/<source>/<source>.stats.json (written by build_dynaword.py).
5
+ Implements the "Documented" principle (datasheets, Gebru et al. 2021) and the
6
+ aggregate README table (paper 2508.02271).
7
+ """
8
+ from __future__ import annotations
9
+ import json, sys
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+ from sources import SOURCES, EXCLUDED, ADDED
14
+
15
+ ROOT = Path(__file__).resolve().parent.parent
16
+ VERSION = "0.2.0"
17
+ CONTACT = "k.wikiel@gmail.com" # notice-and-takedown / data-removal requests
18
+
19
+ # Dupochron: documented good-faith provenance + no-warranty + takedown + PII.
20
+ DISCLAIMER = f"""## Personal & sensitive data
21
+ This corpus contains **only** text that its upstream sources already published
22
+ under open licenses or as official public-domain record. It therefore includes
23
+ names and statements of **public figures acting in a public capacity** — e.g.
24
+ parliamentary speakers (PPC), authorities named in legal acts (EUR-Lex), and
25
+ people described in encyclopedic articles (Wikipedia/Wikisource). No private,
26
+ non-public personal data was collected or added. If you are a data subject and
27
+ want content concerning you removed, contact **{CONTACT}** — it will be dropped
28
+ from the next version (see retroactive-removal policy below).
29
+
30
+ ## Disclaimer & legal
31
+ - **Provenance in good faith.** Per-source licenses are reproduced *as documented
32
+ by the upstream sources and by SpeakLeash* (the intermediate aggregator), to the
33
+ best of our knowledge. We make no independent legal warranty about the copyright
34
+ status of any individual document.
35
+ - **No ownership claim.** This release is a *curated, license-reviewed, documented
36
+ aggregation*. We claim no ownership of the underlying texts; rights remain with
37
+ the original authors/rightsholders under their respective licenses.
38
+ - **Provided "as is"**, without warranty of any kind, express or implied. This is
39
+ not legal advice.
40
+ - **Your compliance is yours.** Downstream users must satisfy each upstream
41
+ license themselves — in particular **CC-BY-SA-4.0 attribution and share-alike**
42
+ for derivatives of this dataset, and attribution to the upstream sources and to
43
+ SpeakLeash.
44
+ - **Notice-and-takedown.** Any source or rightsholder raising a substantiated
45
+ objection can have material removed: contact **{CONTACT}**; it is dropped from
46
+ the next version and recorded in the CHANGELOG. Removal is retroactive
47
+ going-forward (prior immutable snapshots/commits may persist).
48
+ """
49
+
50
+
51
+ def load_stats(name):
52
+ f = ROOT / "data" / name / f"{name}.stats.json"
53
+ return json.loads(f.read_text()) if f.exists() else None
54
+
55
+
56
+ def datasheet(name, cfg, st):
57
+ return f"""# {name}
58
+
59
+ {cfg['pretty']}
60
+
61
+ ## Dataset description
62
+ - **Source (upstream):** {cfg['upstream']}
63
+ - **Domain:** {cfg['domain']}
64
+ - **Language:** Polish (pl)
65
+ - **License:** `{cfg['license']}`
66
+ - **Created (range):** {cfg['created']}
67
+ - **Added:** {ADDED}
68
+
69
+ ## Licensing — traceable basis
70
+ {cfg['traceable']}
71
+
72
+ ## Provenance
73
+ {cfg.get('provenance', f"Pulled from SpeakLeash's public redistribution "
74
+ f"(`speakleash-ds-pub`, key `{cfg.get('speakleash_key')}`) of the upstream source "
75
+ f"above. SpeakLeash credited as intermediate aggregator; upstream "
76
+ f"license/attribution preserved.")}
77
+
78
+ ## Statistics
79
+ | documents | characters | tokens (tiktoken proxy) |
80
+ |---:|---:|---:|
81
+ | {st['kept']:,} | {st['chars']:,} | {st['tokens']:,} |
82
+
83
+ ## Filters applied (build_dynaword.py)
84
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
85
+ - drop documents < 200 chars: **{st['drop_short']:,}**
86
+ - drop non-Polish (diacritic ratio): **{st['drop_lang']:,}**
87
+ - exact cross-source dedup (sha1): **{st['drop_dup']:,}**
88
+ - OCR alpha-ratio < 0.70 (OCR sources only): **{st['drop_ocr']:,}**
89
+ - read {st['read']:,} → kept {st['kept']:,}
90
+
91
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
92
+ Llama-3 count is computed at release.
93
+ """
94
+
95
+
96
+ def main():
97
+ rows, tot_doc, tot_tok, tot_chr = [], 0, 0, 0
98
+ for name, cfg in SOURCES.items():
99
+ st = load_stats(name)
100
+ if not st:
101
+ print(f" ! no stats for {name}"); continue
102
+ (ROOT / "data" / name / f"{name}.md").write_text(datasheet(name, cfg, st))
103
+ rows.append((name, cfg, st))
104
+ tot_doc += st["kept"]; tot_tok += st["tokens"]; tot_chr += st["chars"]
105
+ rows.sort(key=lambda r: -r[2]["tokens"])
106
+
107
+ tbl = "\n".join(
108
+ f"| [{n}](data/{n}/{n}.md) | {c['pretty']} | `{c['license']}` | "
109
+ f"{s['kept']:,} | {s['tokens']/1e6:,.1f}M |"
110
+ for n, c, s in rows)
111
+ excl = "\n".join(f"| `{k}` | {v} |" for k, v in EXCLUDED.items())
112
+
113
+ readme = f"""---
114
+ license: cc-by-sa-4.0
115
+ language:
116
+ - pl
117
+ pretty_name: Polish DynaWord
118
+ task_categories:
119
+ - text-generation
120
+ size_categories:
121
+ - 1M<n<10M
122
+ tags:
123
+ - polish
124
+ - pretraining
125
+ - dynaword
126
+ ---
127
+
128
+ # Polish DynaWord
129
+
130
+ A continuously developed, **openly-licensed**, human-text Polish corpus — a Polish
131
+ edition in the [Dynaword](https://huggingface.co/datasets/danish-foundation-models/danish-dynaword)
132
+ family (Enevoldsen et al., [arXiv:2508.02271](https://arxiv.org/abs/2508.02271)).
133
+
134
+ > **v{VERSION}** · {tot_doc:,} documents · **{tot_tok/1e9:.2f}B tokens** (tiktoken proxy;
135
+ > canonical Llama-3 count at release) · {len(rows)} sources
136
+
137
+ ## What this dataset contributes
138
+ The raw texts come from existing open corpora (redistributed via SpeakLeash and,
139
+ where applicable, fetched from upstream). **The value added here is the curation,
140
+ not the bytes**, following the Dynaword methodology:
141
+
142
+ 1. **License review per source** — each source vetted for an *openly-licensed,
143
+ traceable* legal basis (documented in its datasheet); sources that fail the
144
+ review are **excluded with a stated reason** (see table below), not silently
145
+ kept. This is the core editorial work.
146
+ 2. **Filtering & normalization** — minimal, reproducible gates (short-doc,
147
+ non-Polish, exact cross-source dedup, OCR garble) applied uniformly to one
148
+ clean schema: `id, text, source, added, created, token_count`.
149
+ 3. **Documentation** — a datasheet per source (Gebru et al. 2021) + this card,
150
+ so provenance and licensing are auditable rather than assumed.
151
+ 4. **Reproducibility & versioning** — `src/` rebuilds the corpus from sources;
152
+ new sources and removals are tracked in the CHANGELOG.
153
+
154
+ Credit for the underlying texts belongs to the upstream sources and to SpeakLeash
155
+ as the redistributing aggregator; this release does not claim ownership of them
156
+ (see Disclaimer).
157
+
158
+ ## Guiding principles
159
+ 1. **Open & traceable licensing** — every source is *openly licensed* with a documented
160
+ legal basis (see each datasheet's "traceable basis"), not a vague "public domain".
161
+ 2. **Reproducibility** — `src/build_dynaword.py` rebuilds the corpus from sources.
162
+ 3. **Documented** — a datasheet per source under `data/<source>/`.
163
+ 4. **Extensibility** — versioned; new sources via PR.
164
+
165
+ ## Sources
166
+ | source | description | license | documents | tokens |
167
+ |---|---|---|---:|---:|
168
+ {tbl}
169
+ | **total** | | | **{tot_doc:,}** | **{tot_tok/1e6:,.1f}M** |
170
+
171
+ ## Method
172
+ Only **human-authored** text — no synthetic, machine-translated, or auto-transcribed
173
+ data. Gates are intentionally minimal (drop short docs, non-Polish, exact duplicates,
174
+ OCR garble); heavy quality filtering and mix-weighting are left to downstream training.
175
+ Evaluation-set decontamination is applied/marked separately. Schema:
176
+ `id, text, source, added, created, token_count`.
177
+
178
+ ## Excluded sources (transparency)
179
+ Sources we reviewed and **deliberately left out** — part of the curation:
180
+
181
+ | source | reason |
182
+ |---|---|
183
+ {excl}
184
+
185
+ {DISCLAIMER}
186
+ ## License & attribution
187
+ Released under **CC-BY-SA-4.0** (copyleft inherited from CC-BY-SA sources such as
188
+ Wikipedia/Wikisource/Wolne Lektury). Attribution due to each upstream (see datasheets)
189
+ and to **SpeakLeash** as the intermediate aggregator. Retroactive-removal policy: a
190
+ source that raises an objection is dropped from subsequent versions, recorded in the
191
+ CHANGELOG.
192
+
193
+ ## Reproduce
194
+ ```bash
195
+ python3 src/build_dynaword.py --all --speakleash-dir <speakleash_zst_dir> --out .
196
+ python3 src/make_docs.py
197
+ ```
198
+ """
199
+ (ROOT / "README.md").write_text(readme)
200
+
201
+ (ROOT / "CHANGELOG.md").write_text(
202
+ f"# Changelog\n\n## v{VERSION} ({ADDED})\n\n"
203
+ f"- Initial release: {len(rows)} openly-licensed sources, "
204
+ f"{tot_doc:,} docs, {tot_tok/1e9:.2f}B tokens (tiktoken proxy).\n"
205
+ f"- Sources: {', '.join(n for n, _, _ in rows)}.\n"
206
+ f"- Excluded (see README): {', '.join(EXCLUDED)}.\n")
207
+
208
+ (ROOT / "LICENSE").write_text(
209
+ "Polish DynaWord is released under Creative Commons Attribution-ShareAlike 4.0\n"
210
+ "International (CC-BY-SA-4.0): https://creativecommons.org/licenses/by-sa/4.0/\n\n"
211
+ "Per-source upstream licenses and attribution are documented in each\n"
212
+ "data/<source>/<source>.md datasheet.\n")
213
+
214
+ print(f"docs written: README + CHANGELOG + LICENSE + {len(rows)} datasheets")
215
+ print(f"TOTAL {tot_doc:,} docs | {tot_tok/1e9:.2f}B tok | {tot_chr/1e9:.1f}B chars")
216
+
217
+
218
+ if __name__ == "__main__":
219
+ main()
src/make_linkedin_card.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Beautiful LinkedIn teaser card for the open-licensed Polish token dataset.
3
+ Vague on provenance: shows totals + domain split + licensing claims only.
4
+ """
5
+ import matplotlib
6
+ matplotlib.use("Agg")
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.patches import FancyBboxPatch
9
+ from matplotlib import font_manager as fm
10
+
11
+ FT = "Avenir Next" if "Avenir Next" in {f.name for f in fm.fontManager.ttflist} else "Helvetica Neue"
12
+ plt.rcParams["font.family"] = FT
13
+
14
+ # palette
15
+ BG = "#0B0F14"
16
+ INK = "#EAF1F8"
17
+ MUTED = "#7E8B9A"
18
+ FAINT = "#1B232D"
19
+ GREEN = "#34E0A1" # legal & official
20
+ BLUE = "#5AA2FF" # encyclopedic
21
+ VIOLET = "#B98BFF" # literature
22
+
23
+ # data (vague domains; numbers in millions of tokens, tiktoken proxy)
24
+ domains = [("Legal & official", 4024.9, GREEN),
25
+ ("Encyclopedic & reference", 1509.1, BLUE),
26
+ ("Literature & books", 104.0, VIOLET)]
27
+ total = sum(v for _, v, _ in domains)
28
+
29
+ fig = plt.figure(figsize=(12, 12), dpi=100)
30
+ fig.patch.set_facecolor(BG)
31
+ ax = fig.add_axes([0, 0, 1, 1]); ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
32
+ ax.add_patch(plt.Rectangle((0, 0), 1, 1, color=BG, zorder=-10))
33
+
34
+ # top accent bar
35
+ ax.add_patch(plt.Rectangle((0, 0.988), 1, 0.012, color=GREEN, zorder=5))
36
+
37
+ # eyebrow
38
+ ax.text(0.07, 0.915, "P O L I S H L A N G U A G E · O P E N P R E T R A I N I N G D A T A",
39
+ color=GREEN, fontsize=14.5, weight="bold", alpha=0.95)
40
+ # hero
41
+ ax.text(0.07, 0.85, "Licensed to train.", color=INK, fontsize=52, weight="bold")
42
+ ax.text(0.072, 0.788,
43
+ "A Polish corpus where every single token is openly licensed —\ncleared for model training, with a documented legal basis.",
44
+ color=MUTED, fontsize=18.5, linespacing=1.45)
45
+
46
+ # donut (left)
47
+ dax = fig.add_axes([0.045, 0.30, 0.44, 0.44]); dax.set_aspect("equal")
48
+ vals = [v for _, v, _ in domains]; cols = [c for _, _, c in domains]
49
+ dax.pie(vals, colors=cols, startangle=90, counterclock=False,
50
+ wedgeprops=dict(width=0.30, edgecolor=BG, linewidth=4))
51
+ dax.text(0, 0.10, "5.6B", ha="center", va="center", color=INK, fontsize=58, weight="bold")
52
+ dax.text(0, -0.12, "openly-licensed tokens", ha="center", va="center", color=MUTED, fontsize=16)
53
+
54
+ # legend (right)
55
+ lx, ly = 0.565, 0.625
56
+ for name, v, c in domains:
57
+ ax.add_patch(plt.Circle((lx, ly + 0.011), 0.013, color=c, transform=ax.transAxes))
58
+ ax.text(lx + 0.035, ly + 0.020, name, color=INK, fontsize=20, weight="bold", va="center")
59
+ ax.text(lx + 0.035, ly - 0.012, f"{v/total*100:.0f}% · {v/1000:.1f}B tokens",
60
+ color=MUTED, fontsize=14.5, va="center")
61
+ ly -= 0.085
62
+
63
+ # stat strip
64
+ ax.add_patch(plt.Rectangle((0.07, 0.247), 0.86, 0.0016, color=FAINT))
65
+ stats = [("2.4M", "documents"), ("100%", "open licenses"),
66
+ ("0", "copyrighted media"), ("human", "written, not synthetic")]
67
+ sx = 0.07
68
+ for big, small in stats:
69
+ ax.text(sx, 0.205, big, color=INK, fontsize=27, weight="bold")
70
+ ax.text(sx, 0.168, small, color=MUTED, fontsize=14.5)
71
+ sx += 0.225
72
+
73
+ # license pills (centered row, drawn checkmarks since the font lacks U+2713)
74
+ pills = [("Open licenses only", GREEN), ("Traceable provenance", BLUE),
75
+ ("Deduplicated", VIOLET)]
76
+ def pw(text): return 0.0125 * len(text) + 0.062
77
+ widths = [pw(t) for t, _ in pills]
78
+ gap, ph, py = 0.022, 0.05, 0.088
79
+ total_w = sum(widths) + gap * (len(pills) - 1)
80
+ px = (1 - total_w) / 2
81
+ for (t, c), w in zip(pills, widths):
82
+ ax.add_patch(FancyBboxPatch((px, py), w, ph, boxstyle="round,pad=0.004,rounding_size=0.024",
83
+ mutation_aspect=1, fc=FAINT, ec=c, lw=1.7, zorder=3))
84
+ cx = px + 0.026
85
+ ax.plot([cx, cx + 0.008, cx + 0.02], [py + ph/2, py + ph/2 - 0.008, py + ph/2 + 0.012],
86
+ color=c, lw=2.8, solid_capstyle="round", solid_joinstyle="round", zorder=5)
87
+ ax.text(px + w/2 + 0.016, py + ph/2, t, ha="center", va="center",
88
+ color=INK, fontsize=13.5, weight="bold", zorder=4)
89
+ px += w + gap
90
+
91
+ # footer
92
+ ax.text(0.07, 0.04, "CC-BY-SA · public domain · permissive-only", color=MUTED, fontsize=14)
93
+ ax.text(0.93, 0.04, "SLAYER LABS", color=INK, fontsize=15, weight="bold", ha="right", alpha=0.9)
94
+
95
+ import os
96
+ out = os.path.expanduser("~/Desktop/polish_open_corpus_card.png")
97
+ fig.savefig(out, facecolor=BG, dpi=100)
98
+ print("saved", out)
src/rights.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """edm:rights classifier for the Europeana source (mixed per-record rights).
2
+
3
+ Dynaword principle = openly licensed. Allow only PD / CC0 / CC-BY / CC-BY-SA.
4
+ NC/ND are not open; InC / NoC-* / CNE are in-copyright or unclear -> drop.
5
+ Wire into build_dynaword.py only for europeana (per-record); other sources keep
6
+ their single per-source license.
7
+ """
8
+
9
+ # ponytail: substring match on the rights URI — finite, well-known statement set
10
+ _OPEN = (
11
+ "creativecommons.org/publicdomain/mark", # Public Domain Mark
12
+ "creativecommons.org/publicdomain/zero", # CC0
13
+ "creativecommons.org/licenses/by/", # CC-BY
14
+ "creativecommons.org/licenses/by-sa/", # CC-BY-SA
15
+ )
16
+
17
+
18
+ def rights_ok(uri: str) -> bool:
19
+ u = (uri or "").lower().rstrip("/") + "/"
20
+ return any(tag in u for tag in _OPEN)
21
+
22
+
23
+ def spdx(uri: str) -> str:
24
+ u = (uri or "").lower()
25
+ if "publicdomain/zero" in u: return "CC0-1.0"
26
+ if "publicdomain/mark" in u: return "PD"
27
+ if "/by-sa/" in u: return "CC-BY-SA-4.0"
28
+ if "/by/" in u: return "CC-BY-4.0"
29
+ return "UNKNOWN"
30
+
31
+
32
+ if __name__ == "__main__": # self-check
33
+ assert rights_ok("http://creativecommons.org/licenses/by-sa/4.0/")
34
+ assert rights_ok("https://creativecommons.org/publicdomain/mark/1.0/")
35
+ assert rights_ok("http://creativecommons.org/publicdomain/zero/1.0/")
36
+ assert not rights_ok("http://creativecommons.org/licenses/by-nc/4.0/")
37
+ assert not rights_ok("http://creativecommons.org/licenses/by-nd/4.0/")
38
+ assert not rights_ok("http://rightsstatements.org/vocab/InC/1.0/")
39
+ assert not rights_ok("http://rightsstatements.org/vocab/NoC-OKLR/1.0/")
40
+ assert not rights_ok("")
41
+ assert spdx("http://creativecommons.org/licenses/by-sa/4.0/") == "CC-BY-SA-4.0"
42
+ assert spdx("http://creativecommons.org/publicdomain/zero/1.0/") == "CC0-1.0"
43
+ print("ok")
src/sample_quality.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sample docs per source and score corpus quality with cheap heuristics.
2
+
3
+ ponytail: heuristic eyeball score, not an LLM judge. Add LLM-judge pass if these
4
+ metrics look ambiguous and you need semantic quality, not just surface garble.
5
+ """
6
+ import sys, re, random
7
+ import pyarrow.parquet as pq
8
+
9
+ SOURCES = ["eurlex", "parliamentary", "wikisource", "wikipedia",
10
+ "dziennik_ustaw", "wolne_lektury"]
11
+ N = int(sys.argv[1]) if len(sys.argv) > 1 else 200 # docs sampled per source
12
+ SHOW = 2 # raw samples printed per source
13
+
14
+ PL_DIAC = set("ąćęłńóśźżĄĆĘŁŃÓŚŹŻ")
15
+ LETTER = re.compile(r"[^\W\d_]", re.UNICODE)
16
+
17
+ def sample_rows(path, n):
18
+ """Grab n docs spread across scattered row groups (cheap pseudo-random)."""
19
+ pf = pq.ParquetFile(path)
20
+ ng = pf.num_row_groups
21
+ groups = sorted(random.sample(range(ng), min(ng, 8)))
22
+ out = []
23
+ per = max(1, n // len(groups))
24
+ for g in groups:
25
+ tbl = pf.read_row_group(g, columns=["text"])
26
+ texts = tbl.column("text").to_pylist()
27
+ out += random.sample(texts, min(per, len(texts)))
28
+ if len(out) >= n:
29
+ break
30
+ return out[:n]
31
+
32
+ def score(text):
33
+ t = text or ""
34
+ n = len(t)
35
+ if n == 0:
36
+ return None
37
+ letters = sum(1 for c in t if LETTER.match(c))
38
+ diac = sum(1 for c in t if c in PL_DIAC)
39
+ repl = t.count("�") # OCR/decode garbage
40
+ digits = sum(c.isdigit() for c in t)
41
+ space = sum(c.isspace() for c in t)
42
+ words = t.split()
43
+ uniq = len(set(words)) / len(words) if words else 0
44
+ return dict(
45
+ chars=n,
46
+ letter_ratio=letters / n,
47
+ diac_per_kchar=1000 * diac / n,
48
+ repl_per_kchar=1000 * repl / n,
49
+ digit_ratio=digits / n,
50
+ space_ratio=space / n,
51
+ word_uniq=uniq,
52
+ )
53
+
54
+ def avg(rows, k):
55
+ v = [r[k] for r in rows if r]
56
+ return sum(v) / len(v) if v else 0
57
+
58
+ print(f"sampling {N} docs/source\n")
59
+ print(f"{'source':<16} {'chars':>8} {'letter%':>8} {'diac/k':>7} "
60
+ f"{'repl/k':>7} {'digit%':>7} {'uniq':>6} {'<200ch':>7}")
61
+ for s in SOURCES:
62
+ path = f"data/{s}/{s}.parquet"
63
+ docs = sample_rows(path, N)
64
+ scored = [score(d) for d in docs]
65
+ scored = [x for x in scored if x]
66
+ short = sum(1 for x in scored if x["chars"] < 200) / len(scored)
67
+ print(f"{s:<16} {avg(scored,'chars'):>8.0f} "
68
+ f"{100*avg(scored,'letter_ratio'):>7.1f}% "
69
+ f"{avg(scored,'diac_per_kchar'):>7.1f} "
70
+ f"{avg(scored,'repl_per_kchar'):>7.2f} "
71
+ f"{100*avg(scored,'digit_ratio'):>6.1f}% "
72
+ f"{avg(scored,'word_uniq'):>6.2f} "
73
+ f"{100*short:>6.1f}%")
74
+
75
+ print("\n=== raw samples ===")
76
+ for s in SOURCES:
77
+ docs = sample_rows(f"data/{s}/{s}.parquet", SHOW)
78
+ print(f"\n--- {s} ---")
79
+ for d in docs:
80
+ snippet = re.sub(r"\s+", " ", d)[:300]
81
+ print(f" [{len(d)} ch] {snippet}")
src/sources.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Source registry for Polish DynaWord.
2
+
3
+ Each entry = one openly-licensed, *traceable* human-text source (paper 2508.02271,
4
+ principle: open+traceable licensing). The `traceable` field documents WHY the
5
+ license holds (not just "it's public domain") — e.g. statutory basis or upstream
6
+ license — as required by the Dynaword guidelines.
7
+
8
+ Provenance note: data is pulled from SpeakLeash's public redistribution
9
+ (iDrive e2 bucket) of these upstream sources; SpeakLeash is credited as the
10
+ intermediate aggregator, upstream license/attribution is preserved per source.
11
+ """
12
+
13
+ # clean-6: passed the copyright review (2026-06-15). open_subtitles excluded
14
+ # (derivative of copyrighted film dialogue — same lesson as Danish Gigaword),
15
+ # europeana + 1000_novels deferred pending per-record rights / title check.
16
+ SOURCES = {
17
+ "wikipedia": {
18
+ "speakleash_key": "plwiki",
19
+ "pretty": "Polish Wikipedia",
20
+ "license": "CC-BY-SA-3.0",
21
+ "license_spdx": "CC-BY-SA-3.0",
22
+ "traceable": "Wikimedia dumps explicitly released under CC-BY-SA 3.0; "
23
+ "attribution to contributors + share-alike preserved.",
24
+ "upstream": "https://dumps.wikimedia.org/plwiki/latest/",
25
+ "domain": "encyclopedic",
26
+ "created": "2001-01-15, 2026-06-14",
27
+ "is_ocr": False,
28
+ },
29
+ "wikisource": {
30
+ "speakleash_key": "plwikisource",
31
+ "pretty": "Polish Wikisource",
32
+ "license": "CC-BY-SA-3.0",
33
+ "license_spdx": "CC-BY-SA-3.0",
34
+ "traceable": "Wikimedia dumps under CC-BY-SA 3.0; underlying texts are "
35
+ "public-domain works transcribed by the community.",
36
+ "upstream": "https://dumps.wikimedia.org/plwikisource/latest/",
37
+ "domain": "books/source-texts",
38
+ "created": "2005-01-01, 2026-06-14",
39
+ "is_ocr": False,
40
+ },
41
+ "eurlex": {
42
+ "speakleash_key": "eurlex_corpus",
43
+ "pretty": "EUR-Lex (EU legal acts, Polish)",
44
+ "license": "CC-BY-4.0",
45
+ "license_spdx": "CC-BY-4.0",
46
+ "traceable": "EU documents reusable under Commission Decision 2011/833/EU; "
47
+ "normative acts fall outside copyright (PL art. 4 pr. aut.). "
48
+ "Reuse authorised with source acknowledgement.",
49
+ "upstream": "https://eur-lex.europa.eu",
50
+ "domain": "legal",
51
+ "created": "1952-01-01, 2024-12-31",
52
+ "is_ocr": False,
53
+ },
54
+ "parliamentary": {
55
+ "speakleash_key": "PPC_corpus",
56
+ "pretty": "Polish Parliamentary Corpus (Sejm/Senat)",
57
+ "license": "public-domain (official documents)",
58
+ "license_spdx": "CC-BY-4.0",
59
+ "traceable": "Parliamentary proceedings are official documents outside "
60
+ "copyright (PL art. 4 pr. aut.); PPC redistributed by IPI PAN "
61
+ "under CC-BY-4.0.",
62
+ "upstream": "http://clip.ipipan.waw.pl/PPC",
63
+ "domain": "political/spoken",
64
+ "created": "1991-01-01, 2019-12-31",
65
+ "is_ocr": False,
66
+ },
67
+ "wolne_lektury": {
68
+ "speakleash_key": "wolne_lektury_corpus",
69
+ "pretty": "Wolne Lektury (school readings)",
70
+ "license": "CC-BY-SA-4.0 / Wolna Sztuka 1.3",
71
+ "license_spdx": "CC-BY-SA-4.0",
72
+ "traceable": "Wolne Lektury publishes under CC-BY-SA 4.0 or Free Art "
73
+ "License; texts are public-domain classics + cleared works.",
74
+ "upstream": "https://wolnelektury.pl/api/books/",
75
+ "domain": "literature",
76
+ "created": "1500-01-01, 2024-12-31",
77
+ "is_ocr": False,
78
+ },
79
+ "wikinews": {
80
+ "file_key": "plwikinews", # fetched from Wikimedia dumps, NOT via SpeakLeash
81
+ "pretty": "Polish Wikinews",
82
+ "license": "CC-BY-2.5",
83
+ "license_spdx": "CC-BY-2.5",
84
+ "traceable": "Wikinews content is released under CC-BY 2.5; attribution to "
85
+ "contributors preserved.",
86
+ "upstream": "https://pl.wikinews.org/",
87
+ "provenance": "Fetched directly from the official Wikimedia dump "
88
+ "(plwikinews-latest-pages-articles) by src/fetch_wikimedia.py; "
89
+ "mainspace only, wikitext stripped via mwparserfromhell.",
90
+ "domain": "news",
91
+ "created": "2005-01-01, 2025-12-31",
92
+ "is_ocr": False,
93
+ },
94
+ "wikivoyage": {
95
+ "file_key": "plwikivoyage",
96
+ "pretty": "Polish Wikivoyage (travel guides)",
97
+ "license": "CC-BY-SA-3.0",
98
+ "license_spdx": "CC-BY-SA-3.0",
99
+ "traceable": "Wikivoyage content is released under CC-BY-SA 3.0; "
100
+ "attribution + share-alike preserved.",
101
+ "upstream": "https://pl.wikivoyage.org/",
102
+ "provenance": "Fetched directly from the official Wikimedia dump "
103
+ "(plwikivoyage-latest-pages-articles) by src/fetch_wikimedia.py; "
104
+ "mainspace only, wikitext stripped via mwparserfromhell.",
105
+ "domain": "travel",
106
+ "created": "2012-01-01, 2025-12-31",
107
+ "is_ocr": False,
108
+ },
109
+ "wikibooks": {
110
+ "file_key": "plwikibooks",
111
+ "pretty": "Polish Wikibooks (open textbooks)",
112
+ "license": "CC-BY-SA-3.0",
113
+ "license_spdx": "CC-BY-SA-3.0",
114
+ "traceable": "Wikibooks content is released under CC-BY-SA 3.0; "
115
+ "attribution + share-alike preserved.",
116
+ "upstream": "https://pl.wikibooks.org/",
117
+ "provenance": "Fetched directly from the official Wikimedia dump "
118
+ "(plwikibooks-latest-pages-articles) by src/fetch_wikimedia.py; "
119
+ "mainspace only, wikitext stripped via mwparserfromhell.",
120
+ "domain": "instructional",
121
+ "created": "2004-01-01, 2025-12-31",
122
+ "is_ocr": False,
123
+ },
124
+ "wikiquote": {
125
+ "file_key": "plwikiquote",
126
+ "pretty": "Polish Wikiquote (quotations)",
127
+ "license": "CC-BY-SA-3.0",
128
+ "license_spdx": "CC-BY-SA-3.0",
129
+ "traceable": "Wikiquote content is released under CC-BY-SA 3.0; "
130
+ "attribution + share-alike preserved.",
131
+ "upstream": "https://pl.wikiquote.org/",
132
+ "provenance": "Fetched directly from the official Wikimedia dump "
133
+ "(plwikiquote-latest-pages-articles) by src/fetch_wikimedia.py; "
134
+ "mainspace only, wikitext stripped via mwparserfromhell.",
135
+ "domain": "quotations",
136
+ "created": "2005-01-01, 2025-12-31",
137
+ "is_ocr": False,
138
+ },
139
+ "eltec_pol": {
140
+ "file_key": "eltec_pol",
141
+ "pretty": "ELTeC-pol (European Literary Text Collection, Polish)",
142
+ "license": "CC-BY-4.0",
143
+ "license_spdx": "CC-BY-4.0",
144
+ "traceable": "ELTeC corpora are released under CC-BY 4.0 by the COST Action "
145
+ "'Distant Reading for European Literary History' (CA16204).",
146
+ "upstream": "https://github.com/COST-ELTeC/ELTeC-pol",
147
+ "provenance": "Fetched directly from the COST-ELTeC/ELTeC-pol GitHub "
148
+ "repository (level1 TEI) by src/fetch_eltec.py; reading text "
149
+ "extracted from TEI <body> paragraphs.",
150
+ "domain": "literature",
151
+ "created": "1840-01-01, 1920-12-31",
152
+ "is_ocr": False,
153
+ },
154
+ "dziennik_ustaw": {
155
+ "file_key": "dziennik_ustaw", # fetched directly, NOT via SpeakLeash
156
+ "pretty": "Dziennik Ustaw + Monitor Polski (Polish primary legislation)",
157
+ "license": "public-domain (official documents)",
158
+ "license_spdx": "CC0-1.0",
159
+ "traceable": "Normative acts and their official drafts are not subject to "
160
+ "copyright (PL art. 4 ustawy o prawie autorskim). Published by "
161
+ "the state; reuse unrestricted.",
162
+ "upstream": "https://api.sejm.gov.pl/eli/acts",
163
+ "provenance": "Fetched directly from the Sejm ELI API (text.html per act) "
164
+ "by src/fetch_eli.py — a native source, not redistributed via "
165
+ "SpeakLeash. Full provenance: each act's `meta.url` is its ELI "
166
+ "address, resolvable on api.sejm.gov.pl.",
167
+ "domain": "legal",
168
+ "created": "1918-01-01, 2025-12-31",
169
+ "is_ocr": False,
170
+ },
171
+ }
172
+
173
+ ADDED = "2026-06-15"
174
+ EXCLUDED = {
175
+ "open_subtitles_corpus": "Derivative of copyrighted film/TV dialogue; "
176
+ "OpenSubtitles uploads largely unlicensed. Same copyright lesson as "
177
+ "Danish Gigaword's OpenSubtitles (paper 2508.02271). Not openly licensed.",
178
+ "europeana_eu_pl_corpus": "Aggregated items with mixed per-record rights "
179
+ "(PD / CC-BY-NC / rights-reserved). Needs per-record edm:rights filter "
180
+ "before any inclusion.",
181
+ "1000_novels_corpus_CLARIN-PL": "CC-BY-4.0 label, but 'novels' likely include "
182
+ "in-copyright contemporary works; verify titles/years on CLARIN handle "
183
+ "11321/312 before inclusion.",
184
+ "project_gutenberg_pl_corpus": "Only 31 PL books (4.3MB) — PG is ~99% English; "
185
+ "Polish PD literature already covered by wolne_lektury + wikisource (so "
186
+ "near-redundant after dedup). Dropped to avoid the PD-in-EU per-work check "
187
+ "(PG claims PD-in-US only) for negligible token gain.",
188
+ }
src/tokenize_shards.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Tokenize the corpus with the Polish BPE into modded-nanogpt/llm.c shards.
3
+ Single process: tokenizers' encode_batch parallelises across cores via Rust rayon
4
+ natively — NO mp.Pool (nesting mp.Pool x rayon oversubscribes and is ~4x slower).
5
+ Format: 256 int32 header [magic 20240520, version 1, ntok] + uint16 tokens.
6
+ Docs joined with <|endoftext|>; ~1/200 docs held out for validation."""
7
+ import glob, os, time
8
+ import numpy as np
9
+ import pyarrow.parquet as pq
10
+ from tokenizers import Tokenizer
11
+
12
+ TOKJSON = "/home/ubuntu/dynaword/polish_bpe_32k.json"
13
+ DATA = "/home/ubuntu/dynaword/data"
14
+ OUT = "/home/ubuntu/dynaword/shards"
15
+ SHARD = 100_000_000
16
+ VAL_EVERY = 200
17
+ CHUNK = 50_000 # docs per encode_batch call
18
+ os.makedirs(OUT, exist_ok=True)
19
+
20
+ def doc_stream():
21
+ for f in sorted(glob.glob(f"{DATA}/*/*.parquet")):
22
+ for b in pq.ParquetFile(f).iter_batches(columns=["text"], batch_size=2000):
23
+ for x in b.column("text"):
24
+ s = x.as_py()
25
+ if s:
26
+ yield s
27
+
28
+ def write_shard(path, arr):
29
+ h = np.zeros(256, dtype=np.int32); h[0] = 20240520; h[1] = 1; h[2] = len(arr)
30
+ with open(path, "wb") as f:
31
+ f.write(h.tobytes()); f.write(arr.tobytes())
32
+
33
+ def main():
34
+ tok = Tokenizer.from_file(TOKJSON)
35
+ EOT = tok.token_to_id("<|endoftext|>")
36
+ print(f"EOT={EOT} | shard={SHARD:,} | val 1/{VAL_EVERY} | chunk={CHUNK}", flush=True)
37
+
38
+ buf = np.empty(SHARD + 2_000_000, dtype=np.uint16); tn = 0; sidx = 0
39
+ val = []
40
+ di = 0; total = 0; t0 = time.time()
41
+ chunk = []
42
+
43
+ def flush_chunk():
44
+ nonlocal tn, sidx, di, total
45
+ if not chunk:
46
+ return
47
+ for e in tok.encode_batch(chunk): # rayon -> all cores, single process
48
+ ids = e.ids
49
+ # EOT PREFIX (BOS before each doc) -> matches modded-nanogpt align_to_bos
50
+ if di % VAL_EVERY == 0:
51
+ val.append(EOT); val.extend(ids)
52
+ else:
53
+ buf[tn] = EOT; tn += 1
54
+ m = len(ids)
55
+ buf[tn:tn+m] = ids; tn += m
56
+ if tn >= SHARD:
57
+ write_shard(f"{OUT}/polish_train_{sidx:06d}.bin", buf[:tn])
58
+ total += tn; sidx += 1; tn = 0
59
+ di += 1
60
+ chunk.clear()
61
+ print(f" {di:,} docs | {(total+tn)/1e9:.2f}B train tok | {len(val)/1e6:.1f}M val | {time.time()-t0:.0f}s", flush=True)
62
+
63
+ for s in doc_stream():
64
+ chunk.append(s)
65
+ if len(chunk) >= CHUNK:
66
+ flush_chunk()
67
+ flush_chunk()
68
+ if tn:
69
+ write_shard(f"{OUT}/polish_train_{sidx:06d}.bin", buf[:tn]); total += tn; sidx += 1
70
+ write_shard(f"{OUT}/polish_val_000000.bin", np.array(val, dtype=np.uint16))
71
+ print(f"\nDONE: {sidx} train shards, {total:,} train tok, {len(val):,} val tok | "
72
+ f"{di:,} docs | {time.time()-t0:.0f}s", flush=True)
73
+
74
+ if __name__ == "__main__":
75
+ main()
src/train_bpe.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train a Polish byte-level BPE (32k) on a domain-balanced sample of the corpus,
3
+ then report fertility vs GPT-2 BPE. Runs where the parquet shards live (slayer)."""
4
+ import glob, sys, time
5
+ import pyarrow.parquet as pq
6
+ from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders
7
+
8
+ DATA = "/home/ubuntu/dynaword/data"
9
+ OUT = "/home/ubuntu/dynaword/polish_bpe_32k.json"
10
+ CAP = 220 * 1024 * 1024 # ~220 MB text per source -> balances away the 71% legal skew
11
+ VOCAB = 32768
12
+
13
+ def files():
14
+ return sorted(glob.glob(f"{DATA}/*/*.parquet"))
15
+
16
+ def balanced_texts():
17
+ for f in files():
18
+ src = f.split("/")[-2]; got = 0; done = False
19
+ for batch in pq.ParquetFile(f).iter_batches(columns=["text"], batch_size=1000):
20
+ for x in batch.column("text"):
21
+ s = x.as_py()
22
+ if not s:
23
+ continue
24
+ yield s
25
+ got += len(s)
26
+ if got >= CAP:
27
+ done = True; break
28
+ if done:
29
+ break
30
+ print(f" sampled {src}: ~{got/1e6:.0f} MB", file=sys.stderr, flush=True)
31
+
32
+ t0 = time.time()
33
+ tok = Tokenizer(models.BPE(unk_token=None))
34
+ tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
35
+ tok.decoder = decoders.ByteLevel()
36
+ trainer = trainers.BpeTrainer(
37
+ vocab_size=VOCAB, min_frequency=2,
38
+ special_tokens=["<|endoftext|>"],
39
+ initial_alphabet=pre_tokenizers.ByteLevel.alphabet())
40
+ print("training BPE...", file=sys.stderr, flush=True)
41
+ tok.train_from_iterator(balanced_texts(), trainer=trainer)
42
+ tok.save(OUT)
43
+ print(f"trained in {time.time()-t0:.0f}s | vocab={tok.get_vocab_size()} | saved {OUT}")
44
+
45
+ # fertility vs GPT-2 on a held-out-ish sample (later docs of wikipedia, general domain)
46
+ import tiktoken
47
+ gpt2 = tiktoken.get_encoding("gpt2")
48
+ sample = []
49
+ for b in pq.ParquetFile(f"{DATA}/wikipedia/wikipedia.parquet").iter_batches(columns=["text"], batch_size=1000):
50
+ for x in b.column("text"):
51
+ sample.append(x.as_py())
52
+ if len(sample) >= 6000:
53
+ break
54
+ sample = sample[4000:6000] # avoid the head used in training
55
+ words = sum(len(s.split()) for s in sample)
56
+ chars = sum(len(s) for s in sample)
57
+ ours = sum(len(e.ids) for e in tok.encode_batch(sample))
58
+ g2 = sum(len(x) for x in gpt2.encode_ordinary_batch(sample))
59
+ print(f"\nFertility on {len(sample)} held-out PL docs ({words:,} words):")
60
+ print(f" polish-32k : {ours/words:.3f} tok/word | {ours/chars:.3f} tok/char")
61
+ print(f" gpt2-50k : {g2/words:.3f} tok/word | {g2/chars:.3f} tok/char")
62
+ print(f" -> {g2/ours:.2f}x fewer tokens with the Polish BPE")