Datasets:
Download src/fetch_wikimedia.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 29.7 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/src/fetch_wikimedia.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword/src/fetch_wikimedia.py
-
curl -L -o fetch_wikimedia.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/src/fetch_wikimedia.py
29.7 kB
| #!/usr/bin/env python3 | |
| """Polish Wikinews, Wikivoyage and Wikibooks from the official dumps, licence per record. | |
| v0.2.0-v0.2.5 labelled every row with one licence (Wikinews CC-BY-2.5, the others | |
| CC-BY-SA-3.0). Each row now carries the label of its page's last revision | |
| (`license_for_revision` in src/rights.py): v0.2.6 rights audit, slayerlabs/polish-dynaword-v2#57. | |
| The dump date is pinned to the one the v0.2.5 text came from (the rebuild changes labels, | |
| ids, authors and dates, not the text); the dump file is checked against the sha1 in | |
| dumpstatus.json and in the dump's sha1sums.txt. | |
| B=<build dir, never committed> | |
| python3 src/fetch_wikimedia.py acquire --out $B --sources wikinews wikivoyage wikibooks | |
| python3 src/fetch_wikimedia.py prepare --out $B ... # $B/plwiki{news,voyage,books}.jsonl.zst | |
| python3 src/build_dynaword.py --sources wikinews wikivoyage wikibooks --speakleash-dir $B --out . | |
| python3 src/fetch_wikimedia.py attribution --out $B ... # data/<source> sidecars + evidence | |
| python3 src/fetch_wikimedia.py datasheet --out $B ... # data/<source>/<source>.md | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import bz2 | |
| from collections import Counter | |
| from datetime import timedelta | |
| import gzip | |
| import hashlib | |
| import html | |
| import json | |
| from pathlib import Path | |
| import re | |
| import subprocess | |
| import sys | |
| from urllib.parse import quote | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from build_plwiki_talk_pl import ( # noqa: E402 shared dump helpers | |
| UA, digest, load, now, request, request_json, save, sha1_file, | |
| ) | |
| from fetch_wikipedia import pages, text_key # noqa: E402 | |
| from language_gate import card_line # noqa: E402 | |
| from rights import ( # noqa: E402 | |
| BY_SA_4_CUTOFF, DROPPED_PAGES, WIKINEWS_BY_4_CUTOFF, check_dropped_reached, license_for_revision, | |
| ) | |
| from sources import SOURCES # noqa: E402 | |
| DUMP_DATE = "20260601" # the dump the v0.2.5 text was cut from (checked: same text set) | |
| MIN_CHARS = 200 # same gate as build_dynaword.py | |
| # WMF Terms of Use in force from 2023-06-07 (CC BY-SA 4.0), and the 2014 revision (CC BY-SA 3.0). | |
| WMF_TOU_NEW = { | |
| "title": "Wikimedia Terms of Use in force since 7 June 2023 (CC BY-SA 4.0)", | |
| "url": "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use&oldid=554823&action=raw", | |
| "sha256": "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832", | |
| "effective": "These Terms of Use went into effect on June 7, 2023", | |
| "statement": "Creative Commons Attribution-ShareAlike 4.0 International License", | |
| } | |
| WMF_TOU_OLD = { | |
| "title": "Wikimedia Terms of Use of 2014-2023 (CC BY-SA 3.0)", | |
| "url": "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use&oldid=98524&action=raw", | |
| "sha256": "46617e3576a507b8f83a0cf7b28b60e43817ad93cc5d747a558b503e7d1cc6de", | |
| "effective": "These Terms of Use went into effect on June 16, 2014", | |
| "statement": "Creative Commons Attribution-ShareAlike 3.0 Unported License", | |
| } | |
| # pl.wikinews has its own terms page: CC BY, 2.5 until 2024-12-16, 4.0 since. | |
| WIKINEWS_TERMS = { | |
| "title": "pl.wikinews terms of use (CC BY 2.5 until 2024-12-16, CC BY 4.0 since)", | |
| "url": "https://pl.wikinews.org/w/index.php?title=Wikinews:Warunki_u%C5%BCycia&oldid=342796&action=raw", | |
| "sha256": "8b461acb8e0608eb906e59d9669bc003759d7840d82fc934f83d160a72895de3", | |
| "effective": "udostępnia swoją treść na licencji Creative Commons Uznanie autorstwa 4.0 od 16 grudnia 2024 roku", | |
| "statement": "a wcześniej na licencji. [http://creativecommons.org/licenses/by/2.5/deed.pl Creative Commons Uznanie autorstwa 2.5]", | |
| } | |
| WIKINEWS_SWITCH = { # the config change that made 4.0 the site licence (Phabricator T381421) | |
| "gerrit": "https://gerrit.wikimedia.org/r/changes/operations%2Fmediawiki-config~1101867", | |
| "phabricator": "https://phabricator.wikimedia.org/T381421", | |
| "merged_utc": "2024-12-16 08:07", | |
| "synced_by_utc": "2024-12-16 08:32:24", # SAL scap sync-world finish; read by the rights audit, not re-read | |
| } | |
| GFDL_ERA_END = "2009-06-15" # the Wikimedia sites began dual licensing under CC BY-SA 3.0 and the GFDL | |
| # What the label rule rests on: each licence's own clause on adaptations (read from the legal code). | |
| LEGAL_BY_SA_3 = {"url": "https://creativecommons.org/licenses/by-sa/3.0/legalcode", "section": "4(b)(ii)", | |
| "statement": "a later version of this License with the same License Elements as this License"} | |
| LEGAL_BY_SA_4 = {"url": "https://creativecommons.org/licenses/by-sa/4.0/legalcode", "section": "3(b)(1)", | |
| "statement": "this version or later, or a BY-SA Compatible License"} | |
| LEGAL_BY_2_5 = {"url": "https://creativecommons.org/licenses/by/2.5/legalcode", "section": "4(a)", | |
| "statement": "You may not sublicense the Work", "absent": "later version"} # no later-version clause | |
| SITES = { | |
| "wikinews": { | |
| "wiki": "plwikinews", "host": "pl.wikinews.org", "pretty": "Polish Wikinews", | |
| "author": "Wikinews contributors", "family": "CC BY", | |
| "cutoff": WIKINEWS_BY_4_CUTOFF, "before": "CC-BY-2.5", "after": "CC-BY-4.0", | |
| "site_rights": "creativecommons.org/licenses/by/4.0/", "terms": [WIKINEWS_TERMS], "legal": [LEGAL_BY_2_5], | |
| "clock": WIKINEWS_SWITCH["synced_by_utc"], "era_end": "2005-09-25", "domain": "news", | |
| "v025": (24386, 32524646, 12141355), | |
| }, | |
| "wikivoyage": { | |
| "wiki": "plwikivoyage", "host": "pl.wikivoyage.org", "pretty": "Polish Wikivoyage", | |
| "author": "Wikivoyage contributors", "family": "CC BY-SA", | |
| "cutoff": BY_SA_4_CUTOFF, "before": "CC-BY-SA-3.0", "after": "CC-BY-SA-4.0", | |
| "site_rights": "creativecommons.org/licenses/by-sa/4.0/", "terms": [WMF_TOU_NEW, WMF_TOU_OLD], "legal": [LEGAL_BY_SA_3, LEGAL_BY_SA_4], | |
| "era_end": GFDL_ERA_END, "domain": "travel", "v025": (13645, 45184300, 17128200), | |
| }, | |
| "wikibooks": { | |
| "wiki": "plwikibooks", "host": "pl.wikibooks.org", "pretty": "Polish Wikibooks", | |
| "author": "Wikibooks contributors", "family": "CC BY-SA", | |
| "cutoff": BY_SA_4_CUTOFF, "before": "CC-BY-SA-3.0", "after": "CC-BY-SA-4.0", | |
| "site_rights": "creativecommons.org/licenses/by-sa/4.0/", "terms": [WMF_TOU_NEW, WMF_TOU_OLD], "legal": [LEGAL_BY_SA_3, LEGAL_BY_SA_4], | |
| "era_end": GFDL_ERA_END, "domain": "instructional", "v025": (9112, 38892589, 15571295), | |
| }, | |
| } | |
| def label(key: str, timestamp: str) -> str: | |
| s = SITES[key] | |
| return license_for_revision(timestamp, s["cutoff"], s["before"], s["after"]) | |
| def page_url(key: str, title: str) -> str: | |
| return f"https://{SITES[key]['host']}/wiki/" + quote((title or "").replace(" ", "_"), safe="/:") | |
| def dump_base(key: str) -> str: | |
| return f"https://dumps.wikimedia.org/{SITES[key]['wiki']}/{DUMP_DATE}" | |
| def legal_pin(pin: dict) -> dict: | |
| """Fetch a legal-code page, check the clause the label rests on, record the page hash.""" | |
| body = request(pin["url"]).content | |
| text = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", body.decode("utf-8", "replace")))) | |
| if pin["statement"] not in text or (pin.get("absent") and pin["absent"] in text): | |
| raise ValueError(f"legal code changed: {pin['url']}") | |
| return {**pin, "sha256": hashlib.sha256(body).hexdigest()} | |
| def strip(wikitext: str) -> str | None: | |
| """Wikitext -> plain text, exactly as the v0.2.5 builder did. None when the parser fails.""" | |
| import mwparserfromhell | |
| try: | |
| return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip() | |
| except Exception: # noqa: BLE001 parser failure drops the page, counted | |
| return None | |
| def acquire(out: Path, key: str) -> None: | |
| site, wiki, base = SITES[key], SITES[key]["wiki"], dump_base(key) | |
| status = request_json(f"{base}/dumpstatus.json")["jobs"]["articlesdump"] | |
| if status.get("status") != "done": | |
| raise ValueError(f"{wiki} articlesdump not done: {status.get('status')}") | |
| name = f"{wiki}-{DUMP_DATE}-pages-articles.xml.bz2" | |
| meta = status["files"][name] | |
| sums = {n: sha for sha, n in (ln.split() for ln in request(f"{base}/{wiki}-{DUMP_DATE}-sha1sums.txt").text.splitlines() if ln.strip())} | |
| if sums.get(name) != meta["sha1"]: | |
| raise ValueError(f"sha1sums.txt disagrees with dumpstatus.json for {name}") | |
| rights = request_json(f"https://{site['host']}/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo&format=json")["query"]["rightsinfo"] | |
| if site["site_rights"] not in rights.get("url", ""): | |
| raise ValueError(f"{wiki} rightsinfo changed: {rights}") | |
| terms = [] | |
| for t in site["terms"]: | |
| body = request(t["url"]).content | |
| if hashlib.sha256(body).hexdigest() != t["sha256"] or t["effective"].encode() not in body: | |
| raise ValueError(f"pinned terms page changed: {t['url']}") | |
| terms.append(t) | |
| legal = [legal_pin(p) for p in site["legal"]] | |
| switch = None | |
| if key == "wikinews": # Gerrit prefixes its JSON with ")]}'" | |
| change = json.loads(request(WIKINEWS_SWITCH["gerrit"]).text.split("\n", 1)[1]) | |
| task = request(WIKINEWS_SWITCH["phabricator"]).text | |
| if change["status"] != "MERGED" or not change["submitted"].startswith("2024-12-16") or "T381421" not in task: | |
| raise ValueError(f"Wikinews licence switch evidence changed: {change['status']} {change['submitted']}") | |
| switch = {**WIKINEWS_SWITCH, "gerrit_status": change["status"], "gerrit_submitted": change["submitted"]} | |
| raw = out / "raw_dump" | |
| raw.mkdir(parents=True, exist_ok=True) | |
| dst = raw / name | |
| if not dst.exists() or dst.stat().st_size != meta["size"]: | |
| subprocess.run(["curl", "-fsSL", "--retry", "8", "-C", "-", "-A", UA["User-Agent"], | |
| "-o", str(dst), f"{base}/{name}"], check=True) | |
| if sha1_file(dst) != meta["sha1"]: | |
| raise ValueError(f"sha1 mismatch: {name}") | |
| save(out / f"{key}.selection.json", { | |
| "observed_at": now(), "dump_date": DUMP_DATE, "dump_base": base, "sha1sums_url": f"{base}/{wiki}-{DUMP_DATE}-sha1sums.txt", | |
| "file": {"name": name, "url": f"{base}/{name}", "size": meta["size"], "sha1": meta["sha1"]}, | |
| "rightsinfo": {**rights, "url_queried": f"https://{site['host']}/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo"}, | |
| "terms": terms, "legal": legal, "switch": switch, | |
| "cutoff": site["cutoff"].isoformat(), "before": site["before"], "after": site["after"], | |
| }) | |
| print(f"{key}: {name} sha1 OK") | |
| def prepare(out: Path, key: str) -> None: | |
| """Label each page, drop exact duplicates keeping the lowest page id and the pages in | |
| DROPPED_PAGES[key], 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.""" | |
| site, dropped_ids = SITES[key], DROPPED_PAGES[key] | |
| src = out / "raw_dump" / load(out / f"{key}.selection.json")["file"]["name"] | |
| seen, counts, duplicates, dropped, last_id = set(), Counter(), [], [], 0 | |
| zst = subprocess.Popen(["zstd", "-q", "-f", "-3", "-o", str(out / f"{site['wiki']}.jsonl.zst")], stdin=subprocess.PIPE) | |
| try: | |
| with bz2.open(src, "rb") as fh, gzip.open(out / f"{key}.manifest.jsonl.gz", "wt", encoding="utf-8") as manifest: | |
| for pageid, revid, ns, title, timestamp, redirect, wikitext in pages(fh): | |
| counts["pages"] += 1 | |
| if int(pageid) <= last_id: # "lowest page id wins" below relies on dump order | |
| raise ValueError(f"dump not in page-id order at {pageid}") | |
| last_id = int(pageid) | |
| if ns != "0": | |
| continue | |
| counts["ns0"] += 1 | |
| if redirect: | |
| counts["ns0_redirect"] += 1 | |
| elif not wikitext.strip(): | |
| counts["ns0_empty"] += 1 | |
| elif (text := strip(wikitext)) is None: | |
| counts["ns0_strip_error"] += 1 | |
| elif len(text) < MIN_CHARS: | |
| counts["ns0_short"] += 1 | |
| elif text_key(text) in seen: | |
| counts["exact_duplicate"] += 1 | |
| duplicates.append(pageid) | |
| else: | |
| seen.add(text_key(text)) | |
| if int(pageid) in dropped_ids: | |
| dropped.append({"pageid": pageid, "title": title, "reason": dropped_ids[int(pageid)]}) | |
| continue | |
| lic = label(key, timestamp) | |
| counts["written"] += 1 | |
| counts[lic] += 1 | |
| row_id, url = f"{key}_{pageid}", page_url(key, title) | |
| zst.stdin.write((json.dumps({ | |
| "id": row_id, "text": text, "created": timestamp[:10], | |
| "license": lic, "author": f"{site['author']}, {url}", | |
| }, ensure_ascii=False) + "\n").encode("utf-8")) | |
| manifest.write(json.dumps({ | |
| "id": row_id, "pageid": int(pageid), "revid": int(revid), "title": title, "url": url, | |
| "last_revision_at": timestamp, "license": lic, | |
| }, ensure_ascii=False) + "\n") | |
| finally: # a failed gate must not leave zstd waiting on stdin | |
| zst.stdin.close() | |
| status = zst.wait() | |
| if status: | |
| raise RuntimeError("zstd failed") | |
| check_dropped_reached(key, [p["pageid"] for p in dropped]) | |
| counts["dropped_page"] = len(dropped) | |
| save(out / f"{key}.prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates, | |
| "dropped_pages": dropped}) | |
| print(key, dict(counts)) | |
| def attribution(out: Path, data_dir: Path, key: str) -> None: | |
| """Sidecars for the rows build_dynaword kept: per-page attribution, build record, licence evidence.""" | |
| import pyarrow.parquet as pq | |
| site = SITES[key] | |
| table = pq.read_table(data_dir / f"{key}.parquet", columns=["id", "created", "license", "token_count"]).to_pydict() | |
| tokens_of = dict(zip(table["id"], table["token_count"])) | |
| rows = [] | |
| with gzip.open(out / f"{key}.manifest.jsonl.gz", "rt", encoding="utf-8") as fh: | |
| for line in fh: | |
| if (rec := json.loads(line))["id"] in tokens_of: | |
| rows.append((line, rec)) | |
| if len(rows) != len(tokens_of): | |
| raise ValueError(f"attribution rows {len(rows)} != parquet rows {len(tokens_of)}") | |
| sidecar = data_dir / f"{key}.attribution.jsonl" | |
| sidecar.write_text("".join(line for line, _ in rows), encoding="utf-8") | |
| sel, prep = load(out / f"{key}.selection.json"), load(out / f"{key}.prepare.json") | |
| tokens, docs = Counter(), Counter() | |
| for lic, tok in zip(table["license"], table["token_count"]): | |
| docs[lic] += 1 | |
| tokens[lic] += tok | |
| day = site["cutoff"].date().isoformat() # edits on the switch day are labelled `after` | |
| on_day = [rec["last_revision_at"] for _, rec in rows if rec["last_revision_at"].startswith(day)] | |
| boundary = {"day": day, "docs_last_edited_that_day": len(on_day)} | |
| if clock := site.get("clock"): # known deployment time of the switch, when there is one | |
| boundary.update({"known_switch_time_utc": clock, | |
| "of_which_before_that_time": sum(t.replace("T", " ").rstrip("Z") < clock for t in on_day)}) | |
| scope = {"labels": dict(docs), "tokens": dict(tokens), "created_range": [min(table["created"]), max(table["created"])]} | |
| old = [rec["id"] for _, rec in rows if rec["last_revision_at"] < site["era_end"]] # recorded, not acted on | |
| scope["last_edited_before_era_end"] = {"date": site["era_end"], "docs": len(old), "tokens": sum(tokens_of[i] for i in old)} | |
| save(data_dir / f"{key}.build.json", { | |
| "dump_date": sel["dump_date"], "dump_base": sel["dump_base"], "sha1sums_url": sel["sha1sums_url"], | |
| "file": sel["file"], "rightsinfo": sel["rightsinfo"], "terms": sel["terms"], "switch": sel["switch"], | |
| "cutoff": sel["cutoff"], "labels": {"before": sel["before"], "after": sel["after"]}, | |
| "discovered_at": sel["observed_at"], "prepare": prep, | |
| "attribution_rows": len(rows), "attribution_sha256": digest(sidecar.read_bytes()), | |
| }) | |
| save(data_dir / f"{key}.license-evidence.json", { | |
| "license": f"{sel['before']} or {sel['after']} per record, by the page's last revision", | |
| "spdx": [f"https://spdx.org/licenses/{sel['before']}.html", f"https://spdx.org/licenses/{sel['after']}.html"], | |
| "status": "documented-open-cc-by-sa" if "SA" in sel["after"] else "documented-open-cc-by", | |
| "review_scope": f"licence of contributors' text on {site['host']} and its version per page; not independent legal advice", | |
| "checked_at": sel["observed_at"][:10], | |
| "cutoff": {"at": sel["cutoff"], "before": sel["before"], "after": sel["after"], "boundary_day": boundary}, | |
| "terms": sel["terms"], "legal": sel["legal"], "switch": sel["switch"], | |
| "site_licence": {"observed_at": sel["observed_at"], "rightsinfo": sel["rightsinfo"]}, | |
| "release_scope": scope, | |
| }) | |
| print(f"{key}: attribution rows {len(rows)}, labels {dict(docs)}") | |
| def share(part: int, whole: int) -> str: | |
| return f"{100 * part / whole:.1f}%" | |
| def licensing_text(key: str, ev: dict) -> str: | |
| """The reading of the licences behind the labels, with the cutoff-day count.""" | |
| site, cut = SITES[key], ev["cutoff"] | |
| day, n = cut["boundary_day"]["day"], cut["boundary_day"]["docs_last_edited_that_day"] | |
| next_day = (site["cutoff"] + timedelta(days=1)).date().isoformat() | |
| before, after = cut["before"], cut["after"] | |
| if "SA" in after: | |
| return ( | |
| f"A page last edited on or after the cutoff can still hold 3.0 text from earlier edits;\n" | |
| f"[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/legalcode) §4(b)(ii) lets such an adaptation be licensed under \"a later\n" | |
| f"version of this License with the same License Elements\", so it is labelled 4.0. The Terms\n" | |
| f"of Use give the day of the switch, not the time. The cutoff is midnight UTC, so the\n" | |
| f"{n} pages last edited on {day} itself are labelled 4.0. If the switch came later\n" | |
| f"that day, those last edited before it are 3.0 text under a 4.0 label; a {next_day} cutoff\n" | |
| f"(the citation pass's fallback) would instead put that day's 4.0 edits under a 3.0 label,\n" | |
| f"which [4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode) §3(b)(1) (\"this version or later\") does not allow. Neither choice is\n" | |
| f"exact without the time of the switch. The rule is `license_for_revision` in `src/rights.py`,\n" | |
| f"tested at the cutoff second, across time zones, and on a missing timestamp, which stops the\n" | |
| f"build. v0.2.0-v0.2.5 labelled every row `{before}`." | |
| ) | |
| sw, k = ev["switch"], cut["boundary_day"]["of_which_before_that_time"] | |
| return ( | |
| f"pl.wikinews has its own terms page, which names CC BY 2.5 until {day} and CC BY 4.0 from that\n" | |
| f"day. A page last edited on or after the cutoff can still hold\n" | |
| f"2.5 text from earlier edits, and the [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/legalcode) legal code (§4(a)) has no clause that lets an\n" | |
| f"adaptation be licensed under a later version (BY-SA 3.0 §4(b)(ii) has one). The 4.0 label for such\n" | |
| f"pages rests on the site's terms page alone; whether that is enough is for the lawyer.\n" | |
| f"The terms page gives the day, not the time. The cutoff is midnight UTC, so the {n} pages last edited\n" | |
| f"on {day} are labelled 4.0. The configuration change was merged {sw['merged_utc']} UTC and deployed\n" | |
| f"by {sw['synced_by_utc']} UTC ([Gerrit change]({sw['gerrit']}), [{sw['phabricator'].rsplit('/', 1)[1]}]({sw['phabricator']});\n" | |
| f"the deployment time was read by the rights audit, not re-read), so {k} of those {n} were last edited before it.\n" | |
| f"The rule is `license_for_revision` in `src/rights.py`, tested at the cutoff second, across time\n" | |
| f"zones, and on a missing timestamp, which stops the build. v0.2.0-v0.2.5 labelled every row `{before}`." | |
| ) | |
| def datasheet(out: Path, data_dir: Path, key: str) -> None: | |
| """data/<key>/<key>.md from the stats, build record and licence evidence (custom_datasheet in sources.py).""" | |
| site = SITES[key] | |
| st, build, ev = (load(data_dir / f"{key}.{n}.json") for n in ("stats", "build", "license-evidence")) | |
| scope, prep, file = ev["release_scope"], build["prepare"]["counts"], build["file"] | |
| before, after = ev["cutoff"]["before"], ev["cutoff"]["after"] | |
| kept, tok = st["kept"], st["tokens"] | |
| table = "\n".join( | |
| f"| {when} | `{lab}` | {scope['labels'].get(lab, 0):,} | {scope['tokens'].get(lab, 0):,} | {share(scope['tokens'].get(lab, 0), tok)} |" | |
| for when, lab in ((f"before {ev['cutoff']['boundary_day']['day']}", before), (f"{ev['cutoff']['boundary_day']['day']} or later", after))) | |
| labels = "\n".join(f"| `{lab}` | {scope['labels'].get(lab, 0):,} |" for lab in (before, after)) | |
| v_docs, v_chars, v_tokens = site["v025"] | |
| same = (kept, st["chars"], tok) == (v_docs, v_chars, v_tokens) | |
| n_dropped = prep.get("dropped_page", 0) | |
| v025 = ("The same text set as v0.2.5: documents, characters and tokens are unchanged; only labels, ids, authors and dates differ." | |
| if same else f"v0.2.5 had {v_docs:,} documents, {v_chars:,} characters and {v_tokens:,} tokens" | |
| + (f"; the difference is the {n_dropped:,} pages withheld by the rights review." if n_dropped else ".")) | |
| same_set = "the text set is the same" + (" except for the withheld pages" if n_dropped else "") | |
| old = scope["last_edited_before_era_end"] | |
| if "SA" in after: | |
| era = (f"{old['docs']:,} documents ({old['tokens']:,} tokens, {share(old['tokens'], tok)}) were last edited before {old['date']}, when the Wikimedia sites\n" | |
| f"began dual licensing under CC BY-SA 3.0 and the GFDL. Text first contributed before the 2009 move was\n" | |
| f"under the GFDL only. They are labelled `{before}`, so only the CC BY-SA grant is relied on; the count is recorded, not acted on.") | |
| else: | |
| era = (f"The terms page puts articles created before {old['date']} in the public domain. The dump has only the date of the last\n" | |
| f"revision, so how many released articles were created then is not known; {old['docs']:,} ({old['tokens']:,} tokens) were last edited before it.\n" | |
| f"All rows carry a CC BY label; nothing is dropped or relabelled for this.") | |
| review = "" | |
| if (path := data_dir / f"{key}.gfdl-review.json").exists(): | |
| r = load(path) | |
| review = f"\n\n{r['summary']} Per-document notes: `{path.name}`." | |
| skipped = [f"{prep.get('ns0_redirect', 0):,} redirects", f"{prep.get('ns0_empty', 0):,} empty pages", | |
| f"{prep.get('ns0_strip_error', 0):,} parser failures", f"{prep.get('ns0_short', 0):,} shorter than {MIN_CHARS} characters"] | |
| chain = (f"{prep['pages']:,} pages scanned → {prep['ns0']:,} in namespace 0 → " + ", ".join(skipped) + " skipped" | |
| + (f", {prep['exact_duplicate']:,} exact duplicates dropped" if prep.get("exact_duplicate") else ", no exact duplicates") | |
| + (f", {n_dropped:,} pages withheld by the rights review (`DROPPED_PAGES` in `src/rights.py`; ids, titles and reasons in `{key}.build.json`)" | |
| if n_dropped else "") | |
| + f" → {prep['written']:,} read by the build → {kept:,} released.") | |
| terms = "; ".join(f"[{t['title']}]({t['url']})" for t in ev["terms"]) | |
| with (data_dir / f"{key}.attribution.jsonl").open(encoding="utf-8") as fh: | |
| example = min((json.loads(next(fh))["url"] for _ in range(200)), key=len) # a short real URL | |
| created = scope["created_range"] | |
| when = ev["checked_at"] | |
| (data_dir / f"{key}.md").write_text(f"""# {key} | |
| {site['pretty']} | |
| ## Dataset description | |
| - **Source (upstream):** {build['dump_base']}/ | |
| - **Domain:** {site['domain']} | |
| - **Language:** Polish (pl) | |
| - **License:** `{before}` or `{after}` per record (by last-revision date) | |
| - **Created (range):** {created[0]}, {created[1]} (date of the page's last revision in the dump) | |
| - **Added:** {SOURCES[key]['added']}; rebuilt {when} (UTC) from the official Wikimedia dump | |
| ## Licensing — traceable basis | |
| Contributors' text on {site['host']} is licensed {site['family']}: {terms} (read {when} UTC). The site licence | |
| (`rightsinfo`) reads "{ev['site_licence']['rightsinfo']['text']}". Each row is labelled by its page's last revision in the dump: | |
| | last revision (UTC) | `license` | documents | tokens | share of tokens | | |
| |---|---|---:|---:|---:| | |
| {table} | |
| {licensing_text(key, ev)} | |
| {era}{review} | |
| Evidence: `{key}.license-evidence.json`. | |
| ## Attribution | |
| Each row's `author` is `{site['author']}, <page URL>`, e.g. | |
| `{site['author']}, {example}`. The page history names the contributors; {ATTRIBUTION[key]} | |
| `{key}.attribution.jsonl` has one line per row: `id`, `pageid`, `revid` (the revision | |
| in the dump), `title`, `url`, `last_revision_at`, `license`. The row `id` is | |
| `{key}_<page id>` and `created` is the date of `last_revision_at`. | |
| The text is modified: wiki markup is converted to plain text (see Provenance). | |
| ## Provenance | |
| Parsed from the official Wikimedia dump `{file['name'][:-8]}` by | |
| `src/fetch_wikimedia.py`; the file ({file['size']:,} bytes, sha1 `{file['sha1']}`) was matched against the | |
| dump's `dumpstatus.json` and `sha1sums.txt` (`{key}.build.json`). v0.2.0-v0.2.5 used the same dump | |
| date; {same_set} (the rebuild adds the last-revision time). | |
| Articles (namespace 0) only. Redirects, empty pages and pages shorter than {MIN_CHARS} characters are skipped. | |
| Wikitext is converted with mwparserfromhell `strip_code(normalize=True, collapse=True)`, as in v0.2.5. | |
| Templates and comments are dropped. `<ref>` bodies, category links (`Kategoria:...`) and file-link | |
| options (`thumb|...`) are not removed and stay in the text; the wikipedia fetcher's `strip_article` | |
| removes them, this one does not, because that would change the text set. Of two pages with the same | |
| text (sha1 of the stripped text), the lower page id is kept. | |
| {chain} | |
| ## Statistics | |
| | documents | characters | tokens (tiktoken proxy) | | |
| |---:|---:|---:| | |
| | {kept:,} | {st['chars']:,} | {tok:,} | | |
| {v025} | |
| ## Per-document license metadata | |
| | license | documents | | |
| |---|---:| | |
| {labels} | |
| Author metadata present for **{st['authors_with_value']:,}** documents. | |
| ## Filters applied (build_dynaword.py) | |
| - drop documents < 200 chars: **{st['drop_short']:,}** (the fetcher already dropped {prep.get('ns0_short', 0):,}) | |
| {card_line(st)} | |
| - exact cross-source dedup (sha1): **{st['drop_dup']:,}** | |
| - OCR alpha-ratio < 0.70 (OCR sources only): **{st['drop_ocr']:,}** | |
| - read {st['read']:,} → kept {kept:,} | |
| Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical | |
| Llama-3 count is computed at release. | |
| ## Not checked | |
| {NOT_CHECKED[key]} | |
| """, encoding="utf-8") | |
| print(f"{key}: datasheet written") | |
| ATTRIBUTION = { | |
| "wikinews": "the terms page asks for a link to the source article, which the URL gives.", | |
| "wikivoyage": "the Terms of Use (section 7b) accept a hyperlink or URL to the page as attribution.", | |
| "wikibooks": "the Terms of Use (section 7b) accept a hyperlink or URL to the page as attribution.", | |
| } | |
| NOT_CHECKED = { | |
| "wikinews": """- pastes from copyrighted sources, including articles copied from press agencies or other publishers (no sample was run) | |
| - the 2.5 → 4.0 label of pages edited after the cutoff (a reading of the site's terms page, not a lawyer's opinion; | |
| the lawyer's answer to E1, the wiki 3.0/4.0 labelling, is still pending, and whether it extends to 2.5 → 4.0 is not settled), | |
| and the time of day of the switch | |
| - how many released articles were created before 2005-09-25, the public-domain date in the terms page | |
| - text imported from elsewhere under another licence or with extra attribution requirements | |
| - quotations inside articles (Art. 29 of the Polish copyright act) | |
| - personal data (the NERGAL scrub runs before release)""", | |
| "wikivoyage": """- pastes from copyrighted sources (no sample was run) | |
| - the 3.0 → 4.0 label of pages edited after the cutoff (a reading of 3.0 §4(b)(ii), not a lawyer's opinion; | |
| the lawyer's answer to E1, the wiki 3.0/4.0 labelling, is still pending), and the time of day of the switch | |
| - text imported from elsewhere under another licence or with extra attribution requirements | |
| - text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual | |
| licensing; only the CC BY-SA grant is relied on | |
| - quotations inside articles (Art. 29 of the Polish copyright act) | |
| - personal data (the NERGAL scrub runs before release)""", | |
| } | |
| NOT_CHECKED["wikibooks"] = NOT_CHECKED["wikivoyage"] | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("step", choices=["acquire", "prepare", "attribution", "datasheet"]) | |
| ap.add_argument("--out", required=True, type=Path) | |
| ap.add_argument("--sources", nargs="+", default=list(SITES), choices=list(SITES)) | |
| ap.add_argument("--data-root", type=Path, default=Path(__file__).resolve().parent.parent / "data") | |
| a = ap.parse_args() | |
| a.out.mkdir(parents=True, exist_ok=True) | |
| for key in a.sources: | |
| data_dir = a.data_root / key | |
| {"acquire": lambda: acquire(a.out, key), "prepare": lambda: prepare(a.out, key), | |
| "attribution": lambda: attribution(a.out, data_dir, key), | |
| "datasheet": lambda: datasheet(a.out, data_dir, key)}[a.step]() | |
| if __name__ == "__main__": | |
| main() | |