#!/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. The inputs are the pre-cut release files, pinned by SHA-256. Restore them before a rerun: git checkout 262df1b -- data/sejm_api/sejm_api.{parquet,attribution.jsonl,stats.json} 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 check_pin, release_stats, replace_all, split_release_rows SOURCE = "sejm_api" ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE # Pre-cut release files (main at 262df1b; the Parquet is the v0.2.5 file); # 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", } 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, f"restore it with `git checkout 262df1b -- data/{SOURCE}/{name}`") 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")) 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} drops = ("drop_before_start", "drop_dup", "drop_short", "drop_lang", "drop_ocr") 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()