"""Extract speaker turns from downloaded committee PDFs.""" import json, sys, pathlib, hashlib, re, concurrent.futures as cf from parse_zapis import parse_pdf CACHE = pathlib.Path("sejm_cache") OUTDIR = CACHE / "parsed"; OUTDIR.mkdir(parents=True, exist_ok=True) EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}") PESEL = re.compile(r"(? 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(m): nonlocal n; n += 1 return "[ADRES_EMAIL]" if "@" in m.group(0) else "[DANE_NUMERY]" text = EMAIL.sub(sub, text) text = PESEL.sub(lambda m: "[DANE_NUMERY]" if pesel_ok(m.group(1)) else m.group(0), text) text = NIP.sub(lambda m: "[DANE_NUMERY]" if nip_ok(m.group(1)) else m.group(0), text) text = REGON.sub(lambda m: "[DANE_NUMERY]" if regon_ok(m.group(1)) else m.group(0), text) text = PHONE.sub("[DANE_KONTAKTOWE]", text) text = IBAN.sub("[DANE_NUMERY]", text) return text, n def main(term: int): names = {} for t in (term,): comm = json.loads((CACHE / "api" / f"committees_term{t}.json").read_text(encoding="utf-8")) for c in comm: names[c["code"]] = c.get("name") or c.get("prettyName") or c["code"] jobs = [] dl = CACHE / "api" / f"dl_manifest_{term}.jsonl" for line in open(dl, 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)) print(f"term {term}: parsing {len(jobs)} PDFs", flush=True) dates = {} for f in sorted(CACHE.glob(f"api/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") out = OUTDIR / f"turns_{term}.jsonl" 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: return job, ("__fail__", None, repr(e)[:100]) with open(out, "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("\u241f".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"https://api.sejm.gov.pl/sejm/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]) if __name__ == "__main__": main(int(sys.argv[1]))