ppuzio Claude Opus 5.5 commited on
Commit
ca8d210
·
1 Parent(s): 3393e05

wikipedia: drop the two copied pages and copyright-reason {{ek}} pages

Browse files

COPIED_PAGES in src/fetch_wikipedia.py lists the pages the copyright sample found
copied, keyed on the wiki page id with a reason each: 833396 "Obnazyc prawde"
(Filmweb description) and 1126780 "Czarnka" (dpn.pl lake text). prepare drops
them and fails if a listed page is not reached.

{{ek}} notices (and their redirect aliases from the dump) are read with their
reason; a copyright reason (npa, plagiat, copypaste, kopiuj-wklej, copyvio,
"praw... autorsk...") drops the page. plwiki 20260901 has 0 live {{ek}} notices
on articles, so none are dropped; build.json records ek_tagged.

Rebuilt from the same dump: 1,468,656 -> 1,468,654 documents,
1,226,913,508 -> 1,226,912,191 tokens. Only the two listed rows differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

artifacts/source_findings.md CHANGED
@@ -1537,3 +1537,24 @@ before release.
1537
  source came from the article's own citation and history ("Czarnka": a 2025 forum hit, the
1538
  park's 2012 text behind it). (3) The Terms of Use give the day of the licence switch, not
1539
  the time, so a last-revision label is inexact for one day of edits.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1537
  source came from the article's own citation and history ("Czarnka": a 2025 forum hit, the
1538
  park's 2012 text behind it). (3) The Terms of Use give the day of the licence switch, not
1539
  the time, so a last-revision label is inexact for one day of edits.
1540
+
1541
+ ## wikipedia — update: copied pages and `{{ek}}` dropped
1542
+
1543
+ Drops added to `src/fetch_wikipedia.py` (`prepare`), keyed on the wiki page id; the dump
1544
+ (plwiki 20260901) is unchanged. `COPIED_PAGES`: page 833396 "Obnażyć prawdę" (Filmweb's
1545
+ official description; excluded) and page 1126780 "Czarnka" (Drawieński Park Narodowy lake
1546
+ text; held for review, Art. 4 not assessed). The build fails if a listed page is not reached.
1547
+
1548
+ `{{ek}}` (speedy deletion; aliases EK, Ekspresowe kasowanko, Usuń, Speedy, Delete from the
1549
+ dump's redirects) is read with its reason; a reason naming a copyright violation (npa,
1550
+ plagiat, copypaste, kopiuj-wklej, copyvio, "praw… autorsk…") drops the page. The dump has 0
1551
+ live `{{ek}}` notices on articles, so 0 dropped and no reasons to count; a looser text scan
1552
+ of all 7 shards found 3, all inside `<!-- -->` comments (redirect, content moved, no
1553
+ reason), none about copyright. The hand-check of 10 was not possible.
1554
+
1555
+ Rebuilt from the same dump: 1,468,656 → 1,468,654 documents, 1,226,913,508 → 1,226,912,191
1556
+ tokens (3.0: 190,836 docs / 81,022,938 tokens; 4.0: 1,277,818 / 1,145,889,253). Diff against
1557
+ the previous parquet: only `wikipedia_833396` and `wikipedia_1126780` removed, no row added
1558
+ or changed, same in the attribution sidecar. Row order differs between builds
1559
+ (`build_dynaword.py` uses `imap_unordered`); content per id is identical. The copyright
1560
+ sample keeps its population (the previous build) and records the two dropped ids.
data/wikipedia/wikipedia.attribution.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:09470d9e87b26cb1b2a677c50004c0b6b0b9c0877eec116b227fcd47dca3ada1
3
- size 344192463
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:046067a7992e0f98950ba6d7e0e8b7499e75e58bb5aac0a64e0779e6d69e0a2e
3
+ size 344192023
data/wikipedia/wikipedia.build.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
- "attribution_rows": 1468656,
3
- "attribution_sha256": "09470d9e87b26cb1b2a677c50004c0b6b0b9c0877eec116b227fcd47dca3ada1",
4
  "by_sa_4_cutoff": "2023-06-07T00:00:00+00:00",
5
  "copyvio_tagged": [
6
  {
@@ -147,6 +147,7 @@
147
  "discovered_at": "2026-10-05T22:27:57.741359+00:00",
148
  "dump_base": "https://dumps.wikimedia.org/plwiki/20260901",
149
  "dump_date": "20260901",
 
150
  "extract": {
151
  "extracted": 1706319,
152
  "ns0": 2304425,
@@ -199,12 +200,27 @@
199
  }
200
  ],
201
  "prepare": {
 
 
 
 
 
 
 
 
 
 
 
 
202
  "counts": {
203
- "CC-BY-SA-3.0": 284076,
204
- "CC-BY-SA-4.0": 1421861,
 
 
205
  "exact_duplicate": 382,
206
  "extracted": 1706319
207
  },
 
208
  "exact_duplicate_pageids": [
209
  "28456",
210
  "28459",
@@ -595,6 +611,36 @@
595
  "url": "https://creativecommons.org/licenses/by-sa/4.0/deed.pl"
596
  },
597
  "sha1sums_url": "https://dumps.wikimedia.org/plwiki/20260901/plwiki-20260901-sha1sums.txt",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  "terms_of_use": {
599
  "effective": "These Terms of Use went into effect on June 7, 2023",
600
  "sha256": "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832",
 
1
  {
2
+ "attribution_rows": 1468654,
3
+ "attribution_sha256": "046067a7992e0f98950ba6d7e0e8b7499e75e58bb5aac0a64e0779e6d69e0a2e",
4
  "by_sa_4_cutoff": "2023-06-07T00:00:00+00:00",
5
  "copyvio_tagged": [
6
  {
 
147
  "discovered_at": "2026-10-05T22:27:57.741359+00:00",
148
  "dump_base": "https://dumps.wikimedia.org/plwiki/20260901",
149
  "dump_date": "20260901",
150
+ "ek_tagged": [],
151
  "extract": {
152
  "extracted": 1706319,
153
  "ns0": 2304425,
 
200
  }
201
  ],
202
  "prepare": {
203
+ "copied_pages": [
204
+ {
205
+ "pageid": "833396",
206
+ "reason": "Obnażyć prawdę: the 'Opis fabuły' paragraph closely paraphrases Filmweb's production description of the film; added in revision 15302011 (2008-12-26), which cites Filmweb",
207
+ "title": "Obnażyć prawdę"
208
+ },
209
+ {
210
+ "pageid": "1126780",
211
+ "reason": "Czarnka: the lake paragraph (revision 42979631, 2015-06-19) closely paraphrases the Drawieński Park Narodowy page dpn.pl/czarne, archived 2012-01-25; whether Art. 4 of the Polish copyright act (official materials) applies was not assessed",
212
+ "title": "Czarnka"
213
+ }
214
+ ],
215
  "counts": {
216
+ "CC-BY-SA-3.0": 284075,
217
+ "CC-BY-SA-4.0": 1421860,
218
+ "copied_page": 2,
219
+ "ek_copyright": 0,
220
  "exact_duplicate": 382,
221
  "extracted": 1706319
222
  },
223
+ "ek_copyright": [],
224
  "exact_duplicate_pageids": [
225
  "28456",
226
  "28459",
 
611
  "url": "https://creativecommons.org/licenses/by-sa/4.0/deed.pl"
612
  },
613
  "sha1sums_url": "https://dumps.wikimedia.org/plwiki/20260901/plwiki-20260901-sha1sums.txt",
614
+ "tag_template_redirects": [
615
+ {
616
+ "target": "Szablon:Ek",
617
+ "title": "Szablon:EK"
618
+ },
619
+ {
620
+ "target": "Szablon:Ek",
621
+ "title": "Szablon:Ekspresowe kasowanko"
622
+ },
623
+ {
624
+ "target": "Szablon:Ek",
625
+ "title": "Szablon:Usuń"
626
+ },
627
+ {
628
+ "target": "Szablon:Ek",
629
+ "title": "Szablon:Speedy"
630
+ },
631
+ {
632
+ "target": "Szablon:Ek",
633
+ "title": "Szablon:Delete"
634
+ },
635
+ {
636
+ "target": "Szablon:NPA",
637
+ "title": "Szablon:Copyvio"
638
+ },
639
+ {
640
+ "target": "Szablon:NPA",
641
+ "title": "Szablon:Plagiat"
642
+ }
643
+ ],
644
  "terms_of_use": {
645
  "effective": "These Terms of Use went into effect on June 7, 2023",
646
  "sha256": "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832",
data/wikipedia/wikipedia.license-evidence.json CHANGED
@@ -67,15 +67,15 @@
67
  ],
68
  "attribution": "author = \"Wikipedia contributors, <page URL>\"; the page history names the contributors; Terms of Use section 7 accepts a link or URL to the page. wikipedia.attribution.jsonl: id, pageid, revid, title, url, last_revision_at, license per row",
69
  "intermediary_removed": "v0.2.0-v0.2.5 used the SpeakLeash plwiki snapshot (speakleash-ds-pub); the v0.2.6 rebuild reads the official dump directly",
70
- "finding": "Contributors' text is CC BY-SA; its version follows the page's last revision. Pages carrying the plwiki copyright-violation notice ({{NPA}}, {{Copyvio}}, {{Plagiat}}) are dropped.",
71
  "release_scope": {
72
  "labels": {
73
- "CC-BY-SA-4.0": 1277819,
74
- "CC-BY-SA-3.0": 190837
75
  },
76
  "tokens_by_label": {
77
- "CC-BY-SA-4.0": 1145890205,
78
- "CC-BY-SA-3.0": 81023303
79
  },
80
  "pages_scanned": 2877278,
81
  "namespace_0": 2304425,
@@ -85,9 +85,12 @@
85
  "parser_failures": 0,
86
  "converted": 1706319,
87
  "exact_duplicates": 382,
 
 
 
88
  "under_200_chars": 231717,
89
  "non_polish": 5564,
90
- "documents_released": 1468656,
91
  "last_revised_before_2009": 0
92
  },
93
  "copyvio_notice_recheck": {
@@ -113,7 +116,22 @@
113
  ]
114
  ]
115
  },
116
- "audit_trail": "wikipedia.build.json lists the dropped copyright-notice pages (copyvio_tagged) and the page ids dropped as exact duplicates (prepare.exact_duplicate_pageids)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  "copyright_sample": {
118
  "file": "wikipedia.copyvio-sample.jsonl",
119
  "checked_at": "2026-10-05",
@@ -186,7 +204,22 @@
186
  "note": "Earwig's hit is a 2025-02-21 forum trip report (gorybezgranic.pl) that quotes the lake paragraph verbatim in quotation marks (645 of 2705 chars). The paragraph entered Wikipedia in revision 42979631 (2015-06-19, MOs810, summary 'rozb., źr., ilustracja'), cited to 'Tablica informacyjna in situ' (an on-site board, not read). It follows, fact by fact and in the same order, the Drawieński Park Narodowy page dpn.pl/czarne, archived 2012-01-25 with the same text: 10 tys. lat / bryła martwego lodu, średnio 7 m, 'beztlenowe bakterie Desulfovibrio desulfuricans', 'purpurowe bakterie siarkowe ... utleniające siarkowodór do wolnej siarki', mixing by wind 'wiosną i jesienią', mezotroficzny. Close paraphrase of an earlier park text; the board may hold the verbatim original. Whether a national park's text is protected (Art. 4 of the Polish copyright act excludes official materials) was not assessed."
187
  }
188
  ],
189
- "found_copied_decision": "kept in this release; drop or keep is an open decision"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  },
191
  "not_checked": [
192
  "pastes from copyrighted sources beyond the sample above",
@@ -194,7 +227,7 @@
194
  "text imported from elsewhere under another licence or with extra attribution requirements (Terms of Use, Re-use); template notices are removed by the conversion",
195
  "text first contributed under GFDL before the 2009 move to CC BY-SA (0 pages last edited before 2009); GFDL dual licensing; only the CC BY-SA grant is relied on",
196
  "quotations inside articles (Art. 29 of the Polish copyright act)",
197
- "pages tagged for speedy deletion ({{ek}}) are kept; how many are tagged for copyright reasons was not counted",
198
  "personal data (NERGAL scrub runs before release)"
199
  ]
200
  }
 
