#!/usr/bin/env python3 """Fetch gov.pl ministry/agency press releases into a SpeakLeash-style .jsonl.zst, so build_dynaword.py consumes it unchanged (native source, not via SpeakLeash). All textual content on gov.pl is published under CC-BY-SA 4.0 (site footer: "Treści tekstowe publikowane w serwisie … CC BY-SA 4.0"), authored and hosted by the Polish government — so the redistributor genuinely holds the right to license it. Enumeration is driven by the committed manifest src/govpl_subsites.json (built by discover_govpl.py): {slug, news_path, pages} per subsite. This keeps the fetch pure-stdlib and reproducible — no headless browser at fetch time. Resumable: appends to /govpl.jsonl, skips article URLs already present, then compresses to govpl.jsonl.zst at the end of a run. Per-request failures are retried then logged and skipped (never silently truncating the crawl). Usage: python3 src/discover_govpl.py --out src/govpl_subsites.json # once / to refresh python3 src/fetch_govpl.py --out ~/speakleash --manifest src/govpl_subsites.json """ from __future__ import annotations import argparse, json, re, subprocess, sys, threading, time from concurrent.futures import ThreadPoolExecutor from html import unescape from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from discover_govpl import BASE, http_get, http_get_url, listing_articles # shared, DRY KEY = "govpl" # build_dynaword reads .jsonl.zst MIN_CHARS = 200 # same floor as build_dynaword; skip stubs early _SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?") _BLOCK_END = re.compile(r"(?i)|") _TAG = re.compile(r"<[^>]+>") # Body ends where the editor-content region gives way to gallery/attachments/tags. _END_MARKER = re.compile( r'<[^>]+class="[^"]*(?:attachments|art-tags|tags|social|share|gallery|files)[^"]*"' r'|data-group="gallery"|]*>', re.I) def html_to_text(html: str) -> str: html = _SCRIPT.sub("", html) html = _BLOCK_END.sub("\n", html) html = _TAG.sub("", html) text = unescape(html) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r" *\n *", "\n", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() def article_body(html: str) -> str: """Text of the article body. gov.pl pages carry the class twice; pick the richest editor-content region and cut at the trailing gallery/attachments. ponytail: regex slice, not a DOM parse — end-markers drop gallery captions; upgrade to an HTML parser only if boilerplate leakage shows up in stats.""" best = "" for m in _EDITOR.finditer(html): start = m.end() end = _END_MARKER.search(html, start) chunk = html[start:end.start()] if end else html[start:] text = html_to_text(chunk) if len(text) > len(best): best = text return best def normalize(art: dict, html: str, slug: str) -> dict | None: """Listing entry {url,title,date} + article HTML -> record, or None if thin.""" body = article_body(html) if len(body) < MIN_CHARS: return None title = art.get("title") or "" text = f"{title}\n\n{body}" if title else body return { "text": text, "meta": { "url": BASE + art["url"], "subsite": slug, "title": title, "date": art.get("date") or "", }, } def iter_listing(slug: str, news_path: str, pages: int): """Yield {url,title,date} article entries across a subsite's listing pages. Resolves the news section's canonical URL first: gov.pl aliases (e.g. /aktualnosci) redirect to a canonical feed (/wydarzenia) and drop ?page=, so paginating the alias returns page 1 forever. We paginate the resolved base with ?page=N&size=10 (the exact form gov.pl's own pager emits).""" first_html, canonical = http_get_url(f"{BASE}/web/{slug}/{news_path}") if first_html is None: print(f" WARN news section failed, skipped: {slug}/{news_path}", file=sys.stderr, flush=True) return base = canonical.split("?", 1)[0] # canonical path, no query for page in range(1, pages + 1): html = http_get(f"{base}?page={page}&size=10") if html is None: print(f" WARN listing failed, skipped: {base}?page={page}", file=sys.stderr, flush=True) continue yield from listing_articles(html, slug) def fetch_subsite(si: int, n_sub: int, sub: dict, done: set, lock: threading.Lock, fo, st: dict) -> None: """Crawl one subsite. Runs in a worker thread: the slow article GET stays outside the lock so workers actually overlap; only shared state (done set, file, counters) is lock-guarded.""" slug, news_path, pages = sub["slug"], sub["news_path"], sub["pages"] print(f"[{si}/{n_sub}] {slug}/{news_path} ({pages}p)", flush=True) try: for art in iter_listing(slug, news_path, pages): url = BASE + art["url"] with lock: if url in done: continue done.add(url) st["seen"] += 1 seen = st["seen"] html = http_get(url) # network — deliberately outside the lock if html is None: with lock: st["skipped"] += 1 print(f" WARN article failed, skipped: {url}", file=sys.stderr, flush=True) continue rec = normalize(art, html, slug) line = json.dumps(rec, ensure_ascii=False) + "\n" if rec else None with lock: if line: fo.write(line); st["kept"] += 1 if seen % 500 == 0: print(f" seen {st['seen']:,} | kept {st['kept']:,} | skipped {st['skipped']:,} " f"| {st['seen']/(time.time()-st['t0']):.1f}/s", flush=True) except Exception as e: # A subsite that dies must not abort the whole crawl (ex.map would # propagate and kill every worker). Log, skip the rest, keep going. print(f" WARN subsite crashed, skipped rest: {slug}: {e!r}", file=sys.stderr, flush=True) def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="~/speakleash") ap.add_argument("--manifest", default="src/govpl_subsites.json") ap.add_argument("--workers", type=int, default=2, help="concurrent subsite crawlers (be polite to gov.pl)") args = ap.parse_args() manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8")) subsites = manifest["subsites"] 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") st = {"seen": 0, "kept": 0, "skipped": 0, "t0": time.time()} lock = threading.Lock() with jsonl.open("a", encoding="utf-8") as fo: with ThreadPoolExecutor(max_workers=args.workers) as ex: # list() drains the map so any worker exception surfaces here. list(ex.map( lambda item: fetch_subsite(item[0], len(subsites), item[1], done, lock, fo, st), enumerate(subsites, 1))) print(f"fetched {st['kept']:,} articles ({st['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()-st['t0'])}s") if __name__ == "__main__": main()