| |
| """Fetch Polish primary legislation from the Sejm ELI API into a SpeakLeash-style |
| .jsonl.zst, so build_dynaword.py consumes it unchanged (native source, not via |
| SpeakLeash). Acts of law are public domain by statute (art. 4 ustawy o prawie |
| autorskim — normative acts are not subject to copyright). |
| |
| API: https://api.sejm.gov.pl/eli/acts/{DU|MP}/{year} -> list |
| https://api.sejm.gov.pl/eli/acts/{pub}/{year}/{pos}/text.html -> text |
| |
| Resumable: appends to <out>/<key>.jsonl, skips addresses already present, then |
| compresses to <key>.jsonl.zst at the end of a run. |
| |
| Usage: |
| python3 src/fetch_eli.py --out ~/Local/Ventures/Slayer/data/speakleash \ |
| --publishers DU MP --years 1990-2025 --in-force-only --workers 8 |
| """ |
| from __future__ import annotations |
| import argparse, json, re, subprocess, sys, time |
| from concurrent.futures import ThreadPoolExecutor |
| from html.parser import HTMLParser |
| from pathlib import Path |
| from urllib.request import urlopen, Request |
| from urllib.error import URLError, HTTPError |
|
|
| API = "https://api.sejm.gov.pl/eli/acts" |
| KEY = "dziennik_ustaw" |
| UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"} |
|
|
|
|
| def _get(url, tries=4, raw=False): |
| for i in range(tries): |
| try: |
| with urlopen(Request(url, headers=UA), timeout=30) as r: |
| data = r.read() |
| return data if raw else json.loads(data) |
| except (HTTPError, URLError, TimeoutError) as e: |
| if isinstance(e, HTTPError) and e.code == 404: |
| return None |
| time.sleep(1.5 * (i + 1)) |
| return None |
|
|
|
|
| class _Text(HTMLParser): |
| _SKIP = {"script", "style", "head"} |
|
|
| def __init__(self): |
| super().__init__() |
| self.buf, self._skip = [], 0 |
|
|
| def handle_starttag(self, tag, attrs): |
| if tag in self._SKIP: |
| self._skip += 1 |
|
|
| def handle_endtag(self, tag): |
| if tag in self._SKIP and self._skip: |
| self._skip -= 1 |
|
|
| def handle_data(self, data): |
| if not self._skip and data.strip(): |
| self.buf.append(data) |
|
|
|
|
| def html_to_text(html_bytes): |
| p = _Text() |
| p.feed(html_bytes.decode("utf-8", "replace")) |
| return re.sub(r"\n{3,}", "\n\n", re.sub(r"[ \t]+", " ", "\n".join(p.buf))).strip() |
|
|
|
|
| def list_acts(pub, year, in_force_only): |
| d = _get(f"{API}/{pub}/{year}") |
| items = (d or {}).get("items", []) if isinstance(d, dict) else [] |
| out = [] |
| for it in items: |
| if not it.get("textHTML"): |
| continue |
| if in_force_only and it.get("inForce") not in (None, "IN_FORCE"): |
| continue |
| out.append(it) |
| return out |
|
|
|
|
| def fetch_one(it): |
| pub, year, pos = it["publisher"], it["address"], it["pos"] |
| yr = it.get("year") or int(re.search(r"(\d{4})", it["address"]).group(1)) |
| html = _get(f"{API}/{it['publisher']}/{yr}/{it['pos']}/text.html", raw=True) |
| if not html: |
| return None |
| text = html_to_text(html) |
| if len(text) < 200: |
| return None |
| return { |
| "text": text, |
| "meta": { |
| "url": f"{API}/{it['publisher']}/{yr}/{it['pos']}", |
| "title": it.get("title", ""), |
| "address": it["address"], "publisher": it["publisher"], |
| "year": yr, "pos": it["pos"], "type": it.get("type", ""), |
| "status": it.get("status", ""), |
| "announcementDate": it.get("announcementDate", ""), |
| }, |
| } |
|
|
|
|
| def parse_years(s): |
| if "-" in s: |
| a, b = s.split("-"); return range(int(a), int(b) + 1) |
| return [int(s)] |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash") |
| ap.add_argument("--publishers", nargs="+", default=["DU", "MP"]) |
| ap.add_argument("--years", default="1990-2025") |
| ap.add_argument("--in-force-only", action="store_true") |
| ap.add_argument("--workers", type=int, default=8) |
| args = ap.parse_args() |
|
|
| 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"]["address"]) |
| except Exception: pass |
| print(f"resume: {len(done):,} already fetched") |
|
|
| years = parse_years(args.years) |
| todo = [] |
| for pub in args.publishers: |
| for y in years: |
| for it in list_acts(pub, y, args.in_force_only): |
| if it["address"] not in done: |
| todo.append(it) |
| print(f" listed {pub} {y} | queue={len(todo):,}", flush=True) |
| print(f"to fetch: {len(todo):,}", flush=True) |
|
|
| kept = 0; t0 = time.time() |
| with jsonl.open("a", encoding="utf-8") as fo, \ |
| ThreadPoolExecutor(max_workers=args.workers) as ex: |
| for i, rec in enumerate(ex.map(fetch_one, todo), 1): |
| if rec: |
| fo.write(json.dumps(rec, ensure_ascii=False) + "\n"); kept += 1 |
| if i % 500 == 0: |
| print(f" {i:,}/{len(todo):,} | kept {kept:,} | {i/(time.time()-t0):.1f}/s", flush=True) |
|
|
| print(f"fetched {kept:,} new | total file lines below; 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") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|