polish-dynaword / src /fetch_sejm_interpellations.py
ppuzio's picture
Move PII scrubbing to SlayerLab/NERGAL (#38)
e519157
Raw
History Blame Contribute Delete
8.56 kB
#!/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 scrubbing is SlayerLab/NERGAL, not this repo.
Usage:
python3 src/fetch_sejm_interpellations.py --out ~/speakleash
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 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
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)<head[^>]*>.*?</head>")
_H1 = re.compile(r"(?is)<h1[^>]*>.*?</h1>")
_META_P = re.compile(
r'(?is)<p[^>]*class="[^"]*(?:int-recipient|int-title|intAuthor|'
r'intDateTresc|intDate)[^"]*"[^>]*>.*?</p>'
)
_AUTHOR_P = re.compile(r'(?is)<p[^>]*class="[^"]*intAuthor[^"]*"[^>]*>(.*?)</p>')
_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)
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 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("--max-docs", type=int, default=0, help="stop after N kept rows")
args = ap.parse_args(argv)
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 = 0
t0 = time.time()
with jsonl.open("a", encoding="utf-8") as fo:
for term in terms:
for collection in collections:
print(f"term {term} {collection}", flush=True)
for item in iter_listing(term, collection, args.page_size):
jobs = [(False, None)]
for reply in item.get("replies") or []:
if should_fetch_reply(reply):
jobs.append((True, reply))
for is_reply, reply in jobs:
url = body_url(term, collection, item.get("num"), reply)
seen += 1
if url in done:
continue
raw, hdrs = _get(url)
if raw is None:
skipped += 1
print(f" WARN skip {url} {hdrs.get('error')}",
file=sys.stderr, flush=True)
continue
kind = _KIND[(collection, is_reply)]
rec = normalize_document(
kind, item, raw.decode("utf-8", "replace"), reply
)
done.add(url)
if rec:
fo.write(json.dumps(rec, ensure_ascii=False) + "\n")
kept += 1
else:
skipped += 1
if seen % 200 == 0:
print(f" seen {seen:,} kept {kept:,} skip {skipped:,} "
f"{seen / max(time.time() - t0, 1):.1f}/s", flush=True)
if args.max_docs and kept >= args.max_docs:
break
if args.max_docs and kept >= args.max_docs:
break
if args.max_docs and kept >= args.max_docs:
break
if args.max_docs and kept >= args.max_docs:
break
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())