wikipedia: record links and a citations table (v2#110)
#148
by ppuzio - opened
- data/wikipedia/citations/wikipedia.citations.parquet +3 -0
- data/wikipedia/wikipedia.attribution.jsonl +2 -2
- data/wikipedia/wikipedia.build.json +47 -1
- data/wikipedia/wikipedia.md +19 -3
- src/fetch_wikimedia.py +12 -7
- src/fetch_wikipedia.py +103 -7
- src/takedown.py +15 -8
- src/test_takedown.py +33 -8
- src/test_wikipedia_contract.py +113 -3
- takedown/PROCEDURE.md +6 -4
data/wikipedia/citations/wikipedia.citations.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c667e5df36ab36eb7b812daa6f792c541d2023799b50157c6e3b9fc0d47e3fd3
|
| 3 |
+
size 542434598
|
data/wikipedia/wikipedia.attribution.jsonl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9929e5eccc2cdaa60b804bd9f6d0771a6c3518dfe4681101e29ecf163fe6464e
|
| 3 |
+
size 977918698
|
data/wikipedia/wikipedia.build.json
CHANGED
|
@@ -1,7 +1,53 @@
|
|
| 1 |
{
|
| 2 |
"attribution_rows": 1468647,
|
| 3 |
-
"attribution_sha256": "
|
| 4 |
"by_sa_4_cutoff": "2023-06-07T00:00:00+00:00",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"copyvio_tagged": [
|
| 6 |
{
|
| 7 |
"pageid": "3581",
|
|
|
|
| 1 |
{
|
| 2 |
"attribution_rows": 1468647,
|
| 3 |
+
"attribution_sha256": "9929e5eccc2cdaa60b804bd9f6d0771a6c3518dfe4681101e29ecf163fe6464e",
|
| 4 |
"by_sa_4_cutoff": "2023-06-07T00:00:00+00:00",
|
| 5 |
+
"citations": {
|
| 6 |
+
"citations": 7476723,
|
| 7 |
+
"dumpstatus_url": "https://dumps.wikimedia.org/plwiki/20260901/dumpstatus.json",
|
| 8 |
+
"file": "citations/wikipedia.citations.parquet",
|
| 9 |
+
"issue": "slayerlabs/polish-dynaword-v2#110",
|
| 10 |
+
"rows": 1468647,
|
| 11 |
+
"rows_with_citations": 1165616,
|
| 12 |
+
"sha256": "c667e5df36ab36eb7b812daa6f792c541d2023799b50157c6e3b9fc0d47e3fd3",
|
| 13 |
+
"shards": [
|
| 14 |
+
{
|
| 15 |
+
"name": "plwiki-20260901-pages-meta-current1.xml-p1p187037.bz2",
|
| 16 |
+
"sha1": "2ba8aaceac41ab61745b254be74f5b178a950753",
|
| 17 |
+
"size": 250876720
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"name": "plwiki-20260901-pages-meta-current2.xml-p187038p564779.bz2",
|
| 21 |
+
"sha1": "29e56cb64d15138257c071d6aaca72b70fe6345c",
|
| 22 |
+
"size": 251907424
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"name": "plwiki-20260901-pages-meta-current3.xml-p564780p1199518.bz2",
|
| 26 |
+
"sha1": "73eb6a68a39bcd63793a136174b479aad251691f",
|
| 27 |
+
"size": 368007181
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"name": "plwiki-20260901-pages-meta-current4.xml-p1199519p2047892.bz2",
|
| 31 |
+
"sha1": "87ef59a7603a6269ec9223283a131c173cd3ab12",
|
| 32 |
+
"size": 498502596
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"name": "plwiki-20260901-pages-meta-current5.xml-p2047893p3462393.bz2",
|
| 36 |
+
"sha1": "7d4685c6a85878490b0c70cf4dfcf5c8e5190368",
|
| 37 |
+
"size": 739442045
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"name": "plwiki-20260901-pages-meta-current6.xml-p3462394p4962393.bz2",
|
| 41 |
+
"sha1": "d0dcce1c3222bb7747b4ea4e167611e5f4e791d4",
|
| 42 |
+
"size": 700902977
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"name": "plwiki-20260901-pages-meta-current6.xml-p4962394p6142332.bz2",
|
| 46 |
+
"sha1": "f775b611e6bdb8a0ecbc5f9896b1b52685d1f5b6",
|
| 47 |
+
"size": 690784561
|
| 48 |
+
}
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
"copyvio_tagged": [
|
| 52 |
{
|
| 53 |
"pageid": "3581",
|
data/wikipedia/wikipedia.md
CHANGED
|
@@ -100,6 +100,11 @@ to the sample's dropped rows. Of the other 97, 88 were deleted after a deletion
|
|
| 100 |
7 as duplicates, needless disambiguations, advertising, spam or nonsense, and 2 were deleted
|
| 101 |
for a history merge or a move and restored. They are kept: a quality call, not a rights one.
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
Evidence: `wikipedia.license-evidence.json`.
|
| 104 |
|
| 105 |
## Attribution
|
|
@@ -111,6 +116,17 @@ in the dump), `title`, `url`, `last_revision_at`, `license`,
|
|
| 111 |
`license_basis` (how the label was decided, see Licensing) and `pre_cutoff_revid` (the page's last revision
|
| 112 |
before the cutoff, null for a page created after it or edited after it and since deleted; its text is at `https://pl.wikipedia.org/w/index.php?oldid=<pre_cutoff_revid>`). The row `id` is
|
| 113 |
`wikipedia_<page id>` and `created` is the date of `last_revision_at`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
The text is modified: wiki markup is converted to plain text (see Provenance).
|
| 116 |
|
|
@@ -125,7 +141,7 @@ Articles (namespace 0) only. Redirects, empty pages and pages with a copyright-v
|
|
| 125 |
notice are skipped; pages listed in `COPIED_PAGES` or with a copyright `{{ek}}` reason are
|
| 126 |
dropped after the duplicate check, so a copy of their text on another page goes with them. Wikitext is converted with mwparserfromhell
|
| 127 |
`strip_code(normalize=True, collapse=True)`, as in the sibling Wikimedia builders, after
|
| 128 |
-
removing `<ref>` bodies, file and category links and behaviour switches (`__NOTOC__`).
|
| 129 |
Templates (infoboxes, navigation boxes), `<math>`, galleries and comments are dropped;
|
| 130 |
table cells stay as flattened text; section headings stay as their own line. Of two
|
| 131 |
pages with the same text (sha1 of the stripped text), the lower page id is kept.
|
|
@@ -186,7 +202,7 @@ Llama-3 count is computed at release.
|
|
| 186 |
requirements (Terms of Use, Re-use); notices kept in templates are removed by the conversion
|
| 187 |
- text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual
|
| 188 |
licensing; only the CC BY-SA grant is relied on
|
| 189 |
-
-
|
| 190 |
- deletion discussions and maintenance notices other than `{{NPA}}` and `{{ek}}`; their
|
| 191 |
reasons are not read, except the deletion logs above
|
| 192 |
- pages deleted from plwiki after the stub dump (2026-10-01), and other pages by the authors
|
|
@@ -194,4 +210,4 @@ Llama-3 count is computed at release.
|
|
| 194 |
- "Teatr Piosenki Młyn" (`wikipedia_4033410`), deleted for copyright on 2017-05-23 and recreated
|
| 195 |
by 2017-07-14: the released text was not compared with the deleted one (it is among the
|
| 196 |
88 deleted after a discussion in 2026)
|
| 197 |
-
- personal data (the NERGAL scrub runs before release)
|
|
|
|
| 100 |
7 as duplicates, needless disambiguations, advertising, spam or nonsense, and 2 were deleted
|
| 101 |
for a history merge or a move and restored. They are kept: a quality call, not a rights one.
|
| 102 |
|
| 103 |
+
Text quoted from other works is not under these licences. It is used under the quotation right
|
| 104 |
+
(Art. 29 of the Polish copyright act), which holds while a quotation stays in its context with its
|
| 105 |
+
author and source named. Each page is released as one record, not cut into quotations, and the
|
| 106 |
+
footnotes and citation templates that name the sources are kept in `citations`.
|
| 107 |
+
|
| 108 |
Evidence: `wikipedia.license-evidence.json`.
|
| 109 |
|
| 110 |
## Attribution
|
|
|
|
| 116 |
`license_basis` (how the label was decided, see Licensing) and `pre_cutoff_revid` (the page's last revision
|
| 117 |
before the cutoff, null for a page created after it or edited after it and since deleted; its text is at `https://pl.wikipedia.org/w/index.php?oldid=<pre_cutoff_revid>`). The row `id` is
|
| 118 |
`wikipedia_<page id>` and `created` is the date of `last_revision_at`.
|
| 119 |
+
Each line also gives `permalink` (`https://pl.wikipedia.org/w/index.php?oldid=<revid>`, the shipped revision),
|
| 120 |
+
`history_url` (`https://pl.wikipedia.org/w/index.php?curid=<pageid>&action=history`, the page history, which names
|
| 121 |
+
the contributors), `license_urls` (the deed of each licence in `license`) and `conversion` (how the text was made
|
| 122 |
+
from the wikitext, in one line). Neither link opens for a page deleted since.
|
| 123 |
+
The source citations are in `citations/wikipedia.citations.parquet`, a table of `id` and `citations` with the release's
|
| 124 |
+
rows in the same order and row groups. `citations` lists the page's source citations as wikitext: the non-empty `<ref>` bodies, then the
|
| 125 |
+
`Cytuj...`/`Cite...` templates outside them (1,165,616 rows have any). Each list is in page order, without repeats, and empty for a page
|
| 126 |
+
with none: 7,476,723 citations in all. They are read from the 7 pages-meta-current shards of the same 20260901 dump (names,
|
| 127 |
+
sizes and sha1 in `wikipedia.build.json` `citations`, each matched against `dumpstatus.json`), whose revision of
|
| 128 |
+
every row is the shipped `revid` with its `last_revision_at`. The table is in a folder of its own so that the
|
| 129 |
+
`data/*/*.parquet` file pattern (the README's dataset config, the scripts in `src`) does not read it as documents.
|
| 130 |
|
| 131 |
The text is modified: wiki markup is converted to plain text (see Provenance).
|
| 132 |
|
|
|
|
| 141 |
notice are skipped; pages listed in `COPIED_PAGES` or with a copyright `{{ek}}` reason are
|
| 142 |
dropped after the duplicate check, so a copy of their text on another page goes with them. Wikitext is converted with mwparserfromhell
|
| 143 |
`strip_code(normalize=True, collapse=True)`, as in the sibling Wikimedia builders, after
|
| 144 |
+
removing `<ref>` bodies (kept in the citations table, see Attribution), file and category links and behaviour switches (`__NOTOC__`).
|
| 145 |
Templates (infoboxes, navigation boxes), `<math>`, galleries and comments are dropped;
|
| 146 |
table cells stay as flattened text; section headings stay as their own line. Of two
|
| 147 |
pages with the same text (sha1 of the stripped text), the lower page id is kept.
|
|
|
|
| 202 |
requirements (Terms of Use, Re-use); notices kept in templates are removed by the conversion
|
| 203 |
- text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual
|
| 204 |
licensing; only the CC BY-SA grant is relied on
|
| 205 |
+
- whether each quotation inside articles stays within Art. 29 (see Licensing)
|
| 206 |
- deletion discussions and maintenance notices other than `{{NPA}}` and `{{ek}}`; their
|
| 207 |
reasons are not read, except the deletion logs above
|
| 208 |
- pages deleted from plwiki after the stub dump (2026-10-01), and other pages by the authors
|
|
|
|
| 210 |
- "Teatr Piosenki Młyn" (`wikipedia_4033410`), deleted for copyright on 2017-05-23 and recreated
|
| 211 |
by 2017-07-14: the released text was not compared with the deleted one (it is among the
|
| 212 |
88 deleted after a discussion in 2026)
|
| 213 |
+
- personal data, in the text and in the citations (the NERGAL scrub runs before release)
|
src/fetch_wikimedia.py
CHANGED
|
@@ -223,7 +223,8 @@ def withheld_template(key: str, wikitext: str) -> str | None:
|
|
| 223 |
# The templates kept as a page's `source_notes` (v2#110, 3B): where its text came from. Wikinews: the
|
| 224 |
# imports (IMPORT_TEMPLATES); Wikibooks: the licence templates, not {{Licencja}}, which holds the author's
|
| 225 |
# e-mail; Wikivoyage's ({{Atrybucja}}, {{Import}}) are on withheld pages only; the talk pages keep citations only
|
| 226 |
-
# (clean_plwiki_talk.py provenance).
|
|
|
|
| 227 |
SOURCE_NOTE_TEMPLATES = {
|
| 228 |
"wikinews": frozenset(IMPORT_TEMPLATES["wikinews"]),
|
| 229 |
"wikibooks": frozenset({"Cc-by-sa-3.0-tekst", "Cc-by-3.0-tekst", "GFDL-1.3-Cc-by-sa-3.0-tekst", "PD-tekst",
|
|
@@ -242,7 +243,7 @@ def page_sources(key: str, wikitext: str) -> tuple[list[str], list[str]]:
|
|
| 242 |
outside a <ref>; source_notes: the SOURCE_NOTE_TEMPLATES[key] templates, wherever they are."""
|
| 243 |
import mwparserfromhell
|
| 244 |
code = mwparserfromhell.parse(wikitext)
|
| 245 |
-
notes = [str(t) for t in code.filter_templates(recursive=True) if template_name(t) in SOURCE_NOTE_TEMPLATES
|
| 246 |
refs = [t for t in code.filter_tags(recursive=True) if str(t.tag).strip().lower() == "ref"]
|
| 247 |
cites = [body for t in refs if (body := str(t.contents or "").strip())]
|
| 248 |
for ref in refs:
|
|
@@ -871,10 +872,16 @@ QUOTATIONS = ("Text quoted from other works is not under these licences. It is u
|
|
| 871 |
"footnotes and citation templates that name the sources are kept in `citations`.")
|
| 872 |
|
| 873 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
def sources_text(key: str, side: list[dict]) -> str:
|
| 875 |
"""The cards' account of the sidecar's `citations` and `source_notes` (page_sources, v2#110 3B)."""
|
| 876 |
-
|
| 877 |
-
shown = SOURCE_NOTE_TEMPLATES[key] - set(WITHHELD_TEMPLATES.get(key, ())) # a withheld page is in no row
|
| 878 |
notes = ", ".join(f"`{{{{{name}}}}}`" for name in sorted(shown))
|
| 879 |
n_cites, n_notes = (sum(bool(rec[f]) for rec in side) for f in ("citations", "source_notes"))
|
| 880 |
if notes:
|
|
@@ -886,9 +893,7 @@ def sources_text(key: str, side: list[dict]) -> str:
|
|
| 886 |
+ ", which say where text came from, are withheld (see Provenance).")
|
| 887 |
else: # the talk pages (clean_plwiki_talk.py provenance keeps citations only)
|
| 888 |
notes = "`source_notes` is an empty list on every row: notes on where text\ncame from are read on content pages only."
|
| 889 |
-
return (
|
| 890 |
-
f"`Cytuj...`/`Cite...` templates{''.join(f', `{{{{{name}}}}}`' for name in cites)} outside them ({n_cites:,} rows have any). "
|
| 891 |
-
+ notes + " Each list is in page order, without repeats.")
|
| 892 |
|
| 893 |
|
| 894 |
def datasheet(out: Path, data_dir: Path, key: str) -> None:
|
|
|
|
| 223 |
# The templates kept as a page's `source_notes` (v2#110, 3B): where its text came from. Wikinews: the
|
| 224 |
# imports (IMPORT_TEMPLATES); Wikibooks: the licence templates, not {{Licencja}}, which holds the author's
|
| 225 |
# e-mail; Wikivoyage's ({{Atrybucja}}, {{Import}}) are on withheld pages only; the talk pages keep citations only
|
| 226 |
+
# (clean_plwiki_talk.py provenance). Wikipedia has no entry: no shipped article carries such a template, and its
|
| 227 |
+
# citations ship in a file of their own (fetch_wikipedia.py citations).
|
| 228 |
SOURCE_NOTE_TEMPLATES = {
|
| 229 |
"wikinews": frozenset(IMPORT_TEMPLATES["wikinews"]),
|
| 230 |
"wikibooks": frozenset({"Cc-by-sa-3.0-tekst", "Cc-by-3.0-tekst", "GFDL-1.3-Cc-by-sa-3.0-tekst", "PD-tekst",
|
|
|
|
| 243 |
outside a <ref>; source_notes: the SOURCE_NOTE_TEMPLATES[key] templates, wherever they are."""
|
| 244 |
import mwparserfromhell
|
| 245 |
code = mwparserfromhell.parse(wikitext)
|
| 246 |
+
notes = [str(t) for t in code.filter_templates(recursive=True) if template_name(t) in SOURCE_NOTE_TEMPLATES.get(key, ())]
|
| 247 |
refs = [t for t in code.filter_tags(recursive=True) if str(t.tag).strip().lower() == "ref"]
|
| 248 |
cites = [body for t in refs if (body := str(t.contents or "").strip())]
|
| 249 |
for ref in refs:
|
|
|
|
| 872 |
"footnotes and citation templates that name the sources are kept in `citations`.")
|
| 873 |
|
| 874 |
|
| 875 |
+
def citations_sentence(key: str, n_cites: int) -> str:
|
| 876 |
+
"""The cards' account of what page_sources puts in `citations`; n_cites rows have any."""
|
| 877 |
+
cites = sorted(CITATION_TEMPLATES.get(key, ()))
|
| 878 |
+
return (f"`citations` lists the page's source citations as wikitext: the non-empty `<ref>` bodies, then the\n"
|
| 879 |
+
f"`Cytuj...`/`Cite...` templates{''.join(f', `{{{{{name}}}}}`' for name in cites)} outside them ({n_cites:,} rows have any).")
|
| 880 |
+
|
| 881 |
+
|
| 882 |
def sources_text(key: str, side: list[dict]) -> str:
|
| 883 |
"""The cards' account of the sidecar's `citations` and `source_notes` (page_sources, v2#110 3B)."""
|
| 884 |
+
shown =SOURCE_NOTE_TEMPLATES[key] - set(WITHHELD_TEMPLATES.get(key, ())) # a withheld page is in no row
|
|
|
|
| 885 |
notes = ", ".join(f"`{{{{{name}}}}}`" for name in sorted(shown))
|
| 886 |
n_cites, n_notes = (sum(bool(rec[f]) for rec in side) for f in ("citations", "source_notes"))
|
| 887 |
if notes:
|
|
|
|
| 893 |
+ ", which say where text came from, are withheld (see Provenance).")
|
| 894 |
else: # the talk pages (clean_plwiki_talk.py provenance keeps citations only)
|
| 895 |
notes = "`source_notes` is an empty list on every row: notes on where text\ncame from are read on content pages only."
|
| 896 |
+
return citations_sentence(key, n_cites) + " " + notes + " Each list is in page order, without repeats."
|
|
|
|
|
|
|
| 897 |
|
| 898 |
|
| 899 |
def datasheet(out: Path, data_dir: Path, key: str) -> None:
|
src/fetch_wikipedia.py
CHANGED
|
@@ -25,6 +25,10 @@ labels on the committed release; the pages-articles dump is not re-read. H=<hist
|
|
| 25 |
--history $H/wikipedia.history.jsonl --fetched $H/wikipedia --parquet data/wikipedia/wikipedia.parquet \\
|
| 26 |
--out $H/wikipedia.labels.jsonl
|
| 27 |
python3 src/fetch_wikipedia.py relabel --out $H # data/wikipedia; the card is edited by hand
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
from __future__ import annotations
|
| 30 |
|
|
@@ -54,6 +58,7 @@ DUMP_BASE = f"https://dumps.wikimedia.org/plwiki/{DUMP_DATE}"
|
|
| 54 |
DUMPSTATUS_URL = f"{DUMP_BASE}/dumpstatus.json"
|
| 55 |
SHA1SUMS_URL = f"{DUMP_BASE}/plwiki-{DUMP_DATE}-sha1sums.txt"
|
| 56 |
SHARD_RE = re.compile(r"plwiki-\d{8}-pages-articles\d+\.xml-p\d+p\d+\.bz2")
|
|
|
|
| 57 |
RIGHTSINFO_URL = ("https://pl.wikipedia.org/w/api.php?action=query&meta=siteinfo"
|
| 58 |
"&siprop=rightsinfo&format=json")
|
| 59 |
# WMF Terms of Use, revision in force from 2023-06-07 (sections 7(b)/7(c); history note).
|
|
@@ -176,15 +181,19 @@ def text_key(text: str) -> bytes:
|
|
| 176 |
return hashlib.sha1(text.strip().encode("utf-8")).digest()
|
| 177 |
|
| 178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
def discover(out: Path) -> None:
|
| 180 |
status = request_json(DUMPSTATUS_URL)
|
| 181 |
sums = {name: sha for sha, name in (line.split() for line in request(SHA1SUMS_URL).text.splitlines() if line.strip())}
|
| 182 |
job = status["jobs"]["articlesdump"]
|
| 183 |
if job.get("status") != "done":
|
| 184 |
raise ValueError(f"articlesdump not done: {job.get('status')}")
|
| 185 |
-
files =
|
| 186 |
-
|
| 187 |
-
key=lambda f: int(re.search(r"-p(\d+)p", f["name"]).group(1)))
|
| 188 |
if not files:
|
| 189 |
raise ValueError("no pages-articles shards")
|
| 190 |
for f in files:
|
|
@@ -402,8 +411,8 @@ def withhold(data_dir: Path) -> None:
|
|
| 402 |
print(f"{SOURCE}: nothing to withhold")
|
| 403 |
return
|
| 404 |
build = load(path("build.json"))
|
| 405 |
-
if "licence_labels" in build: # ponytail: relabel's
|
| 406 |
-
raise ValueError(f"{SOURCE}: withhold before relabel, then filter
|
| 407 |
held_ids = {rec["id"] for rec in held}
|
| 408 |
table = pq.read_table(path("parquet"))
|
| 409 |
table = table.filter(pc.invert(pc.is_in(table["id"], pa.array(sorted(held_ids)))))
|
|
@@ -453,9 +462,95 @@ def relabel(out: Path, data_dir: Path) -> None:
|
|
| 453 |
print(f"{SOURCE}: relabelled, {docs}")
|
| 454 |
|
| 455 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
def main() -> None:
|
| 457 |
ap = argparse.ArgumentParser()
|
| 458 |
-
ap.add_argument("step", choices=["discover", "acquire", "extract", "prepare", "attribution", "withhold", "relabel"
|
|
|
|
| 459 |
ap.add_argument("--out", required=True, type=Path)
|
| 460 |
ap.add_argument("--data-dir", type=Path, default=Path(__file__).resolve().parent.parent / "data" / SOURCE)
|
| 461 |
ap.add_argument("--workers", type=int, default=8)
|
|
@@ -464,7 +559,8 @@ def main() -> None:
|
|
| 464 |
{"discover": lambda: discover(a.out), "acquire": lambda: acquire(a.out),
|
| 465 |
"extract": lambda: extract(a.out, a.workers), "prepare": lambda: prepare(a.out),
|
| 466 |
"attribution": lambda: attribution(a.out, a.data_dir), "withhold": lambda: withhold(a.data_dir),
|
| 467 |
-
"relabel": lambda: relabel(a.out, a.data_dir)
|
|
|
|
| 468 |
|
| 469 |
|
| 470 |
if __name__ == "__main__":
|
|
|
|
| 25 |
--history $H/wikipedia.history.jsonl --fetched $H/wikipedia --parquet data/wikipedia/wikipedia.parquet \\
|
| 26 |
--out $H/wikipedia.labels.jsonl
|
| 27 |
python3 src/fetch_wikipedia.py relabel --out $H # data/wikipedia; the card is edited by hand
|
| 28 |
+
|
| 29 |
+
Each row's source citations (v2#110, option A) are read from the same dump's pages-meta-current shards, which hold
|
| 30 |
+
the shipped revision of every page. M=<their dir, never committed>
|
| 31 |
+
python3 src/fetch_wikipedia.py citations --out $M # data/wikipedia/citations; build.json `citations`
|
| 32 |
"""
|
| 33 |
from __future__ import annotations
|
| 34 |
|
|
|
|
| 58 |
DUMPSTATUS_URL = f"{DUMP_BASE}/dumpstatus.json"
|
| 59 |
SHA1SUMS_URL = f"{DUMP_BASE}/plwiki-{DUMP_DATE}-sha1sums.txt"
|
| 60 |
SHARD_RE = re.compile(r"plwiki-\d{8}-pages-articles\d+\.xml-p\d+p\d+\.bz2")
|
| 61 |
+
META_CURRENT_RE = re.compile(r"plwiki-\d{8}-pages-meta-current\d+\.xml-p\d+p\d+\.bz2")
|
| 62 |
RIGHTSINFO_URL = ("https://pl.wikipedia.org/w/api.php?action=query&meta=siteinfo"
|
| 63 |
"&siprop=rightsinfo&format=json")
|
| 64 |
# WMF Terms of Use, revision in force from 2023-06-07 (sections 7(b)/7(c); history note).
|
|
|
|
| 181 |
return hashlib.sha1(text.strip().encode("utf-8")).digest()
|
| 182 |
|
| 183 |
|
| 184 |
+
def by_first_page(files: list[dict]) -> list[dict]:
|
| 185 |
+
"""Dump shards in page-id order (the first page id in each name)."""
|
| 186 |
+
return sorted(files, key=lambda f: int(re.search(r"-p(\d+)p", f["name"]).group(1)))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
def discover(out: Path) -> None:
|
| 190 |
status = request_json(DUMPSTATUS_URL)
|
| 191 |
sums = {name: sha for sha, name in (line.split() for line in request(SHA1SUMS_URL).text.splitlines() if line.strip())}
|
| 192 |
job = status["jobs"]["articlesdump"]
|
| 193 |
if job.get("status") != "done":
|
| 194 |
raise ValueError(f"articlesdump not done: {job.get('status')}")
|
| 195 |
+
files = by_first_page([{"name": name, "url": f"{DUMP_BASE}/{name}", "size": meta["size"], "sha1": meta["sha1"]}
|
| 196 |
+
for name, meta in job["files"].items() if SHARD_RE.fullmatch(name)])
|
|
|
|
| 197 |
if not files:
|
| 198 |
raise ValueError("no pages-articles shards")
|
| 199 |
for f in files:
|
|
|
|
| 411 |
print(f"{SOURCE}: nothing to withhold")
|
| 412 |
return
|
| 413 |
build = load(path("build.json"))
|
| 414 |
+
if "licence_labels" in build or "citations" in build: # ponytail: relabel's counts and the citations would keep them
|
| 415 |
+
raise ValueError(f"{SOURCE}: withhold before relabel and citations, then filter their output to the sidecar")
|
| 416 |
held_ids = {rec["id"] for rec in held}
|
| 417 |
table = pq.read_table(path("parquet"))
|
| 418 |
table = table.filter(pc.invert(pc.is_in(table["id"], pa.array(sorted(held_ids)))))
|
|
|
|
| 462 |
print(f"{SOURCE}: relabelled, {docs}")
|
| 463 |
|
| 464 |
|
| 465 |
+
def _shard_citations(job: tuple[Path, str, frozenset[str]]) -> dict[str, tuple[str, str, list[str]]]:
|
| 466 |
+
"""citations' work on one pages-meta-current shard: {pageid: (revid, timestamp, citations)} of the pages in `wanted`."""
|
| 467 |
+
from fetch_wikimedia import page_sources # not at the top: fetch_wikimedia imports this module
|
| 468 |
+
path, sha1, wanted = job
|
| 469 |
+
if sha1_file(path) != sha1:
|
| 470 |
+
raise ValueError(f"sha1 mismatch: {path.name}")
|
| 471 |
+
found = {}
|
| 472 |
+
with bz2.open(path, "rb") as fh:
|
| 473 |
+
for pageid, revid, _, _, timestamp, _, wikitext in pages(fh):
|
| 474 |
+
if pageid not in wanted:
|
| 475 |
+
continue
|
| 476 |
+
if pageid in found:
|
| 477 |
+
raise ValueError(f"page {pageid} twice in {path.name}")
|
| 478 |
+
found[pageid] = (revid, timestamp, page_sources(SOURCE, wikitext)[0])
|
| 479 |
+
return found
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def citations(dumps: Path, data_dir: Path, status: dict, workers: int) -> None:
|
| 483 |
+
"""citations/wikipedia.citations.parquet: `id` and `citations` (fetch_wikimedia.page_sources: the non-empty <ref>
|
| 484 |
+
bodies, then the Cytuj*/Cite* templates outside them, as wikitext) of every row, in the release's order, read from
|
| 485 |
+
the pages-meta-current shards in `dumps` that `status` (the dump's dumpstatus.json) lists, sha1-checked. A page
|
| 486 |
+
missing from them, or there at another revision or timestamp than the sidecar's, stops it. In a folder: the
|
| 487 |
+
release's `data/*/*.parquet` glob would read a parquet next to wikipedia.parquet as text rows. build.json
|
| 488 |
+
`citations` records the shards, counts and sha256; rerunning changes nothing."""
|
| 489 |
+
import pyarrow as pa
|
| 490 |
+
import pyarrow.parquet as pq
|
| 491 |
+
with (data_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as fh: # in page id order
|
| 492 |
+
meta = {rec["id"]: (str(rec["pageid"]), str(rec["revid"]), rec["last_revision_at"]) for rec in map(json.loads, fh)}
|
| 493 |
+
release = data_dir / f"{SOURCE}.parquet"
|
| 494 |
+
ids = pq.read_table(release, columns=["id"])["id"].to_pylist()
|
| 495 |
+
if len(ids) != len(meta) or meta.keys() != set(ids):
|
| 496 |
+
raise ValueError("the sidecar's ids are not the parquet's")
|
| 497 |
+
side = [(row_id, *meta[row_id]) for row_id in ids]
|
| 498 |
+
shards = by_first_page([{"name": name, "size": f["size"], "sha1": f["sha1"]}
|
| 499 |
+
for name, f in status["jobs"]["metacurrentdump"]["files"].items()
|
| 500 |
+
if META_CURRENT_RE.fullmatch(name)])
|
| 501 |
+
if not shards:
|
| 502 |
+
raise ValueError("no pages-meta-current shards in dumpstatus.json")
|
| 503 |
+
wanted, found = frozenset(pageid for _, pageid, _, _ in side), {}
|
| 504 |
+
with ProcessPoolExecutor(max_workers=workers) as pool:
|
| 505 |
+
for part in pool.map(_shard_citations, [(dumps / f["name"], f["sha1"], wanted) for f in shards]):
|
| 506 |
+
if twice := found.keys() & part.keys():
|
| 507 |
+
raise ValueError(f"pages in two shards: {sorted(twice)[:5]}")
|
| 508 |
+
found.update(part)
|
| 509 |
+
bad = []
|
| 510 |
+
for row_id, pageid, revid, at in side:
|
| 511 |
+
if pageid not in found:
|
| 512 |
+
bad.append(f"{row_id}: not in the dump")
|
| 513 |
+
elif found[pageid][:2] != (revid, at):
|
| 514 |
+
bad.append(f"{row_id}: the dump has revision {found[pageid][0]} at {found[pageid][1]}")
|
| 515 |
+
if bad:
|
| 516 |
+
raise ValueError(f"{len(bad)} rows do not match the dump: {bad[:5]}")
|
| 517 |
+
path = data_dir / "citations" / f"{SOURCE}.citations.parquet"
|
| 518 |
+
path.parent.mkdir(exist_ok=True)
|
| 519 |
+
schema = pa.schema([("id", pa.string()), ("citations", pa.list_(pa.string()))])
|
| 520 |
+
group = pq.ParquetFile(release).metadata.row_group(0).num_rows # the release's row groups, so row n is row n in both
|
| 521 |
+
with pq.ParquetWriter(path, schema, compression="zstd") as writer:
|
| 522 |
+
for start in range(0, len(side), group): # a group at a time: one string array caps at 2 GiB
|
| 523 |
+
rows = side[start:start + group]
|
| 524 |
+
writer.write_table(pa.table([[r[0] for r in rows], [found[r[1]][2] for r in rows]], schema=schema),
|
| 525 |
+
row_group_size=group)
|
| 526 |
+
cites = [found[pageid][2] for _, pageid, _, _ in side]
|
| 527 |
+
build = load(data_dir / f"{SOURCE}.build.json")
|
| 528 |
+
build["citations"] = {
|
| 529 |
+
"issue": "slayerlabs/polish-dynaword-v2#110", "file": path.relative_to(data_dir).as_posix(),
|
| 530 |
+
"dumpstatus_url": DUMPSTATUS_URL, "shards": shards, "rows": len(cites),
|
| 531 |
+
"rows_with_citations": sum(map(bool, cites)), "citations": sum(map(len, cites)), "sha256": digest(path.read_bytes()),
|
| 532 |
+
}
|
| 533 |
+
save(data_dir / f"{SOURCE}.build.json", build)
|
| 534 |
+
print(f"{SOURCE}: {build['citations']['rows_with_citations']} rows with {build['citations']['citations']} citations")
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def citations_text(build: dict) -> str:
|
| 538 |
+
"""The card's account of the citations table (build.json `citations`); the card is edited by hand around it."""
|
| 539 |
+
from fetch_wikimedia import citations_sentence # not at the top: fetch_wikimedia imports this module
|
| 540 |
+
c = build["citations"]
|
| 541 |
+
return (f"The source citations are in `{c['file']}`, a table of `id` and `citations` with the release's\n"
|
| 542 |
+
f"rows in the same order and row groups. " + citations_sentence(SOURCE, c["rows_with_citations"])
|
| 543 |
+
+ f" Each list is in page order, without repeats, and empty for a page\nwith none: {c['citations']:,} citations in all. "
|
| 544 |
+
f"They are read from the {len(c['shards'])} pages-meta-current shards of the same {DUMP_DATE} dump (names,\n"
|
| 545 |
+
f"sizes and sha1 in `{SOURCE}.build.json` `citations`, each matched against `dumpstatus.json`), whose revision of\n"
|
| 546 |
+
f"every row is the shipped `revid` with its `last_revision_at`. The table is in a folder of its own so that the\n"
|
| 547 |
+
f"`data/*/*.parquet` file pattern (the README's dataset config, the scripts in `src`) does not read it as documents.")
|
| 548 |
+
|
| 549 |
+
|
| 550 |
def main() -> None:
|
| 551 |
ap = argparse.ArgumentParser()
|
| 552 |
+
ap.add_argument("step", choices=["discover", "acquire", "extract", "prepare", "attribution", "withhold", "relabel",
|
| 553 |
+
"citations"])
|
| 554 |
ap.add_argument("--out", required=True, type=Path)
|
| 555 |
ap.add_argument("--data-dir", type=Path, default=Path(__file__).resolve().parent.parent / "data" / SOURCE)
|
| 556 |
ap.add_argument("--workers", type=int, default=8)
|
|
|
|
| 559 |
{"discover": lambda: discover(a.out), "acquire": lambda: acquire(a.out),
|
| 560 |
"extract": lambda: extract(a.out, a.workers), "prepare": lambda: prepare(a.out),
|
| 561 |
"attribution": lambda: attribution(a.out, a.data_dir), "withhold": lambda: withhold(a.data_dir),
|
| 562 |
+
"relabel": lambda: relabel(a.out, a.data_dir),
|
| 563 |
+
"citations": lambda: citations(a.out, a.data_dir, request_json(DUMPSTATUS_URL), a.workers)}[a.step]()
|
| 564 |
|
| 565 |
|
| 566 |
if __name__ == "__main__":
|
src/takedown.py
CHANGED
|
@@ -9,11 +9,12 @@ when a row is added; takedown/register.md records every one.
|
|
| 9 |
python3 src/takedown.py row data/<k>/<k>.parquet <id> [<id> ...] # rows to append to the blocklist
|
| 10 |
python3 src/takedown.py apply [data/<k>/<k>.parquet ...] # default: every shard under data/
|
| 11 |
|
| 12 |
-
`apply` drops blocked rows from each shard
|
| 13 |
-
to it
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
"""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
|
@@ -182,14 +183,15 @@ def _refresh_checksums(sums: dict, rewritten: set[Path]) -> None:
|
|
| 182 |
|
| 183 |
|
| 184 |
def apply(paths: list[Path], bl: Blocklist | None = None) -> dict[Path, int]:
|
| 185 |
-
"""Drop blocked records from each shard
|
| 186 |
|
| 187 |
scan() starts worker processes, which on macOS re-run the calling script's top level:
|
| 188 |
call this from under `if __name__ == "__main__":`.
|
| 189 |
"""
|
| 190 |
bl = load() if bl is None else bl
|
| 191 |
sidecars = {p: sorted(p.parent.glob(f"{p.stem}.*.jsonl")) for p in paths}
|
| 192 |
-
|
|
|
|
| 193 |
if pointers:
|
| 194 |
raise RuntimeError(f"LFS pointers, run `git lfs pull` first: {[str(f) for f in pointers]}")
|
| 195 |
found = scan(paths, bl)
|
|
@@ -206,13 +208,18 @@ def apply(paths: list[Path], bl: Blocklist | None = None) -> dict[Path, int]:
|
|
| 206 |
elif how == "text":
|
| 207 |
print(f" ! {source}/{rec_id}: text matches a blocklisted record filed under another id or source. "
|
| 208 |
f"Blocklist row for it:\n{source}\t{rec_id}\t{key}")
|
| 209 |
-
# Attribution and decision lines carry no text: drop the ids just cut from the shard as well.
|
| 210 |
side_bl = bl if gone is None else Blocklist(bl.ids | {(source, i) for i in gone["id"].to_pylist()}, bl.hashes)
|
| 211 |
samples = 0
|
| 212 |
for f in sidecars[path]:
|
| 213 |
if n := _drop_lines(f, side_bl):
|
| 214 |
rewritten.add(f)
|
| 215 |
samples += n if f.name == f"{source}.sample.jsonl" else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
stats = path.with_name(f"{source}.stats.json")
|
| 217 |
if (gone is not None or samples) and stats.exists():
|
| 218 |
gone = gone if gone is not None else pq.read_schema(path).empty_table()
|
|
|
|
| 9 |
python3 src/takedown.py row data/<k>/<k>.parquet <id> [<id> ...] # rows to append to the blocklist
|
| 10 |
python3 src/takedown.py apply [data/<k>/<k>.parquet ...] # default: every shard under data/
|
| 11 |
|
| 12 |
+
`apply` drops blocked rows from each shard, from the <k>.*.jsonl files next
|
| 13 |
+
to it and from the <k>.*.parquet tables in a folder next to it (such as
|
| 14 |
+
citations/<k>.citations.parquet), subtracts them from <k>.stats.json and
|
| 15 |
+
refreshes <k>.checksums.json for the files it rewrote. build_dynaword.py runs
|
| 16 |
+
it on every shard it builds. A shard from any other builder needs an `apply`
|
| 17 |
+
before it is committed, and test_takedown.py fails until it has had one.
|
| 18 |
"""
|
| 19 |
from __future__ import annotations
|
| 20 |
|
|
|
|
| 183 |
|
| 184 |
|
| 185 |
def apply(paths: list[Path], bl: Blocklist | None = None) -> dict[Path, int]:
|
| 186 |
+
"""Drop blocked records from each shard, its sidecar files and its tables; return rows dropped per shard.
|
| 187 |
|
| 188 |
scan() starts worker processes, which on macOS re-run the calling script's top level:
|
| 189 |
call this from under `if __name__ == "__main__":`.
|
| 190 |
"""
|
| 191 |
bl = load() if bl is None else bl
|
| 192 |
sidecars = {p: sorted(p.parent.glob(f"{p.stem}.*.jsonl")) for p in paths}
|
| 193 |
+
tables = {p: sorted(p.parent.glob(f"*/{p.stem}.*.parquet")) for p in paths} # e.g. citations/<k>.citations.parquet
|
| 194 |
+
pointers = [f for p in paths for f in [p, *sidecars[p], *tables[p]] if is_lfs_pointer(f)]
|
| 195 |
if pointers:
|
| 196 |
raise RuntimeError(f"LFS pointers, run `git lfs pull` first: {[str(f) for f in pointers]}")
|
| 197 |
found = scan(paths, bl)
|
|
|
|
| 208 |
elif how == "text":
|
| 209 |
print(f" ! {source}/{rec_id}: text matches a blocklisted record filed under another id or source. "
|
| 210 |
f"Blocklist row for it:\n{source}\t{rec_id}\t{key}")
|
| 211 |
+
# Attribution and decision lines and the tables carry no text: drop the ids just cut from the shard as well.
|
| 212 |
side_bl = bl if gone is None else Blocklist(bl.ids | {(source, i) for i in gone["id"].to_pylist()}, bl.hashes)
|
| 213 |
samples = 0
|
| 214 |
for f in sidecars[path]:
|
| 215 |
if n := _drop_lines(f, side_bl):
|
| 216 |
rewritten.add(f)
|
| 217 |
samples += n if f.name == f"{source}.sample.jsonl" else 0
|
| 218 |
+
for f in tables[path]:
|
| 219 |
+
ids = pq.read_table(f, columns=["id"])["id"].to_pylist()
|
| 220 |
+
if drop := {n for n, rec_id in enumerate(ids) if (source, rec_id) in side_bl.ids}:
|
| 221 |
+
_drop_rows(f, drop)
|
| 222 |
+
rewritten.add(f)
|
| 223 |
stats = path.with_name(f"{source}.stats.json")
|
| 224 |
if (gone is not None or samples) and stats.exists():
|
| 225 |
gone = gone if gone is not None else pq.read_schema(path).empty_table()
|
src/test_takedown.py
CHANGED
|
@@ -38,6 +38,20 @@ def test_no_file_next_to_a_shard_holds_a_blocklisted_record():
|
|
| 38 |
assert hits == {}
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def _register_rows() -> list[list[str]]:
|
| 42 |
lines = REGISTER.read_text(encoding="utf-8").splitlines()
|
| 43 |
start = lines.index("| date | source | record id | reason class | action |") + 2
|
|
@@ -97,7 +111,7 @@ def _texts():
|
|
| 97 |
|
| 98 |
|
| 99 |
def _source(tmp_path):
|
| 100 |
-
"""data/demo with four records, the sidecar files a source ships, and their checksums."""
|
| 101 |
d = tmp_path / "data" / "demo"
|
| 102 |
d.mkdir(parents=True)
|
| 103 |
texts = _texts()
|
|
@@ -114,15 +128,22 @@ def _source(tmp_path):
|
|
| 114 |
encoding="utf-8")
|
| 115 |
(d / "demo.attribution.jsonl").write_text("".join(json.dumps({"id": i, "url": f"https://x/{i}"}) + "\n" for i in ids))
|
| 116 |
(d / "demo.md").write_text("# demo\n")
|
|
|
|
|
|
|
|
|
|
| 117 |
(d / "demo.stats.json").write_text(json.dumps({
|
| 118 |
"kept": 4, "tokens": 100, "chars": sum(map(len, texts)), "authors_with_value": 2,
|
| 119 |
"licenses": {"CC0": 3, "CC-BY-4.0": 1}, "sample_count": 2, "by_year": {"2020": 4},
|
| 120 |
}, indent=2))
|
| 121 |
-
sums = {f.name: hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(d.iterdir())}
|
| 122 |
(d / "demo.checksums.json").write_text(json.dumps(sums, indent=2) + "\n")
|
| 123 |
return d
|
| 124 |
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
def _blocklist():
|
| 127 |
texts = _texts()
|
| 128 |
return Blocklist(
|
|
@@ -140,6 +161,9 @@ def test_apply_drops_blocked_records_from_the_shard_and_every_sidecar(tmp_path,
|
|
| 140 |
assert pq.read_table(shard)["id"].to_pylist() == ["demo_1"]
|
| 141 |
assert [json.loads(ln)["id"] for ln in (d / "demo.sample.jsonl").read_text().splitlines()] == ["demo_1"]
|
| 142 |
assert [json.loads(ln)["id"] for ln in (d / "demo.attribution.jsonl").read_text().splitlines()] == ["demo_1"]
|
|
|
|
|
|
|
|
|
|
| 143 |
stats_raw = (d / "demo.stats.json").read_text()
|
| 144 |
assert not stats_raw.endswith("\n") # layout kept
|
| 145 |
assert json.loads(stats_raw) == {
|
|
@@ -157,21 +181,22 @@ def test_apply_drops_blocked_records_from_the_shard_and_every_sidecar(tmp_path,
|
|
| 157 |
def test_apply_is_a_no_op_once_applied(tmp_path):
|
| 158 |
d = _source(tmp_path)
|
| 159 |
takedown.apply([d / "demo.parquet"], _blocklist())
|
| 160 |
-
before =
|
| 161 |
assert takedown.apply([d / "demo.parquet"], _blocklist()) == {d / "demo.parquet": 0}
|
| 162 |
-
assert
|
| 163 |
|
| 164 |
|
| 165 |
def test_apply_leaves_a_clean_source_byte_for_byte(tmp_path):
|
| 166 |
d = _source(tmp_path)
|
| 167 |
-
before =
|
| 168 |
takedown.apply([d / "demo.parquet"], Blocklist(frozenset({("other", "x")}), frozenset({"0" * 64})))
|
| 169 |
-
assert
|
| 170 |
|
| 171 |
|
| 172 |
-
|
|
|
|
| 173 |
d = _source(tmp_path)
|
| 174 |
-
(d /
|
| 175 |
with pytest.raises(RuntimeError, match="git lfs pull"):
|
| 176 |
takedown.apply([d / "demo.parquet"], _blocklist())
|
| 177 |
|
|
|
|
| 38 |
assert hits == {}
|
| 39 |
|
| 40 |
|
| 41 |
+
def test_no_table_next_to_a_shard_holds_a_record_the_shard_lacks():
|
| 42 |
+
"""data/<k>/*/<k>.*.parquet (citations/wikipedia.citations.parquet) holds only ids its shard has, none blocklisted."""
|
| 43 |
+
bl, hits = takedown.load(), {}
|
| 44 |
+
for f in sorted(DATA.glob("*/*/*.parquet")):
|
| 45 |
+
shard = f.parent.parent / f"{f.name.split('.')[0]}.parquet"
|
| 46 |
+
if takedown.is_lfs_pointer(f) or takedown.is_lfs_pointer(shard):
|
| 47 |
+
continue
|
| 48 |
+
kept = set(pq.read_table(shard, columns=["id"])["id"].to_pylist())
|
| 49 |
+
ids = pq.read_table(f, columns=["id"])["id"].to_pylist()
|
| 50 |
+
if bad := [i for i in ids if (shard.stem, i) in bl.ids or i not in kept]:
|
| 51 |
+
hits[str(f.relative_to(ROOT))] = bad[:5]
|
| 52 |
+
assert hits == {}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
def _register_rows() -> list[list[str]]:
|
| 56 |
lines = REGISTER.read_text(encoding="utf-8").splitlines()
|
| 57 |
start = lines.index("| date | source | record id | reason class | action |") + 2
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
def _source(tmp_path):
|
| 114 |
+
"""data/demo with four records, the sidecar files a source ships, a table in a folder, and their checksums."""
|
| 115 |
d = tmp_path / "data" / "demo"
|
| 116 |
d.mkdir(parents=True)
|
| 117 |
texts = _texts()
|
|
|
|
| 128 |
encoding="utf-8")
|
| 129 |
(d / "demo.attribution.jsonl").write_text("".join(json.dumps({"id": i, "url": f"https://x/{i}"}) + "\n" for i in ids))
|
| 130 |
(d / "demo.md").write_text("# demo\n")
|
| 131 |
+
(d / "citations").mkdir()
|
| 132 |
+
pq.write_table(pa.table({"id": ids, "citations": [[f"Źródło {n}"] for n in range(4)]}),
|
| 133 |
+
d / "citations" / "demo.citations.parquet")
|
| 134 |
(d / "demo.stats.json").write_text(json.dumps({
|
| 135 |
"kept": 4, "tokens": 100, "chars": sum(map(len, texts)), "authors_with_value": 2,
|
| 136 |
"licenses": {"CC0": 3, "CC-BY-4.0": 1}, "sample_count": 2, "by_year": {"2020": 4},
|
| 137 |
}, indent=2))
|
| 138 |
+
sums = {f.name: hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(d.iterdir()) if f.is_file()}
|
| 139 |
(d / "demo.checksums.json").write_text(json.dumps(sums, indent=2) + "\n")
|
| 140 |
return d
|
| 141 |
|
| 142 |
|
| 143 |
+
def _files(d):
|
| 144 |
+
return {f.relative_to(d).as_posix(): f.read_bytes() for f in sorted(d.rglob("*")) if f.is_file()}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
def _blocklist():
|
| 148 |
texts = _texts()
|
| 149 |
return Blocklist(
|
|
|
|
| 161 |
assert pq.read_table(shard)["id"].to_pylist() == ["demo_1"]
|
| 162 |
assert [json.loads(ln)["id"] for ln in (d / "demo.sample.jsonl").read_text().splitlines()] == ["demo_1"]
|
| 163 |
assert [json.loads(ln)["id"] for ln in (d / "demo.attribution.jsonl").read_text().splitlines()] == ["demo_1"]
|
| 164 |
+
# demo_2 is caught by its text, which the table does not carry: it goes by the id the shard dropped
|
| 165 |
+
assert pq.read_table(d / "citations" / "demo.citations.parquet").to_pydict() == {
|
| 166 |
+
"id": ["demo_1"], "citations": [["Źródło 1"]]}
|
| 167 |
stats_raw = (d / "demo.stats.json").read_text()
|
| 168 |
assert not stats_raw.endswith("\n") # layout kept
|
| 169 |
assert json.loads(stats_raw) == {
|
|
|
|
| 181 |
def test_apply_is_a_no_op_once_applied(tmp_path):
|
| 182 |
d = _source(tmp_path)
|
| 183 |
takedown.apply([d / "demo.parquet"], _blocklist())
|
| 184 |
+
before = _files(d)
|
| 185 |
assert takedown.apply([d / "demo.parquet"], _blocklist()) == {d / "demo.parquet": 0}
|
| 186 |
+
assert _files(d) == before
|
| 187 |
|
| 188 |
|
| 189 |
def test_apply_leaves_a_clean_source_byte_for_byte(tmp_path):
|
| 190 |
d = _source(tmp_path)
|
| 191 |
+
before = _files(d)
|
| 192 |
takedown.apply([d / "demo.parquet"], Blocklist(frozenset({("other", "x")}), frozenset({"0" * 64})))
|
| 193 |
+
assert _files(d) == before
|
| 194 |
|
| 195 |
|
| 196 |
+
@pytest.mark.parametrize("name", ["demo.attribution.jsonl", "citations/demo.citations.parquet"])
|
| 197 |
+
def test_apply_refuses_lfs_pointers(tmp_path, name):
|
| 198 |
d = _source(tmp_path)
|
| 199 |
+
(d / name).write_text("version https://git-lfs.github.com/spec/v1\noid sha256:00\nsize 1\n")
|
| 200 |
with pytest.raises(RuntimeError, match="git lfs pull"):
|
| 201 |
takedown.apply([d / "demo.parquet"], _blocklist())
|
| 202 |
|
src/test_wikipedia_contract.py
CHANGED
|
@@ -8,8 +8,10 @@ from pathlib import Path
|
|
| 8 |
import re
|
| 9 |
import shutil
|
| 10 |
import subprocess
|
|
|
|
| 11 |
|
| 12 |
import pyarrow as pa
|
|
|
|
| 13 |
import pyarrow.parquet as pq
|
| 14 |
import pytest
|
| 15 |
|
|
@@ -247,9 +249,90 @@ def test_withhold_drops_pages_added_after_the_build(tmp_path, monkeypatch):
|
|
| 247 |
assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before
|
| 248 |
|
| 249 |
monkeypatch.setattr(fw, "COPIED_PAGES", {10: "Ala: deleted"})
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
|
| 255 |
# --- released data -------------------------------------------------------------------------
|
|
@@ -353,6 +436,33 @@ def test_every_row_is_labelled_by_contribution():
|
|
| 353 |
assert fm.links_text("pl.wikipedia.org") in card
|
| 354 |
|
| 355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
def test_copyright_sample_matches_the_release():
|
| 357 |
"""The sample must be redrawn if the released rows change, except by the copyright drops.
|
| 358 |
|
|
|
|
| 8 |
import re
|
| 9 |
import shutil
|
| 10 |
import subprocess
|
| 11 |
+
from xml.sax.saxutils import escape
|
| 12 |
|
| 13 |
import pyarrow as pa
|
| 14 |
+
import pyarrow.compute as pc
|
| 15 |
import pyarrow.parquet as pq
|
| 16 |
import pytest
|
| 17 |
|
|
|
|
| 249 |
assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before
|
| 250 |
|
| 251 |
monkeypatch.setattr(fw, "COPIED_PAGES", {10: "Ala: deleted"})
|
| 252 |
+
for step in ("licence_labels", "citations"):
|
| 253 |
+
fw.save(tmp_path / "wikipedia.build.json", {**build, step: {}})
|
| 254 |
+
with pytest.raises(ValueError, match="before relabel and citations"):
|
| 255 |
+
fw.withhold(tmp_path)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
S1 = "plwiki-20260901-pages-meta-current1.xml-p1p15.bz2"
|
| 259 |
+
S2 = "plwiki-20260901-pages-meta-current2.xml-p16p30.bz2"
|
| 260 |
+
CITED = ("Ala ma kota<ref>Jan K., ''Koty'', 2001.</ref> i psa<ref name=\"x\" /><ref name=\"p\">{{Cytuj książkę|tytuł=Psy}}"
|
| 261 |
+
"</ref> oraz {{Cytuj stronę|url=http://x.pl|tytuł=X}}<ref>Jan K., ''Koty'', 2001.</ref>.")
|
| 262 |
+
SHARDS = {S1: [(10, "Ala", 0, "2023-06-07T00:00:00Z", CITED), (12, "Kot", 0, "2020-01-01T00:00:00Z", "Bez przypisów."),
|
| 263 |
+
(13, "Dyskusja:Kot", 1, "2020-01-01T00:00:00Z", "Tak<ref>x</ref>")],
|
| 264 |
+
S2: [(16, "Pies", 0, "2021-01-01T00:00:00Z", "Pies<ref>Psy, 1999.</ref>")]}
|
| 265 |
+
SIDE = [(16, 1600, "2021-01-01T00:00:00Z"), (10, 1000, "2023-06-07T00:00:00Z"), (12, 1200, "2020-01-01T00:00:00Z")]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _citations_inputs(tmp_path, shards=SHARDS, side=SIDE, release=None, bad_sha1=None):
|
| 269 |
+
"""fw.citations' inputs: shards in tmp/dumps; a data dir whose release has `side`'s rows in its order, in row groups
|
| 270 |
+
of 2, and whose sidecar has them in page id order; a dumpstatus.json that lists the shards last first, next to the
|
| 271 |
+
combined file."""
|
| 272 |
+
dumps, data = tmp_path / "dumps", tmp_path / "data"
|
| 273 |
+
dumps.mkdir()
|
| 274 |
+
data.mkdir()
|
| 275 |
+
files = {"plwiki-20260901-pages-meta-current.xml.bz2": {"size": 1, "sha1": "0" * 40}}
|
| 276 |
+
for name, rows in shards.items():
|
| 277 |
+
(dumps / name).write_bytes(bz2.compress((
|
| 278 |
+
'<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/">'
|
| 279 |
+
+ "".join(_page(pageid, title, ns, at, escape(text)) for pageid, title, ns, at, text in rows)
|
| 280 |
+
+ "</mediawiki>").encode()))
|
| 281 |
+
files[name] = {"size": (dumps / name).stat().st_size,
|
| 282 |
+
"sha1": "0" * 40 if name == bad_sha1 else fw.sha1_file(dumps / name)}
|
| 283 |
+
ids = [f"wikipedia_{pageid}" for pageid, _, _ in side]
|
| 284 |
+
pq.write_table(pa.table({"id": release or ids}), data / "wikipedia.parquet", row_group_size=2)
|
| 285 |
+
(data / "wikipedia.attribution.jsonl").write_text("".join(
|
| 286 |
+
json.dumps({"id": f"wikipedia_{pageid}", "pageid": pageid, "revid": revid, "last_revision_at": at}) + "\n"
|
| 287 |
+
for pageid, revid, at in sorted(side)))
|
| 288 |
+
fw.save(data / "wikipedia.build.json", {"attribution_rows": len(side)})
|
| 289 |
+
return dumps, data, {"jobs": {"metacurrentdump": {"files": dict(reversed(files.items()))}}}
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_citations_reads_each_rows_revision_from_the_dump(tmp_path):
|
| 293 |
+
dumps, data, status = _citations_inputs(tmp_path)
|
| 294 |
+
fw.citations(dumps, data, status, workers=2)
|
| 295 |
+
path = data / "citations" / "wikipedia.citations.parquet"
|
| 296 |
+
table = pq.read_table(path)
|
| 297 |
+
assert table.schema == pa.schema([("id", pa.string()), ("citations", pa.list_(pa.string()))])
|
| 298 |
+
# the release's order, not the sidecar's; a ref named but empty is not a citation, and a repeated one counts once
|
| 299 |
+
assert table.to_pydict() == {"id": ["wikipedia_16", "wikipedia_10", "wikipedia_12"], "citations": [
|
| 300 |
+
["Psy, 1999."],
|
| 301 |
+
["Jan K., ''Koty'', 2001.", "{{Cytuj książkę|tytuł=Psy}}", "{{Cytuj stronę|url=http://x.pl|tytuł=X}}"],
|
| 302 |
+
[]]}
|
| 303 |
+
meta = pq.ParquetFile(path).metadata
|
| 304 |
+
assert [meta.row_group(i).num_rows for i in range(meta.num_row_groups)] == [2, 1] # the release's row groups
|
| 305 |
+
shards = status["jobs"]["metacurrentdump"]["files"]
|
| 306 |
+
assert fw.load(data / "wikipedia.build.json") == {"attribution_rows": 3, "citations": {
|
| 307 |
+
"issue": "slayerlabs/polish-dynaword-v2#110", "file": "citations/wikipedia.citations.parquet",
|
| 308 |
+
"dumpstatus_url": fw.DUMPSTATUS_URL, "shards": [{"name": S1, **shards[S1]}, {"name": S2, **shards[S2]}],
|
| 309 |
+
"rows": 3, "rows_with_citations": 2, "citations": 4, "sha256": fm.digest(path.read_bytes())}}
|
| 310 |
+
text = fw.citations_text(fw.load(data / "wikipedia.build.json"))
|
| 311 |
+
assert "`citations/wikipedia.citations.parquet`" in text
|
| 312 |
+
assert "the 2 pages-meta-current shards of the same 20260901 dump" in text
|
| 313 |
+
assert "(2 rows have any)" in text and "4 citations in all" in text
|
| 314 |
+
|
| 315 |
+
before = {p: p.read_bytes() for p in data.rglob("*") if p.is_file()}
|
| 316 |
+
fw.citations(dumps, data, status, workers=2) # rerun: nothing changes
|
| 317 |
+
assert {p: p.read_bytes() for p in data.rglob("*") if p.is_file()} == before
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
@pytest.mark.parametrize("change, error", [
|
| 321 |
+
({"side": [(16, 1601, "2021-01-01T00:00:00Z")] + SIDE[1:]}, r"wikipedia_16: the dump has revision 1600 at 2021-"),
|
| 322 |
+
({"side": [(16, 1600, "2021-01-01T00:00:01Z")] + SIDE[1:]}, r"wikipedia_16: the dump has revision 1600 at 2021-"),
|
| 323 |
+
({"side": SIDE + [(99, 9900, "2020-01-01T00:00:00Z")]}, r"wikipedia_99: not in the dump"),
|
| 324 |
+
({"shards": {S1: SHARDS[S1], S2: SHARDS[S2] + SHARDS[S1][:1]}}, r"pages in two shards: \['10'\]"),
|
| 325 |
+
({"shards": {S1: SHARDS[S1] + SHARDS[S1][1:2], S2: SHARDS[S2]}}, r"page 12 twice in " + S1),
|
| 326 |
+
({"bad_sha1": S2}, r"sha1 mismatch: " + S2),
|
| 327 |
+
({"shards": {}}, r"no pages-meta-current shards"),
|
| 328 |
+
({"release": ["wikipedia_16", "wikipedia_10"]}, r"the sidecar's ids are not the parquet's"),
|
| 329 |
+
({"release": ["wikipedia_16", "wikipedia_10", "wikipedia_10"]}, r"the sidecar's ids are not the parquet's"),
|
| 330 |
+
])
|
| 331 |
+
def test_citations_stops_when_the_dump_is_not_the_release(tmp_path, change, error):
|
| 332 |
+
dumps, data, status = _citations_inputs(tmp_path, **change)
|
| 333 |
+
with pytest.raises(ValueError, match=error):
|
| 334 |
+
fw.citations(dumps, data, status, workers=2)
|
| 335 |
+
assert not (data / "citations").exists() and "citations" not in fw.load(data / "wikipedia.build.json")
|
| 336 |
|
| 337 |
|
| 338 |
# --- released data -------------------------------------------------------------------------
|
|
|
|
| 436 |
assert fm.links_text("pl.wikipedia.org") in card
|
| 437 |
|
| 438 |
|
| 439 |
+
def test_citations_table_matches_the_release():
|
| 440 |
+
"""citations/wikipedia.citations.parquet (v2#110, option A) has every released row, in the same order and row
|
| 441 |
+
groups, and is the file and counts build.json and the card give."""
|
| 442 |
+
build = _read("build")
|
| 443 |
+
c = build["citations"]
|
| 444 |
+
path = DATA / c["file"]
|
| 445 |
+
assert c["file"] == "citations/wikipedia.citations.parquet" and c["sha256"] == fm.digest(path.read_bytes())
|
| 446 |
+
table = pq.read_table(path)
|
| 447 |
+
assert table.schema == pa.schema([("id", pa.string()), ("citations", pa.list_(pa.string()))])
|
| 448 |
+
assert table["id"].to_pylist() == _released()[1]["id"]
|
| 449 |
+
groups = [[f.metadata.row_group(i).num_rows for i in range(f.metadata.num_row_groups)]
|
| 450 |
+
for f in (pq.ParquetFile(path), pq.ParquetFile(DATA / "wikipedia.parquet"))]
|
| 451 |
+
assert groups[0] == groups[1]
|
| 452 |
+
lengths = pc.list_value_length(table["citations"])
|
| 453 |
+
assert c["rows"] == table.num_rows
|
| 454 |
+
assert c["rows_with_citations"] == pc.sum(pc.greater(lengths, 0)).as_py()
|
| 455 |
+
assert c["citations"] == pc.sum(lengths).as_py()
|
| 456 |
+
assert pc.min(pc.utf8_length(pc.list_flatten(table["citations"]))).as_py() > 0
|
| 457 |
+
assert c["dumpstatus_url"] == fw.DUMPSTATUS_URL and c["shards"] == fw.by_first_page(c["shards"])
|
| 458 |
+
for shard in c["shards"]:
|
| 459 |
+
assert fw.META_CURRENT_RE.fullmatch(shard["name"]) and shard["name"].startswith(f"plwiki-{fw.DUMP_DATE}-")
|
| 460 |
+
assert re.fullmatch(r"[0-9a-f]{40}", shard["sha1"]) and shard["size"] > 0
|
| 461 |
+
card = (DATA / "wikipedia.md").read_text(encoding="utf-8")
|
| 462 |
+
assert fw.citations_text(build) in card
|
| 463 |
+
assert fm.QUOTATIONS in card # v2#110 E2: quotations rest on Art. 29, not the licence
|
| 464 |
+
|
| 465 |
+
|
| 466 |
def test_copyright_sample_matches_the_release():
|
| 467 |
"""The sample must be redrawn if the released rows change, except by the copyright drops.
|
| 468 |
|
takedown/PROCEDURE.md
CHANGED
|
@@ -80,10 +80,12 @@ Work in your own worktree, on a branch for the PR.
|
|
| 80 |
python3 src/takedown.py apply data/<k>/<k>.parquet [...]
|
| 81 |
```
|
| 82 |
|
| 83 |
-
This drops the rows from the shard
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
|
| 88 |
4. Find what still mentions the record. The id and the phrase can sit in the
|
| 89 |
README, `artifacts/`, the datasheet `data/<k>/<k>.md`, `qa.json`, audits
|
|
|
|
| 80 |
python3 src/takedown.py apply data/<k>/<k>.parquet [...]
|
| 81 |
```
|
| 82 |
|
| 83 |
+
This drops the rows from the shard, from every `<k>.*.jsonl` file next to
|
| 84 |
+
it and from every `<k>.*.parquet` table in a folder next to it, such as
|
| 85 |
+
`citations/<k>.citations.parquet`. It subtracts them from the shared
|
| 86 |
+
counters in `<k>.stats.json` and refreshes `<k>.checksums.json`.
|
| 87 |
+
Breakdowns such as `by_year` stay as they were until the source's builder
|
| 88 |
+
reruns.
|
| 89 |
|
| 90 |
4. Find what still mentions the record. The id and the phrase can sit in the
|
| 91 |
README, `artifacts/`, the datasheet `data/<k>/<k>.md`, `qa.json`, audits
|