67
  ],
68
  "attribution": "author = \"Wikipedia contributors, <page URL>\"; the page history names the contributors; Terms of Use section 7 accepts a link or URL to the page. wikipedia.attribution.jsonl: id, pageid, revid, title, url, last_revision_at, license per row",
69
  "intermediary_removed": "v0.2.0-v0.2.5 used the SpeakLeash plwiki snapshot (speakleash-ds-pub); the v0.2.6 rebuild reads the official dump directly",
70
+ "finding": "Contributors' text is CC BY-SA; its version follows the page's last revision. Pages carrying the plwiki copyright-violation notice ({{NPA}}, {{Copyvio}}, {{Plagiat}}) are dropped, as are pages whose speedy-deletion notice {{ek}} gives a copyright reason (none in this dump) and the pages the copyright sample found copied (src/fetch_wikipedia.py COPIED_PAGES).",
71
  "release_scope": {
72
  "labels": {
73
+ "CC-BY-SA-4.0": 1277818,
74
+ "CC-BY-SA-3.0": 190836
75
  },
76
  "tokens_by_label": {
77
+ "CC-BY-SA-4.0": 1145889253,
78
+ "CC-BY-SA-3.0": 81022938
79
  },
80
  "pages_scanned": 2877278,
81
  "namespace_0": 2304425,
 
85
  "parser_failures": 0,
86
  "converted": 1706319,
87
  "exact_duplicates": 382,
88
+ "copied_pages": 2,
89
+ "ek_notices": 0,
90
+ "ek_copyright": 0,
91
  "under_200_chars": 231717,
92
  "non_polish": 5564,
93
+ "documents_released": 1468654,
94
  "last_revised_before_2009": 0
95
  },
96
  "copyvio_notice_recheck": {
 
116
  ]
117
  ]
118
  },
119
+ "ek_notice": {
120
+ "template": "Szablon:Ek",
121
+ "redirects_in_dump": [
122
+ "Delete",
123
+ "EK",
124
+ "Ekspresowe kasowanko",
125
+ "Speedy",
126
+ "Usuń"
127
+ ],
128
+ "rule": "src/fetch_wikipedia.py ek_tag reads the first parameter (or powód=) of a live {{ek}} call; ek_is_copyright (EK_COPYRIGHT_RE) drops it when the reason is npa, plagiat, copypaste, kopiuj-wklej, copyvio or names 'praw autorskich'; tested in src/test_wikipedia_contract.py",
129
+ "articles_tagged": 0,
130
+ "by_reason": {},
131
+ "copyright_dropped": 0,
132
+ "cross_check": "a looser scan of all 7 shards for {{ek, {{usuń, {{speedy, {{delete and {{ekspresowe in namespace-0 articles found no live notice; 3 pages have one inside an HTML comment (not shown by MediaWiki, not counted): Pożar Londynu (1666) (powód=redir), Tabela wszech czasów w konkursie Miss Supranational (content moved to the main article), Dangdang (no reason)"
133
+ },
134
+ "audit_trail": "wikipedia.build.json lists the dropped copyright-notice pages (copyvio_tagged), every {{ek}} notice (ek_tagged), the pages dropped as copied (prepare.copied_pages) or for a copyright {{ek}} reason (prepare.ek_copyright), the page ids dropped as exact duplicates (prepare.exact_duplicate_pageids), and the redirects to the two notice templates (tag_template_redirects)",
135
  "copyright_sample": {
136
  "file": "wikipedia.copyvio-sample.jsonl",
137
  "checked_at": "2026-10-05",
 
204
  "note": "Earwig's hit is a 2025-02-21 forum trip report (gorybezgranic.pl) that quotes the lake paragraph verbatim in quotation marks (645 of 2705 chars). The paragraph entered Wikipedia in revision 42979631 (2015-06-19, MOs810, summary 'rozb., źr., ilustracja'), cited to 'Tablica informacyjna in situ' (an on-site board, not read). It follows, fact by fact and in the same order, the Drawieński Park Narodowy page dpn.pl/czarne, archived 2012-01-25 with the same text: 10 tys. lat / bryła martwego lodu, średnio 7 m, 'beztlenowe bakterie Desulfovibrio desulfuricans', 'purpurowe bakterie siarkowe ... utleniające siarkowodór do wolnej siarki', mixing by wind 'wiosną i jesienią', mezotroficzny. Close paraphrase of an earlier park text; the board may hold the verbatim original. Whether a national park's text is protected (Art. 4 of the Polish copyright act excludes official materials) was not assessed."
205
  }
206
  ],
207
+ "found_copied_decision": "dropped from the release (src/fetch_wikipedia.py COPIED_PAGES, keyed on the page id); maintainer rule: keep a source clean or drop what cannot be cleared",
208
+ "population": {
209
+ "drawn_from": "Hub PR 68 commit 3393e05c178bb29cd9d0bda0444ef9fb2573fbf3, data/wikipedia/wikipedia.parquet sha256 fca10e80f9ee0c8db289518a001178e1b9580d744976841144fb08784d47256e",
210
+ "documents": 1468656,
211
+ "rows_dropped_since": [
212
+ [
213
+ "wikipedia_833396",
214
+ "CC-BY-SA-3.0"
215
+ ],
216
+ [
217
+ "wikipedia_1126780",
218
+ "CC-BY-SA-4.0"
219
+ ]
220
+ ],
221
+ "note": "the sample was drawn from this earlier build; test_copyright_sample_matches_the_release reproduces it from the released ids plus rows_dropped_since, each of which must be a copyright drop"
222
+ }
223
  },
224
  "not_checked": [
225
  "pastes from copyrighted sources beyond the sample above",
 
227
  "text imported from elsewhere under another licence or with extra attribution requirements (Terms of Use, Re-use); template notices are removed by the conversion",
228
  "text first contributed under GFDL before the 2009 move to CC BY-SA (0 pages last edited before 2009); GFDL dual licensing; only the CC BY-SA grant is relied on",
229
  "quotations inside articles (Art. 29 of the Polish copyright act)",
230
+ "deletion discussions and maintenance notices other than {{NPA}} and {{ek}}; their reasons are not read",
231
  "personal data (NERGAL scrub runs before release)"
232
  ]
233
  }
data/wikipedia/wikipedia.md CHANGED
@@ -19,8 +19,8 @@ dump:
19
 
