File size: 8,563 Bytes
a916ede
 
 
 
 
 
 
 
 
e519157
a916ede
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/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())