"""parliamentary: the Polish Parliamentary Corpus (PPC) rebuilt from IPI PAN's speaker-labelled TEI dump. Upstream: the per-term TEI zips that the PPC page (https://clip.ipipan.waw.pl/PPC) links, dump of 2025-05-21 (https://kdp.ipipan.waw.pl/static/ppcdump-tei/-tei.zip), pinned below by size and SHA-256. It replaces the earlier unlabelled copy of PPC taken from SpeakLeash (`PPC_corpus`), whose committee transcripts mixed guests' statements with the official speakers' (polish-dynaword-v2#54, option C). Scope (polish-dynaword-v2#54, decided 2026-10-07: "1A / 2A but document / 3 A / 4A / 5 A"): - 1A: every term of the dump, 1919-2025, except the Sejm of 2019-2023 and 2023-2027 (DROP_PREFIXES), which sejm_api, sejm_committee_transcripts and sejm_interpellations cover. Kept: the Sejm and Senate of the Second Republic, the Krajowa Rada Narodowa and the Sejm of the PRL, the Sejm and Senate since 1989 and the Senate of 2019-2025. - 2A: in sittings (plenary and committee) only turns by MPs and senators, members of the government, heads of constitutional organs and Sejm/Senate staff are kept: the sejm_committee_transcripts allowlist (classify_speaker) plus PPC_RULES below, each with its evidence. Everything else is dropped, among it committee guests, witnesses of investigative committees, the President's Chancellery (KPRP), heads of agencies other than the constitutional organs, the Government Legislation Centre (RCL), ministry departments and the heads of state ("Naczelnik Państwa", "Prezydent RP"). - 3A: the allowlist applies to plenary sittings too. - 4A: interpellations, questions and the government's replies are kept whole (no speaker filter). - 5A: this source stays the dedup reference of sejm_api_2011_2022 (clean_sejm_api_2011_2022.py re-pins it). Speakers. A sitting's header lists its speakers (): role (roleName), forenames and surnames. PPC strips the party tags that the base allowlist keys MPs on, so a person is classified by role + a placeholder name ("Jan Maria Kowalski"), never by its own name: a role that swallows words of a name ("Minister Spraw Zagranicznych Ukrainy" + a name) then fails because the placeholder no longer fits a 2-3 token name. The person's own name that is not a 1-3 token name ("bad_name": "Piotr Van der Coghen", "Jan Bury s. Antoniego", "Artur Płokszto z Litwy") is kept only if it is, or starts with, the name of an MP, senator or marshal of the same zip (is_member, the check a named committee chair gets). Labels that are free text (persName without parts, and speaker lines inside a turn, "Poseł Kowalski:") are classified as they stand but kept only when the name closing them belongs to a speaker the header keeps in the same zip (absorption guard). Stage directions (the "komentarz" speaker): a bracketed direction ("(Oklaski)") is kept; any other komentarz turn is kept only as the continuation of a kept speaker in the same turn block; a komentarz that contains ": " (an interjection "Głos z sali: ...") is always dropped. Encoding (fix_encoding): some 2007-2011 interpellation records are Windows-1250 text decoded as ISO-8859-2 ("Nawišzujšc", "\x9cwiadczeń"); they are re-decoded. A few other records carry stray C1 controls next to correct text ("\x9fródło", "U\x9aackas"); those lines are repaired. Exact duplicates (same text after both repairs and redaction) keep their first copy in MANIFEST then document order; each dropped id and the id kept in its place go to parliamentary.decisions.jsonl. Usage: python3 src/fetch_parliamentary.py [--dump DIR] [--out DIR] [--download] [--workers N] """ from __future__ import annotations import argparse import datetime import functools import hashlib import json import os import re import shutil import sys import unicodedata import urllib.request import xml.etree.ElementTree as ET import zipfile from collections import Counter, defaultdict from concurrent.futures import ProcessPoolExecutor from pathlib import Path from clean_sejm_committee_transcripts import role_of, roles_table, write_roles from fetch_sejm_committee_transcripts import ( _GOVERNMENT_BODY, _MINISTRY_ABBREVIATION, _MINISTRY_WORDS, _NAME, _NOT_STATE_SECRETARY, _LO, _OFFICE_WORD, _STATE_OFFICE, _STATE_PREFIX, _STATE_RANK, _STATE_SECRETARY_WORDS, _TOK, _UP, FIELDS, LICENSE, classify_speaker, count_tokens, is_label, redact, ) from sejm_api_common import MIN_CHARS, PARLIAMENTARY_SEJM_END, sha256_file, write_json SOURCE = "parliamentary" ADDED = "2026-06-15" DUMP_URL = "https://kdp.ipipan.waw.pl/static/ppcdump-tei/{term}-tei.zip" # (term, bytes, sha256) of the 2025-05-21 dump, as downloaded on 2026-10-07. MANIFEST = ( ("1919-1922", 218013940, "6be0273eccd20989add49e1ca106c5724b64c89c38f9a20f92e97c0dfca1011e"), ("1922-1927", 333034736, "2fcfa873fb45e5f6647889f6fe7417990b3aab6824ebc839f22699a139a15fa0"), ("1928-1930", 107456995, "2816f20b487636e2a879298dfa2fe15d7226641ed8a7f5df3d93fd09985bf9b6"), ("1930-1935", 200928182, "be98a5636958b01be0a0197a6905e812045a282889378b3541839dbfeb1e025f"), ("1935-1938", 126925493, "ce3440542eb757e7decf43e16d8a3f0266ee329f35df28bd180867b936de5f94"), ("1938-1939", 29077576, "d3d115b3298b43d5df405bb8a3ab39ef247c2806af27289f857d71695d9711d6"), ("1943-1947", 575193, "e15f69b186107cd545ad6f1b099fec89a0993a504f02a275b297da9bcf59ba80"), ("1947-1952", 75320036, "0d9f1d60cdf8e6f425f6b5f86d655eb1ca9a5ec935cc6e51696d74ae5506aced"), ("1952-1956", 32602235, "8e5c0be0092bb94b57f8e6fb51ad2b88f434d28f0619b7b55a308b4f587b0730"), ("1957-1961", 76796260, "be2297b8de8ba5f95b7ed88172b3123bcf81d07c4f8611d1f334ba309e01ded3"), ("1961-1965", 39972140, "839599ae0ca23ccebd142a94ddaf41b047e29dc86d7606cc56b094c61775646b"), ("1965-1969", 60609250, "ce81e6ed59e4f1a6b67feab64230ed9d29e795a5e5000dd73181505d93074360"), ("1969-1972", 16901879, "18c6eddef1941d859b16b7e2ad72383e23953ee571a593a19610d01c657206cd"), ("1972-1976", 70960374, "f6d2ba032f47db38cb5ac8ccf8c72299ea43543f52fe70f9e8102fedf103ed4c"), ("1976-1980", 82719414, "2ccd2cc4e4b8bdc627c393419244988f0842c03523e1c4b8ce85f59aeb414f7d"), ("1980-1985", 305014407, "ec844f2968fb091ccbb1efaf9cc2730900b37aad4208e16876fe785926cd103b"), ("1985-1989", 283699561, "94eb7a73f0e688582001d0687e4aeaa87f0d55258715caba07b570a02c431ff6"), ("1989-1991", 322944949, "16aadc2ef1813d1a695049571da3c5af540655e2a82698f955fe382846d4cbbf"), ("1991-1993", 290833981, "1ceebebde162dcc7e26994de8420518809d67c33cd92220a4fb01ef703f00c7d"), ("1993-1997", 2083076422, "e7cd0805b1c2156de66335af389e59d72d728ba59eceeb331168ea162c654ad3"), ("1997-2001", 2596857801, "d9f71ce6899cf29746abceef0c8f4eb990c36e1a59c7c4677c131a65fede7cd9"), ("2001-2005", 3029260742, "6a4e409c7173b1f607dec87c932f69a2f6a254cc4fb28905de09f9b26c30b9b9"), ("2005-2007", 1504583970, "eb0670e07302b03417073fddc2b7d6f253d646f7f05b8d4c0a044837d42950ea"), ("2007-2011", 3613775393, "239a2d617440d9a1b47dc6d26c53d80d6399579bebb688887406e4ff31f62c92"), ("2011-2015", 4119031719, "7b0f823562137e4d07dbaa3ef7ff1519f6f36d79350a5e319aef64ae3dcabccf"), ("2015-2019", 3909365702, "79ef4c1845c37c3c08d569daf8066ba6b130d9ad6f7d1000db5a937fdfbfe5e6"), ("2019-2023", 2086326237, "21d987b939728c08fa9d08df37fb3851f321b49b5da0102c59ef5e7eb2629932"), ("2023-2027", 792882488, "61716f169d4378b158a54fb3f6c93c4ee69b876fab04811807d16bd0c435578c"), ) DROP_PREFIXES = ("2019-2023/sejm/", "2023-2027/sejm/") # 1A: the sejm_* sources cover the Sejm from term 9 # Interpellations of terms 3-7 carry no date: `created` is the term (Sejm terms, first to last day). UNDATED_TERM_RANGES = { "3": "1997-10-20, 2001-10-18", "4": "2001-10-19, 2005-10-18", "5": "2005-10-19, 2007-11-04", "6": "2007-11-05, 2011-11-07", "7": "2011-11-08, 2015-11-11", } T = "{http://www.tei-c.org/ns/1.0}" XID = "{http://www.w3.org/XML/1998/namespace}id" PLACEHOLDER = " Jan Maria Kowalski" # P3: role + a 3-token name stands in for the person's own name PLACEHOLDER_2 = " Jan Kowalski" # P2: only for committee secretaries, whose rule takes exactly two tokens COMMENTARY = "komentarz" REDACTION_TAGS = re.compile(r"\[(?:ADRES_EMAIL|DANE_NUMERY|DANE_KONTAKTOWE)\]") _C1 = re.compile("[\u0080-\u009f]") _POLISH = re.compile("[ąśźĄŚŹ]") # the letters Windows-1250 and ISO-8859-2 encode differently _MISDECODED = re.compile("[\u0080-\u009fšĽ]") # cp1250 ś ź Ś Ź -> C1, ą -> š, Ą -> Ľ # Stray C1 controls in otherwise correct text, from the census of the dump (2026-10-08): cp1250 bytes # (\x9c ś, \x9a š "Milo\x9aević", \x8e Ž "\x8eiburys", \x96 en dash), and two that cp1250 leaves unassigned, # so they say nothing about a line's encoding: \x88 for č ("Poto\x88nik", "Virvi\x88ius") and \x98, a stray # byte ("Gr\x98ünbaum"). _NOT_CP1250 = str.maketrans({"\x88": "č", "\x98": ""}) _C1_MAP = str.maketrans({"\x9c": "ś", "\x9f": "ź", "\x8c": "Ś", "\x8f": "Ź", "\x9a": "š", "\x8e": "Ž", "\x8a": "Š", "\x96": "–"}) _DATE_PART = re.compile(r"(?:(\d{4})-)?(?:(\d{2})-)?(\d{2})") # ------------------------------------------------------------------ PPC rules (2A) # Chars below are the census of the whole dump (2026-10-07, utterance text of the label, all terms). # Historic ministry words ("Minister Skarbu", "Minister Wyznań Religijnych i Oświecenia Publicznego", # "Minister Przemysłu Chemicznego") and "RP" ("Minister Finansów RP") on top of the base list. _PPC_MINISTRY_WORDS = _MINISTRY_WORDS + "|" + "|".join(( "RP skarbu państwa transportu opieki budownictwa przekształceń własnościowych ochrony zasobów naturalnych " "przestrzennej gospodarczej współpracy zagranicą handlu wewnętrznego usług inwestycji łączności " "regionalnego wyznań religijnych oświecenia publicznego reform rolnych żywnościowej oświaty wychowania " "komunikacji wojskowych sztuki płac socjalnych chemicznego lekkiego hutnictwa terenowej poczt telegrafów " "socjalnej rynku energetyki zagranicznego spożywczego skupu materiałów budowlanych górnictwa maszynowego " "robót publicznych aprowizacji techniki kombatantów mieszkalnictwa pomocy postępu naukowo-technicznego " "ciężkiego węglowego leśnictwa komunalnej").split()) # Titles that may stand before a name ("Poseł ks. Kowalski", "Minister gen. Sikorski", "Poseł p. Kowalski"). _HON = r"(?: (?:ks\.?|gen\.|dr\.?|p\.|ob\.|prof\.|inż\.|mgr))*" _PERSON = rf",?{_HON} (?:{_NAME}|{_TOK})" # A free label whose name follows a title ("Poseł ob. Ochab", "Prezes Rady Ministrów ob. Osóbka-Morawski"): the # title marks where the name starts, so the role before it can take the placeholder like a header person's. # The Krajowa Rada Narodowa (1943-47) has only such labels, no structured persons for the name guard. _TITLED = re.compile(rf"(?P.+ (?:ks\.?|gen\.|dr\.?|p\.|ob\.|prof\.|inż\.|mgr)) (?P{_NAME}|{_TOK})") # a full name or a lone surname, optionally after a comma _MINISTER = rf"Minist(?:er|ra)(?:[ ,–-]+(?i:{_PPC_MINISTRY_WORDS}))*" _PREMIER = r"(?:Wice)?[Pp]rezes (?:Rady Ministrów|RM)|Prezydent Ministrów|Wicepremier" # No marker of the President's Chancellery, of local government or of other bodies sharing a word. _NOT_SURNAME_ONLY = (r"(?!.*(?:Minist|Prezes|Premier|Wicepremier|Marsza|Sekretarz|Podsekretarz|Poseł|Senator" r"|[Rr]eferent|Przewodnicz|Sprawozd|Kierown|Dyrekt|Genera|Prokur))") _SENATE_UNIT = (r"(?:Biurze Legislacyjnym|Dziale Petycji i Korespondencji w Biurze " r"(?:Analiz, Dokumentacji i Korespondencji|Analiz i Petycji|Komunikacji Społecznej))") _SENATE_STAFF = (r"(?:Główn[ya] |Starsz[ya] )?(?:Legislator(?:ka)?|Ekspert(?:ka)?(?: do [Ss]praw " r"(?:Legislacji|Oceny Skutków Regulacji))?|[Ss]pecjalist(?:a|ka)) w " + _SENATE_UNIT) _PPC_STATE_BODY = (rf"(?:[ ,–-]+(?:(?i:{_STATE_SECRETARY_WORDS}|{_PPC_MINISTRY_WORDS}|urzędzie|urzędu)" rf"|{_MINISTRY_ABBREVIATION}|URM))*") _CHAIR_OF = r"(?: (?:Komisji|Podkomisji)(?: [^\W\d_]+,?){0,12})?" # The base deputy chair with a capital "Przewodniczącego" too (Senate committees 2015-2023, 2.89M chars). _PPC_CHAIR_DEPUTY = r"(?:(?:[Pp]ierwsz[ya]|[Dd]rug[ia]) )?[Zz]astęp(?:ca|czyni) [Pp]rzewodnicząc(?:ego|ej)" # (rule id, pattern matched with fullmatch, (system, house) the rule is limited to; None = any). After the # base allowlist; first match wins. PPC_RULES = [ # MPs without a party tag (PPC drops it): "Poseł Jan Kowalski", "Poseł Sprawozdawca Jan Kowalski", # "Posłanka Wiceprzewodnicząca Anna Nowak", "Sekretarz poseł Jan Kowalski", "Sprawozdawca p. Kowalski", # "Przewodniczący poseł ob. Szwalbe" (KRN, 32.6k chars), "Sekretarz Poseł Jan Kowalski" (1993-2019, 1.97M), # the typo "Poeł Jan Kowalski" (707k). # A "Poseł" label is an MP's by its own words; in 1919-39 often surname-only ("Poseł Nowicki"). ("mp_no_party", re.compile( rf"(?:[Pp]oseł|[Pp]osłanka|Poeł)(?: (?:[Ss]prawozdawca|[Ww]nioskodawca|[Ss]ekretarz|(?:[Ww]ice)?[Pp]rzewodnicząc[ya]))?{_PERSON}" rf"|(?:Sekretarz|Sprawozdawca|(?:[Ww]ice)?[Pp]rzewodnicząc[ya])(?: [Pp]oseł| [Pp]osłanka| p\.){_PERSON}"), (None, None)), # The Sejm of 1919-39 prints MPs as "P. Nowicki" (6.77M chars). Checked: the plenary text announces the # same people as MPs ("Głos ma poseł Nowicki" before "P. Nowicki"). Not when the label names an office. ("mp_surname_1919_1939", re.compile(rf"P\.{_HON} {_NOT_SURNAME_ONLY}(?:{_NAME}|{_TOK})"), ("II RP", "Sejm")), ("senator_no_party", re.compile( rf"(?:Senator|Senatorka)(?: (?:[Ss]ekretarz|[Ss]prawozdawca|RP))?{_PERSON}"), (None, None)), # The Senate of 1922-39 prints senators as "S. Karnicka" (1.51M chars), announced as "Głos ma s. Karnicka". # ("P." in the Senate, 17k chars, is "Pan" and stays out.) ("senator_surname_1919_1939", re.compile(rf"S\.{_HON} {_NOT_SURNAME_ONLY}(?:{_NAME}|{_TOK})"), ("II RP", "Senat")), # The chamber's own marshals without "Sejmu"/"Senatu" ("Marszałek", "Wicemarszałek Jan Kowalski", # "Marszałek Senior", the 1919 typo "Marszalek poseł Ferdynand Radziwiłł"), never a voivodeship marshal. ("marshal_no_house", re.compile( r"(?!.*(?i:wojew|sejmik|zarząd|SSWW))(?:Wicemarszałkini|(?:Wice)?[Mm]arsza[łl]ek)(?:[- ][Ss]enior)?" r"(?: (?:Sejmu|Senatu)(?: (?:RP|Rzeczypospolitej Polskiej|Ustawodawczego|PRL))?)?(?: poseł)?,?" rf"{_HON}(?: (?:{_NAME}|{_TOK}))?"), (None, None)), # Members of the government before 1989 and since, under their historic titles: "Prezes Rady Ministrów, # Minister Spraw Wewnętrznych Jan Kowalski", "Prezydent Ministrów" (1919-21), "Wicepremier", "Kierownik # Ministerstwa Skarbu", "Minister - Szef Urzędu Rady Ministrów", "Minister - Członek Rady Ministrów". ("government_historic", re.compile( rf"(?:{_PREMIER})(?:,? (?:i )?{_MINISTER})?{_PERSON}|{_MINISTER}{_PERSON}" rf"|Kierownik Ministerstwa(?:[ ,–-]+(?i:{_PPC_MINISTRY_WORDS}))+{_PERSON}" rf"|Minist(?:er|ra) ?[—–-] ?(?:[Ss]zef Urzędu Rady Ministrów|Kierownik|Członek Rady Ministrów)(?: {_OFFICE_WORD}){{0,14}}{_PERSON}" rf"|Szef Urzędu Rady Ministrów{_PERSON}"), (None, None)), # Secretaries/undersecretaries of state as in the base rule, with the historic ministry words and the # Urząd Rady Ministrów (the PM's chancellery before KPRM) as a government body. The President's # Chancellery stays out (_NOT_STATE_SECRETARY). ("state_secretary_historic", re.compile( rf"(?!.*{_NOT_STATE_SECRETARY})(?=.*(?:{_GOVERNMENT_BODY}|Urzęd\w* Rady Ministrów|URM))" rf"(?:(?:{_STATE_PREFIX})?{_STATE_RANK}{_PPC_STATE_BODY}(?:{_STATE_OFFICE} {_NAME}|{_PERSON})" rf"|{_NAME} {_STATE_RANK}{_PPC_STATE_BODY})"), (None, None)), # Sejm and Senate legislative and petitions staff. Evidence (chars): Senate "Główny Legislator w Biurze # Legislacyjnym w Kancelarii Senatu" 10.79M, "Ekspert do spraw Legislacji" 1.59M, "Główny Ekspert" 771k, # "Starszy Legislator" 466k, petitions specialists ~3.6M, "Kancelarii Senatu" without "w" 100k, OSR 77k; # Sejm "Przedstawiciel Biura Legislacyjnego KS" 4.87M (named 3.88M), "Przedstawicielka" 1.49M + 733k, # "Kancelarii Sejmu" forms 325k + 81k, "Legislator w BL KS" 79k. ("legislative_petitions_staff", re.compile( rf"Przedstawiciel(?:ka)? Biura Legislacyjnego (?:KS|Kancelarii (?:Sejmu|Senatu))(?:,? {_NAME})?" rf"|Dyrektor Biura Legislacyjnego Kancelarii Sejmu, {_NAME}" rf"|Legislator(?:ka)? w BL KS {_NAME}" rf"|{_SENATE_STAFF}(?: w)? Kancelarii Senatu {_NAME}" rf"|Kierownik Działu Petycji i Korespondencji w Biurze Komunikacji Społecznej w Kancelarii Senatu {_NAME}"), (None, None)), # The same Senate staff without "Kancelarii Senatu" (102k chars), only in the Senate's own transcripts. ("legislative_petitions_staff", re.compile(rf"{_SENATE_STAFF} {_NAME}"), (None, "Senat")), # A committee chair named in the label: kept only if the same forenames and surnames are an MP or a # senator in the same term (chair_is_member); a foreign or ministry committee's chair is not. ("committee_chair_named", re.compile( rf"(?:Wice)?[Pp]rzewodnicząc[ya]{_CHAIR_OF}(?: obradom)?{_PERSON}|{_PPC_CHAIR_DEPUTY}{_CHAIR_OF}{_PERSON}"), (None, None)), ] MEMBER_RULES = {"mp", "senator", "sejm_senate_marshal", "mp_committee_chair", "mp_no_party", "mp_surname_1919_1939", "senator_no_party", "senator_surname_1919_1939", "marshal_no_house"} STAGE_DIRECTION = re.compile(r"\(.*\)\.?") # A plenary header name that _NAME refuses but that still makes its MP a member: 2-4 tokens, a particle that # may take "der" ("Piotr Van der Coghen"), no lowercase word ("Artur Płokszto z Litwy"). _LONG_NAME = re.compile(rf"{_TOK}(?: (?:(?:[Vv]el|de|von|van)(?: der)? )?{_TOK}){{1,3}}") _CAMEL = re.compile(rf"(?<=[{_LO}])(?=[{_UP}][{_LO}])") # two parts run together: "JanuszPalikot" def _classify(label, system, house): rule = classify_speaker(label) if rule: return rule for rule_id, pattern, (only_system, only_house) in PPC_RULES: if only_system in (None, system) and only_house in (None, house) and pattern.fullmatch(label): return rule_id return None @functools.lru_cache(maxsize=None) def classify_label(label, system, house): """(rule id or None, whether a leading "P. " was cut) of a PPC speaker label in NFC. In 1919-39 "P." also stands for "Pan" before an office ("P. Minister Skarbu ..."): when nothing matches, the label is classified again without it.""" label = unicodedata.normalize("NFC", label) rule = _classify(label, system, house) if rule is None and system == "II RP" and label.startswith("P. "): rule = _classify(label[3:], system, house) return rule, rule is not None return rule, False def sitting_days(date): """ISO days of a : "1938-11-28", or a multi-day sitting as the dump writes it ("1938-11-28 i 29", "1990-09-12, 13 i 14", "1952-07-31 i 08-01", "1989-07-28, 29, 31 i 1989-08-01"); a short part takes the year and month of the part before it. Anything else raises.""" days, year, month = [], None, None for part in re.split(r",\s*|\s+i\s+", date): match = _DATE_PART.fullmatch(part) if not match or (year is None and not match[1]) or (match[1] and not match[2]): raise ValueError(f"unexpected date {date!r}") year, month = match[1] or year, match[2] or month days.append(datetime.date(int(year), int(month), int(match[3])).isoformat()) return days def _redecode(text): """Windows-1250 text that was decoded as ISO-8859-2 back to what it said; raises if it cannot be.""" return text.encode("iso-8859-2").decode("cp1250") def fix_encoding(text): """(text, repair): "redecoded" when no line has a correct ą/ś/ź, "lines" when only some lines are broken.""" if not _MISDECODED.search(text): return text, None if not _POLISH.search(text): # a legitimate "š" (Milošević) never comes without any ą/ś/ź in Polish text return _redecode(text), "redecoded" if not _C1.search(text): return text, None lines = [] for line in text.split("\n"): line = line.translate(_NOT_CP1250) if _C1.search(line) and not _POLISH.search(line): line = _redecode(line) lines.append(line.replace("\x80\x93", "–").translate(_C1_MAP)) return "\n".join(lines), "lines" def collapse(text): return " ".join(text.split()) def note(bibl, kind): element = bibl.find(f"{T}note[@type='{kind}']") return collapse(element.text or "") if element is not None else "" # ------------------------------------------------------------------ speakers class Speakers: """The speakers of one zip: per-person verdicts, plus the names the free-label guard trusts.""" def __init__(self, stats): self.stats = stats self.members = set() # name_key() of every MP/senator/marshal, any doc of the zip self.kept_names = set() # "Forename Surname" of every kept structured person self.kept_labels = set() def structured(self, person, system, house): """(label, role, rule or None, reason, key) of a header person (rule None: dropped).""" pn = person.find(f"{T}persName") label = collapse(" ".join(pn.itertext())) if pn is not None else "" if person.get(XID) == COMMENTARY: return COMMENTARY, COMMENTARY, None, "commentary", None if not label: return label, "(no role)", None, "no_label", None parts = {child.tag for child in pn} if collapse(pn.text or "") or not parts or parts - {f"{T}roleName", f"{T}forename", f"{T}surname"}: return label, None, None, "free", None # classified by free(), after every structured person role = collapse(" ".join(collapse(e.text or "") for e in pn.findall(f"{T}roleName"))) forenames = tuple(collapse(e.text or "") for e in pn.findall(f"{T}forename")) # PPC's party strip leaves a cut tag as one more surname ("Czerniawski", "(niez"; 1,850 persons): # a surname part starting with "(" is never a name. surnames = tuple(s for e in pn.findall(f"{T}surname") if (s := collapse(e.text or "")) and not s.startswith("(")) name = " ".join(forenames + surnames) if not name: # A role alone ("Marszałek", "Przedstawiciel Związku Harcerstwa Polskiego"): it must match both # as it stands and with the placeholder name, so a role ending in capitalised words is no name. rule, stripped = classify_label(role + PLACEHOLDER, system, house) if rule and classify_label(role, system, house)[0]: return label, role, rule, "role_only", None return label, role, None, "role_only_unmatched", None if not role: return label, "(no role)", None, "no_role", None rule, stripped = classify_label(role + PLACEHOLDER, system, house) self.stats["persons_p_strip"] += stripped if rule is None and re.fullmatch(rf"{_TOK} {_TOK}", name) \ and classify_label(role + PLACEHOLDER_2, system, house)[0] == "sejm_committee_secretary": rule = "sejm_committee_secretary" self.stats["persons_p2_fallback"] += 1 if not re.fullmatch(rf"{_NAME}|{_TOK}", name): # the rule stands only if scan_headers finds a member return label, role, rule, "bad_name", (forenames, surnames) return label, role, rule, "structured" if rule else "unmatched", (forenames, surnames) def free(self, label, system, house): """Rule of a free-text label (a header persName without parts, a speaker line inside a turn). Kept only when it matches a rule other than committee_chair_named (which needs a structured name) and either names a speaker the zip's headers keep (the label itself, or its last 1-3 tokens as a name) or has a title before the name (_TITLED) and its role takes the placeholder. Guards against "Minister Spraw Zagranicznych Ukrainy Borys Tarasiuk", "Marszałek Polski Józef Piłsudski", where a role absorbs words that the rules take for a name.""" rule = classify_label(label, system, house)[0] if rule is None or rule == "committee_chair_named": return None, "free_unmatched" tokens = label.split() if label in self.kept_labels or any(" ".join(tokens[-k:]) in self.kept_names for k in (1, 2, 3)): return rule, "free" titled = _TITLED.fullmatch(label) if titled and classify_label(titled["role"] + PLACEHOLDER, system, house)[0] == rule: return rule, "free_titled" return None, "free_guard" def name_key(key): """Casefolded name tokens of a (forenames, surnames) key, without punctuation and one-letter tokens.""" name = _CAMEL.sub(" ", " ".join(key[0] + key[1]).replace("\xad", "")) tokens = (t.strip(":;,.\\/()–-") for t in name.casefold().split()) return tuple(t for t in tokens if len(t) > 1) def is_member(key, members): """The name is a member's, or starts with one ("Jan Bury s. Antoniego", "Jerzy Eysymontt niez").""" tokens = name_key(key) return tokens in members or any(tokens[:n] in members for n in range(len(tokens) - 1, 1, -1)) def chair_is_member(rule, key, members): """A role-only chair ("Przewodniczący Komisji Spraw Zagranicznych", key None) has no name to check.""" return rule != "committee_chair_named" or (key is not None and is_member(key, members)) # ------------------------------------------------------------------ documents def doc_meta(z, d): header = ET.fromstring(z.read(d + "header.xml")) bibl = header.find(f".//{T}sourceDesc/{T}bibl") date_el = bibl.find(f"{T}date") date = collapse(date_el.text or "") if date_el is not None else "" meta = {k: note(bibl, k) for k in ("system", "house", "type", "termNo")} if date: try: days = sitting_days(date) # a sitting over several days (21 shapes in 1922-1991) is a range except ValueError as error: raise ValueError(f"{d}: {error}") from error created = min(days) if len(set(days)) == 1 else f"{min(days)}, {max(days)}" elif meta["termNo"] in UNDATED_TERM_RANGES and "/interpelacje/" in d: created = UNDATED_TERM_RANGES[meta["termNo"]] else: raise ValueError(f"{d}: no date and no term range for term {meta['termNo']!r}") authors = "; ".join(collapse(" ".join(a.itertext())) for a in bibl.findall(f"{T}author")) return header, meta | {"date": date, "created": created, "author": authors} def interpellation_text(z, d): root = ET.fromstring(z.read(d + "text_structure.xml")) return "\n".join(t for p in root.iter(f"{T}p") if (t := collapse("".join(p.itertext())))) def sitting_text(z, d, meta, persons, speakers, acc): """Kept utterances of a sitting joined by "\\n", the labels of their speakers, dropped characters. `persons` maps an utterance's @who to [label, role, rule, reason, key]. The loop runs per body child (a
turn block, or a lone ): a komentarz continues the speaker before it in the same block only.""" system, house = meta["system"], meta["house"] kept, labels, dropped = [], {}, 0 body = ET.fromstring(z.read(d + "text_structure.xml")).find(f".//{T}body") def count(label, role, rule, text, keep): nonlocal dropped stat = acc["labels"][(role, label, rule if keep else None)] stat[0] += 1 stat[1] += len(text) if keep: kept.append(text) labels.setdefault(label, None) acc["stats"]["kept_chars_by_rule"][rule] += len(text) else: dropped += len(text) for block in body: current = None # (label, role, rule) of the turn going on switch = None # (who, label, role, rule) of a speaker line inside a turn for u in ([block] if block.tag == f"{T}u" else block.iter(f"{T}u")): who = (u.get("who") or "").lstrip("#") text = collapse("".join(u.itertext())) if not text: continue if switch and who not in (COMMENTARY, switch[0]): switch = None line = text[:-1].strip() if text.endswith(":") and (is_label(line) or classify_label(line, system, house)[0]): rule, reason = speakers.free(line, system, house) acc["stats"]["inline_labels"][reason] += 1 current = (line, role_of(line, set()), rule) switch = (who, *current) acc["stats"]["dropped_chars"]["inline_label_line"] += len(text) dropped += len(text) continue if who == COMMENTARY: if ": " in text: kind, keep = "komentarz_colon", False elif STAGE_DIRECTION.fullmatch(text): kind, keep = "stage_direction", True elif current is None: kind, keep = "komentarz_unattributed", False else: kind, keep = ("komentarz_continuation", True) if current[2] else ("komentarz_continuation_dropped", False) acc["stats"]["komentarz"][kind] += len(text) if not keep: acc["stats"]["dropped_chars"][kind] += len(text) count(COMMENTARY, COMMENTARY, kind, text, keep) continue if switch: speaker = switch[1:] elif who in persons: speaker = persons[who][:3] else: speaker = ("", "(unknown who)", None) acc["stats"]["dropped_chars"]["unknown_who"] += len(text) current = speaker label, role, rule = speaker if not rule and who in persons and not switch: acc["stats"]["dropped_chars"]["speaker:" + persons[who][3]] += len(text) elif not rule and switch: acc["stats"]["dropped_chars"]["inline_speaker"] += len(text) count(label, role, rule, text, bool(rule)) return kept, list(labels), dropped def scan_headers(z, docs, speakers, stats): """Pass 1: the verdict on every person of the zip's sittings, and the zip's member set. Headers of docs under DROP_PREFIXES count too: a chair of 2019-2023 is checked against that term's MPs. A member rule makes its person a member; with a name _NAME refuses only in a plenary sitting, where a "Poseł" is an MP, and only for a _LONG_NAME (a committee's "Poseł ... z Litwy" is a foreign guest).""" raw = {} for d in docs: if "/interpelacje/" in d: continue header, meta = doc_meta(z, d) persons = {} for person in header.iter(f"{T}person"): label, role, rule, reason, key = speakers.structured(person, meta["system"], meta["house"]) persons[person.get(XID)] = [label, role, rule, reason, key] if rule in MEMBER_RULES and (reason == "structured" or ( reason == "bad_name" and "/posiedzenia/" in d and _LONG_NAME.fullmatch(" ".join(key[0] + key[1])))): speakers.members.add(name_key(key)) raw[d] = (meta, persons) for d, (meta, persons) in raw.items(): for record in persons.values(): label, role, rule, reason, key = record if rule and reason == "bad_name": if is_member(key, speakers.members): record[3] = "bad_name_member" else: record[2] = rule = None if rule and not chair_is_member(rule, key, speakers.members): record[2], record[3] = None, "chair_not_member" if record[2]: speakers.kept_labels.add(label) if key: speakers.kept_names.add(" ".join(key[0] + key[1])) for d, (meta, persons) in raw.items(): for record in persons.values(): if record[3] == "free": record[2], record[3] = speakers.free(record[0], meta["system"], meta["house"]) record[1] = role_of(record[0], set()) if not d.startswith(DROP_PREFIXES): stats["persons"][record[3]] += 1 return raw def process_zip(job): """Pass 1 + pass 2 over one zip; writes /parts/.parquet and .jsonl, returns the tallies.""" term, size, sha, dump, out = job import pyarrow as pa import pyarrow.parquet as pq path = Path(dump) / f"{term}-tei.zip" if path.stat().st_size != size or sha256_file(path) != sha: raise SystemExit(f"{path} does not match the pinned size/SHA-256; rerun with --download") stats = {k: Counter() for k in ("dropped_docs", "dropped_chars", "kept_chars_by_rule", "komentarz", "inline_labels", "persons")} stats |= {"persons_p_strip": 0, "persons_p2_fallback": 0} # the row tallies are merge()'s, after the dedup acc = {"stats": stats, "labels": defaultdict(lambda: [0, 0])} speakers = Speakers(stats) schema = pa.schema([(f, pa.int64() if f == "token_count" else pa.string()) for f in FIELDS]) parts = Path(out) / "parts" with zipfile.ZipFile(path) as z: names = set(z.namelist()) docs = sorted(n[:-len("header.xml")] for n in names if n.endswith("/header.xml")) raw = scan_headers(z, docs, speakers, stats) writer = pq.ParquetWriter(parts / f"{term}.parquet", schema, compression="zstd") attribution = open(parts / f"{term}.jsonl", "w", encoding="utf-8") batch = [] def flush(): for (row, _), tokens in zip(batch, count_tokens([row["text"] for row, _ in batch])): row["token_count"] = tokens if batch: writer.write_table(pa.Table.from_pylist([r for r, _ in batch], schema=schema)) for _, line in batch: attribution.write(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n") batch.clear() for d in docs: if d.startswith(DROP_PREFIXES): stats["dropped_docs"]["prefix_sejm_2019_2027"] += 1 continue if d + "text_structure.xml" not in names: stats["dropped_docs"]["no_text_structure"] += 1 continue kind = "interpellation" if "/interpelacje/" in d else "sitting" if kind == "interpellation": _, meta = doc_meta(z, d) text, speakers_kept, dropped = interpellation_text(z, d), [], 0 else: meta, persons = raw[d] lines, speakers_kept, dropped = sitting_text(z, d, meta, persons, speakers, acc) text = "\n".join(lines) if not text: stats["dropped_docs"][f"empty_{kind}"] += 1 continue text, repair = fix_encoding(text) text, _ = redact(text) if len(text) < MIN_CHARS: # its turns stay counted under their rule: dropped_chars is the allowlist's stats["dropped_docs"][f"short_{kind}"] += 1 continue docid = d.rstrip("/").rsplit("/", 1)[1] row = {"id": f"{SOURCE}_{docid}", "text": text, "source": SOURCE, "added": ADDED, "created": meta["created"], "token_count": 0, "license": LICENSE, "author": meta["author"]} line = {"id": row["id"], "ppc_path": d.rstrip("/"), "term": term, "system": meta["system"], "house": meta["house"], "type": meta["type"], "term_no": meta["termNo"], "date": meta["date"], "created": meta["created"], "speakers": speakers_kept, "kept_characters": len(text), "dropped_characters": dropped, "author": meta["author"], "encoding_repair": repair} batch.append((row, line)) if len(batch) >= 500: flush() flush() writer.close() attribution.close() return term, stats, dict(acc["labels"]) # ------------------------------------------------------------------ download, merge def download(dump): """Fetch any zip that is missing or the wrong size; a fresh download must match its SHA-256.""" dump.mkdir(parents=True, exist_ok=True) for term, size, sha in MANIFEST: path = dump / f"{term}-tei.zip" if path.exists() and path.stat().st_size == size: continue part = path.with_name(path.name + ".part") request = urllib.request.Request(DUMP_URL.format(term=term), headers={"User-Agent": "polish-dynaword"}) with urllib.request.urlopen(request, timeout=120) as response, open(part, "wb") as fh: shutil.copyfileobj(response, fh, 1 << 20) if part.stat().st_size != size or sha256_file(part) != sha: raise SystemExit(f"{part}: size or SHA-256 differs from the 2025-05-21 dump") os.replace(part, path) def merge(out, results): """Concatenate the per-zip parts in MANIFEST order, keeping the first copy of each text; sum the tallies.""" import pyarrow.parquet as pq root, parts = Path(out) / "data" / SOURCE, Path(out) / "parts" root.mkdir(parents=True, exist_ok=True) tally = {k: Counter() for k in ("docs_by_category", "chars_by_category", "encoding_repair")} tally |= dict.fromkeys(("kept", "chars", "tokens", "authors_with_value", "redactions"), 0) extremes = {k: {} for k in ("date_min", "date_max", "created_min", "created_max")} ids, first, duplicates, writer = set(), {}, 0, None with open(root / f"{SOURCE}.attribution.jsonl", "w", encoding="utf-8") as attribution, \ open(root / f"{SOURCE}.decisions.jsonl", "w", encoding="utf-8") as decisions: for term, _, _ in MANIFEST: table = pq.read_table(parts / f"{term}.parquet") with open(parts / f"{term}.jsonl", encoding="utf-8") as fh: lines = [json.loads(line) for line in fh] keep = [] for i, (rid, text, tokens, line) in enumerate(zip( table.column("id").to_pylist(), table.column("text").to_pylist(), table.column("token_count").to_pylist(), lines, strict=True)): if rid in ids or rid != line["id"]: raise SystemExit(f"duplicate or misaligned id {rid}") ids.add(rid) digest = hashlib.sha256(text.encode("utf-8")).digest() if digest in first: decisions.write(json.dumps({"id": rid, "duplicate_of": first[digest]}) + "\n") duplicates += 1 continue first[digest] = rid keep.append(i) attribution.write(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n") category = f"{line['system']}|{line['house']}|{line['type']}" tally["kept"] += 1 tally["chars"] += len(text) tally["tokens"] += tokens tally["authors_with_value"] += bool(line["author"]) tally["redactions"] += len(REDACTION_TAGS.findall(text)) # redact()'s tags: the dump has none tally["docs_by_category"][category] += 1 tally["chars_by_category"][category] += len(text) if line["encoding_repair"]: tally["encoding_repair"][line["encoding_repair"]] += 1 house, created = line["house"], line["created"].split(", ") for key, value, pick in (("created_min", created[0], min), ("created_max", created[-1], max)) + ( (("date_min", created[0], min), ("date_max", created[-1], max)) if line["date"] else ()): extremes[key][house] = pick(extremes[key].get(house, value), value) if writer is None: writer = pq.ParquetWriter(root / f"{SOURCE}.parquet", table.schema, compression="zstd") writer.write_table(table.take(keep)) writer.close() labels, total, scalars = defaultdict(lambda: [0, 0, None]), defaultdict(Counter), Counter() for term, stats, label_stats in results: for key, (turns, chars) in label_stats.items(): labels[key][0] += turns labels[key][1] += chars labels[key][2] = key[2] for k, v in stats.items(): if isinstance(v, Counter): total[k].update(v) else: scalars[k] += v total["dropped_docs"]["exact_duplicate"] = duplicates rows = roles_table({key: tuple(v) for key, v in labels.items()}, {key: key[0] for key in labels}) write_roles(root / f"{SOURCE}.speaker-roles.csv", rows) stats = { "license": LICENSE, "licenses": {LICENSE: tally["kept"]}, "created_min": min(extremes["created_min"].values()), "created_max": max(extremes["created_max"].values()), **{f"{k}_by_house": dict(sorted(v.items())) for k, v in extremes.items()}, "added": ADDED, "dump": "2025-05-21", "drop_prefixes": list(DROP_PREFIXES), "sejm_coverage_end": PARLIAMENTARY_SEJM_END, **{k: dict(sorted(v.items())) for k, v in total.items()}, **dict(scalars), **{k: dict(sorted(v.items())) if isinstance(v, Counter) else v for k, v in tally.items()}, } write_json(root / f"{SOURCE}.stats.json", stats) shutil.rmtree(parts) return stats def build(dump, out, workers): (Path(out) / "parts").mkdir(parents=True, exist_ok=True) jobs = sorted(((t, s, h, str(dump), str(out)) for t, s, h in MANIFEST), key=lambda j: -j[1]) # largest first with ProcessPoolExecutor(workers) as pool: results = list(pool.map(process_zip, jobs)) return merge(out, results) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--dump", type=Path, default=Path("ppc-tei-20250521")) parser.add_argument("--out", type=Path, default=Path(".")) parser.add_argument("--download", action="store_true", help="fetch missing zips from kdp.ipipan.waw.pl") parser.add_argument("--workers", type=int, default=min(12, os.cpu_count() or 1)) args = parser.parse_args(argv) if args.download: download(args.dump) stats = build(args.dump, args.out, args.workers) print(json.dumps({k: stats[k] for k in ("kept", "chars", "tokens", "created_min", "created_max")}, indent=1)) if __name__ == "__main__": sys.exit(main())