polish-dynaword / src /clean_sejm_api.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
4.84 kB
#!/usr/bin/env python3
"""Cut the "Przebieg posiedzenia" trailers off the sejm_api speeches (slayerlabs/polish-dynaword-v2#57).
The PiotrSty snapshot appends to most speeches the header of a later statement of the same sitting
day, and sometimes that statement's text (see sejm_api_common.split_trailers). This script cuts every
trailer and keeps a trailer's speech as a row of its own under the header's speaker
(sejm_api_common.split_release_rows); rows that fall under the 200-character minimum after the cut,
and texts that become exact duplicates, are dropped.
Then the speaker allowlist is applied (slayerlabs/polish-dynaword-v2#99, src/sejm_api_speakers.py): a row stays only
when the pinned table sejm_api.speaker-filter.csv says its speaker held an allowed role (MP, senator, government
member, constitutional organ, chancellery staff) on that sitting day. The table is written offline from the PPC
plenary headers and the committee transcripts; see src/sejm_api_speakers.py to regenerate it.
The inputs are the pre-cut release files of v0.2.5, pinned by SHA-256. The Parquet and the
sidecar predate the October 2026 rights audit and are no longer published:
the release tags v0.2.0-v0.2.5 that held them were deleted after the audit.
The pins record which files a rerun needs; with them in place:
python3 src/clean_sejm_api.py
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
from sejm_api_common import UNPUBLISHED, check_pin, release_stats, replace_all, split_release_rows
from sejm_api_speakers import FILTER_CSV, filter_speakers
SOURCE = "sejm_api"
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / SOURCE
# Pre-cut release files (the v0.2.5 files);
# artifacts/sejm_api_ontology_manifest.json records the fetch output, i.e. these.
INPUT_SHA256 = {
f"{SOURCE}.parquet": "56f7b03483488dec8f0fa145c6d26746926175d83096e9d1931e535aa81cf161",
f"{SOURCE}.attribution.jsonl": "4ab6513f8173498d403f7ec1a9534b8e0086264d3eca6ff9ac4f9c5dbca4c069",
f"{SOURCE}.stats.json": "edee610cdc0fcbc1c7015ed4f7d5dda74b549100cca5f410beaaf8ae3b0229c2",
}
FILTER_SHA256 = "402b11e331ad765c1964d6d9b3a99b685a75ee7150ba99d9423f165c05f7ada3" # sejm_api.speaker-filter.csv
ROW_GROUP_SIZE = 512 # the layout of the released file
def build(input_dir: Path, out_dir: Path) -> dict:
for name, sha in INPUT_SHA256.items():
check_pin(input_dir / name, sha, UNPUBLISHED)
table = pq.read_table(input_dir / f"{SOURCE}.parquet")
with (input_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as stream:
sidecar = [json.loads(line) for line in stream]
stats = json.loads((input_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
rows = table.to_pylist()
recomputed = release_stats(rows, sidecar)
if recomputed != {key: stats[key] for key in recomputed}:
raise SystemExit("the input stats.json does not describe the input Parquet")
rows, sidecar, counts = split_release_rows(rows, sidecar, tiktoken.get_encoding("cl100k_base"))
rows, sidecar, speakers = filter_speakers(rows, sidecar, input_dir / FILTER_CSV.format(source=SOURCE), FILTER_SHA256)
stats.update(release_stats(rows, sidecar))
stats["split_rows"] = counts["split_rows"]
stats["drop_short"] += counts["drop_short"]
stats["drop_dup"] += counts["drop_dup"]
stats["trailer_cut"] = {"input_sha256": INPUT_SHA256, **counts}
stats["drop_speaker"] = speakers["dropped_rows"]
stats["speaker_filter"] = speakers
drops = ("drop_before_start", "drop_dup", "drop_short", "drop_lang", "drop_ocr", "drop_speaker")
if stats["read"] + stats["split_rows"] - sum(stats[k] for k in drops) != stats["kept"]:
raise SystemExit("stats drop counts do not add up to the kept rows")
replace_all({
out_dir / f"{SOURCE}.parquet": lambda p: pq.write_table(
pa.Table.from_pylist(rows, schema=table.schema), p, compression="zstd", row_group_size=ROW_GROUP_SIZE),
out_dir / f"{SOURCE}.attribution.jsonl": lambda p: p.write_text(
"".join(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n" for line in sidecar), encoding="utf-8"),
out_dir / f"{SOURCE}.stats.json": lambda p: p.write_text(
json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8"),
})
return stats
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--data", type=Path, default=DATA, help="directory holding the (restored) input files; outputs are written there")
args = parser.parse_args()
print(json.dumps(build(args.data, args.data), indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()