edukacja_medialna_pl: drop 4 lessons with embedded third-party quotations (252 -> 248)

#74
by ppuzio - opened
artifacts/source_findings.md CHANGED
@@ -1758,3 +1758,43 @@ Licence read-only 2026-10-06: <https://nonsa.pl/wiki/Nonsensopedia:Prawa_autorsk
1758
 
1759
  **Lesson** — a tag name is not a content type. `<poem>` is used for jokes and logs as
1760
  well as verse, so measure what a rule drops before quoting its size.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1758
 
1759
  **Lesson** — a tag name is not a content type. `<poem>` is used for jokes and logs as
1760
  well as verse, so measure what a rule drops before quoting its size.
1761
+
1762
+ ## `edukacja_medialna_pl`: four lessons with embedded third-party quotations dropped
1763
+
1764
+ **Investigated:** 2026-10-06
1765
+ **Verdict:** 252 → 248 lessons stay CC BY-SA 3.0 (728,987 → 713,052 tokens; the Michera pair is 7,282
1766
+ tokens, the profile pair 8,653).
1767
+ `src/clean_edukacja_medialna_pl.py` filters the SHA-pinned PR #26 Parquet and sidecars. Tracks the
1768
+ 2026-10 rights audit line "optionally remove the 3 quote passages".
1769
+
1770
+ ### Verified
1771
+
1772
+ - Two lessons quote the film scholar Wojciech Michera by name, credited to a University of
1773
+ Warsaw course ("cytat z materiałów do kursu ..."): `montaz-materialu-filmowego` and
1774
+ `scenografia-charakteryzacja-kostiumy-i-aktorzy`, one passage each. Dropped whole.
1775
+ - Two lessons (`kim-jestem-w-internecie`, `wizerunek-w-sieci`) share an invented-profile
1776
+ exercise with six "Ulubione cytaty" lines, each credited to a named person (Marilyn Monroe,
1777
+ Winston Churchill and others). Dropped whole as a fail-closed guess (see below).
1778
+ - Kept on purpose: the attributed CC BY-SA Wikipedia excerpt (`ekonomiczne-aspekty-...`),
1779
+ the Constitution and ECHR article quotes (statutory text, Art. 4), lessons that only name
1780
+ films, books or point to a handout by URL (`uzaleznienia` links the Jakubik article, it does
1781
+ not embed it).
1782
+
1783
+ ### Not established
1784
+
1785
+ - The audit says "2-3 short quotes" and "3 quote passages". Only the two Michera passages are
1786
+ reproducible. No third third-party quotation was found by reading every lesson that contains
1787
+ "cytat", "źródło" or a quote followed by an attribution. The profile exercise is a guess at
1788
+ what the audit counted. To keep those two lessons, delete the two `PROFILES` entries from
1789
+ `DROP` and run `git checkout 5ec3e18 -- data/edukacja_medialna_pl` first (+8,653 tokens).
1790
+ - The raw XML is not in the checkout, so the filter works on the Parquet. The datasheet's
1791
+ "Reproduction" section still describes the original build.
1792
+
1793
+ ### Side effects
1794
+
1795
+ - `src/test_edukacja_medialna_contribution.py` pinned the contributed data files by SHA-256
1796
+ through `artifacts/edukacja_medialna_pl_ontology_manifest.json`. It now compares the manifest
1797
+ pins with the input pins in the clean script, so the manifest stays untouched.
1798
+
1799
+ **Lesson:** an audit count ("3 quotes") is a lead, not a list. Reproduce it from the data before
1800
+ writing the filter, and say which drops are confirmed.
data/edukacja_medialna_pl/NOTICE.md CHANGED
@@ -7,4 +7,4 @@ License statement at the origin: every lesson page ends with "Licencja: Creative
7
 
8
  Per-record text/scenario/expert creators, canonical URLs, source dates and rights evidence are preserved in `artifacts/attribution.jsonl`. Raw source XML and acquisition hashes are preserved in `artifacts/raw_xml.jsonl.gz`.
9
 
10
- Preparation: Piotr Styla with OpenAI Codex. Changes: extracted the authored `powiesc` lesson body from source XML; omitted external reading lists; normalized Unicode and whitespace; applied language, length, creator, license, limited PII-pattern and deduplication gates. No endorsement by Fundacja Nowoczesna Polska is implied.
 
7
 
8
  Per-record text/scenario/expert creators, canonical URLs, source dates and rights evidence are preserved in `artifacts/attribution.jsonl`. Raw source XML and acquisition hashes are preserved in `artifacts/raw_xml.jsonl.gz`.
9
 
