polish-dynaword / src /clean_sejm_committee_transcripts.py
ppuzio's picture
parliamentary: rebuild from IPI PAN's PPC TEI dump, official speakers only (v0.2.6 rights audit) (#108)
ceb3dc0
Raw History Blame Contribute Delete
13.2 kB
#!/usr/bin/env python3
"""Keep only official speakers in the sejm_committee_transcripts shard (October 2026 rights audit).
Committee transcripts also hold statements by guests, experts and representatives of unions, NGOs
and companies, and anonymous "Głos z sali" interjections. Only statements by MPs, members of the
government, heads of constitutional organs and Sejm/Senate staff are official materials in the
sense of art. 4 pkt 2 of the Polish copyright act. The allowlist is
fetch_sejm_committee_transcripts.SPEAKER_RULES: a turn is kept only if its `author` label fully
matches one rule (or is one of the few typo labels in EXACT_LABELS), so an unrecognised label is
dropped.
The pre-filter shard started a turn only at a line that began with one of a few anchor words
("Poseł", "Minister", ...). Any other label ("Świadek ...", "Członek zarządu ...") never started a
turn, so a guest's label and speech sat inside the preceding official turn. The PDF cache of the
fetcher is not kept, so this script works on the pinned pre-filter release files and first re-cuts
every input turn with the same code that `parse_pdf()` uses on a fresh PDF:
1. Page-break blocks (page number + stenographer initials, "Pełny Zapis Przebiegu Posiedzenia:",
"Komisji ... (nr N)") are removed (`strip_page_blocks`); a word hyphenated across a block is
rejoined.
2. The turn is cut at every label line (`split_at_labels`). Piece 0, the text before the first
label, keeps the row id and author. The k-th later piece (k = 1, 2, ... in the turn, counted
before any piece is dropped) becomes its own row: author = the label (NFC, colon stripped),
id = "<original id>_<k>", every other field copied from the turn, so the sidecar line is
the turn's line with the new `speaker` and `id`. `turn_idx` and `content_sha1` stay those of the
input turn; ids are unique, `turn_idx` is not.
3. A piece shorter than 15 characters is dropped (rejected_too_short), then a piece equal to the
previous piece of its sitting (same author and text) is dropped (rejected_exact_dup, added to the
pinned count), as `build()` does.
4. Every piece is classified by `classify_speaker`; allowlisted pieces are kept, the rest are dropped
without a marker (rejected_not_official_speaker). A sitting without an official piece has no rows.
Stats: rows_split_out counts the extra rows made in step 2, so kept + rejected == rows_raw_extracted
+ rows_split_out. A piece whose text did not change keeps its stored token_count; every other piece
is counted again with tiktoken cl100k_base.
A fresh `build()` from the PDFs cuts at the same lines with the same code but does not know the
input turns: it numbers the cut turns consecutively ("..._<turn_idx>" without "_<k>") and hashes
the cut turns for `content_sha1`. The PDFs are not available here, so that equivalence of text,
author and order is by construction and not checked. The old indent test (a label line started within
6 columns of the margin) is gone from both, because the stored text has no indentation.
It also writes sejm_committee_transcripts.speaker-roles.csv, one row per distinct role label (the
speaker label with the person's name cut off), decision and rule, with piece and character counts.
The inputs are the pre-filter release files, pinned by SHA-256. Restore them before a rerun:
git checkout 0bbdb0d -- data/sejm_committee_transcripts/sejm_committee_transcripts.{parquet,attribution.jsonl,stats.json}
python3 src/clean_sejm_committee_transcripts.py
"""
from __future__ import annotations
import argparse
import csv
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
from fetch_sejm_committee_transcripts import (
ATTRIBUTION_KEYS, FIELDS, MIN_TURN_CHARS, SOURCE, SPEAKER_RULES, classify_speaker, count_tokens, dedup_turns,
shard_stats, split_at_labels, strip_page_blocks, turn_text)
from sejm_api_common import check_pin, replace_all, write_json
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / SOURCE
# Pre-filter release files (main at 0bbdb0d, added in Hub PR 37).
INPUT_SHA256 = {
f"{SOURCE}.parquet": "03ad043249a4ac1d5cb7ab68792fa62cae53066cfd8017ffd5ca42af6ab946b5",
f"{SOURCE}.attribution.jsonl": "d7277bad9abae279cd5b417e6504c9bcb17c832b41281991b2038489a5453f83",
f"{SOURCE}.stats.json": "e24f5c0fb638b54cb6b6c4086b95f0fb771cde714a60434a769f2376252b0831",
}
ROLES_CSV = f"{SOURCE}.speaker-roles.csv"
ROLES_HEADER = ["role", "decision", "rule", "turns", "characters", "speaker_labels"]
# ---- role label: the speaker label without the person's name (evidence table only; the filter
# itself never uses it). A name is a run of capitalised tokens, preceded by given names seen in
# the MPs' labels; whatever is left in front is the role.
_CAP, _LOW = "A-ZĄĆĘŁŃÓŚŹŻ", "a-ząćęłńóśźżéüöäèç"
_NAME_TOKEN = re.compile(rf"[{_CAP}][{_LOW}'’.]+(?:-[{_CAP}][{_LOW}'’]+)*|[{_CAP}]\.")
_PARTICLES = {"de", "von", "van", "vel", "di", "du", "la", "le", "da", "ter", "den", "der", "ibn", "bin", "al", "el"}
_PARTY_TAIL = re.compile(r"(.+?) \([^()]{1,60}\)((?: ?[–−-] ?.*)?)")
_MP_LABEL = re.compile(r"(?:Przewodnicząc\w+ |Wiceprzewodnicząc\w+ )?(?:Poseł|Posłanka|poseł|posłanka) (.+?) \([^)]+\)")
def given_names(labels) -> set[str]:
"""First names taken from the MP labels ("Poseł Jan Maria Kowalski (PARTY)")."""
names: set[str] = set()
for label in labels:
if match := _MP_LABEL.match(label):
names.update(match.group(1).split()[:-1])
return names
def role_of(label: str, given: set[str]) -> str:
"""`label` without the person's name: surname (with particles), then given names, are cut.
A party in parentheses ends the name of an MP label; what follows it (" – spoza składu
Komisji") stays with the role. A label whose last token is not a name ("Głos z sali") is
its own role."""
suffix = ""
if match := _PARTY_TAIL.fullmatch(label):
label, suffix = match.groups()
tokens = label.split()
cut = len(tokens) - 1
if cut < 1 or not _NAME_TOKEN.fullmatch(tokens[-1]):
return label + suffix
while cut - 1 >= 1 and tokens[cut - 1].lower() in _PARTICLES:
cut -= 1
if cut - 1 >= 1 and _NAME_TOKEN.fullmatch(tokens[cut - 1]):
cut -= 1
while cut - 1 >= 1 and tokens[cut - 1] in given:
cut -= 1
return " ".join(tokens[:cut]) + suffix
def roles_table(label_stats: dict, roles: dict | None = None) -> list[list]:
"""CSV rows from {key: (turns, characters, rule or None)}, biggest first.
`roles` maps each key to its role; without it the keys are speaker labels and the role is the
label without the person's name (role_of)."""
if roles is None:
given = given_names(label_stats)
roles = {label: role_of(label, given) for label in label_stats}
groups: dict[tuple[str, str, str], list[int]] = defaultdict(lambda: [0, 0, 0])
for key, (turns, characters, rule) in label_stats.items():
group = groups[(roles[key], "include" if rule else "exclude", rule or "")]
group[0] += turns
group[1] += characters
group[2] += 1
rows = [[role, decision, rule, *counts] for (role, decision, rule), counts in groups.items()]
return sorted(rows, key=lambda row: (-row[4], row[0], row[1], row[2]))
def write_roles(path: Path, rows: list[list]) -> None:
with path.open("w", encoding="utf-8", newline="") as stream:
writer = csv.writer(stream, lineterminator="\n")
writer.writerow(ROLES_HEADER)
writer.writerows(rows)
def cut_turn(row: dict, attribution: dict) -> tuple[list[dict], dict]:
"""(pieces, page-block counts) of one input turn (steps 1 and 2 of the module docstring).
A piece is the row fields and the sidecar fields in one dict; `token_count` is None where the
text is new and has to be counted."""
lines, counts = strip_page_blocks(row["text"].split("\n"))
pieces = []
for k, (label, body) in enumerate(split_at_labels(lines)):
piece = {**row, **attribution, "text": turn_text(body)}
if k:
piece.update(id=f"{row['id']}_{k}", author=label, speaker=label)
if k or piece["text"] != row["text"]:
piece["token_count"] = None
pieces.append(piece)
return pieces, counts
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 0bbdb0d -- 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()
if [r["id"] for r in rows] != [a["id"] for a in sidecar]:
raise SystemExit("the attribution sidecar does not line up with the input Parquet")
recomputed = shard_stats(rows, sidecar)
if recomputed != {key: stats[key] for key in recomputed}:
raise SystemExit("the input stats.json does not describe the input Parquet")
pieces, page_blocks = [], Counter()
for row, attribution in zip(rows, sidecar):
cut, counts = cut_turn(row, attribution)
pieces += cut
page_blocks.update(counts)
rows_split_out = len(pieces) - len(rows)
if len({p["id"] for p in pieces}) != len(pieces):
raise SystemExit("cutting the turns made duplicate ids")
long_enough = [p for p in pieces if len(p["text"]) >= MIN_TURN_CHARS]
too_short = len(pieces) - len(long_enough)
pieces, joint_dup, exact_dup = dedup_turns(long_enough)
if joint_dup:
raise SystemExit("the input holds a joint-sitting duplicate; it was deduplicated before")
new_text = [p for p in pieces if p["token_count"] is None]
for piece, tokens in zip(new_text, count_tokens([p["text"] for p in new_text])):
piece["token_count"] = tokens
rule_of = {label: classify_speaker(label) for label in {p["author"] for p in pieces}}
label_stats: dict[str, list] = {label: [0, 0, rule] for label, rule in rule_of.items()}
for piece in pieces:
entry = label_stats[piece["author"]]
entry[0] += 1
entry[1] += len(piece["text"])
kept = [p for p in pieces if rule_of[p["author"]]]
dropped = [p for p in pieces if not rule_of[p["author"]]]
kept_rows = [{field: p[field] for field in FIELDS} for p in kept]
kept_sidecar = [{key: p[key] for key in ATTRIBUTION_KEYS} | {"id": p["id"]} for p in kept]
removed = {"turns": len(dropped), "characters": sum(len(p["text"]) for p in dropped),
"tokens": sum(p["token_count"] for p in dropped),
"speaker_labels": sum(1 for rule in rule_of.values() if rule is None)}
kept_by_rule = {}
for rule_id, _ in SPEAKER_RULES:
matched = [entry for entry in label_stats.values() if entry[2] == rule_id]
kept_by_rule[rule_id] = {"speaker_labels": len(matched), "turns": sum(e[0] for e in matched),
"characters": sum(e[1] for e in matched)}
stats.update(shard_stats(kept_rows, kept_sidecar))
stats["rows_split_out"] = rows_split_out
stats["rejected_too_short"] = too_short
stats["rejected_exact_dup"] += exact_dup
stats["rejected_not_official_speaker"] = removed["turns"]
stats["rejected"] += too_short + exact_dup + removed["turns"]
stats["page_blocks"] = {"removed": page_blocks["blocks"], "hyphenated_words_rejoined": page_blocks["rejoined"],
"glued_footers_repaired": page_blocks["fused"],
"stray_footers_removed": page_blocks["lone_footers"]}
stats["speaker_allowlist"] = {"input_sha256": INPUT_SHA256, "removed": removed, "kept_by_rule": kept_by_rule}
if stats["kept"] + stats["rejected"] != stats["rows_raw_extracted"] + rows_split_out:
raise SystemExit("stats drop counts do not add up to the extracted rows")
replace_all({
out_dir / f"{SOURCE}.parquet": lambda p: pq.write_table(
pa.Table.from_pylist(kept_rows, schema=table.schema), p, compression="zstd"),
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 kept_sidecar), encoding="utf-8"),
out_dir / f"{SOURCE}.stats.json": lambda p: write_json(p, stats),
out_dir / ROLES_CSV: lambda p: write_roles(
p, roles_table({label: tuple(entry) for label, entry in label_stats.items()})),
})
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()