Datasets:
Download src/clean_govpl.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 5.56 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/c2099e63208a9182555e01f2dadb935bb47f4803/src/clean_govpl.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword@c2099e63208a9182555e01f2dadb935bb47f4803/src/clean_govpl.py
-
curl -L -o clean_govpl.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/c2099e63208a9182555e01f2dadb935bb47f4803/src/clean_govpl.py
5.56 kB
| #!/usr/bin/env python3 | |
| """Drop PAP reprints 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). | |
| `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. | |
| Both inputs are pinned by SHA-256. Restore the Parquet before a rerun: | |
| git checkout v0.2.5 -- data/govpl/govpl.parquet | |
| 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 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, pap_rule # one rule for fetch and release | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA = ROOT / "data" / SOURCE | |
| INPUT_SHA256 = "9c0310fcdf45804e6547bd197cba55f58f12df618cd3d8b92b8e9077a3720b9f" # v0.2.5 | |
| FETCHED_SHA256 = "368259d0ea8522eced71b426ae238556d5330a410aa994bdcbdc7427478d783a" # 2026-07-19 crawl | |
| 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 check_pin(path: Path, expected: str, restore: str) -> None: | |
| with path.open("rb") as stream: | |
| actual = hashlib.file_digest(stream, "sha256").hexdigest() | |
| if actual != expected: | |
| raise SystemExit(f"{path} does not match the pinned SHA-256; {restore}") | |
| def build(input_path: Path, fetched_path: Path, out_dir: Path) -> dict: | |
| check_pin(input_path, INPUT_SHA256, "restore it with `git checkout v0.2.5 -- data/govpl/govpl.parquet`") | |
| check_pin(fetched_path, FETCHED_SHA256, "it is not the 2026-07-19 gov.pl crawl") | |
| table = pq.read_table(input_path) | |
| meta = fetched_meta(fetched_path) | |
| kept, attribution, dropped = [], [], Counter() | |
| for row in table.to_pylist(): | |
| if rule := pap_rule(row["text"]): | |
| dropped[rule] += 1 | |
| continue | |
| found = meta.get(text_key(row["text"])) | |
| if found is None: | |
| raise SystemExit(f"{row['id']}: text not found in {fetched_path}") | |
| kept.append(row) | |
| attribution.append({ | |
| "id": row["id"], "url": found["url"], "subsite": found["subsite"], | |
| "title": found["title"], "date": found["date"], "license": row["license"], | |
| }) | |
| stats = { | |
| **BUILD_STATS, "drop_pap": sum(dropped.values()), "drop_pap_by_rule": dict(dropped), | |
| "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, | |
| } | |
| 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("--out", type=Path, default=DATA) | |
| args = parser.parse_args() | |
| print(json.dumps(build(args.input, args.fetched, args.out), indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |