File size: 9,973 Bytes
85e7d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
"""Build the `wiktionary_examples` source from the official Polish Wiktionary dump.

Extracts usage-example sections (`{{przykłady}}`) from Polish-language entries
of pl.wiktionary.org and emits a `.jsonl.zst` file in the format expected by
`src/build_dynaword.py` (fields: text / license / author).

Unlike most sources in this registry, this one is NOT routed through
SpeakLeash's redistribution — it is parsed directly from the Wikimedia dump.
The `provenance` field in sources.py records this.

One document = one headword; all its example sentences are concatenated,
newline-separated, in source order. Citation attribution found in
`{{źródło|...}}` templates is stripped from the text and written to a
side-car file for auditing (not part of the corpus).

Only the standard library is required for parsing; `zstandard` is used for
output compression (falls back to plain .jsonl with a warning).

Usage:
  # download the dump yourself, then:
  python3 src/fetch_wiktionary_examples.py \
      --dump plwiktionary-latest-pages-articles.xml.bz2 \
      

  # dump URL:
  # https://dumps.wikimedia.org/plwiktionary/latest/plwiktionary-latest-pages-articles.xml.bz2
"""
from __future__ import annotations

import argparse
import bz2
import html
import json
import re
import sys
from pathlib import Path
from xml.etree import ElementTree as ET

SOURCE_NAME = "wiktionary_examples"
LICENSE = "CC-BY-SA-3.0"
AUTHOR = "Wikimedia contributors"

# Gates mirrored from build_dynaword.py so the preview count matches the build.
MIN_CHARS = 200
MIN_EXAMPLE_CHARS = 10

# `== <headword> ({{język polski}}) ==` opens the Polish section of an entry.
PL_HEADING = re.compile(r"^==\s*(.+?)\s*\(\{\{język polski\}\}\)\s*==\s*$", re.M)
NEXT_HEADING = re.compile(r"^==[^=]", re.M)

# Blocks run until the next top-level `{{template}}` marker.
EXAMPLES_BLOCK = re.compile(
    r"\{\{przykłady\}\}(.*?)(?=\{\{[a-ząćęłńóśźż]+\}\}|\Z)", re.S
)
# Numbered lines: `: (1.1) <sentence>`
NUMBERED_LINE = re.compile(r"^:\s*\(([\d.]+)\)\s*(.+?)\s*$", re.M)
SENSE_NUMBER = re.compile(r"\(\d+\.\d+\)")

CITATION_FIELDS = ("autor", "tytuł", "tytul", "rozdział", "rozdzial", "rok", "isbn")


def split_templates(text: str) -> tuple[str, list[str]]:
    """Remove `{{...}}` spans, counting braces so nested templates are handled.

    A regex cannot do this correctly: `{{źródło|tytuł={{...}}}}` occurs in the
    dump and a non-greedy match closes at the wrong brace pair.
    """
    kept: list[str] = []
    removed: list[str] = []
    i = 0
    while i < len(text):
        if text.startswith("{{", i):
            depth, j = 0, i
            while j < len(text):
                if text.startswith("{{", j):
                    depth += 1
                    j += 2
                elif text.startswith("}}", j):
                    depth -= 1
                    j += 2
                    if depth == 0:
                        break
                else:
                    j += 1
            removed.append(text[i:j])
            i = j
        else:
            kept.append(text[i])
            i += 1
    return "".join(kept), removed


def describe_citation(template: str) -> str:
    """Flatten a `{{źródło|autor=…|tytuł=…}}` template into a readable string."""
    fields: dict[str, str] = {}
    for chunk in template.strip("{}").split("|")[1:]:
        if "=" in chunk:
            key, value = chunk.split("=", 1)
            fields[key.strip().lower()] = value.strip()
    parts = [fields[k] for k in CITATION_FIELDS if fields.get(k)]
    return " | ".join(parts)


def unlink(text: str) -> str:
    """`[[target|label]]` -> label, `[[word]]` -> word, external links -> label."""
    for _ in range(5):
        stripped = re.sub(r"\[\[([^\[\]|]*)\|(.*?)\]\]", r"\2", text)
        stripped = re.sub(r"\[\[([^\[\]|]+?)\]\]", r"\1", stripped)
        if stripped == text:
            break
        text = stripped
    # Safety net for malformed nesting, e.g. `[[zaskoczyć|zaskoczył[y]]]`.
    text = re.sub(r"\[\[[^\[\]]*?\|", "[[", text)
    text = text.replace("[[", "").replace("]]", "")
    text = re.sub(r"\[https?://\S+\s+([^\]]+)\]", r"\1", text)
    text = re.sub(r"\[https?://\S+\]", "", text)
    text = re.sub(r"https?://\S+", "", text)
    return text


