#!/usr/bin/env python3 """Fetch NIK (Supreme Audit Office) control reports into a SpeakLeash-style .jsonl.zst for build_dynaword.py. Official documents of Najwyższa Izba Kontroli ("Informacja o wynikach kontroli"), outside copyright under art. 4 pkt 2 pr. aut., same legal basis as the shipped dziennik_ustaw and sejm_interpellations shards. The audit reports are PDF attachments on server-rendered control pages (https://www.nik.gov.pl/kontrole/...); text is extracted with pypdf. Record = one control report PDF (the "Informacja o wynikach kontroli" and same-page attachments); page chrome lives in meta (nr ewidencyjny, date, thematic field). Caveats (quoted third-party text inside official documents) are recorded in the companion license-evidence file; PII scrubbing is SlayerLab/NERGAL, not this repo. Usage: python3 src/fetch_nik_control_reports_pl.py --out ~/speakleash python3 src/fetch_nik_control_reports_pl.py --out ~/speakleash --max-docs 20 """ from __future__ import annotations import argparse, gzip, html as htmllib, json, re, subprocess, sys, time from multiprocessing import Pool from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import urljoin from urllib.request import Request, urlopen BASE = "https://www.nik.gov.pl" LISTING = BASE + "/kontrole/wyniki-kontroli-nik/prosta/limit,50,strona,{}.html" KEY = "nik_control_reports_pl" UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)", "Accept": "*/*"} MIN_CHARS = 200 LICENSE = "public-domain (official documents)" AUTHOR = "Najwyższa Izba Kontroli" CTRL_RE = re.compile(r'href="([^"]*?/kontrole/[A-Z]{1,3}/\d{2}/\d{3}[^"]*)"') PDF_RE = re.compile(r'href="([^"]*?/kontrole/[^"]*?pobierz[^"]*?\.pdf)"', re.I) EWID_RE = re.compile(r"Nr ewidencyjny:\s*([A-Z]{1,3}/\d{2}/\d{3})") DATE_RE = re.compile(r"Data publikacji:\s*([\d. :]+)") FIELD_RE = re.compile(r"Dział tematyczny:\s*([^<]+)") TITLE_RE = re.compile(r"]*>(.*?)", re.S) TAG_RE = re.compile(r"<[^>]+>") # The results listing is a JS pager (all /strona,N URLs return page 1; no # sitemap). Controls carry official sequential record numbers (Nr ewidencyjny # P|D|I/RR/NNN), so the inventory sweeps that numbering with a gap tolerance # and probes only public detail pages, politely and serially. PREFIXES = ("P", "D", "I", "G", "K", "N", "S", "R", "A", "Z") YEARS = range(2004, 2027) MAX_GAP = 80 def _get(url: str, retries: int = 5): import http.client for attempt in range(retries): try: with urlopen(Request(url, headers=UA), timeout=90) as r: return r.read() except HTTPError as e: if e.code in (403, 404, 410): # permanent answers are misses, not retries return None if attempt == retries - 1: return None time.sleep(2 * (attempt + 1)) except (URLError, TimeoutError, http.client.HTTPException, ConnectionError, OSError): if attempt == retries - 1: return None time.sleep(2 * (attempt + 1)) def pdf_to_text(blob: bytes) -> str: import io import pypdf reader = pypdf.PdfReader(io.BytesIO(blob)) parts = [] for page in reader.pages: parts.append(page.extract_text() or "") return "\n".join(parts) def parse_control_page(url: str, html_src: str): """Control page -> (meta dict, list of PDF urls).""" def clean(x): return " ".join(htmllib.unescape(TAG_RE.sub("", x)).split()) m = EWID_RE.search(html_src) d = DATE_RE.search(html_src) f = FIELD_RE.search(html_src) t = TITLE_RE.search(html_src) meta = { "control_id": clean(m.group(1)) if m else "", "published": clean(d.group(1)).split()[0].replace(".", "-") if d else "", "field": clean(f.group(1)) if f else "", "title": clean(t.group(1)) if t else "", "source_url": url, } pdfs = [urljoin(BASE, u.replace("&", "&")) for u in PDF_RE.findall(html_src)] return meta, sorted(set(pdfs)) def _inventory_block(task): """Sweep one (prefix, year) block serially; ends after MAX_GAP misses.""" pref, yy, delay = task yy2 = str(yy)[2:] rows, miss, found = [], 0, 0 n = 1 while miss < MAX_GAP: url = f"{BASE}/kontrole/{pref}/{yy2}/{n:03d}" raw = _get(url) # None on any fetch failure = miss, never raises n += 1 if raw and b"Nr ewidencyjny" in raw: rows.append({"control_url": url}) found += 1 miss = 0 else: miss += 1 if delay: time.sleep(delay) return pref, yy2, found, rows def inventory(out_dir: Path, delay: float, workers: int = 3): """Sweep official record numbers (Nr ewidencyjny) over public detail pages. The results listing is a JS pager, so the inventory walks the official sequential numbering instead: blocks of (prefix, year), each block serial and polite, a few blocks in parallel. Completed blocks are journaled to inventory.done and rows appended to inventory.jsonl.gz, so a rerun (after a network reset, say) resumes exactly where it stopped. """ out_dir.mkdir(parents=True, exist_ok=True) inv_path = out_dir / "inventory.jsonl.gz" done_path = out_dir / "inventory.done" done = set(done_path.read_text(encoding="utf-8").splitlines()) if done_path.exists() else set() tasks = [(pref, yy, delay) for yy in YEARS for pref in PREFIXES if f"{pref}/{str(yy)[2:]}" not in done] print(f"inventory blocks: {len(tasks)} to do ({len(done)} journaled)", flush=True) total = 0 with Pool(workers) as pool: for pref, yy2, found, block_rows in pool.imap_unordered(_inventory_block, tasks): if block_rows: with gzip.open(inv_path, "at", encoding="utf-8", compresslevel=4) as f: for r in block_rows: f.write(json.dumps(r, ensure_ascii=False) + "\n") total += len(block_rows) with done_path.open("a", encoding="utf-8") as f: f.write(f"{pref}/{yy2}\n") if found: print(f" {pref}/{yy2}: {found} controls (+{total} rows so far)", flush=True) rows = [] seen = set() with gzip.open(inv_path, "rt", encoding="utf-8") as f: for line in f: try: r = json.loads(line) if r["control_url"] not in seen: seen.add(r["control_url"]) rows.append(r) except Exception: pass print(f"inventory controls: {len(rows):,}", flush=True) return rows def compress(jsonl: Path, out_dir: Path) -> Path: target = out_dir / f"{KEY}.jsonl.zst" try: subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl), "-o", str(target)], check=True) except (FileNotFoundError, subprocess.CalledProcessError): import zstandard with open(jsonl, "rb") as src, open(target, "wb") as dst: zstandard.ZstdCompressor(level=19).copy_stream(src, dst) jsonl.unlink() return target def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--out", type=Path, default=Path(".")) parser.add_argument("--delay", type=float, default=0.2) parser.add_argument("--max-docs", type=int, default=0) args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) jsonl = args.out / f"{KEY}.jsonl" t0 = time.time() controls = inventory(args.out, args.delay) print(f"inventory controls: {len(controls):,}", flush=True) done = set() if jsonl.exists(): with open(jsonl, encoding="utf-8") as f: for line in f: try: done.add(json.loads(line)["record_id"]) except Exception: pass kept = skipped = 0 with open(jsonl, "a", encoding="utf-8") as fo: for row in controls: raw = _get(row["control_url"]) if raw is None: skipped += 1 continue html_src = raw.decode("utf-8", "replace") meta, pdfs = parse_control_page(row["control_url"], html_src) for i, pdf_url in enumerate(pdfs): rid = f"{meta['control_id'] or row['control_url'].rstrip('/').split('/')[-1]}#{i}" if rid in done: continue blob = _get(pdf_url) if blob is None: skipped += 1 continue try: text = pdf_to_text(blob) except Exception: skipped += 1 continue text = re.sub(r"[ \t]+", " ", text) text = "\n".join(line.strip() for line in text.splitlines() if line.strip()) if len(text) < MIN_CHARS: skipped += 1 continue fo.write(json.dumps({ "id": f"{KEY}_{meta['control_id'].replace('/', '_').lower()}_{i}" if meta["control_id"] else f"{KEY}_{abs(hash(pdf_url)) % 10**12}_{i}", "record_id": rid, "text": text, "created": meta["published"], "license": LICENSE, "author": AUTHOR, "control_id": meta["control_id"], "title": meta["title"], "field": meta["field"], "source_url": pdf_url, }, ensure_ascii=False) + "\n") done.add(rid) kept += 1 if args.max_docs and kept >= args.max_docs: break if (kept + skipped) % 50 == 0: print(f" seen {kept + skipped:,} kept {kept:,} skip {skipped:,} " f"{(kept + skipped) / max(time.time() - t0, 1):.2f}/s", flush=True) if args.max_docs and kept >= args.max_docs: break if args.delay: time.sleep(args.delay) print(f"fetched {kept:,} new reports ({skipped:,} skipped); compressing...", flush=True) target = compress(jsonl, args.out) print(f"wrote {target} in {round(time.time() - t0)}s") return 0 if __name__ == "__main__": raise SystemExit(main())