polish-dynaword / src /fetch_wiktionary_examples.py
kacperwikiel's picture
feat(data): add wiktionary_examples (8.6k docs / 1.12M tok) (#14)
85e7d9b
Raw
History Blame Contribute Delete
9.97 kB
#!/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()