def clean(text: str) -> str:
    """Strip wiki and HTML markup. Square brackets are kept deliberately:
    `[…]` marks an omission and `[= gloss]` an editorial insertion — both are
    philological convention inside quotations, not markup residue."""
    text = re.sub(r"<ref[^>]*>.*?</ref>", "", text, flags=re.S)
    text = re.sub(r"<ref[^>]*/>", "", text)
    text = re.sub(r"<[^>]+>", "", text)
    text = unlink(text)
    text = re.sub(r"'{2,}", "", text)
    text = html.unescape(html.unescape(text))   # some entities are double-encoded
    text = text.replace("\u00a0", " ")
    text = SENSE_NUMBER.sub("", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip(" -–—•\t")


def polish_section(wikitext: str) -> tuple[str, str] | None:
    match = PL_HEADING.search(wikitext)
    if not match:
        return None
    headword = match.group(1).strip()
    rest = wikitext[match.end():]
    end = NEXT_HEADING.search(rest)
    if end:
        rest = rest[: end.start()]
    return headword, rest


def examples_and_citations(section: str) -> tuple[list[str], list[str]]:
    match = EXAMPLES_BLOCK.search(section)
    if not match:
        return [], []
    examples, citations = [], []
    for _, raw in NUMBERED_LINE.findall(match.group(1)):
        without_templates, templates = split_templates(raw)
        for template in templates:
            if template.startswith(("{{źródło", "{{zrodlo")):
                described = describe_citation(clean(template))
                if described:
                    citations.append(described)
        sentence = clean(without_templates)
        if len(sentence) >= MIN_EXAMPLE_CHARS:
            examples.append(sentence)
    return examples, sorted(set(citations))


def iter_pages(dump_path: Path):
    """Yield (namespace, wikitext) for every page, streaming the bz2 dump."""
    with bz2.open(dump_path, "rb") as handle:
        for _, element in ET.iterparse(handle, events=("end",)):
            if element.tag.rsplit("}", 1)[-1] != "page":
                continue
            values = {}
            for child in element.iter():
                tag = child.tag.rsplit("}", 1)[-1]
                if tag in ("ns", "text") and tag not in values:
                    values[tag] = child.text
            yield (values.get("ns") or "").strip(), values.get("text") or ""
            element.clear()


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dump", required=True,
                        help="plwiktionary-latest-pages-articles.xml.bz2")
    parser.add_argument("--out", default=".",
                        help="directory to write <source>.jsonl.zst into")
    parser.add_argument("--min-chars", type=int, default=MIN_CHARS,
                        help=f"document length gate (default {MIN_CHARS}, "
                             "matching build_dynaword.py)")
    args = parser.parse_args()

    dump_path = Path(args.dump).expanduser()
    if not dump_path.exists():
        sys.exit(f"dump not found: {dump_path}")
    out_dir = Path(args.out).expanduser()
    out_dir.mkdir(parents=True, exist_ok=True)

    pages = entries = with_examples = with_citations = 0
    documents: list[tuple[str, str]] = []
    citation_index: list[dict] = []

    for namespace, wikitext in iter_pages(dump_path):
        pages += 1
        if pages % 100_000 == 0:
            print(f"  {pages:,} pages scanned, {entries:,} Polish entries",
                  flush=True)
        if namespace != "0":
            continue
        section = polish_section(wikitext)
        if section is None:
            continue
        entries += 1
        headword, body = section
        examples, citations = examples_and_citations(body)
        if not examples:
            continue
        with_examples += 1
        if citations:
            with_citations += 1
            citation_index.append({"headword": headword, "citations": citations})
        documents.append((headword, "\n".join(examples)))

    kept = [(h, t) for h, t in documents if len(t) >= args.min_chars]
    chars = sum(len(t) for _, t in kept)

    print()
    print(f"pages scanned:            {pages:,}")
    print(f"Polish entries:           {entries:,}")
    print(f"entries with examples:    {with_examples:,}")
    print(f"entries with attribution: {with_citations:,}")
    print(f"documents >= {args.min_chars} chars:  {len(kept):,}")
    print(f"characters:               {chars:,}")

    payload = "\n".join(
        json.dumps({"text": text, "license": LICENSE, "author": AUTHOR},
                   ensure_ascii=False)
        for _, text in kept
    ) + "\n"

    plain = out_dir / f"{SOURCE_NAME}.jsonl"
    plain.write_text(payload, encoding="utf-8")

    try:
        import zstandard as zstd
    except ImportError:
        print(f"\nwrote {plain} — install `zstandard` (or run `zstd {plain.name}`) "
              "to produce the .jsonl.zst the build expects")
    else:
        compressed = out_dir / f"{SOURCE_NAME}.jsonl.zst"
        compressed.write_bytes(zstd.ZstdCompressor(level=10).compress(
            payload.encode("utf-8")))
        plain.unlink()
        print(f"\nwrote {compressed}")

    audit = out_dir / f"{SOURCE_NAME}.citations.jsonl"
    audit.write_text(
        "\n".join(json.dumps(row, ensure_ascii=False) for row in citation_index) + "\n",
        encoding="utf-8",
    )
    print(f"wrote {audit} (attribution audit trail, not part of the corpus)")
    print()
    print(f"next: python3 src/build_dynaword.py --sources {SOURCE_NAME} "
          f"--speakleash-dir {out_dir} --out .")


if __name__ == "__main__":
    main()