polish-dynaword / src /fetch_wiktionary_examples.py
ppuzio's picture
claude opus 5.5
kacperwikiel's picture
claude opus 5.5
PiotrSty's picture Maggio33's picture dawidmajewski's picture KateMajzel's picture bartoszkobylinski1's picture 1am's picture
Squash history: withdraw the Sejm's interpellations from parliamentary until v0.2.7
81fafcb
Raw History Blame
21.2 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; 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).
Each row and example is then labelled CC BY-SA 3.0, 4.0 or both by the date of
the contribution that added it (v2#110); see `relabel`.
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
# after build_dynaword.py, label by contribution date (a rebuild must be relabelled);
# TITLES holds the released rows' page titles, one per line (the end of `author`):
python3 src/wiki_history.py download --dump plwiktionary --out OUT
python3 src/wiki_history.py scan --stub OUT/plwiktionary-20261001-stub-meta-history.xml.gz \
--titles wiktionary_examples=TITLES --out OUT
python3 src/wiki_history.py fetch --source wiktionary_examples --every-pre \
--history OUT/wiktionary_examples.history.jsonl --out OUT
python3 src/wiki_history.py compare --source wiktionary_examples \
--history OUT/wiktionary_examples.history.jsonl --fetched OUT/wiktionary_examples \
--parquet data/wiktionary_examples/wiktionary_examples.parquet \
--out OUT/wiktionary_examples.labels.jsonl
python3 src/fetch_wiktionary_examples.py --relabel OUT
"""
from __future__ import annotations
import argparse
import bz2
from collections import Counter
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), the
# label the dump build gives every row; `relabel` then gives each the licence of its
# contributions (3.0 before 2023-06-07, wiki_history.WIKIS).
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 relabel(out: Path, data_dir: Path) -> None:
"""Label each released row by contribution date (v2#110) from out/<source>.labels.jsonl
(wiki_history.py compare): an example the page's last revision before the cutoff already
had, verbatim or shortened since, keeps CC BY-SA 3.0; one resembling an example there was
edited after it and carries both licences; any other is 4.0. A row holding examples with
different labels carries both. Rewrites in place the parquet `license` column, the sidecar
<source>.attribution.jsonl (per row: title and URL, label, `license_basis`, `pre_cutoff_revid`,
`example_licenses`, one per line of the text, and wiki_history.record_links), stats `licenses` and `license`, and the
licence evidence's `release_scope` labels, tokens and example labels and `licence_labels`
(the stub dump of out/, cases). Text, ids and every other column are unchanged; rerunning
changes nothing."""
import hashlib
import pyarrow as pa
import pyarrow.parquet as pq
from sources import SOURCES
from wiki_history import EDIT_RATIO, STUB_DATE, WIKIS, record_links
def path(name):
return data_dir / f"{SOURCE_NAME}.{name}"
def load(p):
return json.loads(p.read_text(encoding="utf-8"))
cfg = WIKIS[SOURCE_NAME]
labels = [json.loads(line) for line in (out / f"{SOURCE_NAME}.labels.jsonl").open(encoding="utf-8")]
table = pq.read_table(path("parquet"))
if [lab["id"] for lab in labels] != table["id"].to_pylist():
raise ValueError("labels are not the parquet rows in order")
for lab, text, author in zip(labels, table["text"].to_pylist(), table["author"].to_pylist()):
if len(lab["example_licenses"]) != text.count("\n") + 1:
raise ValueError(f"{lab['id']}: {len(lab['example_licenses'])} labels for {text.count(chr(10)) + 1} examples")
if credit(lab["title"]) != author: # the stub's title is the page the row was built from
raise ValueError(f"{lab['id']}: titled {lab['title']!r} in the stub, credited {author!r}")
groups = pq.ParquetFile(path("parquet")).metadata.row_group(0).num_rows # build_dynaword's batches, kept
table = table.set_column(table.column_names.index("license"), "license",
pa.array([lab["license"] for lab in labels], pa.string()))
pq.write_table(table, path("parquet"), compression="zstd", row_group_size=groups)
side = [{"id": lab["id"], "pageid": lab["pageid"], "title": lab["title"], "url": page_url(lab["title"]),
"license": lab["license"], "license_basis": lab["case"],
"pre_cutoff_revid": lab["pre_revid"], "pre_cutoff_at": lab["pre_at"],
"example_licenses": lab["example_licenses"],
**record_links(SOURCE_NAME, lab["pageid"], lab["shipped_revid"], lab["license"])} for lab in labels]
sidecar = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in side)
path("attribution.jsonl").write_text(sidecar, encoding="utf-8")
docs, tokens = Counter(), Counter()
for lab, tok in zip(labels, table["token_count"].to_pylist()):
docs[lab["license"]] += 1
tokens[lab["license"]] += tok
docs, tokens = dict(sorted(docs.items())), dict(sorted(tokens.items()))
stats = load(path("stats.json"))
stats.update(licenses=docs, license=SOURCES[SOURCE_NAME]["license"])
path("stats.json").write_text(json.dumps(stats, indent=2)) # build_dynaword's format
ev = load(path("license-evidence.json"))
ev["release_scope"].update(
labels=docs, tokens=tokens,
example_labels=dict(sorted(Counter(e for lab in labels for e in lab["example_licenses"]).items())))
ev["licence_labels"] = {
"cutoff": cfg["cutoff"], "before": cfg["before"], "after": cfg["after"], "edit_ratio": EDIT_RATIO,
"stub": load(out / f"{cfg['dump']}-{STUB_DATE}-stub-meta-history.xml.gz.json"),
"cases": dict(sorted(Counter(lab["case"] for lab in labels).items())),
"sidecar": path("attribution.jsonl").name,
"sidecar_sha256": hashlib.sha256(sidecar.encode("utf-8")).hexdigest(),
}
path("license-evidence.json").write_text(json.dumps(ev, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{SOURCE_NAME}: relabelled, {docs}, examples {ev['release_scope']['example_labels']}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
step = parser.add_mutually_exclusive_group(required=True)
step.add_argument("--dump", help="plwiktionary-latest-pages-articles.xml.bz2")
step.add_argument("--relabel", type=Path, metavar="OUT",
help="label the released rows by contribution date from OUT/"
f"{SOURCE_NAME}.labels.jsonl (wiki_history.py compare)")
parser.add_argument("--data", type=Path, default=Path(__file__).resolve().parent.parent / "data" / SOURCE_NAME,
help="the released source, for --relabel")
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()
if args.relabel:
relabel(args.relabel, args.data)
return
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 ., then --relabel (see the module docstring)")
if __name__ == "__main__":
main()