polish-dynaword / src /clean_govpl.py
ppuzio's picture
claude opus 5.5
PiotrSty's picture kacperwikiel's picture Maggio33's picture dawidmajewski's picture KateMajzel's picture bartoszkobylinski1's picture 1am's picture
Squash history: drop the sources held off main in October 2026
8032ef4
Raw History Blame
8.21 kB
#!/usr/bin/env python3
"""Drop PAP reprints and other third-party texts from `govpl` and write a per-row URL sidecar.
gov.pl's copyright page (https://www.gov.pl/web/gov/prawa-autorskie) licenses the
site's text under CC BY-SA 4.0 but excludes works whose copyright belongs to third
parties. Articles that credit PAP (Polish Press Agency) as their source are such
works (slayerlabs/polish-dynaword-v2#51). `fetch_govpl.pap_rule` names them; this
script removes them from the released Parquet, so ids and the other rows stay as they
are (a rebuild through build_dynaword.py would renumber ids).
Other third-party texts are dropped by `govpl.third-party-review.csv` (polish-dynaword-v2#106):
one decision per article that carries a "Źródło:" line (`ZRODLO`) and is not a PAP reprint,
plus six articles reprinted from or written for other outlets. A "Źródło:" article stays only
when its text is credited to a public office (`credit_public_office`) or the line credits
something other than the text, such as data, a chart, a reference or a quotation
(`no_text_credit`). The review must list exactly the non-PAP articles that match `ZRODLO`,
plus the `third_party_text` ones.
The releases of the prosecutor offices' sections (`fetch_govpl.PROSECUTOR_SECTION`:
prokuratura-krajowa, pr-*, po-*) are dropped too. They report criminal cases about people
who can often be identified, even from initials. A row's section is the subsite of its
first fetched URL; no text was fetched from both a prosecutor and another section.
`govpl.attribution.jsonl` gives each kept row the gov.pl URL, subsite, title and date
of the fetched article, matched on build_dynaword's dedup key (SHA-1 of the stripped
text) in the fetch output `govpl.jsonl.zst`. Where the same text was fetched from
several URLs, the first one in fetch order is used.
The inputs and the review are pinned by SHA-256. The Parquet, as of v0.2.5,
predates the October 2026 rights audit and is no longer published:
the release tags v0.2.0-v0.2.5 that held it were deleted after the audit.
The pins record which files a rerun needs; with them in place:
python3 src/clean_govpl.py --fetched ~/speakleash/govpl.jsonl.zst
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import re
import sys
from collections import Counter
from pathlib import Path
import pyarrow.parquet as pq
import zstandard
sys.path.insert(0, str(Path(__file__).resolve().parent))
from fetch_govpl import KEY as SOURCE, PROSECUTOR_SECTION, pap_rule # one rule for fetch and release
from sejm_api_common import UNPUBLISHED, check_pin, read_pinned_review
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / SOURCE
INPUT_SHA256 = "9c0310fcdf45804e6547bd197cba55f58f12df618cd3d8b92b8e9077a3720b9f" # v0.2.5
FETCHED_SHA256 = "368259d0ea8522eced71b426ae238556d5330a410aa994bdcbdc7427478d783a" # 2026-07-19 crawl
REVIEW_SHA256 = "599f678bb1f3e1d058b3d115667e73331f3324eaccc9766cf54694860533e90b" # govpl.third-party-review.csv
REVIEW_REASONS = {
"keep": {"credit_public_office", "no_text_credit"},
"drop": {"credit_media", "credit_other", "third_party_text"},
}
ZRODLO = re.compile(r"(?i)\b[źżz]r[óo]d[łl][oa](?:\s+informacji)?\s*:") # "Źródło:" / "Źródła:" line
BUILD_STATS = { # build_dynaword.py counts for the v0.2.5 Parquet, kept for the datasheet
"read": 90140, "drop_short": 0, "drop_lang": 24, "drop_dup": 1926, "drop_ocr": 0,
}
def text_key(text: str) -> bytes:
"""build_dynaword's dedup key."""
return hashlib.sha1(text.strip().encode("utf-8")).digest()
def fetched_meta(path: Path) -> dict[bytes, dict]:
"""text_key -> meta of the first fetched record with that text."""
meta: dict[bytes, dict] = {}
with path.open("rb") as compressed:
lines = io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(compressed), encoding="utf-8")
for line in lines:
if line.strip():
record = json.loads(line)
meta.setdefault(text_key(record["text"]), record["meta"])
return meta
def build(input_path: Path, fetched_path: Path, review_path: Path, out_dir: Path) -> dict:
check_pin(input_path, INPUT_SHA256, UNPUBLISHED)
check_pin(fetched_path, FETCHED_SHA256, "it is not the 2026-07-19 gov.pl crawl")
review = read_pinned_review(review_path, REVIEW_SHA256, "it is not the reviewed govpl.third-party-review.csv",
REVIEW_REASONS)
table = pq.read_table(input_path)
meta = fetched_meta(fetched_path)
kept, attribution, dropped, dropped_third_party, dropped_prosecutor = [], [], Counter(), Counter(), 0
mismatched, seen = [], set()
for row in table.to_pylist():
if rule := pap_rule(row["text"]):
dropped[rule] += 1
continue
decision, reason = review.get(row["id"], (None, None))
if decision:
seen.add(row["id"])
if bool(ZRODLO.search(row["text"])) != (decision is not None and reason != "third_party_text"):
mismatched.append(row["id"])
if decision == "drop":
dropped_third_party[reason] += 1
continue
found = meta.get(text_key(row["text"]))
if found is None:
raise SystemExit(f"{row['id']}: text not found in {fetched_path}")
if PROSECUTOR_SECTION.match(found["subsite"]):
dropped_prosecutor += 1
continue
kept.append(row)
attribution.append({
"id": row["id"], "url": found["url"], "subsite": found["subsite"],
"title": found["title"], "date": found["date"], "license": row["license"],
})
if mismatched:
raise SystemExit(f"{len(mismatched)} rows where the review and the \"Źródło:\" match disagree: {mismatched[:5]}")
if missing := sorted(review.keys() - seen):
raise SystemExit(f"{len(missing)} reviewed ids are not in the input or are PAP reprints: {missing[:5]}")
stats = {
**BUILD_STATS, "drop_pap": sum(dropped.values()), "drop_pap_by_rule": dict(dropped),
"drop_third_party": sum(dropped_third_party.values()),
"drop_third_party_by_reason": dict(sorted(dropped_third_party.items())),
"drop_prosecutor": dropped_prosecutor,
"kept": len(kept),
"chars": sum(len(r["text"]) for r in kept), "tokens": sum(r["token_count"] for r in kept),
"licenses": dict(Counter(r["license"] for r in kept)),
"authors_with_value": sum(bool(r["author"]) for r in kept), "license": "CC-BY-SA-4.0",
"input_rows": table.num_rows, "input_sha256": INPUT_SHA256, "fetched_sha256": FETCHED_SHA256,
"review_sha256": REVIEW_SHA256,
}
build_drops = sum(v for k, v in BUILD_STATS.items() if k.startswith("drop_"))
if stats["read"] - build_drops != table.num_rows:
raise SystemExit("BUILD_STATS does not add up to the input row count")
staged = {
out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table(
table.from_pylist(kept, schema=table.schema), p, compression="zstd"),
out_dir / f"{SOURCE}.attribution.jsonl.tmp": lambda p: p.write_text(
"".join(json.dumps(a, ensure_ascii=False) + "\n" for a in attribution), encoding="utf-8"),
out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text(
json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"),
}
for path, write in staged.items():
write(path)
for path in staged:
os.replace(path, path.with_suffix(""))
return stats
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet")
parser.add_argument("--fetched", type=Path, required=True, help="govpl.jsonl.zst from fetch_govpl.py")
parser.add_argument("--review", type=Path, default=DATA / f"{SOURCE}.third-party-review.csv")
parser.add_argument("--out", type=Path, default=DATA)
args = parser.parse_args()
print(json.dumps(build(args.input, args.fetched, args.review, args.out), indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()