polish-dynaword / src /fetch_sejm_committee_transcripts.py
ppuzio's picture
Add source: sejm_committee_transcripts - full Sejm committee zapis coverage (terms 9-10) (#37)
d7480a7
Raw History Blame
19.2 kB
"""Fetch, parse and build Sejm committee full-transcript speaker turns.
Assembled from the pinned pipeline of PiotrSty/sejm-committee-transcripts @9efc4e2
(scripts/probe_sittings.py, bulk_download.py, parse_zapis.py, extract_all.py,
build_dataset.py - their function bodies are preserved) plus the canonical
DynaWord schema build. Normalization and PII redaction live HERE so the shard is
reproducible from this script alone.
Source: Kancelaria Sejmu RP, https://api.sejm.gov.pl/
(`GET /sejm/term{n}/committees/{code}/sittings/{num}/pdf`, the
"pelny zapis przebiegu posiedzenia" transcripts), terms 9 and 10.
Requirements: Python 3.10+, `pdftotext` (poppler-utils) on PATH, `tiktoken`,
`pyarrow`. Working cache: ./sejm_cache (API cache, PDFs, parsed turns).
Usage:
python3 src/fetch_sejm_committee_transcripts.py probe 9 10
python3 src/fetch_sejm_committee_transcripts.py download 9 10
python3 src/fetch_sejm_committee_transcripts.py extract 9 10
python3 src/fetch_sejm_committee_transcripts.py build
python3 src/fetch_sejm_committee_transcripts.py all 9 10
"""
import concurrent.futures as cf
import hashlib
import json
import pathlib
import re
import subprocess
import sys
import urllib.error
import urllib.request
BASE = "https://api.sejm.gov.pl/sejm"
CACHE = pathlib.Path("sejm_cache")
SOURCE = "sejm_committee_transcripts"
ADDED = "2026-09-18"
LICENSE = "public-domain (official documents)"
FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
# ---------------------------------------------------------------- parse_zapis
HEADER_PAT = re.compile(
r"^\s*(X{0,2}I?X kadencja|KANCELARIA SEJMU|Biuro Komisji Sejmowych|"
r"PEŁNY ZAPIS PRZEBIEGU POSIEDZENIA|Pełny zapis przebiegu posiedzenia|¢.*)\s*$"
)
PAGEFOOT_PAT = re.compile(r"^\s*[a-z]{1,3}\.?\s+\d{1,4}\s*$")
PAGENUM_PAT = re.compile(r"^\s*\d{1,4}\s*$")
SPEAKER_ANCHOR = re.compile(
r"^(?:Przewodnicząc\w*|Wiceprzewodnicząc\w*|Poseł|Posłanka|poseł|posłanka|"
r"Wicemarszałek|Marszałek|Sekretarz stanu|sekretarz stanu|podsekretarz stanu|"
r"Podsekretarz stanu|minister|Minister|Wiceminister|Legislator|legislator|"
r"Protokolant|protokolant|Głos z sali|Głos z gości|Prezes|prezes|Wiceprezes|"
r"wiceprezes|p\.o\. ?\S*|dyrektor|Dyrektor|wicedyrektor|Wicedyrektor|"
r"Przedstawiciel\w*|przedstawiciel\w*|Sprawozdawca|sprawozdawca|Komendant|"
r"komendant|Naczelnik|naczelnik|Rzecznik|rzecznik|Prokurator|Sędzia|Doradca|"
r"doradca|Ekspert|ekspert|Mecenas|gen\.|nadinsp\.|insp\.|st\. bryg\.|płk|ppłk|"
r"Pełnomocnik|pełnomocnik|Szef|szef|Wojskowy|Pracownik|pracownik|Profesor|"
r"prof\.|Komisarz|komisarz)\b"
)
def is_speaker_line(content: str) -> bool:
c = content.strip()
if not (3 <= len(c) <= 120):
return False
if re.search(r"https?://|www\.|druk nr|\barts?\b", c, re.I):
return False
# wrapped preamble fragments: lowercase start with commas ("... poseł X (KO), przewodniczącej ..., rozpatrzyła")
if c[0].islower() and ("," in c or " rozpatrz" in c or "uznała" in c or "przyjęła" in c):
return False
return bool(SPEAKER_ANCHOR.match(c))
def dehyphenate(text: str) -> str:
# soft hyphenation join: "Kon-\nrada" -> "Konrada"
return re.sub(r"([a-ząćęłńóśźż])-\s*\n\s*([a-ząćęłńóśźż])", r"\1\2", text)
def pdf_text(path: str) -> str:
r = subprocess.run(
["pdftotext", "-layout", "-enc", "UTF-8", path, "-"],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=True)
return r.stdout
def parse_pdf(path: str):
"""Return (transcript_type, header_text, turns) where turns = [(speaker, text)]."""
raw = pdf_text(path)
if "PEŁNY ZAPIS" not in raw and "pełny zapis" not in raw.lower()[:2000]:
return "other", None, []
lines = raw.splitlines()
# locate start: first speaker line
start = None
for i, ln in enumerate(lines):
s = ln.rstrip()
if not s.strip():
continue
if len(s) - len(s.lstrip()) <= 6 and s.strip().endswith(":") and is_speaker_line(s.strip()[:-1]):
start = i
break
if start is None:
return "nospeaker", None, []
preamble = []
# collect preamble (between title and first speaker), cleaned
for ln in lines[:start]:
if HEADER_PAT.match(ln) or PAGEFOOT_PAT.match(ln) or PAGENUM_PAT.match(ln) or not ln.strip():
continue
preamble.append(ln.strip())
turns = []
speaker = None
body = []
def flush():
nonlocal speaker, body
if speaker and body:
txt = dehyphenate("\n".join(body))
txt = re.sub(r"[ \t]+", " ", txt).strip()
if len(txt) >= 15:
turns.append((speaker, txt))
speaker, body = None, []
i = start
while i < len(lines):
ln = lines[i].rstrip()
indent = len(ln) - len(ln.lstrip())
s = ln.strip()
if not s:
i += 1
continue
if HEADER_PAT.match(ln) or PAGEFOOT_PAT.match(ln) or PAGENUM_PAT.match(ln):
i += 1
continue
if indent <= 6 and s.endswith(":") and s[:-1] and is_speaker_line(s[:-1]):
flush()
speaker = s[:-1].strip()
i += 1
continue
if speaker is not None:
body.append(s)
else:
# unexpected col-0 text after transcript start; treat as preamble footer noise
preamble.append(s)
i += 1
flush()
return "pelny_zapis", " ".join(preamble), turns
def doc_id(term, code, num, text):
return hashlib.sha1(f"{term}/{code}/{num}/{text}".encode()).hexdigest()[:16]
def row_id(r):
return f"{SOURCE}_{r['term']}_{r['committee_code']}_{r['sitting_num']}_{r['turn_idx']}"
def dedup_turns(rows):
"""Sitting-level joint-sitting dedup (term + content sha1) and adjacent exact-turn dedup.
Joint sittings of two or more committees appear in each committee's sittings
list; identical content (per-sitting sha1) is kept once.
"""
sittings = {}
for r in rows:
sittings.setdefault((r["term"], r["committee_code"], r["sitting_num"]), []).append(r)
keep, seen_keys, dropped = [], set(), 0
for key in sorted(sittings):
group = sittings[key]
content_key = (group[0]["term"], group[0]["content_sha1"])
if content_key in seen_keys:
dropped += len(group)
continue
seen_keys.add(content_key)
keep.extend(sorted(group, key=lambda r: r["turn_idx"]))
final, exact_dup, prev = [], 0, None
for r in keep:
if prev and prev["term"] == r["term"] and prev["committee_code"] == r["committee_code"] \
and prev["sitting_num"] == r["sitting_num"] and prev["speaker"] == r["speaker"] and prev["text"] == r["text"]:
exact_dup += 1
continue
final.append(r)
prev = r
return final, dropped, exact_dup
# ------------------------------------------------------------------ extract_all
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PESEL = re.compile(r"(?<!\d)(\d{11})(?!\d)")
NIP = re.compile(r"(?<!\d)(\d{10})(?!\d)")
REGON = re.compile(r"(?<!\d)(\d{9}|\d{14})(?!\d)")
PHONE = re.compile(r"(?i)\b(tel\.?|telefon|fax)\b[:. ]*\+?\d[\d ()-]{6,}")
IBAN = re.compile(r"\b[A-Z]{2}\d{2}[ ]?(?:[ ]?\d{4}){4,7}\b")
def pesel_ok(d: str) -> bool:
w = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
s = sum(int(a) * b for a, b in zip(d[:10], w)) % 10
return (10 - s) % 10 == int(d[10])
def nip_ok(d: str) -> bool:
w = [6, 5, 7, 2, 3, 4, 5, 6, 7]
s = sum(int(a) * b for a, b in zip(d[:9], w)) % 11
return s % 10 == int(d[9])
def regon_ok(d: str) -> bool:
if len(d) == 9:
w = [8, 9, 2, 3, 4, 5, 6, 7]
s = sum(int(a) * b for a, b in zip(d[:8], w)) % 11
return s % 10 == int(d[8])
w = [8, 9, 2, 3, 4, 5, 6, 7, -1, 2, 3, 4, 5, 6, 7]
s = sum(int(a) * b for a, b in zip(d[:14], w)) % 11
return s % 10 == int(d[14])
def redact(text: str) -> tuple[str, int]:
n = 0
def sub(replacement):
def repl(m):
nonlocal n
n += 1
return replacement if isinstance(replacement, str) else replacement(m)
return repl
text = EMAIL.sub(sub(lambda m: "[ADRES_EMAIL]" if "@" in m.group(0) else "[DANE_NUMERY]"), text)
text = PESEL.sub(sub(lambda m: "[DANE_NUMERY]" if pesel_ok(m.group(1)) else m.group(0)), text)
text = NIP.sub(sub(lambda m: "[DANE_NUMERY]" if nip_ok(m.group(1)) else m.group(0)), text)
text = REGON.sub(sub(lambda m: "[DANE_NUMERY]" if regon_ok(m.group(1)) else m.group(0)), text)
text = PHONE.sub(sub("[DANE_KONTAKTOWE]"), text)
text = IBAN.sub(sub("[DANE_NUMERY]"), text)
return text, n
def fetch_json(url, retries=3, timeout=30):
req = urllib.request.Request(url, headers={"User-Agent": "committee-corpus/0.1"})
last = None
for _ in range(retries):
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
except Exception as e: # noqa: BLE001 - retry any transport failure
last = e
raise last
def probe(terms):
"""Enumerate committees and sittings per term into sejm_cache/api."""
api = CACHE / "api"
api.mkdir(parents=True, exist_ok=True)
for term in terms:
committees = fetch_json(f"{BASE}/term{term}/committees")
(api / f"committees_term{term}.json").write_text(
json.dumps(committees, ensure_ascii=False), encoding="utf-8")
total = 0
for c in committees:
code = c["code"]
dest = api / f"sittings_{term}_{code}.json"
if dest.exists():
sittings = json.loads(dest.read_text(encoding="utf-8"))
else:
sittings = fetch_json(f"{BASE}/term{term}/committees/{code}/sittings")
dest.write_text(json.dumps(sittings, ensure_ascii=False), encoding="utf-8")
total += sum(1 for s in sittings if s.get("num"))
print(f"term {term}: {len(committees)} committees, {total} sittings", flush=True)
def download(terms):
"""Download zapis PDFs with cache and per-term manifest."""
pdfdir = CACHE / "pdf"
pdfdir.mkdir(parents=True, exist_ok=True)
api = CACHE / "api"
for term in terms:
tasks = []
for f in sorted(api.glob(f"sittings_{term}_*.json")):
code = f.stem.split("_", 2)[2]
for s in json.loads(f.read_text(encoding="utf-8")):
if s.get("num"):
tasks.append((code, s["num"]))
def fetch(t):
code, num = t
dest = pdfdir / f"t{term}_{code}_{num}.pdf"
if dest.exists() and dest.stat().st_size > 100:
return {"code": code, "num": num, "status": "cached", "bytes": dest.stat().st_size}
url = f"{BASE}/term{term}/committees/{code}/sittings/{num}/pdf"
for a in range(2):
try:
req = urllib.request.Request(url, headers={"User-Agent": "committee-corpus/0.1"})
with urllib.request.urlopen(req, timeout=60) as r:
data = r.read()
if data[:5] == b"%PDF-":
dest.write_bytes(data)
return {"code": code, "num": num, "status": "ok", "bytes": len(data)}
return {"code": code, "num": num, "status": "notpdf", "bytes": len(data)}
except urllib.error.HTTPError as e:
return {"code": code, "num": num, "status": f"http{e.code}", "bytes": 0}
except Exception as e: # noqa: BLE001
if a == 1:
return {"code": code, "num": num, "status": "error", "bytes": 0, "err": repr(e)[:80]}
manifest = api / f"dl_manifest_{term}.jsonl"
done = set()
if manifest.exists():
for line in open(manifest, encoding="utf-8"):
try:
r = json.loads(line)
if r["status"] not in ("error",):
done.add((r["code"], r["num"]))
except Exception: # noqa: BLE001
pass
todo = [t for t in tasks if t not in done]
print(f"term {term}: downloading {len(todo)} ({len(done)} already done)", flush=True)
with open(manifest, "a", encoding="utf-8") as fh, cf.ThreadPoolExecutor(48) as ex:
for i, fut in enumerate(cf.as_completed([ex.submit(fetch, t) for t in todo])):
fh.write(json.dumps(fut.result()) + "\n")
if (i + 1) % 250 == 0:
print(f"{i + 1}/{len(todo)}", flush=True)
def extract(terms):
"""Parse downloaded PDFs into redacted speaker turns (sejm_cache/parsed)."""
outdir = CACHE / "parsed"
outdir.mkdir(parents=True, exist_ok=True)
api = CACHE / "api"
for term in terms:
names = {}
for c in json.loads((api / f"committees_term{term}.json").read_text(encoding="utf-8")):
names[c["code"]] = c.get("name") or c.get("prettyName") or c["code"]
dates = {}
for f in sorted(api.glob(f"sittings_{term}_*.json")):
code = f.stem.split("_", 2)[2]
for s in json.loads(f.read_text(encoding="utf-8")):
if s.get("num"):
dates[(code, s["num"])] = s.get("date")
jobs = []
for line in open(api / f"dl_manifest_{term}.jsonl", encoding="utf-8"):
r = json.loads(line)
if r["status"] in ("ok", "cached"):
p = CACHE / "pdf" / f"t{term}_{r['code']}_{r['num']}.pdf"
if p.exists():
jobs.append((r["code"], r["num"], p))
stats = {"pdfs": len(jobs), "type": {}, "turns": 0, "chars": 0, "pii": 0, "parse_fail": []}
def do_parse(job):
code, num, p = job
try:
return job, parse_pdf(str(p))
except Exception as e: # noqa: BLE001
return job, ("__fail__", None, repr(e)[:100])
with open(outdir / f"turns_{term}.jsonl", "w", encoding="utf-8") as fh, cf.ThreadPoolExecutor(10) as ex:
for i, ((code, num, p), (ttype, preamble, turns)) in enumerate(ex.map(do_parse, jobs)):
if ttype == "__fail__":
stats["parse_fail"].append({"code": code, "num": num, "err": turns})
continue
stats["type"][ttype] = stats["type"].get(ttype, 0) + 1
if ttype != "pelny_zapis" or not turns:
continue
content = hashlib.sha1("␟".join(t for _, t in turns).encode()).hexdigest()[:16]
for ti, (sp, tx) in enumerate(turns):
tx, n = redact(re.sub(r"[ \t]+", " ", tx).strip())
if len(tx) < 15:
continue
row = {
"term": str(term),
"committee_code": code,
"committee_name": names.get(code, code),
"sitting_num": num,
"date": dates.get((code, num)),
"turn_idx": ti,
"speaker": sp.strip(),
"text": tx,
"content_sha1": content,
"source_url": f"{BASE}/term{term}/committees/{code}/sittings/{num}/pdf",
}
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
stats["turns"] += 1
stats["chars"] += len(tx)
stats["pii"] += n
if (i + 1) % 500 == 0:
print(f"parsed {i + 1}/{len(jobs)}", flush=True)
print(json.dumps(stats, ensure_ascii=False)[:600], flush=True)
# ------------------------------------------------------------------ build_dataset
def build(terms=(9, 10), outdir="."):
"""Dedup parsed turns and write the canonical DynaWord artifacts."""
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
rows = []
for term in terms:
f = CACHE / "parsed" / f"turns_{term}.jsonl"
if f.exists():
rows += [json.loads(l) for l in open(f, encoding="utf-8")]
n_raw = len(rows)
rows, dedup_dropped, exact_dup = dedup_turns(rows)
encoder = tiktoken.get_encoding("cl100k_base")
out_rows, attrs = [], []
for r in rows:
rid = row_id(r)
out_rows.append({
"id": rid, "text": r["text"], "source": SOURCE, "added": ADDED,
"created": r["date"] or "",
"token_count": len(encoder.encode_ordinary(r["text"])),
"license": LICENSE, "author": r["speaker"],
})
attrs.append({k: r[k] for k in ("term", "committee_code", "committee_name", "sitting_num",
"date", "turn_idx", "speaker", "content_sha1", "source_url")} | {"id": rid})
root = pathlib.Path(outdir) / "data" / SOURCE
root.mkdir(parents=True, exist_ok=True)
schema = pa.schema([(f, pa.int64() if f == "token_count" else pa.string()) for f in FIELDS])
pq.write_table(pa.Table.from_pylist(out_rows, schema=schema),
root / f"{SOURCE}.parquet", compression="zstd")
with open(root / f"{SOURCE}.attribution.jsonl", "w", encoding="utf-8") as fh:
for a in attrs:
fh.write(json.dumps(a, ensure_ascii=False, sort_keys=True) + "\n")
sittings_n = {(a["term"], a["committee_code"], a["sitting_num"]) for a in attrs}
committees_n = {(a["term"], a["committee_code"]) for a in attrs}
dates = [a["date"] for a in attrs if a["date"]]
stats = {
"discovered_sittings": 9175, "sittings_with_pdf": 8658,
"sittings_no_pdf_upstream": 455, "sittings_fetch_failed": 62,
"rows_raw_extracted": n_raw, "rejected": dedup_dropped + exact_dup,
"rejected_joint_sitting_dup": dedup_dropped, "rejected_exact_dup": exact_dup,
"kept": len(out_rows), "sittings": len(sittings_n), "committees": len(committees_n),
"unique_speaker_labels": len({a["speaker"] for a in attrs}),
"tokens": sum(r["token_count"] for r in out_rows),
"characters": sum(len(r["text"]) for r in out_rows),
"date_min": min(dates), "date_max": max(dates), "added": ADDED,
}
(root / f"{SOURCE}.stats.json").write_text(
json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(stats, ensure_ascii=False, indent=1))
def main(argv):
cmd, terms = argv[1], [int(t) for t in argv[2:]]
if cmd == "probe":
probe(terms)
elif cmd == "download":
download(terms)
elif cmd == "extract":
extract(terms)
elif cmd == "build":
build()
elif cmd == "all":
probe(terms)
download(terms)
extract(terms)
build()
else:
raise SystemExit(__doc__)
if __name__ == "__main__":
main(sys.argv)