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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/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; its example sentences are concatenated,
newline-separated, in source order. A quotation from a third-party work (used
under the Art. 29 quotation right, not licensed CC BY-SA by Wiktionary
contributors) is dropped: a line carrying a `{{źródło|...}}` template or a
`<ref>`, a hand-written source such as "(B. Prus: Lalka)" or "(z Internetu)",
or an omission mark "(…)". Its citation goes 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 urllib.parse import quote
from xml.etree import ElementTree as ET

SOURCE_NAME = "wiktionary_examples"
# pl.wiktionary's footer links CC BY-SA 4.0 (Wikimedia Terms of Use, June 2023).
# Older revisions were contributed under 3.0, whose §4(b) allows an adaptation
# to be licensed under a later version with the same elements.
LICENSE = "CC-BY-SA-4.0"
PAGE_URL = "https://pl.wiktionary.org/wiki/"

# 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 section marker, a `{{template}}` opening a line.
# Inline templates such as `{{tłum}}` or `{{pot}}` inside an example don't end it.
EXAMPLES_BLOCK = re.compile(
    r"\{\{przykłady\}\}(.*?)(?=^\{\{[a-ząćęłńóśźż]+\}\}|\Z)", re.S | re.M
)
# Numbered lines: `: (1.1) <sentence>`
NUMBERED_LINE = re.compile(r"^:\s*\(([\d.]+)\)\s*(.+?)\s*$", re.M)
SENSE_NUMBER = re.compile(r"\(\d+\.\d+\)")

# Fields of {{źródło}} and of the templates used inside <ref>: {{NKJP}}, {{cytuj}},
# {{cytuj stronę}}, {{KJP}}, {{Gloger1900}}.
CITATION_FIELDS = ("autor", "autorzy", "tytuł", "tytul", "tytuł_pub", "rozdział", "rozdzial",
                   "hasło", "rok", "data", "isbn", "url")
CITATION_TEMPLATES = ("{{źródło", "{{zrodlo")
# `<ref>source</ref>`, or `<ref name="x" />` reusing a source given elsewhere on the page.
REF = re.compile(r"<ref\b([^>]*?)(?:/>|>(.*?)</ref\s*>)", re.I | re.S)

# Quotations whose source is written by hand instead of with {{źródło}}, matched
# on the cleaned sentence. Patterns come from a survey of the 20261001 dump.
_UP = "A-ZĄĆĘŁŃÓŚŹŻ"
_LOW = "a-ząćęłńóśźż"
_END = r"[\s.!?…]*$"
ATTRIBUTION_TAILS = (
    # A capital opening a word or an initial: "(B. Prus: Lalka)", "(Adam Mickiewicz)",
    # "(Kogel-mogel)", "(Mt 4:19)", "(W leśniczówce …)". Acronyms and formulas
    # ("(ZSRR)", "(C/kg)") don't match.
    # ponytail: also drops a few glosses like "(Alligator missisippiensis)";
    # losing a sentence is cheaper than shipping a quotation.
    re.compile(rf"\(\s*[\"„“]?[{_UP}](?:[{_LOW}]|\.|\s)[^()]*\){_END}"),
    # "(z Internetu)", "(z Wikipedii)", "(z Odysei)": "from <source>".
    re.compile(rf"\(\s*z\s+[{_UP}{_LOW}][{_LOW}]*\){_END}", re.I),
    re.compile(rf"\(\s*(?:źródło|wywiad|tytuł|słowa|cytat|za:)[^()]*\){_END}", re.I),
    # Unparenthesised tag after the sentence: "…Gałczyńskiego. Internet".
    re.compile(rf"(?<=[.!?…\]”\"])\s*(?:z\s+)?(?:internet\w*|wikipedi\w*){_END}", re.I),
)
# "(…)" / "[...]" mark an omission: the line was cut from someone else's text.
EXCERPT_MARK = re.compile(r"[(\[]\s*(?:…|\.\.\.)\s*[)\]]")


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; the
    template's name when it has none of CITATION_FIELDS (e.g. `{{zWikiprojektu|…}}`)."""
    name, *chunks = template.strip("{}").split("|")
    fields: dict[str, str] = {}
    for chunk in chunks:
        if "=" in chunk:
            key, value = chunk.split("=", 1)
            key = key.strip().lower()
            # clean() would delete a bare URL, which is the whole point of `url`.
            fields[key] = value.strip() if key == "url" else clean(value)
    parts = [fields[k] for k in CITATION_FIELDS if fields.get(k)]
    return " | ".join(parts) or "{{" + name.strip() + "}}"


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"<br\s*/?>", " ", text, flags=re.I)   # a line break separates words
    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)   # left behind by a stripped template
    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 is_cited(raw: str, templates: list[str]) -> bool:
    """A line with a source attached is a quotation from a third-party work (Art. 29
    quotation right), not a contributor's own CC BY-SA text."""
    return "<ref" in raw.lower() or any(t.startswith(CITATION_TEMPLATES) for t in templates)