20
  | last revision (UTC) | `license` | documents | tokens | share of tokens |
21
  |---|---|---:|---:|---:|
22
- | before 2023-06-07 | `CC-BY-SA-3.0` | 190,837 | 81,023,303 | 6.6% |
23
- | 2023-06-07 or later | `CC-BY-SA-4.0` | 1,277,819 | 1,145,890,205 | 93.4% |
24
 
25
  A page last edited on or after the cutoff can still hold 3.0 text from earlier edits;
26
  [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
@@ -39,8 +39,13 @@ fetcher drops the 35 pages that carry plwiki's copyright-violation
39
  notice `{{NPA}}` (or its redirects `{{Copyvio}}`, `{{Plagiat}}`) in the dump.
40
  On 2026-10-05 the 31 of them not edited since the dump were re-read on
41
  pl.wikipedia: all carry the notice (some mark one section only; the whole page is dropped).
42
- The 4 edited after the dump were not re-read. A paste without the notice cannot
43
- be detected by the build.
 
 
 
 
 
44
 
45
  To measure undetected pastes, 40 released pages per label (seed
46
  20261006, page-id order) were run through Earwig's Copyvio Detector (web search and
@@ -56,8 +61,11 @@ with the page history and the date of the matching text (see `wikipedia.copyvio-
56
  | text copied or closely paraphrased from a copyrighted source | 1 | 1 |
57
 
58
  1 of 40 (`CC-BY-SA-3.0`) and 1 of 40 (`CC-BY-SA-4.0`) pages contain text
59
- copied or closely paraphrased from a copyrighted source: `wikipedia_833396` "Obnażyć prawdę" (`CC-BY-SA-3.0`); `wikipedia_1126780` "Czarnka" (`CC-BY-SA-4.0`). They stay in
60
- this release (the sample file notes why each is classed so). The share of such pages is below 12.9% (`CC-BY-SA-3.0`) and
 
 
 
61
  12.9% (`CC-BY-SA-4.0`), 95% Wilson upper bounds; the labels hold
62
  6.6% and 93.4% of the tokens. The bounds cover only
63
  what the detector can find: print sources, translations and paraphrase scoring below the
@@ -83,7 +91,8 @@ Parsed from the official Wikimedia dump `plwiki-20260901-pages-articles` by
83
  (`speakleash-ds-pub`); that intermediary was removed in this rebuild.
84
 
85
  Articles (namespace 0) only. Redirects, empty pages and pages with a copyright-violation
86
- notice are skipped. Wikitext is converted with mwparserfromhell
 
87
  `strip_code(normalize=True, collapse=True)`, as in the sibling Wikimedia builders, after
88
  removing `<ref>` bodies, file and category links and behaviour switches (`__NOTOC__`).
89
  Templates (infoboxes, navigation boxes), `<math>`, galleries and comments are dropped;
@@ -93,18 +102,19 @@ pages with the same text (sha1 of the stripped text), the lower page id is kept.
93
  2,877,278 pages scanned → 2,304,425 in namespace 0 → 598,071 redirects,
94
  0 empty pages and 35 with a copyright-violation notice skipped
95
  (0 parser failures) → 1,706,319 converted →
96
- 382 exact duplicates dropped → 1,705,937 read by the build →
97
- 1,468,656 released.
 
98
 
99
  Not cleaned: appendix headings ("Zobacz też", "Uwagi", "Przypisy", "Bibliografia", "Linki
100
- zewnętrzne") stay in 828,389 documents (56.405%), with what is left of those sections
101
  after the conversion (2.96% of all characters from the first such heading to the end);
102
  174,668 documents (11.893%) have whitespace-only lines.
103
 
104
  ## Statistics
105
  | documents | characters | tokens (tiktoken proxy) |
106
  |---:|---:|---:|
107
- | 1,468,656 | 3,140,841,847 | 1,226,913,508 |
108
 
109
  v0.2.5 (SpeakLeash snapshot) had 1,171,897 documents, 1,844,707,761 characters and
110
  707,194,207 tokens. The SpeakLeash extraction is not documented. Its text drops the
@@ -115,17 +125,17 @@ in v0.2.5 and 59,133 here.
115
  ## Per-document license metadata
116
  | license | documents |
117
  |---|---:|
118
- | `CC-BY-SA-3.0` | 190,837 |
119
- | `CC-BY-SA-4.0` | 1,277,819 |
120
 
121
- Author metadata present for **1,468,656** documents.
122
 
123
  ## Filters applied (build_dynaword.py)
124
  - drop documents < 200 chars: **231,717**
125
  - drop non-Polish (diacritic ratio): **5,564**
126
  - exact cross-source dedup (sha1): **0** (the fetcher already dropped 382)
127
  - OCR alpha-ratio < 0.70 (OCR sources only): **0**
128
- - read 1,705,937 → kept 1,468,656
129
 
130
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
131
  Llama-3 count is computed at release.
@@ -139,6 +149,6 @@ Llama-3 count is computed at release.
139
  - text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual
140
  licensing; only the CC BY-SA grant is relied on
141
  - quotations inside articles (Art. 29 of the Polish copyright act)
142
- - pages tagged for speedy deletion (`{{ek}}`) are kept; how many are tagged for copyright
143
- reasons was not counted
144
  - personal data (the NERGAL scrub runs before release)
 
19
 
20
  | last revision (UTC) | `license` | documents | tokens | share of tokens |
21
  |---|---|---:|---:|---:|
22
+ | before 2023-06-07 | `CC-BY-SA-3.0` | 190,836 | 81,022,938 | 6.6% |
23
+ | 2023-06-07 or later | `CC-BY-SA-4.0` | 1,277,818 | 1,145,889,253 | 93.4% |
24
 
25
  A page last edited on or after the cutoff can still hold 3.0 text from earlier edits;
26
  [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
 
39
  notice `{{NPA}}` (or its redirects `{{Copyvio}}`, `{{Plagiat}}`) in the dump.
40
  On 2026-10-05 the 31 of them not edited since the dump were re-read on
41
  pl.wikipedia: all carry the notice (some mark one section only; the whole page is dropped).
42
+ The 4 edited after the dump were not re-read. Pages tagged for speedy deletion with
43
+ `{{ek}}` (or its redirects `{{Delete}}`, `{{EK}}`, `{{Ekspresowe kasowanko}}`, `{{Speedy}}`, `{{Usuń}}`) are also
44
+ dropped when the stated reason is a copyright violation (`EK_COPYRIGHT_RE`: the
45
+ template's codes `npa`, `plagiat`, `copypaste`, `kopiuj-wklej`, or free text with "copyvio" or
46
+ "praw autorskich"). No article in this dump carries a live `{{ek}}` notice; a looser
47
+ scan found 3 inside HTML comments, which MediaWiki does not show and the build does not
48
+ count. A paste without either notice cannot be detected by the build.
49
 
50
  To measure undetected pastes, 40 released pages per label (seed
51
  20261006, page-id order) were run through Earwig's Copyvio Detector (web search and
 
61
  | text copied or closely paraphrased from a copyrighted source | 1 | 1 |
62
 
63
  1 of 40 (`CC-BY-SA-3.0`) and 1 of 40 (`CC-BY-SA-4.0`) pages contain text
64
+ copied or closely paraphrased from a copyrighted source: `wikipedia_833396` "Obnażyć prawdę" (`CC-BY-SA-3.0`); `wikipedia_1126780` "Czarnka" (`CC-BY-SA-4.0`) (the sample file notes
65
+ why each is classed so). Both are dropped from this release: `COPIED_PAGES` in
66
+ `src/fetch_wikipedia.py` lists them by page id with the reason, and the build stops if one is
67
+ not found. The sample was drawn before that drop, from the 1,468,656 documents of Hub PR 68
68
+ commit 3393e05; the test reproduces the draw from the release plus the dropped rows. The share of such pages is below 12.9% (`CC-BY-SA-3.0`) and
69
  12.9% (`CC-BY-SA-4.0`), 95% Wilson upper bounds; the labels hold
70
  6.6% and 93.4% of the tokens. The bounds cover only
71
  what the detector can find: print sources, translations and paraphrase scoring below the
 
91
  (`speakleash-ds-pub`); that intermediary was removed in this rebuild.
92
 
93
  Articles (namespace 0) only. Redirects, empty pages and pages with a copyright-violation
94
+ notice are skipped; pages listed in `COPIED_PAGES` or with a copyright `{{ek}}` reason are
95
+ dropped after the duplicate check, so a copy of their text on another page goes with them. Wikitext is converted with mwparserfromhell
96
  `strip_code(normalize=True, collapse=True)`, as in the sibling Wikimedia builders, after
97
  removing `<ref>` bodies, file and category links and behaviour switches (`__NOTOC__`).
98
  Templates (infoboxes, navigation boxes), `<math>`, galleries and comments are dropped;
 
102
  2,877,278 pages scanned → 2,304,425 in namespace 0 → 598,071 redirects,
103
  0 empty pages and 35 with a copyright-violation notice skipped
104
  (0 parser failures) → 1,706,319 converted →
105
+ 382 exact duplicates, 2 copied pages (`COPIED_PAGES`) and 0 copyright `{{ek}}`
106
+ pages dropped → 1,705,935 read by the build →
107
+ 1,468,654 released.
108
 
109
  Not cleaned: appendix headings ("Zobacz też", "Uwagi", "Przypisy", "Bibliografia", "Linki
110
+ zewnętrzne") stay in 828,388 documents (56.405%), with what is left of those sections
111
  after the conversion (2.96% of all characters from the first such heading to the end);
112
  174,668 documents (11.893%) have whitespace-only lines.
113
 
114
  ## Statistics
115
  | documents | characters | tokens (tiktoken proxy) |
116
  |---:|---:|---:|
117
+ | 1,468,654 | 3,140,838,409 | 1,226,912,191 |
118
 
119
  v0.2.5 (SpeakLeash snapshot) had 1,171,897 documents, 1,844,707,761 characters and
120
  707,194,207 tokens. The SpeakLeash extraction is not documented. Its text drops the
 
125
  ## Per-document license metadata
126
  | license | documents |
127
  |---|---:|
128
+ | `CC-BY-SA-3.0` | 190,836 |
129
+ | `CC-BY-SA-4.0` | 1,277,818 |
130
 
131
+ Author metadata present for **1,468,654** documents.
132
 
133
  ## Filters applied (build_dynaword.py)
134
  - drop documents < 200 chars: **231,717**
135
  - drop non-Polish (diacritic ratio): **5,564**
136
  - exact cross-source dedup (sha1): **0** (the fetcher already dropped 382)
137
  - OCR alpha-ratio < 0.70 (OCR sources only): **0**
138
+ - read 1,705,935 → kept 1,468,654
139
 
140
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
141
  Llama-3 count is computed at release.
 
149
  - text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual
150
  licensing; only the CC BY-SA grant is relied on
151
  - quotations inside articles (Art. 29 of the Polish copyright act)
152
+ - deletion discussions and maintenance notices other than `{{NPA}}` and `{{ek}}`; their
153
+ reasons are not read
154
  - personal data (the NERGAL scrub runs before release)
data/wikipedia/wikipedia.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fca10e80f9ee0c8db289518a001178e1b9580d744976841144fb08784d47256e
3
- size 1462996349
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4abfff711b207691d1278efc28d8af18551454143f3d8f2292ec3ddcefc314a
3
+ size 1462846393
data/wikipedia/wikipedia.stats.json CHANGED
@@ -1,17 +1,17 @@
1
  {
2
- "read": 1705937,
3
- "kept": 1468656,
4
  "drop_short": 231717,
5
  "drop_lang": 5564,
6
  "drop_dup": 0,
7
  "drop_ocr": 0,
8
- "chars": 3140841847,
9
- "tokens": 1226913508,
10
  "licenses": {
11
- "CC-BY-SA-4.0": 1277819,
12
- "CC-BY-SA-3.0": 190837
13
  },
14
- "authors_with_value": 1468656,
15
- "secs": 36.0,
16
  "license": "CC BY-SA (3.0 or 4.0 per record, by last-revision date)"
17
  }
 
1
  {
2
+ "read": 1705935,
3
+ "kept": 1468654,
4
  "drop_short": 231717,
5
  "drop_lang": 5564,
6
  "drop_dup": 0,
7
  "drop_ocr": 0,
8
+ "chars": 3140838409,
9
+ "tokens": 1226912191,
10
  "licenses": {
11
+ "CC-BY-SA-4.0": 1277818,
12
+ "CC-BY-SA-3.0": 190836
13
  },
14
+ "authors_with_value": 1468654,
15
+ "secs": 34.6,
16
  "license": "CC BY-SA (3.0 or 4.0 per record, by last-revision date)"
17
  }
src/fetch_wikipedia.py CHANGED
@@ -8,8 +8,9 @@ checked against the sha1 in dumpstatus.json and in the dump's sha1sums.txt.
8
  B=<build dir, never committed>
9
  python3 src/fetch_wikipedia.py discover --out $B # shards, sha1s, licence evidence
10
  python3 src/fetch_wikipedia.py acquire --out $B # resumable download + sha1 check
11
- python3 src/fetch_wikipedia.py extract --out $B # ns 0, no redirects, no copyvio tag
12
- python3 src/fetch_wikipedia.py prepare --out $B # $B/wikipedia.jsonl.zst
 
13
  python3 src/build_dynaword.py --sources wikipedia --speakleash-dir $B --out .
14
  python3 src/fetch_wikipedia.py attribution --out $B # data/wikipedia sidecars
15
  """
@@ -58,6 +59,29 @@ BY_SA_4_CUTOFF = datetime(2023, 6, 7, tzinfo=timezone.utc)
58
  # plwiki copyright-violation notice and its redirects (Szablon:NPA <- Copyvio, Plagiat).
59
  # Namespace prefix is case-insensitive, the first letter of the name too.
60
  COPYVIO_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?(?:[Nn]PA|[Cc]opyvio|[Pp]lagiat)\s*(?:\||\}\})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # Links that render as an image or a category, not as running text ([[:Kategoria:X]] is a text link).
62
  NON_PROSE_NS = {"plik", "file", "image", "grafika", "media", "kategoria", "category"}
63
  SWITCH_RE = re.compile(r"__[A-ZĄĆĘŁŃÓŚŹŻ]+__") # __NOTOC__, __BEZSPISU__
@@ -91,6 +115,39 @@ def strip_article(wikitext: str) -> str | None:
91
  return SWITCH_RE.sub("", text).strip()
92
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  def license_for_revision(timestamp: str | None) -> str:
95
  """SPDX label for a page whose last revision is at `timestamp` (ISO 8601 with zone)."""
96
  if not timestamp:
@@ -150,10 +207,11 @@ def acquire(out: Path) -> None:
150
 
151
 
152
  def pages(fh):
153
- """Yield (pageid, revid, ns, title, timestamp, is_redirect, wikitext) per <page>."""
 
154
  ids, title = [], None
155
  ns = timestamp = text = None
156
- redirect = False
157
  for _, el in iterparse(fh, events=("end",)):
158
  tag = _local(el.tag)
159
  if tag == "title":
@@ -164,39 +222,51 @@ def pages(fh):
164
  ids.append(el.text)
165
  elif tag == "timestamp":
166
  timestamp = el.text
167
- elif tag == "redirect":
168
- redirect = True
169
  elif tag == "text":
170
  text = el.text
171
  elif tag == "page":
172
  yield ids[0], ids[1], ns, title, timestamp, redirect, text or ""
173
- ids, title, ns, timestamp, text, redirect = [], None, None, None, None, False
174
  el.clear()
175
 
176
 
177
  def extract_shard(src: Path, dst: Path) -> dict:
178
- counts, copyvio = Counter(), []
179
  tmp = dst.with_suffix(".tmp")
180
  with bz2.open(src, "rb") as fh, gzip.open(tmp, "wt", encoding="utf-8") as fo:
181
  for pageid, revid, ns, title, timestamp, redirect, wikitext in pages(fh):
182
  counts["pages"] += 1
 
 
183
  if ns != "0":
184
  continue
185
  counts["ns0"] += 1
186
  if redirect:
187
  counts["ns0_redirect"] += 1
188
- elif not wikitext.strip():
 
189
  counts["ns0_empty"] += 1
190
- elif COPYVIO_RE.search(wikitext):
 
 
 
 
 
191
  counts["ns0_copyvio_tag"] += 1
192
  copyvio.append({"pageid": pageid, "title": title})
193
  elif (text := strip_article(wikitext)) is None:
194
  counts["ns0_strip_error"] += 1
195
  else:
196
  counts["extracted"] += 1
197
- fo.write(json.dumps({"pageid": pageid, "revid": revid, "title": title, "timestamp": timestamp,
198
- "wikitext_chars": len(wikitext), "text": text}, ensure_ascii=False) + "\n")
199
- result = {"shard": src.name, "counts": dict(counts), "copyvio_tagged": copyvio}
 
 
 
 
200
  save(dst.with_name(src.name + ".counts.json"), result)
201
  tmp.rename(dst)
202
  return result
@@ -217,10 +287,12 @@ def extract(out: Path, workers: int) -> None:
217
 
218
 
219
  def prepare(out: Path) -> None:
220
- """Label each page, drop exact duplicates keeping the lowest page id, write the build input."""
 
 
221
  files = load(out / "selection.json")["files"]
222
  seen, counts = set(), Counter()
223
- duplicates = []
224
  zst = subprocess.Popen(["zstd", "-q", "-f", "-3", "-o", str(out / f"{SOURCE}.jsonl.zst")],
225
  stdin=subprocess.PIPE)
226
  with gzip.open(out / "manifest.jsonl.gz", "wt", encoding="utf-8") as manifest:
@@ -234,6 +306,13 @@ def prepare(out: Path) -> None:
234
  duplicates.append(row["pageid"])
235
  continue
236
  seen.add(key)
 
 
 
 
 
 
 
237
  label = license_for_revision(row["timestamp"])
238
  counts[label] += 1
239
  row_id, url = f"{SOURCE}_{row['pageid']}", page_url(row["title"])
@@ -249,8 +328,14 @@ def prepare(out: Path) -> None:
249
  zst.stdin.close()
250
  if zst.wait():
251
  raise RuntimeError("zstd failed")
 
 
 
252
  counts["exact_duplicate"] = len(duplicates)
253
- save(out / "prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates})
 
 
 
254
  print(dict(counts))
255
 
256
 
@@ -276,6 +361,8 @@ def attribution(out: Path, data_dir: Path) -> None:
276
  "by_sa_4_cutoff": selection["by_sa_4_cutoff"], "discovered_at": selection["observed_at"],
277
  "extract": dict(sum((Counter(s["counts"]) for s in shards), Counter())),
278
  "copyvio_tagged": [p for s in shards for p in s["copyvio_tagged"]],
 
 
279
  "prepare": load(out / "prepare.json"),
280
  "attribution_rows": n, "attribution_sha256": digest((data_dir / f"{SOURCE}.attribution.jsonl").read_bytes()),
281
  })
 
8
  B=<build dir, never committed>
9
  python3 src/fetch_wikipedia.py discover --out $B # shards, sha1s, licence evidence
10
  python3 src/fetch_wikipedia.py acquire --out $B # resumable download + sha1 check
11
+ python3 src/fetch_wikipedia.py extract --out $B # ns 0, no redirects, no copyvio tag; {{ek}} recorded
12
+ python3 src/fetch_wikipedia.py prepare --out $B # $B/wikipedia.jsonl.zst; drops duplicates,
13
+ # COPIED_PAGES, copyright {{ek}} pages
14
  python3 src/build_dynaword.py --sources wikipedia --speakleash-dir $B --out .
15
  python3 src/fetch_wikipedia.py attribution --out $B # data/wikipedia sidecars
16
  """
 
59
  # plwiki copyright-violation notice and its redirects (Szablon:NPA <- Copyvio, Plagiat).
60
  # Namespace prefix is case-insensitive, the first letter of the name too.
61
  COPYVIO_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?(?:[Nn]PA|[Cc]opyvio|[Pp]lagiat)\s*(?:\||\}\})")
62
+ # plwiki speedy-deletion template and its redirects (Szablon:Ek <- EK, Ekspresowe kasowanko,
63
+ # Usuń, Speedy, Delete); its first parameter (or powód=) is the stated reason.
64
+ EK_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?"
65
+ r"(?:[Ee][Kk]|[Ee]kspresowe[ _]+kasowanko|[Uu]suń|[Ss]peedy|[Dd]elete)\s*(?:\||\}\})")
66
+ EK_NAMES = {"Ek", "EK", "Ekspresowe kasowanko", "Usuń", "Speedy", "Delete"}
67
+ # The build records every template redirect to these, so the alias lists above can be checked against the dump.
68
+ TAG_TEMPLATES = {"Szablon:NPA", "Szablon:Ek"}
69
+ # Pages the copyright sample (data/wikipedia/wikipedia.copyvio-sample.jsonl) found to hold text
70
+ # copied or closely paraphrased from a copyrighted source. Keyed on the wiki page id, which is
71
+ # stable across dumps (the dataset id is derived from it). prepare fails if one is not reached.
72
+ COPIED_PAGES = {
73
+ 833396: "Obnażyć prawdę: the 'Opis fabuły' paragraph closely paraphrases Filmweb's production "
74
+ "description of the film; added in revision 15302011 (2008-12-26), which cites Filmweb",
75
+ 1126780: "Czarnka: the lake paragraph (revision 42979631, 2015-06-19) closely paraphrases the "
76
+ "Drawieński Park Narodowy page dpn.pl/czarne, archived 2012-01-25; whether Art. 4 of the "
77
+ "Polish copyright act (official materials) applies was not assessed",
78
+ }
79
+ # {{ek}} reasons that state a copyright violation: the template's own codes that render as
80
+ # "naruszenie praw autorskich" (npa, plagiat, copypaste, kopiuj-wklej) and free text naming one
81
+ # (copyvio, "praw autorskich"). "kopia"/"skopiowane" alone are left out: on plwiki they also
82
+ # mark a duplicate of another article, which is not a copyright reason.
83
+ EK_COPYRIGHT_RE = re.compile(
84
+ r"\bnpa\b|copyvio|plagiat|copy[ -]?paste|kopiuj[ -]?wklej|praw\w* autorsk", re.IGNORECASE)
85
  # Links that render as an image or a category, not as running text ([[:Kategoria:X]] is a text link).
86
  NON_PROSE_NS = {"plik", "file", "image", "grafika", "media", "kategoria", "category"}
87
  SWITCH_RE = re.compile(r"__[A-ZĄĆĘŁŃÓŚŹŻ]+__") # __NOTOC__, __BEZSPISU__
 
115
  return SWITCH_RE.sub("", text).strip()
116
 
117
 
118
+ def _template_name(template) -> str:
119
+ """MediaWiki title of a template call: namespace prefix dropped, _ as space, first letter upper."""
120
+ name = " ".join(str(template.name).replace("_", " ").split())
121
+ prefix, sep, rest = name.partition(":")
122
+ if sep and prefix.strip().lower() in ("szablon", "template"):
123
+ name = rest.strip()
124
+ return name[:1].upper() + name[1:]
125
+
126
+
127
+ def _param(template, *names) -> str:
128
+ for name in names:
129
+ if template.has(name):
130
+ return str(template.get(name).value).strip()
131
+ return ""
132
+
133
+
134
+ def ek_tag(wikitext: str) -> dict | None:
135
+ """Stated reason and source of the page's first {{ek}} speedy-deletion notice; None without one
136
+ (a call inside a comment or <nowiki> is not a notice)."""
137
+ if not EK_RE.search(wikitext):
138
+ return None
139
+ import mwparserfromhell
140
+ for template in mwparserfromhell.parse(wikitext).filter_templates():
141
+ if _template_name(template) in EK_NAMES:
142
+ return {"reason": _param(template, "1", "powód"), "source": _param(template, "2", "źródło")}
143
+ return None
144
+
145
+
146
+ def ek_is_copyright(ek: dict) -> bool:
147
+ """True when an {{ek}} notice's stated reason is a copyright violation."""
148
+ return bool(EK_COPYRIGHT_RE.search(ek["reason"]))
149
+
150
+
151
  def license_for_revision(timestamp: str | None) -> str:
152
  """SPDX label for a page whose last revision is at `timestamp` (ISO 8601 with zone)."""
153
  if not timestamp:
 
207
 
208
 
209
  def pages(fh):
210
+ """Yield (pageid, revid, ns, title, timestamp, redirect_target, wikitext) per <page>;
211
+ redirect_target is "" unless the page is a redirect."""
212
  ids, title = [], None
213
  ns = timestamp = text = None
214
+ redirect = ""
215
  for _, el in iterparse(fh, events=("end",)):
216
  tag = _local(el.tag)
217
  if tag == "title":
 
222
  ids.append(el.text)
223
  elif tag == "timestamp":
224
  timestamp = el.text
225
+ elif tag == "redirect": # <redirect title="target" />
226
+ redirect = el.get("title") or "(no target)"
227
  elif tag == "text":
228
  text = el.text
229
  elif tag == "page":
230
  yield ids[0], ids[1], ns, title, timestamp, redirect, text or ""
231
+ ids, title, ns, timestamp, text, redirect = [], None, None, None, None, ""
232
  el.clear()
233
 
234
 
235
  def extract_shard(src: Path, dst: Path) -> dict:
236
+ counts, copyvio, ek_tagged, tag_redirects = Counter(), [], [], []
237
  tmp = dst.with_suffix(".tmp")
238
  with bz2.open(src, "rb") as fh, gzip.open(tmp, "wt", encoding="utf-8") as fo:
239
  for pageid, revid, ns, title, timestamp, redirect, wikitext in pages(fh):
240
  counts["pages"] += 1
241
+ if ns == "10" and redirect in TAG_TEMPLATES:
242
+ tag_redirects.append({"title": title, "target": redirect})
243
  if ns != "0":
244
  continue
245
  counts["ns0"] += 1
246
  if redirect:
247
  counts["ns0_redirect"] += 1
248
+ continue
249
+ if not wikitext.strip():
250
  counts["ns0_empty"] += 1
251
+ continue
252
+ ek = ek_tag(wikitext) # recorded on every article; prepare drops the copyright ones
253
+ if ek is not None:
254
+ counts["ns0_ek_tag"] += 1
255
+ ek_tagged.append({"pageid": pageid, "title": title, **ek})
256
+ if COPYVIO_RE.search(wikitext):
257
  counts["ns0_copyvio_tag"] += 1
258
  copyvio.append({"pageid": pageid, "title": title})
259
  elif (text := strip_article(wikitext)) is None:
260
  counts["ns0_strip_error"] += 1
261
  else:
262
  counts["extracted"] += 1
263
+ row = {"pageid": pageid, "revid": revid, "title": title, "timestamp": timestamp,
264
+ "wikitext_chars": len(wikitext), "text": text}
265
+ if ek is not None:
266
+ row["ek"] = ek
267
+ fo.write(json.dumps(row, ensure_ascii=False) + "\n")
268
+ result = {"shard": src.name, "counts": dict(counts), "copyvio_tagged": copyvio,
269
+ "ek_tagged": ek_tagged, "tag_template_redirects": tag_redirects}
270
  save(dst.with_name(src.name + ".counts.json"), result)
271
  tmp.rename(dst)
272
  return result
 
287
 
288
 
289
  def prepare(out: Path) -> None:
290
+ """Label each page, drop exact duplicates keeping the lowest page id, drop COPIED_PAGES and
291
+ pages whose {{ek}} notice gives a copyright reason, write the build input. A dropped page's
292
+ text stays in `seen`, so a later page with the same text is dropped as its duplicate."""
293
  files = load(out / "selection.json")["files"]
294
  seen, counts = set(), Counter()
295
+ duplicates, copied, ek_copyright = [], [], []
296
  zst = subprocess.Popen(["zstd", "-q", "-f", "-3", "-o", str(out / f"{SOURCE}.jsonl.zst")],
297
  stdin=subprocess.PIPE)
298
  with gzip.open(out / "manifest.jsonl.gz", "wt", encoding="utf-8") as manifest:
 
306
  duplicates.append(row["pageid"])
307
  continue
308
  seen.add(key)
309
+ if int(row["pageid"]) in COPIED_PAGES:
310
+ copied.append({"pageid": row["pageid"], "title": row["title"],
311
+ "reason": COPIED_PAGES[int(row["pageid"])]})
312
+ continue
313
+ if "ek" in row and ek_is_copyright(row["ek"]):
314
+ ek_copyright.append({"pageid": row["pageid"], "title": row["title"], **row["ek"]})
315
+ continue
316
  label = license_for_revision(row["timestamp"])
317
  counts[label] += 1
318
  row_id, url = f"{SOURCE}_{row['pageid']}", page_url(row["title"])
 
328
  zst.stdin.close()
329
  if zst.wait():
330
  raise RuntimeError("zstd failed")
331
+ missing = set(COPIED_PAGES) - {int(p["pageid"]) for p in copied}
332
+ if missing:
333
+ raise ValueError(f"COPIED_PAGES not reached (gone from the dump, tagged or a duplicate): {sorted(missing)}")
334
  counts["exact_duplicate"] = len(duplicates)
335
+ counts["copied_page"] = len(copied)
336
+ counts["ek_copyright"] = len(ek_copyright)
337
+ save(out / "prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates,
338
+ "copied_pages": copied, "ek_copyright": ek_copyright})
339
  print(dict(counts))
340
 
341
 
 
361
  "by_sa_4_cutoff": selection["by_sa_4_cutoff"], "discovered_at": selection["observed_at"],
362
  "extract": dict(sum((Counter(s["counts"]) for s in shards), Counter())),
363
  "copyvio_tagged": [p for s in shards for p in s["copyvio_tagged"]],
364
+ "ek_tagged": [p for s in shards for p in s["ek_tagged"]],
365
+ "tag_template_redirects": [r for s in shards for r in s["tag_template_redirects"]],
366
  "prepare": load(out / "prepare.json"),
367
  "attribution_rows": n, "attribution_sha256": digest((data_dir / f"{SOURCE}.attribution.jsonl").read_bytes()),
368
  })
src/sources.py CHANGED
@@ -125,9 +125,12 @@ SOURCES = {
125
  "v0.2.0-v0.2.5 used the SpeakLeash plwiki snapshot; that intermediary "
126
  "was removed in the v0.2.6 rebuild.",
127
  "legal_note": "Pages carrying the plwiki copyright-violation notice {{NPA}} (or its "
128
- "redirects {{Copyvio}}, {{Plagiat}}) in the dump are dropped. Text "
129
- "pasted into an article without such a notice cannot be detected; a "
130
- "stratified web sample is recorded in wikipedia.license-evidence.json.",
 
 
 
131
  "license": "CC BY-SA (3.0 or 4.0 per record, by last-revision date)",
132
  "license_spdx": "MIXED",
133
  "traceable": "Contributors license their text under CC BY-SA 4.0 since the Wikimedia "
 
125
  "v0.2.0-v0.2.5 used the SpeakLeash plwiki snapshot; that intermediary "
126
  "was removed in the v0.2.6 rebuild.",
127
  "legal_note": "Pages carrying the plwiki copyright-violation notice {{NPA}} (or its "
128
+ "redirects {{Copyvio}}, {{Plagiat}}) in the dump are dropped, as are "
129
+ "pages whose speedy-deletion notice {{ek}} gives a copyright reason and "
130
+ "the pages the copyright sample found copied (COPIED_PAGES in "
131
+ "src/fetch_wikipedia.py). Other text pasted into an article cannot be "
132
+ "detected; the stratified web sample is recorded in "
133
+ "wikipedia.license-evidence.json.",
134
  "license": "CC BY-SA (3.0 or 4.0 per record, by last-revision date)",
135
  "license_spdx": "MIXED",
136
  "traceable": "Contributors license their text under CC BY-SA 4.0 since the Wikimedia "
src/test_wikipedia_contract.py CHANGED
@@ -57,6 +57,36 @@ def test_copyvio_tag(wikitext, tagged):
57
  assert bool(fw.COPYVIO_RE.search(wikitext)) is tagged
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def test_strip_article_drops_markup_left_by_strip_code():
61
  wikitext = ("'''Ala''' ma kota<ref>Jan K., ''Koty'', 2001.</ref> i psa<ref name=\"x\" />.\n"
62
  "[[Plik:Kot.jpg|thumb|250px|Kot [[Ala|Ali]]]]\n[[File:a.png|mały|x]]\n"
@@ -67,24 +97,32 @@ def test_strip_article_drops_markup_left_by_strip_code():
67
 
68
  # --- dump pipeline on a fixture ------------------------------------------------------------
69
 
70
- def _page(pageid, title, ns, timestamp, text, redirect=False):
71
  return (f"<page><title>{title}</title><ns>{ns}</ns><id>{pageid}</id>"
72
- + ('<redirect title="Ala" />' if redirect else "")
73
  + f"<revision><id>{pageid * 100}</id><parentid>1</parentid><timestamp>{timestamp}</timestamp>"
74
  f"<contributor><username>U</username><id>7</id></contributor>"
75
  f"<text bytes=\"1\">{text}</text><sha1>x</sha1></revision></page>")
76
 
77
 
78
  BODY = "Ala jest polskim imieniem żeńskim, noszonym przez wiele znanych osób w różnych epokach. " * 4
 
 
 
79
  OTHER = "Pies domowy jest udomowionym ssakiem z rodziny psowatych, towarzyszem człowieka od wieków. " * 4
80
  XML = ('<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/"><siteinfo><sitename>W</sitename></siteinfo>'
81
  + _page(10, "Ala", 0, "2023-06-07T00:00:00Z", BODY + "[[Kategoria:Imiona]]")
82
- + _page(11, "Przekierowanie", 0, "2020-01-01T00:00:00Z", "#PATRZ [[Ala]]", redirect=True)
83
  + _page(12, "Dyskusja:Ala", 1, "2020-01-01T00:00:00Z", BODY)
84
  + _page(13, "Kot", 0, "2020-01-01T00:00:00Z", "{{NPA|http://x.pl}}" + OTHER)
85
  + _page(14, "Ala (imię)", 0, "2010-01-01T00:00:00Z", BODY)
86
  + _page(15, "Pusty", 0, "2010-01-01T00:00:00Z", "")
87
  + _page(16, "Pies", 0, "2023-06-06T23:59:59Z", OTHER)
 
 
 
 
 
88
  + "</mediawiki>")
89
  SHARD = "plwiki-20260901-pages-articles1.xml-p1p20.bz2"
90
 
@@ -92,11 +130,12 @@ SHARD = "plwiki-20260901-pages-articles1.xml-p1p20.bz2"
92
  def test_pages_reads_page_and_revision_ids_not_contributor_id():
93
  rows = list(fw.pages(io.BytesIO(XML.encode())))
94
  assert [r[:3] for r in rows][:2] == [("10", "1000", "0"), ("11", "1100", "0")]
95
- assert rows[1][5] is True and rows[0][5] is False
96
 
97
 
98
  @pytest.mark.skipif(shutil.which("zstd") is None, reason="zstd CLI")
99
- def test_extract_prepare_attribution_end_to_end(tmp_path):
 
100
  (tmp_path / "raw_dump").mkdir()
101
  (tmp_path / "extracted").mkdir()
102
  (tmp_path / "raw_dump" / SHARD).write_bytes(bz2.compress(XML.encode()))
@@ -105,21 +144,29 @@ def test_extract_prepare_attribution_end_to_end(tmp_path):
105
  "files": [{"name": SHARD}], "rightsinfo": {}, "terms_of_use": {}, "by_sa_4_cutoff": "c",
106
  })
107
  result = fw.extract_shard(tmp_path / "raw_dump" / SHARD, tmp_path / "extracted" / (SHARD + ".jsonl.gz"))
108
- assert result["counts"] == {"pages": 7, "ns0": 6, "ns0_redirect": 1, "ns0_empty": 1,
109
- "ns0_copyvio_tag": 1, "extracted": 3}
110
  assert result["copyvio_tagged"] == [{"pageid": "13", "title": "Kot"}]
 
 
 
111
 
112
  fw.prepare(tmp_path)
113
  out = subprocess.run(["zstd", "-dc", str(tmp_path / "wikipedia.jsonl.zst")], capture_output=True, check=True)
114
  rows = [json.loads(line) for line in out.stdout.decode().splitlines()]
115
- assert [r["id"] for r in rows] == ["wikipedia_10", "wikipedia_16"] # 14 duplicates 10's text
116
- assert [r["license"] for r in rows] == ["CC-BY-SA-4.0", "CC-BY-SA-3.0"]
117
- assert [r["created"] for r in rows] == ["2023-06-07", "2023-06-06"]
 
 
118
  assert rows[0]["author"] == "Wikipedia contributors, https://pl.wikipedia.org/wiki/Ala"
119
- assert "Kategoria" not in rows[0]["text"]
120
  assert fw.load(tmp_path / "prepare.json") == {
121
- "counts": {"extracted": 3, "CC-BY-SA-4.0": 1, "CC-BY-SA-3.0": 1, "exact_duplicate": 1},
122
- "exact_duplicate_pageids": ["14"]}
 
 
 
123
 
124
  data = tmp_path / "data"
125
  data.mkdir()
@@ -131,6 +178,21 @@ def test_extract_prepare_attribution_end_to_end(tmp_path):
131
  "last_revision_at": "2023-06-06T23:59:59Z", "license": "CC-BY-SA-3.0"}]
132
  build = fw.load(data / "wikipedia.build.json")
133
  assert build["attribution_rows"] == 1 and build["extract"]["ns0_copyvio_tag"] == 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
 
136
  # --- released data -------------------------------------------------------------------------
@@ -157,18 +219,40 @@ def test_schema_ids_and_counts():
157
  assert schema.names == ["id", "text", "source", "added", "created", "token_count", "license", "author"]
158
  table, cols = _released()
159
  assert table.num_rows == stats["kept"] == build["attribution_rows"]
160
- assert stats["read"] == build["prepare"]["counts"]["extracted"] - build["prepare"]["counts"]["exact_duplicate"]
 
 
161
  assert stats["drop_dup"] == 0 # the fetcher already dropped exact duplicates, lowest page id kept
162
  assert len(set(cols["id"])) == table.num_rows
163
  assert all(re.fullmatch(r"wikipedia_\d+", i) for i in cols["id"])
164
  assert set(cols["source"]) == {"wikipedia"}
165
  tagged = {f"wikipedia_{p['pageid']}" for p in build["copyvio_tagged"]}
166
  assert tagged and not tagged & set(cols["id"])
 
 
 
 
 
 
167
  assert [f["name"] for f in build["files"]] == sorted(
168
  (f["name"] for f in build["files"]), key=lambda n: int(re.search(r"-p(\d+)p", n).group(1)))
169
  assert all(re.fullmatch(r"[0-9a-f]{40}", f["sha1"]) for f in build["files"])
170
 
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  def test_every_row_label_follows_its_last_revision():
173
  table, cols = _released()
174
  meta = {}
@@ -189,16 +273,24 @@ def test_every_row_label_follows_its_last_revision():
189
 
190
 
191
  def test_copyright_sample_matches_the_release():
192
- """The sample must be redrawn if the released rows change."""
 
 
 
193
  import random
194
 
195
  sample = json.loads((DATA / "wikipedia.license-evidence.json").read_text(encoding="utf-8"))["copyright_sample"]
196
  rows = [json.loads(line) for line in (DATA / sample["file"]).read_text(encoding="utf-8").splitlines()]
197
  _, cols = _released()
 
 
 
 
 
198
  random.seed(sample["seed"])
199
  expected = []
200
  for label in sorted(sample["per_stratum"]):
201
- ids = sorted((i for i, lic in zip(cols["id"], cols["license"]) if lic == label),
202
  key=lambda i: int(i.split("_")[1])) # page-id order, not parquet row order
203
  expected += [(label, i) for i in random.sample(ids, sample["per_stratum"][label])]
204
  assert [(r["stratum"], r["id"]) for r in rows] == expected
 
57
  assert bool(fw.COPYVIO_RE.search(wikitext)) is tagged
58
 
59
 
60
+ @pytest.mark.parametrize("wikitext, ek", [
61
+ ("{{ek|npa|http://x.pl}}\nTekst", {"reason": "npa", "source": "http://x.pl"}),
62
+ ("{{EK|powód=reklama}}", {"reason": "reklama", "source": ""}),
63
+ ("{{ek|1=naruszenie praw autorskich}}", {"reason": "naruszenie praw autorskich", "source": ""}),
64
+ ("{{ Szablon:Ekspresowe_kasowanko | test }}", {"reason": "test", "source": ""}),
65
+ ("{{usuń}}", {"reason": "", "source": ""}), # redirect, first letter case-insensitive
66
+ ("{{Delete|copyvio}}", {"reason": "copyvio", "source": ""}),
67
+ ("{{ek}}", {"reason": "", "source": ""}),
68
+ ("<!-- {{ek|npa}} -->Tekst", None), # commented out: not a notice
69
+ ("<nowiki>{{ek|npa}}</nowiki>", None),
70
+ ("{{Eko}}", None),
71
+ ("{{EKspresowe kasowanko|x}}", None), # only the first letter is case-insensitive
72
+ ("Skrót EK w tekście", None),
73
+ ])
74
+ def test_ek_tag(wikitext, ek):
75
+ assert fw.ek_tag(wikitext) == ek
76
+
77
+
78
+ @pytest.mark.parametrize("reason, copyright", [
79
+ ("npa", True), ("NPA", True), ("plagiat", True), ("copypaste", True), ("kopiuj-wklej", True),
80
+ ("naruszenie praw autorskich (ze strony http://x.pl)", True), ("Prawa autorskie", True),
81
+ ("copyvio z http://x.pl", True), ("copy-paste ze strony gminy", True),
82
+ ("reklama", False), ("nieency", False), ("test", False), ("", False),
83
+ ("kopia artykułu Ala", False), # duplicate of another article, not a copyright reason
84
+ ("Inpakt", False), # npa only as a whole word
85
+ ])
86
+ def test_ek_is_copyright(reason, copyright):
87
+ assert fw.ek_is_copyright({"reason": reason, "source": ""}) is copyright
88
+
89
+
90
  def test_strip_article_drops_markup_left_by_strip_code():
91
  wikitext = ("'''Ala''' ma kota<ref>Jan K., ''Koty'', 2001.</ref> i psa<ref name=\"x\" />.\n"
92
  "[[Plik:Kot.jpg|thumb|250px|Kot [[Ala|Ali]]]]\n[[File:a.png|mały|x]]\n"
 
97
 
98
  # --- dump pipeline on a fixture ------------------------------------------------------------
99
 
100
+ def _page(pageid, title, ns, timestamp, text, redirect=""):
101
  return (f"<page><title>{title}</title><ns>{ns}</ns><id>{pageid}</id>"
102
+ + (f'<redirect title="{redirect}" />' if redirect else "")
103
  + f"<revision><id>{pageid * 100}</id><parentid>1</parentid><timestamp>{timestamp}</timestamp>"
104
  f"<contributor><username>U</username><id>7</id></contributor>"
105
  f"<text bytes=\"1\">{text}</text><sha1>x</sha1></revision></page>")
106
 
107
 
108
  BODY = "Ala jest polskim imieniem żeńskim, noszonym przez wiele znanych osób w różnych epokach. " * 4
109
+ MOUSE = "Mysz domowa jest gryzoniem z rodziny myszowatych, żyjącym zwykle w pobliżu człowieka. " * 4
110
+ FROG = "Żaba trawna jest płazem bezogonowym z rodziny żabowatych, pospolitym w całej Polsce. " * 4
111
+ MOLE = "Kret europejski jest owadożernym ssakiem, który większość życia spędza pod ziemią. " * 4
112
  OTHER = "Pies domowy jest udomowionym ssakiem z rodziny psowatych, towarzyszem człowieka od wieków. " * 4
113
  XML = ('<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/"><siteinfo><sitename>W</sitename></siteinfo>'
114
  + _page(10, "Ala", 0, "2023-06-07T00:00:00Z", BODY + "[[Kategoria:Imiona]]")
115
+ + _page(11, "Przekierowanie", 0, "2020-01-01T00:00:00Z", "#PATRZ [[Ala]]", redirect="Ala")
116
  + _page(12, "Dyskusja:Ala", 1, "2020-01-01T00:00:00Z", BODY)
117
  + _page(13, "Kot", 0, "2020-01-01T00:00:00Z", "{{NPA|http://x.pl}}" + OTHER)
118
  + _page(14, "Ala (imię)", 0, "2010-01-01T00:00:00Z", BODY)
119
  + _page(15, "Pusty", 0, "2010-01-01T00:00:00Z", "")
120
  + _page(16, "Pies", 0, "2023-06-06T23:59:59Z", OTHER)
121
+ + _page(17, "Mysz", 0, "2021-01-01T00:00:00Z", "{{ek|npa|http://y.pl}}" + MOUSE)
122
+ + _page(18, "Żaba", 0, "2021-01-01T00:00:00Z", "{{ek|reklama}}" + FROG)
123
+ + _page(19, "Kopia", 0, "2021-01-01T00:00:00Z", MOUSE) # same text as 17
124
+ + _page(20, "Kret", 0, "2021-01-01T00:00:00Z", MOLE)
125
+ + _page(21, "Szablon:Usuń", 10, "2020-01-01T00:00:00Z", "#PATRZ [[Szablon:Ek]]", redirect="Szablon:Ek")
126
  + "</mediawiki>")
127
  SHARD = "plwiki-20260901-pages-articles1.xml-p1p20.bz2"
128
 
 
130
  def test_pages_reads_page_and_revision_ids_not_contributor_id():
131
  rows = list(fw.pages(io.BytesIO(XML.encode())))
132
  assert [r[:3] for r in rows][:2] == [("10", "1000", "0"), ("11", "1100", "0")]
133
+ assert rows[1][5] == "Ala" and rows[0][5] == ""
134
 
135
 
136
  @pytest.mark.skipif(shutil.which("zstd") is None, reason="zstd CLI")
137
+ def test_extract_prepare_attribution_end_to_end(tmp_path, monkeypatch):
138
+ monkeypatch.setattr(fw, "COPIED_PAGES", {20: "Kret: copied"})
139
  (tmp_path / "raw_dump").mkdir()
140
  (tmp_path / "extracted").mkdir()
141
  (tmp_path / "raw_dump" / SHARD).write_bytes(bz2.compress(XML.encode()))
 
144
  "files": [{"name": SHARD}], "rightsinfo": {}, "terms_of_use": {}, "by_sa_4_cutoff": "c",
145
  })
146
  result = fw.extract_shard(tmp_path / "raw_dump" / SHARD, tmp_path / "extracted" / (SHARD + ".jsonl.gz"))
147
+ assert result["counts"] == {"pages": 12, "ns0": 10, "ns0_redirect": 1, "ns0_empty": 1,
148
+ "ns0_copyvio_tag": 1, "ns0_ek_tag": 2, "extracted": 7}
149
  assert result["copyvio_tagged"] == [{"pageid": "13", "title": "Kot"}]
150
+ assert result["ek_tagged"] == [{"pageid": "17", "title": "Mysz", "reason": "npa", "source": "http://y.pl"},
151
+ {"pageid": "18", "title": "Żaba", "reason": "reklama", "source": ""}]
152
+ assert result["tag_template_redirects"] == [{"title": "Szablon:Usuń", "target": "Szablon:Ek"}]
153
 
154
  fw.prepare(tmp_path)
155
  out = subprocess.run(["zstd", "-dc", str(tmp_path / "wikipedia.jsonl.zst")], capture_output=True, check=True)
156
  rows = [json.loads(line) for line in out.stdout.decode().splitlines()]
157
+ # 14 duplicates 10's text; 17 (ek: npa) and 20 (COPIED_PAGES) are dropped, and 19, a copy
158
+ # of 17's text, goes with it as a duplicate; 18's ek reason is not copyright, so it stays
159
+ assert [r["id"] for r in rows] == ["wikipedia_10", "wikipedia_16", "wikipedia_18"]
160
+ assert [r["license"] for r in rows] == ["CC-BY-SA-4.0", "CC-BY-SA-3.0", "CC-BY-SA-3.0"]
161
+ assert [r["created"] for r in rows] == ["2023-06-07", "2023-06-06", "2021-01-01"]
162
  assert rows[0]["author"] == "Wikipedia contributors, https://pl.wikipedia.org/wiki/Ala"
163
+ assert "Kategoria" not in rows[0]["text"] and "reklama" not in rows[2]["text"]
164
  assert fw.load(tmp_path / "prepare.json") == {
165
+ "counts": {"extracted": 7, "CC-BY-SA-4.0": 1, "CC-BY-SA-3.0": 2, "exact_duplicate": 2,
166
+ "copied_page": 1, "ek_copyright": 1},
167
+ "exact_duplicate_pageids": ["14", "19"],
168
+ "copied_pages": [{"pageid": "20", "title": "Kret", "reason": "Kret: copied"}],
169
+ "ek_copyright": [{"pageid": "17", "title": "Mysz", "reason": "npa", "source": "http://y.pl"}]}
170
 
171
  data = tmp_path / "data"
172
  data.mkdir()
 
178
  "last_revision_at": "2023-06-06T23:59:59Z", "license": "CC-BY-SA-3.0"}]
179
  build = fw.load(data / "wikipedia.build.json")
180
  assert build["attribution_rows"] == 1 and build["extract"]["ns0_copyvio_tag"] == 1
181
+ assert [p["pageid"] for p in build["ek_tagged"]] == ["17", "18"]
182
+ assert build["tag_template_redirects"] == [{"title": "Szablon:Usuń", "target": "Szablon:Ek"}]
183
+
184
+
185
+ @pytest.mark.skipif(shutil.which("zstd") is None, reason="zstd CLI")
186
+ def test_prepare_fails_when_a_listed_page_is_not_reached(tmp_path, monkeypatch):
187
+ (tmp_path / "extracted").mkdir()
188
+ fw.save(tmp_path / "selection.json", {"files": [{"name": SHARD}]})
189
+ import gzip
190
+ with gzip.open(tmp_path / "extracted" / (SHARD + ".jsonl.gz"), "wt", encoding="utf-8") as fo:
191
+ fo.write(json.dumps({"pageid": "10", "revid": "1", "title": "Ala", "timestamp": "2020-01-01T00:00:00Z",
192
+ "text": BODY}) + "\n")
193
+ monkeypatch.setattr(fw, "COPIED_PAGES", {99: "gone"})
194
+ with pytest.raises(ValueError, match="99"):
195
+ fw.prepare(tmp_path)
196
 
197
 
198
  # --- released data -------------------------------------------------------------------------
 
219
  assert schema.names == ["id", "text", "source", "added", "created", "token_count", "license", "author"]
220
  table, cols = _released()
221
  assert table.num_rows == stats["kept"] == build["attribution_rows"]
222
+ counts = build["prepare"]["counts"]
223
+ assert stats["read"] == (counts["extracted"] - counts["exact_duplicate"]
224
+ - counts["copied_page"] - counts["ek_copyright"])
225
  assert stats["drop_dup"] == 0 # the fetcher already dropped exact duplicates, lowest page id kept
226
  assert len(set(cols["id"])) == table.num_rows
227
  assert all(re.fullmatch(r"wikipedia_\d+", i) for i in cols["id"])
228
  assert set(cols["source"]) == {"wikipedia"}
229
  tagged = {f"wikipedia_{p['pageid']}" for p in build["copyvio_tagged"]}
230
  assert tagged and not tagged & set(cols["id"])
231
+ copied = {p["pageid"] for p in build["prepare"]["copied_pages"]}
232
+ assert copied == {str(i) for i in fw.COPIED_PAGES}
233
+ ek = build["prepare"]["ek_copyright"]
234
+ assert len(ek) == counts["ek_copyright"] and all(fw.ek_is_copyright(p) for p in ek)
235
+ dropped = {f"wikipedia_{i}" for i in copied | {p["pageid"] for p in ek}}
236
+ assert not dropped & set(cols["id"])
237
  assert [f["name"] for f in build["files"]] == sorted(
238
  (f["name"] for f in build["files"]), key=lambda n: int(re.search(r"-p(\d+)p", n).group(1)))
239
  assert all(re.fullmatch(r"[0-9a-f]{40}", f["sha1"]) for f in build["files"])
240
 
241
 
242
+ def test_tag_template_aliases_match_the_dump():
243
+ """Every redirect to the notice templates in the dump is one the matchers know."""
244
+ build = json.loads((DATA / "wikipedia.build.json").read_text(encoding="utf-8"))
245
+ names = {}
246
+ for r in build["tag_template_redirects"]:
247
+ names.setdefault(r["target"], set()).add(r["title"].removeprefix("Szablon:"))
248
+ assert names["Szablon:Ek"] == fw.EK_NAMES - {"Ek"}
249
+ assert names["Szablon:NPA"] == {"Copyvio", "Plagiat"}
250
+ for name in names["Szablon:NPA"] | {"NPA"}:
251
+ assert fw.COPYVIO_RE.search("{{%s|http://x.pl}}" % name)
252
+ for name in fw.EK_NAMES:
253
+ assert fw.ek_tag("{{%s|npa}}" % name) == {"reason": "npa", "source": ""}
254
+
255
+
256
  def test_every_row_label_follows_its_last_revision():
257
  table, cols = _released()
258
  meta = {}
 
273
 
274
 
275
  def test_copyright_sample_matches_the_release():
276
+ """The sample must be redrawn if the released rows change, except by the copyright drops.
277
+
278
+ It was drawn from an earlier build; the rows dropped since are listed with their label, so
279
+ the draw is reproduced from the release plus those rows, and each must be a copyright drop."""
280
  import random
281
 
282
  sample = json.loads((DATA / "wikipedia.license-evidence.json").read_text(encoding="utf-8"))["copyright_sample"]
283
  rows = [json.loads(line) for line in (DATA / sample["file"]).read_text(encoding="utf-8").splitlines()]
284
  _, cols = _released()
285
+ prepare = json.loads((DATA / "wikipedia.build.json").read_text(encoding="utf-8"))["prepare"]
286
+ copyright_drops = {f"wikipedia_{p['pageid']}" for p in prepare["copied_pages"] + prepare["ek_copyright"]}
287
+ dropped = dict(sample["population"]["rows_dropped_since"])
288
+ assert set(dropped) <= copyright_drops and not set(dropped) & set(cols["id"])
289
+ population = list(zip(cols["id"], cols["license"])) + list(dropped.items())
290
  random.seed(sample["seed"])
291
  expected = []
292
  for label in sorted(sample["per_stratum"]):
293
+ ids = sorted((i for i, lic in population if lic == label),
294
  key=lambda i: int(i.split("_")[1])) # page-id order, not parquet row order
295
  expected += [(label, i) for i in random.sample(ids, sample["per_stratum"][label])]
296
  assert [(r["stratum"], r["id"]) for r in rows] == expected