wikinews: label each page CC BY 2.5 or 4.0 by its last revision (v0.2.6, v2#57)
#77
by ppuzio - opened
- artifacts/source_findings.md +38 -0
- data/wikinews/wikinews.attribution.jsonl +3 -0
- data/wikinews/wikinews.build.json +53 -0
- data/wikinews/wikinews.license-evidence.json +74 -0
- data/wikinews/wikinews.md +68 -14
- data/wikinews/wikinews.parquet +2 -2
- data/wikinews/wikinews.stats.json +8 -7
- src/fetch_wikimedia.py +467 -86
- src/fetch_wikipedia.py +1 -18
- src/rights.py +32 -0
- src/sources.py +23 -9
- src/test_wikimedia_contract.py +385 -0
- src/test_wikinews_contract.py +12 -0
artifacts/source_findings.md
CHANGED
|
@@ -1889,3 +1889,41 @@ NERGAL pass (#60).
|
|
| 1889 |
**Lesson:** a label-anchored phone regex with no number-shape guard turns amounts and part
|
| 1890 |
numbers into "phones"; check redactions for false positives, not only misses. Keep the raw
|
| 1891 |
download recipe runnable: a rescrub of already-redacted text cannot undo a false positive.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1889 |
**Lesson:** a label-anchored phone regex with no number-shape guard turns amounts and part
|
| 1890 |
numbers into "phones"; check redactions for false positives, not only misses. Keep the raw
|
| 1891 |
download recipe runnable: a rescrub of already-redacted text cannot undo a false positive.
|
| 1892 |
+
|
| 1893 |
+
## wikinews — Polish Wikinews (rebuild from the official dump, 2.5/4.0 labels)
|
| 1894 |
+
|
| 1895 |
+
**Investigated** — 2026-10-06 (October 2026 rights audit, `artifacts/rights_audit_2026-10/reports/wikis_ugc.md`,
|
| 1896 |
+
`reports/citations.md` L17-26; slayerlabs/polish-dynaword-v2#57).
|
| 1897 |
+
|
| 1898 |
+
**Verdict** — `kept`, relabelled; rebuilt from the official dump so the label follows the
|
| 1899 |
+
page's last revision. Documents, characters and tokens are unchanged from v0.2.5
|
| 1900 |
+
(24,386 / 32,524,646 / 12,141,355); the text multiset is identical. Labels per record:
|
| 1901 |
+
`CC-BY-2.5` 17,581 documents (8,956,397 tokens, 73.8%), `CC-BY-4.0` 6,805 (3,184,958, 26.2%);
|
| 1902 |
+
v0.2.5 labelled every row `CC-BY-2.5`. Row ids are now `wikinews_<page id>`; `author` is the
|
| 1903 |
+
page URL and `created` the last-revision date (v0.2.5: empty `author`, and the same range
|
| 1904 |
+
string "2005-01-01, 2025-12-31" as `created` on every row). The parquet `added` column is
|
| 1905 |
+
2026-07-19 (v0.2.5: 2026-06-15).
|
| 1906 |
+
|
| 1907 |
+
**Enumeration** — `plwikinews-20260601-pages-articles.xml.bz2` (sha1 `bfad5f33…` matched to
|
| 1908 |
+
the dump's `sha1sums.txt`), parsed by `src/fetch_wikimedia.py`: 65,253 pages → 47,845 in
|
| 1909 |
+
namespace 0 → 23,366 redirects and 87 pages under 200 characters skipped → 24,392 written →
|
| 1910 |
+
6 non-Polish dropped by `build_dynaword.py` → 24,386. Text conversion is the v0.2.5 one
|
| 1911 |
+
(plain `strip_code`): `<ref>` bodies, `Kategoria:` links and `thumb|` file options stay in
|
| 1912 |
+
the text; nothing was changed in this PR. One sidecar line per row
|
| 1913 |
+
(`wikinews.attribution.jsonl`).
|
| 1914 |
+
|
| 1915 |
+
**License evidence** — verified, read 2026-10-06: pl.wikinews terms of use (oldid 342796:
|
| 1916 |
+
CC BY 2.5 until 2024-12-16, CC BY 4.0 since), Gerrit 1101867 (merged 2024-12-16 08:07 UTC),
|
| 1917 |
+
Phabricator T381421, the 2.5 legal code (§4(a): no later-version clause), pl.wikinews
|
| 1918 |
+
`rightsinfo` (BY 4.0). The 08:32:24 UTC sync time is from the audit and was not re-read.
|
| 1919 |
+
Cutoff is 2024-12-16 00:00 UTC for the whole day: 6 documents were last edited that day, 2 of
|
| 1920 |
+
them before 08:32:24 UTC and so strictly under 2.5. Inferred: because CC BY 2.5 has no
|
| 1921 |
+
later-version clause, the `CC-BY-4.0` label for post-switch pages rests on the site's terms
|
| 1922 |
+
page alone. This is a question for the lawyer, separate from E1 (wiki 3.0/4.0 labelling,
|
| 1923 |
+
v2#56), whose answer is still pending. The terms page also says articles created before
|
| 1924 |
+
2005-09-25 are public domain; 0 released documents were last edited before that date, so the
|
| 1925 |
+
clause does not change a label here. Evidence in `data/wikinews/wikinews.license-evidence.json`.
|
| 1926 |
+
|
| 1927 |
+
**Blockers** — none to merge. Open: lawyer on the 2.5 → 4.0 label and on E1; the 2 boundary
|
| 1928 |
+
documents; copyright pastes in news text (the audit's 100-document press-copying sample was
|
| 1929 |
+
not run); the markup residue above.
|
data/wikinews/wikinews.attribution.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d5a6f9bd4714a5cc5ab9c4e3343254849e7bccf0195d609235ea07919ed5c1f
|
| 3 |
+
size 7843102
|
data/wikinews/wikinews.build.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attribution_rows": 24386,
|
| 3 |
+
"attribution_sha256": "0d5a6f9bd4714a5cc5ab9c4e3343254849e7bccf0195d609235ea07919ed5c1f",
|
| 4 |
+
"cutoff": "2024-12-16T00:00:00+00:00",
|
| 5 |
+
"discovered_at": "2026-10-06T00:00:15.478622+00:00",
|
| 6 |
+
"dump_base": "https://dumps.wikimedia.org/plwikinews/20260601",
|
| 7 |
+
"dump_date": "20260601",
|
| 8 |
+
"file": {
|
| 9 |
+
"name": "plwikinews-20260601-pages-articles.xml.bz2",
|
| 10 |
+
"sha1": "bfad5f33667756de4ded97756d370d7fdec39bcb",
|
| 11 |
+
"size": 21980828,
|
| 12 |
+
"url": "https://dumps.wikimedia.org/plwikinews/20260601/plwikinews-20260601-pages-articles.xml.bz2"
|
| 13 |
+
},
|
| 14 |
+
"labels": {
|
| 15 |
+
"after": "CC-BY-4.0",
|
| 16 |
+
"before": "CC-BY-2.5"
|
| 17 |
+
},
|
| 18 |
+
"prepare": {
|
| 19 |
+
"counts": {
|
| 20 |
+
"CC-BY-2.5": 17587,
|
| 21 |
+
"CC-BY-4.0": 6805,
|
| 22 |
+
"ns0": 47845,
|
| 23 |
+
"ns0_redirect": 23366,
|
| 24 |
+
"ns0_short": 87,
|
| 25 |
+
"pages": 65253,
|
| 26 |
+
"written": 24392
|
| 27 |
+
},
|
| 28 |
+
"exact_duplicate_pageids": []
|
| 29 |
+
},
|
| 30 |
+
"rightsinfo": {
|
| 31 |
+
"text": "Creative Commons Attribution 4.0",
|
| 32 |
+
"url": "https://creativecommons.org/licenses/by/4.0/",
|
| 33 |
+
"url_queried": "https://pl.wikinews.org/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo"
|
| 34 |
+
},
|
| 35 |
+
"sha1sums_url": "https://dumps.wikimedia.org/plwikinews/20260601/plwikinews-20260601-sha1sums.txt",
|
| 36 |
+
"switch": {
|
| 37 |
+
"gerrit": "https://gerrit.wikimedia.org/r/changes/operations%2Fmediawiki-config~1101867",
|
| 38 |
+
"gerrit_status": "MERGED",
|
| 39 |
+
"gerrit_submitted": "2024-12-16 08:07:33.000000000",
|
| 40 |
+
"merged_utc": "2024-12-16 08:07",
|
| 41 |
+
"phabricator": "https://phabricator.wikimedia.org/T381421",
|
| 42 |
+
"synced_by_utc": "2024-12-16 08:32:24"
|
| 43 |
+
},
|
| 44 |
+
"terms": [
|
| 45 |
+
{
|
| 46 |
+
"effective": "udostępnia swoją treść na licencji Creative Commons Uznanie autorstwa 4.0 od 16 grudnia 2024 roku",
|
| 47 |
+
"sha256": "8b461acb8e0608eb906e59d9669bc003759d7840d82fc934f83d160a72895de3",
|
| 48 |
+
"statement": "a wcześniej na licencji. [http://creativecommons.org/licenses/by/2.5/deed.pl Creative Commons Uznanie autorstwa 2.5]",
|
| 49 |
+
"title": "pl.wikinews terms of use (CC BY 2.5 until 2024-12-16, CC BY 4.0 since)",
|
| 50 |
+
"url": "https://pl.wikinews.org/w/index.php?title=Wikinews:Warunki_u%C5%BCycia&oldid=342796&action=raw"
|
| 51 |
+
}
|
| 52 |
+
]
|
| 53 |
+
}
|
data/wikinews/wikinews.license-evidence.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checked_at": "2026-10-06",
|
| 3 |
+
"cutoff": {
|
| 4 |
+
"after": "CC-BY-4.0",
|
| 5 |
+
"at": "2024-12-16T00:00:00+00:00",
|
| 6 |
+
"before": "CC-BY-2.5",
|
| 7 |
+
"boundary_day": {
|
| 8 |
+
"day": "2024-12-16",
|
| 9 |
+
"docs_last_edited_that_day": 6,
|
| 10 |
+
"known_switch_time_utc": "2024-12-16 08:32:24",
|
| 11 |
+
"of_which_before_that_time": 2
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"legal": [
|
| 15 |
+
{
|
| 16 |
+
"absent": "later version",
|
| 17 |
+
"section": "4(a)",
|
| 18 |
+
"sha256": "6f53ec1584dd401724c1cae0fc1139249508ce24cf0891cc70fd6468f4d4b689",
|
| 19 |
+
"statement": "You may not sublicense the Work",
|
| 20 |
+
"url": "https://creativecommons.org/licenses/by/2.5/legalcode"
|
| 21 |
+
}
|
| 22 |
+
],
|
| 23 |
+
"license": "CC-BY-2.5 or CC-BY-4.0 per record, by the page's last revision",
|
| 24 |
+
"release_scope": {
|
| 25 |
+
"created_range": [
|
| 26 |
+
"2011-12-24",
|
| 27 |
+
"2026-05-25"
|
| 28 |
+
],
|
| 29 |
+
"labels": {
|
| 30 |
+
"CC-BY-2.5": 17581,
|
| 31 |
+
"CC-BY-4.0": 6805
|
| 32 |
+
},
|
| 33 |
+
"last_edited_before_era_end": {
|
| 34 |
+
"date": "2005-09-25",
|
| 35 |
+
"docs": 0,
|
| 36 |
+
"tokens": 0
|
| 37 |
+
},
|
| 38 |
+
"tokens": {
|
| 39 |
+
"CC-BY-2.5": 8956397,
|
| 40 |
+
"CC-BY-4.0": 3184958
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
"review_scope": "licence of contributors' text on pl.wikinews.org and its version per page; not independent legal advice",
|
| 44 |
+
"site_licence": {
|
| 45 |
+
"observed_at": "2026-10-06T00:00:15.478622+00:00",
|
| 46 |
+
"rightsinfo": {
|
| 47 |
+
"text": "Creative Commons Attribution 4.0",
|
| 48 |
+
"url": "https://creativecommons.org/licenses/by/4.0/",
|
| 49 |
+
"url_queried": "https://pl.wikinews.org/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo"
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"spdx": [
|
| 53 |
+
"https://spdx.org/licenses/CC-BY-2.5.html",
|
| 54 |
+
"https://spdx.org/licenses/CC-BY-4.0.html"
|
| 55 |
+
],
|
| 56 |
+
"status": "documented-open-cc-by",
|
| 57 |
+
"switch": {
|
| 58 |
+
"gerrit": "https://gerrit.wikimedia.org/r/changes/operations%2Fmediawiki-config~1101867",
|
| 59 |
+
"gerrit_status": "MERGED",
|
| 60 |
+
"gerrit_submitted": "2024-12-16 08:07:33.000000000",
|
| 61 |
+
"merged_utc": "2024-12-16 08:07",
|
| 62 |
+
"phabricator": "https://phabricator.wikimedia.org/T381421",
|
| 63 |
+
"synced_by_utc": "2024-12-16 08:32:24"
|
| 64 |
+
},
|
| 65 |
+
"terms": [
|
| 66 |
+
{
|
| 67 |
+
"effective": "udostępnia swoją treść na licencji Creative Commons Uznanie autorstwa 4.0 od 16 grudnia 2024 roku",
|
| 68 |
+
"sha256": "8b461acb8e0608eb906e59d9669bc003759d7840d82fc934f83d160a72895de3",
|
| 69 |
+
"statement": "a wcześniej na licencji. [http://creativecommons.org/licenses/by/2.5/deed.pl Creative Commons Uznanie autorstwa 2.5]",
|
| 70 |
+
"title": "pl.wikinews terms of use (CC BY 2.5 until 2024-12-16, CC BY 4.0 since)",
|
| 71 |
+
"url": "https://pl.wikinews.org/w/index.php?title=Wikinews:Warunki_u%C5%BCycia&oldid=342796&action=raw"
|
| 72 |
+
}
|
| 73 |
+
]
|
| 74 |
+
}
|
data/wikinews/wikinews.md
CHANGED
|
@@ -3,41 +3,95 @@
|
|
| 3 |
Polish Wikinews
|
| 4 |
|
| 5 |
## Dataset description
|
| 6 |
-
- **Source (upstream):** https://
|
| 7 |
- **Domain:** news
|
| 8 |
- **Language:** Polish (pl)
|
| 9 |
-
- **License:** `CC-BY-2.5`
|
| 10 |
-
- **Created (range):**
|
| 11 |
-
- **Added:** 2026-07-02
|
| 12 |
|
| 13 |
## Licensing — traceable basis
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
## Provenance
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
## Statistics
|
| 20 |
| documents | characters | tokens (tiktoken proxy) |
|
| 21 |
|---:|---:|---:|
|
| 22 |
| 24,386 | 32,524,646 | 12,141,355 |
|
| 23 |
|
|
|
|
| 24 |
|
| 25 |
## Per-document license metadata
|
| 26 |
| license | documents |
|
| 27 |
|---|---:|
|
| 28 |
-
| `CC-BY-2.5` |
|
|
|
|
| 29 |
|
| 30 |
-
Author metadata present for **
|
| 31 |
-
|
| 32 |
-
Statistics were recomputed directly from the released parquet file.
|
| 33 |
|
| 34 |
## Filters applied (build_dynaword.py)
|
| 35 |
-
|
| 36 |
-
- drop
|
| 37 |
-
- drop non-Polish (diacritic ratio): **0**
|
| 38 |
- exact cross-source dedup (sha1): **0**
|
| 39 |
- OCR alpha-ratio < 0.70 (OCR sources only): **0**
|
| 40 |
-
- read 24,
|
| 41 |
|
| 42 |
Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
|
| 43 |
Llama-3 count is computed at release.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
Polish Wikinews
|
| 4 |
|
| 5 |
## Dataset description
|
| 6 |
+
- **Source (upstream):** https://dumps.wikimedia.org/plwikinews/20260601/
|
| 7 |
- **Domain:** news
|
| 8 |
- **Language:** Polish (pl)
|
| 9 |
+
- **License:** `CC-BY-2.5` or `CC-BY-4.0` per record (by last-revision date)
|
| 10 |
+
- **Created (range):** 2011-12-24, 2026-05-25 (date of the page's last revision in the dump)
|
| 11 |
+
- **Added:** 2026-07-02; rebuilt 2026-10-06 (UTC) from the official Wikimedia dump
|
| 12 |
|
| 13 |
## Licensing — traceable basis
|
| 14 |
+
Contributors' text on pl.wikinews.org is licensed CC BY: [pl.wikinews terms of use (CC BY 2.5 until 2024-12-16, CC BY 4.0 since)](https://pl.wikinews.org/w/index.php?title=Wikinews:Warunki_u%C5%BCycia&oldid=342796&action=raw) (read 2026-10-06 UTC). The site licence
|
| 15 |
+
(`rightsinfo`) reads "Creative Commons Attribution 4.0". Each row is labelled by its page's last revision in the dump:
|
| 16 |
+
|
| 17 |
+
| last revision (UTC) | `license` | documents | tokens | share of tokens |
|
| 18 |
+
|---|---|---:|---:|---:|
|
| 19 |
+
| before 2024-12-16 | `CC-BY-2.5` | 17,581 | 8,956,397 | 73.8% |
|
| 20 |
+
| 2024-12-16 or later | `CC-BY-4.0` | 6,805 | 3,184,958 | 26.2% |
|
| 21 |
+
|
| 22 |
+
pl.wikinews has its own terms page, which names CC BY 2.5 until 2024-12-16 and CC BY 4.0 from that
|
| 23 |
+
day. A page last edited on or after the cutoff can still hold
|
| 24 |
+
2.5 text from earlier edits, and the [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/legalcode) legal code (§4(a)) has no clause that lets an
|
| 25 |
+
adaptation be licensed under a later version (BY-SA 3.0 §4(b)(ii) has one). The 4.0 label for such
|
| 26 |
+
pages rests on the site's terms page alone; whether that is enough is for the lawyer.
|
| 27 |
+
The terms page gives the day, not the time. The cutoff is midnight UTC, so the 6 pages last edited
|
| 28 |
+
on 2024-12-16 are labelled 4.0. The configuration change was merged 2024-12-16 08:07 UTC and deployed
|
| 29 |
+
by 2024-12-16 08:32:24 UTC ([Gerrit change](https://gerrit.wikimedia.org/r/changes/operations%2Fmediawiki-config~1101867), [T381421](https://phabricator.wikimedia.org/T381421);
|
| 30 |
+
the deployment time was read by the rights audit, not re-read), so 2 of those 6 were last edited before it.
|
| 31 |
+
The rule is `license_for_revision` in `src/rights.py`, tested at the cutoff second, across time
|
| 32 |
+
zones, and on a missing timestamp, which stops the build. v0.2.0-v0.2.5 labelled every row `CC-BY-2.5`.
|
| 33 |
+
|
| 34 |
+
The terms page puts articles created before 2005-09-25 in the public domain. The dump has only the date of the last
|
| 35 |
+
revision, so how many released articles were created then is not known; 0 (0 tokens) were last edited before it.
|
| 36 |
+
All rows carry a CC BY label; nothing is dropped or relabelled for this.
|
| 37 |
+
|
| 38 |
+
Evidence: `wikinews.license-evidence.json`.
|
| 39 |
+
|
| 40 |
+
## Attribution
|
| 41 |
+
Each row's `author` is `Wikinews contributors, <page URL>`, e.g.
|
| 42 |
+
`Wikinews contributors, https://pl.wikinews.org/wiki/2005-03-18:_Barroso_w_Polsce`. The page history names the contributors; the terms page asks for a link to the source article, which the URL gives.
|
| 43 |
+
`wikinews.attribution.jsonl` has one line per row: `id`, `pageid`, `revid` (the revision
|
| 44 |
+
in the dump), `title`, `url`, `last_revision_at`, `license`. The row `id` is
|
| 45 |
+
`wikinews_<page id>` and `created` is the date of `last_revision_at`.
|
| 46 |
+
|
| 47 |
+
The text is modified: wiki markup is converted to plain text (see Provenance).
|
| 48 |
|
| 49 |
## Provenance
|
| 50 |
+
Parsed from the official Wikimedia dump `plwikinews-20260601-pages-articles` by
|
| 51 |
+
`src/fetch_wikimedia.py`; the file (21,980,828 bytes, sha1 `bfad5f33667756de4ded97756d370d7fdec39bcb`) was matched against the
|
| 52 |
+
dump's `dumpstatus.json` and `sha1sums.txt` (`wikinews.build.json`). v0.2.0-v0.2.5 used the same dump
|
| 53 |
+
date; the text set is the same (the rebuild adds the last-revision time).
|
| 54 |
+
|
| 55 |
+
Articles (namespace 0) only. Redirects, empty pages and pages shorter than 200 characters are skipped.
|
| 56 |
+
Wikitext is converted with mwparserfromhell `strip_code(normalize=True, collapse=True)`, as in v0.2.5.
|
| 57 |
+
Templates and comments are dropped. `<ref>` bodies, category links (`Kategoria:...`) and file-link
|
| 58 |
+
options (`thumb|...`) are not removed and stay in the text; the wikipedia fetcher's `strip_article`
|
| 59 |
+
removes them, this one does not, because that would change the text set. Of two pages with the same
|
| 60 |
+
text (sha1 of the stripped text), the lower page id is kept.
|
| 61 |
+
|
| 62 |
+
65,253 pages scanned → 47,845 in namespace 0 → 23,366 redirects, 0 empty pages, 0 parser failures, 87 shorter than 200 characters skipped, no exact duplicates → 24,392 read by the build → 24,386 released.
|
| 63 |
|
| 64 |
## Statistics
|
| 65 |
| documents | characters | tokens (tiktoken proxy) |
|
| 66 |
|---:|---:|---:|
|
| 67 |
| 24,386 | 32,524,646 | 12,141,355 |
|
| 68 |
|
| 69 |
+
The same text set as v0.2.5: documents, characters and tokens are unchanged; only labels, ids, authors and dates differ.
|
| 70 |
|
| 71 |
## Per-document license metadata
|
| 72 |
| license | documents |
|
| 73 |
|---|---:|
|
| 74 |
+
| `CC-BY-2.5` | 17,581 |
|
| 75 |
+
| `CC-BY-4.0` | 6,805 |
|
| 76 |
|
| 77 |
+
Author metadata present for **24,386** documents.
|
|
|
|
|
|
|
| 78 |
|
| 79 |
## Filters applied (build_dynaword.py)
|
| 80 |
+
- drop documents < 200 chars: **0** (the fetcher already dropped 87)
|
| 81 |
+
- drop non-Polish (diacritic ratio): **6**
|
|
|
|
| 82 |
- exact cross-source dedup (sha1): **0**
|
| 83 |
- OCR alpha-ratio < 0.70 (OCR sources only): **0**
|
| 84 |
+
- read 24,392 → kept 24,386
|
| 85 |
|
| 86 |
Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
|
| 87 |
Llama-3 count is computed at release.
|
| 88 |
+
|
| 89 |
+
## Not checked
|
| 90 |
+
- pastes from copyrighted sources, including articles copied from press agencies or other publishers (no sample was run)
|
| 91 |
+
- the 2.5 → 4.0 label of pages edited after the cutoff (a reading of the site's terms page, not a lawyer's opinion;
|
| 92 |
+
the lawyer's answer to E1, the wiki 3.0/4.0 labelling, is still pending, and whether it extends to 2.5 → 4.0 is not settled),
|
| 93 |
+
and the time of day of the switch
|
| 94 |
+
- how many released articles were created before 2005-09-25, the public-domain date in the terms page
|
| 95 |
+
- text imported from elsewhere under another licence or with extra attribution requirements
|
| 96 |
+
- quotations inside articles (Art. 29 of the Polish copyright act)
|
| 97 |
+
- personal data (the NERGAL scrub runs before release)
|
data/wikinews/wikinews.parquet
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:54feba0a09e8c81aac33619f4ad2e80cdc42cf16f6bb9718bf9edc349a12fbb6
|
| 3 |
+
size 15298826
|
data/wikinews/wikinews.stats.json
CHANGED
|
@@ -1,16 +1,17 @@
|
|
| 1 |
{
|
| 2 |
-
"read":
|
| 3 |
"kept": 24386,
|
| 4 |
"drop_short": 0,
|
| 5 |
-
"drop_lang":
|
| 6 |
"drop_dup": 0,
|
| 7 |
"drop_ocr": 0,
|
| 8 |
"chars": 32524646,
|
| 9 |
"tokens": 12141355,
|
| 10 |
"licenses": {
|
| 11 |
-
"CC-BY-
|
|
|
|
| 12 |
},
|
| 13 |
-
"authors_with_value":
|
| 14 |
-
"
|
| 15 |
-
"
|
| 16 |
-
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"read": 24392,
|
| 3 |
"kept": 24386,
|
| 4 |
"drop_short": 0,
|
| 5 |
+
"drop_lang": 6,
|
| 6 |
"drop_dup": 0,
|
| 7 |
"drop_ocr": 0,
|
| 8 |
"chars": 32524646,
|
| 9 |
"tokens": 12141355,
|
| 10 |
"licenses": {
|
| 11 |
+
"CC-BY-4.0": 6805,
|
| 12 |
+
"CC-BY-2.5": 17581
|
| 13 |
},
|
| 14 |
+
"authors_with_value": 24386,
|
| 15 |
+
"secs": 1.4,
|
| 16 |
+
"license": "CC BY (2.5 or 4.0 per record, by last-revision date)"
|
| 17 |
+
}
|
src/fetch_wikimedia.py
CHANGED
|
@@ -1,103 +1,484 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
from the official dumps into SpeakLeash-style .jsonl.zst, so build_dynaword.py
|
| 4 |
-
consumes them unchanged. All are CC-BY-SA (same basis as Wikipedia/Wikisource).
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
from __future__ import annotations
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from pathlib import Path
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
import
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
}
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
def
|
| 32 |
-
return
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def pages(bz2_path):
|
| 48 |
-
"""Yield (title, wikitext) for mainspace, non-redirect pages."""
|
| 49 |
-
with bz2.open(bz2_path, "rb") as fh:
|
| 50 |
-
title = ns = text = None; redirect = False
|
| 51 |
-
for ev, el in iterparse(fh, events=("end",)):
|
| 52 |
-
t = _local(el.tag)
|
| 53 |
-
if t == "title": title = el.text
|
| 54 |
-
elif t == "ns": ns = el.text
|
| 55 |
-
elif t == "redirect": redirect = True
|
| 56 |
-
elif t == "text": text = el.text
|
| 57 |
-
elif t == "page":
|
| 58 |
-
if ns == "0" and not redirect and text:
|
| 59 |
-
yield title, text
|
| 60 |
-
title = ns = text = None; redirect = False
|
| 61 |
-
el.clear()
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def strip(wikitext):
|
| 65 |
try:
|
| 66 |
return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()
|
| 67 |
-
except Exception:
|
| 68 |
-
return
|
| 69 |
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
continue
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
"
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
if __name__ == "__main__":
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
"""Polish Wikinews, Wikivoyage and Wikibooks from the official dumps, licence per record.
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
v0.2.0-v0.2.5 labelled every row with one licence (Wikinews CC-BY-2.5, the others
|
| 5 |
+
CC-BY-SA-3.0). Each row now carries the label of its page's last revision
|
| 6 |
+
(`license_for_revision` in src/rights.py): v0.2.6 rights audit, slayerlabs/polish-dynaword-v2#57.
|
| 7 |
+
The dump date is pinned to the one the v0.2.5 text came from (the rebuild changes labels,
|
| 8 |
+
ids, authors and dates, not the text); the dump file is checked against the sha1 in
|
| 9 |
+
dumpstatus.json and in the dump's sha1sums.txt.
|
| 10 |
|
| 11 |
+
B=<build dir, never committed>
|
| 12 |
+
python3 src/fetch_wikimedia.py acquire --out $B --sources wikinews wikivoyage wikibooks
|
| 13 |
+
python3 src/fetch_wikimedia.py prepare --out $B ... # $B/plwiki{news,voyage,books}.jsonl.zst
|
| 14 |
+
python3 src/build_dynaword.py --sources wikinews wikivoyage wikibooks --speakleash-dir $B --out .
|
| 15 |
+
python3 src/fetch_wikimedia.py attribution --out $B ... # data/<source> sidecars + evidence
|
| 16 |
+
python3 src/fetch_wikimedia.py datasheet --out $B ... # data/<source>/<source>.md
|
| 17 |
"""
|
| 18 |
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import bz2
|
| 22 |
+
from collections import Counter
|
| 23 |
+
from datetime import timedelta
|
| 24 |
+
import gzip
|
| 25 |
+
import hashlib
|
| 26 |
+
import html
|
| 27 |
+
import json
|
| 28 |
from pathlib import Path
|
| 29 |
+
import re
|
| 30 |
+
import subprocess
|
| 31 |
+
import sys
|
| 32 |
+
from urllib.parse import quote
|
| 33 |
+
|
| 34 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 35 |
+
from build_plwiki_talk_pl import ( # noqa: E402 shared dump helpers
|
| 36 |
+
UA, digest, load, now, request, request_json, save, sha1_file,
|
| 37 |
+
)
|
| 38 |
+
from fetch_wikipedia import pages, text_key # noqa: E402
|
| 39 |
+
from rights import BY_SA_4_CUTOFF, WIKINEWS_BY_4_CUTOFF, license_for_revision # noqa: E402
|
| 40 |
+
|
| 41 |
+
DUMP_DATE = "20260601" # the dump the v0.2.5 text was cut from (checked: same text set)
|
| 42 |
+
MIN_CHARS = 200 # same gate as build_dynaword.py
|
| 43 |
+
|
| 44 |
+
# WMF Terms of Use in force from 2023-06-07 (CC BY-SA 4.0), and the 2014 revision (CC BY-SA 3.0).
|
| 45 |
+
WMF_TOU_NEW = {
|
| 46 |
+
"title": "Wikimedia Terms of Use in force since 7 June 2023 (CC BY-SA 4.0)",
|
| 47 |
+
"url": "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use&oldid=554823&action=raw",
|
| 48 |
+
"sha256": "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832",
|
| 49 |
+
"effective": "These Terms of Use went into effect on June 7, 2023",
|
| 50 |
+
"statement": "Creative Commons Attribution-ShareAlike 4.0 International License",
|
| 51 |
+
}
|
| 52 |
+
WMF_TOU_OLD = {
|
| 53 |
+
"title": "Wikimedia Terms of Use of 2014-2023 (CC BY-SA 3.0)",
|
| 54 |
+
"url": "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Use&oldid=98524&action=raw",
|
| 55 |
+
"sha256": "46617e3576a507b8f83a0cf7b28b60e43817ad93cc5d747a558b503e7d1cc6de",
|
| 56 |
+
"effective": "These Terms of Use went into effect on June 16, 2014",
|
| 57 |
+
"statement": "Creative Commons Attribution-ShareAlike 3.0 Unported License",
|
| 58 |
+
}
|
| 59 |
+
# pl.wikinews has its own terms page: CC BY, 2.5 until 2024-12-16, 4.0 since.
|
| 60 |
+
WIKINEWS_TERMS = {
|
| 61 |
+
"title": "pl.wikinews terms of use (CC BY 2.5 until 2024-12-16, CC BY 4.0 since)",
|
| 62 |
+
"url": "https://pl.wikinews.org/w/index.php?title=Wikinews:Warunki_u%C5%BCycia&oldid=342796&action=raw",
|
| 63 |
+
"sha256": "8b461acb8e0608eb906e59d9669bc003759d7840d82fc934f83d160a72895de3",
|
| 64 |
+
"effective": "udostępnia swoją treść na licencji Creative Commons Uznanie autorstwa 4.0 od 16 grudnia 2024 roku",
|
| 65 |
+
"statement": "a wcześniej na licencji. [http://creativecommons.org/licenses/by/2.5/deed.pl Creative Commons Uznanie autorstwa 2.5]",
|
| 66 |
+
}
|
| 67 |
+
WIKINEWS_SWITCH = { # the config change that made 4.0 the site licence (Phabricator T381421)
|
| 68 |
+
"gerrit": "https://gerrit.wikimedia.org/r/changes/operations%2Fmediawiki-config~1101867",
|
| 69 |
+
"phabricator": "https://phabricator.wikimedia.org/T381421",
|
| 70 |
+
"merged_utc": "2024-12-16 08:07",
|
| 71 |
+
"synced_by_utc": "2024-12-16 08:32:24", # SAL scap sync-world finish; read by the rights audit, not re-read
|
| 72 |
}
|
| 73 |
|
| 74 |
+
GFDL_ERA_END = "2009-06-15" # the Wikimedia sites began dual licensing under CC BY-SA 3.0 and the GFDL
|
| 75 |
+
# What the label rule rests on: each licence's own clause on adaptations (read from the legal code).
|
| 76 |
+
LEGAL_BY_SA_3 = {"url": "https://creativecommons.org/licenses/by-sa/3.0/legalcode", "section": "4(b)(ii)",
|
| 77 |
+
"statement": "a later version of this License with the same License Elements as this License"}
|
| 78 |
+
LEGAL_BY_SA_4 = {"url": "https://creativecommons.org/licenses/by-sa/4.0/legalcode", "section": "3(b)(1)",
|
| 79 |
+
"statement": "this version or later, or a BY-SA Compatible License"}
|
| 80 |
+
LEGAL_BY_2_5 = {"url": "https://creativecommons.org/licenses/by/2.5/legalcode", "section": "4(a)",
|
| 81 |
+
"statement": "You may not sublicense the Work", "absent": "later version"} # no later-version clause
|
| 82 |
+
|
| 83 |
+
SITES = {
|
| 84 |
+
"wikinews": {
|
| 85 |
+
"wiki": "plwikinews", "host": "pl.wikinews.org", "pretty": "Polish Wikinews",
|
| 86 |
+
"author": "Wikinews contributors", "family": "CC BY",
|
| 87 |
+
"cutoff": WIKINEWS_BY_4_CUTOFF, "before": "CC-BY-2.5", "after": "CC-BY-4.0",
|
| 88 |
+
"site_rights": "creativecommons.org/licenses/by/4.0/", "terms": [WIKINEWS_TERMS], "legal": [LEGAL_BY_2_5],
|
| 89 |
+
"clock": WIKINEWS_SWITCH["synced_by_utc"], "era_end": "2005-09-25", "domain": "news", "added": "2026-07-02",
|
| 90 |
+
"v025": (24386, 32524646, 12141355),
|
| 91 |
+
},
|
| 92 |
+
"wikivoyage": {
|
| 93 |
+
"wiki": "plwikivoyage", "host": "pl.wikivoyage.org", "pretty": "Polish Wikivoyage",
|
| 94 |
+
"author": "Wikivoyage contributors", "family": "CC BY-SA",
|
| 95 |
+
"cutoff": BY_SA_4_CUTOFF, "before": "CC-BY-SA-3.0", "after": "CC-BY-SA-4.0",
|
| 96 |
+
"site_rights": "creativecommons.org/licenses/by-sa/4.0/", "terms": [WMF_TOU_NEW, WMF_TOU_OLD], "legal": [LEGAL_BY_SA_3, LEGAL_BY_SA_4],
|
| 97 |
+
"era_end": GFDL_ERA_END, "domain": "travel", "added": "2026-07-02", "v025": (13645, 45184300, 17128200),
|
| 98 |
+
},
|
| 99 |
+
"wikibooks": {
|
| 100 |
+
"wiki": "plwikibooks", "host": "pl.wikibooks.org", "pretty": "Polish Wikibooks",
|
| 101 |
+
"author": "Wikibooks contributors", "family": "CC BY-SA",
|
| 102 |
+
"cutoff": BY_SA_4_CUTOFF, "before": "CC-BY-SA-3.0", "after": "CC-BY-SA-4.0",
|
| 103 |
+
"site_rights": "creativecommons.org/licenses/by-sa/4.0/", "terms": [WMF_TOU_NEW, WMF_TOU_OLD], "legal": [LEGAL_BY_SA_3, LEGAL_BY_SA_4],
|
| 104 |
+
"era_end": GFDL_ERA_END, "domain": "instructional", "added": "2026-07-02", "v025": (9112, 38892589, 15571295),
|
| 105 |
+
},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def label(key: str, timestamp: str) -> str:
|
| 110 |
+
s = SITES[key]
|
| 111 |
+
return license_for_revision(timestamp, s["cutoff"], s["before"], s["after"])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def page_url(key: str, title: str) -> str:
|
| 115 |
+
return f"https://{SITES[key]['host']}/wiki/" + quote((title or "").replace(" ", "_"), safe="/:")
|
| 116 |
+
|
| 117 |
|
| 118 |
+
def dump_base(key: str) -> str:
|
| 119 |
+
return f"https://dumps.wikimedia.org/{SITES[key]['wiki']}/{DUMP_DATE}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def legal_pin(pin: dict) -> dict:
|
| 123 |
+
"""Fetch a legal-code page, check the clause the label rests on, record the page hash."""
|
| 124 |
+
body = request(pin["url"]).content
|
| 125 |
+
text = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", body.decode("utf-8", "replace"))))
|
| 126 |
+
if pin["statement"] not in text or (pin.get("absent") and pin["absent"] in text):
|
| 127 |
+
raise ValueError(f"legal code changed: {pin['url']}")
|
| 128 |
+
return {**pin, "sha256": hashlib.sha256(body).hexdigest()}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def strip(wikitext: str) -> str | None:
|
| 132 |
+
"""Wikitext -> plain text, exactly as the v0.2.5 builder did. None when the parser fails."""
|
| 133 |
+
import mwparserfromhell
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
try:
|
| 135 |
return mwparserfromhell.parse(wikitext).strip_code(normalize=True, collapse=True).strip()
|
| 136 |
+
except Exception: # noqa: BLE001 parser failure drops the page, counted
|
| 137 |
+
return None
|
| 138 |
|
| 139 |
|
| 140 |
+
def acquire(out: Path, key: str) -> None:
|
| 141 |
+
site, wiki, base = SITES[key], SITES[key]["wiki"], dump_base(key)
|
| 142 |
+
status = request_json(f"{base}/dumpstatus.json")["jobs"]["articlesdump"]
|
| 143 |
+
if status.get("status") != "done":
|
| 144 |
+
raise ValueError(f"{wiki} articlesdump not done: {status.get('status')}")
|
| 145 |
+
name = f"{wiki}-{DUMP_DATE}-pages-articles.xml.bz2"
|
| 146 |
+
meta = status["files"][name]
|
| 147 |
+
sums = {n: sha for sha, n in (ln.split() for ln in request(f"{base}/{wiki}-{DUMP_DATE}-sha1sums.txt").text.splitlines() if ln.strip())}
|
| 148 |
+
if sums.get(name) != meta["sha1"]:
|
| 149 |
+
raise ValueError(f"sha1sums.txt disagrees with dumpstatus.json for {name}")
|
| 150 |
+
rights = request_json(f"https://{site['host']}/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo&format=json")["query"]["rightsinfo"]
|
| 151 |
+
if site["site_rights"] not in rights.get("url", ""):
|
| 152 |
+
raise ValueError(f"{wiki} rightsinfo changed: {rights}")
|
| 153 |
+
terms = []
|
| 154 |
+
for t in site["terms"]:
|
| 155 |
+
body = request(t["url"]).content
|
| 156 |
+
if hashlib.sha256(body).hexdigest() != t["sha256"] or t["effective"].encode() not in body:
|
| 157 |
+
raise ValueError(f"pinned terms page changed: {t['url']}")
|
| 158 |
+
terms.append(t)
|
| 159 |
+
legal = [legal_pin(p) for p in site["legal"]]
|
| 160 |
+
switch = None
|
| 161 |
+
if key == "wikinews": # Gerrit prefixes its JSON with ")]}'"
|
| 162 |
+
change = json.loads(request(WIKINEWS_SWITCH["gerrit"]).text.split("\n", 1)[1])
|
| 163 |
+
task = request(WIKINEWS_SWITCH["phabricator"]).text
|
| 164 |
+
if change["status"] != "MERGED" or not change["submitted"].startswith("2024-12-16") or "T381421" not in task:
|
| 165 |
+
raise ValueError(f"Wikinews licence switch evidence changed: {change['status']} {change['submitted']}")
|
| 166 |
+
switch = {**WIKINEWS_SWITCH, "gerrit_status": change["status"], "gerrit_submitted": change["submitted"]}
|
| 167 |
+
raw = out / "raw_dump"
|
| 168 |
+
raw.mkdir(parents=True, exist_ok=True)
|
| 169 |
+
dst = raw / name
|
| 170 |
+
if not dst.exists() or dst.stat().st_size != meta["size"]:
|
| 171 |
+
subprocess.run(["curl", "-fsSL", "--retry", "8", "-C", "-", "-A", UA["User-Agent"],
|
| 172 |
+
"-o", str(dst), f"{base}/{name}"], check=True)
|
| 173 |
+
if sha1_file(dst) != meta["sha1"]:
|
| 174 |
+
raise ValueError(f"sha1 mismatch: {name}")
|
| 175 |
+
save(out / f"{key}.selection.json", {
|
| 176 |
+
"observed_at": now(), "dump_date": DUMP_DATE, "dump_base": base, "sha1sums_url": f"{base}/{wiki}-{DUMP_DATE}-sha1sums.txt",
|
| 177 |
+
"file": {"name": name, "url": f"{base}/{name}", "size": meta["size"], "sha1": meta["sha1"]},
|
| 178 |
+
"rightsinfo": {**rights, "url_queried": f"https://{site['host']}/w/api.php?action=query&meta=siteinfo&siprop=rightsinfo"},
|
| 179 |
+
"terms": terms, "legal": legal, "switch": switch,
|
| 180 |
+
"cutoff": site["cutoff"].isoformat(), "before": site["before"], "after": site["after"],
|
| 181 |
+
})
|
| 182 |
+
print(f"{key}: {name} sha1 OK")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def prepare(out: Path, key: str) -> None:
|
| 186 |
+
"""Label each page, drop exact duplicates keeping the lowest page id, write the build input."""
|
| 187 |
+
site = SITES[key]
|
| 188 |
+
src = out / "raw_dump" / load(out / f"{key}.selection.json")["file"]["name"]
|
| 189 |
+
seen, counts, duplicates, last_id = set(), Counter(), [], 0
|
| 190 |
+
zst = subprocess.Popen(["zstd", "-q", "-f", "-3", "-o", str(out / f"{site['wiki']}.jsonl.zst")], stdin=subprocess.PIPE)
|
| 191 |
+
try:
|
| 192 |
+
with bz2.open(src, "rb") as fh, gzip.open(out / f"{key}.manifest.jsonl.gz", "wt", encoding="utf-8") as manifest:
|
| 193 |
+
for pageid, revid, ns, title, timestamp, redirect, wikitext in pages(fh):
|
| 194 |
+
counts["pages"] += 1
|
| 195 |
+
if int(pageid) <= last_id: # "lowest page id wins" below relies on dump order
|
| 196 |
+
raise ValueError(f"dump not in page-id order at {pageid}")
|
| 197 |
+
last_id = int(pageid)
|
| 198 |
+
if ns != "0":
|
| 199 |
continue
|
| 200 |
+
counts["ns0"] += 1
|
| 201 |
+
if redirect:
|
| 202 |
+
counts["ns0_redirect"] += 1
|
| 203 |
+
elif not wikitext.strip():
|
| 204 |
+
counts["ns0_empty"] += 1
|
| 205 |
+
elif (text := strip(wikitext)) is None:
|
| 206 |
+
counts["ns0_strip_error"] += 1
|
| 207 |
+
elif len(text) < MIN_CHARS:
|
| 208 |
+
counts["ns0_short"] += 1
|
| 209 |
+
elif text_key(text) in seen:
|
| 210 |
+
counts["exact_duplicate"] += 1
|
| 211 |
+
duplicates.append(pageid)
|
| 212 |
+
else:
|
| 213 |
+
seen.add(text_key(text))
|
| 214 |
+
lic = label(key, timestamp)
|
| 215 |
+
counts["written"] += 1
|
| 216 |
+
counts[lic] += 1
|
| 217 |
+
row_id, url = f"{key}_{pageid}", page_url(key, title)
|
| 218 |
+
zst.stdin.write((json.dumps({
|
| 219 |
+
"id": row_id, "text": text, "created": timestamp[:10],
|
| 220 |
+
"license": lic, "author": f"{site['author']}, {url}",
|
| 221 |
+
}, ensure_ascii=False) + "\n").encode("utf-8"))
|
| 222 |
+
manifest.write(json.dumps({
|
| 223 |
+
"id": row_id, "pageid": int(pageid), "revid": int(revid), "title": title, "url": url,
|
| 224 |
+
"last_revision_at": timestamp, "license": lic,
|
| 225 |
+
}, ensure_ascii=False) + "\n")
|
| 226 |
+
finally: # a failed gate must not leave zstd waiting on stdin
|
| 227 |
+
zst.stdin.close()
|
| 228 |
+
status = zst.wait()
|
| 229 |
+
if status:
|
| 230 |
+
raise RuntimeError("zstd failed")
|
| 231 |
+
save(out / f"{key}.prepare.json", {"counts": dict(counts), "exact_duplicate_pageids": duplicates})
|
| 232 |
+
print(key, dict(counts))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def attribution(out: Path, data_dir: Path, key: str) -> None:
|
| 236 |
+
"""Sidecars for the rows build_dynaword kept: per-page attribution, build record, licence evidence."""
|
| 237 |
+
import pyarrow.parquet as pq
|
| 238 |
+
site = SITES[key]
|
| 239 |
+
table = pq.read_table(data_dir / f"{key}.parquet", columns=["id", "created", "license", "token_count"]).to_pydict()
|
| 240 |
+
tokens_of = dict(zip(table["id"], table["token_count"]))
|
| 241 |
+
rows = []
|
| 242 |
+
with gzip.open(out / f"{key}.manifest.jsonl.gz", "rt", encoding="utf-8") as fh:
|
| 243 |
+
for line in fh:
|
| 244 |
+
if (rec := json.loads(line))["id"] in tokens_of:
|
| 245 |
+
rows.append((line, rec))
|
| 246 |
+
if len(rows) != len(tokens_of):
|
| 247 |
+
raise ValueError(f"attribution rows {len(rows)} != parquet rows {len(tokens_of)}")
|
| 248 |
+
sidecar = data_dir / f"{key}.attribution.jsonl"
|
| 249 |
+
sidecar.write_text("".join(line for line, _ in rows), encoding="utf-8")
|
| 250 |
+
sel, prep = load(out / f"{key}.selection.json"), load(out / f"{key}.prepare.json")
|
| 251 |
+
tokens, docs = Counter(), Counter()
|
| 252 |
+
for lic, tok in zip(table["license"], table["token_count"]):
|
| 253 |
+
docs[lic] += 1
|
| 254 |
+
tokens[lic] += tok
|
| 255 |
+
day = site["cutoff"].date().isoformat() # edits on the switch day are labelled `after`
|
| 256 |
+
on_day = [rec["last_revision_at"] for _, rec in rows if rec["last_revision_at"].startswith(day)]
|
| 257 |
+
boundary = {"day": day, "docs_last_edited_that_day": len(on_day)}
|
| 258 |
+
if clock := site.get("clock"): # known deployment time of the switch, when there is one
|
| 259 |
+
boundary.update({"known_switch_time_utc": clock,
|
| 260 |
+
"of_which_before_that_time": sum(t.replace("T", " ").rstrip("Z") < clock for t in on_day)})
|
| 261 |
+
scope = {"labels": dict(docs), "tokens": dict(tokens), "created_range": [min(table["created"]), max(table["created"])]}
|
| 262 |
+
old = [rec["id"] for _, rec in rows if rec["last_revision_at"] < site["era_end"]] # recorded, not acted on
|
| 263 |
+
scope["last_edited_before_era_end"] = {"date": site["era_end"], "docs": len(old), "tokens": sum(tokens_of[i] for i in old)}
|
| 264 |
+
save(data_dir / f"{key}.build.json", {
|
| 265 |
+
"dump_date": sel["dump_date"], "dump_base": sel["dump_base"], "sha1sums_url": sel["sha1sums_url"],
|
| 266 |
+
"file": sel["file"], "rightsinfo": sel["rightsinfo"], "terms": sel["terms"], "switch": sel["switch"],
|
| 267 |
+
"cutoff": sel["cutoff"], "labels": {"before": sel["before"], "after": sel["after"]},
|
| 268 |
+
"discovered_at": sel["observed_at"], "prepare": prep,
|
| 269 |
+
"attribution_rows": len(rows), "attribution_sha256": digest(sidecar.read_bytes()),
|
| 270 |
+
})
|
| 271 |
+
save(data_dir / f"{key}.license-evidence.json", {
|
| 272 |
+
"license": f"{sel['before']} or {sel['after']} per record, by the page's last revision",
|
| 273 |
+
"spdx": [f"https://spdx.org/licenses/{sel['before']}.html", f"https://spdx.org/licenses/{sel['after']}.html"],
|
| 274 |
+
"status": "documented-open-cc-by-sa" if "SA" in sel["after"] else "documented-open-cc-by",
|
| 275 |
+
"review_scope": f"licence of contributors' text on {site['host']} and its version per page; not independent legal advice",
|
| 276 |
+
"checked_at": sel["observed_at"][:10],
|
| 277 |
+
"cutoff": {"at": sel["cutoff"], "before": sel["before"], "after": sel["after"], "boundary_day": boundary},
|
| 278 |
+
"terms": sel["terms"], "legal": sel["legal"], "switch": sel["switch"],
|
| 279 |
+
"site_licence": {"observed_at": sel["observed_at"], "rightsinfo": sel["rightsinfo"]},
|
| 280 |
+
"release_scope": scope,
|
| 281 |
+
})
|
| 282 |
+
print(f"{key}: attribution rows {len(rows)}, labels {dict(docs)}")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def share(part: int, whole: int) -> str:
|
| 286 |
+
return f"{100 * part / whole:.1f}%"
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def licensing_text(key: str, ev: dict) -> str:
|
| 290 |
+
"""The reading of the licences behind the labels, with the cutoff-day count."""
|
| 291 |
+
site, cut = SITES[key], ev["cutoff"]
|
| 292 |
+
day, n = cut["boundary_day"]["day"], cut["boundary_day"]["docs_last_edited_that_day"]
|
| 293 |
+
next_day = (site["cutoff"] + timedelta(days=1)).date().isoformat()
|
| 294 |
+
before, after = cut["before"], cut["after"]
|
| 295 |
+
if "SA" in after:
|
| 296 |
+
return (
|
| 297 |
+
f"A page last edited on or after the cutoff can still hold 3.0 text from earlier edits;\n"
|
| 298 |
+
f"[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/legalcode) §4(b)(ii) lets such an adaptation be licensed under \"a later\n"
|
| 299 |
+
f"version of this License with the same License Elements\", so it is labelled 4.0. The Terms\n"
|
| 300 |
+
f"of Use give the day of the switch, not the time. The cutoff is midnight UTC, so the\n"
|
| 301 |
+
f"{n} pages last edited on {day} itself are labelled 4.0. If the switch came later\n"
|
| 302 |
+
f"that day, those last edited before it are 3.0 text under a 4.0 label; a {next_day} cutoff\n"
|
| 303 |
+
f"(the citation pass's fallback) would instead put that day's 4.0 edits under a 3.0 label,\n"
|
| 304 |
+
f"which [4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode) §3(b)(1) (\"this version or later\") does not allow. Neither choice is\n"
|
| 305 |
+
f"exact without the time of the switch. The rule is `license_for_revision` in `src/rights.py`,\n"
|
| 306 |
+
f"tested at the cutoff second, across time zones, and on a missing timestamp, which stops the\n"
|
| 307 |
+
f"build. v0.2.0-v0.2.5 labelled every row `{before}`."
|
| 308 |
+
)
|
| 309 |
+
sw, k = ev["switch"], cut["boundary_day"]["of_which_before_that_time"]
|
| 310 |
+
return (
|
| 311 |
+
f"pl.wikinews has its own terms page, which names CC BY 2.5 until {day} and CC BY 4.0 from that\n"
|
| 312 |
+
f"day. A page last edited on or after the cutoff can still hold\n"
|
| 313 |
+
f"2.5 text from earlier edits, and the [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/legalcode) legal code (§4(a)) has no clause that lets an\n"
|
| 314 |
+
f"adaptation be licensed under a later version (BY-SA 3.0 §4(b)(ii) has one). The 4.0 label for such\n"
|
| 315 |
+
f"pages rests on the site's terms page alone; whether that is enough is for the lawyer.\n"
|
| 316 |
+
f"The terms page gives the day, not the time. The cutoff is midnight UTC, so the {n} pages last edited\n"
|
| 317 |
+
f"on {day} are labelled 4.0. The configuration change was merged {sw['merged_utc']} UTC and deployed\n"
|
| 318 |
+
f"by {sw['synced_by_utc']} UTC ([Gerrit change]({sw['gerrit']}), [{sw['phabricator'].rsplit('/', 1)[1]}]({sw['phabricator']});\n"
|
| 319 |
+
f"the deployment time was read by the rights audit, not re-read), so {k} of those {n} were last edited before it.\n"
|
| 320 |
+
f"The rule is `license_for_revision` in `src/rights.py`, tested at the cutoff second, across time\n"
|
| 321 |
+
f"zones, and on a missing timestamp, which stops the build. v0.2.0-v0.2.5 labelled every row `{before}`."
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def datasheet(out: Path, data_dir: Path, key: str) -> None:
|
| 326 |
+
"""data/<key>/<key>.md from the stats, build record and licence evidence (custom_datasheet in sources.py)."""
|
| 327 |
+
site = SITES[key]
|
| 328 |
+
st, build, ev = (load(data_dir / f"{key}.{n}.json") for n in ("stats", "build", "license-evidence"))
|
| 329 |
+
scope, prep, file = ev["release_scope"], build["prepare"]["counts"], build["file"]
|
| 330 |
+
before, after = ev["cutoff"]["before"], ev["cutoff"]["after"]
|
| 331 |
+
kept, tok = st["kept"], st["tokens"]
|
| 332 |
+
table = "\n".join(
|
| 333 |
+
f"| {when} | `{lab}` | {scope['labels'].get(lab, 0):,} | {scope['tokens'].get(lab, 0):,} | {share(scope['tokens'].get(lab, 0), tok)} |"
|
| 334 |
+
for when, lab in ((f"before {ev['cutoff']['boundary_day']['day']}", before), (f"{ev['cutoff']['boundary_day']['day']} or later", after)))
|
| 335 |
+
labels = "\n".join(f"| `{lab}` | {scope['labels'].get(lab, 0):,} |" for lab in (before, after))
|
| 336 |
+
v_docs, v_chars, v_tokens = site["v025"]
|
| 337 |
+
same = (kept, st["chars"], tok) == (v_docs, v_chars, v_tokens)
|
| 338 |
+
v025 = ("The same text set as v0.2.5: documents, characters and tokens are unchanged; only labels, ids, authors and dates differ."
|
| 339 |
+
if same else f"v0.2.5 had {v_docs:,} documents, {v_chars:,} characters and {v_tokens:,} tokens.")
|
| 340 |
+
old = scope["last_edited_before_era_end"]
|
| 341 |
+
if "SA" in after:
|
| 342 |
+
era = (f"{old['docs']:,} documents ({old['tokens']:,} tokens, {share(old['tokens'], tok)}) were last edited before {old['date']}, when the Wikimedia sites\n"
|
| 343 |
+
f"began dual licensing under CC BY-SA 3.0 and the GFDL. Text first contributed before the 2009 move was\n"
|
| 344 |
+
f"under the GFDL only. They are labelled `{before}`, so only the CC BY-SA grant is relied on; the count is recorded, not acted on.")
|
| 345 |
+
else:
|
| 346 |
+
era = (f"The terms page puts articles created before {old['date']} in the public domain. The dump has only the date of the last\n"
|
| 347 |
+
f"revision, so how many released articles were created then is not known; {old['docs']:,} ({old['tokens']:,} tokens) were last edited before it.\n"
|
| 348 |
+
f"All rows carry a CC BY label; nothing is dropped or relabelled for this.")
|
| 349 |
+
review = ""
|
| 350 |
+
if (path := data_dir / f"{key}.gfdl-review.json").exists():
|
| 351 |
+
r = load(path)
|
| 352 |
+
review = f"\n\n{r['summary']} Per-document notes: `{path.name}`."
|
| 353 |
+
skipped = [f"{prep.get('ns0_redirect', 0):,} redirects", f"{prep.get('ns0_empty', 0):,} empty pages",
|
| 354 |
+
f"{prep.get('ns0_strip_error', 0):,} parser failures", f"{prep.get('ns0_short', 0):,} shorter than {MIN_CHARS} characters"]
|
| 355 |
+
chain = (f"{prep['pages']:,} pages scanned → {prep['ns0']:,} in namespace 0 → " + ", ".join(skipped) + " skipped"
|
| 356 |
+
+ (f", {prep['exact_duplicate']:,} exact duplicates dropped" if prep.get("exact_duplicate") else ", no exact duplicates")
|
| 357 |
+
+ f" → {prep['written']:,} read by the build → {kept:,} released.")
|
| 358 |
+
terms = "; ".join(f"[{t['title']}]({t['url']})" for t in ev["terms"])
|
| 359 |
+
with (data_dir / f"{key}.attribution.jsonl").open(encoding="utf-8") as fh:
|
| 360 |
+
example = min((json.loads(next(fh))["url"] for _ in range(200)), key=len) # a short real URL
|
| 361 |
+
created = scope["created_range"]
|
| 362 |
+
when = ev["checked_at"]
|
| 363 |
+
(data_dir / f"{key}.md").write_text(f"""# {key}
|
| 364 |
+
|
| 365 |
+
{site['pretty']}
|
| 366 |
+
|
| 367 |
+
## Dataset description
|
| 368 |
+
- **Source (upstream):** {build['dump_base']}/
|
| 369 |
+
- **Domain:** {site['domain']}
|
| 370 |
+
- **Language:** Polish (pl)
|
| 371 |
+
- **License:** `{before}` or `{after}` per record (by last-revision date)
|
| 372 |
+
- **Created (range):** {created[0]}, {created[1]} (date of the page's last revision in the dump)
|
| 373 |
+
- **Added:** {site['added']}; rebuilt {when} (UTC) from the official Wikimedia dump
|
| 374 |
+
|
| 375 |
+
## Licensing — traceable basis
|
| 376 |
+
Contributors' text on {site['host']} is licensed {site['family']}: {terms} (read {when} UTC). The site licence
|
| 377 |
+
(`rightsinfo`) reads "{ev['site_licence']['rightsinfo']['text']}". Each row is labelled by its page's last revision in the dump:
|
| 378 |
+
|
| 379 |
+
| last revision (UTC) | `license` | documents | tokens | share of tokens |
|
| 380 |
+
|---|---|---:|---:|---:|
|
| 381 |
+
{table}
|
| 382 |
+
|
| 383 |
+
{licensing_text(key, ev)}
|
| 384 |
+
|
| 385 |
+
{era}{review}
|
| 386 |
+
|
| 387 |
+
Evidence: `{key}.license-evidence.json`.
|
| 388 |
+
|
| 389 |
+
## Attribution
|
| 390 |
+
Each row's `author` is `{site['author']}, <page URL>`, e.g.
|
| 391 |
+
`{site['author']}, {example}`. The page history names the contributors; {ATTRIBUTION[key]}
|
| 392 |
+
`{key}.attribution.jsonl` has one line per row: `id`, `pageid`, `revid` (the revision
|
| 393 |
+
in the dump), `title`, `url`, `last_revision_at`, `license`. The row `id` is
|
| 394 |
+
`{key}_<page id>` and `created` is the date of `last_revision_at`.
|
| 395 |
+
|
| 396 |
+
The text is modified: wiki markup is converted to plain text (see Provenance).
|
| 397 |
+
|
| 398 |
+
## Provenance
|
| 399 |
+
Parsed from the official Wikimedia dump `{file['name'][:-8]}` by
|
| 400 |
+
`src/fetch_wikimedia.py`; the file ({file['size']:,} bytes, sha1 `{file['sha1']}`) was matched against the
|
| 401 |
+
dump's `dumpstatus.json` and `sha1sums.txt` (`{key}.build.json`). v0.2.0-v0.2.5 used the same dump
|
| 402 |
+
date; the text set is the same (the rebuild adds the last-revision time).
|
| 403 |
+
|
| 404 |
+
Articles (namespace 0) only. Redirects, empty pages and pages shorter than {MIN_CHARS} characters are skipped.
|
| 405 |
+
Wikitext is converted with mwparserfromhell `strip_code(normalize=True, collapse=True)`, as in v0.2.5.
|
| 406 |
+
Templates and comments are dropped. `<ref>` bodies, category links (`Kategoria:...`) and file-link
|
| 407 |
+
options (`thumb|...`) are not removed and stay in the text; the wikipedia fetcher's `strip_article`
|
| 408 |
+
removes them, this one does not, because that would change the text set. Of two pages with the same
|
| 409 |
+
text (sha1 of the stripped text), the lower page id is kept.
|
| 410 |
+
|
| 411 |
+
{chain}
|
| 412 |
+
|
| 413 |
+
## Statistics
|
| 414 |
+
| documents | characters | tokens (tiktoken proxy) |
|
| 415 |
+
|---:|---:|---:|
|
| 416 |
+
| {kept:,} | {st['chars']:,} | {tok:,} |
|
| 417 |
+
|
| 418 |
+
{v025}
|
| 419 |
+
|
| 420 |
+
## Per-document license metadata
|
| 421 |
+
| license | documents |
|
| 422 |
+
|---|---:|
|
| 423 |
+
{labels}
|
| 424 |
+
|
| 425 |
+
Author metadata present for **{st['authors_with_value']:,}** documents.
|
| 426 |
+
|
| 427 |
+
## Filters applied (build_dynaword.py)
|
| 428 |
+
- drop documents < 200 chars: **{st['drop_short']:,}** (the fetcher already dropped {prep.get('ns0_short', 0):,})
|
| 429 |
+
- drop non-Polish (diacritic ratio): **{st['drop_lang']:,}**
|
| 430 |
+
- exact cross-source dedup (sha1): **{st['drop_dup']:,}**
|
| 431 |
+
- OCR alpha-ratio < 0.70 (OCR sources only): **{st['drop_ocr']:,}**
|
| 432 |
+
- read {st['read']:,} → kept {kept:,}
|
| 433 |
+
|
| 434 |
+
Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
|
| 435 |
+
Llama-3 count is computed at release.
|
| 436 |
+
|
| 437 |
+
## Not checked
|
| 438 |
+
{NOT_CHECKED[key]}
|
| 439 |
+
""", encoding="utf-8")
|
| 440 |
+
print(f"{key}: datasheet written")
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
ATTRIBUTION = {
|
| 444 |
+
"wikinews": "the terms page asks for a link to the source article, which the URL gives.",
|
| 445 |
+
"wikivoyage": "the Terms of Use (section 7b) accept a hyperlink or URL to the page as attribution.",
|
| 446 |
+
"wikibooks": "the Terms of Use (section 7b) accept a hyperlink or URL to the page as attribution.",
|
| 447 |
+
}
|
| 448 |
+
NOT_CHECKED = {
|
| 449 |
+
"wikinews": """- pastes from copyrighted sources, including articles copied from press agencies or other publishers (no sample was run)
|
| 450 |
+
- the 2.5 → 4.0 label of pages edited after the cutoff (a reading of the site's terms page, not a lawyer's opinion;
|
| 451 |
+
the lawyer's answer to E1, the wiki 3.0/4.0 labelling, is still pending, and whether it extends to 2.5 → 4.0 is not settled),
|
| 452 |
+
and the time of day of the switch
|
| 453 |
+
- how many released articles were created before 2005-09-25, the public-domain date in the terms page
|
| 454 |
+
- text imported from elsewhere under another licence or with extra attribution requirements
|
| 455 |
+
- quotations inside articles (Art. 29 of the Polish copyright act)
|
| 456 |
+
- personal data (the NERGAL scrub runs before release)""",
|
| 457 |
+
"wikivoyage": """- pastes from copyrighted sources (no sample was run)
|
| 458 |
+
- the 3.0 → 4.0 label of pages edited after the cutoff (a reading of 3.0 §4(b)(ii), not a lawyer's opinion;
|
| 459 |
+
the lawyer's answer to E1, the wiki 3.0/4.0 labelling, is still pending), and the time of day of the switch
|
| 460 |
+
- text imported from elsewhere under another licence or with extra attribution requirements
|
| 461 |
+
- text first contributed under GFDL before the 2009 move to CC BY-SA, and GFDL dual
|
| 462 |
+
licensing; only the CC BY-SA grant is relied on
|
| 463 |
+
- quotations inside articles (Art. 29 of the Polish copyright act)
|
| 464 |
+
- personal data (the NERGAL scrub runs before release)""",
|
| 465 |
+
}
|
| 466 |
+
NOT_CHECKED["wikibooks"] = NOT_CHECKED["wikivoyage"]
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def main() -> None:
|
| 470 |
+
ap = argparse.ArgumentParser()
|
| 471 |
+
ap.add_argument("step", choices=["acquire", "prepare", "attribution", "datasheet"])
|
| 472 |
+
ap.add_argument("--out", required=True, type=Path)
|
| 473 |
+
ap.add_argument("--sources", nargs="+", default=list(SITES), choices=list(SITES))
|
| 474 |
+
ap.add_argument("--data-root", type=Path, default=Path(__file__).resolve().parent.parent / "data")
|
| 475 |
+
a = ap.parse_args()
|
| 476 |
+
a.out.mkdir(parents=True, exist_ok=True)
|
| 477 |
+
for key in a.sources:
|
| 478 |
+
data_dir = a.data_root / key
|
| 479 |
+
{"acquire": lambda: acquire(a.out, key), "prepare": lambda: prepare(a.out, key),
|
| 480 |
+
"attribution": lambda: attribution(a.out, data_dir, key),
|
| 481 |
+
"datasheet": lambda: datasheet(a.out, data_dir, key)}[a.step]()
|
| 482 |
|
| 483 |
|
| 484 |
if __name__ == "__main__":
|
src/fetch_wikipedia.py
CHANGED
|
@@ -20,7 +20,6 @@ import argparse
|
|
| 20 |
import bz2
|
| 21 |
from collections import Counter
|
| 22 |
from concurrent.futures import ProcessPoolExecutor
|
| 23 |
-
from datetime import datetime, timezone
|
| 24 |
import gzip
|
| 25 |
import hashlib
|
| 26 |
import json
|
|
@@ -34,6 +33,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
| 34 |
from build_plwiki_talk_pl import ( # noqa: E402 shared plwiki dump helpers
|
| 35 |
UA, _local, digest, load, now, page_url, request, request_json, save, sha1_file,
|
| 36 |
)
|
|
|
|
| 37 |
|
| 38 |
SOURCE = "wikipedia"
|
| 39 |
AUTHOR = "Wikipedia contributors" # + page URL; the page history names them
|
|
@@ -49,13 +49,6 @@ TOU_URL = "https://foundation.wikimedia.org/w/index.php?title=Policy:Terms_of_Us
|
|
| 49 |
TOU_SHA256 = "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832"
|
| 50 |
TOU_EFFECTIVE = "These Terms of Use went into effect on June 7, 2023"
|
| 51 |
|
| 52 |
-
# Text contributed under the 2014 ToU is CC BY-SA 3.0; the ToU in force from
|
| 53 |
-
# 2023-06-07 moved new text to CC BY-SA 4.0. A page last edited on or after the
|
| 54 |
-
# cutoff is an adaptation of its 3.0 text, which BY-SA 3.0 s4(b)(ii) lets us
|
| 55 |
-
# distribute under 4.0 (same licence elements). Time of day of the switch is not
|
| 56 |
-
# published, so midnight UTC labels that whole day 4.0 (the later licence).
|
| 57 |
-
BY_SA_4_CUTOFF = datetime(2023, 6, 7, tzinfo=timezone.utc)
|
| 58 |
-
|
| 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*(?:\||\}\})")
|
|
@@ -148,16 +141,6 @@ def ek_is_copyright(ek: dict) -> bool:
|
|
| 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:
|
| 154 |
-
raise ValueError("missing revision timestamp")
|
| 155 |
-
ts = datetime.fromisoformat(timestamp)
|
| 156 |
-
if ts.tzinfo is None:
|
| 157 |
-
raise ValueError(f"revision timestamp without timezone: {timestamp!r}")
|
| 158 |
-
return "CC-BY-SA-4.0" if ts >= BY_SA_4_CUTOFF else "CC-BY-SA-3.0"
|
| 159 |
-
|
| 160 |
-
|
| 161 |
def text_key(text: str) -> bytes:
|
| 162 |
"""Exact-duplicate key, identical to build_dynaword's (sha1 of the stripped text)."""
|
| 163 |
return hashlib.sha1(text.strip().encode("utf-8")).digest()
|
|
|
|
| 20 |
import bz2
|
| 21 |
from collections import Counter
|
| 22 |
from concurrent.futures import ProcessPoolExecutor
|
|
|
|
| 23 |
import gzip
|
| 24 |
import hashlib
|
| 25 |
import json
|
|
|
|
| 33 |
from build_plwiki_talk_pl import ( # noqa: E402 shared plwiki dump helpers
|
| 34 |
UA, _local, digest, load, now, page_url, request, request_json, save, sha1_file,
|
| 35 |
)
|
| 36 |
+
from rights import BY_SA_4_CUTOFF, license_for_revision # noqa: E402,F401 re-exported for callers
|
| 37 |
|
| 38 |
SOURCE = "wikipedia"
|
| 39 |
AUTHOR = "Wikipedia contributors" # + page URL; the page history names them
|
|
|
|
| 49 |
TOU_SHA256 = "c96ef93b439ff9b8242dc3233f41ede57c0984ef9153fafa51aa5f8cf0678832"
|
| 50 |
TOU_EFFECTIVE = "These Terms of Use went into effect on June 7, 2023"
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# plwiki copyright-violation notice and its redirects (Szablon:NPA <- Copyvio, Plagiat).
|
| 53 |
# Namespace prefix is case-insensitive, the first letter of the name too.
|
| 54 |
COPYVIO_RE = re.compile(r"\{\{\s*(?:(?i:szablon|template)\s*:\s*)?(?:[Nn]PA|[Cc]opyvio|[Pp]lagiat)\s*(?:\||\}\})")
|
|
|
|
| 141 |
return bool(EK_COPYRIGHT_RE.search(ek["reason"]))
|
| 142 |
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
def text_key(text: str) -> bytes:
|
| 145 |
"""Exact-duplicate key, identical to build_dynaword's (sha1 of the stripped text)."""
|
| 146 |
return hashlib.sha1(text.strip().encode("utf-8")).digest()
|
src/rights.py
CHANGED
|
@@ -4,7 +4,13 @@ Dynaword principle = openly licensed. Allow only PD / CC0 / CC-BY / CC-BY-SA.
|
|
| 4 |
NC/ND are not open; InC / NoC-* / CNE are in-copyright or unclear -> drop.
|
| 5 |
Wire into build_dynaword.py only for europeana (per-record); other sources keep
|
| 6 |
their single per-source license.
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# ponytail: substring match on the rights URI — finite, well-known statement set
|
| 10 |
_OPEN = (
|
|
@@ -32,6 +38,30 @@ def spdx(uri: str) -> str:
|
|
| 32 |
return "UNKNOWN"
|
| 33 |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
if __name__ == "__main__": # self-check
|
| 36 |
assert rights_ok("http://creativecommons.org/licenses/by-sa/4.0/")
|
| 37 |
assert rights_ok("https://creativecommons.org/publicdomain/mark/1.0/")
|
|
@@ -44,4 +74,6 @@ if __name__ == "__main__": # self-check
|
|
| 44 |
assert spdx("http://creativecommons.org/licenses/by-sa/4.0/") == "CC-BY-SA-4.0"
|
| 45 |
assert spdx("http://creativecommons.org/publicdomain/zero/1.0/") == "CC0-1.0"
|
| 46 |
assert spdx("http://creativecommons.org/publicdomain/mark/1.0/") == "public-domain (PDM-1.0)"
|
|
|
|
|
|
|
| 47 |
print("ok")
|
|
|
|
| 4 |
NC/ND are not open; InC / NoC-* / CNE are in-copyright or unclear -> drop.
|
| 5 |
Wire into build_dynaword.py only for europeana (per-record); other sources keep
|
| 6 |
their single per-source license.
|
| 7 |
+
|
| 8 |
+
Also holds license_for_revision(): the per-page label of the Wikimedia sources
|
| 9 |
+
(wikipedia, wikinews, wikivoyage, wikibooks), chosen by the page's last revision.
|
| 10 |
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
|
| 15 |
# ponytail: substring match on the rights URI — finite, well-known statement set
|
| 16 |
_OPEN = (
|
|
|
|
| 38 |
return "UNKNOWN"
|
| 39 |
|
| 40 |
|
| 41 |
+
# Text contributed under the 2014 Wikimedia ToU is CC BY-SA 3.0; the ToU in force from
|
| 42 |
+
# 2023-06-07 moved new text to CC BY-SA 4.0. A page last edited on or after the
|
| 43 |
+
# cutoff is an adaptation of its 3.0 text, which BY-SA 3.0 s4(b)(ii) lets us
|
| 44 |
+
# distribute under 4.0 (same licence elements). Time of day of the switch is not
|
| 45 |
+
# published, so midnight UTC labels that whole day 4.0 (the later licence).
|
| 46 |
+
BY_SA_4_CUTOFF = datetime(2023, 6, 7, tzinfo=timezone.utc)
|
| 47 |
+
# pl.wikinews moved from CC BY 2.5 to CC BY 4.0 on 2024-12-16 (Wikinews:Warunki uzycia;
|
| 48 |
+
# config deployed 08:08-08:32 UTC, Phabricator T381421). Same midnight-UTC rule.
|
| 49 |
+
WIKINEWS_BY_4_CUTOFF = datetime(2024, 12, 16, tzinfo=timezone.utc)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def license_for_revision(timestamp: str | None, cutoff: datetime = BY_SA_4_CUTOFF,
|
| 53 |
+
before: str = "CC-BY-SA-3.0", after: str = "CC-BY-SA-4.0") -> str:
|
| 54 |
+
"""SPDX label for a page whose last revision is at `timestamp` (ISO 8601 with zone):
|
| 55 |
+
`before` if it predates `cutoff`, else `after`. The defaults are the Wikimedia
|
| 56 |
+
CC BY-SA 3.0 -> 4.0 switch; wikinews passes its own cutoff and labels."""
|
| 57 |
+
if not timestamp:
|
| 58 |
+
raise ValueError("missing revision timestamp")
|
| 59 |
+
ts = datetime.fromisoformat(timestamp)
|
| 60 |
+
if ts.tzinfo is None:
|
| 61 |
+
raise ValueError(f"revision timestamp without timezone: {timestamp!r}")
|
| 62 |
+
return after if ts >= cutoff else before
|
| 63 |
+
|
| 64 |
+
|
| 65 |
if __name__ == "__main__": # self-check
|
| 66 |
assert rights_ok("http://creativecommons.org/licenses/by-sa/4.0/")
|
| 67 |
assert rights_ok("https://creativecommons.org/publicdomain/mark/1.0/")
|
|
|
|
| 74 |
assert spdx("http://creativecommons.org/licenses/by-sa/4.0/") == "CC-BY-SA-4.0"
|
| 75 |
assert spdx("http://creativecommons.org/publicdomain/zero/1.0/") == "CC0-1.0"
|
| 76 |
assert spdx("http://creativecommons.org/publicdomain/mark/1.0/") == "public-domain (PDM-1.0)"
|
| 77 |
+
assert license_for_revision("2023-06-06T23:59:59Z") == "CC-BY-SA-3.0"
|
| 78 |
+
assert license_for_revision("2023-06-07T00:00:00Z") == "CC-BY-SA-4.0"
|
| 79 |
print("ok")
|
src/sources.py
CHANGED
|
@@ -355,18 +355,32 @@ SOURCES = {
|
|
| 355 |
"added": "2026-07-02",
|
| 356 |
"release": "0.2.0",
|
| 357 |
"file_key": "plwikinews", # fetched from Wikimedia dumps, NOT via SpeakLeash
|
|
|
|
|
|
|
| 358 |
"pretty": "Polish Wikinews",
|
| 359 |
-
"
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
"
|
| 366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
"domain": "news",
|
| 368 |
-
"created": "
|
| 369 |
"is_ocr": False,
|
|
|
|
| 370 |
},
|
| 371 |
"wikivoyage": {
|
| 372 |
"added": "2026-07-02",
|
|
|
|
| 355 |
"added": "2026-07-02",
|
| 356 |
"release": "0.2.0",
|
| 357 |
"file_key": "plwikinews", # fetched from Wikimedia dumps, NOT via SpeakLeash
|
| 358 |
+
"preserve_id": True,
|
| 359 |
+
"preserve_created": True,
|
| 360 |
"pretty": "Polish Wikinews",
|
| 361 |
+
"provenance": "Parsed directly from the official Wikimedia dump "
|
| 362 |
+
"plwikinews-20260601-pages-articles (sha1 checked against the "
|
| 363 |
+
"dump's dumpstatus.json and sha1sums.txt) by "
|
| 364 |
+
"src/fetch_wikimedia.py. Articles (namespace 0) only, no "
|
| 365 |
+
"redirects; one document per page, id from the page id. The text "
|
| 366 |
+
"set is the one released in v0.2.0-v0.2.5; the rebuild adds the "
|
| 367 |
+
"page's last-revision time, which sets the licence label.",
|
| 368 |
+
"license": "CC BY (2.5 or 4.0 per record, by last-revision date)",
|
| 369 |
+
"license_spdx": "MIXED",
|
| 370 |
+
"traceable": "pl.wikinews licenses its content CC BY 2.5 until 2024-12-16 and "
|
| 371 |
+
"CC BY 4.0 from that day (its terms page). A page whose last "
|
| 372 |
+
"revision predates 2024-12-16 is labelled CC-BY-2.5; one revised "
|
| 373 |
+
"on or after that day is labelled CC-BY-4.0. It may still hold 2.5 "
|
| 374 |
+
"text, and CC BY 2.5 has no later-version clause, so that label "
|
| 375 |
+
"rests on the terms page alone. Each row's author field links its "
|
| 376 |
+
"page, whose history names the contributors; "
|
| 377 |
+
"wikinews.attribution.jsonl gives page id, revision id, title and "
|
| 378 |
+
"last-revision time per row.",
|
| 379 |
+
"upstream": "https://dumps.wikimedia.org/plwikinews/20260601/",
|
| 380 |
"domain": "news",
|
| 381 |
+
"created": "2011-12-24, 2026-05-25",
|
| 382 |
"is_ocr": False,
|
| 383 |
+
"custom_datasheet": True,
|
| 384 |
},
|
| 385 |
"wikivoyage": {
|
| 386 |
"added": "2026-07-02",
|
src/test_wikimedia_contract.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit and contract checks for src/fetch_wikimedia.py (wikinews, wikivoyage, wikibooks).
|
| 2 |
+
|
| 3 |
+
The unit tests run on a fixture dump and never touch data/. `check_released(key, tmp_path)`
|
| 4 |
+
is the contract on a released source; test_<key>_contract.py calls it, so a branch carrying
|
| 5 |
+
one source's data is tested against that source only."""
|
| 6 |
+
|
| 7 |
+
import bz2
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from datetime import datetime, timedelta, timezone
|
| 10 |
+
import gzip
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import re
|
| 14 |
+
import shutil
|
| 15 |
+
import subprocess
|
| 16 |
+
|
| 17 |
+
import pyarrow as pa
|
| 18 |
+
import pyarrow.parquet as pq
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
import fetch_wikimedia as fm
|
| 22 |
+
import fetch_wikipedia as fw
|
| 23 |
+
import rights
|
| 24 |
+
from rights import BY_SA_4_CUTOFF, WIKINEWS_BY_4_CUTOFF, license_for_revision
|
| 25 |
+
from sources import SOURCES
|
| 26 |
+
from verify_paper_claims import license_family
|
| 27 |
+
|
| 28 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 29 |
+
KEYS = sorted(fm.SITES)
|
| 30 |
+
SHA256 = re.compile(r"[0-9a-f]{64}")
|
| 31 |
+
SHA1 = re.compile(r"[0-9a-f]{40}")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _read(path):
|
| 35 |
+
return json.loads(Path(path).read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# --- licence label per last-revision timestamp -------------------------------------------
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize("timestamp, label", [
|
| 41 |
+
("2023-06-07T00:00:00Z", "CC-BY-SA-4.0"), # exactly the cutoff
|
| 42 |
+
("2023-06-06T23:59:59Z", "CC-BY-SA-3.0"), # one second before
|
| 43 |
+
("2023-06-07T00:30:00+01:00", "CC-BY-SA-3.0"), # 2023-06-06T23:30Z
|
| 44 |
+
("2023-06-06T23:30:00-01:00", "CC-BY-SA-4.0"), # 2023-06-07T00:30Z
|
| 45 |
+
("2004-03-01T10:00:00Z", "CC-BY-SA-3.0"),
|
| 46 |
+
("2026-09-01T12:00:00Z", "CC-BY-SA-4.0"),
|
| 47 |
+
])
|
| 48 |
+
def test_license_for_revision_defaults_are_the_wikimedia_by_sa_switch(timestamp, label):
|
| 49 |
+
assert license_for_revision(timestamp) == label
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize("timestamp, label", [
|
| 53 |
+
("2024-12-16T00:00:00Z", "CC-BY-4.0"),
|
| 54 |
+
("2024-12-15T23:59:59Z", "CC-BY-2.5"),
|
| 55 |
+
("2024-12-16T00:30:00+01:00", "CC-BY-2.5"), # 2024-12-15T23:30Z
|
| 56 |
+
("2024-12-15T23:30:00-01:00", "CC-BY-4.0"), # 2024-12-16T00:30Z
|
| 57 |
+
("2011-12-24T00:00:00Z", "CC-BY-2.5"),
|
| 58 |
+
("2023-06-07T00:00:00Z", "CC-BY-2.5"), # the BY-SA cutoff means nothing to wikinews
|
| 59 |
+
])
|
| 60 |
+
def test_license_for_revision_with_the_wikinews_cutoff(timestamp, label):
|
| 61 |
+
assert license_for_revision(timestamp, WIKINEWS_BY_4_CUTOFF, "CC-BY-2.5", "CC-BY-4.0") == label
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@pytest.mark.parametrize("timestamp", [None, "", "2023-06-07T00:00:00", "2023-06-07", "not a date"])
|
| 65 |
+
@pytest.mark.parametrize("args", [(), (WIKINEWS_BY_4_CUTOFF, "CC-BY-2.5", "CC-BY-4.0")])
|
| 66 |
+
def test_license_for_revision_fails_without_a_zoned_timestamp(timestamp, args):
|
| 67 |
+
with pytest.raises(ValueError):
|
| 68 |
+
license_for_revision(timestamp, *args)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_cutoffs_are_midnight_utc_and_the_wikipedia_module_re_exports_the_helper():
|
| 72 |
+
for cutoff in (BY_SA_4_CUTOFF, WIKINEWS_BY_4_CUTOFF):
|
| 73 |
+
assert cutoff.utcoffset() == timedelta(0) and cutoff.time().isoformat() == "00:00:00"
|
| 74 |
+
assert (BY_SA_4_CUTOFF.date().isoformat(), WIKINEWS_BY_4_CUTOFF.date().isoformat()) == ("2023-06-07", "2024-12-16")
|
| 75 |
+
assert fw.license_for_revision is rights.license_for_revision and fw.BY_SA_4_CUTOFF is BY_SA_4_CUTOFF
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize("key", KEYS)
|
| 79 |
+
def test_site_config(key):
|
| 80 |
+
site = fm.SITES[key]
|
| 81 |
+
assert site["cutoff"].tzinfo is not None and site["before"] != site["after"]
|
| 82 |
+
assert fm.label(key, (site["cutoff"] - timedelta(seconds=1)).isoformat()) == site["before"]
|
| 83 |
+
assert fm.label(key, site["cutoff"].isoformat()) == site["after"]
|
| 84 |
+
assert site["cutoff"] == (WIKINEWS_BY_4_CUTOFF if key == "wikinews" else BY_SA_4_CUTOFF)
|
| 85 |
+
assert site["wiki"] == "pl" + key and site["host"] == f"pl.{key}.org"
|
| 86 |
+
assert all(SHA256.fullmatch(t["sha256"]) and t["effective"] and t["statement"] for t in site["terms"])
|
| 87 |
+
assert all(p["url"].startswith("https://creativecommons.org/licenses/") and p["statement"] for p in site["legal"])
|
| 88 |
+
assert ("clock" in site) == (key == "wikinews") # only wikinews has a known time of day for the switch
|
| 89 |
+
assert fm.dump_base(key) == f"https://dumps.wikimedia.org/pl{key}/{fm.DUMP_DATE}"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# --- small helpers -------------------------------------------------------------------------
|
| 93 |
+
|
| 94 |
+
def test_page_url_quotes_the_title_and_keeps_namespace_and_subpage_separators():
|
| 95 |
+
assert fm.page_url("wikivoyage", "Kraków (miasto)") == "https://pl.wikivoyage.org/wiki/Krak%C3%B3w_%28miasto%29"
|
| 96 |
+
assert fm.page_url("wikibooks", "Książka:C/O podręczniku") == "https://pl.wikibooks.org/wiki/Ksi%C4%85%C5%BCka:C/O_podr%C4%99czniku"
|
| 97 |
+
assert fm.page_url("wikinews", None) == "https://pl.wikinews.org/wiki/"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_strip_converts_wikitext_as_the_v025_builder_did():
|
| 101 |
+
# plain strip_code: templates and comments go, ref bodies and category links stay (see the card)
|
| 102 |
+
assert fm.strip("'''Ala''' ma [[kot|kota]]<!-- x -->{{Szablon|a}}.\n\n\n[[Kategoria:Koty]]") == "Ala ma kota.\n\nKategoria:Koty"
|
| 103 |
+
assert fm.strip(" \n") == ""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_strip_reports_a_parser_failure_as_none(monkeypatch):
|
| 107 |
+
import mwparserfromhell
|
| 108 |
+
|
| 109 |
+
def boom(_):
|
| 110 |
+
raise RuntimeError("parser")
|
| 111 |
+
monkeypatch.setattr(mwparserfromhell, "parse", boom)
|
| 112 |
+
assert fm.strip("tekst") is None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class _Reply:
|
| 116 |
+
def __init__(self, body):
|
| 117 |
+
self.content = body
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@pytest.mark.parametrize("body, ok", [
|
| 121 |
+
(b"<p>a later version of this</p> <b>License</b> text", True),
|
| 122 |
+
(b"<p>text without the clause</p>", False),
|
| 123 |
+
(b"<p>a later version of this License text; also: later version</p>", True),
|
| 124 |
+
])
|
| 125 |
+
def test_legal_pin_requires_the_clause_the_label_rests_on(monkeypatch, body, ok):
|
| 126 |
+
pin = {"url": "https://x/legalcode", "section": "4", "statement": "a later version of this License"}
|
| 127 |
+
monkeypatch.setattr(fm, "request", lambda url: _Reply(body))
|
| 128 |
+
if ok:
|
| 129 |
+
assert fm.legal_pin(pin) == {**pin, "sha256": fm.hashlib.sha256(body).hexdigest()}
|
| 130 |
+
else:
|
| 131 |
+
with pytest.raises(ValueError, match="legal code changed"):
|
| 132 |
+
fm.legal_pin(pin)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_legal_pin_fails_when_a_clause_that_must_be_absent_appears(monkeypatch):
|
| 136 |
+
pin = {"url": "https://x/legalcode", "section": "4(a)", "statement": "You may not sublicense", "absent": "later version"}
|
| 137 |
+
monkeypatch.setattr(fm, "request", lambda url: _Reply(b"You may not sublicense the Work"))
|
| 138 |
+
assert fm.legal_pin(pin)["sha256"]
|
| 139 |
+
monkeypatch.setattr(fm, "request", lambda url: _Reply(b"You may not sublicense the Work. A later version applies."))
|
| 140 |
+
with pytest.raises(ValueError, match="legal code changed"):
|
| 141 |
+
fm.legal_pin(pin)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# --- dump pipeline on a fixture ------------------------------------------------------------
|
| 145 |
+
|
| 146 |
+
def _page(pageid, title, ns, timestamp, text, redirect=""):
|
| 147 |
+
return (f"<page><title>{title}</title><ns>{ns}</ns><id>{pageid}</id>"
|
| 148 |
+
+ (f'<redirect title="{redirect}" />' if redirect else "")
|
| 149 |
+
+ f"<revision><id>{pageid * 100}</id><parentid>1</parentid>"
|
| 150 |
+
+ (f"<timestamp>{timestamp}</timestamp>" if timestamp else "")
|
| 151 |
+
+ f"<contributor><username>U</username><id>7</id></contributor>"
|
| 152 |
+
f"<text bytes=\"1\">{text}</text><sha1>x</sha1></revision></page>")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _wrap(*pages):
|
| 156 |
+
return ('<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/"><siteinfo><sitename>W</sitename></siteinfo>'
|
| 157 |
+
+ "".join(pages) + "</mediawiki>")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
OLD = "Stary artykuł opisuje wydarzenia sprzed wielu lat, spisane przez pierwszych autorów tego serwisu. " * 4
|
| 161 |
+
BODY = "Ala jest polskim imieniem żeńskim, noszonym przez wiele znanych osób w różnych epokach. " * 4
|
| 162 |
+
DOG = "Pies domowy jest udomowionym ssakiem z rodziny psowatych, towarzyszem człowieka od wieków. " * 4
|
| 163 |
+
MOUSE = "Mysz domowa jest gryzoniem z rodziny myszowatych, żyjącym zwykle w pobliżu człowieka. " * 4
|
| 164 |
+
NAME = "dump.xml.bz2"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _stamp(moment):
|
| 168 |
+
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _fixture(key):
|
| 172 |
+
"""Pages around the site's cutoff; the page ids are in dump order."""
|
| 173 |
+
site = fm.SITES[key]
|
| 174 |
+
cut, era = site["cutoff"], datetime.fromisoformat(site["era_end"]) - timedelta(days=1)
|
| 175 |
+
return _wrap(
|
| 176 |
+
_page(5, "Stara", 0, _stamp(era), OLD),
|
| 177 |
+
_page(10, "Ala", 0, _stamp(cut), BODY + "[[Kategoria:Imiona]]"), # the cutoff second
|
| 178 |
+
_page(11, "Przekierowanie", 0, _stamp(cut), "#PATRZ [[Ala]]", redirect="Ala"),
|
| 179 |
+
_page(12, "Dyskusja:Ala", 1, _stamp(cut), BODY),
|
| 180 |
+
_page(13, "Pusty", 0, _stamp(cut), ""),
|
| 181 |
+
_page(14, "Krótki", 0, _stamp(cut), "Krótki tekst."),
|
| 182 |
+
_page(15, "Kopia Ali", 0, _stamp(cut), BODY + "[[Kategoria:Imiona]]"), # same text as 10
|
| 183 |
+
_page(16, "Pies", 0, _stamp(cut - timedelta(seconds=1)), DOG),
|
| 184 |
+
_page(17, "Mysz (zwierzę)", 0, _stamp(cut + timedelta(hours=9)), MOUSE),
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _selection(tmp_path, key):
|
| 189 |
+
site = fm.SITES[key]
|
| 190 |
+
(tmp_path / "raw_dump").mkdir(exist_ok=True)
|
| 191 |
+
fm.save(tmp_path / f"{key}.selection.json", {
|
| 192 |
+
"observed_at": "2026-10-06T00:00:00Z", "dump_date": fm.DUMP_DATE, "dump_base": fm.dump_base(key),
|
| 193 |
+
"sha1sums_url": "s", "file": {"name": NAME, "size": 1, "sha1": "x"}, "rightsinfo": {"url": "r"},
|
| 194 |
+
"terms": site["terms"], "legal": site["legal"], "switch": None,
|
| 195 |
+
"cutoff": site["cutoff"].isoformat(), "before": site["before"], "after": site["after"],
|
| 196 |
+
})
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _prepare(tmp_path, key, xml):
|
| 200 |
+
_selection(tmp_path, key)
|
| 201 |
+
(tmp_path / "raw_dump" / NAME).write_bytes(bz2.compress(xml.encode()))
|
| 202 |
+
fm.prepare(tmp_path, key)
|
| 203 |
+
out = subprocess.run(["zstd", "-dc", str(tmp_path / f"pl{key}.jsonl.zst")], capture_output=True, check=True)
|
| 204 |
+
return [json.loads(line) for line in out.stdout.decode().splitlines()]
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
needs_zstd = pytest.mark.skipif(shutil.which("zstd") is None, reason="zstd CLI")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@needs_zstd
|
| 211 |
+
@pytest.mark.parametrize("key", KEYS)
|
| 212 |
+
def test_prepare_labels_filters_and_dedups(tmp_path, key):
|
| 213 |
+
site = fm.SITES[key]
|
| 214 |
+
before, after = site["before"], site["after"]
|
| 215 |
+
rows = _prepare(tmp_path, key, _fixture(key))
|
| 216 |
+
# 15 repeats 10's text and is dropped (lowest id wins); redirect, talk page, empty and short pages are skipped
|
| 217 |
+
assert [r["id"] for r in rows] == [f"{key}_{i}" for i in (5, 10, 16, 17)]
|
| 218 |
+
assert [r["license"] for r in rows] == [before, after, before, after]
|
| 219 |
+
cut = site["cutoff"]
|
| 220 |
+
assert [r["created"] for r in rows][1:] == [cut.date().isoformat(), (cut - timedelta(seconds=1)).date().isoformat(),
|
| 221 |
+
cut.date().isoformat()]
|
| 222 |
+
assert rows[1]["author"] == f"{site['author']}, https://{site['host']}/wiki/Ala"
|
| 223 |
+
assert rows[3]["author"] == f"{site['author']}, https://{site['host']}/wiki/Mysz_%28zwierz%C4%99%29"
|
| 224 |
+
assert set(rows[0]) == {"id", "text", "created", "license", "author"}
|
| 225 |
+
prep = _read(tmp_path / f"{key}.prepare.json")
|
| 226 |
+
assert prep == {"counts": {"pages": 9, "ns0": 8, "ns0_redirect": 1, "ns0_empty": 1, "ns0_short": 1,
|
| 227 |
+
"exact_duplicate": 1, "written": 4, before: 2, after: 2},
|
| 228 |
+
"exact_duplicate_pageids": ["15"]}
|
| 229 |
+
with gzip.open(tmp_path / f"{key}.manifest.jsonl.gz", "rt", encoding="utf-8") as fh:
|
| 230 |
+
manifest = [json.loads(line) for line in fh]
|
| 231 |
+
assert [(m["id"], m["pageid"], m["revid"], m["license"]) for m in manifest] == [
|
| 232 |
+
(f"{key}_5", 5, 500, before), (f"{key}_10", 10, 1000, after), (f"{key}_16", 16, 1600, before), (f"{key}_17", 17, 1700, after)]
|
| 233 |
+
assert manifest[1]["last_revision_at"] == _stamp(cut) and manifest[1]["title"] == "Ala"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@needs_zstd
|
| 237 |
+
def test_prepare_fails_on_a_dump_out_of_page_id_order(tmp_path):
|
| 238 |
+
xml = _wrap(_page(20, "A", 0, "2020-01-01T00:00:00Z", BODY), _page(10, "B", 0, "2020-01-01T00:00:00Z", DOG))
|
| 239 |
+
with pytest.raises(ValueError, match="page-id order at 10"):
|
| 240 |
+
_prepare(tmp_path, "wikibooks", xml)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@needs_zstd
|
| 244 |
+
@pytest.mark.parametrize("timestamp", [None, "2020-01-01T00:00:00"])
|
| 245 |
+
def test_prepare_fails_on_a_kept_page_without_a_usable_timestamp(tmp_path, timestamp):
|
| 246 |
+
xml = _wrap(_page(10, "A", 0, timestamp, BODY))
|
| 247 |
+
with pytest.raises(ValueError):
|
| 248 |
+
_prepare(tmp_path, "wikinews", xml)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@needs_zstd
|
| 252 |
+
def test_prepare_ignores_a_missing_timestamp_on_a_skipped_page(tmp_path):
|
| 253 |
+
xml = _wrap(_page(10, "A", 0, None, "#PATRZ [[B]]", redirect="B"), _page(11, "B", 0, "2020-01-01T00:00:00Z", BODY))
|
| 254 |
+
assert [r["id"] for r in _prepare(tmp_path, "wikinews", xml)] == ["wikinews_11"]
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _kept_table(tmp_path, ids_tokens, rows):
|
| 258 |
+
"""The parquet the build would leave: attribution reads id, created, license, token_count."""
|
| 259 |
+
by_id = {r["id"]: r for r in rows}
|
| 260 |
+
data = tmp_path / "data"
|
| 261 |
+
data.mkdir(exist_ok=True)
|
| 262 |
+
pq.write_table(pa.table({
|
| 263 |
+
"id": [i for i, _ in ids_tokens], "created": [by_id[i]["created"] for i, _ in ids_tokens],
|
| 264 |
+
"license": [by_id[i]["license"] for i, _ in ids_tokens], "token_count": [t for _, t in ids_tokens]}),
|
| 265 |
+
data / "x.parquet")
|
| 266 |
+
return data
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@needs_zstd
|
| 270 |
+
@pytest.mark.parametrize("key", KEYS)
|
| 271 |
+
def test_attribution_sidecars_cover_the_kept_rows_and_split_the_cutoff_day(tmp_path, key):
|
| 272 |
+
site = fm.SITES[key]
|
| 273 |
+
rows = _prepare(tmp_path, key, _fixture(key))
|
| 274 |
+
# the build keeps 5, 10 and 17 (16 fails its language gate)
|
| 275 |
+
kept = [(f"{key}_5", 100), (f"{key}_10", 200), (f"{key}_17", 300)]
|
| 276 |
+
data = _kept_table(tmp_path, kept, rows)
|
| 277 |
+
(data / "x.parquet").rename(data / f"{key}.parquet")
|
| 278 |
+
fm.attribution(tmp_path, data, key)
|
| 279 |
+
sidecar = data / f"{key}.attribution.jsonl"
|
| 280 |
+
recs = [json.loads(line) for line in sidecar.read_text(encoding="utf-8").splitlines()]
|
| 281 |
+
assert [r["id"] for r in recs] == [i for i, _ in kept]
|
| 282 |
+
assert set(recs[1]) == {"id", "pageid", "revid", "title", "url", "last_revision_at", "license"}
|
| 283 |
+
assert recs[2]["url"] == f"https://{site['host']}/wiki/Mysz_%28zwierz%C4%99%29" and recs[2]["revid"] == 1700
|
| 284 |
+
|
| 285 |
+
build = _read(data / f"{key}.build.json")
|
| 286 |
+
assert build["attribution_rows"] == 3 and build["attribution_sha256"] == fm.digest(sidecar.read_bytes())
|
| 287 |
+
assert build["prepare"] == _read(tmp_path / f"{key}.prepare.json") and build["labels"] == {"before": site["before"], "after": site["after"]}
|
| 288 |
+
|
| 289 |
+
ev = _read(data / f"{key}.license-evidence.json")
|
| 290 |
+
day = site["cutoff"].date().isoformat()
|
| 291 |
+
boundary = {"day": day, "docs_last_edited_that_day": 2} # 10 at midnight and 17 at 09:00; 16 is the day before
|
| 292 |
+
if "clock" in site:
|
| 293 |
+
boundary.update(known_switch_time_utc=site["clock"], of_which_before_that_time=1) # 10 only
|
| 294 |
+
assert ev["cutoff"] == {"at": site["cutoff"].isoformat(), "before": site["before"], "after": site["after"], "boundary_day": boundary}
|
| 295 |
+
scope = ev["release_scope"]
|
| 296 |
+
assert scope["labels"] == {site["before"]: 1, site["after"]: 2}
|
| 297 |
+
assert scope["tokens"] == {site["before"]: 100, site["after"]: 500}
|
| 298 |
+
assert scope["created_range"] == [min(r["created"] for r in rows if r["id"] in dict(kept)), day]
|
| 299 |
+
assert scope["last_edited_before_era_end"] == {"date": site["era_end"], "docs": 1, "tokens": 100} # page 5
|
| 300 |
+
assert ev["status"] == ("documented-open-cc-by-sa" if "SA" in site["after"] else "documented-open-cc-by")
|
| 301 |
+
assert ev["checked_at"] == "2026-10-06" and ev["terms"] == site["terms"]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@needs_zstd
|
| 305 |
+
def test_attribution_fails_when_the_parquet_has_a_row_the_dump_does_not(tmp_path):
|
| 306 |
+
rows = _prepare(tmp_path, "wikibooks", _fixture("wikibooks"))
|
| 307 |
+
data = _kept_table(tmp_path, [("wikibooks_10", 1), ("wikibooks_999", 1)], rows + [{"id": "wikibooks_999", "created": "2020-01-01", "license": "x"}])
|
| 308 |
+
(data / "x.parquet").rename(data / "wikibooks.parquet")
|
| 309 |
+
with pytest.raises(ValueError, match="attribution rows 1 != parquet rows 2"):
|
| 310 |
+
fm.attribution(tmp_path, data, "wikibooks")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# --- the contract on a released source -----------------------------------------------------
|
| 314 |
+
|
| 315 |
+
def check_released(key, tmp_path):
|
| 316 |
+
"""Checks that hold for any source built by fetch_wikimedia.py; counts specific to a source live in its own test file."""
|
| 317 |
+
site, data, entry = fm.SITES[key], ROOT / "data" / key, SOURCES[key]
|
| 318 |
+
stats, build, ev = (_read(data / f"{key}.{n}.json") for n in ("stats", "build", "license-evidence"))
|
| 319 |
+
assert pq.read_schema(data / f"{key}.parquet").names == ["id", "text", "source", "added", "created", "token_count", "license", "author"]
|
| 320 |
+
cols = pq.read_table(data / f"{key}.parquet").to_pydict()
|
| 321 |
+
n = len(cols["id"])
|
| 322 |
+
meta = {}
|
| 323 |
+
with (data / f"{key}.attribution.jsonl").open(encoding="utf-8") as fh:
|
| 324 |
+
for line in fh:
|
| 325 |
+
rec = json.loads(line)
|
| 326 |
+
meta[rec["id"]] = rec
|
| 327 |
+
sidecar = (data / f"{key}.attribution.jsonl").read_bytes()
|
| 328 |
+
|
| 329 |
+
# rows, counts, the unchanged text set
|
| 330 |
+
assert n == stats["kept"] == build["attribution_rows"] == len(meta) == len(set(cols["id"]))
|
| 331 |
+
assert set(cols["source"]) == {key} and len(set(cols["added"])) == 1
|
| 332 |
+
assert (stats["kept"], stats["chars"], stats["tokens"]) == site["v025"] # the rebuild changes labels, not the text set
|
| 333 |
+
assert sum(len(t) for t in cols["text"]) == stats["chars"] and sum(cols["token_count"]) == stats["tokens"]
|
| 334 |
+
assert min(len(t) for t in cols["text"]) >= fm.MIN_CHARS and stats["drop_short"] == stats["drop_dup"] == 0
|
| 335 |
+
counts = build["prepare"]["counts"]
|
| 336 |
+
skipped = sum(counts.get(k, 0) for k in ("ns0_redirect", "ns0_empty", "ns0_strip_error", "ns0_short", "exact_duplicate"))
|
| 337 |
+
assert counts["ns0"] == skipped + counts["written"] and counts["written"] == stats["read"] == n + stats["drop_lang"]
|
| 338 |
+
assert counts[site["before"]] + counts[site["after"]] == counts["written"]
|
| 339 |
+
assert build["attribution_sha256"] == fm.digest(sidecar)
|
| 340 |
+
|
| 341 |
+
# every row's label, date, author and id follow the page's last revision
|
| 342 |
+
for row_id, created, label, author in zip(cols["id"], cols["created"], cols["license"], cols["author"]):
|
| 343 |
+
m = meta[row_id]
|
| 344 |
+
assert label == m["license"] == fm.label(key, m["last_revision_at"]) and label in (site["before"], site["after"])
|
| 345 |
+
assert created == m["last_revision_at"][:10]
|
| 346 |
+
assert m["url"] == fm.page_url(key, m["title"]) and author == f"{site['author']}, {m['url']}"
|
| 347 |
+
assert row_id == f"{key}_{m['pageid']}"
|
| 348 |
+
scope = ev["release_scope"]
|
| 349 |
+
tokens = Counter()
|
| 350 |
+
for label, tok in zip(cols["license"], cols["token_count"]):
|
| 351 |
+
tokens[label] += tok
|
| 352 |
+
assert stats["licenses"] == dict(Counter(cols["license"])) == scope["labels"] and scope["tokens"] == dict(tokens)
|
| 353 |
+
assert scope["created_range"] == [min(cols["created"]), max(cols["created"])]
|
| 354 |
+
day = site["cutoff"].date().isoformat()
|
| 355 |
+
on_day = [m["last_revision_at"] for m in meta.values() if m["last_revision_at"].startswith(day)]
|
| 356 |
+
assert ev["cutoff"]["boundary_day"]["docs_last_edited_that_day"] == len(on_day)
|
| 357 |
+
if "clock" in site:
|
| 358 |
+
assert ev["cutoff"]["boundary_day"]["of_which_before_that_time"] == sum(t.replace("T", " ").rstrip("Z") < site["clock"] for t in on_day)
|
| 359 |
+
old = [m for m in meta.values() if m["last_revision_at"] < site["era_end"]]
|
| 360 |
+
assert scope["last_edited_before_era_end"] == {"date": site["era_end"], "docs": len(old),
|
| 361 |
+
"tokens": sum(t for i, t in zip(cols["id"], cols["token_count"]) if meta[i]["last_revision_at"] < site["era_end"])}
|
| 362 |
+
|
| 363 |
+
# the evidence is what the fetcher pins
|
| 364 |
+
assert ev["cutoff"]["at"] == site["cutoff"].isoformat() and ev["terms"] == site["terms"]
|
| 365 |
+
assert [(p["url"], p["section"], p["statement"]) for p in ev["legal"]] == [(p["url"], p["section"], p["statement"]) for p in site["legal"]]
|
| 366 |
+
assert all(SHA256.fullmatch(p["sha256"]) for p in ev["legal"]) and ev["switch"] == build["switch"]
|
| 367 |
+
assert (ev["switch"]["synced_by_utc"] == site["clock"] and ev["switch"]["gerrit_status"] == "MERGED") if "clock" in site else ev["switch"] is None
|
| 368 |
+
assert build["file"]["name"] == f"{site['wiki']}-{fm.DUMP_DATE}-pages-articles.xml.bz2" and SHA1.fullmatch(build["file"]["sha1"])
|
| 369 |
+
assert build["dump_date"] == fm.DUMP_DATE and build["dump_base"] == fm.dump_base(key)
|
| 370 |
+
assert re.fullmatch(r"\d{4}-\d\d-\d\d", ev["checked_at"])
|
| 371 |
+
|
| 372 |
+
# the registry entry and the card
|
| 373 |
+
assert entry["file_key"] == site["wiki"] and entry["preserve_id"] is True and entry["preserve_created"] is True
|
| 374 |
+
assert entry["license_spdx"] == "MIXED" and entry["release"] == "0.2.0" and entry["custom_datasheet"] is True
|
| 375 |
+
assert entry["upstream"] == build["dump_base"] + "/" and stats["license"] == entry["license"]
|
| 376 |
+
assert entry["created"] == ", ".join(scope["created_range"])
|
| 377 |
+
assert license_family(entry["license"]) == site["family"].replace(" ", "-")
|
| 378 |
+
work = tmp_path / "data"
|
| 379 |
+
work.mkdir()
|
| 380 |
+
for f in data.glob(f"{key}.*"):
|
| 381 |
+
if f.suffix in (".json", ".jsonl"):
|
| 382 |
+
shutil.copy(f, work)
|
| 383 |
+
fm.datasheet(tmp_path, work, key) # the committed card is what the generator writes from the sidecars
|
| 384 |
+
assert (work / f"{key}.md").read_text(encoding="utf-8") == (data / f"{key}.md").read_text(encoding="utf-8")
|
| 385 |
+
return stats, ev
|
src/test_wikinews_contract.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contract checks for the released wikinews source (Polish Wikinews, CC BY 2.5 until 2024-12-16 and CC BY 4.0 after); the shared checks live in test_wikimedia_contract.py."""
|
| 2 |
+
|
| 3 |
+
from test_wikimedia_contract import check_released
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_wikinews_contract(tmp_path):
|
| 7 |
+
stats, ev = check_released("wikinews", tmp_path)
|
| 8 |
+
assert (stats["kept"], stats["tokens"]) == (24386, 12141355)
|
| 9 |
+
assert stats["licenses"] == {"CC-BY-2.5": 17581, "CC-BY-4.0": 6805}
|
| 10 |
+
assert ev["release_scope"]["tokens"] == {"CC-BY-2.5": 8956397, "CC-BY-4.0": 3184958}
|
| 11 |
+
assert ev["cutoff"]["boundary_day"] == {"day": "2024-12-16", "docs_last_edited_that_day": 6, "known_switch_time_utc": "2024-12-16 08:32:24", "of_which_before_that_time": 2}
|
| 12 |
+
assert ev["release_scope"]["last_edited_before_era_end"] == {"date": "2005-09-25", "docs": 0, "tokens": 0}
|