def cited_sources(raw: str, templates: list[str]) -> list[str]:
    """The sources a cited line gives, for the audit side-car."""
    sources = [describe_citation(t) for t in templates if t.startswith(CITATION_TEMPLATES)]
    for ref in REF.finditer(raw):
        attributes, body = ref.groups()
        if body is None:
            sources.append(f"<ref{attributes.rstrip()}/>")
            continue
        text, inner = split_templates(body)
        # {{źródło}} inside a <ref> is already in `templates`.
        sources += [describe_citation(t) for t in inner if not t.startswith(CITATION_TEMPLATES)]
        sources.append(clean(text))
    return [source for source in sources if source]


def hand_attribution(sentence: str) -> str | None:
    """The source a quotation names without {{źródło}}, or "(…)" for an excerpt
    that names none; None for a contributor's own example."""
    for pattern in ATTRIBUTION_TAILS:
        match = pattern.search(sentence)
        if match:
            return match.group(0).strip(" .!?…")
    match = EXCERPT_MARK.search(sentence)
    return match.group(0) if match else None


def examples_and_citations(section: str) -> tuple[list[str], list[str], int]:
    """(example sentences, citations of the dropped quotations, number of dropped lines).

    A line is a quotation when it carries {{źródło}}/<ref> or a hand-written
    source (see hand_attribution)."""
    match = EXAMPLES_BLOCK.search(section)
    if not match:
        return [], [], 0
    examples, citations, dropped = [], [], 0
    for _, raw in NUMBERED_LINE.findall(match.group(1)):
        without_templates, templates = split_templates(raw)
        if is_cited(raw, templates):
            dropped += 1
            citations.extend(cited_sources(raw, templates) or ["(no source text)"])
            continue
        sentence = clean(without_templates)
        attribution = hand_attribution(sentence)
        if attribution:
            dropped += 1
            citations.append(attribution)
            continue
        if len(sentence) >= MIN_EXAMPLE_CHARS:
            examples.append(sentence)
    return examples, sorted(set(citations)), dropped


def page_url(title: str) -> str:
    return PAGE_URL + quote(title.replace(" ", "_"), safe="/:()',!")


def credit(title: str) -> str:
    """BY-SA 4.0 §3(a)(2) allows attribution by a URI; the page history lists the authors."""
    return f"Wikisłownik contributors, {page_url(title)}"


def iter_pages(dump_path: Path):
    """Yield (namespace, page id, title, 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]
                # The page's own <id> precedes its revision's <id>.
                if tag in ("ns", "id", "title", "text") and tag not in values:
                    values[tag] = child.text
            yield ((values.get("ns") or "").strip(), (values.get("id") or "").strip(),
                   values.get("title") or "", 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 = quoted_lines = example_lines = 0
    documents: list[dict] = []
    citation_index: list[dict] = []

    for namespace, page_id, title, 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, dropped = examples_and_citations(body)
        quoted_lines += dropped
        if citations:
            with_citations += 1
            citation_index.append({"id": f"{SOURCE_NAME}_{page_id}", "headword": headword,
                                   "citations": citations})
        if not examples:
            continue
        with_examples += 1
        example_lines += len(examples)
        documents.append({"id": f"{SOURCE_NAME}_{page_id}", "text": "\n".join(examples),
                          "license": LICENSE, "author": credit(title)})

    kept = [d for d in documents if len(d["text"]) >= args.min_chars]
    chars = sum(len(d["text"]) for d 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"quoted lines dropped:     {quoted_lines:,}")
    print(f"example lines kept:       {example_lines:,}")
    print(f"documents >= {args.min_chars} chars:  {len(kept):,}")
    print(f"characters:               {chars:,}")

    payload = "\n".join(
        json.dumps(document, ensure_ascii=False) for document 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()