govpl: drop 188 PAP reprints (gov.pl third-party carve-out), add URL sidecar

#63
by ppuzio - opened
artifacts/source_findings.md CHANGED
@@ -1260,3 +1260,64 @@ References: `rights_audit_2026-10/reports/citations.md` L10;
1260
  **Lesson** — a project-wide label on an aggregator pull hides per-page licences. Pull
1261
  from the official dump with page ids and licence templates, so each page can be
1262
  screened and labelled.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1260
  **Lesson** — a project-wide label on an aggregator pull hides per-page licences. Pull
1261
  from the official dump with page ids and licence templates, so each page can be
1262
  screened and labelled.
1263
+
1264
+ ## biblioteka_nauki — public-domain-label records dropped (2026-10-06)
1265
+
1266
+ **Verdict** — `added`, kept for v0.2.6 minus 3 records (polish-dynaword-v2#52). 42,071 →
1267
+ 42,068 documents, 673,488,831 → 673,112,676 tokens (−376,155), 1,748,333,935 →
1268
+ 1,747,387,478 characters. `src/clean_biblioteka_nauki.py` filters the v0.2.5 Parquet
1269
+ (pinned by SHA-256): it keeps `cc-by`, `cc-by-sa` and `cc0`, drops `public-domain`, and
1270
+ fails on any other value. `recover_attribution.py` no longer counts `public-domain` as clean.
1271
+
1272
+ **Reason** — the 3 rows (`books_2142716`, `books_2147851`, `articles_2097363`) carry the
1273
+ platform's "Domena publiczna" label. Verified 2026-10-06 against
1274
+ `bibliotekanauki.pl/api/{type}/{id}`: licence id 22, `creativeCommons: false`, URL
1275
+ `creativecommons.org/publicdomain/mark/1.0/`. Creative Commons describes the Mark as "a tag
1276
+ or a label" for works already free of copyright; it grants nothing. All three are original
1277
+ texts (`reprintPublication` and `translationPublication` false) first published 2019, 2021
1278
+ and 2022 by named authors (Jerzy Zając, Witold Rakowski, Beata Michalec), so life+70 has
1279
+ not run out. The 2019 book's own colophon reads "Copyright by Jerzy Zając 2019 / Copyright
1280
+ by Muzeum Niepodległości w Warszawie 2019". That the authors are alive is inferred.
1281
+
1282
+ **Not done here** — the licence version is still collapsed: rows say `cc-by`/`cc-by-sa`,
1283
+ the card and `stats.json` say 4.0. A live re-check (seed 20261006, 24 rows) found 4 of 12
1284
+ `cc-by` rows under 3.0 PL or 3.0 Unported; all 12 `cc-by-sa` rows were 4.0. Fixing it needs
1285
+ a per-record API re-fetch of name and version (tracked under polish-dynaword-v2#57). The
1286
+ card still names SpeakLeash while `src/sources.py` says direct rebuild; `licenses.jsonl`,
1287
+ `index.jsonl` and `build_parquet.py` are not in the repo. 128 kept rows (88 `cc-by`, 40
1288
+ `cc-by-sa`; 1.56% of tokens) contain "Wszelkie prawa zastrzeżone" or "All rights
1289
+ reserved" in their text (publication years 2010-2021); regex count only, not reviewed.
1290
+
1291
+ **Lesson** — a platform's "public domain" label can be the PD Mark. Check the URL behind
1292
+ the label, and check the date: a 2019 work cannot be public domain by term in Poland.
1293
+
1294
+ ## govpl — PAP reprints dropped (2026-10-06)
1295
+
1296
+ **Verdict** — `kept`, minus 188 PAP reprints (slayerlabs/polish-dynaword-v2#51).
1297
+ 88,190 → 88,002 documents, 80,666,129 → 80,445,758 tokens (−220,371). `release` stays
1298
+ `0.2.2`. `src/clean_govpl.py` filters the pinned v0.2.5 Parquet, so ids are unchanged,
1299
+ and writes `govpl.attribution.jsonl` with each row's gov.pl URL, subsite, title and date.
1300
+ `fetch_govpl.normalize()` applies the same rule (`pap_rule`) to future crawls.
1301
+
1302
+ **Reason** — gov.pl's copyright page grants CC BY-SA 4.0 for its text but carves out
1303
+ works whose copyright belongs to third parties; their use needs the owners' consent.
1304
+ Articles that credit PAP as their source are such works.
1305
+ - The issue's rule (`Źródło:` line naming PAP) matches 154 rows. A hand-check of 20
1306
+ (seed 51) found 20 text source lines and no photo credits; 14 credit PAP jointly with
1307
+ the ministry, so the text may be partly the ministry's. PAP's archive is not public, so
1308
+ verbatim PAP authorship was not confirmed.
1309
+ - A scan of the other rows added 34 verified text attributions: misspelt or colon-less
1310
+ source lines (9), `Na podst. … PAP` (22, all uw-podlaski), a lone `(PAP)` sign-off line
1311
+ (2) and one PAP interview transcript (prokuratura-krajowa). Photo credits (`fot. PAP`)
1312
+ and rows that quote or mention PAP stay.
1313
+ - Left in, flagged: a mid-text `(PAP)` after one paragraph (govpl_30227, govpl_58869), a
1314
+ footnote crediting PAP and the health ministry (govpl_81037), a KRRiT report quoting two
1315
+ PAP questions (govpl_86914).
1316
+ - Not reviewed: 710 kept rows carry a `Źródło:` line naming some other source (mostly
1317
+ government bodies; some name WHO, universities, journals).
1318
+
1319
+ References: `rights_audit_2026-10/reports/govweb.md` (govpl block);
1320
+ https://www.gov.pl/web/gov/prawa-autorskie (read 2026-10-06).
1321
+
1322
+ **Lesson** — an open-licence footer covers the publisher's own text. On a news-style
1323
+ site, check source lines for agency copy before taking the footer at face value.
data/biblioteka_nauki/biblioteka_nauki.md CHANGED
@@ -6,7 +6,7 @@ Biblioteka Nauki — Polish open-access scholarly corpus (scientific articles, b
6
  - **Source (upstream):** https://bibliotekanauki.pl (operated by ICM, University of Warsaw — Centrum Otwartej Nauki)
7
  - **Domain:** academic (scientific articles, books, chapters)
8
  - **Language:** Polish (pl)
9
- - **License:** per-document — CC BY 4.0 28,335 · CC BY-SA 4.0 13,733 · Public Domain 3
10
  - **Created (range):** per-document publication year, from each item's bibliotekanauki.pl metadata
11
  - **Added:** 2026-06-27
12
 
@@ -20,10 +20,16 @@ items are kept; all-rights-reserved and unknown items are gated out. Recovery yi
20
  |---|---:|
21
  | CC BY 4.0 | 28,335 |
22
  | CC BY-SA 4.0 | 13,733 |
23
- | Public Domain | 3 |
24
 
25
  The per-document license is carried in the parquet `license` column.
26
 
 
 
 
 
 
 
 
27
  ## Attribution
28
  Per-document attribution (author · year · title · publisher) was re-fetched 1:1 from
29
  bibliotekanauki.pl (43,576 / 43,576 ok) and is carried in the parquet `attribution` column,
@@ -37,7 +43,7 @@ attribution recovered per document and preserved.
37
  ## Statistics
38
  | documents | characters | tokens (tiktoken proxy) |
39
  |---:|---:|---:|
40
- | 42,071 | 1,748,333,935 | 673,488,831 |
41
 
42
  ## Filters applied (build_dynaword.py)
43
  Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
@@ -45,7 +51,8 @@ Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
45
  - drop non-Polish (diacritic ratio): **925**
46
  - exact cross-source dedup (sha1): **180**
47
  - OCR alpha-ratio < 0.70 (OCR source): **400**
48
- - read 43,576 → kept 42,071
 
49
 
50
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
51
  Llama-3 count is computed at release.
 
6
  - **Source (upstream):** https://bibliotekanauki.pl (operated by ICM, University of Warsaw — Centrum Otwartej Nauki)
7
  - **Domain:** academic (scientific articles, books, chapters)
8
  - **Language:** Polish (pl)
9
+ - **License:** per-document — CC BY 4.0 28,335 · CC BY-SA 4.0 13,733
10
  - **Created (range):** per-document publication year, from each item's bibliotekanauki.pl metadata
11
  - **Added:** 2026-06-27
12
 
 
20
  |---|---:|
21
  | CC BY 4.0 | 28,335 |
22
  | CC BY-SA 4.0 | 13,733 |
 
23
 
24
  The per-document license is carried in the parquet `license` column.
25
 
26
+ Three items labelled "Domena publiczna" were dropped for v0.2.6 (`src/clean_biblioteka_nauki.py`,
27
+ polish-dynaword-v2#52): `books_2142716`, `books_2147851`, `articles_2097363` (376,155 tokens).
28
+ Biblioteka Nauki gives them API licence id 22, the CC Public Domain Mark 1.0, which is a label, not a
29
+ waiver or a licence. They are original works first published 2019-2022, so the Polish life+70 term has
30
+ not run out, and `books_2147851` itself prints "Copyright by Jerzy Zając 2019". Only CC BY, CC BY-SA
31
+ and CC0 values are kept; any other value fails the script.
32
+
33
  ## Attribution
34
  Per-document attribution (author · year · title · publisher) was re-fetched 1:1 from
35
  bibliotekanauki.pl (43,576 / 43,576 ok) and is carried in the parquet `attribution` column,
 
43
  ## Statistics
44
  | documents | characters | tokens (tiktoken proxy) |
45
  |---:|---:|---:|
46
+ | 42,068 | 1,747,387,478 | 673,112,676 |
47
 
48
  ## Filters applied (build_dynaword.py)
49
  Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
 
51
  - drop non-Polish (diacritic ratio): **925**
52
  - exact cross-source dedup (sha1): **180**
53
  - OCR alpha-ratio < 0.70 (OCR source): **400**
54
+ - licence not an established grant, CC Public Domain Mark (`src/clean_biblioteka_nauki.py`): **3**
55
+ - read 43,576 → kept 42,068
56
 
57
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
58
  Llama-3 count is computed at release.
data/biblioteka_nauki/biblioteka_nauki.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26
3
- size 1076638904
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b57b8eec198c9899198a73cea1af372df09b43783a49474a856ccbf83c97da4
3
+ size 1075953966
data/biblioteka_nauki/biblioteka_nauki.stats.json CHANGED
@@ -1,12 +1,18 @@
1
  {
2
  "read": 43576,
3
- "kept": 42071,
4
  "drop_short": 0,
5
  "drop_lang": 925,
6
  "drop_dup": 180,
7
  "drop_ocr": 400,
8
- "chars": 1748333935,
9
- "tokens": 673488831,
10
  "secs": 484.1,
11
- "license": "CC-BY-4.0 / CC-BY-SA-4.0"
 
 
 
 
 
 
12
  }
 
1
  {
2
  "read": 43576,
3
+ "kept": 42068,
4
  "drop_short": 0,
5
  "drop_lang": 925,
6
  "drop_dup": 180,
7
  "drop_ocr": 400,
8
+ "chars": 1747387478,
9
+ "tokens": 673112676,
10
  "secs": 484.1,
11
+ "license": "CC-BY-4.0 / CC-BY-SA-4.0",
12
+ "drop_rights": 3,
13
+ "licenses": {
14
+ "cc-by": 28335,
15
+ "cc-by-sa": 13733
16
+ },
17
+ "input_sha256": "cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26"
18
  }
data/biblioteka_nauki/recover_attribution.py CHANGED
@@ -1,5 +1,5 @@
1
  #!/usr/bin/env python3
2
- """Targeted attribution pass for the CLEAN (CC-BY/CC-BY-SA/PD) Biblioteka Nauki ids ONLY.
3
  The first recovery pass stored the license correctly but parsed the wrong attribution fields.
4
  CC-BY/CC-BY-SA legally REQUIRE attribution, so re-fetch just the ~43.6k clean ids and extract:
5
  authors = contributors[role=AUTHOR] firstName+lastName ; year = dates[PUBLISHED].date.year ;
@@ -16,7 +16,10 @@ HERE = os.path.dirname(os.path.abspath(__file__))
16
  LIC = os.path.join(HERE, "licenses.jsonl")
17
  OUT = os.path.join(HERE, "attribution.jsonl")
18
  PROG = os.path.join(HERE, "attribution_progress.txt")
19
- CLEAN = {"cc-by", "cc-by-sa", "cc0", "public-domain"}
 
 
 
20
  WORKERS = 8
21
  UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
22
  "(KHTML, like Gecko) Chrome/124 Safari/537.36")
 
1
  #!/usr/bin/env python3
2
+ """Targeted attribution pass for the CLEAN (CC-BY/CC-BY-SA/CC0) Biblioteka Nauki ids ONLY.
3
  The first recovery pass stored the license correctly but parsed the wrong attribution fields.
4
  CC-BY/CC-BY-SA legally REQUIRE attribution, so re-fetch just the ~43.6k clean ids and extract:
5
  authors = contributors[role=AUTHOR] firstName+lastName ; year = dates[PUBLISHED].date.year ;
 
16
  LIC = os.path.join(HERE, "licenses.jsonl")
17
  OUT = os.path.join(HERE, "attribution.jsonl")
18
  PROG = os.path.join(HERE, "attribution_progress.txt")
19
+ # The v0.2.4 run also kept "public-domain": the CC Public Domain Mark, a label rather than a grant
20
+ # (polish-dynaword-v2#52). src/clean_biblioteka_nauki.py drops it from the shipped Parquet; its KEEP
21
+ # set must equal this one.
22
+ CLEAN = {"cc-by", "cc-by-sa", "cc0"}
23
  WORKERS = 8
24
  UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
25
  "(KHTML, like Gecko) Chrome/124 Safari/537.36")
data/govpl/govpl.attribution.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff137d2042ff32198ec7eb28347631dbf21735ab27afc2d823f8c27d0904aa33
3
+ size 26318408
data/govpl/govpl.md CHANGED
@@ -8,34 +8,46 @@ gov.pl — Polish government press releases
8
  - **Language:** Polish (pl)
9
  - **License:** `CC-BY-SA-4.0`
10
  - **Created (range):** 2005-09-26, 2026-07-19
11
- - **Added:** 2026-07-19
12
 
13
  ## Licensing — traceable basis
14
- All textual content on gov.pl is published under CC-BY-SA 4.0 (site footer: "Treści tekstowe publikowane w serwisie … są udostępniane na licencji CC BY-SA 4.0"). Authored and hosted by the Polish government, which holds the right to license it — same open family as Polish Wikipedia.
15
 
16
  ## Provenance
17
- Ministry/agency press releases fetched directly from gov.pl (editor-content per article, HTML stripped) by src/fetch_govpl.py. Subsites + their non-uniform news-section paths are enumerated by src/discover_govpl.py into the committed manifest src/govpl_subsites.json (gov.pl has no sitemap/API). Each record's meta.url resolves on gov.pl.
 
 
 
 
 
 
 
18
 
19
  ## Statistics
20
  | documents | characters | tokens (tiktoken proxy) |
21
  |---:|---:|---:|
22
- | 88,190 | 218,099,000 | 80,666,129 |
23
-
24
 
25
  ## Per-document license metadata
26
  | license | documents |
27
  |---|---:|
28
- | `CC-BY-SA-4.0` | 88,190 |
29
 
30
  Author metadata present for **0** documents. Empty values mean the upstream record did not expose a machine-readable author field.
31
 
32
- ## Filters applied (build_dynaword.py)
33
- Minimal, per Dynaword guidelines (heavy filtering left to downstream use):
 
 
 
34
  - drop documents < 200 chars: **0**
35
  - drop non-Polish (diacritic ratio): **24**
36
  - exact cross-source dedup (sha1): **1,926**
37
- - OCR alpha-ratio < 0.70 (OCR sources only): **0**
38
  - read 90,140 → kept 88,190
39
 
 
 
 
 
40
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
41
  Llama-3 count is computed at release.
 
8
  - **Language:** Polish (pl)
9
  - **License:** `CC-BY-SA-4.0`
10
  - **Created (range):** 2005-09-26, 2026-07-19
11
+ - **Added:** 2026-07-19; PAP reprints removed 2026-10-06
12
 
13
  ## Licensing — traceable basis
14
+ gov.pl publishes its text under CC BY-SA 4.0 (site footer and https://www.gov.pl/web/gov/prawa-autorskie: "Treści tekstowe publikowane w serwisie … są udostępniane na licencji CC BY-SA 4.0"). The same page excludes works whose copyright belongs to third parties; using those needs the owners' consent. Articles crediting PAP are therefore dropped (legal note).
15
 
16
  ## Provenance
17
+ Ministry/agency press releases fetched directly from gov.pl (editor-content per article, HTML stripped) by src/fetch_govpl.py. Subsites + their non-uniform news-section paths are enumerated by src/discover_govpl.py into the committed manifest src/govpl_subsites.json (gov.pl has no sitemap/API). v0.2.6 removes PAP reprints from the v0.2.5 Parquet with src/clean_govpl.py, which also writes govpl.attribution.jsonl: each row's gov.pl URL, subsite, title and date.
18
+
19
+ ## Attribution
20
+ CC BY-SA 4.0 requires credit and a link to the source. `govpl.attribution.jsonl` has one
21
+ line per row, in Parquet order: `id`, `url` (the gov.pl article), `subsite` (the publishing
22
+ ministry or agency), `title`, `date` (as listed on gov.pl) and `license`. Rows were matched
23
+ to the 2026-07-19 crawl on SHA-1 of the stripped text; for 1,189 rows the same text was
24
+ fetched from more than one URL, and the first in fetch order is given.
25
 
26
  ## Statistics
27
  | documents | characters | tokens (tiktoken proxy) |
28
  |---:|---:|---:|
29
+ | 88,002 | 217,515,240 | 80,445,758 |
 
30
 
31
  ## Per-document license metadata
32
  | license | documents |
33
  |---|---:|
34
+ | `CC-BY-SA-4.0` | 88,002 |
35
 
36
  Author metadata present for **0** documents. Empty values mean the upstream record did not expose a machine-readable author field.
37
 
38
+ ## Legal scope note
39
+ gov.pl's copyright page carves out "utwory, co do których prawa autorskie przysługują osobom trzecim" from its CC BY-SA 4.0 grant. Articles crediting PAP (Polish Press Agency) as their source are such works, so 188 are dropped (rule fetch_govpl.pap_rule, applied by src/clean_govpl.py): a "Źródło:" line naming PAP (163), "Na podst. … PAP" (22), a "(PAP)" sign-off line (2) and one PAP interview transcript (1). PAP photo credits and articles that only quote or mention PAP stay. Other third-party text is not screened: 710 kept articles carry a "Źródło:" line naming some other source; they were not reviewed.
40
+
41
+ ## Filters applied
42
+ `build_dynaword.py` (v0.2.2), minimal per Dynaword guidelines:
43
  - drop documents < 200 chars: **0**
44
  - drop non-Polish (diacritic ratio): **24**
45
  - exact cross-source dedup (sha1): **1,926**
 
46
  - read 90,140 → kept 88,190
47
 
48
+ `src/clean_govpl.py` (v0.2.6), third-party carve-out:
49
+ - drop PAP reprints: **188** (`Źródło:` line 163, `Na podst.` 22, `(PAP)` sign-off 2, interview 1)
50
+ - read 88,190 → kept 88,002
51
+
52
  Token counts are a fast tiktoken (cl100k) proxy (~1% off Llama-3); the canonical
53
  Llama-3 count is computed at release.
data/govpl/govpl.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9c0310fcdf45804e6547bd197cba55f58f12df618cd3d8b92b8e9077a3720b9f
3
- size 82940575
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e97d5b1ec04aebadaddd9ecb9fc6835324885606f59d4e8569f5516528f839b
3
+ size 82308595
data/govpl/govpl.stats.json CHANGED
@@ -1,16 +1,25 @@
1
  {
2
  "read": 90140,
3
- "kept": 88190,
4
  "drop_short": 0,
5
  "drop_lang": 24,
6
  "drop_dup": 1926,
7
  "drop_ocr": 0,
8
- "chars": 218099000,
9
- "tokens": 80666129,
 
 
 
 
 
 
 
 
10
  "licenses": {
11
- "CC-BY-SA-4.0": 88190
12
  },
13
  "authors_with_value": 0,
14
- "secs": 2.9,
15
- "license": "CC-BY-SA-4.0"
16
- }
 
 
 
1
  {
2
  "read": 90140,
 
3
  "drop_short": 0,
4
  "drop_lang": 24,
5
  "drop_dup": 1926,
6
  "drop_ocr": 0,
7
+ "drop_pap": 188,
8
+ "drop_pap_by_rule": {
9
+ "source_line": 163,
10
+ "sign_off": 2,
11
+ "based_on": 22,
12
+ "interview": 1
13
+ },
14
+ "kept": 88002,
15
+ "chars": 217515240,
16
+ "tokens": 80445758,
17
  "licenses": {
18
+ "CC-BY-SA-4.0": 88002
19
  },
20
  "authors_with_value": 0,
21
+ "license": "CC-BY-SA-4.0",
22
+ "input_rows": 88190,
23
+ "input_sha256": "9c0310fcdf45804e6547bd197cba55f58f12df618cd3d8b92b8e9077a3720b9f",
24
+ "fetched_sha256": "368259d0ea8522eced71b426ae238556d5330a410aa994bdcbdc7427478d783a"
25
+ }
src/clean_biblioteka_nauki.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Drop Biblioteka Nauki rows whose licence is not an established grant.
3
+
4
+ Kept: `cc-by`, `cc-by-sa` and `cc0` (none in v0.2.5), the per-item Creative Commons licence read from
5
+ bibliotekanauki.pl/api/{type}/{id} (`license.iconId`) by data/biblioteka_nauki/recover_licenses.py.
6
+ Dropped: `public-domain`. The platform shows it for items tagged with the CC Public Domain Mark 1.0
7
+ (API licence id 22, https://creativecommons.org/publicdomain/mark/1.0/). The Mark is a label, not
8
+ a waiver or a licence, and the 3 tagged items are original works first published 2019-2022, so
9
+ the Polish life+70 term cannot have run out (polish-dynaword-v2#52,
10
+ artifacts/rights_audit_2026-10/reports/academic.md). Any other licence value fails the run.
11
+
12
+ The v0.2.4 assembly script (build_parquet.py) was never committed, so this filters the shipped
13
+ v0.2.5 Parquet, pinned by SHA-256, and updates the stats file in place. Rerun:
14
+ git checkout v0.2.5 -- data/biblioteka_nauki/biblioteka_nauki.parquet
15
+ python3 src/clean_biblioteka_nauki.py
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import hashlib
21
+ import json
22
+ import os
23
+ from collections import Counter
24
+ from pathlib import Path
25
+
26
+ import pyarrow as pa
27
+ import pyarrow.compute as pc
28
+ import pyarrow.parquet as pq
29
+
30
+ SOURCE = "biblioteka_nauki"
31
+ DATA = Path(__file__).resolve().parents[1] / "data" / SOURCE
32
+ INPUT_SHA256 = "cc93cdd5ca3e6576a1da0aa294df1308e879b8516ac30911289e430c69a07b26" # v0.2.5
33
+ KEEP = {"cc-by", "cc-by-sa", "cc0"} # = CLEAN in data/biblioteka_nauki/recover_attribution.py
34
+ DROP = {"public-domain"} # CC Public Domain Mark: a label, not a grant (see docstring)
35
+
36
+
37
+ def filter_table(table: pa.Table) -> pa.Table:
38
+ """Rows whose `license` is in KEEP. Fails on any value in neither KEEP nor DROP."""
39
+ if unknown := set(table.column("license").unique().to_pylist()) - KEEP - DROP:
40
+ raise SystemExit(f"unexpected license values: {sorted(unknown, key=str)}")
41
+ return table.filter(pc.is_in(table.column("license"), pa.array(sorted(KEEP))))
42
+
43
+
44
+ def build(input_path: Path, out_dir: Path) -> dict:
45
+ with input_path.open("rb") as stream:
46
+ if hashlib.file_digest(stream, "sha256").hexdigest() != INPUT_SHA256:
47
+ raise SystemExit(f"{input_path} is not the v0.2.5 Parquet; restore it with "
48
+ f"`git checkout v0.2.5 -- data/{SOURCE}/{SOURCE}.parquet`")
49
+ table = pq.read_table(input_path)
50
+ kept = filter_table(table)
51
+ dropped = sorted(set(table.column("id").to_pylist()) - set(kept.column("id").to_pylist()))
52
+
53
+ stats_path = out_dir / f"{SOURCE}.stats.json"
54
+ stats = json.loads(stats_path.read_text(encoding="utf-8")) # keeps build_dynaword's read/drop_* counts
55
+ stats.update(
56
+ kept=kept.num_rows,
57
+ drop_rights=table.num_rows - kept.num_rows,
58
+ chars=pc.sum(pc.utf8_length(kept.column("text"))).as_py(),
59
+ tokens=pc.sum(kept.column("token_count")).as_py(),
60
+ licenses=dict(sorted(Counter(kept.column("license").to_pylist()).items())),
61
+ input_sha256=INPUT_SHA256,
62
+ )
63
+ parquet_tmp = out_dir / f"{SOURCE}.parquet.tmp"
64
+ stats_tmp = out_dir / f"{SOURCE}.stats.json.tmp"
65
+ pq.write_table(kept, parquet_tmp)
66
+ stats_tmp.write_text(json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
67
+ os.replace(parquet_tmp, out_dir / f"{SOURCE}.parquet")
68
+ os.replace(stats_tmp, stats_path)
69
+ return {**stats, "dropped_ids": dropped}
70
+
71
+
72
+ def main() -> None:
73
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
74
+ parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
75
+ parser.add_argument("--out", type=Path, default=DATA)
76
+ args = parser.parse_args()
77
+ print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False))
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
src/clean_govpl.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Drop PAP reprints from `govpl` and write a per-row URL sidecar.
3
+
4
+ gov.pl's copyright page (https://www.gov.pl/web/gov/prawa-autorskie) licenses the
5
+ site's text under CC BY-SA 4.0 but excludes works whose copyright belongs to third
6
+ parties. Articles that credit PAP (Polish Press Agency) as their source are such
7
+ works (slayerlabs/polish-dynaword-v2#51). `fetch_govpl.pap_rule` names them; this
8
+ script removes them from the released Parquet, so ids and the other rows stay as they
9
+ are (a rebuild through build_dynaword.py would renumber ids).
10
+
11
+ `govpl.attribution.jsonl` gives each kept row the gov.pl URL, subsite, title and date
12
+ of the fetched article, matched on build_dynaword's dedup key (SHA-1 of the stripped
13
+ text) in the fetch output `govpl.jsonl.zst`. Where the same text was fetched from
14
+ several URLs, the first one in fetch order is used.
15
+
16
+ Both inputs are pinned by SHA-256. Restore the Parquet before a rerun:
17
+ git checkout v0.2.5 -- data/govpl/govpl.parquet
18
+ python3 src/clean_govpl.py --fetched ~/speakleash/govpl.jsonl.zst
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import io
25
+ import json
26
+ import os
27
+ import sys
28
+ from collections import Counter
29
+ from pathlib import Path
30
+
31
+ import pyarrow.parquet as pq
32
+ import zstandard
33
+
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+ from fetch_govpl import KEY as SOURCE, pap_rule # one rule for fetch and release
36
+
37
+ ROOT = Path(__file__).resolve().parents[1]
38
+ DATA = ROOT / "data" / SOURCE
39
+ INPUT_SHA256 = "9c0310fcdf45804e6547bd197cba55f58f12df618cd3d8b92b8e9077a3720b9f" # v0.2.5
40
+ FETCHED_SHA256 = "368259d0ea8522eced71b426ae238556d5330a410aa994bdcbdc7427478d783a" # 2026-07-19 crawl
41
+ BUILD_STATS = { # build_dynaword.py counts for the v0.2.5 Parquet, kept for the datasheet
42
+ "read": 90140, "drop_short": 0, "drop_lang": 24, "drop_dup": 1926, "drop_ocr": 0,
43
+ }
44
+
45
+
46
+ def text_key(text: str) -> bytes:
47
+ """build_dynaword's dedup key."""
48
+ return hashlib.sha1(text.strip().encode("utf-8")).digest()
49
+
50
+
51
+ def fetched_meta(path: Path) -> dict[bytes, dict]:
52
+ """text_key -> meta of the first fetched record with that text."""
53
+ meta: dict[bytes, dict] = {}
54
+ with path.open("rb") as compressed:
55
+ lines = io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(compressed), encoding="utf-8")
56
+ for line in lines:
57
+ if line.strip():
58
+ record = json.loads(line)
59
+ meta.setdefault(text_key(record["text"]), record["meta"])
60
+ return meta
61
+
62
+
63
+ def check_pin(path: Path, expected: str, restore: str) -> None:
64
+ with path.open("rb") as stream:
65
+ actual = hashlib.file_digest(stream, "sha256").hexdigest()
66
+ if actual != expected:
67
+ raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}")
68
+
69
+
70
+ def build(input_path: Path, fetched_path: Path, out_dir: Path) -> dict:
71
+ check_pin(input_path, INPUT_SHA256, "restore it with `git checkout v0.2.5 -- data/govpl/govpl.parquet`")
72
+ check_pin(fetched_path, FETCHED_SHA256, "it is not the 2026-07-19 gov.pl crawl")
73
+ table = pq.read_table(input_path)
74
+ meta = fetched_meta(fetched_path)
75
+
76
+ kept, attribution, dropped = [], [], Counter()
77
+ for row in table.to_pylist():
78
+ if rule := pap_rule(row["text"]):
79
+ dropped[rule] += 1
80
+ continue
81
+ found = meta.get(text_key(row["text"]))
82
+ if found is None:
83
+ raise SystemExit(f"{row['id']}: text not found in {fetched_path}")
84
+ kept.append(row)
85
+ attribution.append({
86
+ "id": row["id"], "url": found["url"], "subsite": found["subsite"],
87
+ "title": found["title"], "date": found["date"], "license": row["license"],
88
+ })
89
+
90
+ stats = {
91
+ **BUILD_STATS, "drop_pap": sum(dropped.values()), "drop_pap_by_rule": dict(dropped),
92
+ "kept": len(kept),
93
+ "chars": sum(len(r["text"]) for r in kept), "tokens": sum(r["token_count"] for r in kept),
94
+ "licenses": dict(Counter(r["license"] for r in kept)),
95
+ "authors_with_value": sum(bool(r["author"]) for r in kept), "license": "CC-BY-SA-4.0",
96
+ "input_rows": table.num_rows, "input_sha256": INPUT_SHA256, "fetched_sha256": FETCHED_SHA256,
97
+ }
98
+ build_drops = sum(v for k, v in BUILD_STATS.items() if k.startswith("drop_"))
99
+ if stats["read"] - build_drops != table.num_rows:
100
+ raise SystemExit("BUILD_STATS does not add up to the input row count")
101
+ staged = {
102
+ out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table(
103
+ table.from_pylist(kept, schema=table.schema), p, compression="zstd"),
104
+ out_dir / f"{SOURCE}.attribution.jsonl.tmp": lambda p: p.write_text(
105
+ "".join(json.dumps(a, ensure_ascii=False) + "\n" for a in attribution), encoding="utf-8"),
106
+ out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text(
107
+ json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"),
108
+ }
109
+ for path, write in staged.items():
110
+ write(path)
111
+ for path in staged:
112
+ os.replace(path, path.with_suffix(""))
113
+ return stats
114
+
115
+
116
+ def main() -> None:
117
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
118
+ parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
119
+ parser.add_argument("--fetched", type=Path, required=True, help="govpl.jsonl.zst from fetch_govpl.py")
120
+ parser.add_argument("--out", type=Path, default=DATA)
121
+ args = parser.parse_args()
122
+ print(json.dumps(build(args.input, args.fetched, args.out), indent=2, ensure_ascii=False))
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()
src/fetch_govpl.py CHANGED
@@ -1,10 +1,11 @@
1
  #!/usr/bin/env python3
2
  """Fetch gov.pl ministry/agency press releases into a SpeakLeash-style
3
  .jsonl.zst, so build_dynaword.py consumes it unchanged (native source, not via
4
- SpeakLeash). All textual content on gov.pl is published under CC-BY-SA 4.0 (site
5
- footer: "Treści tekstowe publikowane w serwisie … CC BY-SA 4.0"), authored and
6
- hosted by the Polish government — so the redistributor genuinely holds the right
7
- to license it.
 
8
 
9
  Enumeration is driven by the committed manifest src/govpl_subsites.json (built
10
  by discover_govpl.py): {slug, news_path, pages} per subsite. This keeps the
@@ -30,6 +31,35 @@ from html_text import html_to_text
30
  KEY = "govpl" # build_dynaword reads <KEY>.jsonl.zst
31
  MIN_CHARS = 200 # same floor as build_dynaword; skip stubs early
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # Body ends where the editor-content region gives way to gallery/attachments/tags.
34
  _END_MARKER = re.compile(
35
  r'<[^>]+class="[^"]*(?:attachments|art-tags|tags|social|share|gallery|files)[^"]*"'
@@ -54,12 +84,15 @@ def article_body(html: str) -> str:
54
 
55
 
56
  def normalize(art: dict, html: str, slug: str) -> dict | None:
57
- """Listing entry {url,title,date} + article HTML -> record, or None if thin."""
 
58
  body = article_body(html)
59
  if len(body) < MIN_CHARS:
60
  return None
61
  title = art.get("title") or ""
62
  text = f"{title}\n\n{body}" if title else body
 
 
63
  return {
64
  "text": text,
65
  "meta": {
 
1
  #!/usr/bin/env python3
2
  """Fetch gov.pl ministry/agency press releases into a SpeakLeash-style
3
  .jsonl.zst, so build_dynaword.py consumes it unchanged (native source, not via
4
+ SpeakLeash). gov.pl publishes its text under CC-BY-SA 4.0 (site footer: "Treści
5
+ tekstowe publikowane w serwisie … CC BY-SA 4.0"), but its copyright page excludes
6
+ works whose copyright belongs to third parties. Articles that credit PAP (Polish
7
+ Press Agency) as their source are such works, so normalize() drops them
8
+ (pap_rule below; the same rule filters the released Parquet in clean_govpl.py).
9
 
10
  Enumeration is driven by the committed manifest src/govpl_subsites.json (built
11
  by discover_govpl.py): {slug, news_path, pages} per subsite. This keeps the
 
31
  KEY = "govpl" # build_dynaword reads <KEY>.jsonl.zst
32
  MIN_CHARS = 200 # same floor as build_dynaword; skip stubs early
33
 
34
+ # PAP attribution forms seen in the fetched articles (hand-checked, issue
35
+ # slayerlabs/polish-dynaword-v2#51). A photo credit ("fot. PAP") is not one of them.
36
+ _PAP = r"(?:\bPAP\b|\bPolsk\w*\s+Agencj\w*\s+Prasow\w*)"
37
+ PAP_RULES = {
38
+ # "Źródło: /PAP, MKiDN/", "Źródła: PAP, Culture.pl", "Źródło informacji: PAP/MKIDN",
39
+ # "Żródło: Polska Agencja Prasowa". Covers the issue's rule
40
+ # (?i)\bźr[óo]d[łl]o\s*:\s*/?[^\n]{0,60}\bPAP\b and its misspellings.
41
+ "source_line": re.compile(
42
+ r"(?i)\b[źżz]r[óo]d[łl][oa](?:\s+informacji)?\s*:?\s*/?[^\n]{0,60}" + _PAP),
43
+ # "Na podst. PAP", "Na podst. PKP S.A. i PAP" (uw-podlaski)
44
+ "based_on": re.compile(r"(?i)\bna\s+podst\.[^\n]{0,60}\bPAP\b"),
45
+ # a line holding only "(PAP)" or "/PAP/", the agency's own sign-off
46
+ "sign_off": re.compile(r"(?m)^[ \t]*[/(*]?[ \t]*PAP[ \t]*[)/]?\.?[ \t\r]*$"),
47
+ }
48
+ # A PAP interview transcript: the agency's questions start lines with "PAP:".
49
+ # ponytail: three such lines; one KRRiT report quoting two PAP questions stays in.
50
+ _PAP_QUESTION = re.compile(r"(?m)^PAP\s*:")
51
+ PAP_INTERVIEW_MIN_QUESTIONS = 3
52
+
53
+
54
+ def pap_rule(text: str) -> str | None:
55
+ """Name of the first PAP rule that matches `text`, or None."""
56
+ for name, rx in PAP_RULES.items():
57
+ if rx.search(text):
58
+ return name
59
+ if len(_PAP_QUESTION.findall(text)) >= PAP_INTERVIEW_MIN_QUESTIONS:
60
+ return "interview"
61
+ return None
62
+
63
  # Body ends where the editor-content region gives way to gallery/attachments/tags.
64
  _END_MARKER = re.compile(
65
  r'<[^>]+class="[^"]*(?:attachments|art-tags|tags|social|share|gallery|files)[^"]*"'
 
84
 
85
 
86
  def normalize(art: dict, html: str, slug: str) -> dict | None:
87
+ """Listing entry {url,title,date} + article HTML -> record, or None if thin
88
+ or a PAP reprint."""
89
  body = article_body(html)
90
  if len(body) < MIN_CHARS:
91
  return None
92
  title = art.get("title") or ""
93
  text = f"{title}\n\n{body}" if title else body
94
+ if pap_rule(text):
95
+ return None
96
  return {
97
  "text": text,
98
  "meta": {
src/sources.py CHANGED
@@ -471,22 +471,38 @@ SOURCES = {
471
  "pretty": "gov.pl — Polish government press releases",
472
  "license": "CC-BY-SA-4.0",
473
  "license_spdx": "CC-BY-SA-4.0",
474
- "traceable": "All textual content on gov.pl is published under CC-BY-SA "
475
- "4.0 (site footer: \"Treści tekstowe publikowane w serwisie "
476
- "… są udostępniane na licencji CC BY-SA 4.0\"). Authored and "
477
- "hosted by the Polish government, which holds the right to "
478
- "license it — same open family as Polish Wikipedia.",
 
479
  "upstream": "https://www.gov.pl/",
480
  "provenance": "Ministry/agency press releases fetched directly from gov.pl "
481
  "(editor-content per article, HTML stripped) by "
482
  "src/fetch_govpl.py. Subsites + their non-uniform news-section "
483
  "paths are enumerated by src/discover_govpl.py into the "
484
  "committed manifest src/govpl_subsites.json (gov.pl has no "
485
- "sitemap/API). Each record's meta.url resolves on gov.pl.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  "domain": "government",
487
  # actual min/max of article dates in the fetched corpus (90,124 dated).
488
  "created": "2005-09-26, 2026-07-19",
489
  "is_ocr": False,
 
490
  },
491
  "samorzad_gov_pl": {
492
  "added": "2026-08-14",
 
471
  "pretty": "gov.pl — Polish government press releases",
472
  "license": "CC-BY-SA-4.0",
473
  "license_spdx": "CC-BY-SA-4.0",
474
+ "traceable": "gov.pl publishes its text under CC BY-SA 4.0 (site footer and "
475
+ "https://www.gov.pl/web/gov/prawa-autorskie: \"Treści tekstowe "
476
+ "publikowane w serwisie … są udostępniane na licencji CC BY-SA "
477
+ "4.0\"). The same page excludes works whose copyright belongs to "
478
+ "third parties; using those needs the owners' consent. "
479
+ "Articles crediting PAP are therefore dropped (legal note).",
480
  "upstream": "https://www.gov.pl/",
481
  "provenance": "Ministry/agency press releases fetched directly from gov.pl "
482
  "(editor-content per article, HTML stripped) by "
483
  "src/fetch_govpl.py. Subsites + their non-uniform news-section "
484
  "paths are enumerated by src/discover_govpl.py into the "
485
  "committed manifest src/govpl_subsites.json (gov.pl has no "
486
+ "sitemap/API). v0.2.6 removes PAP reprints from the v0.2.5 "
487
+ "Parquet with src/clean_govpl.py, which also writes "
488
+ "govpl.attribution.jsonl: each row's gov.pl URL, subsite, "
489
+ "title and date.",
490
+ "legal_note": "gov.pl's copyright page carves out \"utwory, co do których "
491
+ "prawa autorskie przysługują osobom trzecim\" from its CC BY-SA "
492
+ "4.0 grant. Articles crediting PAP (Polish Press Agency) as their "
493
+ "source are such works, so 188 are dropped (rule "
494
+ "fetch_govpl.pap_rule, applied by src/clean_govpl.py): a "
495
+ "\"Źródło:\" line naming PAP (163), \"Na podst. … PAP\" (22), a "
496
+ "\"(PAP)\" sign-off line (2) and one PAP interview transcript (1). "
497
+ "PAP photo credits and articles that only quote or mention PAP "
498
+ "stay. Other third-party text is not screened: 710 kept articles "
499
+ "carry a \"Źródło:\" line naming some other source; they were "
500
+ "not reviewed.",
501
  "domain": "government",
502
  # actual min/max of article dates in the fetched corpus (90,124 dated).
503
  "created": "2005-09-26, 2026-07-19",
504
  "is_ocr": False,
505
+ "custom_datasheet": True,
506
  },
507
  "samorzad_gov_pl": {
508
  "added": "2026-08-14",
src/test_biblioteka_nauki_contract.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract checks for biblioteka_nauki after the public-domain drop (src/clean_biblioteka_nauki.py)."""
2
+
3
+ import importlib.util
4
+ import json
5
+ import sys
6
+ from collections import Counter
7
+ from pathlib import Path
8
+
9
+ import pyarrow as pa
10
+ import pyarrow.compute as pc
11
+ import pyarrow.parquet as pq
12
+ import pytest
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+
16
+ from clean_biblioteka_nauki import DATA, KEEP, filter_table
17
+
18
+ PUBLIC_DOMAIN_MARK_IDS = {
19
+ "biblioteka_nauki_books_2142716",
20
+ "biblioteka_nauki_books_2147851",
21
+ "biblioteka_nauki_articles_2097363",
22
+ }
23
+
24
+
25
+ def test_shard_has_no_public_domain_rows_and_matches_stats():
26
+ stats = json.loads((DATA / "biblioteka_nauki.stats.json").read_text(encoding="utf-8"))
27
+ path = DATA / "biblioteka_nauki.parquet"
28
+ assert pq.read_schema(path).names == [
29
+ "id", "text", "source", "added", "created", "token_count", "license", "attribution"]
30
+ table = pq.read_table(path, columns=["id", "source", "token_count", "license", "attribution"])
31
+ ids = table.column("id").to_pylist()
32
+ licenses = Counter(table.column("license").to_pylist())
33
+
34
+ assert table.num_rows == stats["kept"] == 42_068
35
+ assert len(set(ids)) == len(ids)
36
+ assert not PUBLIC_DOMAIN_MARK_IDS & set(ids)
37
+ assert "public-domain" not in licenses
38
+ assert licenses == stats["licenses"] == {"cc-by": 28_335, "cc-by-sa": 13_733}
39
+ assert set(table.column("source").to_pylist()) == {"biblioteka_nauki"}
40
+ assert pc.sum(table.column("token_count")).as_py() == stats["tokens"]
41
+ assert pc.min(table.column("token_count")).as_py() > 0
42
+ assert all(a and a.strip() for a in table.column("attribution").to_pylist())
43
+ drops = ("drop_short", "drop_lang", "drop_dup", "drop_ocr", "drop_rights")
44
+ assert stats["read"] - sum(stats[k] for k in drops) == stats["kept"]
45
+ assert stats["drop_rights"] == 3
46
+
47
+
48
+ def test_datasheet_counts_match_stats():
49
+ stats = json.loads((DATA / "biblioteka_nauki.stats.json").read_text(encoding="utf-8"))
50
+ card = (DATA / "biblioteka_nauki.md").read_text(encoding="utf-8")
51
+ assert f"| {stats['kept']:,} | {stats['chars']:,} | {stats['tokens']:,} |" in card
52
+ for license, docs in stats["licenses"].items():
53
+ assert f"{docs:,}" in card, license
54
+ assert "| Public Domain |" not in card
55
+
56
+
57
+ def test_filter_drops_public_domain_and_fails_closed():
58
+ table = pa.table({"id": ["a", "b", "c", "d"], "license": ["cc-by", "public-domain", "cc-by-sa", "cc0"]})
59
+ assert filter_table(table).column("id").to_pylist() == ["a", "c", "d"]
60
+ for bad in ("cc-by-nc", "cc-by-nd", "all-rights-reserved", None):
61
+ with pytest.raises(SystemExit):
62
+ filter_table(pa.table({"license": ["cc-by", bad]}))
63
+
64
+
65
+ def test_upstream_gate_matches_filter():
66
+ spec = importlib.util.spec_from_file_location("recover_attribution", DATA / "recover_attribution.py")
67
+ module = importlib.util.module_from_spec(spec)
68
+ spec.loader.exec_module(module)
69
+ assert module.CLEAN == KEEP
src/test_govpl_contract.py CHANGED
@@ -1,12 +1,20 @@
1
  """TDD contract for the direct gov.pl (press releases) ingestion path."""
 
 
2
  import sys
3
  import unittest
4
  from pathlib import Path
5
 
 
 
6
  sys.path.insert(0, str(Path(__file__).resolve().parent))
7
 
8
  from discover_govpl import listing_articles, news_candidates, max_page
9
- from fetch_govpl import article_body, normalize, BASE
 
 
 
 
10
 
11
  LISTING = """
12
  <div class="art-prev">
@@ -79,6 +87,83 @@ class GovplContractTest(unittest.TestCase):
79
  self.assertEqual(max_page('<a href="?page=2">2</a><a href="?page=294">294</a>'), 294)
80
  self.assertEqual(max_page("<html>no pager</html>"), 1) # single-page listing
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  if __name__ == "__main__":
84
  unittest.main()
 
1
  """TDD contract for the direct gov.pl (press releases) ingestion path."""
2
+ import json
3
+ import re
4
  import sys
5
  import unittest
6
  from pathlib import Path
7
 
8
+ import pyarrow.parquet as pq
9
+
10
  sys.path.insert(0, str(Path(__file__).resolve().parent))
11
 
12
  from discover_govpl import listing_articles, news_candidates, max_page
13
+ from fetch_govpl import article_body, normalize, pap_rule, BASE
14
+
15
+ DATA = Path(__file__).resolve().parents[1] / "data" / "govpl"
16
+ ISSUE_51_RULE = re.compile(r"(?i)\bźr[óo]d[łl]o\s*:\s*/?[^\n]{0,60}\bPAP\b") # polish-dynaword-v2#51
17
+ RELEASED_ROWS = 88002 # 88,190 in v0.2.5 minus 188 PAP reprints
18
 
19
  LISTING = """
20
  <div class="art-prev">
 
87
  self.assertEqual(max_page('<a href="?page=2">2</a><a href="?page=294">294</a>'), 294)
88
  self.assertEqual(max_page("<html>no pager</html>"), 1) # single-page listing
89
 
90
+ def test_pap_reprints_are_named(self):
91
+ cases = {
92
+ "Tekst.\n\nŹródło: /PAP, MKiDN/\n\nZdjęcia (3)": "source_line",
93
+ "Tekst.\n\nŹródło: PAP": "source_line",
94
+ "Tekst. Źródło PAP, MKiDN": "source_line",
95
+ "Źródło informacji: PAP/MKIDN": "source_line",
96
+ "żródło: /PAP,MKiDN/": "source_line",
97
+ "Źródła: dzieje.pl, Mariusz Jarosiński (PAP), Muzeum Historii Polski": "source_line",
98
+ "Żródło: Polska Agencja Prasowa": "source_line",
99
+ "Tekst.\n\nNa podst. PKP S.A. i PAP\n\r\nZdjęcia (13)": "based_on",
100
+ "Tekst.\n\n(PAP)\n\n\r\nZdjęcia (1)": "sign_off",
101
+ "Wywiad\n\nPAP: Pytanie?\nOdpowiedź.\nPAP: Drugie?\nTak.\nPAP: Trzecie?\nNie.": "interview",
102
+ }
103
+ for text, rule in cases.items():
104
+ self.assertEqual(pap_rule(text), rule, text)
105
+
106
+ def test_pap_mentions_and_photo_credits_are_kept(self):
107
+ for text in (
108
+ "Minister na konferencji. Fot. PAP/Leszek Szymański",
109
+ "fot. PAP\n\nZdjęcia (2)",
110
+ "– powiedziała minister w rozmowie z PAP.",
111
+ "Wyniki ogłoszono w Centrum Prasowym PAP.",
112
+ "Akapit kończy się tak (PAP). Dalej tekst ministerstwa.",
113
+ "Źródło: MKiDN\n\nfot. PAP",
114
+ "Raport KRRiT\n\nPAP: Pytanie?\nOdpowiedź.\nPAP: Drugie?\nTak.",
115
+ ):
116
+ self.assertIsNone(pap_rule(text), text)
117
+
118
+ def test_normalize_drops_pap_reprint(self):
119
+ art = {"url": "/web/kultura/x", "title": "Nagłówek", "date": "14.07.2026"}
120
+ reprint = ARTICLE.replace("</p>", "</p><p>Źródło: /PAP, MKiDN/</p>", 1)
121
+ self.assertIsNotNone(normalize(art, ARTICLE, "kultura"))
122
+ self.assertIsNone(normalize(art, reprint, "kultura"))
123
+
124
+
125
+ class GovplReleaseContractTest(unittest.TestCase):
126
+ """The released files: PAP reprints gone, stats and URL sidecar match the Parquet."""
127
+
128
+ @classmethod
129
+ def setUpClass(cls):
130
+ cls.table = pq.read_table(DATA / "govpl.parquet")
131
+ cls.stats = json.loads((DATA / "govpl.stats.json").read_text(encoding="utf-8"))
132
+ with (DATA / "govpl.attribution.jsonl").open(encoding="utf-8") as stream:
133
+ cls.sidecar = [json.loads(line) for line in stream]
134
+
135
+ def test_no_pap_reprints(self):
136
+ texts = self.table.column("text").to_pylist()
137
+ self.assertEqual([t for t in texts if ISSUE_51_RULE.search(t)], [])
138
+ self.assertEqual([t for t in texts if pap_rule(t)], [])
139
+
140
+ def test_row_count_and_stats(self):
141
+ st = self.stats
142
+ self.assertEqual(self.table.num_rows, RELEASED_ROWS)
143
+ self.assertEqual(st["kept"], RELEASED_ROWS)
144
+ self.assertEqual(st["drop_pap"], sum(st["drop_pap_by_rule"].values()))
145
+ self.assertEqual(st["input_rows"] - st["drop_pap"], st["kept"])
146
+ drops = sum(v for k, v in st.items() if k.startswith("drop_") and isinstance(v, int))
147
+ self.assertEqual(st["read"] - drops, st["kept"])
148
+ self.assertEqual(st["tokens"], sum(self.table.column("token_count").to_pylist()))
149
+ self.assertEqual(st["chars"], sum(map(len, self.table.column("text").to_pylist())))
150
+ self.assertEqual(st["licenses"], {"CC-BY-SA-4.0": RELEASED_ROWS})
151
+ ids = self.table.column("id").to_pylist()
152
+ self.assertEqual(len(set(ids)), len(ids))
153
+
154
+ def test_datasheet_matches_stats(self):
155
+ st, md = self.stats, (DATA / "govpl.md").read_text(encoding="utf-8")
156
+ self.assertIn(f"| {st['kept']:,} | {st['chars']:,} | {st['tokens']:,} |", md)
157
+ self.assertIn(f"drop PAP reprints: **{st['drop_pap']:,}**", md)
158
+ self.assertIn(f"read {st['input_rows']:,} → kept {st['kept']:,}", md)
159
+
160
+ def test_sidecar_gives_every_row_a_govpl_url(self):
161
+ self.assertEqual([a["id"] for a in self.sidecar], self.table.column("id").to_pylist())
162
+ for a in self.sidecar:
163
+ self.assertEqual(set(a), {"id", "url", "subsite", "title", "date", "license"})
164
+ self.assertTrue(a["url"].startswith(BASE + "/web/" + a["subsite"] + "/"), a)
165
+ self.assertEqual(a["license"], "CC-BY-SA-4.0")
166
+
167
 
168
  if __name__ == "__main__":
169
  unittest.main()