#!/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= 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 python3 src/fetch_wikipedia.py withhold --out $B # drops pages added to COPIED_PAGES since Labels by contribution (slayerlabs/polish-dynaword-v2#110, option B) replace the last-revision labels on the committed release; the pages-articles dump is not re-read. H= python3 src/wiki_history.py download --dump plwiki --out $H python3 src/wiki_history.py scan --stub $H/plwiki-20261001-stub-meta-history.xml.gz \\ --sidecar wikipedia=data/wikipedia/wikipedia.attribution.jsonl --out $H python3 src/wiki_history.py fetch --source wikipedia --history $H/wikipedia.history.jsonl --out $H python3 src/wiki_history.py compare --source wikipedia --sidecar data/wikipedia/wikipedia.attribution.jsonl \\ --history $H/wikipedia.history.jsonl --fetched $H/wikipedia --parquet data/wikipedia/wikipedia.parquet \\ --out $H/wikipedia.labels.jsonl python3 src/fetch_wikipedia.py relabel --out $H # data/wikipedia; the card is edited by hand Each row's source citations (v2#110, option A) are read from the same dump's pages-meta-current shards, which hold the shipped revision of every page. M= python3 src/fetch_wikipedia.py citations --out $M # data/wikipedia/citations; build.json `citations` """ 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") META_CURRENT_RE = re.compile(r"plwiki-\d{8}-pages-meta-current\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"} def _deleted(day: str, reason: str = "[[Wikipedia:Prawa autorskie|naruszenie praw autorskich]]") -> str: """A COPIED_PAGES reason for a page deleted from plwiki for copyright: the day and the log's reason.""" return f'deleted from plwiki on {day} for a copyright violation, deletion log: "{reason}"' # Pages that hold text copied or closely paraphrased from a copyrighted source: found by the # copyright sample (data/wikipedia/wikipedia.copyvio-sample.jsonl), or deleted from plwiki for a # copyright violation after the dump (Special:Log/delete). 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; # `withhold` drops one added after the build from the committed release. 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", 4095632: "Brzezina (opowiadanie): " + _deleted("2026-09-01", ( # the link's tracking query left out "Naruszenie praw autorskich: https://www.studocu.com/pl/document/uniwersytet-jagiellonski/" "filologia-polska/proza-poetycka-i-awangardowa-iwaszkiewicz-jasienski-choromanski/74568413")), 6131122: "Edmund Bielecki: " + _deleted("2026-09-05"), 6131594: "Ryszard Cyffer: " + _deleted("2026-09-05"), 6131631: "Stanisław Czarnomski: " + _deleted("2026-09-05"), 6131646: "Mikołaj Dmochowski: " + _deleted("2026-09-05"), 6132108: "Włodzimierz Daszkiewicz: " + _deleted("2026-09-06"), 6132151: "Konstanty Jankowski (oficer): " + _deleted("2026-09-06"), } # {{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: 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 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 by_first_page(files: list[dict]) -> list[dict]: """Dump shards in page-id order (the first page id in each name).""" return sorted(files, key=lambda f: int(re.search(r"-p(\d+)p", f["name"]).group(1))) 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 = by_first_page([{"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)]) 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 ; 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: # , then ids.append(el.text) elif tag == "timestamp": timestamp = el.text elif tag == "redirect": # 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 withhold(data_dir: Path) -> None: """Drop from the committed release the pages added to COPIED_PAGES after the build, as prepare would on a rebuild, without re-reading the dump: the parquet and sidecar rows, stats, build.json (`prepare.counts` and `copied_pages`, attribution rows and sha) and the evidence's release scope. Each is added to the copyright sample's `rows_dropped_since` with its stratum, so the sample's draw still reproduces. Run before `relabel`; rerunning changes nothing.""" import pyarrow as pa import pyarrow.compute as pc import pyarrow.parquet as pq from fetch_wikimedia import label_totals # not at the top: fetch_wikimedia imports this module def path(name): return data_dir / f"{SOURCE}.{name}" side = [json.loads(line) for line in path("attribution.jsonl").open(encoding="utf-8")] held = [rec for rec in side if rec["pageid"] in COPIED_PAGES] if not held: print(f"{SOURCE}: nothing to withhold") return build = load(path("build.json")) if "licence_labels" in build or "citations" in build: # ponytail: relabel's counts and the citations would keep them raise ValueError(f"{SOURCE}: withhold before relabel and citations, then filter their output to the sidecar") held_ids = {rec["id"] for rec in held} table = pq.read_table(path("parquet")) table = table.filter(pc.invert(pc.is_in(table["id"], pa.array(sorted(held_ids))))) groups = pq.ParquetFile(path("parquet")).metadata.row_group(0).num_rows # build_dynaword's batches, kept pq.write_table(table, path("parquet"), compression="zstd", row_group_size=groups) side = [rec for rec in side if rec["id"] not in held_ids] path("attribution.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in side), encoding="utf-8") docs, tokens = label_totals(table["license"].to_pylist(), table["token_count"].to_pylist()) stats = load(path("stats.json")) stats.update(read=stats["read"] - len(held), kept=table.num_rows, chars=pc.sum(pc.utf8_length(table["text"])).as_py(), tokens=sum(tokens.values()), licenses=docs, authors_with_value=table.num_rows) path("stats.json").write_text(json.dumps(stats, indent=2)) # build_dynaword's format prep = build["prepare"] prep["counts"]["copied_page"] += len(held) for rec in held: # prepare's per-row label is the last revision's prep["counts"][license_for_revision(rec["last_revision_at"])] -= 1 prep["copied_pages"] += [{"pageid": str(rec["pageid"]), "title": rec["title"], "reason": COPIED_PAGES[rec["pageid"]]} for rec in held] build.update(attribution_rows=len(side), attribution_sha256=digest(path("attribution.jsonl").read_bytes())) save(path("build.json"), build) ev = load(path("license-evidence.json")) scope = ev["release_scope"] scope.update(labels=docs, tokens_by_label=tokens, copied_pages=len(prep["copied_pages"]), documents_released=table.num_rows) ev["copyright_sample"]["population"]["rows_dropped_since"] += [ [rec["id"], license_for_revision(rec["last_revision_at"])] for rec in held] path("license-evidence.json").write_text(json.dumps(ev, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") # the file's format print(f"{SOURCE}: withheld {sorted(held_ids)}, {stats['kept']} rows left") def relabel(out: Path, data_dir: Path) -> None: """Label each row by contribution (v2#110) from out/wikipedia.labels.jsonl (wiki_history.py compare): fetch_wikimedia.write_labels rewrites the parquet `license` column, the sidecar, stats and build record; this updates the licence evidence's labels and tokens. Text, ids and every other column are unchanged; rerunning changes nothing.""" from fetch_wikimedia import write_labels # not at the top: fetch_wikimedia imports this module docs, tokens = write_labels(out, data_dir, SOURCE, "plwiki", BY_SA_4_CUTOFF) path = data_dir / f"{SOURCE}.license-evidence.json" ev = load(path) ev["license"] = "CC-BY-SA-3.0, CC-BY-SA-4.0 or both per record, by contribution date" ev["review_scope"] = ("licence of contributors' text on pl.wikipedia and its version per contribution; " "copyright pastes estimated by sample; not independent legal advice") scope = ev["release_scope"] scope.pop("tokens_by_label", None) # the wikimedia sources' name, so their card text applies scope.update(labels=docs, tokens=tokens) path.write_text(json.dumps(ev, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") # the file's format print(f"{SOURCE}: relabelled, {docs}") def _shard_citations(job: tuple[Path, str, frozenset[str]]) -> dict[str, tuple[str, str, list[str]]]: """citations' work on one pages-meta-current shard: {pageid: (revid, timestamp, citations)} of the pages in `wanted`.""" from fetch_wikimedia import page_sources # not at the top: fetch_wikimedia imports this module path, sha1, wanted = job if sha1_file(path) != sha1: raise ValueError(f"sha1 mismatch: {path.name}") found = {} with bz2.open(path, "rb") as fh: for pageid, revid, _, _, timestamp, _, wikitext in pages(fh): if pageid not in wanted: continue if pageid in found: raise ValueError(f"page {pageid} twice in {path.name}") found[pageid] = (revid, timestamp, page_sources(SOURCE, wikitext)[0]) return found def citations(dumps: Path, data_dir: Path, status: dict, workers: int) -> None: """citations/wikipedia.citations.parquet: `id` and `citations` (fetch_wikimedia.page_sources: the non-empty bodies, then the Cytuj*/Cite* templates outside them, as wikitext) of every row, in the release's order, read from the pages-meta-current shards in `dumps` that `status` (the dump's dumpstatus.json) lists, sha1-checked. A page missing from them, or there at another revision or timestamp than the sidecar's, stops it. In a folder: the release's `data/*/*.parquet` glob would read a parquet next to wikipedia.parquet as text rows. build.json `citations` records the shards, counts and sha256; rerunning changes nothing.""" import pyarrow as pa import pyarrow.parquet as pq with (data_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as fh: # in page id order meta = {rec["id"]: (str(rec["pageid"]), str(rec["revid"]), rec["last_revision_at"]) for rec in map(json.loads, fh)} release = data_dir / f"{SOURCE}.parquet" ids = pq.read_table(release, columns=["id"])["id"].to_pylist() if len(ids) != len(meta) or meta.keys() != set(ids): raise ValueError("the sidecar's ids are not the parquet's") side = [(row_id, *meta[row_id]) for row_id in ids] shards = by_first_page([{"name": name, "size": f["size"], "sha1": f["sha1"]} for name, f in status["jobs"]["metacurrentdump"]["files"].items() if META_CURRENT_RE.fullmatch(name)]) if not shards: raise ValueError("no pages-meta-current shards in dumpstatus.json") wanted, found = frozenset(pageid for _, pageid, _, _ in side), {} with ProcessPoolExecutor(max_workers=workers) as pool: for part in pool.map(_shard_citations, [(dumps / f["name"], f["sha1"], wanted) for f in shards]): if twice := found.keys() & part.keys(): raise ValueError(f"pages in two shards: {sorted(twice)[:5]}") found.update(part) bad = [] for row_id, pageid, revid, at in side: if pageid not in found: bad.append(f"{row_id}: not in the dump") elif found[pageid][:2] != (revid, at): bad.append(f"{row_id}: the dump has revision {found[pageid][0]} at {found[pageid][1]}") if bad: raise ValueError(f"{len(bad)} rows do not match the dump: {bad[:5]}") path = data_dir / "citations" / f"{SOURCE}.citations.parquet" path.parent.mkdir(exist_ok=True) schema = pa.schema([("id", pa.string()), ("citations", pa.list_(pa.string()))]) group = pq.ParquetFile(release).metadata.row_group(0).num_rows # the release's row groups, so row n is row n in both with pq.ParquetWriter(path, schema, compression="zstd") as writer: for start in range(0, len(side), group): # a group at a time: one string array caps at 2 GiB rows = side[start:start + group] writer.write_table(pa.table([[r[0] for r in rows], [found[r[1]][2] for r in rows]], schema=schema), row_group_size=group) cites = [found[pageid][2] for _, pageid, _, _ in side] build = load(data_dir / f"{SOURCE}.build.json") build["citations"] = { "issue": "slayerlabs/polish-dynaword-v2#110", "file": path.relative_to(data_dir).as_posix(), "dumpstatus_url": DUMPSTATUS_URL, "shards": shards, "rows": len(cites), "rows_with_citations": sum(map(bool, cites)), "citations": sum(map(len, cites)), "sha256": digest(path.read_bytes()), } save(data_dir / f"{SOURCE}.build.json", build) print(f"{SOURCE}: {build['citations']['rows_with_citations']} rows with {build['citations']['citations']} citations") def citations_text(build: dict) -> str: """The card's account of the citations table (build.json `citations`); the card is edited by hand around it.""" from fetch_wikimedia import citations_sentence # not at the top: fetch_wikimedia imports this module c = build["citations"] return (f"The source citations are in `{c['file']}`, a table of `id` and `citations` with the release's\n" f"rows in the same order and row groups. " + citations_sentence(SOURCE, c["rows_with_citations"]) + f" Each list is in page order, without repeats, and empty for a page\nwith none: {c['citations']:,} citations in all. " f"They are read from the {len(c['shards'])} pages-meta-current shards of the same {DUMP_DATE} dump (names,\n" f"sizes and sha1 in `{SOURCE}.build.json` `citations`, each matched against `dumpstatus.json`), whose revision of\n" f"every row is the shipped `revid` with its `last_revision_at`. The table is in a folder of its own so that the\n" f"`data/*/*.parquet` file pattern (the README's dataset config, the scripts in `src`) does not read it as documents.") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("step", choices=["discover", "acquire", "extract", "prepare", "attribution", "withhold", "relabel", "citations"]) 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), "withhold": lambda: withhold(a.data_dir), "relabel": lambda: relabel(a.out, a.data_dir), "citations": lambda: citations(a.out, a.data_dir, request_json(DUMPSTATUS_URL), a.workers)}[a.step]() if __name__ == "__main__": main()