feat(data): add wiktionary_examples (8.6k docs / 1.12M tok)

#14
data/wiktionary_examples/wiktionary_examples.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wiktionary_examples
2
+
3
+ Polish Wiktionary usage examples
4
+
5
+ ## Dataset description
6
+ - **Source (upstream):** https://dumps.wikimedia.org/plwiktionary/latest/
7
+ - **Domain:** lexicographic
8
+ - **Language:** Polish (pl)
9
+ - **License:** `CC-BY-SA-3.0`
10
+ - **Created (range):** 2004-03-22, 2026-08-15
11
+ - **Added:** 2026-07-19
12
+
13
+ ## Licensing — traceable basis
14
+ Wikimedia dumps explicitly released under CC-BY-SA 3.0; attribution to contributors + share-alike preserved. Derived subset: usage-example sections from Polish-language entries only, grouped one document per headword.
15
+
16
+ ## Provenance
17
+ Parsed directly from the official Wikimedia dump (plwiktionary-latest-pages-articles.xml.bz2); not routed through SpeakLeash. Usage-example sections of Polish-language entries extracted and grouped one document per headword.
18
+
19
+ ## Statistics
20
+ | documents | characters | tokens (tiktoken proxy) |
21
+ |---:|---:|---:|
22
+ | 8,639 | 2,889,761 | 1,115,820 |
23
+
24
+
25
+ ## Per-document license metadata
26
+ | license | documents |
27
+ |---|---:|
28
+ | `CC-BY-SA-3.0` | 8,639 |
29
+
30
+ Author metadata present for **8,639** documents. Empty values mean the upstream record did not expose a machine-readable author field.
31
+
32
+ ## Filters applied (build_dynaword.py)
33
+ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
34
+ - drop documents < 200 chars: **0**
35
+ - drop non-Polish (diacritic ratio): **0**
36
+ - exact cross-source dedup (sha1): **481**
37
+ - OCR alpha-ratio < 0.70 (OCR sources only): **0**
38
+ - read 9,120 → kept 8,639
39
+
40
+ Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
41
+ Llama-3 count is computed at release.
data/wiktionary_examples/wiktionary_examples.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:633427b261c1ae7524be43e5b0ecfbf673596ab6250a86a1304d69c975f0bd0d
3
+ size 1646449
data/wiktionary_examples/wiktionary_examples.stats.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 9120,
3
+ "kept": 8639,
4
+ "drop_short": 0,
5
+ "drop_lang": 0,
6
+ "drop_dup": 481,
7
+ "drop_ocr": 0,
8
+ "chars": 2889761,
9
+ "tokens": 1115820,
10
+ "licenses": {
11
+ "CC-BY-SA-3.0": 8639
12
+ },
13
+ "authors_with_value": 8639,
14
+ "secs": 2.9,
15
+ "license": "CC-BY-SA-3.0"
16
+ }
src/fetch_wiktionary_examples.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the `wiktionary_examples` source from the official Polish Wiktionary dump.
3
+
4
+ Extracts usage-example sections (`{{przykłady}}`) from Polish-language entries
5
+ of pl.wiktionary.org and emits a `.jsonl.zst` file in the format expected by
6
+ `src/build_dynaword.py` (fields: text / license / author).
7
+
8
+ Unlike most sources in this registry, this one is NOT routed through
9
+ SpeakLeash's redistribution — it is parsed directly from the Wikimedia dump.
10
+ The `provenance` field in sources.py records this.
11
+
12
+ One document = one headword; all its example sentences are concatenated,
13
+ newline-separated, in source order. Citation attribution found in
14
+ `{{źródło|...}}` templates is stripped from the text and written to a
15
+ side-car file for auditing (not part of the corpus).
16
+
17
+ Only the standard library is required for parsing; `zstandard` is used for
18
+ output compression (falls back to plain .jsonl with a warning).
19
+
20
+ Usage:
21
+ # download the dump yourself, then:
22
+ python3 src/fetch_wiktionary_examples.py \
23
+ --dump plwiktionary-latest-pages-articles.xml.bz2 \
24
+
25
+
26
+ # dump URL:
27
+ # https://dumps.wikimedia.org/plwiktionary/latest/plwiktionary-latest-pages-articles.xml.bz2
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import bz2
33
+ import html
34
+ import json
35
+ import re
36
+ import sys
37
+ from pathlib import Path
38
+ from xml.etree import ElementTree as ET
39
+
40
+ SOURCE_NAME = "wiktionary_examples"
41
+ LICENSE = "CC-BY-SA-3.0"
42
+ AUTHOR = "Wikimedia contributors"
43
+
44
+ # Gates mirrored from build_dynaword.py so the preview count matches the build.
45
+ MIN_CHARS = 200
46
+ MIN_EXAMPLE_CHARS = 10
47
+
48
+ # `== <headword> ({{język polski}}) ==` opens the Polish section of an entry.
49
+ PL_HEADING = re.compile(r"^==\s*(.+?)\s*\(\{\{język polski\}\}\)\s*==\s*$", re.M)
50
+ NEXT_HEADING = re.compile(r"^==[^=]", re.M)
51
+
52
+ # Blocks run until the next top-level `{{template}}` marker.
53
+ EXAMPLES_BLOCK = re.compile(
54
+ r"\{\{przykłady\}\}(.*?)(?=\{\{[a-ząćęłńóśźż]+\}\}|\Z)", re.S
55
+ )
56
+ # Numbered lines: `: (1.1) <sentence>`
57
+ NUMBERED_LINE = re.compile(r"^:\s*\(([\d.]+)\)\s*(.+?)\s*$", re.M)
58
+ SENSE_NUMBER = re.compile(r"\(\d+\.\d+\)")
59
+
60
+ CITATION_FIELDS = ("autor", "tytuł", "tytul", "rozdział", "rozdzial", "rok", "isbn")
61
+
62
+
63
+ def split_templates(text: str) -> tuple[str, list[str]]:
64
+ """Remove `{{...}}` spans, counting braces so nested templates are handled.
65
+
66
+ A regex cannot do this correctly: `{{źródło|tytuł={{...}}}}` occurs in the
67
+ dump and a non-greedy match closes at the wrong brace pair.
68
+ """
69
+ kept: list[str] = []
70
+ removed: list[str] = []
71
+ i = 0
72
+ while i < len(text):
73
+ if text.startswith("{{", i):
74
+ depth, j = 0, i
75
+ while j < len(text):
76
+ if text.startswith("{{", j):
77
+ depth += 1
78
+ j += 2
79
+ elif text.startswith("}}", j):
80
+ depth -= 1
81
+ j += 2
82
+ if depth == 0:
83
+ break
84
+ else:
85
+ j += 1
86
+ removed.append(text[i:j])
87
+ i = j
88
+ else:
89
+ kept.append(text[i])
90
+ i += 1
91
+ return "".join(kept), removed
92
+
93
+
94
+ def describe_citation(template: str) -> str:
95
+ """Flatten a `{{źródło|autor=…|tytuł=…}}` template into a readable string."""
96
+ fields: dict[str, str] = {}
97
+ for chunk in template.strip("{}").split("|")[1:]:
98
+ if "=" in chunk:
99
+ key, value = chunk.split("=", 1)
100
+ fields[key.strip().lower()] = value.strip()
101
+ parts = [fields[k] for k in CITATION_FIELDS if fields.get(k)]
102
+ return " | ".join(parts)
103
+
104
+
105
+ def unlink(text: str) -> str:
106
+ """`[[target|label]]` -> label, `[[word]]` -> word, external links -> label."""
107
+ for _ in range(5):
108
+ stripped = re.sub(r"\[\[([^\[\]|]*)\|(.*?)\]\]", r"\2", text)
109
+ stripped = re.sub(r"\[\[([^\[\]|]+?)\]\]", r"\1", stripped)
110
+ if stripped == text:
111
+ break
112
+ text = stripped
113
+ # Safety net for malformed nesting, e.g. `[[zaskoczyć|zaskoczył[y]]]`.
114
+ text = re.sub(r"\[\[[^\[\]]*?\|", "[[", text)
115
+ text = text.replace("[[", "").replace("]]", "")
116
+ text = re.sub(r"\[https?://\S+\s+([^\]]+)\]", r"\1", text)
117
+ text = re.sub(r"\[https?://\S+\]", "", text)
118
+ text = re.sub(r"https?://\S+", "", text)
119
+ return text
120
+
121
+
122
+ def clean(text: str) -> str:
123
+ """Strip wiki and HTML markup. Square brackets are kept deliberately:
124
+ `[…]` marks an omission and `[= gloss]` an editorial insertion — both are
125
+ philological convention inside quotations, not markup residue."""
126
+ text = re.sub(r"<ref[^>]*>.*?</ref>", "", text, flags=re.S)
127
+ text = re.sub(r"<ref[^>]*/>", "", text)
128
+ text = re.sub(r"<[^>]+>", "", text)
129
+ text = unlink(text)
130
+ text = re.sub(r"'{2,}", "", text)
131
+ text = html.unescape(html.unescape(text)) # some entities are double-encoded
132
+ text = text.replace("\u00a0", " ")
133
+ text = SENSE_NUMBER.sub("", text)
134
+ text = re.sub(r"\s+", " ", text)
135
+ return text.strip(" -–—•\t")
136
+
137
+
138
+ def polish_section(wikitext: str) -> tuple[str, str] | None:
139
+ match = PL_HEADING.search(wikitext)
140
+ if not match:
141
+ return None
142
+ headword = match.group(1).strip()
143
+ rest = wikitext[match.end():]
144
+ end = NEXT_HEADING.search(rest)
145
+ if end:
146
+ rest = rest[: end.start()]
147
+ return headword, rest
148
+
149
+
150
+ def examples_and_citations(section: str) -> tuple[list[str], list[str]]:
151
+ match = EXAMPLES_BLOCK.search(section)
152
+ if not match:
153
+ return [], []
154
+ examples, citations = [], []
155
+ for _, raw in NUMBERED_LINE.findall(match.group(1)):
156
+ without_templates, templates = split_templates(raw)
157
+ for template in templates:
158
+ if template.startswith(("{{źródło", "{{zrodlo")):
159
+ described = describe_citation(clean(template))
160
+ if described:
161
+ citations.append(described)
162
+ sentence = clean(without_templates)
163
+ if len(sentence) >= MIN_EXAMPLE_CHARS:
164
+ examples.append(sentence)
165
+ return examples, sorted(set(citations))
166
+
167
+
168
+ def iter_pages(dump_path: Path):
169
+ """Yield (namespace, wikitext) for every page, streaming the bz2 dump."""
170
+ with bz2.open(dump_path, "rb") as handle:
171
+ for _, element in ET.iterparse(handle, events=("end",)):
172
+ if element.tag.rsplit("}", 1)[-1] != "page":
173
+ continue
174
+ values = {}
175
+ for child in element.iter():
176
+ tag = child.tag.rsplit("}", 1)[-1]
177
+ if tag in ("ns", "text") and tag not in values:
178
+ values[tag] = child.text
179
+ yield (values.get("ns") or "").strip(), values.get("text") or ""
180
+ element.clear()
181
+
182
+
183
+ def main() -> None:
184
+ parser = argparse.ArgumentParser(description=__doc__)
185
+ parser.add_argument("--dump", required=True,
186
+ help="plwiktionary-latest-pages-articles.xml.bz2")
187
+ parser.add_argument("--out", default=".",
188
+ help="directory to write <source>.jsonl.zst into")
189
+ parser.add_argument("--min-chars", type=int, default=MIN_CHARS,
190
+ help=f"document length gate (default {MIN_CHARS}, "
191
+ "matching build_dynaword.py)")
192
+ args = parser.parse_args()
193
+
194
+ dump_path = Path(args.dump).expanduser()
195
+ if not dump_path.exists():
196
+ sys.exit(f"dump not found: {dump_path}")
197
+ out_dir = Path(args.out).expanduser()
198
+ out_dir.mkdir(parents=True, exist_ok=True)
199
+
200
+ pages = entries = with_examples = with_citations = 0
201
+ documents: list[tuple[str, str]] = []
202
+ citation_index: list[dict] = []
203
+
204
+ for namespace, wikitext in iter_pages(dump_path):
205
+ pages += 1
206
+ if pages % 100_000 == 0:
207
+ print(f" {pages:,} pages scanned, {entries:,} Polish entries",
208
+ flush=True)
209
+ if namespace != "0":
210
+ continue
211
+ section = polish_section(wikitext)
212
+ if section is None:
213
+ continue
214
+ entries += 1
215
+ headword, body = section
216
+ examples, citations = examples_and_citations(body)
217
+ if not examples:
218
+ continue
219
+ with_examples += 1
220
+ if citations:
221
+ with_citations += 1
222
+ citation_index.append({"headword": headword, "citations": citations})
223
+ documents.append((headword, "\n".join(examples)))
224
+
225
+ kept = [(h, t) for h, t in documents if len(t) >= args.min_chars]
226
+ chars = sum(len(t) for _, t in kept)
227
+
228
+ print()
229
+ print(f"pages scanned: {pages:,}")
230
+ print(f"Polish entries: {entries:,}")
231
+ print(f"entries with examples: {with_examples:,}")
232
+ print(f"entries with attribution: {with_citations:,}")
233
+ print(f"documents >= {args.min_chars} chars: {len(kept):,}")
234
+ print(f"characters: {chars:,}")
235
+
236
+ payload = "\n".join(
237
+ json.dumps({"text": text, "license": LICENSE, "author": AUTHOR},
238
+ ensure_ascii=False)
239
+ for _, text in kept
240
+ ) + "\n"
241
+
242
+ plain = out_dir / f"{SOURCE_NAME}.jsonl"
243
+ plain.write_text(payload, encoding="utf-8")
244
+
245
+ try:
246
+ import zstandard as zstd
247
+ except ImportError:
248
+ print(f"\nwrote {plain} — install `zstandard` (or run `zstd {plain.name}`) "
249
+ "to produce the .jsonl.zst the build expects")
250
+ else:
251
+ compressed = out_dir / f"{SOURCE_NAME}.jsonl.zst"
252
+ compressed.write_bytes(zstd.ZstdCompressor(level=10).compress(
253
+ payload.encode("utf-8")))
254
+ plain.unlink()
255
+ print(f"\nwrote {compressed}")
256
+
257
+ audit = out_dir / f"{SOURCE_NAME}.citations.jsonl"
258
+ audit.write_text(
259
+ "\n".join(json.dumps(row, ensure_ascii=False) for row in citation_index) + "\n",
260
+ encoding="utf-8",
261
+ )
262
+ print(f"wrote {audit} (attribution audit trail, not part of the corpus)")
263
+ print()
264
+ print(f"next: python3 src/build_dynaword.py --sources {SOURCE_NAME} "
265
+ f"--speakleash-dir {out_dir} --out .")
266
+
267
+
268
+ if __name__ == "__main__":
269
+ main()
src/sources.py CHANGED
@@ -39,6 +39,24 @@ SOURCES = {
39
  "created": "2005-01-01, 2026-06-14",
40
  "is_ocr": False,
41
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  "eurlex": {
43
  "speakleash_key": "eurlex_corpus",
44
  "pretty": "EUR-Lex (EU legal acts, Polish)",
 
39
  "created": "2005-01-01, 2026-06-14",
40
  "is_ocr": False,
41
  },
42
+ "wiktionary_examples": {
43
+ "file_key": "wiktionary_examples",
44
+ "pretty": "Polish Wiktionary usage examples",
45
+ "provenance": "Parsed directly from the official Wikimedia dump "
46
+ "(plwiktionary-latest-pages-articles.xml.bz2); not routed "
47
+ "through SpeakLeash. Usage-example sections of Polish-language "
48
+ "entries extracted and grouped one document per headword.",
49
+ "license": "CC-BY-SA-3.0",
50
+ "license_spdx": "CC-BY-SA-3.0",
51
+ "traceable": "Wikimedia dumps explicitly released under CC-BY-SA 3.0; "
52
+ "attribution to contributors + share-alike preserved. "
53
+ "Derived subset: usage-example sections from Polish-language "
54
+ "entries only, grouped one document per headword.",
55
+ "upstream": "https://dumps.wikimedia.org/plwiktionary/latest/",
56
+ "domain": "lexicographic",
57
+ "created": "2004-03-22, 2026-08-15",
58
+ "is_ocr": False,
59
+ },
60
  "eurlex": {
61
  "speakleash_key": "eurlex_corpus",
62
  "pretty": "EUR-Lex (EU legal acts, Polish)",