polish-dynaword / src /clean_edukacja_medialna_pl.py
ppuzio's picture
edukacja_medialna_pl: drop 4 lessons with embedded third-party quotations (252 -> 248) (#74)
c6d92bb
Raw History Blame
8.19 kB
#!/usr/bin/env python3
"""Drop lessons that embed third-party quotations from edukacja_medialna_pl (rights audit 2026-10).
The audit found embedded third-party text "negligible" but listed "2-3 short quotes" and advised to
"optionally remove the 3 quote passages". The raw XML is no longer in the checkout, so this script
filters the pinned Parquet instead of rebuilding it. A lesson is dropped whole (fail closed), and each
drop names the exact string that identifies the quotation:
confirmed: two lessons quote the film scholar Wojciech Michera by name ("cytat z materiałów do kursu ...
Uniwersytet Warszawski"); the quotation is credited to him and not to the lesson authors.
candidates: the audit names no third quote, so none was confirmed. The two lessons that reuse the
"Kim jestem w internecie" exercise carry six attributed quotations of named people
("Ulubione cytaty: ... (Winston Churchill)") inside invented profiles. They are dropped
on the same fail-closed reasoning; delete both from DROP to keep them.
`build()` exits unless the markers match exactly the DROP ids, so a changed or extended input cannot slip
through. Kept on purpose: attributed CC BY-SA excerpts (a Wikipedia article and CC BY-SA photo credits),
a one-sentence GMO definition cited to a ministry page, and lesson plans that only name films or books.
The input is the Parquet and sidecars as contributed in PR #26 (unchanged since), pinned by SHA-256.
Restore them before a rerun (the three globs match exactly the six pinned files, so the datasheet and
NOTICE.md are left alone):
git checkout 5ec3e18 -- 'data/edukacja_medialna_pl/*.parquet' 'data/edukacja_medialna_pl/*.jsonl' 'data/edukacja_medialna_pl/*.json'
python3 src/clean_edukacja_medialna_pl.py
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
SOURCE = "edukacja_medialna_pl"
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / SOURCE
INPUT_SHA256 = {
f"{SOURCE}.parquet": "dbce26650981e8e552c7fdac48bd35c02e9bd0a56fced4ea4871489b5a2365c4",
f"{SOURCE}.attribution.jsonl": "8522652f776bd59c115453331b4a5c771f01e6467fab2938798c3aad0065e55d",
f"{SOURCE}.decisions.jsonl": "960bffd3e684a52a119633efbedc7d1ef0cd6d8c70bfbb16bb2c03c551da9962",
f"{SOURCE}.sample.jsonl": "1d3277d93a5a1b9281ef1c71e745c9669eb2fac4cc78c7e60946557aedc7c1fa",
f"{SOURCE}.stats.json": "38c7a8418b798021ce217a8bd9c9c120a7b92a7ac8e0cdbf56cb76757eb7b8cf",
f"{SOURCE}.qa.json": "95e42a29bd2f1d328efac5f20378311a1806bd934b5bd88d6002a3bbf2ec78dc",
}
REASON = "third_party_quote"
SAMPLE_SIZE = 12
MICHERA = "Wojciech Michera"
PROFILES = "Ulubione cytaty"
# id -> (string that must occur in the lesson, why it is dropped)
DROP = {
f"{SOURCE}_montaz-materialu-filmowego": (MICHERA, "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course"),
f"{SOURCE}_scenografia-charakteryzacja-kostiumy-i-aktorzy": (MICHERA, "confirmed: quotes Wojciech Michera, credited to a University of Warsaw course"),
f"{SOURCE}_kim-jestem-w-internecie": (PROFILES, "candidate: six attributed quotations of named people in the profile exercise"),
f"{SOURCE}_wizerunek-w-sieci": (PROFILES, "candidate: six attributed quotations of named people in the profile exercise"),
}
def sha(value: bytes | object) -> str:
if not isinstance(value, bytes):
value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
return hashlib.sha256(value).hexdigest()
def read_lines(path: Path) -> list[dict]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
def lines(rows: list[dict]) -> str:
return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows)
def dump(value: dict) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
def write_text(path: Path, text: str, eol: str) -> None:
path.write_bytes(text.replace("\n", eol).encode("utf-8"))
def build(input_dir: Path, out_dir: Path) -> dict:
paths = {name: input_dir / name for name in INPUT_SHA256}
for name, expected in INPUT_SHA256.items():
if sha(paths[name].read_bytes()) != expected:
raise SystemExit(f"{paths[name]} is not the PR #26 input; restore it with the command in this script's docstring")
# The contributed text files use CRLF; keep it so the diff shows only the dropped records.
eol = "\r\n"
if any(b"\r\n" not in paths[name].read_bytes() for name in INPUT_SHA256 if not name.endswith(".parquet")):
raise SystemExit("expected CRLF line endings in the PR #26 text files")
table = pq.read_table(paths[f"{SOURCE}.parquet"])
rows = table.to_pylist()
ids = [row["id"] for row in rows]
attribution = read_lines(paths[f"{SOURCE}.attribution.jsonl"])
decisions = read_lines(paths[f"{SOURCE}.decisions.jsonl"])
if len(set(ids)) != len(ids) or [r["id"] for r in attribution] != ids:
raise SystemExit("Parquet and attribution sidecar do not list the same ids in the same order")
if stale := DROP.keys() - set(ids):
raise SystemExit(f"DROP names ids that are not in the input: {sorted(stale)}")
markers = {marker for marker, _ in DROP.values()}
hits = {row["id"] for row in rows if any(marker in row["text"] for marker in markers)}
if hits != DROP.keys():
raise SystemExit(f"markers match {sorted(hits ^ DROP.keys())} differently from DROP")
if missing := [i for i, row in zip(ids, rows) if i in DROP and DROP[i][0] not in row["text"]]:
raise SystemExit(f"DROP markers missing from {missing}")
kept = [row for row in rows if row["id"] not in DROP]
kept_ids = {row["id"] for row in kept}
samples = sorted(kept, key=lambda row: sha(("sample:" + row["id"]).encode()))[:SAMPLE_SIZE]
decisions = [{**d, "selected": False, "reason": REASON} if d["id"] in DROP else d for d in decisions]
stats = {
**json.loads(paths[f"{SOURCE}.stats.json"].read_text(encoding="utf-8")),
"kept": len(kept), "rejected": len(decisions) - len(kept),
"tokens": sum(row["token_count"] for row in kept), "characters": sum(len(row["text"]) for row in kept),
"sample_count": len(samples), "author_coverage": sum(bool(row["author"]) for row in kept) / len(kept),
"drop_third_party_quote": len(DROP), "stats_recomputed_from_parquet": True, "input_sha256": INPUT_SHA256,
}
qa = {**json.loads(paths[f"{SOURCE}.qa.json"].read_text(encoding="utf-8")),
"third_party_quotes": {"rule": "whole lesson dropped when it embeds a quotation credited to a named third party",
"dropped": {i: why for i, (_, why) in sorted(DROP.items())}}}
staged = {
f"{SOURCE}.parquet": lambda p: pq.write_table(pa.Table.from_pylist(kept, schema=table.schema), p, compression="zstd"),
f"{SOURCE}.attribution.jsonl": lambda p: write_text(p, lines([r for r in attribution if r["id"] in kept_ids]), eol),
f"{SOURCE}.decisions.jsonl": lambda p: write_text(p, lines(decisions), eol),
f"{SOURCE}.sample.jsonl": lambda p: write_text(p, lines(samples), eol),
f"{SOURCE}.stats.json": lambda p: write_text(p, dump(stats), eol),
f"{SOURCE}.qa.json": lambda p: write_text(p, dump(qa), eol),
}
out_dir.mkdir(parents=True, exist_ok=True)
for name, write in staged.items():
write(out_dir / (name + ".tmp"))
for name in staged:
os.replace(out_dir / (name + ".tmp"), out_dir / name)
return {**stats, "dropped": {i: why for i, (_, why) in sorted(DROP.items())}}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--input", type=Path, default=DATA, help="directory holding the PR #26 Parquet and sidecars")
parser.add_argument("--out", type=Path, default=DATA)
args = parser.parse_args()
print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()