File size: 5,563 Bytes
c2099e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/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()