Download src/fetch_wikimedia.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 77.6 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/refs%2Fpr%2F47/src/fetch_wikimedia.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword@refs/pr/47/src/fetch_wikimedia.py
-
curl -L -o fetch_wikimedia.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/refs%2Fpr%2F47/src/fetch_wikimedia.py
77.6 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. `strip` now also drops the category lines and | |
| file-link options strip_code leaves (slayerlabs/polish-dynaword-v2#116); `retext` applies that | |
| step to a committed release, so the pages-articles dump is not re-read. | |
| 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 | |
| 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=<history dir, never committed> | |
| python3 src/fetch_wikimedia.py retext --out $H --sources wikivoyage # v2#116, before compare; reads | |
| # $H/raw_dump/<the build's pages-articles dump> for WITHHELD_TEMPLATES (wikivoyage, wikibooks) | |
| python3 src/wiki_history.py download --dump plwikivoyage --out $H | |
| python3 src/wiki_history.py scan --stub $H/plwikivoyage-20261001-stub-meta-history.xml.gz \\ | |
| --sidecar wikivoyage=data/wikivoyage/wikivoyage.attribution.jsonl --out $H | |
| python3 src/wiki_history.py fetch --source wikivoyage --history $H/wikivoyage.history.jsonl --out $H | |
| python3 src/wiki_history.py compare --source wikivoyage --sidecar data/wikivoyage/wikivoyage.attribution.jsonl \\ | |
| --history $H/wikivoyage.history.jsonl --fetched $H/wikivoyage --parquet data/wikivoyage/wikivoyage.parquet \\ | |
| --out $H/wikivoyage.labels.jsonl | |
| python3 src/fetch_wikimedia.py relabel --out $H --sources wikivoyage | |
| python3 src/fetch_wikimedia.py datasheet --out $H --sources wikivoyage | |
| """ | |
| 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, IMPORT_TEMPLATES, WIKINEWS_BY_4_CUTOFF, WITHHELD_TEMPLATES, 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 | |
| } | |
| # The licence notice on the edit page: CC BY 2.5 in revision by_2_5 (2011-05-19), CC BY 4.0 from its | |
| # next revision by_4_0 at wiki_history.WIKIS["wikinews"]["window_end"] | |
| WIKINEWS_EDIT_NOTICE = {"page": "MediaWiki:Copyrightwarning", "by_2_5": 137136, "by_4_0": 342971, "read_at": "2026-10-18"} | |
| 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: the v0.2.5 builder's strip_code, then drop_residue. None when the parser fails.""" | |
| import mwparserfromhell | |
| try: | |
| return drop_residue(mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()) | |
| except Exception: # noqa: BLE001 parser failure drops the page, counted | |
| return None | |
| # What strip_code leaves of category and file links (slayerlabs/polish-dynaword-v2#116): a category | |
| # link becomes a line "Kategoria:X", a file link its options and caption ("thumb|250px|Caption"), | |
| # its options alone ("20px") or, with neither, its title ("File:X.ogg"). | |
| CATEGORY_LINE = re.compile(r"[ \t]*(?:[Kk]ategoria|[Cc]ategory)[ \t]*:[^\n]*") | |
| FILE_LINE = re.compile(r"[ \t]*(?:[Pp]lik|[Ff]ile|[Ii]mage|[Gg]rafika|[Mm]edia)[ \t]*:[^|\n]*\.[A-Za-z0-9]{2,4}[ \t]*") | |
| # options that are never prose on their own (sizes written so a long digit line does not backtrack) ... | |
| MARKUP = r"(?:thumb(?:nail)?|frameless|bezramki|upright(?:[= ]?[\d.]+)?|hochkant(?:=[\d.]+)?|(?:\d*x)?\d+ ?px)" | |
| # ... and words and key=values that are options only next to a pipe ("alt=..." alone can be a sentence about the option) | |
| WORDS = (r"|mały|mini|miniatura|framed?|ramka|border|right|left|cent(?:er|re)|none|prawo|lewo|centruj" | |
| r"|brak|links|rechts|droite|destra|sinistra|direita|skala(?:=[\d.]+)?") | |
| # a link target ends at the link's "]]", which strip_code drops: before a pipe it is bounded, at the end of a line | |
| # it may run on into the prose after the link ("70px|link=w:Polska (dziennik) opublikowała wczoraj ..."). There it | |
| # is a title of at most 8 words, else the line is prose and stays; "link= Nowa wersja" is an empty target before | |
| # prose. An alt text is a sentence either way | |
| OPTION = rf"(?:{MARKUP}|(?:alt|alternativtext)=[^|\n]*|(?:link|посилання|lang|page|class)=(?:[^|\s][^|\n]*)?{WORDS})" | |
| # ponytail: a word cap, not the real "]]"; the released targets have up to 6 words, the prose runs 14 and more | |
| OPTION_LAST = (rf"(?:{MARKUP}|(?:alt|alternativtext)=[^|\n]*" | |
| rf"|(?:link|посилання|lang|page|class)=(?:[^|\s]+(?:[ \t]+[^|\s]+){{0,7}})?{WORDS})") | |
| MARKUP_LINE = re.compile(rf"[ \t]*{MARKUP}[ \t]*") | |
| # the one option left of "[[Plik:X.jpg|mały]]"; each such line in the wikinews, wikivoyage and wikibooks releases | |
| # was one (checked against the shipped wikitext). Indented, it is a list item ("* mały" in a word list): prose | |
| POSITION = r"(?:right|left|cent(?:er|re))" | |
| LONE_OPTION_LINE = re.compile(rf"(?:mały|{POSITION})[ \t]*") | |
| PIPE = r"[ \t]*\|[ \t]*" # "thumb | 300px | Caption" is written too | |
| OPTIONS_LINE = re.compile(rf"[ \t]*(?:{OPTION}{PIPE})+{OPTION_LAST}?[ \t]*") # at least one pipe | |
| # before a caption; "||" is a table. The run's last option, a markup or position word, can be glued to the | |
| # caption by a space or a capital ("200px|right wieści", "65px|rightWitaj") | |
| OPTION_RUN = re.compile(rf"(?<![\w|])(?:{OPTION}{PIPE})+(?:link=[ \t]+)?(?:(?:{MARKUP}|{POSITION})(?:[ \t]+|(?=[A-ZĄĆĘŁŃÓŚŹŻ])))?(?!\|)") | |
| # after a caption, not after "||" or a table's "{|"; "| link=* http://..." is a list item (the Martwy link | |
| # template), not a link target | |
| TRAILING_OPTIONS = re.compile(rf"(?:[ \t]*(?<![|{{])\|[ \t]*{OPTION}(?=[ \t]*\|))*[ \t]*(?<![|{{])\|[ \t]*" | |
| rf"(?!(?:link|посилання|lang|page|class)=[ \t]*\*){OPTION_LAST}[ \t]*$") | |
| TEMPLATE_NS = re.compile(r"(?:szablon|template)[ \t]*:[ \t]*", re.I) | |
| def template_name(tpl) -> str: | |
| """A template's name as MediaWiki reads it: comments dropped, underscores and runs of spaces as one | |
| space, a "Szablon:"/"Template:" prefix in any case dropped, the first letter capitalised. | |
| "{{:Atrybucja}}" transcludes the article, not the template, so its name keeps the colon.""" | |
| name = " ".join(tpl.name.strip_code().replace("_", " ").split()) | |
| if m := TEMPLATE_NS.match(name): | |
| name = name[m.end():] | |
| return name[:1].upper() + name[1:] | |
| def withheld_template(key: str, wikitext: str) -> str | None: | |
| """The first WITHHELD_TEMPLATES[key] template the page transcludes, else None.""" | |
| names = WITHHELD_TEMPLATES[key] | |
| if not names: | |
| return None | |
| import mwparserfromhell | |
| for tpl in mwparserfromhell.parse(wikitext).filter_templates(recursive=True): | |
| if (name := template_name(tpl)) in names: | |
| return name | |
| return None | |
| # The templates kept as a page's `source_notes` (v2#110, 3B): where its text came from. Wikinews: the | |
| # imports (IMPORT_TEMPLATES); Wikibooks: the licence templates, not {{Licencja}}, which holds the author's | |
| # e-mail; Wikivoyage's ({{Atrybucja}}, {{Import}}) are on withheld pages only; the talk pages keep citations only | |
| # (clean_plwiki_talk.py provenance). Wikipedia has no entry: no shipped article carries such a template, and its | |
| # citations ship in a file of their own (fetch_wikipedia.py citations). | |
| SOURCE_NOTE_TEMPLATES = { | |
| "wikinews": frozenset(IMPORT_TEMPLATES["wikinews"]), | |
| "wikibooks": frozenset({"Cc-by-sa-3.0-tekst", "Cc-by-3.0-tekst", "GFDL-1.3-Cc-by-sa-3.0-tekst", "PD-tekst", | |
| "PD-ineligible-tekst", "GFDL-tekst", "Wikibooks:GNU Free Documentation License"}), | |
| "wikivoyage": frozenset(), | |
| "plwiki_talk": frozenset(), | |
| "plwiki_user_talk": frozenset(), | |
| } | |
| # Citation templates besides Cytuj*/Cite*, kept as `citations` when outside a <ref> ({{Źródło grafiki}} credits an image) | |
| CITATION_TEMPLATES = {"wikinews": frozenset({"Źródło", "Źródło PAP", "Źródło IAR"})} | |
| def page_sources(key: str, wikitext: str) -> tuple[list[str], list[str]]: | |
| """(citations, source_notes) of a page, as raw wikitext, each in page order without repeats. | |
| citations: the non-empty <ref> bodies, then the Cytuj*/Cite* (and CITATION_TEMPLATES[key]) templates | |
| outside a <ref>; source_notes: the SOURCE_NOTE_TEMPLATES[key] templates, wherever they are.""" | |
| import mwparserfromhell | |
| code = mwparserfromhell.parse(wikitext) | |
| notes = [str(t) for t in code.filter_templates(recursive=True) if template_name(t) in SOURCE_NOTE_TEMPLATES.get(key, ())] | |
| refs = [t for t in code.filter_tags(recursive=True) if str(t.tag).strip().lower() == "ref"] | |
| cites = [body for t in refs if (body := str(t.contents or "").strip())] | |
| for ref in refs: | |
| try: | |
| code.remove(ref) | |
| except ValueError: # inside a <ref> already removed | |
| pass | |
| extra = CITATION_TEMPLATES.get(key, frozenset()) | |
| cites += [str(t) for t in code.filter_templates(recursive=True) | |
| if (name := template_name(t)).startswith(("Cytuj", "Cite")) or name in extra] | |
| return list(dict.fromkeys(cites)), list(dict.fromkeys(notes)) | |
| # A licence as editors state it in {{Zaimportowany|licencja=…}}: "[http://…/by/2.5/pl/ CC-BY 2.5 PL]", "CC: BY 4.0", | |
| # "Creative Commons Uznanie Autorstwa 3.0 Polska", "CC-4.0 International" (every CC 4.0 licence has BY) | |
| _CC_URL = re.compile(r"creativecommons\.org/(?:licenses/(by(?:-sa)?)/(\d\.\d)/(pl/)?|publicdomain/zero/1\.0)", re.I) | |
| # Szablon:Przetłumaczony's own switch on `licencja` (default "cc-by 2.5"); anything else it shows as an unknown licence | |
| _TRANSLATED = {"cc-by 2.5": "CC-BY-2.5", "2.5": "CC-BY-2.5", "cc-by 4.0": "CC-BY-4.0", "4.0": "CC-BY-4.0"} | |
| def stated_license(statement: str) -> str | None: | |
| """The label of a licence statement: from its text, else, when the text names no version, from its | |
| creativecommons.org link. The text wins: 8 Wikinews pages link the 2.5 deed under the text "CC-BY 4.0". | |
| None when neither names one; an NC or ND licence fails.""" | |
| if re.search(r"\b(?:by-)?n[cd]\b|non-?commercial|no-?deriv", statement, re.I): | |
| raise ValueError(f"not an open licence: {statement!r}") | |
| text = re.sub(r"https?://\S+", " ", statement) | |
| if re.search(r"\bCC0\b", text, re.I): | |
| return "CC0-1.0" | |
| if m := re.search(r"\d\.\d", text): | |
| sa = "-SA" if re.search(r"\bBY[\s:-]*SA\b", text, re.I) else "" | |
| return f"CC-BY{sa}-{m[0]}" + ("-PL" if re.search(r"\b(?:PL|Polska)\b", text) else "") | |
| if m := _CC_URL.search(statement): | |
| return f"CC-{m[1].upper()}-{m[2]}" + ("-PL" if m[3] else "") if m[1] else "CC0-1.0" | |
| return None | |
| def import_licenses(key: str, notes: list[str]) -> list[str]: | |
| """The licences of the text a page imports (IMPORT_TEMPLATES[key]), read from its `source_notes`, in order | |
| without repeats. A template's own `licencja` wins over its partner's licence; {{Zaimportowany}} with no | |
| `licencja` argument is searched for a "licencja=" swallowed by the argument before it (a missing "|"). | |
| Fails when an import states no licence.""" | |
| import mwparserfromhell | |
| from wiki_history import LICENSE_URLS | |
| found = [] | |
| for note in notes: | |
| tpl = mwparserfromhell.parse(note).filter_templates(recursive=False)[0] | |
| if (name := template_name(tpl)) not in IMPORT_TEMPLATES.get(key, {}): | |
| continue | |
| arg = str(tpl.get("licencja").value).strip() if tpl.has("licencja") else "" | |
| if name == "Przetłumaczony": | |
| if (label := _TRANSLATED.get(arg.lower() or "cc-by 2.5")) is None: | |
| raise ValueError(f"{{{{Przetłumaczony}}}} with a licence it does not know: {arg!r}") | |
| elif not (label := stated_license(arg) if arg else IMPORT_TEMPLATES[key][name]): | |
| swallowed = re.search(r"\blicencja\s*=([^\n|}]*)", note) if not arg else None | |
| if not (label := swallowed and stated_license(swallowed[1])): | |
| raise ValueError(f"{{{{{name}}}}} states no licence: {note[:200]!r}") | |
| if label not in LICENSE_URLS: | |
| raise ValueError(f"{{{{{name}}}}}: no licence URL for {label}: {note[:200]!r}") | |
| found.append(label) | |
| return list(dict.fromkeys(found)) | |
| def with_imports(key: str, label: str, notes: list[str] | None) -> str: | |
| """`label` with the licences of imported text added after its own parts (" AND "), for a source with | |
| IMPORT_TEMPLATES; `notes` is the record's `source_notes`, None when `provenance` has not run.""" | |
| if key not in IMPORT_TEMPLATES: | |
| return label | |
| if notes is None: | |
| raise ValueError(f"{key}: a record has no source_notes; run `provenance` before relabel") | |
| return " AND ".join(dict.fromkeys(label.split(" AND ") + import_licenses(key, notes))) | |
| def shipped_pages(out: Path, key: str, build: dict, side: list[dict]): | |
| """(page id, wikitext) of each released page at its shipped revision, from the build's own pages-articles | |
| dump (out/raw_dump, checked by sha1). Fails on another revision or a page missing from the dump.""" | |
| src = out / "raw_dump" / build["file"]["name"] | |
| if sha1_file(src) != build["file"]["sha1"]: | |
| raise ValueError(f"{src} is not the build's dump (sha1 {build['file']['sha1']})") | |
| revid_of = {int(rec["pageid"]): int(rec["revid"]) for rec in side} | |
| found = set() | |
| with bz2.open(src, "rb") as fh: | |
| for pageid, revid, _ns, _title, _ts, _redirect, wikitext in pages(fh): | |
| if (page := int(pageid)) in revid_of: | |
| if int(revid) != revid_of[page]: | |
| raise ValueError(f"{key}_{page}: the dump has revision {revid}, the release {revid_of[page]}") | |
| found.add(page) | |
| yield page, wikitext | |
| if missing := revid_of.keys() - found: | |
| raise ValueError(f"{len(missing)} released pages are not in the dump, e.g. {key}_{min(missing)}") | |
| def template_holds(out: Path, key: str, build: dict, side: list[dict]) -> dict[int, str]: | |
| """{page id: template} for the released pages whose shipped revision carries a WITHHELD_TEMPLATES[key] template.""" | |
| if not WITHHELD_TEMPLATES[key]: | |
| return {} | |
| return {page: tpl for page, wikitext in shipped_pages(out, key, build, side) if (tpl := withheld_template(key, wikitext))} | |
| def provenance(out: Path, data_dir: Path, key: str) -> None: | |
| """Add each sidecar record's `citations` and `source_notes` (page_sources, v2#110 3B), read from the build's | |
| own dump at the shipped revision (shipped_pages), and update build.json's `attribution_sha256`. Run after | |
| retext and before relabel, which adds the imports' licences to the labels (with_imports).""" | |
| path = data_dir / f"{key}.attribution.jsonl" | |
| side = [json.loads(line) for line in path.open(encoding="utf-8")] | |
| build = load(data_dir / f"{key}.build.json") | |
| found = {page: page_sources(key, wikitext) for page, wikitext in shipped_pages(out, key, build, side)} | |
| for rec in side: | |
| rec["citations"], rec["source_notes"] = found[int(rec["pageid"])] | |
| path.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in side), encoding="utf-8") | |
| build["attribution_sha256"] = digest(path.read_bytes()) | |
| save(data_dir / f"{key}.build.json", build) | |
| print(f"{key}: {sum(bool(r['citations']) for r in side)} records with citations, " | |
| f"{sum(bool(r['source_notes']) for r in side)} with source notes, of {len(side)}") | |
| def withheld_pageids(prep: dict) -> set[int]: | |
| """The page ids a build record says the rights review withheld (DROPPED_PAGES and WITHHELD_TEMPLATES).""" | |
| return {int(p["pageid"]) for p in prep.get("dropped_pages", [])} | { | |
| int(p["pageid"]) for held in prep.get("withheld_by_template", {}).values() for p in held["pages"]} | |
| def _gap(m: re.Match) -> str: | |
| """A run glued to the text before it ("Offenburga.thumb|Zamek") leaves a space.""" | |
| return " " if m.start() and not m.string[m.start() - 1].isspace() else "" | |
| def _clean_line(line: str, rules) -> str | None: | |
| """The line without its file-link options, or None when a rule drops it or nothing is left. Repeats | |
| to a fixed point: two links on one line leave a line a rule drops ("left|150px right|150px" -> "150px", | |
| "File:X.jpg thumb| thumb|" -> "File:X.jpg"). Each pass that changes the line shortens it.""" | |
| while not any(r.fullmatch(line) for r in rules): | |
| new = TRAILING_OPTIONS.sub("", OPTION_RUN.sub(_gap, line)) | |
| if new == line: | |
| return line | |
| if not new.strip(): | |
| return None | |
| line = new | |
| return None | |
| def drop_residue(text: str, categories: bool = True) -> str: | |
| """`text` without category lines, bare file titles and file-link options; captions stay. A line | |
| left empty goes, and blank lines collapse as strip_code collapses them. `categories=False` keeps | |
| the category lines: on the talk pages they are discussion about categories (v2#116).""" | |
| # ponytail: options glued to a word ("Ladadikathumb|") stay; a run glued after a letter is prose too often to cut | |
| rules = (CATEGORY_LINE,) * categories + (FILE_LINE, MARKUP_LINE, LONE_OPTION_LINE, OPTIONS_LINE) | |
| text = "\n".join(new for line in text.split("\n") if (new := _clean_line(line, rules)) is not None) | |
| while "\n\n\n" in text: | |
| text = text.replace("\n\n\n", "\n\n") | |
| return text.strip() | |
| 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, the pages in | |
| DROPPED_PAGES[key] and those carrying a WITHHELD_TEMPLATES[key] template, 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, by_template, 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 | |
| if tpl := withheld_template(key, wikitext): | |
| by_template.setdefault(tpl, {"reason": WITHHELD_TEMPLATES[key][tpl], "pages": []})[ | |
| "pages"].append({"pageid": pageid, "title": title}) | |
| 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) | |
| counts["withheld_template"] = sum(len(held["pages"]) for held in by_template.values()) | |
| save(out / f"{key}.prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates, | |
| "dropped_pages": dropped, "withheld_by_template": dict(sorted(by_template.items()))}) | |
| 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") | |
| boundary, scope = release_scope(key, [rec for _, rec in rows], table) | |
| docs = scope["labels"] | |
| 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 {docs}") | |
| def label_totals(licenses, token_counts) -> tuple[dict, dict]: | |
| """(documents, tokens) per licence label.""" | |
| docs, tokens = Counter(), Counter() | |
| for lic, tok in zip(licenses, token_counts): | |
| docs[lic] += 1 | |
| tokens[lic] += tok | |
| return dict(docs), dict(tokens) | |
| def release_scope(key: str, recs: list[dict], table: dict) -> tuple[dict, dict]: | |
| """The evidence's `cutoff.boundary_day` and `release_scope` for the released rows: sidecar | |
| records and the parquet's id, created, license and token_count columns.""" | |
| site = SITES[key] | |
| docs, tokens = label_totals(table["license"], table["token_count"]) | |
| day = site["cutoff"].date().isoformat() # edits on the switch day are labelled `after` | |
| on_day = [rec["last_revision_at"] for rec in recs 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)}) | |
| tokens_of = dict(zip(table["id"], table["token_count"])) | |
| old = [rec["id"] for rec in recs if rec["last_revision_at"] < site["era_end"]] # recorded, not acted on | |
| return boundary, {"labels": docs, "tokens": tokens, "created_range": [min(table["created"]), max(table["created"])], | |
| "last_edited_before_era_end": {"date": site["era_end"], "docs": len(old), | |
| "tokens": sum(tokens_of[i] for i in old)}} | |
| def retext(out: Path, data_dir: Path, key: str) -> None: | |
| """Apply drop_residue (v2#116) to the committed text, as `strip` now does, without re-reading the | |
| dump: recount the changed rows' tokens and drop the rows that fall under MIN_CHARS, which a | |
| rebuild would skip as `ns0_short`, and the rows whose cleaned text repeats a lower page id's, | |
| which it would skip as `exact_duplicate`, from the parquet and the sidecar. A page added to | |
| DROPPED_PAGES[key] after the build, or carrying a WITHHELD_TEMPLATES[key] template (read from the | |
| build's dump in out/raw_dump), is withheld here first, as prepare would skip it, and the | |
| cleanup is measured on what remains. Updates stats, build.json (`prepare.counts`, `dropped_pages` | |
| and `withheld_by_template`, attribution rows and sha, `residue_cleanup`) and the evidence's cutoff day | |
| and release scope. Labels stay as they are: run wiki_history.py compare and `relabel` next. | |
| Rerunning changes nothing.""" | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| import tiktoken | |
| def path(name): | |
| return data_dir / f"{key}.{name}" | |
| table = pq.read_table(path("parquet")) | |
| side = [json.loads(line) for line in path("attribution.jsonl").open(encoding="utf-8")] | |
| build = load(path("build.json")) | |
| by_template = template_holds(out, key, build, side) | |
| dropped = DROPPED_PAGES[key] # wins over a template | |
| held = [rec for rec in side if int(rec["pageid"]) in dropped or int(rec["pageid"]) in by_template] | |
| if held: | |
| held_ids = {rec["id"] for rec in held} | |
| held_texts = [t for i, t in zip(table["id"].to_pylist(), table["text"].to_pylist()) if i in held_ids] | |
| table = table.filter(pa.array([i not in held_ids for i in table["id"].to_pylist()])) | |
| side = [rec for rec in side if rec["id"] not in held_ids] | |
| old = table["text"].to_pylist() | |
| new = [drop_residue(t) for t in old] | |
| changed = [i for i, (a, b) in enumerate(zip(old, new)) if a != b] | |
| if not changed and not held: | |
| print(f"{key}: text already clean") | |
| return | |
| if not changed: # the cleanup's before/after would still count the withheld pages | |
| raise ValueError(f"{key}: withholding {sorted(held_ids)} from a cleaned release; rerun retext on the uncleaned one") | |
| enc = tiktoken.get_encoding("cl100k_base") | |
| tokens = table["token_count"].to_pylist() | |
| for i in changed: | |
| tokens[i] = len(enc.encode_ordinary(new[i])) | |
| ids = table["id"].to_pylist() | |
| short = {i: len(t) for i, t in zip(ids, new) if len(t) < MIN_CHARS} | |
| pageid_of = {rec["id"]: int(rec["pageid"]) for rec in side} | |
| first, dup_of = {}, {} # cleaned rows that are now equal: the lowest page id keeps the text, as in prepare | |
| for n in sorted((n for n, i in enumerate(ids) if i not in short), key=lambda n: pageid_of[ids[n]]): | |
| if (k := text_key(new[n])) in first: | |
| dup_of[ids[n]] = first[k] | |
| else: | |
| first[k] = ids[n] | |
| if held and {text_key(drop_residue(t)) for t in held_texts} & set(first): # a rebuild would drop the copy | |
| raise ValueError(f"{key}: a cleaned text repeats a withheld page's; resolve it by hand") | |
| keep = [i not in short and i not in dup_of for i in ids] | |
| before = {"docs": len(old), "chars": sum(map(len, old)), "tokens": sum(table["token_count"].to_pylist())} | |
| groups = pq.ParquetFile(path("parquet")).metadata.row_group(0).num_rows # build_dynaword's batches, kept | |
| table = table.set_column(table.column_names.index("text"), "text", pa.array(new, pa.string())) | |
| table = table.set_column(table.column_names.index("token_count"), "token_count", pa.array(tokens, pa.int64())) | |
| table = table.filter(pa.array(keep)) | |
| pq.write_table(table, path("parquet"), compression="zstd", row_group_size=groups) | |
| gone = [rec for rec in side if rec["id"] in short] | |
| dups = [rec for rec in side if rec["id"] in dup_of] | |
| side = [rec for rec in side if rec["id"] not in short and rec["id"] not in dup_of] | |
| path("attribution.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in side), encoding="utf-8") | |
| cols = table.select(["id", "created", "license", "token_count"]).to_pydict() | |
| after = {"docs": table.num_rows, "chars": sum(len(t) for t in table["text"].to_pylist()), "tokens": sum(cols["token_count"])} | |
| stats = load(path("stats.json")) | |
| stats.update(read=stats["read"] - len(short) - len(dups) - len(held), kept=after["docs"], chars=after["chars"], tokens=after["tokens"], | |
| licenses=label_totals(cols["license"], cols["token_count"])[0], authors_with_value=after["docs"]) | |
| path("stats.json").write_text(json.dumps(stats, indent=2)) # build_dynaword's format | |
| counts = build["prepare"]["counts"] | |
| counts["ns0_short"] = counts.get("ns0_short", 0) + len(short) | |
| counts["exact_duplicate"] = counts.get("exact_duplicate", 0) + len(dups) | |
| by_page = [rec for rec in held if int(rec["pageid"]) in dropped] | |
| counts["dropped_page"] = counts.get("dropped_page", 0) + len(by_page) | |
| if len(by_page) < len(held): | |
| counts["withheld_template"] = counts.get("withheld_template", 0) + len(held) - len(by_page) | |
| counts["written"] -= len(short) + len(dups) + len(held) | |
| for rec in gone + dups + held: # prepare's per-row label is the last revision's | |
| counts[label(key, rec["last_revision_at"])] -= 1 | |
| build["prepare"]["exact_duplicate_pageids"] = sorted( | |
| build["prepare"].get("exact_duplicate_pageids", []) + [str(rec["pageid"]) for rec in dups], key=int) | |
| build["prepare"]["dropped_pages"] = build["prepare"].get("dropped_pages", []) + [ | |
| {"pageid": str(rec["pageid"]), "title": rec["title"], "reason": dropped[int(rec["pageid"])]} for rec in by_page] | |
| for rec in held: | |
| if int(rec["pageid"]) not in dropped: | |
| tpl = by_template[int(rec["pageid"])] | |
| build["prepare"].setdefault("withheld_by_template", {}).setdefault( | |
| tpl, {"reason": WITHHELD_TEMPLATES[key][tpl], "pages": []})["pages"].append( | |
| {"pageid": str(rec["pageid"]), "title": rec["title"]}) | |
| build.update(attribution_rows=len(side), attribution_sha256=digest(path("attribution.jsonl").read_bytes())) | |
| build["residue_cleanup"] = { | |
| "issue": "slayerlabs/polish-dynaword-v2#116", "step": "fetch_wikimedia.drop_residue", | |
| "rows_changed": len(changed), "before": before, "after": after, | |
| "dropped_short": [{"id": rec["id"], "title": rec["title"], "chars": short[rec["id"]]} for rec in gone], | |
| "dropped_duplicate": [{"id": rec["id"], "title": rec["title"], "duplicate_of": dup_of[rec["id"]]} for rec in dups], | |
| } | |
| save(path("build.json"), build) | |
| ev = load(path("license-evidence.json")) | |
| ev["cutoff"]["boundary_day"], ev["release_scope"] = release_scope(key, side, cols) | |
| save(path("license-evidence.json"), ev) | |
| print(f"{key}: {len(held)} withheld ({len(held) - len(by_page)} by template), {len(changed)} rows cleaned, {len(short)} dropped under {MIN_CHARS} chars, " | |
| f"{len(dups)} as duplicates, {before} -> {after}") | |
| def relabel(out: Path, data_dir: Path, key: str) -> None: | |
| """Label each committed row by contribution from out/<key>.labels.jsonl (wiki_history.py compare): | |
| text added before the cutoff keeps `before`, a page created after it is `after`, a page with | |
| text from both sides carries both ("<before> AND <after>"). Rewrites in place the parquet | |
| `license` column, the sidecar (wiki_history.apply_labels), stats `licenses` and `license`, | |
| build.json (`attribution_sha256`, `licence_labels`) and the licence evidence's labels and tokens. | |
| Text, ids and every other column are unchanged; rerunning changes nothing.""" | |
| from wiki_history import WIKIS | |
| site = SITES[key] | |
| docs, tokens = write_labels(out, data_dir, key, site["wiki"], site["cutoff"]) | |
| path = data_dir / f"{key}.license-evidence.json" | |
| ev = load(path) | |
| ev["license"] = (f"{site['before']}, {site['after']} or both per record, by contribution date" | |
| + ", plus the licence of imported text" * (len(label_order(site["before"], site["after"], docs)) > 3)) | |
| ev["review_scope"] = f"licence of contributors' text on {site['host']} and its version per contribution; not independent legal advice" | |
| ev["release_scope"].update(labels=docs, tokens=tokens) | |
| if "window_end" in (cfg := WIKIS[key]): # wikinews: `cutoff.at` is prepare's last-revision day, the labels use the window | |
| note = WIKINEWS_EDIT_NOTICE | |
| ev["cutoff"]["by_contribution"] = { | |
| "before_until": cfg["cutoff"], "after_from": cfg["window_end"], "in_between": f"{site['before']} AND {site['after']}", | |
| "edit_notice": {**note, **{k: f"https://{site['host']}/w/index.php?oldid={note[k]}" for k in ("by_2_5", "by_4_0")}}} | |
| save(path, ev) | |
| print(f"{key}: relabelled, {docs}") | |
| def write_labels(out: Path, data_dir: Path, key: str, wiki: str, cutoff) -> tuple[dict, dict]: | |
| """relabel's rewrite of the parquet, sidecar, stats and build record, shared with | |
| fetch_wikipedia.py relabel; `wiki` names the stub dump, `cutoff` is the licence switch. | |
| Returns (documents, tokens) per label.""" | |
| import pyarrow.parquet as pq | |
| from wiki_history import STUB_DATE, apply_labels | |
| def path(name): | |
| return data_dir / f"{key}.{name}" | |
| side = [json.loads(line) for line in path("attribution.jsonl").open(encoding="utf-8")] | |
| build = load(path("build.json")) | |
| withheld = withheld_pageids(build.get("prepare", {})) # labelled before the rights review withheld them | |
| labels = [lab for line in (out / f"{key}.labels.jsonl").open(encoding="utf-8") | |
| if int((lab := json.loads(line))["pageid"]) not in withheld] | |
| notes = {rec["id"]: rec.get("source_notes") for rec in side} | |
| for lab in labels: # v2#110 2A: imported text keeps its own licence; a label of no row fails in apply_labels | |
| lab["license"] = with_imports(key, lab["license"], notes.get(lab["id"], [])) | |
| table = apply_labels(pq.read_table(path("parquet")), side, labels, key) | |
| 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) | |
| 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(licenses=docs, license=SOURCES[key]["license"]) | |
| path("stats.json").write_text(json.dumps(stats, indent=2)) # build_dynaword's format | |
| day = cutoff.date().isoformat() | |
| build["attribution_sha256"] = digest(path("attribution.jsonl").read_bytes()) | |
| build["licence_labels"] = { | |
| "stub": load(out / f"{wiki}-{STUB_DATE}-stub-meta-history.xml.gz.json"), | |
| "cases": dict(Counter(lab["case"] for lab in labels)), | |
| "created_on_cutoff_day": sum(lab["case"] == "created_after_cutoff" and lab["first_at"].startswith(day) for lab in labels), | |
| } | |
| save(path("build.json"), build) | |
| return docs, tokens | |
| 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; the per-contribution labels (v2#110) from the relabel step do not.\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 label_order(before: str, after: str, labels) -> list[str]: | |
| """The labels a card lists: the page's own (before, both, after), then those with an imported licence added (v2#110 2A).""" | |
| own = (before, f"{before} AND {after}", after) | |
| return [*own, *sorted(set(labels) - set(own))] | |
| def contribution_text(key: str, build: dict, ev: dict, tok: int, flagged: Counter) -> str: | |
| """The labels of a release relabelled by contribution, and how they were decided (also in | |
| data/wikipedia/wikipedia.md, which is written by hand). `flagged` counts the sidecar's `license_flags`.""" | |
| from wiki_history import CASES, CONVERTERS, WIKIS | |
| cfg, lab, scope, stub = WIKIS[key], build["licence_labels"], ev["release_scope"], build["licence_labels"]["stub"] | |
| before, after, day = cfg["before"], cfg["after"], cfg["cutoff"][:10] | |
| window = "window_end" in cfg # wikinews: the switch has a known start and end (v2#110, E3) | |
| module, convert = CONVERTERS[key] | |
| licence = {"before": before, "after": after, "mixed": f"{before} AND {after}"} | |
| rules = {**BASIS, "created_after_cutoff": "the page was created after the switch window"} if window else BASIS | |
| labels = "\n".join(f"| `{lic}` | {scope['labels'].get(lic, 0):,} | {scope['tokens'].get(lic, 0):,} | {share(scope['tokens'].get(lic, 0), tok)} |" | |
| for lic in label_order(before, after, scope["labels"])) | |
| imported = label_order(before, after, scope["labels"])[3:] | |
| stated = "the template's `licencja` argument when it has one, else " * (None in IMPORT_TEMPLATES.get(key, {}).values()) | |
| imports = (f""" | |
| A label longer than the page's own ({", ".join(f"`{lic}`" for lic in imported)}) adds the licence of text the page marks | |
| as taken from elsewhere or as under another licence: the template that says so is in the sidecar's `source_notes`, and | |
| the licence is {stated}the one `IMPORT_TEMPLATES` in `src/rights.py` gives that template (`import_licenses` in | |
| `src/fetch_wikimedia.py`). The `license_basis` table below gives each row's own label. | |
| """ if imported else "") | |
| basis = "\n".join(f"| `{case}` | `{licence[kind]}` | {lab['cases'].get(case, 0):,} | {rules[case]} |" | |
| for case, kind in CASES.items() if window or case != "created_in_switch_window") | |
| if window: | |
| cut, end = (cfg[k].replace("T", " ").rstrip("Z") for k in ("cutoff", "window_end")) | |
| rule = f"`{before}` before {cut} UTC, `{after}` after {end} UTC, both in between (see below)" | |
| since, prior, created_after = f"at or\nafter {cut} UTC", "that time", "the switch window" | |
| sw, note, host = ev["switch"], WIKINEWS_EDIT_NOTICE, SITES[key]["host"] | |
| tail = f"""The switch took most of a day. The site licence was changed to `{after}` by a configuration change merged at | |
| {cut} UTC and deployed by {sw['synced_by_utc']} UTC ([Gerrit change]({sw['gerrit']}), [{sw['phabricator'].rsplit('/', 1)[1]}]({sw['phabricator']}); the deployment | |
| time was read by the rights audit, not re-read). The licence notice on the edit page, `{note['page']}`, named | |
| CC BY 2.5 ([revision {note['by_2_5']}](https://{host}/w/index.php?oldid={note['by_2_5']})) until it was changed at {end} UTC ([revision {note['by_4_0']}](https://{host}/w/index.php?oldid={note['by_4_0']})). | |
| Text saved in between was offered under 2.5 while the site licence was 4.0 or being changed to it, so it is | |
| labelled with both: a page created then is `{licence['mixed']}` (`created_in_switch_window`), though its history | |
| cannot tell the two apart, and text added then to an older page makes that page `{licence['mixed']}` as any later | |
| addition does. Neither licence can stand in for the other: the [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/legalcode) legal code (§4(a)) has no | |
| clause that lets a work be licensed under a later version. The sidecar's `license_flags` marks the rows with a | |
| revision in the window (`edited_in_switch_window`, {flagged['edited_in_switch_window']:,}) and, of those, the rows whose shipped revision is in it | |
| (`shipped_in_switch_window`, {flagged['shipped_in_switch_window']:,}). | |
| v0.2.0-v0.2.5 labelled every row `{before}`; before this relabel, main labelled each row by its page's last | |
| revision alone (`{after}` from {day} 00:00 UTC).""" | |
| else: | |
| rule = f"`{before}` before {day}, `{after}` from that day" | |
| since, prior, created_after = f"on or\nafter {day}", "that day", "the cutoff" | |
| tail = f"""The Terms of Use give the day of the switch, not the time. The cutoff is midnight UTC, so revisions made on | |
| {day} itself count as `{after}`. Pages labelled `{after}` alone and created that day: {lab['created_on_cutoff_day']}. | |
| If the switch came later that day, their first edits may be 3.0 text under a 4.0 label. | |
| v0.2.0-v0.2.5 labelled every row `{before}`; before this relabel, main labelled each row by its page's last | |
| revision alone (`{after}` from {day}).""" | |
| return f"""Each contribution keeps the licence it was made under: {rule}. | |
| Each row is labelled by the contributions its text holds: | |
| | `license` | documents | tokens | share of tokens | | |
| |---|---:|---:|---:| | |
| {labels} | |
| {imports} | |
| A row labelled `{licence['mixed']}` holds text under each licence. It is not split by contribution; | |
| its page history tells the two apart. The basis of each label is the sidecar's `license_basis`: | |
| | `license_basis` | `license` | documents | rule | | |
| |---|---|---:|---| | |
| {basis} | |
| The page histories come from the stub dump `{stub['name']}` ({stub['size']:,} bytes, sha1 `{stub['sha1']}`, | |
| matched against its `dumpstatus.json`; revision metadata, no text). For each row shipped from a revision made {since}, the text of the page's last revision before {prior} (`pre_cutoff_revid`) was fetched from the | |
| MediaWiki API, converted with the same `{convert}` as the release and compared with the shipped text, whitespace | |
| folded. Where they differ, a word diff (Python `difflib`) counts the words the later edits added; any added | |
| word, however few, makes the row `{licence['mixed']}`. Text moved into a page created after {created_after} from an | |
| older page is not traced, so that page is `{after}` alone. `src/wiki_history.py` (`download`, `scan`, `fetch`, | |
| `compare`) does this; `src/{module}.py relabel` writes the labels. | |
| {tail}""" | |
| def links_text(host: str) -> str: | |
| """The cards' account of wiki_history.record_links (v2#110); the hand-written wikipedia and talk cards carry it too.""" | |
| return (f"Each line also gives `permalink` (`https://{host}/w/index.php?oldid=<revid>`, the shipped revision),\n" | |
| f"`history_url` (`https://{host}/w/index.php?curid=<pageid>&action=history`, the page history, which names\n" | |
| f"the contributors), `license_urls` (the deed of each licence in `license`) and `conversion` (how the text was made\n" | |
| f"from the wikitext, in one line). Neither link opens for a page deleted since.") | |
| # v2#110 E2, our assessment in our own words; the cards carry it where the sidecar has `citations` | |
| QUOTATIONS = ("Text quoted from other works is not under these licences. It is used under the quotation right\n" | |
| "(Art. 29 of the Polish copyright act), which holds while a quotation stays in its context with its\n" | |
| "author and source named. Each page is released as one record, not cut into quotations, and the\n" | |
| "footnotes and citation templates that name the sources are kept in `citations`.") | |
| def citations_sentence(key: str, n_cites: int) -> str: | |
| """The cards' account of what page_sources puts in `citations`; n_cites rows have any.""" | |
| cites = sorted(CITATION_TEMPLATES.get(key, ())) | |
| return (f"`citations` lists the page's source citations as wikitext: the non-empty `<ref>` bodies, then the\n" | |
| f"`Cytuj...`/`Cite...` templates{''.join(f', `{{{{{name}}}}}`' for name in cites)} outside them ({n_cites:,} rows have any).") | |
| def sources_text(key: str, side: list[dict]) -> str: | |
| """The cards' account of the sidecar's `citations` and `source_notes` (page_sources, v2#110 3B).""" | |
| shown =SOURCE_NOTE_TEMPLATES[key] - set(WITHHELD_TEMPLATES.get(key, ())) # a withheld page is in no row | |
| notes = ", ".join(f"`{{{{{name}}}}}`" for name in sorted(shown)) | |
| n_cites, n_notes = (sum(bool(rec[f]) for rec in side) for f in ("citations", "source_notes")) | |
| if notes: | |
| notes = (f"`source_notes` lists the templates\nthat say where text came from or under what licence: {notes} " | |
| f"({n_notes:,} rows have any).") | |
| elif WITHHELD_TEMPLATES.get(key): | |
| notes = ("`source_notes` is an empty list on every row: the pages that\ncarry " | |
| + " or ".join(f"`{{{{{name}}}}}`" for name in WITHHELD_TEMPLATES[key]) | |
| + ", which say where text came from, are withheld (see Provenance).") | |
| else: # the talk pages (clean_plwiki_talk.py provenance keeps citations only) | |
| notes = "`source_notes` is an empty list on every row: notes on where text\ncame from are read on content pages only." | |
| return citations_sentence(key, n_cites) + " " + notes + " Each list is in page order, without repeats." | |
| 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). | |
| A release relabelled by contribution (`licence_labels` in build.json) gets those labels; until then, each | |
| row's label follows its page's last revision.""" | |
| 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"] | |
| with (data_dir / f"{key}.attribution.jsonl").open(encoding="utf-8") as fh: | |
| side = [json.loads(line) for line in fh] | |
| flagged = Counter(f for rec in side for f in rec.get("license_flags", [])) | |
| by_contribution = "licence_labels" in build | |
| if by_contribution: | |
| order = label_order(before, after, scope["labels"]) | |
| license_line = (f"`{before}`, `{after}` or both per record (by contribution date)" | |
| + ", plus the licence of imported text (see Licensing)" * (len(order) > 3)) | |
| labelled = contribution_text(key, build, ev, tok, flagged) | |
| fields = (f",\n`license_basis` (how the label was decided, see Licensing) and `pre_cutoff_revid` (the page's last revision\n" | |
| f"before the cutoff, null for a page created after it" | |
| + (" or edited after it and since deleted" * ("page_not_in_dump" in build["licence_labels"]["cases"])) | |
| + f"; its text is at `https://{site['host']}/w/index.php?oldid=<pre_cutoff_revid>`)" | |
| + (", and `license_flags`\n(the flags described in Licensing, when any apply)" * bool(flagged))) | |
| else: | |
| license_line = f"`{before}` or `{after}` per record (by last-revision date)" | |
| 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))) | |
| labelled = f"""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)}""" | |
| order, fields = (before, after), "" | |
| labels = "\n".join(f"| `{lab}` | {scope['labels'].get(lab, 0):,} |" for lab in order) | |
| v_docs, v_chars, v_tokens = site["v025"] | |
| same = (kept, st["chars"], tok) == (v_docs, v_chars, v_tokens) | |
| n_dropped, by_template = prep.get("dropped_page", 0), build["prepare"].get("withheld_by_template", {}) | |
| n_template = sum(len(held["pages"]) for held in by_template.values()) | |
| if n_template != prep.get("withheld_template", 0): | |
| raise ValueError(f"{key}: withheld_by_template lists {n_template} pages, prepare.counts says {prep.get('withheld_template', 0)}") | |
| clean = build.get("residue_cleanup") | |
| held = n_dropped + n_template | |
| why = [f"the {held:,} page{'s' * (held != 1)} withheld by the rights review"] * bool(held) + ["the residue cleanup"] * bool(clean) | |
| 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 {' and '.join(why)}{' (see Provenance)' * bool(clean)}." if why else ".")) | |
| same_set = ("the text set is the same except for " + " and ".join(why) + " described below" * bool(clean)) if why else "the text set is the same" | |
| if clean: | |
| b, gone, dups = clean["before"], clean["dropped_short"], clean.get("dropped_duplicate", []) | |
| conversion = f"""Wikitext is converted with mwparserfromhell `strip_code(normalize=True, collapse=True)`, as in v0.2.5, | |
| then `drop_residue` removes what that leaves of category and file links: `Kategoria:...` lines, bare file | |
| titles and file-link options (`thumb|250px|...`); captions stay ([v2#116](https://github.com/slayerlabs/polish-dynaword-v2/issues/116)). | |
| It was applied to the committed text (`fetch_wikimedia.py retext`): {clean['rows_changed']:,} rows changed, | |
| {b['chars'] - clean['after']['chars']:,} characters and {b['tokens'] - clean['after']['tokens']:,} tokens removed, and {len(gone)} pages that fell under {MIN_CHARS} | |
| characters were dropped{f", as {'was' if len(dups) == 1 else 'were'} {len(dups)} whose cleaned text repeated a lower page id's" * bool(dups)} (ids and titles in `{key}.build.json`). Templates and comments are dropped; `<ref>` | |
| bodies stay in the text (the wikipedia fetcher's `strip_article` removes them). Of two pages with the same text | |
| (sha1 of the stripped text), the lower page id is kept.""" | |
| else: | |
| conversion = """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.""" | |
| 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.") | |
| elif by_contribution: # wikinews, with the first revisions from the stub dump | |
| old_by = Counter(rec["license"] for rec in side if "created_before_cc_by_2_5" in rec.get("license_flags", [])) | |
| era = (f"The terms page puts articles created before {old['date']} in the public domain. {sum(old_by.values()):,} released rows are of pages created\n" | |
| f"before then (their first revision in the stub dump; `created_before_cc_by_2_5` in `license_flags`). The\n" | |
| f"public-domain statement is not relied on: they are labelled by contribution like the other rows (" | |
| + ", ".join(f"{n:,} `{lab}`" for lab, n in sorted(old_by.items())) + ").") | |
| 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.") | |
| links = "" | |
| if by_contribution and "permalink" in side[0]: # wiki_history.record_links (v2#110) | |
| links = "\n" + links_text(site["host"]) | |
| if n_old := flagged["created_before_cc_by_2_5"]: # wikinews (v2#110, E3) | |
| links += (f"\nThe history is the article's list of authors; it credits them on every row, the {n_old:,} rows of pages created\n" | |
| f"before {old['date']} included. No usernames are copied.") | |
| quotes = "" | |
| if "citations" in side[0]: # provenance (v2#110 3B) | |
| links += "\n" + sources_text(key, side) | |
| quotes = "\n\n" + QUOTATIONS | |
| 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:,} page{'s' * (n_dropped != 1)} withheld by the rights review (`DROPPED_PAGES` in `src/rights.py`; ids, titles and reasons in `{key}.build.json`)" | |
| if n_dropped else "") | |
| + (f", {n_template:,} pages withheld for a template they carry (`WITHHELD_TEMPLATES` in `src/rights.py`; ids and titles in `{key}.build.json`)" | |
| if n_template else "") | |
| + f" → {prep['written']:,} read by the build → {kept:,} released.") | |
| reasons: dict[str, list[str]] = {} # templates that share a reason (a redirect and its target) get one line | |
| for name, held in by_template.items(): | |
| reasons.setdefault(held["reason"], []).append(f"`{{{{{name}}}}}` ({len(held['pages']):,} pages)") | |
| chain += "".join(f"\n\nWithheld for {' and '.join(names)}. Reason: {reason}." for reason, names in reasons.items()) | |
| terms = "; ".join(f"[{t['title']}]({t['url']})" for t in ev["terms"]) | |
| example = min((rec["url"] for rec in side[: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:** {license_line} | |
| - **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']}". {labelled} | |
| {era}{review}{quotes} | |
| 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`{fields}. The row `id` is | |
| `{key}_<page id>` and `created` is the date of `last_revision_at`.{links} | |
| 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. | |
| {conversion} | |
| {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 tiktoken (cl100k) proxy; no Llama-3 count is published. | |
| ## Not checked | |
| {(NOT_CHECKED_BY_CONTRIBUTION if by_contribution else 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, an inference, not confirmed; | |
| the label here is by last revision; the per-contribution labels (v2#110) come from the relabel step), | |
| 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 v0.2.7)""", | |
| "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), an inference, not confirmed; | |
| the label here is by last revision; the per-contribution labels (v2#110) come from the relabel step), 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 v0.2.7)""", | |
| } | |
| NOT_CHECKED["wikibooks"] = NOT_CHECKED["wikivoyage"] | |
| # the card's rule for each wiki_history.CASES basis | |
| BASIS = { | |
| "shipped_before_cutoff": "the shipped revision predates the cutoff", | |
| "same_revision_text": "the shipped revision has the sha1 of the last pre-cutoff one in the stub dump (e.g. a revert)", | |
| "identical_text": "the last pre-cutoff revision converts to the shipped text, whitespace aside", | |
| "no_text_added": "later edits only removed words: the shipped words are a subsequence of the pre-cutoff ones", | |
| "created_after_cutoff": "the page has no revision before the cutoff", | |
| "created_in_switch_window": "the page was created in the switch window (see below)", | |
| "changed_after_cutoff": "later edits added at least one word", | |
| "page_not_in_dump": "the page is not in the stub dump (deleted since), so its history is not known", | |
| "pre_text_hidden": "the API returns no text for the last pre-cutoff revision (hidden or missing)", | |
| "pre_text_unparseable": "the last pre-cutoff revision does not convert", | |
| } | |
| NOT_CHECKED_BY_CONTRIBUTION = { | |
| "wikinews": """- pastes from copyrighted sources, including articles copied from press agencies or other publishers (no sample was run) | |
| - whether a small post-cutoff edit is a contribution of its own: any added word makes the row | |
| `CC-BY-2.5 AND CC-BY-4.0`, with no threshold | |
| - text moved or merged from an older page into a page created after the switch window (labelled `CC-BY-4.0` alone) | |
| - the public-domain statement for pages created before 2005-09-25 (not relied on, see Licensing) | |
| - what `drop_residue` leaves: file-link options glued to the word before them (`Profil trasythumb|...`) or | |
| after `||` (`mały||`), raw `<gallery>` file lines, flag icons in tables (`30px|`), category links inside | |
| a line, a link target that prose follows on its line (`link=w:Polska (dziennik) opublikowała...`, 3 rows), | |
| and `<ref>` bodies | |
| - text imported from elsewhere under another licence or with extra attribution requirements | |
| - whether each quotation inside articles stays within Art. 29 (see Licensing) | |
| - personal data (the NERGAL scrub runs before v0.2.7)""", | |
| "wikivoyage": """- pastes from copyrighted sources (no sample was run) | |
| - whether a small post-cutoff edit is a contribution of its own: any added word makes the row | |
| `CC-BY-SA-3.0 AND CC-BY-SA-4.0`, with no threshold | |
| - text moved or merged from an older page into a page created after the cutoff (labelled `CC-BY-SA-4.0` alone) | |
| - the time of day of the switch (see Licensing) | |
| - what `drop_residue` leaves: file-link options glued to the word before them (`Ladadikathumb|...`), category | |
| links inside a line of prose, and `<ref>` bodies | |
| - text imported from elsewhere on a page without `{{Atrybucja}}` or `{{Import}}` (the pages that carry them | |
| are withheld, see Provenance), 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 | |
| - whether each quotation inside articles stays within Art. 29 (see Licensing) | |
| - personal data (the NERGAL scrub runs before v0.2.7)""", | |
| "wikibooks": """- pastes from copyrighted sources beyond the 2026-10 sample (79 pages, and 90 more by one contributor) | |
| - whether a small post-cutoff edit is a contribution of its own: any added word makes the row | |
| `CC-BY-SA-3.0 AND CC-BY-SA-4.0`, with no threshold | |
| - text moved or merged from an older page into a page created after the cutoff (labelled `CC-BY-SA-4.0` alone) | |
| - the time of day of the switch (see Licensing) | |
| - what `drop_residue` leaves: file-link options glued to the word before them (`mthumb|...`), category links | |
| inside a line of prose, and `<ref>` bodies; and what it takes from a code table whose value reads as an option | |
| (`none` in `wikibooks_26200`, `ramka` in `wikibooks_24843`) | |
| - why Wikibooks has hidden the shipped revisions of `wikibooks_12937` and `wikibooks_13743` since the dump | |
| (no reason is logged; the same text is in their current public revisions) | |
| - text imported from elsewhere under another licence or with extra attribution requirements, beyond the | |
| documents that mention the GNU FDL (see Licensing) | |
| - 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 | |
| - of the 13 kept pages that state a GNU FDL grant or name a GFDL work they draw on: whether text from a GFDL | |
| work was added after 2008-11-01, and whether the upstream works had invariant sections or cover texts, | |
| either of which the 2009 relicensing excludes | |
| - whether each quotation inside books stays within Art. 29 (see Licensing) | |
| - personal data (the NERGAL scrub runs before v0.2.7)""", | |
| } | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("step", choices=["acquire", "prepare", "attribution", "retext", "provenance", "relabel", "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), | |
| "retext": lambda: retext(a.out, data_dir, key), "provenance": lambda: provenance(a.out, data_dir, key), | |
| "relabel": lambda: relabel(a.out, data_dir, key), | |
| "datasheet": lambda: datasheet(a.out, data_dir, key)}[a.step]() | |
| if __name__ == "__main__": | |
| main() | |