10
+ Preparation: Piotr Styla with OpenAI Codex. Changes: extracted the authored `powiesc` lesson body from source XML; omitted external reading lists; normalized Unicode and whitespace; applied language, length, creator, license, limited PII-pattern and deduplication gates. Four lessons that embed quotations credited to named third parties are omitted. No endorsement by Fundacja Nowoczesna Polska is implied.
data/edukacja_medialna_pl/edukacja_medialna_pl.attribution.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:8522652f776bd59c115453331b4a5c771f01e6467fab2938798c3aad0065e55d
3
- size 347519
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4263644a00b2cb0b65ecbc2bedb5a6433ba8297b9b67acd838fedf6c013e7d9
3
+ size 341996
data/edukacja_medialna_pl/edukacja_medialna_pl.decisions.jsonl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:960bffd3e684a52a119633efbedc7d1ef0cd6d8c70bfbb16bb2c03c551da9962
3
- size 67322
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab37785368d6b417cea223c5728c122e7bb4fe312819927561559ad7a2935b19
3
+ size 67366
data/edukacja_medialna_pl/edukacja_medialna_pl.md CHANGED
@@ -16,8 +16,8 @@ configs:
16
  A text-only snapshot of Polish media-literacy lesson explanations and scenarios acquired directly from official lesson XML.
17
 
18
  - Discovered: 255 lesson URLs
19
- - Retained: 252 records
20
- - Tokens: 728,987 (`cl100k_base` proxy)
21
  - License: CC BY-SA 3.0 per retained record
22
  - Author coverage: 100.0%
23
 
