File size: 7,983 Bytes
87f5bc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/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 <out>/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 <KEY>.jsonl.zst
MIN_CHARS = 200  # same floor as build_dynaword; skip stubs early

_SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
_BLOCK_END = re.compile(r"(?i)</(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|<br\s*/?>")
_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"|</article', re.I)
_EDITOR = re.compile(r'<div class="editor-content"[^>]*>', 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()