endomorphosis commited on
Commit
4dca07c
·
verified ·
1 Parent(s): 7a8c11f

Refresh/add Samoa official snapshot (95 laws)

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_samoa_laws manifest
2
+
3
+ generated_utc: 2026-09-08T22:53:33Z
4
+ cc: ws
5
+ laws_rows: 95
6
+ articles_rows: 2274
7
+ laws_bytes: 1516770
8
+ articles_bytes: 1509227
9
+ laws_sha256: cf6d5b17292791c98d52735f59c67dc9f1332a13a8eaa37fa1f1a66bf2326a90
10
+ articles_sha256: cf0c5a98ba71d0b4c75a7c86b560c9f900e7a0ab7927258e7f3db021352f4d3f
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_samoa_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_samoa_laws/data/articles.parquet
13
+ compression: zstd
14
+ collector: scrapers/collect_ws.py
15
+ license: Official Samoan consolidation texts; AG / authentic text prevails; not legal advice
16
+ retrieval: live-official
17
+ live_instruments: 95
18
+ archive_instruments: 0
19
+ wayback_instruments: 0
20
+ common_crawl_instruments: 0
21
+ archive_is_instruments: 0
22
+ constitution_present: true
23
+ catalog_expected: 267
24
+ catalog_gap: 172
25
+ gaps: Consolidation of Laws of Samoa PDFs from official ag.gov.ws. Parliament SharePoint skipped (403). Not legal advice.
26
+ uploaded: false
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Samoa Consolidation of Laws (Attorney General)
3
+ license: other
4
+ license_name: ws-ag-official-texts
5
+ language:
6
+ - en
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - samoa
13
+ - attorney-general
14
+ - official-texts
15
+ size_categories:
16
+ - 1K<n<10K
17
+ configs:
18
+ - config_name: laws
19
+ data_files: data/laws.parquet
20
+ default: true
21
+ - config_name: articles
22
+ data_files: data/articles.parquet
23
+ ---
24
+
25
+ # Samoa Consolidation of Laws (Attorney General)
26
+
27
+ Research snapshot of official national legislation from **Attorney General Consolidation of Laws of Samoa (ag.gov.ws)**.
28
+
29
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
30
+
31
+ ## Snapshot
32
+
33
+ | Field | Value |
34
+ | --- | --- |
35
+ | Snapshot date | 2026-09-08 |
36
+ | Coverage | ag-consolidation-2023-pdfs |
37
+ | Source | Attorney General Consolidation of Laws of Samoa (ag.gov.ws) |
38
+ | Collector | `scrapers/collect_ws.py` |
39
+ | Laws / instruments | 95 |
40
+ | Articles | 2,274 |
41
+ | Language | en |
42
+ | Jurisdiction | Samoa |
43
+ | License | `ws-ag-official-texts` |
44
+
45
+ ## Contents
46
+
47
+ - `data/laws.parquet` — one row per instrument.
48
+ - `data/articles.parquet` — article/section rows for the same snapshot.
49
+ - `scrapers/collect_ws.py` — research collector used to build this snapshot.
50
+
51
+ ## License / reuse
52
+
53
+ Official Samoan consolidation texts; AG / authentic text prevails; not legal advice.
54
+
55
+ This dataset is **not legal advice**. The official source prevails.
56
+
57
+ ## Source
58
+
59
+ - https://www.ag.gov.ws/consolidation-of-laws-of-samoa/
60
+
61
+ ## Known gaps
62
+
63
+ Consolidation of Laws of Samoa PDFs from official ag.gov.ws. Parliament SharePoint skipped (403). Not legal advice.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf0c5a98ba71d0b4c75a7c86b560c9f900e7a0ab7927258e7f3db021352f4d3f
3
+ size 1509227
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf6d5b17292791c98d52735f59c67dc9f1332a13a8eaa37fa1f1a66bf2326a90
3
+ size 1516770
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "https://web.archive.org/cdx/search/cdx"
28
+ WAYBACK_WEB = "https://web.archive.org/web"
29
+ WAYBACK_CDX_HTTP = "http://web.archive.org/cdx/search/cdx"
30
+ WAYBACK_WEB_HTTP = "http://web.archive.org/web"
31
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
32
+ CC_DATA = "https://data.commoncrawl.org"
33
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
34
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
35
+
36
+ UA = (
37
+ "legal-corpora-collector/1.0 "
38
+ "(research archive of official national gazettes; polite; "
39
+ "contact via local operator)"
40
+ )
41
+
42
+ CHALLENGE_RE = re.compile(
43
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
44
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
45
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
46
+ r"request\s+rejected|access\s+denied",
47
+ re.I,
48
+ )
49
+ SPA_SHELL_RE = re.compile(
50
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
51
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
52
+ re.I,
53
+ )
54
+
55
+ _session: Optional[requests.Session] = None
56
+ _cc_indexes: Optional[list[str]] = None
57
+ _cc_dead: set[str] = set()
58
+ _last_wayback = 0.0
59
+ _last_cc = 0.0
60
+
61
+
62
+ def session() -> requests.Session:
63
+ global _session
64
+ if _session is None:
65
+ s = requests.Session()
66
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
67
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
68
+ s.mount("https://", ad)
69
+ s.mount("http://", ad)
70
+ _session = s
71
+ return _session
72
+
73
+
74
+ def _sleep_wayback(delay: float = 1.0) -> None:
75
+ global _last_wayback
76
+ now = time.time()
77
+ wait = delay - (now - _last_wayback)
78
+ if wait > 0:
79
+ time.sleep(wait)
80
+ _last_wayback = time.time()
81
+
82
+
83
+ def _sleep_cc(delay: float = 0.35) -> None:
84
+ global _last_cc
85
+ now = time.time()
86
+ wait = delay - (now - _last_cc)
87
+ if wait > 0:
88
+ time.sleep(wait)
89
+ _last_cc = time.time()
90
+
91
+
92
+ def has_brave_key() -> bool:
93
+ return bool(
94
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
95
+ )
96
+
97
+
98
+ def is_challenge(html: str, status: int = 200) -> bool:
99
+ if status in (401, 403, 429, 503):
100
+ return True
101
+ if not html:
102
+ return False
103
+ head = html[:8000]
104
+ if CHALLENGE_RE.search(head):
105
+ return True
106
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
107
+ return True
108
+ return False
109
+
110
+
111
+ def is_spa_shell(html: str, text: str) -> bool:
112
+ if not html:
113
+ return False
114
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
115
+ return True
116
+ return False
117
+
118
+
119
+ # --- Wayback ---
120
+
121
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
122
+
123
+
124
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
125
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
126
+ if not isinstance(data, list) or len(data) <= 1:
127
+ return [], None
128
+ resume = None
129
+ rows = data
130
+ # Trailer: ..., [], ["resumeKey"]
131
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
132
+ resume = str(data[-1][0]) if data[-1][0] else None
133
+ rows = data[:-2]
134
+ headers = rows[0] if rows else []
135
+ out: list[dict] = []
136
+ for row in rows[1:]:
137
+ if not row:
138
+ continue
139
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
140
+ if not rec and isinstance(row, list) and len(row) >= 5:
141
+ rec = {
142
+ "urlkey": row[0],
143
+ "timestamp": row[1],
144
+ "original": row[2],
145
+ "mimetype": row[3],
146
+ "statuscode": row[4],
147
+ "digest": row[5] if len(row) > 5 else "",
148
+ "length": row[6] if len(row) > 6 else "0",
149
+ }
150
+ orig = rec.get("original") or rec.get("url") or ""
151
+ ts = rec.get("timestamp") or ""
152
+ mime = rec.get("mimetype") or ""
153
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
154
+ "application/pdf",
155
+ "application/xml",
156
+ "text/xml",
157
+ "application/xhtml+xml",
158
+ "text/html",
159
+ "application/json",
160
+ ):
161
+ continue
162
+ if not orig or not ts:
163
+ continue
164
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
165
+ rec["source"] = "wayback"
166
+ out.append(rec)
167
+ return out, resume
168
+
169
+
170
+ def _wayback_cdx_page(
171
+ url: str,
172
+ *,
173
+ limit: int,
174
+ collapse: str,
175
+ filter_status: str,
176
+ from_date: Optional[str],
177
+ to_date: Optional[str],
178
+ match_type: Optional[str],
179
+ extra_filters: Optional[list[str]],
180
+ resume_key: Optional[str],
181
+ mime_prefix: Optional[str],
182
+ page_size: int,
183
+ ) -> tuple[list[dict], Optional[str]]:
184
+ items: list[tuple[str, Any]] = [
185
+ ("url", url),
186
+ ("output", "json"),
187
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
188
+ ("limit", int(page_size)),
189
+ ("showResumeKey", "true"),
190
+ ]
191
+ if collapse:
192
+ items.append(("collapse", collapse))
193
+ if from_date:
194
+ items.append(("from", from_date))
195
+ if to_date:
196
+ items.append(("to", to_date))
197
+ if match_type:
198
+ items.append(("matchType", match_type))
199
+ if filter_status:
200
+ items.append(("filter", f"statuscode:{filter_status}"))
201
+ for flt in extra_filters or []:
202
+ items.append(("filter", flt))
203
+ if resume_key:
204
+ items.append(("resumeKey", resume_key))
205
+ _sleep_wayback(1.0)
206
+ last_err = None
207
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
208
+ if attempt > 1:
209
+ items = [(k, psz if k == "limit" else v) for k, v in items]
210
+ _sleep_wayback(1.5)
211
+ try:
212
+ try:
213
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
214
+ except requests.RequestException:
215
+ r = session().get(WAYBACK_CDX_HTTP, params=items, timeout=(20, 90))
216
+ except requests.RequestException as exc:
217
+ last_err = exc
218
+ log.warning("wayback cdx fail %s: %s", url, exc)
219
+ continue
220
+ if r.status_code in (502, 503, 504) or not r.content:
221
+ last_err = f"http_{r.status_code}"
222
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
223
+ continue
224
+ if r.status_code != 200:
225
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
226
+ return [], None
227
+ try:
228
+ data = r.json()
229
+ except Exception:
230
+ return [], None
231
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
232
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
233
+ return [], None
234
+
235
+
236
+ def search_wayback_machine(
237
+ url: str,
238
+ *,
239
+ from_date: Optional[str] = None,
240
+ to_date: Optional[str] = None,
241
+ limit: int = 100,
242
+ collapse: str = "urlkey",
243
+ filter_status: str = "200",
244
+ match_type: Optional[str] = None,
245
+ mime_prefix: Optional[str] = None,
246
+ extra_filters: Optional[list[str]] = None,
247
+ ) -> list[dict]:
248
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
249
+ target = max(1, int(limit))
250
+ page_size = CDX_PAGE if target > CDX_PAGE else target
251
+ out: list[dict] = []
252
+ seen = set()
253
+ resume: Optional[str] = None
254
+ empty = 0
255
+ while len(out) < target:
256
+ need = min(page_size, target - len(out))
257
+ batch, resume = _wayback_cdx_page(
258
+ url,
259
+ limit=need,
260
+ collapse=collapse,
261
+ filter_status=filter_status,
262
+ from_date=from_date,
263
+ to_date=to_date,
264
+ match_type=match_type,
265
+ extra_filters=extra_filters,
266
+ resume_key=resume,
267
+ mime_prefix=mime_prefix,
268
+ page_size=need,
269
+ )
270
+ added = 0
271
+ for rec in batch:
272
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
273
+ if key in seen:
274
+ continue
275
+ seen.add(key)
276
+ out.append(rec)
277
+ added += 1
278
+ if added == 0:
279
+ empty += 1
280
+ if empty >= 2 or not resume:
281
+ break
282
+ else:
283
+ empty = 0
284
+ if not resume:
285
+ break
286
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
287
+ return out[:target]
288
+
289
+
290
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
291
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
292
+
293
+ Prefer HTTP Wayback; HTTPS Wayback SSL-EOFs from this host (same as VN VBPL).
294
+ """
295
+ if timestamp:
296
+ path = f"/{timestamp}id_/{url}"
297
+ else:
298
+ path = f"/2id_/{url}"
299
+ r = None
300
+ last_err = None
301
+ candidates = [WAYBACK_WEB_HTTP + path, WAYBACK_WEB + path]
302
+ for attempt in range(1, 4):
303
+ target = candidates[min(attempt-1, len(candidates)-1)]
304
+ _sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))
305
+ try:
306
+ r = session().get(target, timeout=(20, 90), allow_redirects=True)
307
+ except requests.RequestException as exc:
308
+ last_err = str(exc)
309
+ log.info("wayback replay fail %s: %s", url, exc)
310
+ continue
311
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 3:
312
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
313
+ continue
314
+ break
315
+ if r is None:
316
+ return {"status": "error", "error": last_err or "no_response", "url": url}
317
+ cap_ts = timestamp or ""
318
+ m = re.search(r"/web/(\d{14})", r.url or "")
319
+ if m:
320
+ cap_ts = m.group(1)
321
+ ctype = r.headers.get("content-type") or ""
322
+ body = r.content or b""
323
+ text = ""
324
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
325
+ enc = r.encoding or "utf-8"
326
+ try:
327
+ text = body.decode(enc, "replace")
328
+ except Exception:
329
+ text = body.decode("utf-8", "replace")
330
+ if r.status_code != 200 or not body:
331
+ return {
332
+ "status": "error",
333
+ "error": f"http_{r.status_code}",
334
+ "http_status": r.status_code,
335
+ "wayback_url": r.url,
336
+ "original_url": url,
337
+ }
338
+ if text and is_challenge(text, r.status_code):
339
+ return {
340
+ "status": "error",
341
+ "error": "challenge_or_shell",
342
+ "http_status": r.status_code,
343
+ "wayback_url": r.url,
344
+ "original_url": url,
345
+ "content": text[:2000],
346
+ }
347
+ return {
348
+ "status": "success",
349
+ "content": body,
350
+ "text": text,
351
+ "content_type": ctype,
352
+ "wayback_url": r.url,
353
+ "capture_timestamp": cap_ts,
354
+ "original_url": url,
355
+ "http_status": r.status_code,
356
+ "method": "wayback",
357
+ }
358
+
359
+
360
+ # --- Common Crawl ---
361
+
362
+ def _http_cc_index(url: str) -> str:
363
+ if url.startswith("https://index.commoncrawl.org"):
364
+ return "http://" + url[len("https://"):]
365
+ return url
366
+
367
+
368
+ def cc_indexes(n: int = 6) -> list[str]:
369
+ global _cc_indexes
370
+ if _cc_indexes is None:
371
+ cols = []
372
+ last_exc = None
373
+ for coll in (CC_COLLINFO, CC_COLLINFO.replace("https://", "http://", 1)):
374
+ try:
375
+ r = session().get(coll, timeout=30)
376
+ if r.status_code == 200:
377
+ cols = r.json() or []
378
+ break
379
+ except Exception as exc:
380
+ last_exc = exc
381
+ log.warning("cc collinfo %s: %s", coll, exc)
382
+ ids = []
383
+ for c in cols:
384
+ cid = c.get("id") or ""
385
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
386
+ if cid:
387
+ ids.append(_http_cc_index(cdx or f"http://index.commoncrawl.org/{cid}-index"))
388
+ # collinfo is newest-first. Do not drop crawls that 404 a
389
+ # specific URL (that means "no captures", not a dead index).
390
+ _cc_indexes = ids or [
391
+ "http://index.commoncrawl.org/CC-MAIN-2026-34-index",
392
+ "http://index.commoncrawl.org/CC-MAIN-2024-33-index",
393
+ ]
394
+ if last_exc and not ids:
395
+ log.warning("cc collinfo fallback indexes after %s", last_exc)
396
+ return _cc_indexes[:n]
397
+
398
+
399
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
400
+ """Query public CC CDX (https://index.commoncrawl.org/).
401
+
402
+ Do not send filter=status:200 — on some shards that returns a false
403
+ 404 "No Captures found". Filter status client-side instead.
404
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
405
+ """
406
+ out = []
407
+ seen = set()
408
+ empty = 0
409
+ for idx in (indexes or cc_indexes(12)):
410
+ if idx in _cc_dead:
411
+ continue
412
+ params = {
413
+ "url": url,
414
+ "output": "json",
415
+ "limit": str(limit),
416
+ }
417
+ _sleep_cc(0.3)
418
+ try:
419
+ r = session().get(idx, params=params, timeout=(12, 25))
420
+ except requests.RequestException as exc:
421
+ alt = _http_cc_index(idx) if idx.startswith("https://") else idx.replace("http://", "https://", 1)
422
+ try:
423
+ r = session().get(alt, params=params, timeout=(12, 25))
424
+ except requests.RequestException as exc2:
425
+ log.info("cc cdx %s fail %s / %s", idx, exc, exc2)
426
+ continue
427
+ if r.status_code == 404:
428
+ msg = (r.text or "")[:80]
429
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
430
+ empty += 1
431
+ if empty >= 8 and not out:
432
+ continue
433
+ continue
434
+ if r.status_code in (410,):
435
+ _cc_dead.add(idx)
436
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
437
+ continue
438
+ if r.status_code != 200 or not r.content:
439
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
440
+ continue
441
+ for line in r.text.splitlines():
442
+ line = line.strip()
443
+ if not line or line[0] not in "{[":
444
+ continue
445
+ try:
446
+ rec = json.loads(line)
447
+ except Exception:
448
+ continue
449
+ orig = rec.get("url") or rec.get("original") or ""
450
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
451
+ if st and st not in ("200", "201", "206"):
452
+ continue
453
+ key = (orig, rec.get("filename"), rec.get("offset"))
454
+ if not orig or key in seen:
455
+ continue
456
+ seen.add(key)
457
+ rec["original"] = orig
458
+ rec["source"] = "common_crawl"
459
+ rec["cc_index"] = idx
460
+ out.append(rec)
461
+ if out:
462
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
463
+ if len(out) >= limit or out:
464
+ break
465
+ return out[:limit]
466
+
467
+
468
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
469
+ data = raw
470
+ if data[:2] == b"\x1f\x8b":
471
+ try:
472
+ data = gzip.decompress(data)
473
+ except Exception:
474
+ try:
475
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
476
+ except Exception:
477
+ pass
478
+ # WARC record: headers, then HTTP payload
479
+ split = data.split(b"\r\n\r\n", 1)
480
+ if len(split) < 2:
481
+ return 0, "", data
482
+ warc_headers, rest = split
483
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
484
+ http_split = rest.split(b"\r\n\r\n", 1)
485
+ http_head = http_split[0].decode("latin-1", "replace")
486
+ body = http_split[1] if len(http_split) > 1 else b""
487
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
488
+ status = int(m.group(1)) if m else 0
489
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
490
+ ctype = cm.group(1).strip() if cm else ""
491
+ return status, ctype, body
492
+ return 0, "", rest
493
+
494
+
495
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
496
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
497
+ try:
498
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
499
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
500
+ except Exception:
501
+ return {"status": "error", "error": "bad_pointer"}
502
+ if not fn or ln <= 0:
503
+ return {"status": "error", "error": "missing_pointer"}
504
+ ln = min(ln, max_bytes)
505
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
506
+ _sleep_cc(0.25)
507
+ try:
508
+ r = session().get(
509
+ url,
510
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
511
+ timeout=(20, 90),
512
+ )
513
+ except requests.RequestException as exc:
514
+ return {"status": "error", "error": str(exc)}
515
+ if r.status_code not in (200, 206) or not r.content:
516
+ return {"status": "error", "error": f"http_{r.status_code}"}
517
+ status, ctype, body = _parse_warc_http(r.content)
518
+ text = ""
519
+ if body and (
520
+ "html" in (ctype or "")
521
+ or "xml" in (ctype or "")
522
+ or "text/" in (ctype or "")
523
+ or not ctype
524
+ ):
525
+ text = body.decode("utf-8", "replace")
526
+ orig = rec.get("original") or rec.get("url") or ""
527
+ if text and is_challenge(text, status or 200):
528
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
529
+ return {
530
+ "status": "success",
531
+ "content": body,
532
+ "text": text,
533
+ "content_type": ctype,
534
+ "original_url": orig,
535
+ "http_status": status or 200,
536
+ "method": "common_crawl",
537
+ "cc_record": {
538
+ "filename": fn,
539
+ "offset": off,
540
+ "length": ln,
541
+ "timestamp": rec.get("timestamp"),
542
+ },
543
+ }
544
+
545
+
546
+ # --- archive.is ---
547
+
548
+ def get_archive_is_content(url: str) -> dict:
549
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
550
+ try:
551
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
552
+ except requests.RequestException as exc:
553
+ log.info("archive.is %s", exc)
554
+ continue
555
+ if r.status_code != 200 or not r.content:
556
+ continue
557
+ if "archive." not in (r.url or ""):
558
+ continue
559
+ text = r.text or ""
560
+ if is_challenge(text, r.status_code):
561
+ continue
562
+ return {
563
+ "status": "success",
564
+ "content": r.content,
565
+ "text": text,
566
+ "content_type": r.headers.get("content-type") or "text/html",
567
+ "archive_url": r.url,
568
+ "original_url": url,
569
+ "http_status": r.status_code,
570
+ "method": "archive_is",
571
+ }
572
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
573
+
574
+
575
+ # --- Direct HTTP last ---
576
+
577
+ def get_http(url: str) -> dict:
578
+ try:
579
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
580
+ except requests.RequestException as exc:
581
+ return {"status": "error", "error": str(exc), "original_url": url}
582
+ text = ""
583
+ ctype = r.headers.get("content-type") or ""
584
+ body = r.content or b""
585
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
586
+ text = body.decode(r.encoding or "utf-8", "replace")
587
+ if r.status_code != 200 or not body:
588
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
589
+ if text and is_challenge(text, r.status_code):
590
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
591
+ return {
592
+ "status": "success",
593
+ "content": body,
594
+ "text": text,
595
+ "content_type": ctype,
596
+ "original_url": url,
597
+ "http_status": r.status_code,
598
+ "method": "http",
599
+ "final_url": r.url,
600
+ }
601
+
602
+
603
+ def fetch_with_fallbacks(
604
+ url: str,
605
+ *,
606
+ cc_record: Optional[dict] = None,
607
+ wayback_ts: Optional[str] = None,
608
+ try_archive_is: bool = False,
609
+ try_http: bool = True,
610
+ try_cc: bool = True,
611
+ ) -> dict:
612
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
613
+
614
+ Brave Search skipped (no API key in this environment).
615
+ Playwright is attempted by the caller when this returns a SPA shell.
616
+ Does not run Wayback CDX search; Wayback is replay only.
617
+ """
618
+ errors = []
619
+ cc_recs: list[dict] = []
620
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
621
+ cc_recs = [cc_record]
622
+ elif try_cc:
623
+ try:
624
+ cc_recs = search_common_crawl(url, limit=4)
625
+ except Exception as exc:
626
+ errors.append(f"common_crawl:{exc}")
627
+ cc_recs = []
628
+ for rec in cc_recs:
629
+ res = fetch_common_crawl_warc(rec)
630
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
631
+ return res
632
+ errors.append(f"common_crawl:{res.get('error')}")
633
+ if wayback_ts or url:
634
+ res = get_wayback_content(url, timestamp=wayback_ts)
635
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
636
+ return res
637
+ errors.append(f"wayback:{res.get('error')}")
638
+ if try_archive_is:
639
+ res = get_archive_is_content(url)
640
+ if res.get("status") == "success":
641
+ return res
642
+ errors.append(f"archive_is:{res.get('error')}")
643
+ if try_http:
644
+ res = get_http(url)
645
+ if res.get("status") == "success":
646
+ return res
647
+ errors.append(f"http:{res.get('error')}")
648
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_ws.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Samoa: Consolidation of Laws PDFs from Attorney General (ag.gov.ws).
3
+
4
+ Official only:
5
+ https://www.ag.gov.ws/consolidation-of-laws-of-samoa/
6
+
7
+ ≥267 public consolidation PDFs under /wp-content/uploads/.
8
+ SKIP palemene.sharepoint.com (403 auth wall). No WAF bypass. Not legal advice.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import re
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+ from typing import Optional
20
+ from urllib.parse import unquote, urljoin
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
23
+ from common import *
24
+ import archive_fallbacks as af
25
+ from pdf_extract_lib import extract_pdf_text, honest_split, split_by_pattern
26
+
27
+ CC = "ws"
28
+ COUNTRY = "Samoa"
29
+ SOURCE_TYPE = "ag_gov_ws_consolidation"
30
+ LICENSE = (
31
+ "Official Consolidation of Laws of Samoa as published by the Office of the "
32
+ "Attorney General (ag.gov.ws). The authentic official text prevails. Not legal advice."
33
+ )
34
+ UA = DEFAULT_UA + " source=https://www.ag.gov.ws/"
35
+ INDEX = "https://www.ag.gov.ws/consolidation-of-laws-of-samoa/"
36
+ SLEEP = float(os.environ.get("SLEEP", "0.55"))
37
+ MIN_TEXT = 80
38
+ log = logging.getLogger("ws")
39
+ ART_WS = re.compile(
40
+ r"(?im)^\s*((?:Section|Article|PART|Part|SCHEDULE|Schedule)\s+[\dIVXLCDM]+[A-Za-z]?)\b"
41
+ )
42
+ PDF_HREF = re.compile(r'href=["\']([^"\']+\.pdf)["\']', re.I)
43
+
44
+
45
+ def setup():
46
+ ensure_dirs(CC)
47
+ logging.basicConfig(
48
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
49
+ handlers=[
50
+ logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
51
+ logging.StreamHandler(sys.stdout),
52
+ ],
53
+ )
54
+
55
+
56
+ def catalog_path() -> Path:
57
+ return ROOT / CC / "raw" / "catalog.jsonl"
58
+
59
+
60
+ def load_catalog() -> list[dict]:
61
+ p = catalog_path()
62
+ if not p.exists() or p.stat().st_size < 40:
63
+ return []
64
+ out = []
65
+ with p.open(encoding="utf-8") as f:
66
+ for line in f:
67
+ line = line.strip()
68
+ if not line:
69
+ continue
70
+ try:
71
+ out.append(json.loads(line))
72
+ except Exception:
73
+ continue
74
+ return out
75
+
76
+
77
+ def save_catalog(items: list[dict]) -> None:
78
+ atomic_write(catalog_path(), "".join(json.dumps(it, ensure_ascii=False) + "\n" for it in items))
79
+
80
+
81
+ def title_from_url(url: str) -> str:
82
+ stem = Path(unquote(url.split("?")[0])).stem
83
+ stem = stem.replace("_", " ").replace("-", " ")
84
+ return re.sub(r"\s+", " ", stem).strip()[:240] or "Act"
85
+
86
+
87
+ def get_bytes(url: str) -> tuple[bytes, str]:
88
+ if "sharepoint.com" in url.lower():
89
+ return b"", "skip_sharepoint"
90
+ try:
91
+ r = http_get(
92
+ url, ua=UA, sleep=SLEEP, timeout=(20, 180), retries=3,
93
+ headers={"Accept": "application/pdf,*/*", "Referer": INDEX},
94
+ )
95
+ except Exception as exc:
96
+ log.info("live fail %s: %s", url, exc)
97
+ r = None
98
+ if r is not None and r.status_code == 200 and r.content and r.content[:4] == b"%PDF":
99
+ return r.content, "live"
100
+ res = af.fetch_with_fallbacks(url, try_http=False)
101
+ body = res.get("content") or b""
102
+ if res.get("status") == "success" and body[:4] == b"%PDF":
103
+ return body, res.get("method") or "archive"
104
+ return b"", "failed"
105
+
106
+
107
+ def discover() -> list[dict]:
108
+ existing = load_catalog()
109
+ if existing and len(existing) >= 100:
110
+ log.info("resume catalog n=%s", len(existing))
111
+ return existing
112
+ try:
113
+ r = http_get(INDEX, ua=UA, sleep=SLEEP, timeout=(20, 90), retries=4)
114
+ except Exception as exc:
115
+ log.error("index fail: %s", exc)
116
+ return existing
117
+ if r.status_code != 200 or not r.text:
118
+ log.error("index HTTP %s", r.status_code)
119
+ return existing
120
+ items, seen = [], set()
121
+ for href in PDF_HREF.findall(r.text):
122
+ url = urljoin(INDEX, href.split("#")[0])
123
+ low = url.lower()
124
+ if "sharepoint.com" in low:
125
+ continue
126
+ if "ag.gov.ws" not in low:
127
+ continue
128
+ if url in seen:
129
+ continue
130
+ seen.add(url)
131
+ title = title_from_url(url)
132
+ ident = Path(unquote(url.split("?")[0])).stem[:160]
133
+ items.append({"url": url, "title": title, "identifier": ident, "kind": "act"})
134
+ save_catalog(items)
135
+ log.info("catalog n=%s", len(items))
136
+ return items
137
+
138
+
139
+ def split_ws(text: str, law_id: str, source_url: str) -> list[dict]:
140
+ docs, _ = honest_split(CC, text, law_id, source_url)
141
+ if docs:
142
+ return docs
143
+ docs = split_articles(text, law_id, source_url)
144
+ if len(docs) >= 2:
145
+ return docs
146
+ return split_by_pattern(text, law_id, source_url, ART_WS, "section")
147
+
148
+
149
+ def fetch_one(it: dict, done: set[str]) -> str:
150
+ url = it["url"]
151
+ ident = it.get("identifier") or Path(unquote(url.split("?")[0])).stem
152
+ rid = slug_id(CC, ident)
153
+ if rid in done:
154
+ return "skip"
155
+ body, method = get_bytes(url)
156
+ if method == "skip_sharepoint":
157
+ return "skip"
158
+ if body[:4] != b"%PDF":
159
+ log_failure(CC, {"id": rid, "url": url, "reason": f"not_pdf method={method}"})
160
+ return "fail"
161
+ text, backend, pages = extract_pdf_text(body, enable_ocr=True, ocr_lang="eng", ocr_max_pages=50)
162
+ if len(text) < MIN_TEXT:
163
+ log_failure(CC, {"id": rid, "url": url, "reason": f"empty_text backend={backend}"})
164
+ return "fail"
165
+ title = it.get("title") or title_from_url(url)
166
+ year_m = re.search(r"(19|20)\d{2}", title) or re.search(r"(19|20)\d{2}", url)
167
+ date = f"{year_m.group(0)}-01-01" if year_m else None
168
+ docs = split_ws(text, rid, url)
169
+ rec = base_record(
170
+ cc=CC, country=COUNTRY, language="en", ident=ident, title=title,
171
+ text=text, source_url=url, source_type=SOURCE_TYPE, license_text=LICENSE,
172
+ collector="collect_ws.py", date=date, official_identifier=ident,
173
+ document_type="statute", law_status="current", is_current=True,
174
+ documents=docs,
175
+ extra_meta={
176
+ "retrieval": method, "pdf_pages": pages,
177
+ "text_extraction": {"source": "official", "backend": backend},
178
+ "consolidation": "Laws of Samoa 2023 (AG)",
179
+ },
180
+ )
181
+ write_instrument(CC, rec)
182
+ done.add(rid)
183
+ log.info("ok %s method=%s chars=%s arts=%s", rid[:70], method, len(text), len(docs))
184
+ return "ok"
185
+
186
+
187
+ def main():
188
+ setup()
189
+ t0 = utcnow()
190
+ max_new = int(os.environ.get("MAX_NEW", "0") or "0")
191
+ max_seconds = int(os.environ.get("MAX_SECONDS", "7200") or "7200")
192
+ t_start = time.time()
193
+ items = discover()
194
+ done = existing_ids(CC)
195
+ ok = skip = fail = 0
196
+ for it in items:
197
+ if max_new and ok >= max_new:
198
+ break
199
+ if time.time() - t_start > max_seconds:
200
+ break
201
+ status = fetch_one(it, done)
202
+ if status == "ok":
203
+ ok += 1
204
+ elif status == "skip":
205
+ skip += 1
206
+ else:
207
+ fail += 1
208
+ write_summary(
209
+ CC, country=COUNTRY, source="AG Consolidation of Laws of Samoa (ag.gov.ws)",
210
+ source_urls=[INDEX],
211
+ license_text=LICENSE, discovered=len(items), fetched=ok, skipped=skip, failed=fail,
212
+ coverage="ag-consolidation-2023-pdfs",
213
+ notes=(
214
+ "Consolidation of Laws of Samoa PDFs from official ag.gov.ws. "
215
+ "Parliament SharePoint binaries skipped (403). Not legal advice."
216
+ ),
217
+ last_run=t0,
218
+ )
219
+ log.info("done ok=%s skip=%s fail=%s catalog=%s", ok, skip, fail, len(items))
220
+
221
+
222
+ if __name__ == "__main__":
223
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\.|str\.|para(?:graph)?\.?|szakasz)\s+"
238
+ r"[\dIVXLCDM]+[a-zA-Z]?)\b"
239
+ )
240
+
241
+
242
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
243
+ if not text or len(text) < 40:
244
+ return []
245
+ matches = list(ARTICLE_SPLIT.finditer(text))
246
+ if len(matches) < 2:
247
+ return []
248
+ docs = []
249
+ for i, m in enumerate(matches):
250
+ start = m.start()
251
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
252
+ chunk = text[start:end].strip()
253
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
254
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
255
+ heading = chunk.split("\n", 1)[0][:200]
256
+ docs.append({
257
+ "id": f"{law_id}-{aid}"[:180],
258
+ "title": heading,
259
+ "text": chunk,
260
+ "date_filed": date,
261
+ "document_number": num,
262
+ "source_url": source_url,
263
+ "record_type": "article",
264
+ "article_number": num,
265
+ "law_identifier": law_id,
266
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
267
+ })
268
+ if len(docs) >= 4000:
269
+ break
270
+ return docs
271
+
272
+
273
+ def load_schema():
274
+ global _schema
275
+ with _schema_lock:
276
+ if _schema is None:
277
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
278
+ _schema = json.load(f)
279
+ return _schema
280
+
281
+
282
+ def validate_record(record: dict) -> Optional[str]:
283
+ try:
284
+ import jsonschema
285
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
286
+ return None
287
+ except Exception as exc:
288
+ return str(exc)
289
+
290
+
291
+ def existing_ids(cc: str) -> set[str]:
292
+ d = ROOT / cc / "instruments"
293
+ if not d.exists():
294
+ return set()
295
+ return {p.stem for p in d.glob("*.json")}
296
+
297
+
298
+ def write_instrument(cc: str, record: dict) -> Path:
299
+ ident = record["id"]
300
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
301
+ dest.parent.mkdir(parents=True, exist_ok=True)
302
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
303
+ atomic_write(dest, body)
304
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
305
+ index_line["path"] = f"instruments/{ident}.json"
306
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
307
+ index_line["bytes"] = dest.stat().st_size
308
+ index_line["id"] = ident
309
+ with _index_lock:
310
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
311
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
312
+ return dest
313
+
314
+
315
+ def log_failure(cc: str, payload: dict) -> None:
316
+ path = ROOT / cc / "failures.jsonl"
317
+ path.parent.mkdir(parents=True, exist_ok=True)
318
+ payload = dict(payload)
319
+ payload.setdefault("retrieved_at", utcnow())
320
+ with _fail_lock:
321
+ with path.open("a", encoding="utf-8") as handle:
322
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
323
+
324
+
325
+ def append_catalog(cc: str, row: dict) -> None:
326
+ path = ROOT / cc / "raw" / "catalog.jsonl"
327
+ path.parent.mkdir(parents=True, exist_ok=True)
328
+ with _index_lock:
329
+ with path.open("a", encoding="utf-8") as handle:
330
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
331
+
332
+
333
+ def law_status_hist(cc: str) -> Counter:
334
+ c: Counter = Counter()
335
+ d = ROOT / cc / "instruments"
336
+ if not d.exists():
337
+ return c
338
+ for p in d.glob("*.json"):
339
+ try:
340
+ rec = json.loads(p.read_text(encoding="utf-8"))
341
+ c[rec.get("law_status") or "unknown"] += 1
342
+ except Exception:
343
+ c["unknown"] += 1
344
+ return c
345
+
346
+
347
+ def corpus_bytes(cc: str) -> int:
348
+ d = ROOT / cc / "instruments"
349
+ if not d.exists():
350
+ return 0
351
+ return sum(p.stat().st_size for p in d.glob("*.json"))
352
+
353
+
354
+ def count_jsonl(path: Path) -> int:
355
+ if not path.exists():
356
+ return 0
357
+ n = 0
358
+ with path.open(encoding="utf-8") as f:
359
+ for _ in f:
360
+ n += 1
361
+ return n
362
+
363
+
364
+ def write_summary(
365
+ cc: str,
366
+ *,
367
+ country: str,
368
+ source: str,
369
+ source_urls: Iterable[str],
370
+ license_text: str,
371
+ discovered: int,
372
+ fetched: int,
373
+ skipped: int,
374
+ failed: int,
375
+ coverage: str,
376
+ notes: str,
377
+ last_run: Optional[str] = None,
378
+ extra: Optional[str] = None,
379
+ ) -> None:
380
+ last_run = last_run or utcnow()
381
+ instr = ROOT / cc / "instruments"
382
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
383
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
384
+ hist = law_status_hist(cc)
385
+ nbytes = corpus_bytes(cc)
386
+ lines = [
387
+ f"# {country} legislation corpus",
388
+ "",
389
+ f"- jurisdiction: {cc.upper()}",
390
+ f"- source: {source}",
391
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
392
+ f"- instruments_json: {n_json}",
393
+ f"- index_jsonl_lines: {n_index}",
394
+ f"- discovered: {discovered}",
395
+ f"- fetched: {fetched}",
396
+ f"- skipped: {skipped}",
397
+ f"- failed: {failed}",
398
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
399
+ f"- coverage: {coverage}",
400
+ f"- total_json_bytes: {nbytes}",
401
+ f"- license: {license_text}",
402
+ "- source_urls:",
403
+ ]
404
+ for u in source_urls:
405
+ lines.append(f" - {u}")
406
+ lines.append("- notes:")
407
+ for n in (notes or "").splitlines():
408
+ lines.append(f" {n}")
409
+ if extra:
410
+ lines.append("")
411
+ lines.append(extra)
412
+ lines.append("")
413
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
414
+
415
+
416
+ def base_record(
417
+ *,
418
+ cc: str,
419
+ country: str,
420
+ language: str,
421
+ ident: str,
422
+ title: str,
423
+ text: str,
424
+ source_url: str,
425
+ source_type: str,
426
+ license_text: str,
427
+ collector: str,
428
+ eli: Optional[str] = None,
429
+ date: Optional[str] = None,
430
+ official_identifier: Optional[str] = None,
431
+ document_type: str = "statute",
432
+ law_status: str = "current",
433
+ is_current: Optional[bool] = True,
434
+ documents: Optional[list] = None,
435
+ extra_meta: Optional[dict] = None,
436
+ extra_fields: Optional[dict] = None,
437
+ ) -> dict:
438
+ rid = slug_id(cc, ident)
439
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
440
+ rec = {
441
+ "schema_version": "collection_record.v1",
442
+ "record_type": "law",
443
+ "id": rid,
444
+ "title": title or ident,
445
+ "text": text or "",
446
+ "source_url": source_url,
447
+ "source_type": source_type,
448
+ "date": date,
449
+ "jurisdiction": cc.upper(),
450
+ "country": country,
451
+ "language": language,
452
+ "eli": eli,
453
+ "license": license_text,
454
+ "retrieved_at": utcnow(),
455
+ "identifier": official_identifier or ident,
456
+ "official_identifier": official_identifier or ident,
457
+ "law_identifier": official_identifier or ident,
458
+ "document_type": document_type,
459
+ "law_status": law_status,
460
+ "is_current": is_current,
461
+ "canonical_law_url": source_url,
462
+ "article_count": len(docs),
463
+ "article_extraction_status": "ok" if docs else "missing",
464
+ "documents": docs,
465
+ "metadata": {
466
+ "collector": collector,
467
+ "schema": "collection_record.v1",
468
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
469
+ "content_sha256": sha256_text(text or ""),
470
+ "rights": {
471
+ "not_legal_advice": True,
472
+ "official_reuse_url": source_url,
473
+ "license": license_text,
474
+ },
475
+ "text_extraction": {"source": "official", "backend": "collector"},
476
+ },
477
+ }
478
+ if extra_meta:
479
+ rec["metadata"].update(extra_meta)
480
+ if extra_fields:
481
+ rec.update(extra_fields)
482
+ return rec
483
+
484
+
485
+ def ensure_dirs(cc: str) -> Path:
486
+ root = ROOT / cc
487
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
488
+ (root / "raw").mkdir(parents=True, exist_ok=True)
489
+ (root / "logs").mkdir(parents=True, exist_ok=True)
490
+ return root
491
+
492
+
493
+ def iso_date(val: Optional[str]) -> Optional[str]:
494
+ if not val:
495
+ return None
496
+ val = str(val).strip()
497
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
498
+ if m:
499
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
500
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
501
+ if m:
502
+ return m.group(1)
503
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
504
+ if m:
505
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
506
+ return None
507
+
508
+
509
+ def pdf_bytes_to_text(raw: bytes, timeout: int = 180) -> str:
510
+ """Extract text from PDF bytes via pdftotext. Empty on failure."""
511
+ import subprocess
512
+ if not raw:
513
+ return ""
514
+ if raw[:4] != b"%PDF":
515
+ idx = raw.find(b"%PDF", 0, 8192)
516
+ if idx < 0:
517
+ return ""
518
+ raw = raw[idx:]
519
+ try:
520
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
521
+ tmp.write(raw)
522
+ tmp.flush()
523
+ proc = subprocess.run(
524
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
525
+ check=False, capture_output=True, timeout=timeout,
526
+ )
527
+ if proc.returncode == 0 and proc.stdout:
528
+ return proc.stdout.decode("utf-8", "replace").strip()
529
+ except Exception:
530
+ return ""
531
+ return ""
scrapers/pdf_extract_lib.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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[:8000]
30
+ # Broken ToUnicode / CID font dumps from Arabic/Persian PDFs
31
+ if sample.count("(cid:") >= 8:
32
+ return True
33
+ arabic = sum(1 for ch in sample if "\u0600" <= ch <= "\u06FF")
34
+ ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t\x0c")
35
+ n = max(1, len(sample))
36
+ # Encoding-corrupt Arabic/Persian PDFs: many controls / almost no Arabic script
37
+ if len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05:
38
+ return True
39
+ if len(sample) > 800 and arabic < 80 and sample.count("@") > 30:
40
+ return True
41
+ letters = sum(ch.isalpha() for ch in sample)
42
+ spaces = sample.count(" ")
43
+ if letters < 80 and arabic < 40:
44
+ return True
45
+ # Mojibake Latin stand-in for Arabic (common in old MoJ PDFs)
46
+ ascii_letters = sum(ch.isalpha() and ord(ch) < 128 for ch in sample)
47
+ if len(sample) > 500 and arabic < 20 and ascii_letters > 400:
48
+ return True
49
+ if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):
50
+ return True
51
+ singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))
52
+ if singles > 30 and singles > letters * 0.15:
53
+ return True
54
+ return False
55
+
56
+
57
+ def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
58
+ import pdfplumber
59
+ with pdfplumber.open(io.BytesIO(raw)) as pdf:
60
+ n = len(pdf.pages)
61
+ parts = []
62
+ for page in pdf.pages[:max_pages]:
63
+ try:
64
+ parts.append(page.extract_text() or "")
65
+ except Exception:
66
+ continue
67
+ text = "\n".join(parts)
68
+ text = re.sub(r"[ \t]+", " ", text)
69
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
70
+ return text, n
71
+
72
+
73
+ def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
74
+ import pymupdf
75
+ doc = pymupdf.open(stream=raw, filetype="pdf")
76
+ n = doc.page_count
77
+ parts = [page.get_text() for page in doc[:max_pages]]
78
+ text = "\n".join(parts)
79
+ text = re.sub(r"[ \t]+", " ", text)
80
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
81
+ return text, n
82
+
83
+
84
+ def extract_pdftotext(raw: bytes) -> str:
85
+ if not raw or raw[:4] != b"%PDF":
86
+ return ""
87
+ try:
88
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
89
+ tmp.write(raw)
90
+ tmp.flush()
91
+ proc = subprocess.run(
92
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
93
+ check=False, capture_output=True, timeout=180,
94
+ )
95
+ if proc.returncode == 0 and proc.stdout:
96
+ return proc.stdout.decode("utf-8", "replace").strip()
97
+ except Exception as exc:
98
+ log.warning("pdftotext: %s", exc)
99
+ return ""
100
+
101
+
102
+ def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]:
103
+ """Render pages with pymupdf and OCR via tesseract CLI."""
104
+ import pymupdf
105
+ doc = pymupdf.open(stream=raw, filetype="pdf")
106
+ n = doc.page_count
107
+ parts = []
108
+ mat = pymupdf.Matrix(dpi / 72, dpi / 72)
109
+ for i, page in enumerate(doc):
110
+ if i >= max_pages:
111
+ break
112
+ pix = page.get_pixmap(matrix=mat, alpha=False)
113
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img:
114
+ pix.save(img.name)
115
+ img_path = img.name
116
+ try:
117
+ env = dict(**__import__("os").environ)
118
+ env["OMP_THREAD_LIMIT"] = "1"
119
+ env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata")
120
+ proc = subprocess.run(
121
+ ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"],
122
+ capture_output=True, text=True, timeout=180, env=env,
123
+ )
124
+ if proc.returncode == 0 and proc.stdout:
125
+ parts.append(proc.stdout)
126
+ except Exception as exc:
127
+ log.debug("ocr page %s: %s", i, exc)
128
+ finally:
129
+ try:
130
+ import os
131
+ os.unlink(img_path)
132
+ except Exception:
133
+ pass
134
+ text = "\n".join(parts)
135
+ text = re.sub(r"[ \t]+", " ", text)
136
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
137
+ return text, n
138
+
139
+
140
+ def extract_pdf_text(
141
+ raw: bytes,
142
+ *,
143
+ enable_ocr: bool = True,
144
+ ocr_lang: str = "eng",
145
+ ocr_max_pages: int = 40,
146
+ ) -> tuple[str, str, int]:
147
+ """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order."""
148
+ if not raw:
149
+ return "", "not_pdf", 0
150
+ if raw[:4] != b"%PDF":
151
+ idx = raw.find(b"%PDF", 0, 65536)
152
+ if idx < 0:
153
+ return "", "not_pdf", 0
154
+ raw = raw[idx:]
155
+ best_text, best_method, pages = "", "failed", 0
156
+ for name, fn in (
157
+ ("pdfplumber", lambda: extract_pdfplumber(raw)),
158
+ ("pymupdf", lambda: extract_pymupdf(raw)),
159
+ ):
160
+ try:
161
+ text, pages = fn()
162
+ if text and not is_garbage_text(text) and len(text) >= 80:
163
+ return text, name, pages
164
+ if len(text) > len(best_text):
165
+ best_text, best_method = text, name
166
+ except Exception as exc:
167
+ log.debug("%s failed: %s", name, exc)
168
+ try:
169
+ text = extract_pdftotext(raw)
170
+ if text and not is_garbage_text(text) and len(text) >= 80:
171
+ return text, "pdftotext", pages
172
+ if len(text) > len(best_text):
173
+ best_text, best_method = text, "pdftotext"
174
+ except Exception:
175
+ pass
176
+ if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120):
177
+ try:
178
+ text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages)
179
+ if text and len(text) >= 80 and not is_garbage_text(text):
180
+ return text, "ocr_tesseract", pages
181
+ if len(text) > len(best_text):
182
+ best_text, best_method = text, "ocr_tesseract"
183
+ except Exception as exc:
184
+ log.debug("ocr failed: %s", exc)
185
+ return best_text, best_method if best_text else "failed", pages
186
+
187
+
188
+ def normalize_bidi(text: str) -> str:
189
+ return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200c\u200d\ufeff]", "", text or "")
190
+
191
+
192
+ _EASTERN_DIGITS = str.maketrans(
193
+ "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669"
194
+ "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9",
195
+ "01234567890123456789",
196
+ )
197
+
198
+
199
+ def normalize_rtl_text(text: str) -> str:
200
+ """Strip bidi marks and map Arabic/Persian digits to ASCII for heading regexes."""
201
+ t = normalize_bidi(text or "")
202
+ t = re.sub(r"[\u00ad\u200b]", "", t)
203
+ return t.translate(_EASTERN_DIGITS)
204
+
205
+
206
+
207
+ def split_by_pattern(
208
+ text: str,
209
+ law_id: str,
210
+ source_url: str,
211
+ pat: re.Pattern,
212
+ record_type: str = "article",
213
+ min_chunk: int = 40,
214
+ max_docs: int = 4000,
215
+ ) -> list[dict]:
216
+ matches = list(pat.finditer(text or ""))
217
+ if len(matches) < 2:
218
+ return []
219
+ docs = []
220
+ for i, m in enumerate(matches):
221
+ start = m.start()
222
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
223
+ chunk = text[start:end].strip()
224
+ if len(chunk) < min_chunk:
225
+ continue
226
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
227
+ aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80]
228
+ heading = chunk.split("\n", 1)[0][:200]
229
+ docs.append({
230
+ "id": f"{law_id}-{aid}"[:180],
231
+ "title": heading,
232
+ "text": chunk,
233
+ "date_filed": None,
234
+ "document_number": num,
235
+ "source_url": source_url,
236
+ "record_type": record_type,
237
+ "article_number": num,
238
+ "law_identifier": law_id,
239
+ "metadata": {
240
+ "text_extraction": {
241
+ "source": "official",
242
+ "backend": "honest_heading_split",
243
+ "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split",
244
+ "pattern": pat.pattern[:100],
245
+ }
246
+ },
247
+ })
248
+ if len(docs) >= max_docs:
249
+ break
250
+ return docs if len(docs) >= 2 else []
251
+
252
+
253
+ # Country-specific honest patterns (tried in order)
254
+ COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = {
255
+ "sv": [
256
+ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"),
257
+ ],
258
+ "tn": [
259
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"),
260
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
261
+ ],
262
+ "et": [
263
+ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"),
264
+ ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
265
+ ("article_inline", re.compile(r"(?im)((?:Article|Art\.)\s+\d+)(?![\d])"), "article"),
266
+ ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"),
267
+ ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"),
268
+ ],
269
+ "jm": [
270
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"),
271
+ ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"),
272
+ ],
273
+ "fj": [
274
+ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"),
275
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"),
276
+ ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"),
277
+ ],
278
+ "la": [
279
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"),
280
+ ],
281
+ "lk": [
282
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"),
283
+ ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"),
284
+ ],
285
+ "md": [
286
+ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"),
287
+ ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"),
288
+ ],
289
+ "iq": [
290
+ ("mada", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:]*\s*\d+)(?!\d)"), "article"),
291
+ ("mada_ocr", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:\s]*\d+)(?!\d)"), "article"),
292
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|الباب)\s+\S+)"), "section"),
293
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
294
+ ],
295
+ "ir": [
296
+ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"),
297
+ ("mada_prefixed", re.compile(
298
+ r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)"
299
+ ), "article"),
300
+ ("fasl_bab", re.compile(
301
+ r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))"
302
+ ), "section"),
303
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
304
+ ],
305
+ "mz": [
306
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
307
+ ],
308
+ }
309
+
310
+
311
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
312
+ if cc in ("tn", "iq", "ir", "dz", "lb", "ma", "eg", "sa", "ae"):
313
+ text_n = normalize_rtl_text(text)
314
+ else:
315
+ text_n = text
316
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
317
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
318
+ if docs:
319
+ return docs, name
320
+ # shared fallback
321
+ from common import split_articles
322
+ docs = split_articles(text_n, law_id, source_url)
323
+ if len(docs) >= 2:
324
+ return docs, "common_article_split"
325
+ return [], "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if not raw or raw[:4] != b"%PDF":
56
+ return ""
57
+ try:
58
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
59
+ tmp.write(raw)
60
+ tmp.flush()
61
+ proc = subprocess.run(
62
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
63
+ check=False,
64
+ capture_output=True,
65
+ timeout=180,
66
+ )
67
+ if proc.returncode == 0 and proc.stdout:
68
+ return proc.stdout.decode("utf-8", "replace").strip()
69
+ except Exception as exc:
70
+ log.warning("pdftotext: %s", exc)
71
+ return ""
72
+
73
+
74
+ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]:
75
+ docs = split_articles(text, law_id, source_url, date)
76
+ if not pattern:
77
+ return docs
78
+ matches = list(pattern.finditer(text or ""))
79
+ if len(matches) < 2:
80
+ return docs if len(docs) >= 2 else []
81
+ out = []
82
+ for i, m in enumerate(matches):
83
+ start = m.start()
84
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
85
+ chunk = text[start:end].strip()
86
+ if len(chunk) < 20:
87
+ continue
88
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
89
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]
90
+ heading = chunk.split("\n", 1)[0][:200]
91
+ out.append({
92
+ "id": f"{law_id}-{aid}"[:180],
93
+ "title": heading,
94
+ "text": chunk,
95
+ "date_filed": date,
96
+ "document_number": num,
97
+ "source_url": source_url,
98
+ "record_type": "article",
99
+ "article_number": num,
100
+ "law_identifier": law_id,
101
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
102
+ })
103
+ if len(out) >= 4000:
104
+ break
105
+ return out if len(out) >= 2 else docs
106
+
107
+
108
+
109
+ def normalize_official_url(url: str) -> str:
110
+ """Fix CDX quirks: https://host:80/... breaks TLS (WRONG_VERSION_NUMBER)."""
111
+ if not url:
112
+ return url
113
+ url = url.replace("http://", "https://", 1) if "lawcommission.gov.np" in url and url.startswith("http://") else url
114
+ url = url.replace("https://www.lawcommission.gov.np:80/", "https://www.lawcommission.gov.np/")
115
+ url = url.replace("https://lawcommission.gov.np:80/", "https://lawcommission.gov.np/")
116
+ url = url.replace(":80/", "/") if url.startswith("https://") and ":80/" in url else url
117
+ url = url.replace(":80?", "?") if url.startswith("https://") and ":80?" in url else url
118
+ return url
119
+
120
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
121
+ url = normalize_official_url(url)
122
+ import requests
123
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
124
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
125
+ last = None
126
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ time.sleep(0.2)
130
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
131
+ return resp
132
+ except Exception as exc:
133
+ last = exc
134
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
135
+ try:
136
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
137
+ return resp
138
+ except Exception as exc2:
139
+ last = exc2
140
+ time.sleep(min(8, 1.5 * attempt))
141
+ raise RuntimeError(f"live_get failed {url}: {last}")
142
+
143
+
144
+ def fetch_official(
145
+ url: str,
146
+ *,
147
+ ua: str = DEFAULT_UA,
148
+ verify: bool = True,
149
+ wayback: bool = True,
150
+ wayback_ts: Optional[str] = None,
151
+ min_text: int = MIN_TEXT,
152
+ ) -> dict:
153
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
154
+ url = normalize_official_url(url)
155
+ out = {
156
+ "status": "error",
157
+ "text": "",
158
+ "content": b"",
159
+ "source_url": url,
160
+ "method": "",
161
+ "content_type": "",
162
+ "error": "",
163
+ }
164
+ body = b""
165
+ ctype = ""
166
+ try:
167
+ r = live_get(url, ua=ua, verify=verify)
168
+ body = r.content or b""
169
+ ctype = r.headers.get("content-type") or ""
170
+ if r.status_code == 200 and body:
171
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
172
+ text = pdf_to_text(body)
173
+ if len(text) >= min_text:
174
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
175
+ return out
176
+ text = ""
177
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
178
+ raw = body.decode(r.encoding or "utf-8", "replace")
179
+ if af.is_challenge(raw, r.status_code):
180
+ out["error"] = "challenge_or_shell"
181
+ else:
182
+ text = html_to_text(raw) if "<" in raw[:500] else raw
183
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
184
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
185
+ return out
186
+ if len(text) < min_text:
187
+ out["error"] = "short_or_spa"
188
+ elif body[:4] == b"%PDF":
189
+ out["error"] = "pdf_extract_failed"
190
+ elif len(body) > min_text:
191
+ try:
192
+ text = body.decode("utf-8", "replace")
193
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
194
+ out["error"] = "raw_pdf_bytes"
195
+ elif len(text) >= min_text:
196
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
197
+ return out
198
+ except Exception:
199
+ pass
200
+ else:
201
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
202
+ except Exception as exc:
203
+ out["error"] = f"live:{exc}"
204
+
205
+ if wayback:
206
+ try:
207
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
208
+ if w.get("status") == "success":
209
+ raw_b = w.get("content") or b""
210
+ raw_t = w.get("text") or ""
211
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
212
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
213
+ text = pdf_to_text(pdf_bytes)
214
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
215
+ out.update(
216
+ status="success",
217
+ text=text,
218
+ content=pdf_bytes,
219
+ method="wayback_pdf",
220
+ source_url=w.get("url") or url,
221
+ content_type="application/pdf",
222
+ )
223
+ return out
224
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
225
+ return out
226
+ if not raw_t and isinstance(raw_b, bytes):
227
+ raw_t = raw_b.decode("utf-8", "replace")
228
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
229
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
230
+ return out
231
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
232
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
233
+ out.update(
234
+ status="success",
235
+ text=text,
236
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
237
+ method="wayback_html",
238
+ source_url=w.get("url") or url,
239
+ content_type=w.get("content_type") or "text/html",
240
+ )
241
+ return out
242
+ out["error"] = (out.get("error") or "") + ";wayback_short"
243
+ else:
244
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
245
+ except Exception as exc:
246
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
247
+ return out
248
+
249
+
250
+ def first_title(text: str, fallback: str) -> str:
251
+ for line in (text or "").splitlines():
252
+ s = line.strip()
253
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
254
+ return s[:240]
255
+ return fallback[:240]
256
+
257
+
258
+ def save_instrument(
259
+ *,
260
+ cc: str,
261
+ country: str,
262
+ language: str,
263
+ ident: str,
264
+ title: str,
265
+ text: str,
266
+ source_url: str,
267
+ source_type: str,
268
+ license_text: str,
269
+ collector: str,
270
+ date: Optional[str] = None,
271
+ article_re: Optional[re.Pattern] = None,
272
+ extra_meta: Optional[dict] = None,
273
+ ) -> bool:
274
+ if not text or len(text) < MIN_TEXT:
275
+ return False
276
+ rid = slug_id(cc, ident)
277
+ docs = split_custom(text, rid, source_url, date, article_re)
278
+ rec = base_record(
279
+ cc=cc,
280
+ country=country,
281
+ language=language,
282
+ ident=ident,
283
+ title=title or first_title(text, ident),
284
+ text=text,
285
+ source_url=source_url,
286
+ source_type=source_type,
287
+ license_text=license_text,
288
+ collector=collector,
289
+ date=iso_date(date) or date,
290
+ documents=docs,
291
+ extra_meta=extra_meta,
292
+ )
293
+ write_instrument(cc, rec)
294
+ return True
295
+
296
+
297
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
298
+ try:
299
+ hits = af.search_wayback_machine(
300
+ host_or_url,
301
+ limit=limit,
302
+ match_type=match_type,
303
+ collapse="urlkey",
304
+ extra_filters=extra_filters,
305
+ )
306
+ except Exception as exc:
307
+ log.info("cdx err %s: %s", host_or_url, exc)
308
+ return []
309
+ return hits or []
310
+
311
+
312
+ def env_int(name: str, default: int) -> int:
313
+ try:
314
+ return int(os.environ.get(name, str(default)) or default)
315
+ except Exception:
316
+ return default