#!/usr/bin/env python3 """Fetch Sejm interpellations and written questions into a SpeakLeash-style .jsonl.zst for build_dynaword.py. Official parliamentary materials, outside copyright under art. 4 pkt 2 pr. aut., same legal basis as the shipped sejm_api shard. HTML body endpoints only — attachment-only replies (PDFs) and keyless prolongation stubs are skipped. Header chrome (nr / recipient / title / signatory / date) is stripped so it lives in meta, not text. PII regex-scrub runs before the line is written. Usage: python3 src/fetch_sejm_interpellations.py --out ~/speakleash python3 src/fetch_sejm_interpellations.py --out ~/speakleash --terms 10 --workers 4 python3 src/fetch_sejm_interpellations.py --out ~/speakleash --terms 10 --max-docs 30 """ from __future__ import annotations import argparse, json, re, subprocess, sys, time from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED from pathlib import Path from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen sys.path.insert(0, str(Path(__file__).resolve().parent)) from html_text import html_to_text from scrub_pii import scrub_pii API = "https://api.sejm.gov.pl" KEY = "sejm_interpellations" UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)", "Accept": "*/*"} MIN_CHARS = 200 DEFAULT_TERMS = (7, 8, 9, 10) # 1–6 time out; see artifacts/source_findings.md COLLECTIONS = ("interpellations", "writtenQuestions") _KIND = { ("interpellations", False): "interpellation", ("interpellations", True): "interpellation_reply", ("writtenQuestions", False): "written_question", ("writtenQuestions", True): "written_question_reply", } _COLLECTION = { "interpellation": "interpellations", "interpellation_reply": "interpellations", "written_question": "writtenQuestions", "written_question_reply": "writtenQuestions", } _HEAD = re.compile(r"(?is)
]*>.*?") _H1 = re.compile(r"(?is)]*class="[^"]*(?:int-recipient|int-title|intAuthor|' r'intDateTresc|intDate)[^"]*"[^>]*>.*?
' ) _AUTHOR_P = re.compile(r'(?is)]*class="[^"]*intAuthor[^"]*"[^>]*>(.*?)
') _AUTHOR_LABEL = re.compile(r"^(Zgłaszający|Odpowiadający):\s*", re.I) _ATTACH_LINE = re.compile( r"(?i)^(?:Treść odpowiedzi znajduje się w załączniku\.?|Załączniki|" r"\(podpisane elektronicznie\).*|.*\.pdf)\s*$" ) def should_fetch_reply(reply: dict | None) -> bool: if not reply: return False key = reply.get("key") if not key: return False return not reply.get("onlyAttachment") def body_url(term, collection, num, reply=None) -> str: base = f"{API}/sejm/term{term}/{collection}/{num}" if reply: return f"{base}/reply/{reply['key']}/body" return f"{base}/body" def _author_from_html(html: str) -> str: m = _AUTHOR_P.search(html) if not m: return "" return _AUTHOR_LABEL.sub("", html_to_text(m.group(1))).strip() def extract_body(html: str) -> str: html = _HEAD.sub("", html) html = _H1.sub("", html) html = _META_P.sub("", html) text = html_to_text(html) lines = [ln for ln in text.splitlines() if not _ATTACH_LINE.match(ln.strip())] return "\n".join(lines).strip() def normalize_document(kind: str, item: dict, html: str, reply: dict | None = None): """Listing item + body HTML → {text, meta}, or None if thin / stub.""" text = extract_body(html) text, _ = scrub_pii(text) if len(text) < MIN_CHARS: return None collection = _COLLECTION[kind] term = item.get("term") num = item.get("num") author = _author_from_html(html) if not author and reply: author = (reply.get("from") or "").strip() date = (reply or {}).get("receiptDate") or item.get("receiptDate") or "" meta = { "url": body_url(term, collection, num, reply), "term": term, "num": num, "kind": kind, "title": item.get("title") or "", "date": date, "author": author, } if reply: meta["reply_key"] = reply.get("key") or "" return {"text": text, "meta": meta} def _get(url, tries=4): last = None for i in range(tries): try: with urlopen(Request(url, headers=UA), timeout=45) as r: return r.read(), dict(r.headers) except (HTTPError, URLError, TimeoutError) as e: last = e if isinstance(e, HTTPError) and e.code in (404, 500): break time.sleep(1.5 * (i + 1)) return None, {"error": repr(last)} def _get_json(url): raw, hdrs = _get(url) if raw is None: return None, hdrs return json.loads(raw), hdrs def iter_listing(term, collection, page_size): offset = 0 while True: url = f"{API}/sejm/term{term}/{collection}?limit={page_size}&offset={offset}" items, hdrs = _get_json(url) if items is None: raise RuntimeError(f"list failed after retries: {url} ({hdrs.get('error')})") if not items: return yield from items offset += len(items) if len(items) < page_size: return def _jobs_for_item(item): jobs = [(False, None)] for reply in item.get("replies") or []: if should_fetch_reply(reply): jobs.append((True, reply)) return jobs def _fetch_job(term, collection, item, reply): url = body_url(term, collection, item.get("num"), reply) raw, hdrs = _get(url) if raw is None: return url, None, hdrs.get("error") kind = _KIND[(collection, bool(reply))] rec = normalize_document(kind, item, raw.decode("utf-8", "replace"), reply) return url, rec, None def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="~/speakleash") ap.add_argument("--terms", default="7,8,9,10", help="comma-separated Sejm terms (default 7-10)") ap.add_argument("--collections", default="interpellations,writtenQuestions") ap.add_argument("--page-size", type=int, default=50) ap.add_argument("--workers", type=int, default=4, help="parallel body fetches (default 4)") ap.add_argument("--max-docs", type=int, default=0, help="stop after N kept rows") args = ap.parse_args(argv) workers = max(1, args.workers) terms = [int(t) for t in args.terms.split(",") if t.strip()] collections = [c.strip() for c in args.collections.split(",") if c.strip()] out_dir = Path(args.out).expanduser() out_dir.mkdir(parents=True, exist_ok=True) jsonl = out_dir / f"{KEY}.jsonl" done = set() if jsonl.exists(): for ln in jsonl.open(encoding="utf-8"): try: done.add(json.loads(ln)["meta"]["url"]) except Exception: pass print(f"resume: {len(done):,} already fetched") kept = seen = skipped = finished = 0 t0 = time.time() stop = False def consume(fut, fo): nonlocal kept, skipped, finished url, rec, err = fut.result() done.add(url) finished += 1 if err: skipped += 1 print(f" WARN skip {url} {err}", file=sys.stderr, flush=True) elif rec: fo.write(json.dumps(rec, ensure_ascii=False) + "\n") fo.flush() kept += 1 else: skipped += 1 if finished % 200 == 0: print(f" seen {seen:,} kept {kept:,} skip {skipped:,} " f"{finished / max(time.time() - t0, 1):.1f}/s", flush=True) with jsonl.open("a", encoding="utf-8") as fo, \ ThreadPoolExecutor(max_workers=workers) as pool: pending = set() limit = max(workers * 4, workers) def drain(block=False): nonlocal pending if not pending: return if block: finished = pending wait(finished) else: finished, pending = wait(pending, return_when=FIRST_COMPLETED) for fut in finished: if not block: pending.discard(fut) consume(fut, fo) if block: pending = set() print(f"workers={workers}", flush=True) for term in terms: if stop: break for collection in collections: if stop: break print(f"term {term} {collection}", flush=True) for item in iter_listing(term, collection, args.page_size): if stop: break for is_reply, reply in _jobs_for_item(item): url = body_url(term, collection, item.get("num"), reply) seen += 1 if url in done: continue pending.add(pool.submit( _fetch_job, term, collection, item, reply, )) if len(pending) >= limit: drain() if args.max_docs and kept >= args.max_docs: stop = True break if stop: break drain(block=True) print(f"fetched {kept:,} new docs ({skipped:,} skipped); compressing...", flush=True) subprocess.run( ["zstd", "-19", "-f", "--rm", str(jsonl), "-o", str(out_dir / f"{KEY}.jsonl.zst")], check=True, ) print(f"wrote {out_dir / (KEY + '.jsonl.zst')} in {round(time.time() - t0)}s") return 0 if __name__ == "__main__": raise SystemExit(main())