endomorphosis commited on
Commit
93eb238
·
verified ·
1 Parent(s): 3ea8e77

Create namibia laws: 86 laws / 180 articles

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # MANIFEST
2
+
3
+ - generated_at: 2026-09-04T21:18:40Z
4
+ - laws: 86
5
+ - articles: 180
6
+ - files:
7
+ - data/laws.parquet: 1708647 bytes
8
+ - data/articles.parquet: 1070576 bytes
9
+ - README.md: 2103 bytes
README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Laws of Namibia
3
+ license: other
4
+ license_name: na-parliament-bon
5
+ language:
6
+ - en
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - namibia
13
+ - official-texts
14
+ size_categories:
15
+ - n<1K
16
+ configs:
17
+ - config_name: laws
18
+ data_files: data/laws.parquet
19
+ default: true
20
+ - config_name: articles
21
+ data_files: data/articles.parquet
22
+ ---
23
+
24
+ # Laws of Namibia
25
+
26
+ Research snapshot of official legislation collected from **laws.parliament.na Bills / Bank of Namibia / parliament.na**.
27
+
28
+ **Not legal advice.** Official gazettes / government portals prevail over this corpus.
29
+
30
+ ## Snapshot
31
+
32
+ | Field | Value |
33
+ | --- | --- |
34
+ | Snapshot date | 2026-09-04 |
35
+ | Coverage | catalog-backed incomplete |
36
+ | Source | laws.parliament.na Bills / Bank of Namibia / parliament.na |
37
+ | Collector | `scrapers/collect_na.py` |
38
+ | Laws / instruments | 86 |
39
+ | Articles | 180 |
40
+ | Language | en |
41
+ | Jurisdiction | Namibia |
42
+ | License | `na-parliament-bon` |
43
+
44
+ ## Contents
45
+
46
+ - `data/laws.parquet` — one row per instrument (id, title, full text, dates, status, identifiers, article count, source URL).
47
+ - `data/articles.parquet` — one row per article/section (`law_id`, article number, title, text, source URL).
48
+ - `scrapers/collect_na.py` — research collector used to build this snapshot.
49
+ - `scrapers/common.py` — shared collector helpers.
50
+ - `scrapers/world_lib.py` — shared fetch (live official URL, Wayback fallback).
51
+ - `scrapers/archive_fallbacks.py` — Wayback / Common Crawl CDX helpers.
52
+
53
+ ## License / reuse
54
+
55
+ Official government / gazette texts; reuse per public-sector terms of the
56
+ source portal. This packaging, metadata, and collector script are provided
57
+ for research.
58
+
59
+ This dataset is **not** an official consolidation and is **not legal advice**.
60
+ The official source prevails.
61
+
62
+ ## Notes
63
+
64
+ Namibia Parliament Bill Tracking (laws.parliament.na embedded PDFs) + parliament.na wp-content Act/Bill PDFs + Bank of Namibia statutory Act/Regulation/Determination PDFs. laws.parliament.na/cms_documents via CDX+Wayback. Skipped lac.org.na and namiblii.org. gov.na/moj.gov.na/mfpe.gov.na unreachable (SSL/DNS). Not legal advice.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:afa73d3fc6f5d7ea4c28d0574d410fdd581f9aeeec0dd5664fd4b507ee6e0789
3
+ size 1070576
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82f5bb3487aa86c034c358935bbd381e4fe0bf70e1dd7c06dea7f95be4d90c7c
3
+ size 1708647
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public Wayback CDX + Common Crawl CDX/WARC fetch (ipfs_datasets_py fallback intent).
3
+
4
+ Does not import the full ipfs_datasets_py package. Matches:
5
+ search_wayback_machine / get_wayback_content (wayback_machine_engine.py)
6
+ Common Crawl CDX at https://index.commoncrawl.org/
7
+ archive.is newest lookup
8
+ Brave Search is skipped when no API key is present.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import gzip
13
+ import io
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Optional
20
+ from urllib.parse import quote, urljoin, urlparse
21
+
22
+ import requests
23
+ from requests.adapters import HTTPAdapter
24
+
25
+ log = logging.getLogger("archive_fallbacks")
26
+
27
+ WAYBACK_CDX = "http://web.archive.org/cdx/search/cdx"
28
+ WAYBACK_WEB = "http://web.archive.org/web"
29
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
+ CC_DATA = "https://data.commoncrawl.org"
31
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
32
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
33
+
34
+ UA = (
35
+ "legal-corpora-collector/1.0 "
36
+ "(research archive of official national gazettes; polite; "
37
+ "contact via local operator)"
38
+ )
39
+
40
+ CHALLENGE_RE = re.compile(
41
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
42
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
43
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
44
+ r"request\s+rejected|access\s+denied",
45
+ re.I,
46
+ )
47
+ SPA_SHELL_RE = re.compile(
48
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
49
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
50
+ re.I,
51
+ )
52
+
53
+ _session: Optional[requests.Session] = None
54
+ _cc_indexes: Optional[list[str]] = None
55
+ _cc_dead: set[str] = set()
56
+ _last_wayback = 0.0
57
+ _last_cc = 0.0
58
+
59
+
60
+ def session() -> requests.Session:
61
+ global _session
62
+ if _session is None:
63
+ s = requests.Session()
64
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
65
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
66
+ s.mount("https://", ad)
67
+ s.mount("http://", ad)
68
+ _session = s
69
+ return _session
70
+
71
+
72
+ def _sleep_wayback(delay: float = 1.0) -> None:
73
+ global _last_wayback
74
+ now = time.time()
75
+ wait = delay - (now - _last_wayback)
76
+ if wait > 0:
77
+ time.sleep(wait)
78
+ _last_wayback = time.time()
79
+
80
+
81
+ def _sleep_cc(delay: float = 0.35) -> None:
82
+ global _last_cc
83
+ now = time.time()
84
+ wait = delay - (now - _last_cc)
85
+ if wait > 0:
86
+ time.sleep(wait)
87
+ _last_cc = time.time()
88
+
89
+
90
+ def has_brave_key() -> bool:
91
+ return bool(
92
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
93
+ )
94
+
95
+
96
+ def is_challenge(html: str, status: int = 200) -> bool:
97
+ if status in (401, 403, 429, 503):
98
+ return True
99
+ if not html:
100
+ return False
101
+ head = html[:8000]
102
+ if CHALLENGE_RE.search(head):
103
+ return True
104
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
105
+ return True
106
+ return False
107
+
108
+
109
+ def is_spa_shell(html: str, text: str) -> bool:
110
+ if not html:
111
+ return False
112
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
113
+ return True
114
+ return False
115
+
116
+
117
+ # --- Wayback ---
118
+
119
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
120
+
121
+
122
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
123
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
124
+ if not isinstance(data, list) or len(data) <= 1:
125
+ return [], None
126
+ resume = None
127
+ rows = data
128
+ # Trailer: ..., [], ["resumeKey"]
129
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
130
+ resume = str(data[-1][0]) if data[-1][0] else None
131
+ rows = data[:-2]
132
+ headers = rows[0] if rows else []
133
+ out: list[dict] = []
134
+ for row in rows[1:]:
135
+ if not row:
136
+ continue
137
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
138
+ if not rec and isinstance(row, list) and len(row) >= 5:
139
+ rec = {
140
+ "urlkey": row[0],
141
+ "timestamp": row[1],
142
+ "original": row[2],
143
+ "mimetype": row[3],
144
+ "statuscode": row[4],
145
+ "digest": row[5] if len(row) > 5 else "",
146
+ "length": row[6] if len(row) > 6 else "0",
147
+ }
148
+ orig = rec.get("original") or rec.get("url") or ""
149
+ ts = rec.get("timestamp") or ""
150
+ mime = rec.get("mimetype") or ""
151
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
152
+ "application/pdf",
153
+ "application/xml",
154
+ "text/xml",
155
+ "application/xhtml+xml",
156
+ "text/html",
157
+ "application/json",
158
+ ):
159
+ continue
160
+ if not orig or not ts:
161
+ continue
162
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
163
+ rec["source"] = "wayback"
164
+ out.append(rec)
165
+ return out, resume
166
+
167
+
168
+ def _wayback_cdx_page(
169
+ url: str,
170
+ *,
171
+ limit: int,
172
+ collapse: str,
173
+ filter_status: str,
174
+ from_date: Optional[str],
175
+ to_date: Optional[str],
176
+ match_type: Optional[str],
177
+ extra_filters: Optional[list[str]],
178
+ resume_key: Optional[str],
179
+ mime_prefix: Optional[str],
180
+ page_size: int,
181
+ ) -> tuple[list[dict], Optional[str]]:
182
+ items: list[tuple[str, Any]] = [
183
+ ("url", url),
184
+ ("output", "json"),
185
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
186
+ ("limit", int(page_size)),
187
+ ("showResumeKey", "true"),
188
+ ]
189
+ if collapse:
190
+ items.append(("collapse", collapse))
191
+ if from_date:
192
+ items.append(("from", from_date))
193
+ if to_date:
194
+ items.append(("to", to_date))
195
+ if match_type:
196
+ items.append(("matchType", match_type))
197
+ if filter_status:
198
+ items.append(("filter", f"statuscode:{filter_status}"))
199
+ for flt in extra_filters or []:
200
+ items.append(("filter", flt))
201
+ if resume_key:
202
+ items.append(("resumeKey", resume_key))
203
+ _sleep_wayback(1.0)
204
+ last_err = None
205
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
206
+ if attempt > 1:
207
+ items = [(k, psz if k == "limit" else v) for k, v in items]
208
+ _sleep_wayback(1.5)
209
+ try:
210
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
211
+ except requests.RequestException as exc:
212
+ last_err = exc
213
+ log.warning("wayback cdx fail %s: %s", url, exc)
214
+ continue
215
+ if r.status_code in (502, 503, 504) or not r.content:
216
+ last_err = f"http_{r.status_code}"
217
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
218
+ continue
219
+ if r.status_code != 200:
220
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
221
+ return [], None
222
+ try:
223
+ data = r.json()
224
+ except Exception:
225
+ return [], None
226
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
227
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
228
+ return [], None
229
+
230
+
231
+ def search_wayback_machine(
232
+ url: str,
233
+ *,
234
+ from_date: Optional[str] = None,
235
+ to_date: Optional[str] = None,
236
+ limit: int = 100,
237
+ collapse: str = "urlkey",
238
+ filter_status: str = "200",
239
+ match_type: Optional[str] = None,
240
+ mime_prefix: Optional[str] = None,
241
+ extra_filters: Optional[list[str]] = None,
242
+ ) -> list[dict]:
243
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
244
+ target = max(1, int(limit))
245
+ page_size = CDX_PAGE if target > CDX_PAGE else target
246
+ out: list[dict] = []
247
+ seen = set()
248
+ resume: Optional[str] = None
249
+ empty = 0
250
+ while len(out) < target:
251
+ need = min(page_size, target - len(out))
252
+ batch, resume = _wayback_cdx_page(
253
+ url,
254
+ limit=need,
255
+ collapse=collapse,
256
+ filter_status=filter_status,
257
+ from_date=from_date,
258
+ to_date=to_date,
259
+ match_type=match_type,
260
+ extra_filters=extra_filters,
261
+ resume_key=resume,
262
+ mime_prefix=mime_prefix,
263
+ page_size=need,
264
+ )
265
+ added = 0
266
+ for rec in batch:
267
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
268
+ if key in seen:
269
+ continue
270
+ seen.add(key)
271
+ out.append(rec)
272
+ added += 1
273
+ if added == 0:
274
+ empty += 1
275
+ if empty >= 2 or not resume:
276
+ break
277
+ else:
278
+ empty = 0
279
+ if not resume:
280
+ break
281
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
282
+ return out[:target]
283
+
284
+
285
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
286
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search."""
287
+ if timestamp:
288
+ wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}"
289
+ else:
290
+ wb = f"{WAYBACK_WEB}/2id_/{url}"
291
+ r = None
292
+ last_err = None
293
+ for attempt in range(1, 5):
294
+ _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt))
295
+ try:
296
+ r = session().get(wb, timeout=(20, 90), allow_redirects=True)
297
+ except requests.RequestException as exc:
298
+ last_err = str(exc)
299
+ log.info("wayback replay fail %s: %s", url, exc)
300
+ continue
301
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 4:
302
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
303
+ continue
304
+ break
305
+ if r is None:
306
+ return {"status": "error", "error": last_err or "no_response", "url": url}
307
+ cap_ts = timestamp or ""
308
+ m = re.search(r"/web/(\d{14})", r.url or "")
309
+ if m:
310
+ cap_ts = m.group(1)
311
+ ctype = r.headers.get("content-type") or ""
312
+ body = r.content or b""
313
+ text = ""
314
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
315
+ enc = r.encoding or "utf-8"
316
+ try:
317
+ text = body.decode(enc, "replace")
318
+ except Exception:
319
+ text = body.decode("utf-8", "replace")
320
+ if r.status_code != 200 or not body:
321
+ return {
322
+ "status": "error",
323
+ "error": f"http_{r.status_code}",
324
+ "http_status": r.status_code,
325
+ "wayback_url": r.url,
326
+ "original_url": url,
327
+ }
328
+ if text and is_challenge(text, r.status_code):
329
+ return {
330
+ "status": "error",
331
+ "error": "challenge_or_shell",
332
+ "http_status": r.status_code,
333
+ "wayback_url": r.url,
334
+ "original_url": url,
335
+ "content": text[:2000],
336
+ }
337
+ return {
338
+ "status": "success",
339
+ "content": body,
340
+ "text": text,
341
+ "content_type": ctype,
342
+ "wayback_url": r.url,
343
+ "capture_timestamp": cap_ts,
344
+ "original_url": url,
345
+ "http_status": r.status_code,
346
+ "method": "wayback",
347
+ }
348
+
349
+
350
+ # --- Common Crawl ---
351
+
352
+ def cc_indexes(n: int = 6) -> list[str]:
353
+ global _cc_indexes
354
+ if _cc_indexes is None:
355
+ try:
356
+ r = session().get(CC_COLLINFO, timeout=30)
357
+ cols = r.json() if r.status_code == 200 else []
358
+ ids = []
359
+ for c in cols:
360
+ cid = c.get("id") or ""
361
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
362
+ if cid:
363
+ ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index")
364
+ # collinfo is newest-first. Do not drop crawls that 404 a
365
+ # specific URL (that means "no captures", not a dead index).
366
+ _cc_indexes = ids or [
367
+ "https://index.commoncrawl.org/CC-MAIN-2025-18-index",
368
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
369
+ ]
370
+ except Exception as exc:
371
+ log.warning("cc collinfo: %s", exc)
372
+ _cc_indexes = [
373
+ "https://index.commoncrawl.org/CC-MAIN-2026-34-index",
374
+ "https://index.commoncrawl.org/CC-MAIN-2026-30-index",
375
+ "https://index.commoncrawl.org/CC-MAIN-2026-25-index",
376
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
377
+ ]
378
+ return _cc_indexes[:n]
379
+
380
+
381
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
382
+ """Query public CC CDX (https://index.commoncrawl.org/).
383
+
384
+ Do not send filter=status:200 — on some shards that returns a false
385
+ 404 "No Captures found". Filter status client-side instead.
386
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
387
+ """
388
+ out = []
389
+ seen = set()
390
+ empty = 0
391
+ for idx in (indexes or cc_indexes(12)):
392
+ if idx in _cc_dead:
393
+ continue
394
+ params = {
395
+ "url": url,
396
+ "output": "json",
397
+ "limit": str(limit),
398
+ }
399
+ _sleep_cc(0.3)
400
+ try:
401
+ r = session().get(idx, params=params, timeout=(12, 25))
402
+ except requests.RequestException as exc:
403
+ log.info("cc cdx %s fail %s", idx, exc)
404
+ continue
405
+ if r.status_code == 404:
406
+ msg = (r.text or "")[:80]
407
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
408
+ empty += 1
409
+ if empty >= 8 and not out:
410
+ continue
411
+ continue
412
+ if r.status_code in (410,):
413
+ _cc_dead.add(idx)
414
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
415
+ continue
416
+ if r.status_code != 200 or not r.content:
417
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
418
+ continue
419
+ for line in r.text.splitlines():
420
+ line = line.strip()
421
+ if not line or line[0] not in "{[":
422
+ continue
423
+ try:
424
+ rec = json.loads(line)
425
+ except Exception:
426
+ continue
427
+ orig = rec.get("url") or rec.get("original") or ""
428
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
429
+ if st and st not in ("200", "201", "206"):
430
+ continue
431
+ key = (orig, rec.get("filename"), rec.get("offset"))
432
+ if not orig or key in seen:
433
+ continue
434
+ seen.add(key)
435
+ rec["original"] = orig
436
+ rec["source"] = "common_crawl"
437
+ rec["cc_index"] = idx
438
+ out.append(rec)
439
+ if out:
440
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
441
+ if len(out) >= limit or out:
442
+ break
443
+ return out[:limit]
444
+
445
+
446
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
447
+ data = raw
448
+ if data[:2] == b"\x1f\x8b":
449
+ try:
450
+ data = gzip.decompress(data)
451
+ except Exception:
452
+ try:
453
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
454
+ except Exception:
455
+ pass
456
+ # WARC record: headers, then HTTP payload
457
+ split = data.split(b"\r\n\r\n", 1)
458
+ if len(split) < 2:
459
+ return 0, "", data
460
+ warc_headers, rest = split
461
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
462
+ http_split = rest.split(b"\r\n\r\n", 1)
463
+ http_head = http_split[0].decode("latin-1", "replace")
464
+ body = http_split[1] if len(http_split) > 1 else b""
465
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
466
+ status = int(m.group(1)) if m else 0
467
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
468
+ ctype = cm.group(1).strip() if cm else ""
469
+ return status, ctype, body
470
+ return 0, "", rest
471
+
472
+
473
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
474
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
475
+ try:
476
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
477
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
478
+ except Exception:
479
+ return {"status": "error", "error": "bad_pointer"}
480
+ if not fn or ln <= 0:
481
+ return {"status": "error", "error": "missing_pointer"}
482
+ ln = min(ln, max_bytes)
483
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
484
+ _sleep_cc(0.25)
485
+ try:
486
+ r = session().get(
487
+ url,
488
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
489
+ timeout=(20, 90),
490
+ )
491
+ except requests.RequestException as exc:
492
+ return {"status": "error", "error": str(exc)}
493
+ if r.status_code not in (200, 206) or not r.content:
494
+ return {"status": "error", "error": f"http_{r.status_code}"}
495
+ status, ctype, body = _parse_warc_http(r.content)
496
+ text = ""
497
+ if body and (
498
+ "html" in (ctype or "")
499
+ or "xml" in (ctype or "")
500
+ or "text/" in (ctype or "")
501
+ or not ctype
502
+ ):
503
+ text = body.decode("utf-8", "replace")
504
+ orig = rec.get("original") or rec.get("url") or ""
505
+ if text and is_challenge(text, status or 200):
506
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
507
+ return {
508
+ "status": "success",
509
+ "content": body,
510
+ "text": text,
511
+ "content_type": ctype,
512
+ "original_url": orig,
513
+ "http_status": status or 200,
514
+ "method": "common_crawl",
515
+ "cc_record": {
516
+ "filename": fn,
517
+ "offset": off,
518
+ "length": ln,
519
+ "timestamp": rec.get("timestamp"),
520
+ },
521
+ }
522
+
523
+
524
+ # --- archive.is ---
525
+
526
+ def get_archive_is_content(url: str) -> dict:
527
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
528
+ try:
529
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
530
+ except requests.RequestException as exc:
531
+ log.info("archive.is %s", exc)
532
+ continue
533
+ if r.status_code != 200 or not r.content:
534
+ continue
535
+ if "archive." not in (r.url or ""):
536
+ continue
537
+ text = r.text or ""
538
+ if is_challenge(text, r.status_code):
539
+ continue
540
+ return {
541
+ "status": "success",
542
+ "content": r.content,
543
+ "text": text,
544
+ "content_type": r.headers.get("content-type") or "text/html",
545
+ "archive_url": r.url,
546
+ "original_url": url,
547
+ "http_status": r.status_code,
548
+ "method": "archive_is",
549
+ }
550
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
551
+
552
+
553
+ # --- Direct HTTP last ---
554
+
555
+ def get_http(url: str) -> dict:
556
+ try:
557
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
558
+ except requests.RequestException as exc:
559
+ return {"status": "error", "error": str(exc), "original_url": url}
560
+ text = ""
561
+ ctype = r.headers.get("content-type") or ""
562
+ body = r.content or b""
563
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
564
+ text = body.decode(r.encoding or "utf-8", "replace")
565
+ if r.status_code != 200 or not body:
566
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
567
+ if text and is_challenge(text, r.status_code):
568
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
569
+ return {
570
+ "status": "success",
571
+ "content": body,
572
+ "text": text,
573
+ "content_type": ctype,
574
+ "original_url": url,
575
+ "http_status": r.status_code,
576
+ "method": "http",
577
+ "final_url": r.url,
578
+ }
579
+
580
+
581
+ def fetch_with_fallbacks(
582
+ url: str,
583
+ *,
584
+ cc_record: Optional[dict] = None,
585
+ wayback_ts: Optional[str] = None,
586
+ try_archive_is: bool = False,
587
+ try_http: bool = True,
588
+ try_cc: bool = True,
589
+ ) -> dict:
590
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
591
+
592
+ Brave Search skipped (no API key in this environment).
593
+ Playwright is attempted by the caller when this returns a SPA shell.
594
+ Does not run Wayback CDX search; Wayback is replay only.
595
+ """
596
+ errors = []
597
+ cc_recs: list[dict] = []
598
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
599
+ cc_recs = [cc_record]
600
+ elif try_cc:
601
+ try:
602
+ cc_recs = search_common_crawl(url, limit=4)
603
+ except Exception as exc:
604
+ errors.append(f"common_crawl:{exc}")
605
+ cc_recs = []
606
+ for rec in cc_recs:
607
+ res = fetch_common_crawl_warc(rec)
608
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
609
+ return res
610
+ errors.append(f"common_crawl:{res.get('error')}")
611
+ if wayback_ts or url:
612
+ res = get_wayback_content(url, timestamp=wayback_ts)
613
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
614
+ return res
615
+ errors.append(f"wayback:{res.get('error')}")
616
+ if try_archive_is:
617
+ res = get_archive_is_content(url)
618
+ if res.get("status") == "success":
619
+ return res
620
+ errors.append(f"archive_is:{res.get('error')}")
621
+ if try_http:
622
+ res = get_http(url)
623
+ if res.get("status") == "success":
624
+ return res
625
+ errors.append(f"http:{res.get('error')}")
626
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_na.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Namibia: official Bills / Acts / Gazette instruments from Parliament + BoN.
3
+
4
+ Primary: laws.parliament.na (Online Bill Tracking — embedded official Bill PDFs),
5
+ www.parliament.na (wp-content Bill / Act PDFs + wp-json media), Bank of Namibia
6
+ (bon.com.na Regulations / Determinations / Act getattachment PDFs).
7
+
8
+ Skips: lac.org.na (entirely), namiblii.org, SAFLII, gazettes.africa, speeches,
9
+ motivations, contributions, tenders, minutes, notices of award.
10
+
11
+ Live official URL first; Wayback of the same official URL on failure.
12
+ OCR=1 enables pdftoppm+tesseract for image-only official PDFs. No WAF bypass.
13
+
14
+ Gaps (recorded): www.gov.na SSL EOF from collector host; moj.gov.na timeout;
15
+ mfpe.gov.na DNS fail; laws.parliament.na/cms_documents live often 404 → Wayback; full Government Gazette series not mirrored on parliament.na.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import logging
21
+ import os
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+ import time
27
+ from pathlib import Path
28
+ from urllib.parse import unquote, urljoin, urlparse
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ from common import existing_ids, log_failure, utcnow, write_summary
32
+ from world_lib import cdx_urls, env_int, fetch_official, fetch_official_prefer_pdf, live_get, save_instrument, setup_log, slug_id
33
+
34
+ CC, COUNTRY, LANG = "na", "Namibia", "en"
35
+ SOURCE_TYPE = "namibia_official_parliament_bon"
36
+ LICENSE = (
37
+ "Laws / Bills / Gazette instruments of Namibia as published on official "
38
+ "Parliament portals (parliament.na / laws.parliament.na) and Bank of Namibia "
39
+ "(bon.com.na) statutory hosts. Authentic Government Gazette / Parliament text "
40
+ "prevails. Not legal advice."
41
+ )
42
+ UA = "legal-corpora-collector/1.0 (research; source=https://www.parliament.na/)"
43
+ ART = re.compile(
44
+ r"(?im)^\s*((?:Section|Sec\.|Article|Art\.|Regulation|Reg\.)\s+\d+[A-Za-z]?\.?)\b"
45
+ )
46
+ log = logging.getLogger("na")
47
+
48
+ BLOCK_HOST = re.compile(
49
+ r"(lac\.org\.na|namiblii\.org|saflii\.org|gazettes\.africa|"
50
+ r"africanlii\.org|commonlii\.org|ulii\.org)",
51
+ re.I,
52
+ )
53
+ SKIP_NAME = re.compile(
54
+ r"(contribution|motivation|response|speech|report[_\-\s]|NOTICE[_\-\s]?OF|"
55
+ r"minutes|tender|award|vacancy|advert|newsletter|workshop|consultative|"
56
+ r"stakeholder|explanatory[_\-\s]?memorandum|budget[_\-\s]?statement|"
57
+ r"vote\d|sofa|upholstery|procurement[_\-\s]?notice|selection[_\-\s]?for|"
58
+ r"cancellation[_\-\s]?of[_\-\s]?a[_\-\s]?bid|facilitator|travel[_\-\s]?management|"
59
+ r"supply[_\-\s]?and[_\-\s]?delivery|service[_\-\s]?level[_\-\s]?agreement|"
60
+ r"strategy[_\-\s]?advert|mefmi[_\-\s]?advertisement)",
61
+ re.I,
62
+ )
63
+ LAWISH_NAME = re.compile(
64
+ r"("
65
+ r"\bbill\b|_bill_|-bill-|bill\.pdf|"
66
+ r"\bact\b|_act_|-act-|act\.pdf|"
67
+ r"gazette|regulation|regulations|determination|"
68
+ r"constitution|statutory[_\-\s]?instrument|"
69
+ r"\bb\.?\s*\d+|amendment"
70
+ r")",
71
+ re.I,
72
+ )
73
+ LAW_MARK = re.compile(
74
+ r"(BE IT ENACTED|AN ACT\b|A BILL\b|BILL\b|Short title|"
75
+ r"This Act may be cited|GOVERNMENT GAZETTE|REPUBLIC OF NAMIBIA|"
76
+ r"ARRANGEMENT OF SECTIONS|NATIONAL ASSEMBLY|PROMULGATION OF ACT|"
77
+ r"No\.\s*\d+\s+of\s+20\d{2}|\[B\.\s*\d+)",
78
+ re.I,
79
+ )
80
+
81
+ CDX_PREFIXES = [
82
+ "laws.parliament.na/cms_documents/",
83
+ "www.parliament.na/wp-content/uploads/",
84
+ "parliament.na/wp-content/uploads/",
85
+ "www.bon.com.na/CMSTemplates/Bon/Files/",
86
+ "bon.com.na/CMSTemplates/Bon/Files/",
87
+ ]
88
+
89
+ LIVE_SEEDS = [
90
+ "https://www.parliament.na/bills/",
91
+ "https://www.parliament.na/acts-of-parliament/",
92
+ "https://laws.parliament.na/Bill-register",
93
+ "https://www.bon.com.na/Regulations.aspx",
94
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks.aspx",
95
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Determinations.aspx",
96
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Regulations.aspx",
97
+ ]
98
+
99
+ BON_SEED_PAGES = [
100
+ "https://www.bon.com.na/Regulations.aspx",
101
+ "https://www.bon.com.na/Regulations/Bank-of-Namibia-Act-2020.aspx",
102
+ "https://www.bon.com.na/Regulations/Banking-Institutions-Act-2023.aspx",
103
+ "https://www.bon.com.na/Regulations/Virtual-Assets-Act-2023.aspx",
104
+ "https://www.bon.com.na/Regulations/Financial-Intelligence-Act-2012.aspx",
105
+ "https://www.bon.com.na/Regulations/Namibia-Deposit-Guarantee-Act-2018.aspx",
106
+ "https://www.bon.com.na/Regulations/Payment-System-Management-Act-2003.aspx",
107
+ "https://www.bon.com.na/Regulations/Payment-System-Management-Amendment-Act-2023.aspx",
108
+ "https://www.bon.com.na/Regulations/Currencies-and-Exchanges-Act-1933.aspx",
109
+ "https://www.bon.com.na/Regulations/Prevention-of-Counterfeiting-of-Currency-Act-1965.aspx",
110
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Determinations.aspx",
111
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Regulations.aspx",
112
+ "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Other-Bylaws.aspx",
113
+ "https://www.bon.com.na/Bank/National-Payment-System/Legal-Framework.aspx",
114
+ "https://www.bon.com.na/Bank/Financial-Stability/Determinations-Regulations-and-Guidance-Notes.aspx",
115
+ ]
116
+
117
+
118
+ def _norm(url: str) -> str:
119
+ u = (url or "").split("#")[0]
120
+ u = u.replace("http://", "https://")
121
+ u = re.sub(r":80/", "/", u)
122
+ u = re.sub(r"https://parliament\.na/", "https://www.parliament.na/", u)
123
+ u = re.sub(r"https://bon\.com\.na/", "https://www.bon.com.na/", u)
124
+ # Drop tracking query junk; keep empty for getattachment
125
+ parts = urlparse(u)
126
+ path = parts.path or ""
127
+ if " " in unquote(path) or "%" in path:
128
+ from urllib.parse import quote
129
+
130
+ path = quote(unquote(path), safe="/%")
131
+ return parts._replace(path=path, query="", params="", fragment="").geturl().rstrip("?")
132
+
133
+
134
+ def _ident_from_url(url: str) -> str:
135
+ path = unquote(urlparse(url.split("?")[0]).path)
136
+ name = Path(path).name
137
+ if name.lower() in ("", ".aspx", ".aspx/") or name.lower() == ".aspx":
138
+ # BoN getattachment/<uuid>/.aspx
139
+ m = re.search(r"getattachment/([0-9a-f-]{36})", url, re.I)
140
+ if m:
141
+ name = f"bon-{m.group(1)[:12]}"
142
+ else:
143
+ name = Path(path.rstrip("/")).name or "na-doc"
144
+ if name.lower().endswith(".pdf"):
145
+ name = name[:-4]
146
+ if name.lower().endswith(".aspx"):
147
+ name = name[:-5]
148
+ name = re.sub(r"\s+", " ", name).strip()
149
+ return re.sub(r"[^\w.\-]+", "-", name)[:160] or "na-doc"
150
+
151
+
152
+ def _host_ok(url: str) -> bool:
153
+ if not url or not url.startswith("http"):
154
+ return False
155
+ if BLOCK_HOST.search(url):
156
+ return False
157
+ host = (urlparse(url).hostname or "").lower()
158
+ ok = (
159
+ "parliament.na",
160
+ "bon.com.na",
161
+ "gov.na",
162
+ "moj.gov.na",
163
+ "mfpe.gov.na",
164
+ "opm.gov.na",
165
+ )
166
+ return any(host == s or host.endswith("." + s) for s in ok)
167
+
168
+
169
+ def _is_law_url(url: str) -> bool:
170
+ u = _norm(url)
171
+ if not _host_ok(u):
172
+ return False
173
+ low = unquote(u).lower()
174
+ if SKIP_NAME.search(low):
175
+ return False
176
+ # Historic laws.parliament.na statute book (live often 404 → Wayback)
177
+ if "laws.parliament.na" in low and "/cms_documents/" in low and ".pdf" in low:
178
+ return True
179
+ # BoN getattachment — accepted when discovered from Act/Determination pages
180
+ if "parliament.gov.na" in low and "/acts_documents/" in low and ".pdf" in low:
181
+ return True
182
+ if "bon.com.na" in low and "/getattachment/" in low:
183
+ return True
184
+ if "bon.com.na" in low and "/cmstemplates/bon/files/" in low and ".pdf" in low:
185
+ return True
186
+ if ".pdf" not in low:
187
+ return False
188
+ name = unquote(urlparse(u.split("?")[0]).path).split("/")[-1]
189
+ if SKIP_NAME.search(name):
190
+ return False
191
+ if LAWISH_NAME.search(name) or LAWISH_NAME.search(low):
192
+ return True
193
+ return False
194
+
195
+
196
+ def _title_from_text(text: str, fallback: str) -> str:
197
+ lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
198
+ for ln in lines[:60]:
199
+ if re.search(r"\b(ACT|BILL|REGULATIONS?|GAZETTE|DETERMINATION)\b", ln) and 8 <= len(ln) <= 180:
200
+ if not re.match(r"^(TITLE|PREVIOUS|NEXT|CONTENTS|EXPLANATORY)\b", ln, re.I):
201
+ return ln[:240]
202
+ for ln in lines:
203
+ if len(ln) >= 12 and not ln.lower().startswith("just a moment"):
204
+ return ln[:240]
205
+ return fallback[:240]
206
+
207
+
208
+ def _looks_like_law(text: str) -> bool:
209
+ if not text or len(text) < 200:
210
+ return False
211
+ head = text[:10000]
212
+ if LAW_MARK.search(head):
213
+ return True
214
+ secs = len(re.findall(r"(?im)^\s*Section\s+\d+", text[:25000]))
215
+ return secs >= 5
216
+
217
+
218
+ def _add(items: list, seen: set, url: str, ident: str | None = None) -> None:
219
+ url = _norm(url)
220
+ if not url or url in seen or not _is_law_url(url):
221
+ return
222
+ seen.add(url)
223
+ items.append((ident or _ident_from_url(url), url))
224
+
225
+
226
+ def pdf_ocr_text(raw: bytes, *, max_pages: int = 30, dpi: int = 160) -> str:
227
+ """OCR scanned / image-only official PDFs via pdftoppm + tesseract (eng)."""
228
+ if not raw or raw[:4] != b"%PDF":
229
+ return ""
230
+ max_pages = env_int("OCR_MAX_PAGES", max_pages)
231
+ try:
232
+ with tempfile.TemporaryDirectory() as d:
233
+ pdf = Path(d) / "in.pdf"
234
+ pdf.write_bytes(raw)
235
+ subprocess.run(
236
+ [
237
+ "pdftoppm",
238
+ "-png",
239
+ "-r",
240
+ str(dpi),
241
+ "-f",
242
+ "1",
243
+ "-l",
244
+ str(max_pages),
245
+ str(pdf),
246
+ str(Path(d) / "p"),
247
+ ],
248
+ check=False,
249
+ capture_output=True,
250
+ timeout=300,
251
+ )
252
+ pages = sorted(Path(d).glob("p*.png"))
253
+ chunks = []
254
+ for page in pages:
255
+ proc = subprocess.run(
256
+ ["tesseract", str(page), "stdout", "-l", "eng", "--psm", "6"],
257
+ capture_output=True,
258
+ timeout=180,
259
+ )
260
+ if proc.stdout:
261
+ chunks.append(proc.stdout.decode("utf-8", "replace"))
262
+ return "\n".join(chunks).strip()
263
+ except Exception as exc:
264
+ log.info("ocr fail: %s", exc)
265
+ return ""
266
+
267
+
268
+ def fetch_na(url: str) -> dict:
269
+ """Live (+Wayback of same official URL); OCR when OCR=1 for image-only PDFs."""
270
+ got = fetch_official_prefer_pdf(url, ua=UA, verify=False, min_text=180)
271
+ if got.get("status") == "success":
272
+ return got
273
+ if os.environ.get("OCR", "0") != "1":
274
+ return got
275
+ err = got.get("error") or ""
276
+ body = got.get("content") if isinstance(got.get("content"), (bytes, bytearray)) else b""
277
+ if not body or body[:4] != b"%PDF":
278
+ try:
279
+ r = live_get(url, ua=UA, verify=False, timeout=(15, 90), retries=2)
280
+ body = r.content or b""
281
+ except Exception:
282
+ body = b""
283
+ if (not body or body[:4] != b"%PDF") and "wayback" not in err:
284
+ try:
285
+ import archive_fallbacks as af
286
+
287
+ w = af.get_wayback_content(url)
288
+ if w.get("status") == "success":
289
+ body = w.get("content") or b""
290
+ if isinstance(body, str):
291
+ body = body.encode("latin-1", "replace")
292
+ except Exception:
293
+ pass
294
+ if body and body[:4] == b"%PDF":
295
+ text = pdf_ocr_text(bytes(body))
296
+ if len(text) >= 180:
297
+ got.update(
298
+ status="success",
299
+ text=text,
300
+ content=bytes(body),
301
+ method=(got.get("method") or "http") + "+ocr",
302
+ error="",
303
+ )
304
+ return got
305
+ got["error"] = (err or "") + ";ocr_short_or_failed"
306
+ return got
307
+
308
+
309
+ def _decode_data_pdf(html: str) -> bytes:
310
+ m = re.search(r"data:application/pdf;base64,([A-Za-z0-9+/=\s&#x0-9a-fA-F;]+)", html or "")
311
+ if not m:
312
+ return b""
313
+ b64 = m.group(1)
314
+ b64 = (
315
+ b64.replace("&#x2B;", "+")
316
+ .replace("&#x2F;", "/")
317
+ .replace("&#x3D;", "=")
318
+ .replace("&amp;", "&")
319
+ .replace("&#43;", "+")
320
+ )
321
+ b64 = re.sub(r"\s+", "", b64)
322
+ # strip residual HTML entities
323
+ b64 = re.sub(r"&#x[0-9a-fA-F]+;", "", b64)
324
+ b64 = re.sub(r"&#\d+;", "", b64)
325
+ try:
326
+ raw = base64.b64decode(b64, validate=False)
327
+ except Exception:
328
+ return b""
329
+ return raw if raw[:4] == b"%PDF" else b""
330
+
331
+
332
+ def _harvest_html(url: str) -> list[str]:
333
+ out = []
334
+ try:
335
+ r = live_get(url, ua=UA, verify=False, timeout=(20, 50))
336
+ except Exception as exc:
337
+ log.info("seed fail %s: %s", url[:90], exc)
338
+ return out
339
+ text = r.text or ""
340
+ for href in re.findall(r'href=["\']([^"\']+)["\']', text, re.I):
341
+ full = urljoin(url, href)
342
+ if ".pdf" in full.lower() or "/getattachment/" in full.lower():
343
+ out.append(full)
344
+ for m in re.findall(r'(https?://[^"\'\s>]+\.pdf)', text, re.I):
345
+ out.append(m)
346
+ return out
347
+
348
+
349
+ def _laws_parliament_bills() -> list[tuple[str, str, str]]:
350
+ """Return (ident, synthetic_source_url, detail_url) for Bill Tracking PDFs.
351
+
352
+ Instruments are stored against the Public/Bills/Details/<uuid> official URL;
353
+ PDF bytes are embedded as data:application/pdf;base64 on that page.
354
+ """
355
+ items, seen = [], set()
356
+ register = "https://laws.parliament.na/Bill-register"
357
+ try:
358
+ r = live_get(register, ua=UA, verify=False, timeout=(25, 70))
359
+ except Exception as exc:
360
+ log.info("bill register fail: %s", exc)
361
+ return items
362
+ ids = sorted(set(re.findall(r"/Public/Bills/Details/([0-9a-f-]{36})", r.text or "", re.I)))
363
+ log.info("laws.parliament.na bill ids %s", len(ids))
364
+ cap = env_int("BILL_DETAILS", 120)
365
+ for bid in ids[:cap]:
366
+ detail = f"https://laws.parliament.na/Public/Bills/Details/{bid}"
367
+ if detail in seen:
368
+ continue
369
+ seen.add(detail)
370
+ # Title from register table if present
371
+ m = re.search(
372
+ rf'href=["\']/Public/Bills/Details/{bid}["\'][^>]*>([^<]{{3,120}})',
373
+ r.text or "",
374
+ re.I,
375
+ )
376
+ label = (m.group(1).strip() if m else "") or f"bill-{bid[:8]}"
377
+ ident = re.sub(r"[^\w.\-]+", "-", label)[:120] or f"bill-{bid[:8]}"
378
+ items.append((ident, detail, detail))
379
+ return items
380
+
381
+
382
+ def _fetch_embedded_bill(detail_url: str) -> dict:
383
+ out = {
384
+ "status": "error",
385
+ "text": "",
386
+ "content": b"",
387
+ "source_url": detail_url,
388
+ "method": "",
389
+ "error": "",
390
+ }
391
+ try:
392
+ r = live_get(detail_url, ua=UA, verify=False, timeout=(30, 120), retries=2)
393
+ except Exception as exc:
394
+ out["error"] = f"live:{exc}"
395
+ return out
396
+ html = r.text or ""
397
+ title_m = re.search(r'<h2[^>]*class="[^"]*page-title[^"]*"[^>]*>([^<]+)', html, re.I)
398
+ page_title = (title_m.group(1).strip() if title_m else "")
399
+ raw = _decode_data_pdf(html)
400
+ if not raw:
401
+ out["error"] = "no_embedded_pdf"
402
+ return out
403
+ # text extract
404
+ from world_lib import pdf_to_text
405
+
406
+ text = pdf_to_text(raw)
407
+ method = "embedded_pdf"
408
+ if len(text) < 180 and os.environ.get("OCR", "0") == "1":
409
+ ocr = pdf_ocr_text(raw)
410
+ if len(ocr) > len(text):
411
+ text, method = ocr, "embedded_pdf+ocr"
412
+ if len(text) < 180:
413
+ out.update(error="pdf_extract_failed", content=raw)
414
+ return out
415
+ out.update(
416
+ status="success",
417
+ text=text,
418
+ content=raw,
419
+ method=method,
420
+ source_url=detail_url,
421
+ page_title=page_title,
422
+ )
423
+ return out
424
+
425
+
426
+ def _wp_json_media() -> list[tuple[str, str]]:
427
+ items, seen = [], set()
428
+ try:
429
+ import requests
430
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
431
+
432
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
433
+ except Exception:
434
+ return items
435
+ for page in range(1, env_int("WP_MEDIA_PAGES", 8) + 1):
436
+ url = (
437
+ "https://www.parliament.na/wp-json/wp/v2/media"
438
+ f"?per_page=100&page={page}&mime_type=application/pdf"
439
+ )
440
+ try:
441
+ r = requests.get(url, timeout=(20, 50), headers={"User-Agent": UA}, verify=False)
442
+ except Exception as exc:
443
+ log.info("wp media fail page %s: %s", page, exc)
444
+ break
445
+ if r.status_code != 200:
446
+ break
447
+ data = r.json() if r.content else []
448
+ if not data:
449
+ break
450
+ for it in data:
451
+ su = it.get("source_url") or ""
452
+ if not su or su in seen:
453
+ continue
454
+ if not _is_law_url(su):
455
+ continue
456
+ seen.add(su)
457
+ items.append((_ident_from_url(su), su))
458
+ log.info("wp-json lawish pdfs %s", len(items))
459
+ return items
460
+
461
+
462
+ def _bon_attachments() -> list[tuple[str, str]]:
463
+ items, seen = [], set()
464
+ pages = list(BON_SEED_PAGES)
465
+ # Expand Regulations.aspx child Act pages
466
+ try:
467
+ r = live_get("https://www.bon.com.na/Regulations.aspx", ua=UA, verify=False, timeout=(20, 50))
468
+ for href in re.findall(r'href=["\']([^"\']+)["\']', r.text or "", re.I):
469
+ full = urljoin("https://www.bon.com.na/Regulations.aspx", href)
470
+ if re.search(r"/Regulations/[^\"']+(Act|Regulation|Determination)", full, re.I):
471
+ if full not in pages:
472
+ pages.append(full)
473
+ except Exception as exc:
474
+ log.info("bon regulations index fail: %s", exc)
475
+
476
+ for page in pages[: env_int("BON_PAGES", 40)]:
477
+ try:
478
+ r = live_get(page, ua=UA, verify=False, timeout=(20, 50))
479
+ except Exception as exc:
480
+ log.info("bon page fail %s: %s", page[:80], exc)
481
+ continue
482
+ # Prefer labelled Act/Determination attachments near lawish anchor text
483
+ html = r.text or ""
484
+ for href in re.findall(r'href=["\']([^"\']*getattachment[^"\']*)["\']', html, re.I):
485
+ full = _norm(urljoin(page, href))
486
+ if full in seen:
487
+ continue
488
+ # Skip obvious image/css attachments by fetching later; filter by nearby text
489
+ seen.add(full)
490
+ # ident from surrounding context if possible
491
+ slug = Path(urlparse(page).path).name.replace(".aspx", "")
492
+ m = re.search(r"getattachment/([0-9a-f-]{36})", full, re.I)
493
+ uuid = m.group(1)[:12] if m else "att"
494
+ ident = f"{slug}-{uuid}"[:140]
495
+ items.append((ident, full))
496
+ log.info("bon attachments %s", len(items))
497
+ return items
498
+
499
+
500
+ def discover():
501
+ items, seen = [], set()
502
+
503
+ # 1) Live seed harvest (parliament + BoN HTML)
504
+ for su in LIVE_SEEDS:
505
+ for href in _harvest_html(su):
506
+ _add(items, seen, href)
507
+
508
+ # 2) Parliament wp-json media (Bill/Act PDFs)
509
+ for ident, url in _wp_json_media():
510
+ _add(items, seen, url, ident)
511
+
512
+ # 3) BoN Act / Determination / Regulation attachments
513
+ for ident, url in _bon_attachments():
514
+ # BoN getattachment always allowed when harvested from Act pages
515
+ url = _norm(url)
516
+ if not url or url in seen or not _host_ok(url):
517
+ continue
518
+ if BLOCK_HOST.search(url):
519
+ continue
520
+ seen.add(url)
521
+ items.append((ident, url))
522
+
523
+ # 4) CDX of official hosts
524
+ limit = env_int("CDX_LIMIT", 500)
525
+ for prefix in CDX_PREFIXES:
526
+ for h in cdx_urls(prefix, limit=limit, match_type="prefix", extra_filters=["mimetype:application/pdf"]):
527
+ orig = (h.get("original") or "").replace("http://", "https://")
528
+ _add(items, seen, orig)
529
+ if len(items) >= env_int("CATALOG_CAP", 500):
530
+ break
531
+
532
+ log.info("catalog pdf/attach %s", len(items))
533
+ return items
534
+
535
+
536
+ def main():
537
+ setup_log(CC)
538
+ t0 = utcnow()
539
+ max_new = env_int("MAX_NEW", 80)
540
+ max_seconds = env_int("MAX_SECONDS", 3600)
541
+ t_start = time.time()
542
+ done = existing_ids(CC)
543
+ ok = skip = fail = 0
544
+
545
+ # A) Embedded Bill PDFs from laws.parliament.na (priority — official Bill Tracking)
546
+ for ident, source_url, detail in _laws_parliament_bills():
547
+ if max_new and ok >= max_new:
548
+ break
549
+ if time.time() - t_start > max_seconds:
550
+ break
551
+ rid = slug_id(CC, ident)
552
+ if rid in done:
553
+ skip += 1
554
+ continue
555
+ got = _fetch_embedded_bill(detail)
556
+ text = got.get("text") or ""
557
+ if got.get("status") != "success":
558
+ fail += 1
559
+ log_failure(CC, {"identifier": ident, "source_url": source_url, "reason": got.get("error")})
560
+ continue
561
+ if not _looks_like_law(text):
562
+ fail += 1
563
+ log_failure(CC, {"identifier": ident, "source_url": source_url, "reason": "not_law_like"})
564
+ continue
565
+ title = got.get("page_title") or _title_from_text(text, ident)
566
+ if save_instrument(
567
+ cc=CC,
568
+ country=COUNTRY,
569
+ language=LANG,
570
+ ident=ident,
571
+ title=title,
572
+ text=text,
573
+ source_url=source_url,
574
+ source_type=SOURCE_TYPE,
575
+ license_text=LICENSE,
576
+ collector="collect_na.py",
577
+ article_re=ART,
578
+ extra_meta={"fetch_method": got.get("method"), "portal": "laws.parliament.na"},
579
+ ):
580
+ ok += 1
581
+ done.add(rid)
582
+ log.info("ok bill %s chars=%s method=%s", ident[:70], len(text), got.get("method"))
583
+ else:
584
+ fail += 1
585
+
586
+ # B) Direct PDF / BoN attachment catalog
587
+ for ident, url in discover():
588
+ if max_new and ok >= max_new:
589
+ break
590
+ if time.time() - t_start > max_seconds:
591
+ break
592
+ rid = slug_id(CC, ident)
593
+ if rid in done:
594
+ skip += 1
595
+ continue
596
+ got = fetch_na(url)
597
+ text = got.get("text") or ""
598
+ if got.get("status") != "success":
599
+ fail += 1
600
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")})
601
+ continue
602
+ if not _looks_like_law(text):
603
+ fail += 1
604
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "not_law_like"})
605
+ continue
606
+ title = _title_from_text(text, ident)
607
+ if save_instrument(
608
+ cc=CC,
609
+ country=COUNTRY,
610
+ language=LANG,
611
+ ident=ident,
612
+ title=title,
613
+ text=text,
614
+ source_url=url,
615
+ source_type=SOURCE_TYPE,
616
+ license_text=LICENSE,
617
+ collector="collect_na.py",
618
+ article_re=ART,
619
+ extra_meta={"fetch_method": got.get("method")},
620
+ ):
621
+ ok += 1
622
+ done.add(rid)
623
+ log.info("ok %s chars=%s method=%s", ident[:70], len(text), got.get("method"))
624
+ else:
625
+ fail += 1
626
+
627
+ write_summary(
628
+ CC,
629
+ country=COUNTRY,
630
+ source="Namibia Parliament (parliament.na / laws.parliament.na) + Bank of Namibia",
631
+ source_urls=[
632
+ "https://www.parliament.na/",
633
+ "https://laws.parliament.na/",
634
+ "https://laws.parliament.na/Bill-register",
635
+ "https://www.bon.com.na/Regulations.aspx",
636
+ "https://www.gov.na/",
637
+ ],
638
+ license_text=LICENSE,
639
+ discovered=ok + skip + fail,
640
+ fetched=ok,
641
+ skipped=skip,
642
+ failed=fail,
643
+ coverage=(
644
+ "catalog-backed incomplete; lac.org.na skipped by policy; "
645
+ "gov.na/moj.gov.na/mfpe.gov.na unreachable or SSL-fail from collector host; "
646
+ "full Government Gazette series not on parliament.na"
647
+ ),
648
+ notes=(
649
+ "Official Bills from laws.parliament.na Bill Tracking (embedded PDFs) and "
650
+ "parliament.na wp-content; BoN Act/Determination/Regulation getattachment PDFs. "
651
+ "Skipped lac.org.na / NamibLII / SAFLII. OCR when OCR=1. Not legal advice."
652
+ ),
653
+ last_run=t0,
654
+ )
655
+ log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
656
+
657
+
658
+ if __name__ == "__main__":
659
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import traceback
14
+ from collections import Counter
15
+ from datetime import datetime, timezone, timedelta
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Any, Iterable, Optional
19
+ from xml.etree import ElementTree as ET
20
+
21
+ import requests
22
+ from requests.adapters import HTTPAdapter
23
+
24
+ ROOT = Path("/workspace/legal-corpora")
25
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
26
+ PT = timezone(timedelta(hours=-7))
27
+ DEFAULT_UA = (
28
+ "legal-corpora-collector/1.0 "
29
+ "(research archive of official national gazettes; polite; "
30
+ "no commercial scraping; contact via local operator)"
31
+ )
32
+ INDEX_FIELDS = (
33
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
34
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
35
+ "article_count", "bytes",
36
+ )
37
+
38
+ _tls = threading.local()
39
+ _index_lock = threading.Lock()
40
+ _fail_lock = threading.Lock()
41
+ _schema = None
42
+ _schema_lock = threading.Lock()
43
+
44
+
45
+ def utcnow() -> str:
46
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
47
+
48
+
49
+ def pt_from_iso(iso: str) -> str:
50
+ try:
51
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
52
+ except Exception:
53
+ return iso
54
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
55
+
56
+
57
+ def localtag(tag: str) -> str:
58
+ return tag.rsplit("}", 1)[-1]
59
+
60
+
61
+ def slug_id(cc: str, official: str) -> str:
62
+ s = (official or "").strip()
63
+ s = s.replace("https://", "").replace("http://", "")
64
+ s = re.sub(r"[/\\]+", "__", s)
65
+ s = re.sub(r"\s+", "_", s)
66
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
67
+ s = s.strip("-._")
68
+ if not s:
69
+ s = "unknown"
70
+ s = s.lower()
71
+ if not s.startswith(cc.lower() + "-"):
72
+ s = f"{cc.lower()}-{s}"
73
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
74
+ s = "x" + s
75
+ return s[:180]
76
+
77
+
78
+ def atomic_write(path: Path, text: str) -> None:
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
81
+ try:
82
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
83
+ handle.write(text)
84
+ os.replace(tmp, path)
85
+ except Exception:
86
+ try:
87
+ os.unlink(tmp)
88
+ except OSError:
89
+ pass
90
+ raise
91
+
92
+
93
+ def sha256_text(s: str) -> str:
94
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
95
+
96
+
97
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
98
+ s = getattr(_tls, "session", None)
99
+ if s is None or getattr(_tls, "ua", None) != ua:
100
+ s = requests.Session()
101
+ s.headers.update({
102
+ "User-Agent": ua,
103
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
104
+ "Accept-Language": "en,*;q=0.8",
105
+ })
106
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
107
+ s.mount("https://", ad)
108
+ s.mount("http://", ad)
109
+ _tls.session = s
110
+ _tls.ua = ua
111
+ return s
112
+
113
+
114
+ def http_get(
115
+ url: str,
116
+ *,
117
+ ua: str = DEFAULT_UA,
118
+ timeout: tuple = (20, 90),
119
+ retries: int = 5,
120
+ sleep: float = 0.35,
121
+ headers: Optional[dict] = None,
122
+ params: Optional[dict] = None,
123
+ allow_empty: bool = False,
124
+ ) -> requests.Response:
125
+ last = None
126
+ hdrs = headers or {}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ if sleep:
130
+ time.sleep(sleep)
131
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
132
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
133
+ time.sleep(min(30, 2 ** attempt))
134
+ last = resp
135
+ continue
136
+ if resp.status_code == 200 and (allow_empty or resp.content):
137
+ return resp
138
+ if resp.status_code in (404, 410, 403, 401):
139
+ return resp
140
+ last = resp
141
+ if attempt < retries:
142
+ time.sleep(min(20, 1.5 * attempt))
143
+ continue
144
+ return resp
145
+ except requests.RequestException as exc:
146
+ last = exc
147
+ time.sleep(min(20, 1.5 * attempt))
148
+ if isinstance(last, requests.Response):
149
+ return last
150
+ raise RuntimeError(f"GET failed {url}: {last}")
151
+
152
+
153
+ class _HTMLText(HTMLParser):
154
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
155
+
156
+ def __init__(self) -> None:
157
+ super().__init__(convert_charrefs=True)
158
+ self.parts: list[str] = []
159
+ self.skip = 0
160
+ self._block = {
161
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
162
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
163
+ }
164
+
165
+ def handle_starttag(self, tag, attrs):
166
+ if tag in self.SKIP:
167
+ self.skip += 1
168
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
169
+ self.parts.append("\n")
170
+
171
+ def handle_endtag(self, tag):
172
+ if tag in self.SKIP and self.skip:
173
+ self.skip -= 1
174
+ if tag in self._block and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_data(self, data):
178
+ if self.skip == 0:
179
+ self.parts.append(data)
180
+
181
+
182
+ def html_to_text(raw: str) -> str:
183
+ if not raw:
184
+ return ""
185
+ p = _HTMLText()
186
+ try:
187
+ p.feed(raw)
188
+ p.close()
189
+ except Exception:
190
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
191
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
192
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
193
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
194
+ text = "".join(p.parts)
195
+ text = html.unescape(text)
196
+ text = text.replace("\xa0", " ")
197
+ text = re.sub(r"[ \t]+", " ", text)
198
+ text = re.sub(r"\n[ \t]+", "\n", text)
199
+ text = re.sub(r"\n{3,}", "\n\n", text)
200
+ return text.strip()
201
+
202
+
203
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
204
+ skip_tags = skip_tags or {
205
+ "meta", "identification", "references", "classification",
206
+ "workflow", "analysis", "proprietary", "presentation",
207
+ }
208
+ try:
209
+ root = ET.fromstring(raw)
210
+ except ET.ParseError:
211
+ return html_to_text(raw)
212
+ parts: list[str] = []
213
+
214
+ def walk(el: ET.Element) -> None:
215
+ tag = localtag(el.tag).lower()
216
+ if tag in skip_tags:
217
+ return
218
+ if el.text and el.text.strip():
219
+ parts.append(el.text.strip())
220
+ for child in list(el):
221
+ walk(child)
222
+ if child.tail and child.tail.strip():
223
+ parts.append(child.tail.strip())
224
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
225
+ parts.append("\n")
226
+
227
+ walk(root)
228
+ text = " ".join(parts)
229
+ text = re.sub(r"[ \t]+", " ", text)
230
+ text = re.sub(r" *\n *", "\n", text)
231
+ text = re.sub(r"\n{3,}", "\n\n", text)
232
+ return text.strip()
233
+
234
+
235
+ ARTICLE_SPLIT = re.compile(
236
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
237
+ r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"
238
+ r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"
239
+ r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b"
240
+ )
241
+
242
+
243
+
244
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
245
+ if not text or len(text) < 40:
246
+ return []
247
+ matches = list(ARTICLE_SPLIT.finditer(text))
248
+ if len(matches) < 2:
249
+ return []
250
+ docs = []
251
+ for i, m in enumerate(matches):
252
+ start = m.start()
253
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
254
+ chunk = text[start:end].strip()
255
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
256
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
257
+ heading = chunk.split("\n", 1)[0][:200]
258
+ docs.append({
259
+ "id": f"{law_id}-{aid}"[:180],
260
+ "title": heading,
261
+ "text": chunk,
262
+ "date_filed": date,
263
+ "document_number": num,
264
+ "source_url": source_url,
265
+ "record_type": "article",
266
+ "article_number": num,
267
+ "law_identifier": law_id,
268
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
269
+ })
270
+ if len(docs) >= 4000:
271
+ break
272
+ return docs
273
+
274
+
275
+ def load_schema():
276
+ global _schema
277
+ with _schema_lock:
278
+ if _schema is None:
279
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
280
+ _schema = json.load(f)
281
+ return _schema
282
+
283
+
284
+ def validate_record(record: dict) -> Optional[str]:
285
+ try:
286
+ import jsonschema
287
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
288
+ return None
289
+ except Exception as exc:
290
+ return str(exc)
291
+
292
+
293
+ def existing_ids(cc: str) -> set[str]:
294
+ d = ROOT / cc / "instruments"
295
+ if not d.exists():
296
+ return set()
297
+ return {p.stem for p in d.glob("*.json")}
298
+
299
+
300
+ def write_instrument(cc: str, record: dict) -> Path:
301
+ ident = record["id"]
302
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
303
+ dest.parent.mkdir(parents=True, exist_ok=True)
304
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
305
+ atomic_write(dest, body)
306
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
307
+ index_line["path"] = f"instruments/{ident}.json"
308
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
309
+ index_line["bytes"] = dest.stat().st_size
310
+ index_line["id"] = ident
311
+ with _index_lock:
312
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
313
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
314
+ return dest
315
+
316
+
317
+ def log_failure(cc: str, payload: dict) -> None:
318
+ path = ROOT / cc / "failures.jsonl"
319
+ path.parent.mkdir(parents=True, exist_ok=True)
320
+ payload = dict(payload)
321
+ payload.setdefault("retrieved_at", utcnow())
322
+ with _fail_lock:
323
+ with path.open("a", encoding="utf-8") as handle:
324
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
325
+
326
+
327
+ def append_catalog(cc: str, row: dict) -> None:
328
+ path = ROOT / cc / "raw" / "catalog.jsonl"
329
+ path.parent.mkdir(parents=True, exist_ok=True)
330
+ with _index_lock:
331
+ with path.open("a", encoding="utf-8") as handle:
332
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
333
+
334
+
335
+ def law_status_hist(cc: str) -> Counter:
336
+ c: Counter = Counter()
337
+ d = ROOT / cc / "instruments"
338
+ if not d.exists():
339
+ return c
340
+ for p in d.glob("*.json"):
341
+ try:
342
+ rec = json.loads(p.read_text(encoding="utf-8"))
343
+ c[rec.get("law_status") or "unknown"] += 1
344
+ except Exception:
345
+ c["unknown"] += 1
346
+ return c
347
+
348
+
349
+ def corpus_bytes(cc: str) -> int:
350
+ d = ROOT / cc / "instruments"
351
+ if not d.exists():
352
+ return 0
353
+ return sum(p.stat().st_size for p in d.glob("*.json"))
354
+
355
+
356
+ def count_jsonl(path: Path) -> int:
357
+ if not path.exists():
358
+ return 0
359
+ n = 0
360
+ with path.open(encoding="utf-8") as f:
361
+ for _ in f:
362
+ n += 1
363
+ return n
364
+
365
+
366
+ def write_summary(
367
+ cc: str,
368
+ *,
369
+ country: str,
370
+ source: str,
371
+ source_urls: Iterable[str],
372
+ license_text: str,
373
+ discovered: int,
374
+ fetched: int,
375
+ skipped: int,
376
+ failed: int,
377
+ coverage: str,
378
+ notes: str,
379
+ last_run: Optional[str] = None,
380
+ extra: Optional[str] = None,
381
+ ) -> None:
382
+ last_run = last_run or utcnow()
383
+ instr = ROOT / cc / "instruments"
384
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
385
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
386
+ hist = law_status_hist(cc)
387
+ nbytes = corpus_bytes(cc)
388
+ lines = [
389
+ f"# {country} legislation corpus",
390
+ "",
391
+ f"- jurisdiction: {cc.upper()}",
392
+ f"- source: {source}",
393
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
394
+ f"- instruments_json: {n_json}",
395
+ f"- index_jsonl_lines: {n_index}",
396
+ f"- discovered: {discovered}",
397
+ f"- fetched: {fetched}",
398
+ f"- skipped: {skipped}",
399
+ f"- failed: {failed}",
400
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
401
+ f"- coverage: {coverage}",
402
+ f"- total_json_bytes: {nbytes}",
403
+ f"- license: {license_text}",
404
+ "- source_urls:",
405
+ ]
406
+ for u in source_urls:
407
+ lines.append(f" - {u}")
408
+ lines.append("- notes:")
409
+ for n in (notes or "").splitlines():
410
+ lines.append(f" {n}")
411
+ if extra:
412
+ lines.append("")
413
+ lines.append(extra)
414
+ lines.append("")
415
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
416
+
417
+
418
+ def base_record(
419
+ *,
420
+ cc: str,
421
+ country: str,
422
+ language: str,
423
+ ident: str,
424
+ title: str,
425
+ text: str,
426
+ source_url: str,
427
+ source_type: str,
428
+ license_text: str,
429
+ collector: str,
430
+ eli: Optional[str] = None,
431
+ date: Optional[str] = None,
432
+ official_identifier: Optional[str] = None,
433
+ document_type: str = "statute",
434
+ law_status: str = "current",
435
+ is_current: Optional[bool] = True,
436
+ documents: Optional[list] = None,
437
+ extra_meta: Optional[dict] = None,
438
+ extra_fields: Optional[dict] = None,
439
+ ) -> dict:
440
+ rid = slug_id(cc, ident)
441
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
442
+ rec = {
443
+ "schema_version": "collection_record.v1",
444
+ "record_type": "law",
445
+ "id": rid,
446
+ "title": title or ident,
447
+ "text": text or "",
448
+ "source_url": source_url,
449
+ "source_type": source_type,
450
+ "date": date,
451
+ "jurisdiction": cc.upper(),
452
+ "country": country,
453
+ "language": language,
454
+ "eli": eli,
455
+ "license": license_text,
456
+ "retrieved_at": utcnow(),
457
+ "identifier": official_identifier or ident,
458
+ "official_identifier": official_identifier or ident,
459
+ "law_identifier": official_identifier or ident,
460
+ "document_type": document_type,
461
+ "law_status": law_status,
462
+ "is_current": is_current,
463
+ "canonical_law_url": source_url,
464
+ "article_count": len(docs),
465
+ "article_extraction_status": "ok" if docs else "missing",
466
+ "documents": docs,
467
+ "metadata": {
468
+ "collector": collector,
469
+ "schema": "collection_record.v1",
470
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
471
+ "content_sha256": sha256_text(text or ""),
472
+ "rights": {
473
+ "not_legal_advice": True,
474
+ "official_reuse_url": source_url,
475
+ "license": license_text,
476
+ },
477
+ "text_extraction": {"source": "official", "backend": "collector"},
478
+ },
479
+ }
480
+ if extra_meta:
481
+ rec["metadata"].update(extra_meta)
482
+ if extra_fields:
483
+ rec.update(extra_fields)
484
+ return rec
485
+
486
+
487
+ def ensure_dirs(cc: str) -> Path:
488
+ root = ROOT / cc
489
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
490
+ (root / "raw").mkdir(parents=True, exist_ok=True)
491
+ (root / "logs").mkdir(parents=True, exist_ok=True)
492
+ return root
493
+
494
+
495
+ def iso_date(val: Optional[str]) -> Optional[str]:
496
+ if not val:
497
+ return None
498
+ val = str(val).strip()
499
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
500
+ if m:
501
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
502
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
503
+ if m:
504
+ return m.group(1)
505
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
506
+ if m:
507
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
508
+ return None
scrapers/pdf_extract_lib.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PDF text extraction helpers mirroring ipfs_datasets_py IntegratedPDFProcessor.
3
+
4
+ Prefer pdfplumber -> pymupdf -> pdftotext; OCR (tesseract) only when text layer
5
+ is missing or garbage. Honest article splits require >=2 heading matches.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import logging
11
+ import re
12
+ import subprocess
13
+ import tempfile
14
+ from typing import Optional
15
+
16
+ log = logging.getLogger("pdf_extract_lib")
17
+
18
+ # Spaced-out OCR garbage like "D IA R IO"
19
+ _GARBAGE_SPACING = re.compile(r"(?:^[A-Za-z]\s+){6,}", re.M)
20
+
21
+
22
+ def is_garbage_text(text: str) -> bool:
23
+ if not text or len(text) < 40:
24
+ return True
25
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
26
+ return True
27
+ if "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:
28
+ return True
29
+ sample = text[:4000]
30
+ letters = sum(ch.isalpha() for ch in sample)
31
+ spaces = sample.count(" ")
32
+ if letters < 80:
33
+ return True
34
+ if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):
35
+ return True
36
+ # high ratio of isolated single letters
37
+ singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))
38
+ if singles > 30 and singles > letters * 0.15:
39
+ return True
40
+ return False
41
+
42
+
43
+ def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
44
+ import pdfplumber
45
+ with pdfplumber.open(io.BytesIO(raw)) as pdf:
46
+ n = len(pdf.pages)
47
+ parts = []
48
+ for page in pdf.pages[:max_pages]:
49
+ try:
50
+ parts.append(page.extract_text() or "")
51
+ except Exception:
52
+ continue
53
+ text = "\n".join(parts)
54
+ text = re.sub(r"[ \t]+", " ", text)
55
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
56
+ return text, n
57
+
58
+
59
+ def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
60
+ import pymupdf
61
+ doc = pymupdf.open(stream=raw, filetype="pdf")
62
+ n = doc.page_count
63
+ parts = [page.get_text() for page in doc[:max_pages]]
64
+ text = "\n".join(parts)
65
+ text = re.sub(r"[ \t]+", " ", text)
66
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
67
+ return text, n
68
+
69
+
70
+ def extract_pdftotext(raw: bytes) -> str:
71
+ if not raw or raw[:4] != b"%PDF":
72
+ return ""
73
+ try:
74
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
75
+ tmp.write(raw)
76
+ tmp.flush()
77
+ proc = subprocess.run(
78
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
79
+ check=False, capture_output=True, timeout=180,
80
+ )
81
+ if proc.returncode == 0 and proc.stdout:
82
+ return proc.stdout.decode("utf-8", "replace").strip()
83
+ except Exception as exc:
84
+ log.warning("pdftotext: %s", exc)
85
+ return ""
86
+
87
+
88
+ def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]:
89
+ """Render pages with pymupdf and OCR via tesseract CLI."""
90
+ import pymupdf
91
+ doc = pymupdf.open(stream=raw, filetype="pdf")
92
+ n = doc.page_count
93
+ parts = []
94
+ mat = pymupdf.Matrix(dpi / 72, dpi / 72)
95
+ for i, page in enumerate(doc):
96
+ if i >= max_pages:
97
+ break
98
+ pix = page.get_pixmap(matrix=mat, alpha=False)
99
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img:
100
+ pix.save(img.name)
101
+ img_path = img.name
102
+ try:
103
+ env = dict(**__import__("os").environ)
104
+ env["OMP_THREAD_LIMIT"] = "1"
105
+ env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata")
106
+ proc = subprocess.run(
107
+ ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"],
108
+ capture_output=True, text=True, timeout=180, env=env,
109
+ )
110
+ if proc.returncode == 0 and proc.stdout:
111
+ parts.append(proc.stdout)
112
+ except Exception as exc:
113
+ log.debug("ocr page %s: %s", i, exc)
114
+ finally:
115
+ try:
116
+ import os
117
+ os.unlink(img_path)
118
+ except Exception:
119
+ pass
120
+ text = "\n".join(parts)
121
+ text = re.sub(r"[ \t]+", " ", text)
122
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
123
+ return text, n
124
+
125
+
126
+ def extract_pdf_text(
127
+ raw: bytes,
128
+ *,
129
+ enable_ocr: bool = True,
130
+ ocr_lang: str = "eng",
131
+ ocr_max_pages: int = 40,
132
+ ) -> tuple[str, str, int]:
133
+ """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order."""
134
+ if not raw:
135
+ return "", "not_pdf", 0
136
+ if raw[:4] != b"%PDF":
137
+ idx = raw.find(b"%PDF", 0, 65536)
138
+ if idx < 0:
139
+ return "", "not_pdf", 0
140
+ raw = raw[idx:]
141
+ best_text, best_method, pages = "", "failed", 0
142
+ for name, fn in (
143
+ ("pdfplumber", lambda: extract_pdfplumber(raw)),
144
+ ("pymupdf", lambda: extract_pymupdf(raw)),
145
+ ):
146
+ try:
147
+ text, pages = fn()
148
+ if text and not is_garbage_text(text) and len(text) >= 80:
149
+ return text, name, pages
150
+ if len(text) > len(best_text):
151
+ best_text, best_method = text, name
152
+ except Exception as exc:
153
+ log.debug("%s failed: %s", name, exc)
154
+ try:
155
+ text = extract_pdftotext(raw)
156
+ if text and not is_garbage_text(text) and len(text) >= 80:
157
+ return text, "pdftotext", pages
158
+ if len(text) > len(best_text):
159
+ best_text, best_method = text, "pdftotext"
160
+ except Exception:
161
+ pass
162
+ if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120):
163
+ try:
164
+ text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages)
165
+ if text and len(text) >= 80 and not is_garbage_text(text):
166
+ return text, "ocr_tesseract", pages
167
+ if len(text) > len(best_text):
168
+ best_text, best_method = text, "ocr_tesseract"
169
+ except Exception as exc:
170
+ log.debug("ocr failed: %s", exc)
171
+ return best_text, best_method if best_text else "failed", pages
172
+
173
+
174
+ def normalize_bidi(text: str) -> str:
175
+ return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069]", "", text or "")
176
+
177
+
178
+ def split_by_pattern(
179
+ text: str,
180
+ law_id: str,
181
+ source_url: str,
182
+ pat: re.Pattern,
183
+ record_type: str = "article",
184
+ min_chunk: int = 40,
185
+ max_docs: int = 4000,
186
+ ) -> list[dict]:
187
+ matches = list(pat.finditer(text or ""))
188
+ if len(matches) < 2:
189
+ return []
190
+ docs = []
191
+ for i, m in enumerate(matches):
192
+ start = m.start()
193
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
194
+ chunk = text[start:end].strip()
195
+ if len(chunk) < min_chunk:
196
+ continue
197
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
198
+ aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80]
199
+ heading = chunk.split("\n", 1)[0][:200]
200
+ docs.append({
201
+ "id": f"{law_id}-{aid}"[:180],
202
+ "title": heading,
203
+ "text": chunk,
204
+ "date_filed": None,
205
+ "document_number": num,
206
+ "source_url": source_url,
207
+ "record_type": record_type,
208
+ "article_number": num,
209
+ "law_identifier": law_id,
210
+ "metadata": {
211
+ "text_extraction": {
212
+ "source": "official",
213
+ "backend": "honest_heading_split",
214
+ "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split",
215
+ "pattern": pat.pattern[:100],
216
+ }
217
+ },
218
+ })
219
+ if len(docs) >= max_docs:
220
+ break
221
+ return docs if len(docs) >= 2 else []
222
+
223
+
224
+ # Country-specific honest patterns (tried in order)
225
+ COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = {
226
+ "sv": [
227
+ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"),
228
+ ],
229
+ "tn": [
230
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"),
231
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
232
+ ],
233
+ "et": [
234
+ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"),
235
+ ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
236
+ ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"),
237
+ ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"),
238
+ ],
239
+ "jm": [
240
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"),
241
+ ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"),
242
+ ],
243
+ "fj": [
244
+ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"),
245
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"),
246
+ ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"),
247
+ ],
248
+ "la": [
249
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"),
250
+ ],
251
+ "lk": [
252
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"),
253
+ ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"),
254
+ ],
255
+ "md": [
256
+ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"),
257
+ ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"),
258
+ ],
259
+ "mz": [
260
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
261
+ ],
262
+ }
263
+
264
+
265
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
266
+ text_n = normalize_bidi(text) if cc == "tn" else text
267
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
268
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
269
+ if docs:
270
+ return docs, name
271
+ # shared fallback
272
+ from common import split_articles
273
+ docs = split_articles(text_n, law_id, source_url)
274
+ if len(docs) >= 2:
275
+ return docs, "common_article_split"
276
+ return [], "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for new-country official gazette collectors."""
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import time
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Optional
14
+ from urllib.parse import urljoin, urlparse
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ from common import (
18
+ ROOT,
19
+ DEFAULT_UA,
20
+ base_record,
21
+ ensure_dirs,
22
+ existing_ids,
23
+ html_to_text,
24
+ http_get,
25
+ iso_date,
26
+ log_failure,
27
+ slug_id,
28
+ split_articles,
29
+ utcnow,
30
+ write_instrument,
31
+ write_summary,
32
+ )
33
+ import archive_fallbacks as af
34
+
35
+ log = logging.getLogger("world_lib")
36
+
37
+ MIN_TEXT = 80
38
+ MAX_PDF = 35 * 1024 * 1024
39
+
40
+
41
+ def setup_log(cc: str, name: str | None = None) -> None:
42
+ ensure_dirs(cc)
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s %(levelname)s %(message)s",
46
+ handlers=[
47
+ logging.FileHandler(ROOT / cc / "logs" / "collector.log", encoding="utf-8"),
48
+ logging.StreamHandler(sys.stdout),
49
+ ],
50
+ force=True,
51
+ )
52
+
53
+
54
+ def pdf_to_text(raw: bytes) -> str:
55
+ """Extract text via pdftotext. Tries qpdf --decrypt first for copy-restricted
56
+ digital PDFs (still not OCR — image-only scans stay empty)."""
57
+ if not raw:
58
+ return ""
59
+ if raw[:4] != b"%PDF":
60
+ idx = raw.find(b"%PDF")
61
+ if idx < 0 or idx > 8192:
62
+ return ""
63
+ raw = raw[idx:]
64
+ try:
65
+ with tempfile.TemporaryDirectory() as d:
66
+ dpath = Path(d)
67
+ src = dpath / "in.pdf"
68
+ src.write_bytes(raw)
69
+ candidates = [src]
70
+ dec = dpath / "dec.pdf"
71
+ try:
72
+ q = subprocess.run(
73
+ ["qpdf", "--decrypt", str(src), str(dec)],
74
+ check=False,
75
+ capture_output=True,
76
+ timeout=120,
77
+ )
78
+ if q.returncode == 0 and dec.exists() and dec.stat().st_size > 1000:
79
+ candidates.insert(0, dec)
80
+ except Exception:
81
+ pass
82
+ best = ""
83
+ for cand in candidates:
84
+ for args in (
85
+ ["pdftotext", "-layout", "-enc", "UTF-8", str(cand), "-"],
86
+ ["pdftotext", "-raw", "-enc", "UTF-8", str(cand), "-"],
87
+ ):
88
+ proc = subprocess.run(
89
+ args, check=False, capture_output=True, timeout=180
90
+ )
91
+ if proc.returncode == 0 and proc.stdout:
92
+ text = proc.stdout.decode("utf-8", "replace").strip()
93
+ # Ignore form-feed-only / tiny junk from image-only pages
94
+ if len(text) > len(best):
95
+ best = text
96
+ if len(best) >= 150:
97
+ break
98
+ return best
99
+ except Exception as exc:
100
+ log.warning("pdftotext: %s", exc)
101
+ return ""
102
+
103
+
104
+ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]:
105
+ docs = split_articles(text, law_id, source_url, date)
106
+ if not pattern:
107
+ return docs
108
+ matches = list(pattern.finditer(text or ""))
109
+ if len(matches) < 2:
110
+ return docs if len(docs) >= 2 else []
111
+ out = []
112
+ for i, m in enumerate(matches):
113
+ start = m.start()
114
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
115
+ chunk = text[start:end].strip()
116
+ if len(chunk) < 20:
117
+ continue
118
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
119
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]
120
+ heading = chunk.split("\n", 1)[0][:200]
121
+ out.append({
122
+ "id": f"{law_id}-{aid}"[:180],
123
+ "title": heading,
124
+ "text": chunk,
125
+ "date_filed": date,
126
+ "document_number": num,
127
+ "source_url": source_url,
128
+ "record_type": "article",
129
+ "article_number": num,
130
+ "law_identifier": law_id,
131
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
132
+ })
133
+ if len(out) >= 4000:
134
+ break
135
+ return out if len(out) >= 2 else docs
136
+
137
+
138
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
139
+ import requests
140
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
141
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
142
+ last = None
143
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
144
+ for attempt in range(1, retries + 1):
145
+ try:
146
+ time.sleep(0.2)
147
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
148
+ return resp
149
+ except Exception as exc:
150
+ last = exc
151
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
152
+ try:
153
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
154
+ return resp
155
+ except Exception as exc2:
156
+ last = exc2
157
+ time.sleep(min(8, 1.5 * attempt))
158
+ raise RuntimeError(f"live_get failed {url}: {last}")
159
+
160
+
161
+ def fetch_official(
162
+ url: str,
163
+ *,
164
+ ua: str = DEFAULT_UA,
165
+ verify: bool = True,
166
+ wayback: bool = True,
167
+ wayback_ts: Optional[str] = None,
168
+ min_text: int = MIN_TEXT,
169
+ ) -> dict:
170
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
171
+ out = {
172
+ "status": "error",
173
+ "text": "",
174
+ "content": b"",
175
+ "source_url": url,
176
+ "method": "",
177
+ "content_type": "",
178
+ "error": "",
179
+ }
180
+ body = b""
181
+ ctype = ""
182
+ try:
183
+ r = live_get(url, ua=ua, verify=verify)
184
+ body = r.content or b""
185
+ ctype = r.headers.get("content-type") or ""
186
+ if r.status_code == 200 and body:
187
+ is_pdf = (
188
+ body[:4] == b"%PDF"
189
+ or (0 <= body.find(b"%PDF") <= 64)
190
+ or "pdf" in ctype.lower()
191
+ )
192
+ if is_pdf:
193
+ text = pdf_to_text(body)
194
+ if len(text) >= min_text:
195
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
196
+ return out
197
+ text = ""
198
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
199
+ raw = body.decode(r.encoding or "utf-8", "replace")
200
+ if af.is_challenge(raw, r.status_code):
201
+ out["error"] = "challenge_or_shell"
202
+ else:
203
+ text = html_to_text(raw) if "<" in raw[:500] else raw
204
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
205
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
206
+ return out
207
+ if len(text) < min_text:
208
+ out["error"] = "short_or_spa"
209
+ elif body[:4] == b"%PDF" or (0 <= body.find(b"%PDF") <= 64):
210
+ # Keep bytes so callers (OCR) can work without a second download
211
+ pdf_body = body if body[:4] == b"%PDF" else body[body.find(b"%PDF"):]
212
+ out["error"] = "pdf_extract_failed"
213
+ out["content"] = pdf_body
214
+ out["content_type"] = ctype or "application/pdf"
215
+ elif len(body) > min_text:
216
+ try:
217
+ text = body.decode("utf-8", "replace")
218
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
219
+ out["error"] = "raw_pdf_bytes"
220
+ elif len(text) >= min_text:
221
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
222
+ return out
223
+ except Exception:
224
+ pass
225
+ else:
226
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
227
+ except Exception as exc:
228
+ out["error"] = f"live:{exc}"
229
+
230
+ if wayback:
231
+ try:
232
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
233
+ if w.get("status") == "success":
234
+ raw_b = w.get("content") or b""
235
+ raw_t = w.get("text") or ""
236
+ pdf_bytes = b""
237
+ if isinstance(raw_b, (bytes, bytearray)) and raw_b:
238
+ if raw_b[:4] == b"%PDF":
239
+ pdf_bytes = bytes(raw_b)
240
+ else:
241
+ _idx = raw_b.find(b"%PDF", 0, 8192)
242
+ if _idx >= 0:
243
+ pdf_bytes = bytes(raw_b[_idx:])
244
+ if not pdf_bytes and raw_t:
245
+ enc = raw_t.encode("latin-1", "replace")
246
+ if enc[:4] == b"%PDF":
247
+ pdf_bytes = enc
248
+ else:
249
+ _idx = enc.find(b"%PDF", 0, 8192)
250
+ if _idx >= 0:
251
+ pdf_bytes = enc[_idx:]
252
+ if pdf_bytes or (isinstance(raw_b, bytes) and (w.get("content_type") or "").lower().find("pdf") >= 0):
253
+ if not pdf_bytes and isinstance(raw_b, bytes):
254
+ pdf_bytes = raw_b
255
+ text = pdf_to_text(pdf_bytes)
256
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
257
+ out.update(
258
+ status="success",
259
+ text=text,
260
+ content=pdf_bytes,
261
+ method="wayback_pdf",
262
+ source_url=w.get("wayback_url") or w.get("url") or url,
263
+ content_type="application/pdf",
264
+ )
265
+ return out
266
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
267
+ return out
268
+ if not raw_t and isinstance(raw_b, bytes):
269
+ raw_t = raw_b.decode("utf-8", "replace")
270
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:400] or "startxref" in raw_t[:800]:
271
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
272
+ return out
273
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
274
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
275
+ out.update(
276
+ status="success",
277
+ text=text,
278
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
279
+ method="wayback_html",
280
+ source_url=w.get("url") or url,
281
+ content_type=w.get("content_type") or "text/html",
282
+ )
283
+ return out
284
+ out["error"] = (out.get("error") or "") + ";wayback_short"
285
+ else:
286
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
287
+ except Exception as exc:
288
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
289
+ return out
290
+
291
+
292
+
293
+ def best_cdx_pdf_timestamp(url: str) -> Optional[str]:
294
+ """Pick a CDX snapshot timestamp that looks like a real PDF (status 200)."""
295
+ try:
296
+ # Prefer exact URL match via prefix of the path
297
+ from urllib.parse import urlsplit
298
+ parts = urlsplit(url)
299
+ host = (parts.hostname or "").replace("www.", "")
300
+ path = parts.path or "/"
301
+ # try a few URL variants
302
+ candidates = []
303
+ for u in (url, url.replace("https://", "http://"), url.replace("http://", "https://")):
304
+ u2 = u.replace(":80/", "/")
305
+ for h in cdx_urls(u2, limit=20, match_type="exact"):
306
+ candidates.append(h)
307
+ # also prefix on host+path
308
+ prefix = f"{host}{path}".lstrip("/")
309
+ if prefix:
310
+ for h in cdx_urls(prefix, limit=30, match_type="prefix",
311
+ extra_filters=["mimetype:application/pdf"]):
312
+ candidates.append(h)
313
+ for h in cdx_urls("www." + prefix, limit=30, match_type="prefix",
314
+ extra_filters=["mimetype:application/pdf"]):
315
+ candidates.append(h)
316
+ best = None
317
+ for h in candidates:
318
+ ts = h.get("timestamp") or ""
319
+ sc = str(h.get("statuscode") or h.get("status") or "")
320
+ mt = (h.get("mimetype") or "").lower()
321
+ orig = (h.get("original") or "").lower()
322
+ if not ts:
323
+ continue
324
+ if sc and sc not in ("200", "226", "-"):
325
+ continue
326
+ score = 0
327
+ if "pdf" in mt or orig.endswith(".pdf"):
328
+ score += 2
329
+ if sc == "200":
330
+ score += 1
331
+ if best is None or score > best[0] or (score == best[0] and ts > best[1]):
332
+ best = (score, ts)
333
+ return best[1] if best else None
334
+ except Exception as exc:
335
+ log.info("best_cdx_pdf_timestamp fail %s: %s", url[:80], exc)
336
+ return None
337
+
338
+
339
+ def fetch_official_prefer_pdf(
340
+ url: str,
341
+ *,
342
+ ua: str = DEFAULT_UA,
343
+ verify: bool = True,
344
+ min_text: int = MIN_TEXT,
345
+ wayback_ts: Optional[str] = None,
346
+ ) -> dict:
347
+ """Live first; on failure, Wayback with CDX PDF timestamp when available."""
348
+ got = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=wayback_ts, min_text=min_text)
349
+ if got.get("status") == "success" and not (got.get("text") or "").lstrip().startswith("%PDF"):
350
+ # reject obvious HTML shells mistaken for success when URL is a PDF
351
+ if url.lower().endswith(".pdf") and got.get("method") == "wayback_html":
352
+ pass # try timestamped below
353
+ else:
354
+ return got
355
+ ts = wayback_ts or best_cdx_pdf_timestamp(url)
356
+ if ts:
357
+ got2 = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
358
+ if got2.get("status") == "success":
359
+ return got2
360
+ # try http variant with same ts
361
+ alt = url.replace("https://", "http://") if url.startswith("https://") else url.replace("http://", "https://")
362
+ got3 = fetch_official(alt, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
363
+ if got3.get("status") == "success":
364
+ return got3
365
+ return got
366
+
367
+ def first_title(text: str, fallback: str) -> str:
368
+ for line in (text or "").splitlines():
369
+ s = line.strip()
370
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
371
+ return s[:240]
372
+ return fallback[:240]
373
+
374
+
375
+ def save_instrument(
376
+ *,
377
+ cc: str,
378
+ country: str,
379
+ language: str,
380
+ ident: str,
381
+ title: str,
382
+ text: str,
383
+ source_url: str,
384
+ source_type: str,
385
+ license_text: str,
386
+ collector: str,
387
+ date: Optional[str] = None,
388
+ article_re: Optional[re.Pattern] = None,
389
+ extra_meta: Optional[dict] = None,
390
+ ) -> bool:
391
+ if not text or len(text) < MIN_TEXT:
392
+ return False
393
+ rid = slug_id(cc, ident)
394
+ docs = split_custom(text, rid, source_url, date, article_re)
395
+ rec = base_record(
396
+ cc=cc,
397
+ country=country,
398
+ language=language,
399
+ ident=ident,
400
+ title=title or first_title(text, ident),
401
+ text=text,
402
+ source_url=source_url,
403
+ source_type=source_type,
404
+ license_text=license_text,
405
+ collector=collector,
406
+ date=iso_date(date) or date,
407
+ documents=docs,
408
+ extra_meta=extra_meta,
409
+ )
410
+ write_instrument(cc, rec)
411
+ return True
412
+
413
+
414
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
415
+ try:
416
+ hits = af.search_wayback_machine(
417
+ host_or_url,
418
+ limit=limit,
419
+ match_type=match_type,
420
+ collapse="urlkey",
421
+ extra_filters=extra_filters,
422
+ )
423
+ except Exception as exc:
424
+ log.info("cdx err %s: %s", host_or_url, exc)
425
+ return []
426
+ return hits or []
427
+
428
+
429
+ def env_int(name: str, default: int) -> int:
430
+ try:
431
+ return int(os.environ.get(name, str(default)) or default)
432
+ except Exception:
433
+ return default