@@ -49,7 +49,7 @@ See `NOTICE.md`, `artifacts/attribution.jsonl`, `artifacts/decisions.jsonl`, `ar
49
  - **Register**: prepared didactic Polish — formal written prose with classroom
50
  instructions, exercises and check questions; gender-inclusive paired forms
51
  ("uczestnicy i uczestniczki"); standard spelling. Human-authored, not OCR'd,
52
- not machine-translated; 62 credited authors across 252 records (roles
53
  `textbook`, `scenario`, `expert`, `methodologist`).
54
  - **Time span**: upstream publication dates 2012-11-09 – 2015-01-12 (per-record
55
  `created`). The material includes historically dated technology and legal
@@ -78,7 +78,13 @@ pinned raw XML, so the shard is reproducible:
78
  creator (3 dropped: `missing_creator`), body ≥ 300 chars (0 dropped), langid
79
  Polish (7-language set, confidence ≥ 0.99; 0 dropped), exact dedup on
80
  normalized text (0 dropped), near-dedup seeded MinHash 128 / LSH 0.8 with
81
- exact 5-word Jaccard ≥ 0.9 (0 dropped). 252 of 255 retained.
 
 
 
 
 
 
82
 
83
  Before/after excerpts of the extraction and normalization are in the PR
84
  description.
@@ -105,7 +111,7 @@ The records are CC BY-SA 3.0 works; the corpus is redistributed as CC BY-SA 4.0.
105
  What this adds: authored didactic prose — objectives, exercises, classroom
106
  procedure, glossary definitions — a school-teaching register the corpus does not
107
  otherwise draw from (its registers are encyclopedic, legal, parliamentary,
108
- journalistic and fiction). 728,987 tokens is a diversity addition, not a scale
109
  one.
110
 
111
  Bias and quality caveats: a single publisher (Fundacja Nowoczesna Polska) and 62
@@ -121,3 +127,18 @@ The source includes historically dated technology and legal guidance. Dates are
121
  ## Reproduction
122
 
123
  Install `src/requirements.txt`, decompress `artifacts/raw_xml.jsonl.gz` to a work directory as `raw_xml.jsonl`, and run the builder against the preserved inventory. Live acquisition creates a new source Version and must use a fresh work directory.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  A text-only snapshot of Polish media-literacy lesson explanations and scenarios acquired directly from official lesson XML.
17
 
18
  - Discovered: 255 lesson URLs
19
+ - Retained: 248 records
20
+ - Tokens: 713,052 (`cl100k_base` proxy)
21
  - License: CC BY-SA 3.0 per retained record
22
  - Author coverage: 100.0%
23
 
 
49
  - **Register**: prepared didactic Polish — formal written prose with classroom
50
  instructions, exercises and check questions; gender-inclusive paired forms
51
  ("uczestnicy i uczestniczki"); standard spelling. Human-authored, not OCR'd,
52
+ not machine-translated; 62 credited authors across 248 records (roles
53
  `textbook`, `scenario`, `expert`, `methodologist`).
54
  - **Time span**: upstream publication dates 2012-11-09 – 2015-01-12 (per-record
55
  `created`). The material includes historically dated technology and legal
 
78
  creator (3 dropped: `missing_creator`), body ≥ 300 chars (0 dropped), langid
79
  Polish (7-language set, confidence ≥ 0.99; 0 dropped), exact dedup on
80
  normalized text (0 dropped), near-dedup seeded MinHash 128 / LSH 0.8 with
81
+ exact 5-word Jaccard ≥ 0.9 (0 dropped). 252 of 255 passed these gates.
82
+ - **Third-party quotations** (rights audit 2026-10): 4 further lessons are dropped whole by
83
+ `src/clean_edukacja_medialna_pl.py` (reason `third_party_quote` in `artifacts/decisions.jsonl`).
84
+ Two quote Wojciech Michera, credited to a University of Warsaw course
85
+ (`montaz-materialu-filmowego`, `scenografia-charakteryzacja-kostiumy-i-aktorzy`); two reuse an
86
+ exercise with six attributed quotations of named people (`kim-jestem-w-internecie`,
87
+ `wizerunek-w-sieci`). 248 of 255 retained.
88
 
89
  Before/after excerpts of the extraction and normalization are in the PR
90
  description.
 
111
  What this adds: authored didactic prose — objectives, exercises, classroom
112
  procedure, glossary definitions — a school-teaching register the corpus does not
113
  otherwise draw from (its registers are encyclopedic, legal, parliamentary,
114
+ journalistic and fiction). 713,052 tokens is a diversity addition, not a scale
115
  one.
116
 
117
  Bias and quality caveats: a single publisher (Fundacja Nowoczesna Polska) and 62
 
127
  ## Reproduction
128
 
129
  Install `src/requirements.txt`, decompress `artifacts/raw_xml.jsonl.gz` to a work directory as `raw_xml.jsonl`, and run the builder against the preserved inventory. Live acquisition creates a new source Version and must use a fresh work directory.
130
+
131
+ The builder yields the 252 records contributed in PR #26. The published shard is 248: after the build, run
132
+ `python3 src/clean_edukacja_medialna_pl.py --input <dir> --out data/edukacja_medialna_pl`, where `<dir>` holds the
133
+ six builder outputs under their Dynaword names (`edukacja_medialna_pl.parquet`, `.attribution.jsonl`,
134
+ `.decisions.jsonl`, `.sample.jsonl`, `.stats.json`, `.qa.json`). The script drops the four lessons listed under
135
+ "Third-party quotations" above and rewrites those six files, statistics included. It exits before writing
136
+ anything unless the SHA-256 of every input file equals its pin in `INPUT_SHA256`, so a rebuild that is not
137
+ byte-identical to PR #26 stops there instead of being filtered silently; it also exits unless the quotation
138
+ markers match exactly the four ids in `DROP`. To rerun it from the PR #26 files without rebuilding, restore them
139
+ and run the script with its defaults:
140
+
141
+ ```
142
+ git checkout 5ec3e18 -- 'data/edukacja_medialna_pl/*.parquet' 'data/edukacja_medialna_pl/*.jsonl' 'data/edukacja_medialna_pl/*.json'
143
+ python3 src/clean_edukacja_medialna_pl.py
144
+ ```
data/edukacja_medialna_pl/edukacja_medialna_pl.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dbce26650981e8e552c7fdac48bd35c02e9bd0a56fced4ea4871489b5a2365c4
3
- size 778646
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1de35ab7c6c4db5fad67704c3f79afa65db6bfd411a1a55291bea05a4c940222
3
+ size 761117
data/edukacja_medialna_pl/edukacja_medialna_pl.qa.json CHANGED
@@ -16,5 +16,14 @@
16
  "pii_pattern_matches": {
17
  "email": 1,
18
  "labelled_phone": 0
 
 
 
 
 
 
 
 
 
19
  }
20
  }
 
16
  "pii_pattern_matches": {
17
  "email": 1,
18
  "labelled_phone": 0
19
+ },
20
+ "third_party_quotes": {
21
+ "dropped": {
22
+ "edukacja_medialna_pl_kim-jestem-w-internecie": "candidate: six attributed quotations of named people in the profile exercise",
23
+ "edukacja_medialna_pl_montaz-materialu-filmowego": "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course",
24
+ "edukacja_medialna_pl_scenografia-charakteryzacja-kostiumy-i-aktorzy": "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course",
25
+ "edukacja_medialna_pl_wizerunek-w-sieci": "candidate: six attributed quotations of named people in the profile exercise"
26
+ },
27
+ "rule": "whole lesson dropped when it embeds a quotation credited to a named third party"
28
  }
29
  }
data/edukacja_medialna_pl/edukacja_medialna_pl.stats.json CHANGED
@@ -2,10 +2,20 @@
2
  "acquired": 255,
3
  "added": "2026-09-06",
4
  "author_coverage": 1.0,
5
- "characters": 2033576,
6
  "discovered": 255,
7
- "kept": 252,
8
- "rejected": 3,
 
 
 
 
 
 
 
 
 
9
  "sample_count": 12,
10
- "tokens": 728987
 
11
  }
 
2
  "acquired": 255,
3
  "added": "2026-09-06",
4
  "author_coverage": 1.0,
5
+ "characters": 1988751,
6
  "discovered": 255,
7
+ "drop_third_party_quote": 4,
8
+ "input_sha256": {
9
+ "edukacja_medialna_pl.attribution.jsonl": "8522652f776bd59c115453331b4a5c771f01e6467fab2938798c3aad0065e55d",
10
+ "edukacja_medialna_pl.decisions.jsonl": "960bffd3e684a52a119633efbedc7d1ef0cd6d8c70bfbb16bb2c03c551da9962",
11
+ "edukacja_medialna_pl.parquet": "dbce26650981e8e552c7fdac48bd35c02e9bd0a56fced4ea4871489b5a2365c4",
12
+ "edukacja_medialna_pl.qa.json": "95e42a29bd2f1d328efac5f20378311a1806bd934b5bd88d6002a3bbf2ec78dc",
13
+ "edukacja_medialna_pl.sample.jsonl": "1d3277d93a5a1b9281ef1c71e745c9669eb2fac4cc78c7e60946557aedc7c1fa",
14
+ "edukacja_medialna_pl.stats.json": "38c7a8418b798021ce217a8bd9c9c120a7b92a7ac8e0cdbf56cb76757eb7b8cf"
15
+ },
16
+ "kept": 248,
17
+ "rejected": 7,
18
  "sample_count": 12,
19
+ "stats_recomputed_from_parquet": true,
20
+ "tokens": 713052
21
  }
src/clean_edukacja_medialna_pl.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Drop lessons that embed third-party quotations from edukacja_medialna_pl (rights audit 2026-10).
3
+
4
+ The audit found embedded third-party text "negligible" but listed "2-3 short quotes" and advised to
5
+ "optionally remove the 3 quote passages". The raw XML is no longer in the checkout, so this script
6
+ filters the pinned Parquet instead of rebuilding it. A lesson is dropped whole (fail closed), and each
7
+ drop names the exact string that identifies the quotation:
8
+
9
+ confirmed: two lessons quote the film scholar Wojciech Michera by name ("cytat z materiałów do kursu ...
10
+ Uniwersytet Warszawski"); the quotation is credited to him and not to the lesson authors.
11
+ candidates: the audit names no third quote, so none was confirmed. The two lessons that reuse the
12
+ "Kim jestem w internecie" exercise carry six attributed quotations of named people
13
+ ("Ulubione cytaty: ... (Winston Churchill)") inside invented profiles. They are dropped
14
+ on the same fail-closed reasoning; delete both from DROP to keep them.
15
+
16
+ `build()` exits unless the markers match exactly the DROP ids, so a changed or extended input cannot slip
17
+ through. Kept on purpose: attributed CC BY-SA excerpts (a Wikipedia article and CC BY-SA photo credits),
18
+ a one-sentence GMO definition cited to a ministry page, and lesson plans that only name films or books.
19
+
20
+ The input is the Parquet and sidecars as contributed in PR #26 (unchanged since), pinned by SHA-256.
21
+ Restore them before a rerun (the three globs match exactly the six pinned files, so the datasheet and
22
+ NOTICE.md are left alone):
23
+ git checkout 5ec3e18 -- 'data/edukacja_medialna_pl/*.parquet' 'data/edukacja_medialna_pl/*.jsonl' 'data/edukacja_medialna_pl/*.json'
24
+ python3 src/clean_edukacja_medialna_pl.py
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import hashlib
30
+ import json
31
+ import os
32
+ from pathlib import Path
33
+
34
+ import pyarrow as pa
35
+ import pyarrow.parquet as pq
36
+
37
+ SOURCE = "edukacja_medialna_pl"
38
+ ROOT = Path(__file__).resolve().parents[1]
39
+ DATA = ROOT / "data" / SOURCE
40
+ INPUT_SHA256 = {
41
+ f"{SOURCE}.parquet": "dbce26650981e8e552c7fdac48bd35c02e9bd0a56fced4ea4871489b5a2365c4",
42
+ f"{SOURCE}.attribution.jsonl": "8522652f776bd59c115453331b4a5c771f01e6467fab2938798c3aad0065e55d",
43
+ f"{SOURCE}.decisions.jsonl": "960bffd3e684a52a119633efbedc7d1ef0cd6d8c70bfbb16bb2c03c551da9962",
44
+ f"{SOURCE}.sample.jsonl": "1d3277d93a5a1b9281ef1c71e745c9669eb2fac4cc78c7e60946557aedc7c1fa",
45
+ f"{SOURCE}.stats.json": "38c7a8418b798021ce217a8bd9c9c120a7b92a7ac8e0cdbf56cb76757eb7b8cf",
46
+ f"{SOURCE}.qa.json": "95e42a29bd2f1d328efac5f20378311a1806bd934b5bd88d6002a3bbf2ec78dc",
47
+ }
48
+ REASON = "third_party_quote"
49
+ SAMPLE_SIZE = 12
50
+
51
+ MICHERA = "Wojciech Michera"
52
+ PROFILES = "Ulubione cytaty"
53
+ # id -> (string that must occur in the lesson, why it is dropped)
54
+ DROP = {
55
+ f"{SOURCE}_montaz-materialu-filmowego": (MICHERA, "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course"),
56
+ f"{SOURCE}_scenografia-charakteryzacja-kostiumy-i-aktorzy": (MICHERA, "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course"),
57
+ f"{SOURCE}_kim-jestem-w-internecie": (PROFILES, "candidate: six attributed quotations of named people in the profile exercise"),
58
+ f"{SOURCE}_wizerunek-w-sieci": (PROFILES, "candidate: six attributed quotations of named people in the profile exercise"),
59
+ }
60
+
61
+
62
+ def sha(value: bytes | object) -> str:
63
+ if not isinstance(value, bytes):
64
+ value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
65
+ return hashlib.sha256(value).hexdigest()
66
+
67
+
68
+ def read_lines(path: Path) -> list[dict]:
69
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
70
+
71
+
72
+ def lines(rows: list[dict]) -> str:
73
+ return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows)
74
+
75
+
76
+ def dump(value: dict) -> str:
77
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
78
+
79
+
80
+ def write_text(path: Path, text: str, eol: str) -> None:
81
+ path.write_bytes(text.replace("\n", eol).encode("utf-8"))
82
+
83
+
84
+ def build(input_dir: Path, out_dir: Path) -> dict:
85
+ paths = {name: input_dir / name for name in INPUT_SHA256}
86
+ for name, expected in INPUT_SHA256.items():
87
+ if sha(paths[name].read_bytes()) != expected:
88
+ raise SystemExit(f"{paths[name]} is not the PR #26 input; restore it with the command in this script's docstring")
89
+ # The contributed text files use CRLF; keep it so the diff shows only the dropped records.
90
+ eol = "\r\n"
91
+ if any(b"\r\n" not in paths[name].read_bytes() for name in INPUT_SHA256 if not name.endswith(".parquet")):
92
+ raise SystemExit("expected CRLF line endings in the PR #26 text files")
93
+ table = pq.read_table(paths[f"{SOURCE}.parquet"])
94
+ rows = table.to_pylist()
95
+ ids = [row["id"] for row in rows]
96
+ attribution = read_lines(paths[f"{SOURCE}.attribution.jsonl"])
97
+ decisions = read_lines(paths[f"{SOURCE}.decisions.jsonl"])
98
+ if len(set(ids)) != len(ids) or [r["id"] for r in attribution] != ids:
99
+ raise SystemExit("Parquet and attribution sidecar do not list the same ids in the same order")
100
+ if stale := DROP.keys() - set(ids):
101
+ raise SystemExit(f"DROP names ids that are not in the input: {sorted(stale)}")
102
+ markers = {marker for marker, _ in DROP.values()}
103
+ hits = {row["id"] for row in rows if any(marker in row["text"] for marker in markers)}
104
+ if hits != DROP.keys():
105
+ raise SystemExit(f"markers match {sorted(hits ^ DROP.keys())} differently from DROP")
106
+ if missing := [i for i, row in zip(ids, rows) if i in DROP and DROP[i][0] not in row["text"]]:
107
+ raise SystemExit(f"DROP markers missing from {missing}")
108
+
109
+ kept = [row for row in rows if row["id"] not in DROP]
110
+ kept_ids = {row["id"] for row in kept}
111
+ samples = sorted(kept, key=lambda row: sha(("sample:" + row["id"]).encode()))[:SAMPLE_SIZE]
112
+ decisions = [{**d, "selected": False, "reason": REASON} if d["id"] in DROP else d for d in decisions]
113
+ stats = {
114
+ **json.loads(paths[f"{SOURCE}.stats.json"].read_text(encoding="utf-8")),
115
+ "kept": len(kept), "rejected": len(decisions) - len(kept),
116
+ "tokens": sum(row["token_count"] for row in kept), "characters": sum(len(row["text"]) for row in kept),
117
+ "sample_count": len(samples), "author_coverage": sum(bool(row["author"]) for row in kept) / len(kept),
118
+ "drop_third_party_quote": len(DROP), "stats_recomputed_from_parquet": True, "input_sha256": INPUT_SHA256,
119
+ }
120
+ qa = {**json.loads(paths[f"{SOURCE}.qa.json"].read_text(encoding="utf-8")),
121
+ "third_party_quotes": {"rule": "whole lesson dropped when it embeds a quotation credited to a named third party",
122
+ "dropped": {i: why for i, (_, why) in sorted(DROP.items())}}}
123
+ staged = {
124
+ f"{SOURCE}.parquet": lambda p: pq.write_table(pa.Table.from_pylist(kept, schema=table.schema), p, compression="zstd"),
125
+ f"{SOURCE}.attribution.jsonl": lambda p: write_text(p, lines([r for r in attribution if r["id"] in kept_ids]), eol),
126
+ f"{SOURCE}.decisions.jsonl": lambda p: write_text(p, lines(decisions), eol),
127
+ f"{SOURCE}.sample.jsonl": lambda p: write_text(p, lines(samples), eol),
128
+ f"{SOURCE}.stats.json": lambda p: write_text(p, dump(stats), eol),
129
+ f"{SOURCE}.qa.json": lambda p: write_text(p, dump(qa), eol),
130
+ }
131
+ out_dir.mkdir(parents=True, exist_ok=True)
132
+ for name, write in staged.items():
133
+ write(out_dir / (name + ".tmp"))
134
+ for name in staged:
135
+ os.replace(out_dir / (name + ".tmp"), out_dir / name)
136
+ return {**stats, "dropped": {i: why for i, (_, why) in sorted(DROP.items())}}
137
+
138
+
139
+ def main() -> None:
140
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
141
+ parser.add_argument("--input", type=Path, default=DATA, help="directory holding the PR #26 Parquet and sidecars")
142
+ parser.add_argument("--out", type=Path, default=DATA)
143
+ args = parser.parse_args()
144
+ print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False))
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()
src/test_edukacja_medialna_contribution.py CHANGED
@@ -5,6 +5,8 @@ import re
5
 
6
  import pyarrow.parquet as pq
7
 
 
 
8
  SOURCE = "edukacja_medialna_pl"
9
  LICENSE = "CC-BY-SA-3.0"
10
  FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
@@ -48,19 +50,22 @@ def test_ontology_is_addressed_and_falsifiable():
48
  manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
49
  evidence = {item["id"]: item for item in manifest["evidence"]}
50
  checks = next(item["payload"] for item in manifest["evidence"] if item["observation_type"] == "checksums")
 
 
 
 
 
 
 
 
 
 
 
51
  for name, expected in checks.items():
52
- mapping = {
53
- "data/train-00000-of-00001.parquet": DATA / f"{SOURCE}.parquet",
54
- "artifacts/attribution.jsonl": DATA / f"{SOURCE}.attribution.jsonl",
55
- "artifacts/decisions.jsonl": DATA / f"{SOURCE}.decisions.jsonl",
56
- "artifacts/sample.jsonl": DATA / f"{SOURCE}.sample.jsonl",
57
- "artifacts/stats.json": DATA / f"{SOURCE}.stats.json",
58
- "artifacts/qa.json": DATA / f"{SOURCE}.qa.json",
59
- "src/build_edukacja_medialna_pl.py": ROOT / "src/build_edukacja_medialna_pl.py",
60
- "src/test_edukacja_medialna_contribution.py": ROOT / "src/test_edukacja_medialna_contribution.py",
61
- }
62
- if name in mapping:
63
- assert digest(mapping[name].read_bytes()) == expected
64
  assert all(item["falsification_condition"] for item in manifest["claims"])
65
  assert all(set(item["supported_by"]) <= set(evidence) for item in manifest["claims"])
66
  assert any(item["predicate"] == "VALIDATED_AGAINST" for item in manifest["relations"])
 
5
 
6
  import pyarrow.parquet as pq
7
 
8
+ from clean_edukacja_medialna_pl import INPUT_SHA256
9
+
10
  SOURCE = "edukacja_medialna_pl"
11
  LICENSE = "CC-BY-SA-3.0"
12
  FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
 
50
  manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
51
  evidence = {item["id"]: item for item in manifest["evidence"]}
52
  checks = next(item["payload"] for item in manifest["evidence"] if item["observation_type"] == "checksums")
53
+ # The manifest pins the contributed build. src/clean_edukacja_medialna_pl.py later rewrote the data files,
54
+ # so their pins must equal the input hashes that script checks (the cleaned files are checked in
55
+ # test_edukacja_medialna_pl_contract.py). This test file changed with the cleaning and cannot pin itself.
56
+ contributed = {
57
+ "data/train-00000-of-00001.parquet": f"{SOURCE}.parquet",
58
+ "artifacts/attribution.jsonl": f"{SOURCE}.attribution.jsonl",
59
+ "artifacts/decisions.jsonl": f"{SOURCE}.decisions.jsonl",
60
+ "artifacts/sample.jsonl": f"{SOURCE}.sample.jsonl",
61
+ "artifacts/stats.json": f"{SOURCE}.stats.json",
62
+ "artifacts/qa.json": f"{SOURCE}.qa.json",
63
+ }
64
  for name, expected in checks.items():
65
+ if name in contributed:
66
+ assert INPUT_SHA256[contributed[name]] == expected
67
+ elif name == "src/build_edukacja_medialna_pl.py":
68
+ assert digest((ROOT / name).read_bytes()) == expected
 
 
 
 
 
 
 
 
69
  assert all(item["falsification_condition"] for item in manifest["claims"])
70
  assert all(set(item["supported_by"]) <= set(evidence) for item in manifest["claims"])
71
  assert any(item["predicate"] == "VALIDATED_AGAINST" for item in manifest["relations"])
src/test_edukacja_medialna_pl_contract.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract checks for the third-party-quote drop in edukacja_medialna_pl (src/clean_edukacja_medialna_pl.py)."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import pyarrow as pa
7
+ import pyarrow.parquet as pq
8
+ import pytest
9
+
10
+ import clean_edukacja_medialna_pl as clean
11
+
12
+ SOURCE = "edukacja_medialna_pl"
13
+ DATA = Path(__file__).resolve().parents[1] / "data" / SOURCE
14
+ # 255 lessons discovered, 3 without a creator, 4 dropped for quotations of named third parties.
15
+ KEPT, TOKENS, CHARACTERS = 248, 713_052, 1_988_751
16
+ # Confirmed: lessons that quote Wojciech Michera by name. Candidates: the "Kim jestem w internecie" exercise.
17
+ CONFIRMED = {f"{SOURCE}_montaz-materialu-filmowego", f"{SOURCE}_scenografia-charakteryzacja-kostiumy-i-aktorzy"}
18
+ CANDIDATES = {f"{SOURCE}_kim-jestem-w-internecie", f"{SOURCE}_wizerunek-w-sieci"}
19
+
20
+
21
+ def jsonl(name):
22
+ return [json.loads(line) for line in (DATA / f"{SOURCE}.{name}.jsonl").read_text(encoding="utf-8").splitlines() if line]
23
+
24
+
25
+ def test_the_four_quoting_lessons_are_gone_and_recorded_as_rejected():
26
+ assert clean.DROP.keys() == CONFIRMED | CANDIDATES
27
+ rows = pq.read_table(DATA / f"{SOURCE}.parquet").to_pylist()
28
+ ids = {row["id"] for row in rows}
29
+ assert not (CONFIRMED | CANDIDATES) & ids
30
+ assert not (CONFIRMED | CANDIDATES) & {r["id"] for r in jsonl("attribution")}
31
+ assert not (CONFIRMED | CANDIDATES) & {r["id"] for r in jsonl("sample")}
32
+ decisions = {d["id"]: d for d in jsonl("decisions")}
33
+ assert {i for i, d in decisions.items() if d["reason"] == clean.REASON} == CONFIRMED | CANDIDATES
34
+ assert not any(decisions[i]["selected"] for i in CONFIRMED | CANDIDATES)
35
+ # No lesson that is kept still carries one of the quotation markers.
36
+ assert [r["id"] for r in rows if any(marker in r["text"] for marker, _ in clean.DROP.values())] == []
37
+
38
+
39
+ def test_counts_stats_and_sidecars_agree():
40
+ table = pq.read_table(DATA / f"{SOURCE}.parquet")
41
+ rows = table.to_pylist()
42
+ stats = json.loads((DATA / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
43
+ qa = json.loads((DATA / f"{SOURCE}.qa.json").read_text(encoding="utf-8"))
44
+ attribution, decisions, sample = jsonl("attribution"), jsonl("decisions"), jsonl("sample")
45
+ ids = [row["id"] for row in rows]
46
+ assert table.column_names == ["id", "text", "source", "added", "created", "token_count", "license", "author"]
47
+ assert len(rows) == stats["kept"] == len(attribution) == sum(d["selected"] for d in decisions) == KEPT
48
+ assert stats["tokens"] == sum(r["token_count"] for r in rows) == TOKENS
49
+ assert stats["characters"] == sum(len(r["text"]) for r in rows) == CHARACTERS
50
+ assert stats["discovered"] == stats["acquired"] == len(decisions) == 255
51
+ assert stats["rejected"] == len(decisions) - KEPT == 3 + stats["drop_third_party_quote"] == 7
52
+ assert [a["id"] for a in attribution] == ids and len(set(ids)) == len(ids)
53
+ assert {r["license"] for r in rows} == {a["license"] for a in attribution} == {"CC-BY-SA-3.0"}
54
+ assert len(sample) == stats["sample_count"] == 12 and all(s in rows for s in sample)
55
+ assert sample == sorted(rows, key=lambda r: clean.sha(("sample:" + r["id"]).encode()))[:12]
56
+ assert stats["input_sha256"] == clean.INPUT_SHA256
57
+ assert qa["third_party_quotes"]["dropped"].keys() == clean.DROP.keys()
58
+
59
+
60
+ def write_input(directory, rows):
61
+ """A miniature input with CRLF text files, plus the pins for it."""
62
+ directory.mkdir(parents=True)
63
+ names = {kind: directory / f"{SOURCE}.{kind}" for kind in ("parquet", "attribution.jsonl", "decisions.jsonl", "sample.jsonl", "stats.json", "qa.json")}
64
+ schema = pa.schema([(f, pa.int64() if f == "token_count" else pa.string()) for f in clean.pq.read_table(DATA / f"{SOURCE}.parquet").column_names])
65
+ pq.write_table(pa.Table.from_pylist(rows, schema=schema), names["parquet"])
66
+ text = {
67
+ "attribution.jsonl": clean.lines([{"id": r["id"], "license": r["license"]} for r in rows]),
68
+ "decisions.jsonl": clean.lines([{"id": r["id"], "selected": True, "reason": "include", "page_sha256": "p", "xml_sha256": "x"} for r in rows]),
69
+ "sample.jsonl": clean.lines(rows),
70
+ "stats.json": clean.dump({"acquired": len(rows), "discovered": len(rows), "kept": len(rows), "rejected": 0, "added": "2026-09-06"}),
71
+ "qa.json": clean.dump({"license_gate": "x"}),
72
+ }
73
+ for kind, content in text.items():
74
+ clean.write_text(names[kind], content, "\r\n")
75
+ return {path.name: clean.sha(path.read_bytes()) for path in names.values()}
76
+
77
+
78
+ def row(slug, text):
79
+ return {"id": f"{SOURCE}_{slug}", "text": text, "source": SOURCE, "added": "2026-09-06", "created": "2013-01-01",
80
+ "token_count": len(text.split()), "license": "CC-BY-SA-3.0", "author": "Anna Autor"}
81
+
82
+
83
+ @pytest.fixture
84
+ def mini(tmp_path, monkeypatch):
85
+ rows = [row("a", "plain lesson"), row("b", "as Wojciech Michera said"), row("c", "another plain lesson here")]
86
+ pins = write_input(tmp_path / "in", rows)
87
+ monkeypatch.setattr(clean, "INPUT_SHA256", pins)
88
+ monkeypatch.setattr(clean, "DROP", {f"{SOURCE}_b": ("Wojciech Michera", "confirmed: test")})
89
+ return tmp_path
90
+
91
+
92
+ def test_build_drops_the_listed_lesson_and_rewrites_every_file(mini):
93
+ out = mini / "out"
94
+ stats = clean.build(mini / "in", out)
95
+ assert pq.read_table(out / f"{SOURCE}.parquet").column("id").to_pylist() == [f"{SOURCE}_a", f"{SOURCE}_c"]
96
+ assert (stats["kept"], stats["rejected"], stats["tokens"], stats["drop_third_party_quote"]) == (2, 1, 6, 1)
97
+ decisions = {d["id"]: d for d in map(json.loads, (out / f"{SOURCE}.decisions.jsonl").read_text(encoding="utf-8").splitlines())}
98
+ assert decisions[f"{SOURCE}_b"]["reason"] == clean.REASON and not decisions[f"{SOURCE}_b"]["selected"]
99
+ assert decisions[f"{SOURCE}_a"]["selected"]
100
+ assert b"\r\n" in (out / f"{SOURCE}.stats.json").read_bytes()
101
+ assert not list(out.glob("*.tmp"))
102
+
103
+
104
+ def test_build_refuses_an_input_that_is_not_the_pinned_one(mini):
105
+ (mini / "in" / f"{SOURCE}.qa.json").write_bytes(b"{}\r\n")
106
+ with pytest.raises(SystemExit, match="not the PR #26 input"):
107
+ clean.build(mini / "in", mini / "out")
108
+ assert not (mini / "out").exists()
109
+
110
+
111
+ def test_build_fails_closed_on_a_stale_id_or_an_unlisted_quotation(mini, monkeypatch):
112
+ monkeypatch.setattr(clean, "DROP", {f"{SOURCE}_zzz": ("Wojciech Michera", "stale")})
113
+ with pytest.raises(SystemExit, match="not in the input"):
114
+ clean.build(mini / "in", mini / "out")
115
+ # The marker also matches lesson b, which DROP does not list.
116
+ monkeypatch.setattr(clean, "DROP", {f"{SOURCE}_a": ("Wojciech Michera", "wrong lesson")})
117
+ with pytest.raises(SystemExit, match="differently from DROP"):
118
+ clean.build(mini / "in", mini / "out")
119
+
120
+
121
+ def test_build_refuses_the_already_cleaned_data(tmp_path):
122
+ with pytest.raises(SystemExit, match="not the PR #26 input"):
123
+ clean.build(DATA, tmp_path / "out")
124
+
125
+
126
+ def test_datasheet_reproduction_steps_include_the_clean_script_and_its_pin_check():
127
+ text = (DATA / f"{SOURCE}.md").read_text(encoding="utf-8")
128
+ assert text.count("## Reproduction") == 1
129
+ reproduction = text.split("## Reproduction")[1]
130
+ for needle in ("src/clean_edukacja_medialna_pl.py", "INPUT_SHA256", "DROP", "5ec3e18"):
131
+ assert needle in reproduction
132
+
133
+
134
+ def test_restore_command_is_the_same_in_docstring_and_datasheet_and_touches_only_the_pinned_files():
135
+ command = next(line.strip() for line in clean.__doc__.splitlines() if line.strip().startswith("git checkout"))
136
+ assert command in (DATA / f"{SOURCE}.md").read_text(encoding="utf-8")
137
+ globs = [arg.strip("'").rsplit("/", 1)[1] for arg in command.split(" -- ")[1].split()]
138
+ assert sorted(p.name for pattern in globs for p in DATA.glob(pattern)) == sorted(clean.INPUT_SHA256)