polish-dynaword / src /fetch_wikipedia.py
ppuzio's picture
wikinews: label each page CC BY 2.5 or 4.0 by its last revision (v0.2.6, v2#57) (#77)
312a6c4
Raw History Blame
19.1 kB
#!/usr/bin/env python3
"""Polish Wikipedia articles (ns 0) from the official plwiki dump, licence per record.
Replaces the SpeakLeash `plwiki` snapshot (v0.2.6 rights audit,
slayerlabs/polish-dynaword-v2#69). The dump date is pinned; every shard is
checked against the sha1 in dumpstatus.json and in the dump's sha1sums.txt.
B=<build dir, never committed>
python3 src/fetch_wikipedia.py discover --out $B # shards, sha1s, licence evidence
python3 src/fetch_wikipedia.py acquire --out $B # resumable download + sha1 check
python3 src/fetch_wikipedia.py extract --out $B # ns 0, no redirects, no copyvio tag; {{ek}} recorded
python3 src/fetch_wikipedia.py prepare --out $B # $B/wikipedia.jsonl.zst; drops duplicates,
# COPIED_PAGES, copyright {{ek}} pages
python3 src/build_dynaword.py --sources wikipedia --speakleash-dir $B --out .
python3 src/fetch_wikipedia.py attribution --out $B # data/wikipedia sidecars
"""
from __future__ import annotations
import argparse
import bz2
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
import gzip
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys
from xml.etree.ElementTree import iterparse
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_plwiki_talk_pl import ( # noqa: E402 shared plwiki dump helpers
UA, _local, digest, load, now, page_url, request, request_json, save, sha1_file,
)
from rights import BY_SA_4_CUTOFF, license_for_revision # noqa: E402,F401 re-exported for callers
SOURCE = "wikipedia"
AUTHOR = "Wikipedia contributors" # + page URL; the page history names them
DUMP_DATE = "20260901" # same snapshot as plwiki_talk / plwiki_user_talk
DUMP_BASE = f"https://dumps.wikimedia.org/plwiki/{DUMP_DATE}"
DUMPSTATUS_URL = f"{DUMP_BASE}/dumpstatus.json"
SHA1SUMS_URL = f"{DUMP_BASE}/plwiki-{DUMP_DATE}-sha1sums.txt"
SHARD_RE = re.compile(r"plwiki-\d{8}-pages-articles\d+\.xml-p\d+p\d+\.bz2")
RIGHTSINFO_URL = ("https://pl.wikipedia.org/w/api.php?action=query&meta=siteinfo"
"&siprop=rightsinfo&format=json")
# WMF Terms of Use, revision in force from 2023-06-07 (sections 7(b)/7(c); history note).
TOU_URL = "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use&oldid=554823&action=raw"
TOU_SHA256 = "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832"
TOU_EFFECTIVE = "These Terms of Use went into effect on June 7, 2023"
# plwiki copyright-violation notice and its redirects (Szablon:NPA <- Copyvio, Plagiat).
# Namespace prefix is case-insensitive, the first letter of the name too.
COPYVIO_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?(?:[Nn]PA|[Cc]opyvio|[Pp]lagiat)\s*(?:\||\}\})")
# plwiki speedy-deletion template and its redirects (Szablon:Ek <- EK, Ekspresowe kasowanko,
# Usuń, Speedy, Delete); its first parameter (or powód=) is the stated reason.
EK_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?"
r"(?:[Ee][Kk]|[Ee]kspresowe[ _]+kasowanko|[Uu]suń|[Ss]peedy|[Dd]elete)\s*(?:\||\}\})")
EK_NAMES = {"Ek", "EK", "Ekspresowe kasowanko", "Usuń", "Speedy", "Delete"}
# The build records every template redirect to these, so the alias lists above can be checked against the dump.
TAG_TEMPLATES = {"Szablon:NPA", "Szablon:Ek"}
# Pages the copyright sample (data/wikipedia/wikipedia.copyvio-sample.jsonl) found to hold text
# copied or closely paraphrased from a copyrighted source. Keyed on the wiki page id, which is
# stable across dumps (the dataset id is derived from it). prepare fails if one is not reached.
COPIED_PAGES = {
833396: "Obnażyć prawdę: the 'Opis fabuły' paragraph closely paraphrases Filmweb's production "
"description of the film; added in revision 15302011 (2008-12-26), which cites Filmweb",
1126780: "Czarnka: the lake paragraph (revision 42979631, 2015-06-19) closely paraphrases the "
"Drawieński Park Narodowy page dpn.pl/czarne, archived 2012-01-25; whether Art. 4 of the "
"Polish copyright act (official materials) applies was not assessed",
}
# {{ek}} reasons that state a copyright violation: the template's own codes that render as
# "naruszenie praw autorskich" (npa, plagiat, copypaste, kopiuj-wklej) and free text naming one
# (copyvio, "praw autorskich"). "kopia"/"skopiowane" alone are left out: on plwiki they also
# mark a duplicate of another article, which is not a copyright reason.
EK_COPYRIGHT_RE = re.compile(
r"\bnpa\b|copyvio|plagiat|copy[ -]?paste|kopiuj[ -]?wklej|praw\w* autorsk", re.IGNORECASE)
# Links that render as an image or a category, not as running text ([[:Kategoria:X]] is a text link).
NON_PROSE_NS = {"plik", "file", "image", "grafika", "media", "kategoria", "category"}
SWITCH_RE = re.compile(r"__[A-ZĄĆĘŁŃÓŚŹŻ]+__") # __NOTOC__, __BEZSPISU__
def _non_prose(node) -> bool:
from mwparserfromhell.nodes import Tag, Wikilink
if isinstance(node, Tag):
return str(node.tag).strip().lower() == "ref"
if isinstance(node, Wikilink):
title = str(node.title).strip()
return ":" in title and not title.startswith(":") and title.split(":", 1)[0].strip().lower() in NON_PROSE_NS
return False
def strip_article(wikitext: str) -> str | None:
"""The sibling builders' strip_code, minus what it leaves as text: <ref> bodies,
"thumb|250px|caption" of file links, "Kategoria:X" lines, behaviour switches.
None when mwparserfromhell fails on the page."""
import mwparserfromhell
try:
code = mwparserfromhell.parse(wikitext)
for node in code.filter(matches=_non_prose):
try:
code.remove(node)
except ValueError: # nested in a node removed earlier
pass
text = code.strip_code(normalize=True, collapse=True)
except Exception: # noqa: BLE001 parser failure drops the page, counted
return None
return SWITCH_RE.sub("", text).strip()
def _template_name(template) -> str:
"""MediaWiki title of a template call: namespace prefix dropped, _ as space, first letter upper."""
name = " ".join(str(template.name).replace("_", " ").split())
prefix, sep, rest = name.partition(":")
if sep and prefix.strip().lower() in ("szablon", "template"):
name = rest.strip()
return name[:1].upper() + name[1:]
def _param(template, *names) -> str:
for name in names:
if template.has(name):
return str(template.get(name).value).strip()
return ""
def ek_tag(wikitext: str) -> dict | None:
"""Stated reason and source of the page's first {{ek}} speedy-deletion notice; None without one
(a call inside a comment or <nowiki> is not a notice)."""
if not EK_RE.search(wikitext):
return None
import mwparserfromhell
for template in mwparserfromhell.parse(wikitext).filter_templates():
if _template_name(template) in EK_NAMES:
return {"reason": _param(template, "1", "powód"), "source": _param(template, "2", "źródło")}
return None
def ek_is_copyright(ek: dict) -> bool:
"""True when an {{ek}} notice's stated reason is a copyright violation."""
return bool(EK_COPYRIGHT_RE.search(ek["reason"]))
def text_key(text: str) -> bytes:
"""Exact-duplicate key, identical to build_dynaword's (sha1 of the stripped text)."""
return hashlib.sha1(text.strip().encode("utf-8")).digest()
def discover(out: Path) -> None:
status = request_json(DUMPSTATUS_URL)
sums = {name: sha for sha, name in (line.split() for line in request(SHA1SUMS_URL).text.splitlines() if line.strip())}
job = status["jobs"]["articlesdump"]
if job.get("status") != "done":
raise ValueError(f"articlesdump not done: {job.get('status')}")
files = sorted(({"name": name, "url": f"{DUMP_BASE}/{name}", "size": meta["size"], "sha1": meta["sha1"]}
for name, meta in job["files"].items() if SHARD_RE.fullmatch(name)),
key=lambda f: int(re.search(r"-p(\d+)p", f["name"]).group(1)))
if not files:
raise ValueError("no pages-articles shards")
for f in files:
if sums.get(f["name"]) != f["sha1"]:
raise ValueError(f"sha1sums.txt disagrees with dumpstatus.json for {f['name']}")
rights = request_json(RIGHTSINFO_URL)["query"]["rightsinfo"]
if "creativecommons.org/licenses/by-sa/4.0" not in rights.get("url", ""):
raise ValueError(f"plwiki rightsinfo changed: {rights}")
tou = request(TOU_URL).content
if hashlib.sha256(tou).hexdigest() != TOU_SHA256 or TOU_EFFECTIVE.encode() not in tou:
raise ValueError("pinned Terms of Use revision changed")
save(out / "selection.json", {
"observed_at": now(), "dump_date": DUMP_DATE, "dump_base": DUMP_BASE,
"dumpstatus_url": DUMPSTATUS_URL, "sha1sums_url": SHA1SUMS_URL, "files": files,
"total_bytes": sum(f["size"] for f in files), "rightsinfo": rights,
"terms_of_use": {"url": TOU_URL, "sha256": TOU_SHA256, "effective": TOU_EFFECTIVE},
"by_sa_4_cutoff": BY_SA_4_CUTOFF.isoformat(),
})
print(f"{len(files)} shards, {sum(f['size'] for f in files) / 1e9:.2f} GB")
def acquire(out: Path) -> None:
raw = out / "raw_dump"
raw.mkdir(parents=True, exist_ok=True)
for f in load(out / "selection.json")["files"]:
dst = raw / f["name"]
if not dst.exists() or dst.stat().st_size != f["size"]:
subprocess.run(["curl", "-fsSL", "--retry", "8", "-C", "-", "-A", UA["User-Agent"],
"-o", str(dst), f["url"]], check=True)
if sha1_file(dst) != f["sha1"]:
raise ValueError(f"sha1 mismatch: {f['name']}")
print(f" {f['name']} sha1 OK", flush=True)
def pages(fh):
"""Yield (pageid, revid, ns, title, timestamp, redirect_target, wikitext) per <page>;
redirect_target is "" unless the page is a redirect."""
ids, title = [], None
ns = timestamp = text = None
redirect = ""
for _, el in iterparse(fh, events=("end",)):
tag = _local(el.tag)
if tag == "title":
title = el.text
elif tag == "ns":
ns = el.text
elif tag == "id" and len(ids) < 2: # <page><id>, then <revision><id>
ids.append(el.text)
elif tag == "timestamp":
timestamp = el.text
elif tag == "redirect": # <redirect title="target" />
redirect = el.get("title") or "(no target)"
elif tag == "text":
text = el.text
elif tag == "page":
yield ids[0], ids[1], ns, title, timestamp, redirect, text or ""
ids, title, ns, timestamp, text, redirect = [], None, None, None, None, ""
el.clear()
def extract_shard(src: Path, dst: Path) -> dict:
counts, copyvio, ek_tagged, tag_redirects = Counter(), [], [], []
tmp = dst.with_suffix(".tmp")
with bz2.open(src, "rb") as fh, gzip.open(tmp, "wt", encoding="utf-8") as fo:
for pageid, revid, ns, title, timestamp, redirect, wikitext in pages(fh):
counts["pages"] += 1
if ns == "10" and redirect in TAG_TEMPLATES:
tag_redirects.append({"title": title, "target": redirect})
if ns != "0":
continue
counts["ns0"] += 1
if redirect:
counts["ns0_redirect"] += 1
continue
if not wikitext.strip():
counts["ns0_empty"] += 1
continue
ek = ek_tag(wikitext) # recorded on every article; prepare drops the copyright ones
if ek is not None:
counts["ns0_ek_tag"] += 1
ek_tagged.append({"pageid": pageid, "title": title, **ek})
if COPYVIO_RE.search(wikitext):
counts["ns0_copyvio_tag"] += 1
copyvio.append({"pageid": pageid, "title": title})
elif (text := strip_article(wikitext)) is None:
counts["ns0_strip_error"] += 1
else:
counts["extracted"] += 1
row = {"pageid": pageid, "revid": revid, "title": title, "timestamp": timestamp,
"wikitext_chars": len(wikitext), "text": text}
if ek is not None:
row["ek"] = ek
fo.write(json.dumps(row, ensure_ascii=False) + "\n")
result = {"shard": src.name, "counts": dict(counts), "copyvio_tagged": copyvio,
"ek_tagged": ek_tagged, "tag_template_redirects": tag_redirects}
save(dst.with_name(src.name + ".counts.json"), result)
tmp.rename(dst)
return result
def extract(out: Path, workers: int) -> None:
files = load(out / "selection.json")["files"]
ext = out / "extracted"
ext.mkdir(exist_ok=True)
todo = [f["name"] for f in files if not (ext / (f["name"] + ".jsonl.gz")).exists()]
for f in files: # acquire checked the sha1; refuse a shard it has not finished
if f["name"] in todo and (out / "raw_dump" / f["name"]).stat().st_size != f["size"]:
raise ValueError(f"incomplete shard, run acquire: {f['name']}")
with ProcessPoolExecutor(max_workers=workers) as pool:
for r in pool.map(extract_shard, [out / "raw_dump" / n for n in todo],
[ext / (n + ".jsonl.gz") for n in todo]):
print(f" {r['shard']}: {r['counts']}", flush=True)
def prepare(out: Path) -> None:
"""Label each page, drop exact duplicates keeping the lowest page id, drop COPIED_PAGES and
pages whose {{ek}} notice gives a copyright reason, write the build input. A dropped page's
text stays in `seen`, so a later page with the same text is dropped as its duplicate."""
files = load(out / "selection.json")["files"]
seen, counts = set(), Counter()
duplicates, copied, ek_copyright = [], [], []
zst = subprocess.Popen(["zstd", "-q", "-f", "-3", "-o", str(out / f"{SOURCE}.jsonl.zst")],
stdin=subprocess.PIPE)
with gzip.open(out / "manifest.jsonl.gz", "wt", encoding="utf-8") as manifest:
for f in files: # shards are in page-id order, pages inside a shard too
with gzip.open(out / "extracted" / (f["name"] + ".jsonl.gz"), "rt", encoding="utf-8") as fh:
for line in fh:
row = json.loads(line)
counts["extracted"] += 1
key = text_key(row["text"])
if key in seen:
duplicates.append(row["pageid"])
continue
seen.add(key)
if int(row["pageid"]) in COPIED_PAGES:
copied.append({"pageid": row["pageid"], "title": row["title"],
"reason": COPIED_PAGES[int(row["pageid"])]})
continue
if "ek" in row and ek_is_copyright(row["ek"]):
ek_copyright.append({"pageid": row["pageid"], "title": row["title"], **row["ek"]})
continue
label = license_for_revision(row["timestamp"])
counts[label] += 1
row_id, url = f"{SOURCE}_{row['pageid']}", page_url(row["title"])
zst.stdin.write((json.dumps({
"id": row_id, "text": row["text"], "created": row["timestamp"][:10],
"license": label, "author": f"{AUTHOR}, {url}",
}, ensure_ascii=False) + "\n").encode("utf-8"))
manifest.write(json.dumps({
"id": row_id, "pageid": int(row["pageid"]), "revid": int(row["revid"]),
"title": row["title"], "url": url,
"last_revision_at": row["timestamp"], "license": label,
}, ensure_ascii=False) + "\n")
zst.stdin.close()
if zst.wait():
raise RuntimeError("zstd failed")
missing = set(COPIED_PAGES) - {int(p["pageid"]) for p in copied}
if missing:
raise ValueError(f"COPIED_PAGES not reached (gone from the dump, tagged or a duplicate): {sorted(missing)}")
counts["exact_duplicate"] = len(duplicates)
counts["copied_page"] = len(copied)
counts["ek_copyright"] = len(ek_copyright)
save(out / "prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates,
"copied_pages": copied, "ek_copyright": ek_copyright})
print(dict(counts))
def attribution(out: Path, data_dir: Path) -> None:
"""Sidecars for the rows build_dynaword kept: per-page attribution and the build record."""
import pyarrow.parquet as pq
kept = set(pq.read_table(data_dir / f"{SOURCE}.parquet", columns=["id"])["id"].to_pylist())
n = 0
with gzip.open(out / "manifest.jsonl.gz", "rt", encoding="utf-8") as fh, \
(data_dir / f"{SOURCE}.attribution.jsonl").open("w", encoding="utf-8") as fo:
for line in fh:
if json.loads(line)["id"] in kept:
fo.write(line)
n += 1
if n != len(kept):
raise ValueError(f"attribution rows {n} != parquet rows {len(kept)}")
selection = load(out / "selection.json")
shards = [load(out / "extracted" / (f["name"] + ".counts.json")) for f in selection["files"]]
save(data_dir / f"{SOURCE}.build.json", {
"dump_date": selection["dump_date"], "dump_base": selection["dump_base"],
"sha1sums_url": selection["sha1sums_url"], "files": selection["files"],
"rightsinfo": selection["rightsinfo"], "terms_of_use": selection["terms_of_use"],
"by_sa_4_cutoff": selection["by_sa_4_cutoff"], "discovered_at": selection["observed_at"],
"extract": dict(sum((Counter(s["counts"]) for s in shards), Counter())),
"copyvio_tagged": [p for s in shards for p in s["copyvio_tagged"]],
"ek_tagged": [p for s in shards for p in s["ek_tagged"]],
"tag_template_redirects": [r for s in shards for r in s["tag_template_redirects"]],
"prepare": load(out / "prepare.json"),
"attribution_rows": n, "attribution_sha256": digest((data_dir / f"{SOURCE}.attribution.jsonl").read_bytes()),
})
print(f"attribution rows: {n}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("step", choices=["discover", "acquire", "extract", "prepare", "attribution"])
ap.add_argument("--out", required=True, type=Path)
ap.add_argument("--data-dir", type=Path, default=Path(__file__).resolve().parent.parent / "data" / SOURCE)
ap.add_argument("--workers", type=int, default=8)
a = ap.parse_args()
a.out.mkdir(parents=True, exist_ok=True)
{"discover": lambda: discover(a.out), "acquire": lambda: acquire(a.out),
"extract": lambda: extract(a.out, a.workers), "prepare": lambda: prepare(a.out),
"attribution": lambda: attribution(a.out, a.data_dir)}[a.step]()
if __name__ == "__main__":
main()