endomorphosis commited on
Commit
eec5869
·
verified ·
1 Parent(s): 2e8736d

Add scrapers_and_normalizers overlay for PY (data/* untouched)

Browse files
scrapers_and_normalizers/PROVENANCE_NATIONAL_OVERLAY.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "code": "PY",
3
+ "repo": "endomorphosis/ipfs_paraguay_laws",
4
+ "bundle": "national_scrapers_bundle_20261105"
5
+ }
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/archive_fallbacks.py ADDED
@@ -0,0 +1,1366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = os.environ.get("WAYBACK_CDX", "https://web.archive.org/cdx/search/cdx") # tip+30o 23:2x PT Oct 1: port 80 to web.archive.org times out; https OK
28
+ WAYBACK_WEB = os.environ.get("WAYBACK_WEB", "https://web.archive.org/web")
29
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
+ CC_DATA = "https://data.commoncrawl.org"
31
+ CC_DATA_HOSTS = (
32
+ "https://data.commoncrawl.org",
33
+ "https://commoncrawl.s3.amazonaws.com",
34
+ )
35
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
36
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
37
+
38
+ UA = (
39
+ "legal-corpora-collector/1.0 "
40
+ "(research archive of official national gazettes; polite; "
41
+ "contact via local operator)"
42
+ )
43
+
44
+ CHALLENGE_RE = re.compile(
45
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
46
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
47
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
48
+ r"request\s+rejected|access\s+denied",
49
+ re.I,
50
+ )
51
+ SPA_SHELL_RE = re.compile(
52
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
53
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
54
+ re.I,
55
+ )
56
+
57
+ _session: Optional[requests.Session] = None
58
+ _cc_indexes: Optional[list[str]] = None
59
+ _cc_dead: set[str] = set()
60
+ _last_wayback = 0.0
61
+ _last_cc = 0.0
62
+
63
+
64
+ def session() -> requests.Session:
65
+ global _session
66
+ if _session is None:
67
+ s = requests.Session()
68
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
69
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
70
+ s.mount("https://", ad)
71
+ s.mount("http://", ad)
72
+ _session = s
73
+ return _session
74
+
75
+
76
+ def _sleep_wayback(delay: float = 1.0) -> None:
77
+ global _last_wayback
78
+ now = time.time()
79
+ wait = delay - (now - _last_wayback)
80
+ if wait > 0:
81
+ time.sleep(wait)
82
+ _last_wayback = time.time()
83
+
84
+
85
+ def _sleep_cc(delay: float = 0.35) -> None:
86
+ global _last_cc
87
+ now = time.time()
88
+ wait = delay - (now - _last_cc)
89
+ if wait > 0:
90
+ time.sleep(wait)
91
+ _last_cc = time.time()
92
+
93
+
94
+ def has_brave_key() -> bool:
95
+ return bool(
96
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
97
+ )
98
+
99
+
100
+ def is_challenge(html: str, status: int = 200) -> bool:
101
+ if status in (401, 403, 429, 503):
102
+ return True
103
+ if not html:
104
+ return False
105
+ head = html[:8000]
106
+ if CHALLENGE_RE.search(head):
107
+ return True
108
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
109
+ return True
110
+ return False
111
+
112
+
113
+ def is_spa_shell(html: str, text: str) -> bool:
114
+ if not html:
115
+ return False
116
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
117
+ return True
118
+ return False
119
+
120
+
121
+ # --- Wayback ---
122
+
123
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
124
+
125
+
126
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
127
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
128
+ if not isinstance(data, list) or len(data) <= 1:
129
+ return [], None
130
+ resume = None
131
+ rows = data
132
+ # Trailer: ..., [], ["resumeKey"]
133
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
134
+ resume = str(data[-1][0]) if data[-1][0] else None
135
+ rows = data[:-2]
136
+ headers = rows[0] if rows else []
137
+ out: list[dict] = []
138
+ for row in rows[1:]:
139
+ if not row:
140
+ continue
141
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
142
+ if not rec and isinstance(row, list) and len(row) >= 5:
143
+ rec = {
144
+ "urlkey": row[0],
145
+ "timestamp": row[1],
146
+ "original": row[2],
147
+ "mimetype": row[3],
148
+ "statuscode": row[4],
149
+ "digest": row[5] if len(row) > 5 else "",
150
+ "length": row[6] if len(row) > 6 else "0",
151
+ }
152
+ orig = rec.get("original") or rec.get("url") or ""
153
+ ts = rec.get("timestamp") or ""
154
+ mime = rec.get("mimetype") or ""
155
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
156
+ "application/pdf",
157
+ "application/xml",
158
+ "text/xml",
159
+ "application/xhtml+xml",
160
+ "text/html",
161
+ "application/json",
162
+ ):
163
+ continue
164
+ if not orig or not ts:
165
+ continue
166
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
167
+ rec["source"] = "wayback"
168
+ out.append(rec)
169
+ return out, resume
170
+
171
+
172
+ def _wayback_cdx_page(
173
+ url: str,
174
+ *,
175
+ limit: int,
176
+ collapse: str,
177
+ filter_status: str,
178
+ from_date: Optional[str],
179
+ to_date: Optional[str],
180
+ match_type: Optional[str],
181
+ extra_filters: Optional[list[str]],
182
+ resume_key: Optional[str],
183
+ mime_prefix: Optional[str],
184
+ page_size: int,
185
+ ) -> tuple[list[dict], Optional[str]]:
186
+ items: list[tuple[str, Any]] = [
187
+ ("url", url),
188
+ ("output", "json"),
189
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
190
+ ("limit", int(page_size)),
191
+ ("showResumeKey", "true"),
192
+ ]
193
+ if collapse:
194
+ items.append(("collapse", collapse))
195
+ if from_date:
196
+ items.append(("from", from_date))
197
+ if to_date:
198
+ items.append(("to", to_date))
199
+ if match_type:
200
+ items.append(("matchType", match_type))
201
+ if filter_status:
202
+ items.append(("filter", f"statuscode:{filter_status}"))
203
+ for flt in extra_filters or []:
204
+ items.append(("filter", flt))
205
+ if resume_key:
206
+ items.append(("resumeKey", resume_key))
207
+ _sleep_wayback(1.0)
208
+ last_err = None
209
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
210
+ if attempt > 1:
211
+ items = [(k, psz if k == "limit" else v) for k, v in items]
212
+ _sleep_wayback(1.5)
213
+ try:
214
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
215
+ except requests.RequestException as exc:
216
+ last_err = exc
217
+ log.warning("wayback cdx fail %s: %s", url, exc)
218
+ continue
219
+ if r.status_code in (502, 503, 504) or not r.content:
220
+ last_err = f"http_{r.status_code}"
221
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
222
+ continue
223
+ if r.status_code != 200:
224
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
225
+ return [], None
226
+ try:
227
+ data = r.json()
228
+ except Exception:
229
+ return [], None
230
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
231
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
232
+ return [], None
233
+
234
+
235
+ def search_wayback_machine(
236
+ url: str,
237
+ *,
238
+ from_date: Optional[str] = None,
239
+ to_date: Optional[str] = None,
240
+ limit: int = 100,
241
+ collapse: str = "urlkey",
242
+ filter_status: str = "200",
243
+ match_type: Optional[str] = None,
244
+ mime_prefix: Optional[str] = None,
245
+ extra_filters: Optional[list[str]] = None,
246
+ ) -> list[dict]:
247
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
248
+ target = max(1, int(limit))
249
+ page_size = CDX_PAGE if target > CDX_PAGE else target
250
+ out: list[dict] = []
251
+ seen = set()
252
+ resume: Optional[str] = None
253
+ empty = 0
254
+ while len(out) < target:
255
+ need = min(page_size, target - len(out))
256
+ batch, resume = _wayback_cdx_page(
257
+ url,
258
+ limit=need,
259
+ collapse=collapse,
260
+ filter_status=filter_status,
261
+ from_date=from_date,
262
+ to_date=to_date,
263
+ match_type=match_type,
264
+ extra_filters=extra_filters,
265
+ resume_key=resume,
266
+ mime_prefix=mime_prefix,
267
+ page_size=need,
268
+ )
269
+ added = 0
270
+ for rec in batch:
271
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
272
+ if key in seen:
273
+ continue
274
+ seen.add(key)
275
+ out.append(rec)
276
+ added += 1
277
+ if added == 0:
278
+ empty += 1
279
+ if empty >= 2 or not resume:
280
+ break
281
+ else:
282
+ empty = 0
283
+ if not resume:
284
+ break
285
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
286
+ return out[:target]
287
+
288
+
289
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
290
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search."""
291
+ if timestamp:
292
+ wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}"
293
+ else:
294
+ wb = f"{WAYBACK_WEB}/2id_/{url}"
295
+ r = None
296
+ last_err = None
297
+ for attempt in range(1, 5):
298
+ _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt))
299
+ try:
300
+ r = session().get(wb, timeout=(20, 90), allow_redirects=True)
301
+ except requests.RequestException as exc:
302
+ last_err = str(exc)
303
+ log.info("wayback replay fail %s: %s", url, exc)
304
+ continue
305
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 4:
306
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
307
+ continue
308
+ break
309
+ if r is None:
310
+ return {"status": "error", "error": last_err or "no_response", "url": url}
311
+ cap_ts = timestamp or ""
312
+ m = re.search(r"/web/(\d{14})", r.url or "")
313
+ if m:
314
+ cap_ts = m.group(1)
315
+ ctype = r.headers.get("content-type") or ""
316
+ body = r.content or b""
317
+ text = ""
318
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
319
+ enc = r.encoding or "utf-8"
320
+ try:
321
+ text = body.decode(enc, "replace")
322
+ except Exception:
323
+ text = body.decode("utf-8", "replace")
324
+ if r.status_code != 200 or not body:
325
+ return {
326
+ "status": "error",
327
+ "error": f"http_{r.status_code}",
328
+ "http_status": r.status_code,
329
+ "wayback_url": r.url,
330
+ "original_url": url,
331
+ }
332
+ if text and is_challenge(text, r.status_code):
333
+ return {
334
+ "status": "error",
335
+ "error": "challenge_or_shell",
336
+ "http_status": r.status_code,
337
+ "wayback_url": r.url,
338
+ "original_url": url,
339
+ "content": text[:2000],
340
+ }
341
+ return {
342
+ "status": "success",
343
+ "content": body,
344
+ "text": text,
345
+ "content_type": ctype,
346
+ "wayback_url": r.url,
347
+ "capture_timestamp": cap_ts,
348
+ "original_url": url,
349
+ "http_status": r.status_code,
350
+ "method": "wayback",
351
+ }
352
+
353
+
354
+ # --- Common Crawl ---
355
+
356
+ def cc_indexes(n: int = 6) -> list[str]:
357
+ global _cc_indexes
358
+ if _cc_indexes is None:
359
+ try:
360
+ r = session().get(CC_COLLINFO, timeout=30)
361
+ cols = r.json() if r.status_code == 200 else []
362
+ ids = []
363
+ for c in cols:
364
+ cid = c.get("id") or ""
365
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
366
+ if cid:
367
+ ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index")
368
+ # collinfo is newest-first. Do not drop crawls that 404 a
369
+ # specific URL (that means "no captures", not a dead index).
370
+ _cc_indexes = ids or [
371
+ "https://index.commoncrawl.org/CC-MAIN-2025-18-index",
372
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
373
+ ]
374
+ except Exception as exc:
375
+ log.warning("cc collinfo: %s", exc)
376
+ _cc_indexes = [
377
+ "https://index.commoncrawl.org/CC-MAIN-2026-34-index",
378
+ "https://index.commoncrawl.org/CC-MAIN-2026-30-index",
379
+ "https://index.commoncrawl.org/CC-MAIN-2026-25-index",
380
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
381
+ ]
382
+ return _cc_indexes[:n]
383
+
384
+
385
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
386
+ """Query public CC CDX (https://index.commoncrawl.org/).
387
+
388
+ Prefer S3 cluster.idx+CDXJ harvest (harvest_thin_s3_cc / *_cc_urls.jsonl)
389
+ over this HTTP index — it often returns 0 hits or stalls. Short timeouts;
390
+ never blocks on cdx_toolkit.
391
+
392
+ Do not send filter=status:200 — on some shards that returns a false
393
+ 404 "No Captures found". Filter status client-side instead.
394
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
395
+ """
396
+ out = []
397
+ seen = set()
398
+ empty = 0
399
+ for idx in (indexes or cc_indexes(int(os.environ.get('CC_INDEX_N', '4') or 4))):
400
+ if idx in _cc_dead:
401
+ continue
402
+ params = {
403
+ "url": url,
404
+ "output": "json",
405
+ "limit": str(limit),
406
+ }
407
+ _sleep_cc(0.3)
408
+ try:
409
+ r = session().get(idx, params=params, timeout=(8, 15))
410
+ except requests.RequestException as exc:
411
+ log.info("cc cdx %s fail %s", idx, exc)
412
+ continue
413
+ if r.status_code == 404:
414
+ msg = (r.text or "")[:80]
415
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
416
+ empty += 1
417
+ if empty >= 8 and not out:
418
+ continue
419
+ continue
420
+ if r.status_code in (410,):
421
+ _cc_dead.add(idx)
422
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
423
+ continue
424
+ if r.status_code != 200 or not r.content:
425
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
426
+ continue
427
+ for line in r.text.splitlines():
428
+ line = line.strip()
429
+ if not line or line[0] not in "{[":
430
+ continue
431
+ try:
432
+ rec = json.loads(line)
433
+ except Exception:
434
+ continue
435
+ orig = rec.get("url") or rec.get("original") or ""
436
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
437
+ if st and st not in ("200", "201", "206"):
438
+ continue
439
+ key = (orig, rec.get("filename"), rec.get("offset"))
440
+ if not orig or key in seen:
441
+ continue
442
+ seen.add(key)
443
+ rec["original"] = orig
444
+ rec["source"] = "common_crawl"
445
+ rec["cc_index"] = idx
446
+ out.append(rec)
447
+ if out:
448
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
449
+ if len(out) >= limit or out:
450
+ break
451
+ return out[:limit]
452
+
453
+
454
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
455
+ data = raw
456
+ if data[:2] == b"\x1f\x8b":
457
+ try:
458
+ data = gzip.decompress(data)
459
+ except Exception:
460
+ try:
461
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
462
+ except Exception:
463
+ pass
464
+ # WARC record: headers, then HTTP payload
465
+ split = data.split(b"\r\n\r\n", 1)
466
+ if len(split) < 2:
467
+ return 0, "", data
468
+ warc_headers, rest = split
469
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
470
+ http_split = rest.split(b"\r\n\r\n", 1)
471
+ http_head = http_split[0].decode("latin-1", "replace")
472
+ body = http_split[1] if len(http_split) > 1 else b""
473
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
474
+ status = int(m.group(1)) if m else 0
475
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
476
+ ctype = cm.group(1).strip() if cm else ""
477
+ return status, ctype, body
478
+ return 0, "", rest
479
+
480
+
481
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
482
+ """Range-GET a WARC record from data.commoncrawl.org (S3 mirror fallback).
483
+
484
+ Retries 403/429/5xx with short backoff. Does not use index.commoncrawl.org
485
+ or cdx_toolkit. API stable for ingest_cc_ts_wb / ingest_cc_warc_fast.
486
+ """
487
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
488
+ try:
489
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
490
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
491
+ except Exception:
492
+ return {"status": "error", "error": "bad_pointer"}
493
+ if not fn or ln <= 0:
494
+ return {"status": "error", "error": "missing_pointer"}
495
+ ln = min(ln, max_bytes)
496
+ if str(fn).startswith("http"):
497
+ candidates = [fn]
498
+ else:
499
+ path = fn.lstrip("/")
500
+ candidates = [f"{h}/{path}" for h in CC_DATA_HOSTS]
501
+ headers_base = {
502
+ "User-Agent": (
503
+ "Mozilla/5.0 (compatible; legal-corpora-collector/1.0; "
504
+ "+https://commoncrawl.org; research)"
505
+ ),
506
+ "Accept": "*/*",
507
+ }
508
+ last_err = "no_attempt"
509
+ body_raw = b""
510
+ used_url = ""
511
+ for url in candidates:
512
+ for attempt in range(3):
513
+ _sleep_cc(0.2 if attempt == 0 else min(8.0, 1.5 * (2 ** attempt)))
514
+ try:
515
+ r = session().get(
516
+ url,
517
+ headers={**headers_base, "Range": f"bytes={off}-{off + ln - 1}"},
518
+ timeout=(12, 60),
519
+ )
520
+ except requests.RequestException as exc:
521
+ last_err = str(exc)
522
+ continue
523
+ if r.status_code in (403, 429, 500, 502, 503):
524
+ last_err = f"http_{r.status_code}"
525
+ continue
526
+ if r.status_code not in (200, 206) or not r.content:
527
+ last_err = f"http_{r.status_code}"
528
+ break
529
+ body_raw = r.content
530
+ used_url = url
531
+ break
532
+ if body_raw:
533
+ break
534
+ if not body_raw:
535
+ return {"status": "error", "error": last_err or "empty"}
536
+ # Prefer warcio when available; fall back to lightweight parse
537
+ status, ctype, body = 0, "", b""
538
+ try:
539
+ from warcio.archiveiterator import ArchiveIterator
540
+ for warc_rec in ArchiveIterator(io.BytesIO(body_raw)):
541
+ if warc_rec.rec_type != "response":
542
+ continue
543
+ payload = warc_rec.content_stream().read()
544
+ http_headers = warc_rec.http_headers
545
+ if http_headers is not None:
546
+ try:
547
+ status = int(http_headers.get_statuscode() or 0)
548
+ except Exception:
549
+ status = 0
550
+ ctype = http_headers.get_header("Content-Type") or ""
551
+ body = payload
552
+ break
553
+ if not body:
554
+ status, ctype, body = _parse_warc_http(body_raw)
555
+ except Exception:
556
+ status, ctype, body = _parse_warc_http(body_raw)
557
+ text = ""
558
+ if body and (
559
+ "html" in (ctype or "")
560
+ or "xml" in (ctype or "")
561
+ or "text/" in (ctype or "")
562
+ or not ctype
563
+ ):
564
+ text = body.decode("utf-8", "replace")
565
+ orig = rec.get("original") or rec.get("url") or ""
566
+ if text and is_challenge(text, status or 200):
567
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
568
+ return {
569
+ "status": "success",
570
+ "content": body,
571
+ "text": text,
572
+ "content_type": ctype,
573
+ "original_url": orig,
574
+ "http_status": status or 200,
575
+ "method": "common_crawl",
576
+ "cc_record": {
577
+ "filename": fn,
578
+ "offset": off,
579
+ "length": ln,
580
+ "timestamp": rec.get("timestamp"),
581
+ "fetch_url": used_url,
582
+ },
583
+ }
584
+
585
+
586
+ # --- archive.is ---
587
+
588
+ def get_archive_is_content(url: str) -> dict:
589
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
590
+ try:
591
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
592
+ except requests.RequestException as exc:
593
+ log.info("archive.is %s", exc)
594
+ continue
595
+ if r.status_code != 200 or not r.content:
596
+ continue
597
+ if "archive." not in (r.url or ""):
598
+ continue
599
+ text = r.text or ""
600
+ if is_challenge(text, r.status_code):
601
+ continue
602
+ return {
603
+ "status": "success",
604
+ "content": r.content,
605
+ "text": text,
606
+ "content_type": r.headers.get("content-type") or "text/html",
607
+ "archive_url": r.url,
608
+ "original_url": url,
609
+ "http_status": r.status_code,
610
+ "method": "archive_is",
611
+ }
612
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
613
+
614
+
615
+ # --- Direct HTTP last ---
616
+
617
+ def get_http(url: str) -> dict:
618
+ try:
619
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
620
+ except requests.RequestException as exc:
621
+ return {"status": "error", "error": str(exc), "original_url": url}
622
+ text = ""
623
+ ctype = r.headers.get("content-type") or ""
624
+ body = r.content or b""
625
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
626
+ text = body.decode(r.encoding or "utf-8", "replace")
627
+ if r.status_code != 200 or not body:
628
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
629
+ if text and is_challenge(text, r.status_code):
630
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
631
+ return {
632
+ "status": "success",
633
+ "content": body,
634
+ "text": text,
635
+ "content_type": ctype,
636
+ "original_url": url,
637
+ "http_status": r.status_code,
638
+ "method": "http",
639
+ "final_url": r.url,
640
+ }
641
+
642
+
643
+ # --- Fetch ladder (serial + parallel race) ---
644
+ # Order (2026-09-15):
645
+ # PARALLEL_LADDER race: WARC/slice pointer + Wayback CDX/replay + archive.is newest
646
+ # First successful non-empty body wins; losers abandoned.
647
+ # Then (serial, only on race miss): live HTTP/bs4 → optional Playwright (allowlist).
648
+ # Cloudflare Browser Rendering / IPWB only when creds/local usable (skipped otherwise).
649
+
650
+ _last_archive_is = 0.0
651
+ _archive_is_submit_count = 0
652
+ _ARCHIVE_IS_SUBMIT_CAP = int(os.environ.get("ARCHIVE_IS_SUBMIT_CAP", "3") or 3)
653
+
654
+ # Default Playwright allowlist: known JS-heavy Easy/Hard gazette portals
655
+ _DEFAULT_PLAYWRIGHT_HOSTS = (
656
+ "gacetaoficialdebolivia.gob.bo",
657
+ "eqanun.az",
658
+ "e-qanun.az",
659
+ "iort.gov.tn",
660
+ "dotic.ir",
661
+ "paragraf.rs",
662
+ "pravno-informacioni-sistem.rs",
663
+ )
664
+
665
+
666
+ def _env_truthy(name: str, default: str = "0") -> bool:
667
+ return os.environ.get(name, default) in ("1", "true", "True", "yes", "YES", "on", "ON")
668
+
669
+
670
+ def _sleep_archive_is(delay: float = 2.0) -> None:
671
+ global _last_archive_is
672
+ now = time.time()
673
+ wait = delay - (now - _last_archive_is)
674
+ if wait > 0:
675
+ time.sleep(wait)
676
+ _last_archive_is = time.time()
677
+
678
+
679
+ def has_cloudflare_creds() -> bool:
680
+ """Cloudflare Browser Rendering only when API key present."""
681
+ tok = (
682
+ os.environ.get("CLOUDFLARE_API_TOKEN")
683
+ or os.environ.get("CF_API_TOKEN")
684
+ or os.environ.get("CLOUDFLARE_BROWSER_RENDERING_TOKEN")
685
+ or ""
686
+ ).strip()
687
+ acct = (
688
+ os.environ.get("CLOUDFLARE_ACCOUNT_ID")
689
+ or os.environ.get("CF_ACCOUNT_ID")
690
+ or ""
691
+ ).strip()
692
+ return bool(tok and acct)
693
+
694
+
695
+ def has_ipwb_local() -> bool:
696
+ """IPWB only if local package already usable — never install/start from tip."""
697
+ if not _env_truthy("TRY_IPWB", "0"):
698
+ return False
699
+ try:
700
+ import ipwb # noqa: F401
701
+ return True
702
+ except Exception:
703
+ return False
704
+
705
+
706
+ def playwright_host_ok(url: str) -> bool:
707
+ raw = (os.environ.get("PLAYWRIGHT_HOSTS") or "").strip()
708
+ hosts = [h.strip().lower() for h in raw.split(",") if h.strip()] if raw else list(_DEFAULT_PLAYWRIGHT_HOSTS)
709
+ try:
710
+ host = (urlparse(url).hostname or "").lower().lstrip(".")
711
+ except Exception:
712
+ return False
713
+ if not host:
714
+ return False
715
+ for h in hosts:
716
+ if host == h or host.endswith("." + h):
717
+ return True
718
+ return False
719
+
720
+
721
+ def _body_nonempty(res: Optional[dict], min_text: int = 0) -> bool:
722
+ if not res or res.get("status") != "success":
723
+ return False
724
+ text = res.get("text") or ""
725
+ content = res.get("content") or b""
726
+ if isinstance(content, (bytes, bytearray)) and len(content) >= 64:
727
+ if content[:4] == b"%PDF" or b"%PDF" in content[:8192]:
728
+ return True
729
+ if len(text) >= max(min_text, 1) or len(content) >= max(min_text, 256):
730
+ return True
731
+ if len(text) >= max(min_text, 1):
732
+ return True
733
+ return False
734
+
735
+
736
+ def get_wayback_cdx_then_replay(url: str, timestamp: Optional[str] = None, min_text: int = 0) -> dict:
737
+ """Wayback: use given ts, else CDX newest then id_ replay. Honors global Wayback delay."""
738
+ ts = timestamp
739
+ if not ts and not _env_truthy("SKIP_WAYBACK_CDX", "0"):
740
+ try:
741
+ hits = search_wayback_machine(url, limit=3, collapse="digest")
742
+ if hits:
743
+ ts = hits[0].get("timestamp") or None
744
+ except Exception as exc:
745
+ log.info("wayback cdx search fail %s: %s", url[:80], exc)
746
+ res = get_wayback_content(url, timestamp=ts)
747
+ if _body_nonempty(res, min_text=min_text):
748
+ res["method"] = "wayback_cdx_replay" if ts and not timestamp else (res.get("method") or "wayback")
749
+ if ts:
750
+ res["capture_timestamp"] = res.get("capture_timestamp") or ts
751
+ return res
752
+ return res if res else {"status": "error", "error": "wayback_empty", "original_url": url}
753
+
754
+
755
+ def submit_archive_is(url: str, *, wait: bool = False, timeout: int = 45) -> dict:
756
+ """Sparse archive.is submit (rate-limited + session cap). Prefer newest lookup first."""
757
+ global _archive_is_submit_count
758
+ if _archive_is_submit_count >= _ARCHIVE_IS_SUBMIT_CAP:
759
+ return {"status": "error", "error": "archive_is_submit_cap", "original_url": url}
760
+ if not _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0"):
761
+ return {"status": "error", "error": "archive_is_submit_disabled", "original_url": url}
762
+ _sleep_archive_is(float(os.environ.get("ARCHIVE_IS_SUBMIT_DELAY", "5") or 5))
763
+ _archive_is_submit_count += 1
764
+ try:
765
+ r = session().post(
766
+ "https://archive.is/submit/",
767
+ data={"url": url, "anyway": "1"},
768
+ timeout=(10, timeout),
769
+ allow_redirects=True,
770
+ )
771
+ except requests.RequestException as exc:
772
+ return {"status": "error", "error": f"archive_is_submit:{exc}", "original_url": url}
773
+ if "archive." in (r.url or "") and r.url and "submit" not in (r.url or ""):
774
+ text = r.text or ""
775
+ if not is_challenge(text, r.status_code):
776
+ return {
777
+ "status": "success",
778
+ "content": r.content or b"",
779
+ "text": text,
780
+ "content_type": r.headers.get("content-type") or "text/html",
781
+ "archive_url": r.url,
782
+ "original_url": url,
783
+ "method": "archive_is_submit",
784
+ "http_status": r.status_code,
785
+ }
786
+ # Non-blocking: return pending; caller may re-hit newest later
787
+ if not wait:
788
+ return {"status": "error", "error": "archive_is_submit_pending", "original_url": url, "http_status": r.status_code}
789
+ time.sleep(3)
790
+ return get_archive_is_content(url)
791
+
792
+
793
+ def get_archive_is_content_ladder(url: str, *, submit_on_miss: Optional[bool] = None) -> dict:
794
+ """archive.is newest (+ optional sparse submit). Always rate-limited."""
795
+ _sleep_archive_is(float(os.environ.get("ARCHIVE_IS_DELAY", "2") or 2))
796
+ res = get_archive_is_content(url)
797
+ if _body_nonempty(res):
798
+ return res
799
+ do_submit = (
800
+ submit_on_miss
801
+ if submit_on_miss is not None
802
+ else _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0")
803
+ )
804
+ if do_submit:
805
+ sub = submit_archive_is(url, wait=_env_truthy("ARCHIVE_IS_SUBMIT_WAIT", "0"))
806
+ if _body_nonempty(sub):
807
+ return sub
808
+ # One more newest lookup after submit
809
+ _sleep_archive_is(2.0)
810
+ res2 = get_archive_is_content(url)
811
+ if _body_nonempty(res2):
812
+ res2["method"] = "archive_is_after_submit"
813
+ return res2
814
+ return sub if sub.get("error") else res
815
+ return res
816
+
817
+
818
+ def get_http_bs4(url: str) -> dict:
819
+ """Live HTTP with BeautifulSoup text extraction when available."""
820
+ res = get_http(url)
821
+ if res.get("status") != "success":
822
+ return res
823
+ text = res.get("text") or ""
824
+ ctype = (res.get("content_type") or "").lower()
825
+ if "html" in ctype or (text[:200].lstrip().startswith("<")):
826
+ try:
827
+ from bs4 import BeautifulSoup
828
+
829
+ soup = BeautifulSoup(text, "html.parser")
830
+ for tag in soup(["script", "style", "noscript"]):
831
+ tag.decompose()
832
+ extracted = " ".join(soup.get_text(" ", strip=True).split())
833
+ if len(extracted) > len(text) * 0.05 and len(extracted) >= 80:
834
+ res = dict(res)
835
+ res["text"] = extracted
836
+ res["method"] = "http_bs4"
837
+ except Exception as exc:
838
+ log.info("bs4 extract skip %s: %s", url[:60], exc)
839
+ return res
840
+
841
+
842
+ def get_playwright_content(url: str, *, timeout_ms: int = 45000) -> dict:
843
+ """Optional Playwright for allowlisted JS portals. Skip if package/browser missing."""
844
+ if not playwright_host_ok(url):
845
+ return {"status": "error", "error": "playwright_host_not_allowlisted", "original_url": url}
846
+ try:
847
+ from playwright.sync_api import sync_playwright
848
+ except Exception as exc:
849
+ return {"status": "error", "error": f"playwright_unavailable:{exc}", "original_url": url}
850
+ try:
851
+ with sync_playwright() as p:
852
+ browser = p.chromium.launch(headless=True)
853
+ try:
854
+ page = browser.new_page()
855
+ page.goto(url, wait_until="networkidle", timeout=timeout_ms)
856
+ page.wait_for_timeout(1500)
857
+ html = page.content() or ""
858
+ content = html.encode("utf-8", "replace")
859
+ finally:
860
+ browser.close()
861
+ except Exception as exc:
862
+ return {"status": "error", "error": f"playwright:{exc}", "original_url": url}
863
+ if not html or is_challenge(html, 200):
864
+ return {"status": "error", "error": "playwright_challenge_or_empty", "original_url": url}
865
+ text = html
866
+ try:
867
+ from bs4 import BeautifulSoup
868
+
869
+ soup = BeautifulSoup(html, "html.parser")
870
+ for tag in soup(["script", "style", "noscript"]):
871
+ tag.decompose()
872
+ text = " ".join(soup.get_text(" ", strip=True).split())
873
+ except Exception:
874
+ pass
875
+ return {
876
+ "status": "success",
877
+ "content": content,
878
+ "text": text,
879
+ "content_type": "text/html",
880
+ "original_url": url,
881
+ "method": "playwright",
882
+ "http_status": 200,
883
+ }
884
+
885
+
886
+ def _race_fetch_one(name: str, fn, winner_event: "threading.Event") -> tuple[str, dict]:
887
+ if winner_event.is_set():
888
+ return name, {"status": "error", "error": "abandoned_after_winner"}
889
+ try:
890
+ res = fn()
891
+ except Exception as exc:
892
+ return name, {"status": "error", "error": f"{name}:{exc}"}
893
+ return name, res if isinstance(res, dict) else {"status": "error", "error": f"{name}:bad_result"}
894
+
895
+
896
+ def parse_parallel_ladder_sources() -> list[str]:
897
+ """Parse PARALLEL_LADDER env into ordered source names.
898
+
899
+ PARALLEL_LADDER=1 / true / all → full five-way race.
900
+ PARALLEL_LADDER=0 / false / serial → empty (caller uses serial path).
901
+ PARALLEL_LADDER=warc,wayback,archive_is,live,playwright → explicit set.
902
+ """
903
+ raw = (os.environ.get("PARALLEL_LADDER", "1") or "1").strip()
904
+ low = raw.lower()
905
+ if low in ("0", "false", "no", "off", "serial"):
906
+ return []
907
+ all5 = ["warc", "wayback", "archive_is", "live", "playwright"]
908
+ if low in ("1", "true", "yes", "on", "all", "full"):
909
+ return all5
910
+ parts = [x.strip().lower().replace("-", "_") for x in raw.split(",") if x.strip()]
911
+ alias = {
912
+ "ais": "archive_is",
913
+ "archiveis": "archive_is",
914
+ "ia": "wayback",
915
+ "wb": "wayback",
916
+ "http": "live",
917
+ "http_live": "live",
918
+ "bs4": "live",
919
+ "pw": "playwright",
920
+ "cc": "warc",
921
+ "common_crawl": "warc",
922
+ }
923
+ out: list[str] = []
924
+ for p in parts:
925
+ name = alias.get(p, p)
926
+ if name in all5 and name not in out:
927
+ out.append(name)
928
+ return out or all5
929
+
930
+
931
+ _playwright_jobs_this_process = 0
932
+ _playwright_lock = None
933
+
934
+
935
+ def _get_playwright_lock():
936
+ global _playwright_lock
937
+ if _playwright_lock is None:
938
+ import threading
939
+ _playwright_lock = threading.Lock()
940
+ return _playwright_lock
941
+
942
+
943
+ def _mem_avail_gi() -> float:
944
+ try:
945
+ with open("/proc/meminfo") as f:
946
+ for line in f:
947
+ if line.startswith("MemAvailable:"):
948
+ return int(line.split()[1]) / 1024 / 1024
949
+ except Exception:
950
+ pass
951
+ return 99.0
952
+
953
+
954
+ def _playwright_soft_ok() -> bool:
955
+ """≤1 Playwright per country job (process); box ≤2 via PLAYWRIGHT_BOX_MAX; Mem≥6Gi."""
956
+ global _playwright_jobs_this_process
957
+ if _mem_avail_gi() < float(os.environ.get("PLAYWRIGHT_MIN_MEM_GI", "6") or 6):
958
+ return False
959
+ per_job = int(os.environ.get("PLAYWRIGHT_PER_JOB", "1") or 1)
960
+ if _playwright_jobs_this_process >= per_job:
961
+ return False
962
+ # Soft box-wide cap via lockfile count (best-effort, no kill)
963
+ box_max = int(os.environ.get("PLAYWRIGHT_BOX_MAX", "2") or 2)
964
+ lock_dir = os.environ.get("PLAYWRIGHT_LOCK_DIR", "/tmp/legal_scrapers_pw_locks")
965
+ try:
966
+ os.makedirs(lock_dir, exist_ok=True)
967
+ active = 0
968
+ for entry in os.listdir(lock_dir):
969
+ if not entry.endswith(".pw"):
970
+ continue
971
+ path = os.path.join(lock_dir, entry)
972
+ try:
973
+ pid = int(entry.split("_", 1)[0])
974
+ os.kill(pid, 0)
975
+ active += 1
976
+ except ProcessLookupError:
977
+ try:
978
+ os.unlink(path)
979
+ except OSError:
980
+ pass
981
+ except (ValueError, PermissionError, OSError):
982
+ active += 1 # fail closed for unknown/foreign lock
983
+ if active >= box_max:
984
+ return False
985
+ except Exception:
986
+ pass
987
+ return True
988
+
989
+
990
+ def _playwright_acquire_slot() -> Optional[str]:
991
+ """Create a lockfile slot; return path or None."""
992
+ global _playwright_jobs_this_process
993
+ if not _playwright_soft_ok():
994
+ return None
995
+ with _get_playwright_lock():
996
+ if not _playwright_soft_ok():
997
+ return None
998
+ lock_dir = os.environ.get("PLAYWRIGHT_LOCK_DIR", "/tmp/legal_scrapers_pw_locks")
999
+ os.makedirs(lock_dir, exist_ok=True)
1000
+ path = os.path.join(lock_dir, f"{os.getpid()}_{int(time.time() * 1000)}.pw")
1001
+ try:
1002
+ with open(path, "w") as f:
1003
+ f.write(str(os.getpid()))
1004
+ except Exception:
1005
+ return None
1006
+ _playwright_jobs_this_process += 1
1007
+ return path
1008
+
1009
+
1010
+ def _playwright_release_slot(path: Optional[str]) -> None:
1011
+ if not path:
1012
+ return
1013
+ try:
1014
+ os.unlink(path)
1015
+ except Exception:
1016
+ pass
1017
+
1018
+
1019
+ def fetch_ladder_parallel_race(
1020
+ url: str,
1021
+ *,
1022
+ cc_record: Optional[dict] = None,
1023
+ wayback_ts: Optional[str] = None,
1024
+ min_text: int = 150,
1025
+ sources: Optional[list[str]] = None,
1026
+ try_cc: bool = True,
1027
+ try_wayback: bool = True,
1028
+ try_archive_is: bool = True,
1029
+ try_http: bool = True,
1030
+ try_playwright: bool = True,
1031
+ ) -> dict:
1032
+ """Five-way race: WARC ∥ Wayback ∥ archive.is ∥ live ∥ Playwright.
1033
+
1034
+ First successful non-empty body wins; losers abandoned (cancel futures best-effort).
1035
+ Soft caps: ≤1 Playwright/job, box ≤2, skip PW if MemAvail<6Gi.
1036
+ archive.is submit_on_miss stays sparse (newest lookup races; submit not in race).
1037
+ Shared global Wayback delay via get_wayback_*.
1038
+ """
1039
+ import concurrent.futures
1040
+ import threading
1041
+
1042
+ errors: list[str] = []
1043
+ winner_event = threading.Event()
1044
+ srcs = sources if sources is not None else parse_parallel_ladder_sources()
1045
+ if not srcs:
1046
+ return {"status": "error", "error": "no_parallel_sources", "original_url": url, "ladder": "parallel_race"}
1047
+
1048
+ def _warc_job() -> dict:
1049
+ if winner_event.is_set():
1050
+ return {"status": "error", "error": "abandoned_after_winner"}
1051
+ recs: list[dict] = []
1052
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
1053
+ recs = [cc_record]
1054
+ elif try_cc and _env_truthy("LADDER_CC_SEARCH", "0"):
1055
+ try:
1056
+ recs = search_common_crawl(url, limit=2)
1057
+ except Exception as exc:
1058
+ return {"status": "error", "error": f"common_crawl_search:{exc}"}
1059
+ if not recs:
1060
+ return {"status": "error", "error": "no_warc_pointer"}
1061
+ last = {"status": "error", "error": "warc_miss"}
1062
+ for rec in recs:
1063
+ if winner_event.is_set():
1064
+ return {"status": "error", "error": "abandoned_after_winner"}
1065
+ last = fetch_common_crawl_warc(rec)
1066
+ if _body_nonempty(last, min_text=0):
1067
+ last = dict(last)
1068
+ last["method"] = last.get("method") or "common_crawl_warc"
1069
+ return last
1070
+ return last
1071
+
1072
+ def _wb_job() -> dict:
1073
+ if winner_event.is_set():
1074
+ return {"status": "error", "error": "abandoned_after_winner"}
1075
+ return get_wayback_cdx_then_replay(url, timestamp=wayback_ts, min_text=0)
1076
+
1077
+ def _ais_job() -> dict:
1078
+ if winner_event.is_set():
1079
+ return {"status": "error", "error": "abandoned_after_winner"}
1080
+ # Newest lookup only in race; submit_on_miss stays sparse / out-of-race
1081
+ return get_archive_is_content_ladder(url, submit_on_miss=False)
1082
+
1083
+ def _live_job() -> dict:
1084
+ if winner_event.is_set():
1085
+ return {"status": "error", "error": "abandoned_after_winner"}
1086
+ res = get_http_bs4(url)
1087
+ if res.get("status") == "success":
1088
+ raw = res.get("text") or ""
1089
+ if is_challenge(raw, res.get("http_status") or 200) or is_spa_shell(raw, raw):
1090
+ return {"status": "error", "error": "live_challenge_or_spa", "original_url": url}
1091
+ return res
1092
+
1093
+ def _pw_job() -> dict:
1094
+ if winner_event.is_set():
1095
+ return {"status": "error", "error": "abandoned_after_winner"}
1096
+ if not playwright_host_ok(url):
1097
+ return {"status": "error", "error": "playwright_host_not_allowlisted", "original_url": url}
1098
+ slot = _playwright_acquire_slot()
1099
+ if not slot:
1100
+ return {"status": "error", "error": "playwright_soft_cap", "original_url": url}
1101
+ try:
1102
+ if winner_event.is_set():
1103
+ return {"status": "error", "error": "abandoned_after_winner"}
1104
+ return get_playwright_content(url)
1105
+ finally:
1106
+ _playwright_release_slot(slot)
1107
+
1108
+ tasks: list[tuple[str, Any]] = []
1109
+ if "warc" in srcs and (try_cc or (cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")))):
1110
+ tasks.append(("warc", _warc_job))
1111
+ if "wayback" in srcs and try_wayback and not _env_truthy("SKIP_WAYBACK", "0"):
1112
+ tasks.append(("wayback", _wb_job))
1113
+ if "archive_is" in srcs and try_archive_is and _env_truthy("TRY_ARCHIVE_IS", "1"):
1114
+ tasks.append(("archive_is", _ais_job))
1115
+ if "live" in srcs and try_http:
1116
+ tasks.append(("live", _live_job))
1117
+ # Playwright: include in race when listed; TRY_PLAYWRIGHT default 1 if listed in PARALLEL_LADDER
1118
+ pw_wanted = "playwright" in srcs and (
1119
+ try_playwright or _env_truthy("TRY_PLAYWRIGHT", "1" if "playwright" in srcs else "0")
1120
+ )
1121
+ if pw_wanted:
1122
+ tasks.append(("playwright", _pw_job))
1123
+
1124
+ if not tasks:
1125
+ return {"status": "error", "error": "no_race_tasks", "original_url": url, "ladder": "parallel_race", "sources": srcs}
1126
+
1127
+ winner: Optional[dict] = None
1128
+ max_workers = min(5, len(tasks))
1129
+ ex = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="ladder")
1130
+ futs = {ex.submit(_race_fetch_one, name, fn, winner_event): name for name, fn in tasks}
1131
+ try:
1132
+ for fut in concurrent.futures.as_completed(
1133
+ futs, timeout=float(os.environ.get("LADDER_RACE_TIMEOUT", "90") or 90)
1134
+ ):
1135
+ name = futs[fut]
1136
+ try:
1137
+ _n, res = fut.result()
1138
+ except Exception as exc:
1139
+ errors.append(f"{name}:{exc}")
1140
+ continue
1141
+ if _body_nonempty(res, min_text=0):
1142
+ winner_event.set()
1143
+ winner = dict(res)
1144
+ winner["ladder"] = "parallel_race"
1145
+ winner["ladder_winner"] = name
1146
+ winner["ladder_sources"] = srcs
1147
+ winner["method"] = winner.get("method") or name
1148
+ for other in futs:
1149
+ if other is not fut and not other.done():
1150
+ other.cancel()
1151
+ break
1152
+ errors.append(f"{name}:{res.get('error') or 'empty'}")
1153
+ except concurrent.futures.TimeoutError:
1154
+ errors.append("race_timeout")
1155
+ winner_event.set()
1156
+ for other in futs:
1157
+ if not other.done():
1158
+ other.cancel()
1159
+ finally:
1160
+ # Critical: do not wait for in-flight losers. They see winner_event where possible;
1161
+ # already-blocked HTTP calls are abandoned and finish in background.
1162
+ ex.shutdown(wait=False, cancel_futures=True)
1163
+
1164
+ if winner and _body_nonempty(winner, min_text=min_text if min_text else 0):
1165
+ winner["ladder_errors"] = errors
1166
+ return winner
1167
+ if winner and _body_nonempty(winner, min_text=0):
1168
+ winner["ladder_errors"] = errors
1169
+ winner["warning"] = "below_min_text"
1170
+ return winner
1171
+ return {
1172
+ "status": "error",
1173
+ "error": "; ".join(errors) or "parallel_race_miss",
1174
+ "original_url": url,
1175
+ "ladder": "parallel_race",
1176
+ "ladder_sources": srcs,
1177
+ "ladder_errors": errors,
1178
+ }
1179
+
1180
+
1181
+
1182
+ def fetch_ladder(
1183
+ url: str,
1184
+ *,
1185
+ cc_record: Optional[dict] = None,
1186
+ wayback_ts: Optional[str] = None,
1187
+ min_text: int = 150,
1188
+ try_cc: Optional[bool] = None,
1189
+ try_wayback: Optional[bool] = None,
1190
+ try_archive_is: Optional[bool] = None,
1191
+ try_http: Optional[bool] = None,
1192
+ try_playwright: Optional[bool] = None,
1193
+ parallel: Optional[bool] = None,
1194
+ sources: Optional[list[str]] = None,
1195
+ ) -> dict:
1196
+ """Unified fetch ladder for tip climb.
1197
+
1198
+ PARALLEL_LADDER default = warc,wayback,archive_is,live,playwright (five-way race).
1199
+ First good body wins. Soft-cap Playwright; sparse archive.is submit (newest races).
1200
+ PARALLEL_LADDER=0 → serial: WARC → Wayback → archive.is → live → Playwright.
1201
+ Skips: Cloudflare unless creds; IPWB unless local+TRY_IPWB; Brave without key.
1202
+ """
1203
+ if try_cc is None:
1204
+ try_cc = True
1205
+ if try_wayback is None:
1206
+ try_wayback = not _env_truthy("SKIP_WAYBACK", "0")
1207
+ if try_archive_is is None:
1208
+ try_archive_is = _env_truthy("TRY_ARCHIVE_IS", "1")
1209
+ srcs = sources if sources is not None else parse_parallel_ladder_sources()
1210
+ if try_http is None:
1211
+ # Listing live in PARALLEL_LADDER opts into live race even if SKIP_LIVE=1
1212
+ if "live" in srcs:
1213
+ try_http = not _env_truthy("LADDER_SKIP_LIVE", "0")
1214
+ else:
1215
+ try_http = not _env_truthy("SKIP_LIVE", "0")
1216
+ if try_playwright is None:
1217
+ # If playwright listed in PARALLEL_LADDER, default on unless TRY_PLAYWRIGHT=0
1218
+ if "playwright" in srcs:
1219
+ try_playwright = _env_truthy("TRY_PLAYWRIGHT", "1")
1220
+ else:
1221
+ try_playwright = _env_truthy("TRY_PLAYWRIGHT", "0")
1222
+ if parallel is None:
1223
+ parallel = bool(srcs)
1224
+
1225
+ errors: list[str] = []
1226
+ steps: list[str] = []
1227
+
1228
+ if parallel and srcs:
1229
+ steps.append("parallel_race:" + ",".join(srcs))
1230
+ res = fetch_ladder_parallel_race(
1231
+ url,
1232
+ cc_record=cc_record,
1233
+ wayback_ts=wayback_ts,
1234
+ min_text=min_text,
1235
+ sources=srcs,
1236
+ try_cc=try_cc,
1237
+ try_wayback=try_wayback,
1238
+ try_archive_is=try_archive_is,
1239
+ try_http=try_http,
1240
+ try_playwright=try_playwright,
1241
+ )
1242
+ if _body_nonempty(res, min_text=0):
1243
+ res = dict(res)
1244
+ res["ladder_steps"] = steps
1245
+ return res
1246
+ errors.append(f"race:{res.get('error')}")
1247
+ # Sparse submit only after race miss (not inside race)
1248
+ if try_archive_is and _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0"):
1249
+ steps.append("archive_is_submit")
1250
+ sub = submit_archive_is(url, wait=_env_truthy("ARCHIVE_IS_SUBMIT_WAIT", "0"))
1251
+ if _body_nonempty(sub, min_text=0):
1252
+ sub = dict(sub)
1253
+ sub["ladder"] = "after_race_submit"
1254
+ sub["ladder_steps"] = steps
1255
+ return sub
1256
+ errors.append(f"archive_is_submit:{sub.get('error')}")
1257
+ else:
1258
+ # Serial fallback
1259
+ if try_cc or (cc_record and (cc_record.get("filename") or cc_record.get("warc_filename"))):
1260
+ steps.append("warc")
1261
+ cc_recs: list[dict] = []
1262
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
1263
+ cc_recs = [cc_record]
1264
+ elif try_cc and _env_truthy("LADDER_CC_SEARCH", "0"):
1265
+ try:
1266
+ cc_recs = search_common_crawl(url, limit=4)
1267
+ except Exception as exc:
1268
+ errors.append(f"common_crawl:{exc}")
1269
+ for rec in cc_recs:
1270
+ res = fetch_common_crawl_warc(rec)
1271
+ if _body_nonempty(res, min_text=0):
1272
+ res = dict(res)
1273
+ res["method"] = res.get("method") or "common_crawl_warc"
1274
+ res["ladder"] = "serial"
1275
+ res["ladder_steps"] = steps
1276
+ return res
1277
+ errors.append(f"common_crawl:{res.get('error')}")
1278
+ if try_wayback:
1279
+ steps.append("wayback")
1280
+ res = get_wayback_cdx_then_replay(url, timestamp=wayback_ts, min_text=0)
1281
+ if _body_nonempty(res, min_text=0):
1282
+ res = dict(res)
1283
+ res["ladder"] = "serial"
1284
+ res["ladder_steps"] = steps
1285
+ return res
1286
+ errors.append(f"wayback:{res.get('error')}")
1287
+ if try_archive_is:
1288
+ steps.append("archive_is")
1289
+ res = get_archive_is_content_ladder(url)
1290
+ if _body_nonempty(res, min_text=0):
1291
+ res = dict(res)
1292
+ res["ladder"] = "serial"
1293
+ res["ladder_steps"] = steps
1294
+ return res
1295
+ errors.append(f"archive_is:{res.get('error')}")
1296
+ if try_http:
1297
+ steps.append("live_http")
1298
+ res = get_http_bs4(url)
1299
+ if _body_nonempty(res, min_text=0):
1300
+ raw = res.get("text") or ""
1301
+ if not is_challenge(raw, res.get("http_status") or 200):
1302
+ res = dict(res)
1303
+ res["ladder"] = "serial"
1304
+ res["ladder_steps"] = steps
1305
+ return res
1306
+ errors.append(f"http:{res.get('error') or 'empty'}")
1307
+ if try_playwright and playwright_host_ok(url):
1308
+ steps.append("playwright")
1309
+ if _playwright_soft_ok():
1310
+ slot = _playwright_acquire_slot()
1311
+ try:
1312
+ res = get_playwright_content(url)
1313
+ finally:
1314
+ _playwright_release_slot(slot)
1315
+ if _body_nonempty(res, min_text=0):
1316
+ res = dict(res)
1317
+ res["ladder"] = "serial"
1318
+ res["ladder_steps"] = steps
1319
+ return res
1320
+ errors.append(f"playwright:{res.get('error')}")
1321
+ else:
1322
+ errors.append("playwright:soft_cap")
1323
+
1324
+ if has_cloudflare_creds() and _env_truthy("TRY_CLOUDFLARE", "0"):
1325
+ errors.append("cloudflare:no_sync_tip_impl")
1326
+ if has_ipwb_local():
1327
+ errors.append("ipwb:not_wired_in_tip_ladder")
1328
+
1329
+ return {
1330
+ "status": "error",
1331
+ "error": "; ".join(errors) or "ladder_all_failed",
1332
+ "original_url": url,
1333
+ "ladder": "parallel" if (parallel and srcs) else "serial",
1334
+ "ladder_steps": steps,
1335
+ "ladder_errors": errors,
1336
+ }
1337
+
1338
+
1339
+
1340
+ def fetch_with_fallbacks(
1341
+ url: str,
1342
+ *,
1343
+ cc_record: Optional[dict] = None,
1344
+ wayback_ts: Optional[str] = None,
1345
+ try_archive_is: bool = False,
1346
+ try_http: bool = True,
1347
+ try_cc: bool = True,
1348
+ ) -> dict:
1349
+ """Back-compat wrapper → fetch_ladder.
1350
+
1351
+ Historical default was serial WARC→Wayback→(optional archive.is)→HTTP.
1352
+ When PARALLEL_LADDER=1 (default for new tip paths), races archive sources first.
1353
+ Pass try_archive_is=True or set TRY_ARCHIVE_IS=1 to include archive.is.
1354
+ """
1355
+ # Preserve prior call-site semantics for try_archive_is default False unless env set
1356
+ ais = try_archive_is or _env_truthy("TRY_ARCHIVE_IS", "0")
1357
+ return fetch_ladder(
1358
+ url,
1359
+ cc_record=cc_record,
1360
+ wayback_ts=wayback_ts,
1361
+ try_cc=try_cc,
1362
+ try_archive_is=ais,
1363
+ try_http=try_http,
1364
+ # Back-compat callers stay serial unless env explicitly opts into race.
1365
+ parallel=bool(parse_parallel_ladder_sources()) if "PARALLEL_LADDER" in os.environ else False,
1366
+ )
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collect_py.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Paraguay: Biblioteca y Archivo del Congreso Nacional (BACN) leyes HTML."""
3
+ from __future__ import annotations
4
+ import logging, re, sys, time
5
+ from pathlib import Path
6
+ from urllib.parse import urljoin
7
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
8
+ from common import existing_ids, html_to_text, http_get, log_failure, utcnow, write_summary
9
+ from world_lib import cdx_urls, env_int, fetch_official, save_instrument, setup_log, slug_id
10
+
11
+ CC, COUNTRY, LANG = "py", "Paraguay", "es"
12
+ SOURCE_TYPE = "bacn_congreso"
13
+ LICENSE = (
14
+ "Official texts of laws of the Republic of Paraguay as published by the "
15
+ "Biblioteca y Archivo del Congreso Nacional (bacn.gov.py). Gaceta Oficial / "
16
+ "authentic congressional text prevails. Not legal advice."
17
+ )
18
+ UA = "legal-corpora-collector/1.0 (research; source=https://www.bacn.gov.py/leyes-paraguayas)"
19
+ ART = re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.|iculo)?|ART[IÍ]CULO)\s+[\d]+[º°o.]?)\b")
20
+ LIST = "https://www.bacn.gov.py/leyes-paraguayas"
21
+ log = logging.getLogger("py")
22
+
23
+
24
+ def discover() -> list[tuple[str, str]]:
25
+ items, seen = [], set()
26
+ def add(ident, url):
27
+ if ident in seen:
28
+ return
29
+ seen.add(ident)
30
+ items.append((ident, url))
31
+ try:
32
+ r = http_get(LIST, ua=UA, sleep=0.2)
33
+ if r.status_code == 200:
34
+ for href in re.findall(r'href="(https://www\.bacn\.gov\.py/leyes-paraguayas/\d+/[^"]+)"', r.text or ""):
35
+ m = re.search(r"/leyes-paraguayas/(\d+)/", href)
36
+ if m:
37
+ add(m.group(1), href.split("#")[0])
38
+ for href in re.findall(r'href="(/leyes-paraguayas/\d+/[^"]+)"', r.text or ""):
39
+ m = re.search(r"/leyes-paraguayas/(\d+)/", href)
40
+ if m:
41
+ add(m.group(1), urljoin("https://www.bacn.gov.py/", href))
42
+ except Exception as exc:
43
+ log.info("list err %s", exc)
44
+ for start in range(0, env_int("LIST_PAGES", 8) * 20, 20):
45
+ try:
46
+ r = http_get(f"{LIST}?start={start}", ua=UA, sleep=0.3)
47
+ if r.status_code != 200:
48
+ continue
49
+ for href in re.findall(r'href="(https://www\.bacn\.gov\.py/leyes-paraguayas/\d+/[^"]+)"', r.text or ""):
50
+ m = re.search(r"/leyes-paraguayas/(\d+)/", href)
51
+ if m:
52
+ add(m.group(1), href.split("#")[0])
53
+ except Exception:
54
+ continue
55
+ for h in cdx_urls("bacn.gov.py/leyes-paraguayas/", limit=env_int("CDX_LIMIT", 300), match_type="prefix"):
56
+ orig = (h.get("original") or "").split("#")[0]
57
+ m = re.search(r"/leyes-paraguayas/(\d+)/", orig)
58
+ if m and ".pdf" not in orig.lower():
59
+ add(m.group(1), orig.replace("http://", "https://"))
60
+ log.info("catalog %s", len(items))
61
+ return items
62
+
63
+
64
+ def main():
65
+ setup_log(CC)
66
+ t0 = utcnow()
67
+ max_new = env_int("MAX_NEW", 80)
68
+ max_seconds = env_int("MAX_SECONDS", 2400)
69
+ t_start = time.time()
70
+ done = existing_ids(CC)
71
+ ok = skip = fail = 0
72
+ items = discover()
73
+ for ident, url in items:
74
+ if max_new and ok >= max_new:
75
+ break
76
+ if max_seconds and (time.time() - t_start) > max_seconds:
77
+ break
78
+ rid = slug_id(CC, ident)
79
+ if rid in done:
80
+ skip += 1
81
+ continue
82
+ got = fetch_official(url, ua=UA, min_text=120)
83
+ text = got.get("text") or ""
84
+ if got.get("status") != "success":
85
+ fail += 1
86
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")})
87
+ continue
88
+ title = None
89
+ for line in text.splitlines():
90
+ if re.search(r"Ley\s+N", line, re.I) or (len(line.strip()) > 20 and "BACN" not in line):
91
+ title = line.strip()[:240]
92
+ break
93
+ if save_instrument(
94
+ cc=CC, country=COUNTRY, language=LANG, ident=ident,
95
+ title=title or f"Ley BACN {ident}", text=text, source_url=url,
96
+ source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_py.py",
97
+ article_re=ART, extra_meta={"fetch_method": got.get("method")},
98
+ ):
99
+ ok += 1
100
+ done.add(rid)
101
+ log.info("ok %s", ident)
102
+ else:
103
+ fail += 1
104
+ write_summary(
105
+ CC, country=COUNTRY, source="BACN leyes paraguayas",
106
+ source_urls=["https://www.bacn.gov.py/leyes-paraguayas"],
107
+ license_text=LICENSE, discovered=len(items), fetched=ok, skipped=skip, failed=fail,
108
+ coverage="catalog-backed incomplete",
109
+ notes="Official BACN HTML. Not Gaceta Oficial bulk (TLS). Not legal advice.",
110
+ last_run=t0,
111
+ )
112
+ log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collector.py ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect current Swiss federal classified compilation (SR) from Fedlex."""
3
+ from __future__ import annotations
4
+
5
+ import concurrent.futures
6
+ import hashlib
7
+ import html
8
+ import io
9
+ import json
10
+ import logging
11
+ import os
12
+ import random
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ import time
18
+ import traceback
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ import zipfile
23
+ from datetime import datetime, timezone
24
+ from html.parser import HTMLParser
25
+ from pathlib import Path
26
+ from xml.etree import ElementTree as ET
27
+
28
+ ROOT = Path("/workspace/legal-corpora/ch")
29
+ INSTR = ROOT / "instruments"
30
+ LOGS = ROOT / "logs"
31
+ TMP = ROOT / "tmp"
32
+ INDEX = ROOT / "index.jsonl"
33
+ SUMMARY = ROOT / "SUMMARY.md"
34
+ CATALOG = TMP / "catalog.json"
35
+ FAILED = LOGS / "failed.jsonl"
36
+
37
+ SPARQL_ENDPOINT = "https://fedlex.data.admin.ch/sparqlendpoint"
38
+ TODAY = "2026-09-02"
39
+ USER_AGENT = "legal-corpora-ch-collector/1.0 (research corpus; polite; contact via local operator)"
40
+ IN_FORCE = "https://fedlex.data.admin.ch/vocabulary/enforcement-status/0"
41
+ LANG_URI = {
42
+ "de": "http://publications.europa.eu/resource/authority/language/DEU",
43
+ "fr": "http://publications.europa.eu/resource/authority/language/FRA",
44
+ "it": "http://publications.europa.eu/resource/authority/language/ITA",
45
+ "rm": "http://publications.europa.eu/resource/authority/language/ROH",
46
+ "en": "http://publications.europa.eu/resource/authority/language/ENG",
47
+ }
48
+ URI_LANG = {v: k for k, v in LANG_URI.items()}
49
+ FMT_RANK = {
50
+ "https://fedlex.data.admin.ch/vocabulary/user-format/xml": 0,
51
+ "https://fedlex.data.admin.ch/vocabulary/user-format/html": 1,
52
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a": 2,
53
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf": 3,
54
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-x": 4,
55
+ "https://fedlex.data.admin.ch/vocabulary/user-format/docx": 5,
56
+ "https://fedlex.data.admin.ch/vocabulary/user-format/doc": 6,
57
+ }
58
+ FMT_NAME = {
59
+ "https://fedlex.data.admin.ch/vocabulary/user-format/xml": "xml",
60
+ "https://fedlex.data.admin.ch/vocabulary/user-format/html": "html",
61
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a": "pdf-a",
62
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf": "pdf",
63
+ "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-x": "pdf-x",
64
+ "https://fedlex.data.admin.ch/vocabulary/user-format/docx": "docx",
65
+ "https://fedlex.data.admin.ch/vocabulary/user-format/doc": "doc",
66
+ }
67
+ LICENSE = (
68
+ "Official legislative texts are not protected by copyright (URG Art. 5; "
69
+ "https://www.fedlex.admin.ch/eli/cc/1993/1798_1798_1798/de). "
70
+ "Consultation and download for reuse are free (PublG Art. 19; PublV Art. 48). "
71
+ "Reuse is subject to PublV Art. 49 (SR 170.512.1): do not alter the wording; "
72
+ "visually distinguish the text from commentary; include the notice "
73
+ "'Dies ist keine amtliche Veröffentlichung. Massgebend ist allein die "
74
+ "Veröffentlichung durch die Bundeskanzlei.'; do not present the copy as an "
75
+ "official publication; paid redistribution only in added-value form. "
76
+ "See https://www.fedlex.admin.ch/de/legal-information and "
77
+ "https://www.fedlex.admin.ch/de/broadcasters"
78
+ )
79
+ REUSE_NOTICE = (
80
+ "Dies ist keine amtliche Veröffentlichung. Massgebend ist allein die "
81
+ "Veröffentlichung durch die Bundeskanzlei."
82
+ )
83
+
84
+ WORKERS = 8
85
+ HTTP_TIMEOUT = 90
86
+ SPARQL_TIMEOUT = 180
87
+ MAX_BYTES = 80 * 1024 * 1024
88
+ RETRIES = 5
89
+
90
+ log = logging.getLogger("collector")
91
+ index_lock = threading.Lock()
92
+ fail_lock = threading.Lock()
93
+ stats_lock = threading.Lock()
94
+ STATS = {
95
+ "listed": 0,
96
+ "collected": 0,
97
+ "failed": 0,
98
+ "skipped_resume": 0,
99
+ "bytes": 0,
100
+ "empty_text": 0,
101
+ "started_at": None,
102
+ "by_format": {},
103
+ "by_lang_primary": {},
104
+ }
105
+
106
+
107
+ def setup_logging() -> None:
108
+ LOGS.mkdir(parents=True, exist_ok=True)
109
+ INSTR.mkdir(parents=True, exist_ok=True)
110
+ TMP.mkdir(parents=True, exist_ok=True)
111
+ log.setLevel(logging.INFO)
112
+ fmt = logging.Formatter("%(asctime)sZ %(levelname)s %(message)s", "%Y-%m-%dT%H:%M:%S")
113
+ fh = logging.FileHandler(LOGS / "collector.log", encoding="utf-8")
114
+ fh.setFormatter(fmt)
115
+ sh = logging.StreamHandler(sys.stdout)
116
+ sh.setFormatter(fmt)
117
+ log.addHandler(fh)
118
+ log.addHandler(sh)
119
+
120
+
121
+ def now_iso() -> str:
122
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
123
+
124
+
125
+ def strip_markup(s: str | None) -> str | None:
126
+ if not s:
127
+ return s
128
+ s = re.sub(r"<[^>]+>", " ", s)
129
+ s = html.unescape(s)
130
+ s = re.sub(r"\s+", " ", s).strip()
131
+ return s
132
+
133
+
134
+ def safe_id(sr: str) -> str:
135
+ sid = re.sub(r"[^0-9A-Za-z._-]+", "_", sr.strip())
136
+ sid = sid.strip("._") or "unknown"
137
+ if len(sid) > 180:
138
+ sid = sid[:160] + "_" + hashlib.sha1(sr.encode()).hexdigest()[:10]
139
+ return sid
140
+
141
+
142
+ def sparql(query: str, timeout: int = SPARQL_TIMEOUT) -> list[dict]:
143
+ last = None
144
+ for attempt in range(1, RETRIES + 1):
145
+ try:
146
+ data = urllib.parse.urlencode({"query": query}).encode("utf-8")
147
+ req = urllib.request.Request(
148
+ SPARQL_ENDPOINT,
149
+ data=data,
150
+ headers={
151
+ "Accept": "application/sparql-results+json",
152
+ "Content-Type": "application/x-www-form-urlencoded",
153
+ "User-Agent": USER_AGENT,
154
+ },
155
+ method="POST",
156
+ )
157
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
158
+ payload = json.loads(resp.read().decode("utf-8"))
159
+ rows = []
160
+ for b in payload.get("results", {}).get("bindings", []):
161
+ rows.append({k: v.get("value") for k, v in b.items()})
162
+ return rows
163
+ except Exception as e:
164
+ last = e
165
+ wait = min(60, 2 ** attempt) + random.random()
166
+ log.warning("SPARQL attempt %s failed: %s; sleep %.1fs", attempt, e, wait)
167
+ time.sleep(wait)
168
+ raise RuntimeError(f"SPARQL failed after retries: {last}")
169
+
170
+
171
+ def http_get(url: str, timeout: int = HTTP_TIMEOUT) -> tuple[bytes, str, str]:
172
+ last = None
173
+ for attempt in range(1, RETRIES + 1):
174
+ try:
175
+ req = urllib.request.Request(
176
+ url,
177
+ headers={
178
+ "User-Agent": USER_AGENT,
179
+ "Accept": "*/*",
180
+ "Accept-Encoding": "identity",
181
+ },
182
+ )
183
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
184
+ ctype = resp.headers.get("Content-Type") or ""
185
+ final = resp.geturl()
186
+ chunks = []
187
+ total = 0
188
+ while True:
189
+ buf = resp.read(256 * 1024)
190
+ if not buf:
191
+ break
192
+ total += len(buf)
193
+ if total > MAX_BYTES:
194
+ raise RuntimeError(f"response exceeds {MAX_BYTES} bytes")
195
+ chunks.append(buf)
196
+ return b"".join(chunks), ctype, final
197
+ except Exception as e:
198
+ last = e
199
+ wait = min(45, 1.5 ** attempt) + random.random()
200
+ log.warning("GET %s attempt %s failed: %s; sleep %.1fs", url, attempt, e, wait)
201
+ time.sleep(wait)
202
+ raise RuntimeError(f"GET failed {url}: {last}")
203
+
204
+
205
+ class HTMLTextParser(HTMLParser):
206
+ SKIP = {"script", "style", "noscript", "svg", "head"}
207
+
208
+ def __init__(self) -> None:
209
+ super().__init__(convert_charrefs=True)
210
+ self.parts: list[str] = []
211
+ self.skip = 0
212
+ self.seen_lawcontent = False
213
+ self.in_law = False
214
+ self.capture_all = False
215
+
216
+ def handle_starttag(self, tag: str, attrs) -> None:
217
+ tag = tag.lower()
218
+ ad = {k.lower(): (v or "") for k, v in attrs}
219
+ if tag in self.SKIP:
220
+ self.skip += 1
221
+ return
222
+ if ad.get("id") == "lawcontent":
223
+ self.seen_lawcontent = True
224
+ self.in_law = True
225
+ if tag in {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr", "article",
226
+ "section", "br", "dt", "blockquote", "pre", "figcaption"}:
227
+ self.parts.append("\n")
228
+ elif tag in {"td", "th", "dd"}:
229
+ self.parts.append("\t")
230
+
231
+ def handle_endtag(self, tag: str) -> None:
232
+ tag = tag.lower()
233
+ if tag in self.SKIP and self.skip:
234
+ self.skip -= 1
235
+ return
236
+ if tag in {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr", "article", "section"}:
237
+ self.parts.append("\n")
238
+ if tag == "div" and self.in_law:
239
+ # keep capturing nested; parser is not stack-precise for lawcontent end
240
+ pass
241
+
242
+ def handle_data(self, data: str) -> None:
243
+ if self.skip:
244
+ return
245
+ if self.seen_lawcontent and not self.in_law and not self.capture_all:
246
+ return
247
+ if data and data.strip():
248
+ self.parts.append(data)
249
+ elif data:
250
+ self.parts.append(" ")
251
+
252
+
253
+ def html_to_text(raw: bytes) -> str:
254
+ text = raw.decode("utf-8", "replace")
255
+ p = HTMLTextParser()
256
+ try:
257
+ p.feed(text)
258
+ p.close()
259
+ except Exception:
260
+ pass
261
+ if p.seen_lawcontent and not any(x.strip() for x in p.parts):
262
+ p = HTMLTextParser()
263
+ p.capture_all = True
264
+ p.in_law = True
265
+ p.feed(text)
266
+ out = "".join(p.parts)
267
+ out = re.sub(r"[ \t]+\n", "\n", out)
268
+ out = re.sub(r"\n{3,}", "\n\n", out)
269
+ out = re.sub(r"[ \t]{2,}", " ", out)
270
+ return out.strip()
271
+
272
+
273
+ def localname(tag: str) -> str:
274
+ if "}" in tag:
275
+ return tag.rsplit("}", 1)[-1]
276
+ if tag.startswith("{") is False and ":" in tag:
277
+ return tag.split(":", 1)[-1]
278
+ return tag
279
+
280
+
281
+ SKIP_XML = {
282
+ "meta", "identification", "publication", "lifecycle", "workflow",
283
+ "analysis", "references", "classification", "proprietary",
284
+ }
285
+
286
+
287
+ def xml_to_text(raw: bytes) -> str:
288
+ try:
289
+ root = ET.fromstring(raw)
290
+ except ET.ParseError:
291
+ # try recovering by taking inner well-known start
292
+ txt = raw.decode("utf-8", "replace")
293
+ txt = re.sub(r"&(?!#|amp;|lt;|gt;|quot;|apos;)", "&amp;", txt)
294
+ root = ET.fromstring(txt.encode("utf-8"))
295
+ parts: list[str] = []
296
+
297
+ def walk(el: ET.Element, skip_depth: int = 0) -> None:
298
+ name = localname(el.tag).lower()
299
+ if name in SKIP_XML:
300
+ return
301
+ if name in {"p", "paragraph", "article", "chapter", "section", "book", "title",
302
+ "subtitle", "formula", "preamble", "preface", "conclusion",
303
+ "alinea", "list", "point", "recital", "heading", "num", "content"}:
304
+ parts.append("\n")
305
+ if el.text and el.text.strip():
306
+ parts.append(el.text)
307
+ elif el.text and "\n" in el.text:
308
+ parts.append("\n")
309
+ for child in list(el):
310
+ walk(child)
311
+ if child.tail and child.tail.strip():
312
+ parts.append(child.tail)
313
+ elif child.tail and "\n" in child.tail:
314
+ parts.append("\n")
315
+
316
+ walk(root)
317
+ out = " ".join(parts)
318
+ out = re.sub(r"[ \t]+\n", "\n", out)
319
+ out = re.sub(r"\n{3,}", "\n\n", out)
320
+ out = re.sub(r"[ \t]{2,}", " ", out)
321
+ out = re.sub(r" *\n *", "\n", out)
322
+ out = out.strip()
323
+ if len(out) < 40:
324
+ fallback = []
325
+ for el in root.iter():
326
+ if el.text and el.text.strip():
327
+ fallback.append(el.text.strip())
328
+ if el.tail and el.tail.strip():
329
+ fallback.append(el.tail.strip())
330
+ fb = "\n".join(fallback).strip()
331
+ if len(fb) > len(out):
332
+ out = fb
333
+ return out
334
+
335
+
336
+ def pdf_to_text(raw: bytes, stem: str) -> str:
337
+ pdf_path = TMP / f"{stem}.pdf"
338
+ pdf_path.write_bytes(raw)
339
+ try:
340
+ r = subprocess.run(
341
+ ["pdftotext", "-layout", "-enc", "UTF-8", str(pdf_path), "-"],
342
+ capture_output=True,
343
+ timeout=120,
344
+ )
345
+ if r.returncode != 0:
346
+ r = subprocess.run(
347
+ ["pdftotext", "-enc", "UTF-8", str(pdf_path), "-"],
348
+ capture_output=True,
349
+ timeout=120,
350
+ )
351
+ text = r.stdout.decode("utf-8", "replace")
352
+ return text.strip()
353
+ finally:
354
+ try:
355
+ pdf_path.unlink(missing_ok=True)
356
+ except Exception:
357
+ pass
358
+
359
+
360
+ def docx_to_text(raw: bytes) -> str:
361
+ with zipfile.ZipFile(io.BytesIO(raw)) as zf:
362
+ xml = zf.read("word/document.xml")
363
+ root = ET.fromstring(xml)
364
+ parts: list[str] = []
365
+ for el in root.iter():
366
+ name = localname(el.tag)
367
+ if name == "tab":
368
+ parts.append("\t")
369
+ elif name == "br":
370
+ parts.append("\n")
371
+ elif name == "p":
372
+ parts.append("\n")
373
+ if el.text:
374
+ parts.append(el.text)
375
+ if el.tail:
376
+ parts.append(el.tail)
377
+ out = "".join(parts)
378
+ out = re.sub(r"\n{3,}", "\n\n", out)
379
+ return out.strip()
380
+
381
+
382
+ def extract_text(fmt_name: str, raw: bytes, stem: str) -> str:
383
+ if fmt_name == "xml":
384
+ return xml_to_text(raw)
385
+ if fmt_name == "html":
386
+ return html_to_text(raw)
387
+ if fmt_name in {"pdf", "pdf-a", "pdf-x"}:
388
+ return pdf_to_text(raw, stem)
389
+ if fmt_name == "docx":
390
+ return docx_to_text(raw)
391
+ if fmt_name == "doc":
392
+ raise RuntimeError("doc binary skipped (no converter); use pdf/html/xml)")
393
+ raise RuntimeError(f"unknown format {fmt_name}")
394
+
395
+
396
+ def load_done() -> set[str]:
397
+ done: set[str] = set()
398
+ if not INDEX.exists():
399
+ return done
400
+ with INDEX.open("r", encoding="utf-8") as f:
401
+ for line in f:
402
+ line = line.strip()
403
+ if not line:
404
+ continue
405
+ try:
406
+ rec = json.loads(line)
407
+ except json.JSONDecodeError:
408
+ continue
409
+ rid = rec.get("id")
410
+ st = rec.get("status")
411
+ if rid and st == "ok":
412
+ done.add(rid)
413
+ elif rid and st == "failed":
414
+ done.discard(rid) # retry failed
415
+ return done
416
+
417
+
418
+ def append_index(rec: dict) -> None:
419
+ line = json.dumps(rec, ensure_ascii=False) + "\n"
420
+ with index_lock:
421
+ with INDEX.open("a", encoding="utf-8") as f:
422
+ f.write(line)
423
+ f.flush()
424
+ os.fsync(f.fileno())
425
+
426
+
427
+ def append_failed(rec: dict) -> None:
428
+ line = json.dumps(rec, ensure_ascii=False) + "\n"
429
+ with fail_lock:
430
+ with FAILED.open("a", encoding="utf-8") as f:
431
+ f.write(line)
432
+
433
+
434
+ def write_summary(extra: dict | None = None) -> None:
435
+ extra = extra or {}
436
+ with stats_lock:
437
+ s = dict(STATS)
438
+ collected_bytes = 0
439
+ n_files = 0
440
+ if INSTR.exists():
441
+ for p in INSTR.glob("*.json"):
442
+ n_files += 1
443
+ try:
444
+ collected_bytes += p.stat().st_size
445
+ except OSError:
446
+ pass
447
+ listed = s.get("listed") or extra.get("listed") or 0
448
+ body = f"""# Switzerland — Classified Compilation (SR / Classified Compilation)
449
+
450
+ **Retrieved:** {now_iso()} (UTC) / {datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")}
451
+ **Source:** Fedlex (Federal Chancellery / Swiss Confederation)
452
+ - Portal: https://www.fedlex.admin.ch/
453
+ - SPARQL/LINDAS: https://fedlex.data.admin.ch/sparqlendpoint
454
+ - ELI CC: https://www.fedlex.admin.ch/eli/cc
455
+ - Legal info: https://www.fedlex.admin.ch/de/legal-information
456
+
457
+ ## Scope
458
+ Current **in-force** entries of the **Systematische Rechtssammlung (SR)** /
459
+ **Classified Compilation (CC)**, including domestic federal law and
460
+ international-law texts classified in the SR (chapter 0). Historical
461
+ Official Compilation (AS / OC) amending acts are **not** stored as separate
462
+ instruments; their effect is already consolidated in the current SR text.
463
+
464
+ In-force filter: `jolux:inForceStatus` =
465
+ `https://fedlex.data.admin.ch/vocabulary/enforcement-status/0` ("In force")
466
+ as of {TODAY}.
467
+
468
+ ## Counts
469
+ - Listed (in-force SR instruments): **{listed}**
470
+ - Collected (JSON with non-empty primary text): **{s.get("collected", 0)}**
471
+ - Failed: **{s.get("failed", 0)}**
472
+ - Resumed/skipped already-ok: **{s.get("skipped_resume", 0)}**
473
+ - Empty-text: **{s.get("empty_text", 0)}**
474
+ - Instrument JSON files on disk: **{n_files}**
475
+ - Instrument JSON bytes: **{collected_bytes}** ({collected_bytes/1024/1024:.1f} MiB)
476
+
477
+ ## Formats used (primary text)
478
+ {json.dumps(s.get("by_format") or {}, ensure_ascii=False, indent=2)}
479
+
480
+ ## Primary language of stored record
481
+ {json.dumps(s.get("by_lang_primary") or {}, ensure_ascii=False, indent=2)}
482
+
483
+ ## Record layout
484
+ - `instruments/{{safe_id}}.json` — one file per SR number
485
+ - `index.jsonl` — append-only collection log (resume key: `id` + `status=ok`)
486
+ - German is the primary `text` when available; French/Italian (and RM/EN if
487
+ present) are listed in `metadata.languages` and stored under `documents`
488
+ when XML/HTML could be fetched without extra PDF-only downloads.
489
+
490
+ ## Copyright / reuse
491
+ {LICENSE}
492
+
493
+ Required reuse notice: {REUSE_NOTICE}
494
+
495
+ ## Collector
496
+ - Script: `/workspace/legal-corpora/ch/collector.py`
497
+ - Log: `/workspace/legal-corpora/ch/logs/collector.log`
498
+ - Started (UTC): {s.get("started_at")}
499
+ - Workers: {WORKERS}
500
+ - No git clone; no git commit; streamed to disk.
501
+
502
+ ## Blockers
503
+ {extra.get("blockers", "None at summary write.")}
504
+ """
505
+ SUMMARY.write_text(body, encoding="utf-8")
506
+
507
+
508
+
509
+
510
+ def fetch_catalog() -> list[dict]:
511
+ if CATALOG.exists():
512
+ try:
513
+ data = json.loads(CATALOG.read_text(encoding="utf-8"))
514
+ if isinstance(data, list) and len(data) >= 5000:
515
+ with_files = sum(1 for a in data if a.get("files"))
516
+ if with_files >= 5000:
517
+ log.info("Loaded cached catalog: %s acts (%s with files)", len(data), with_files)
518
+ return data
519
+ log.info("Cached catalog incomplete (%s/%s with files); rebuilding", with_files, len(data))
520
+ except Exception as e:
521
+ log.warning("Catalog cache unreadable: %s", e)
522
+
523
+ log.info("SPARQL: listing in-force ConsolidationAbstracts + titles")
524
+ meta_q = f"""
525
+ PREFIX jolux: <http://data.legilux.public.lu/resource/ontology/jolux#>
526
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
527
+ SELECT DISTINCT ?abstract ?sr ?lang ?title ?dateDocument ?dateEntryInForce ?historicalId
528
+ WHERE {{
529
+ ?abstract a jolux:ConsolidationAbstract ;
530
+ jolux:inForceStatus <{IN_FORCE}> ;
531
+ jolux:classifiedByTaxonomyEntry ?tax .
532
+ ?tax skos:notation ?sr .
533
+ OPTIONAL {{ ?abstract jolux:dateDocument ?dateDocument }}
534
+ OPTIONAL {{ ?abstract jolux:dateEntryInForce ?dateEntryInForce }}
535
+ OPTIONAL {{ ?abstract jolux:historicalLegalId ?historicalId }}
536
+ ?abstract jolux:isRealizedBy ?expr .
537
+ ?expr jolux:language ?lang .
538
+ OPTIONAL {{ ?expr jolux:title ?title }}
539
+ }}
540
+ """
541
+ meta_rows = sparql(meta_q, timeout=180)
542
+ log.info("Title rows: %s", len(meta_rows))
543
+
544
+ acts: dict[str, dict] = {}
545
+ for row in meta_rows:
546
+ uri = row.get("abstract")
547
+ if not uri:
548
+ continue
549
+ rec = acts.setdefault(
550
+ uri,
551
+ {
552
+ "abstract": uri,
553
+ "sr": row.get("sr") or "",
554
+ "historical_id": row.get("historicalId"),
555
+ "date_document": row.get("dateDocument"),
556
+ "date_entry_in_force": row.get("dateEntryInForce"),
557
+ "titles": {},
558
+ "languages": set(),
559
+ "files": [],
560
+ "cons": None,
561
+ "cons_date": None,
562
+ },
563
+ )
564
+ lang = URI_LANG.get(row.get("lang") or "", None)
565
+ if lang:
566
+ rec["languages"].add(lang)
567
+ title = strip_markup(row.get("title"))
568
+ if title:
569
+ rec["titles"].setdefault(lang, title)
570
+ if row.get("sr") and not rec["sr"]:
571
+ rec["sr"] = row["sr"]
572
+
573
+ log.info("Distinct in-force abstracts from titles: %s", len(acts))
574
+
575
+ # One SPARQL per (language, format) to stay under Virtuoso result-size caps.
576
+ fmt_list = [
577
+ ("xml", "https://fedlex.data.admin.ch/vocabulary/user-format/xml"),
578
+ ("html", "https://fedlex.data.admin.ch/vocabulary/user-format/html"),
579
+ ("pdf-a", "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a"),
580
+ ]
581
+ lang_list = [("de", LANG_URI["de"]), ("fr", LANG_URI["fr"]), ("it", LANG_URI["it"])]
582
+ url_rows: list[dict] = []
583
+ for lang_code, lang_uri in lang_list:
584
+ for fmt_name, fmt_uri in fmt_list:
585
+ log.info("SPARQL: latest manifestations lang=%s fmt=%s", lang_code, fmt_name)
586
+ url_q = f"""
587
+ PREFIX jolux: <http://data.legilux.public.lu/resource/ontology/jolux#>
588
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
589
+ SELECT DISTINCT ?abstract ?cons ?date ?url
590
+ WHERE {{
591
+ ?abstract a jolux:ConsolidationAbstract ;
592
+ jolux:inForceStatus <{IN_FORCE}> .
593
+ ?cons jolux:isMemberOf ?abstract ;
594
+ jolux:dateApplicability ?date ;
595
+ jolux:isRealizedBy ?expr .
596
+ FILTER(?date <= xsd:date("{TODAY}"))
597
+ FILTER NOT EXISTS {{
598
+ ?c2 jolux:isMemberOf ?abstract ;
599
+ jolux:dateApplicability ?d2 .
600
+ FILTER(?d2 <= xsd:date("{TODAY}") && ?d2 > ?date)
601
+ ?c2 jolux:isRealizedBy ?e2 .
602
+ ?e2 jolux:isEmbodiedBy ?m2 .
603
+ ?m2 jolux:isExemplifiedBy ?x .
604
+ }}
605
+ ?expr jolux:language <{lang_uri}> ;
606
+ jolux:isEmbodiedBy ?manif .
607
+ ?manif jolux:userFormat <{fmt_uri}> ;
608
+ jolux:isExemplifiedBy ?url .
609
+ }}
610
+ """
611
+ rows = sparql(url_q, timeout=180)
612
+ log.info(" %s/%s -> %s rows", lang_code, fmt_name, len(rows))
613
+ for row in rows:
614
+ row["lang"] = lang_uri
615
+ row["fmt"] = fmt_uri
616
+ url_rows.extend(rows)
617
+
618
+ log.info("Total manifestation rows: %s", len(url_rows))
619
+ seen_files = set()
620
+ for row in url_rows:
621
+ uri = row.get("abstract")
622
+ if not uri:
623
+ continue
624
+ if uri not in acts:
625
+ acts[uri] = {
626
+ "abstract": uri,
627
+ "sr": "",
628
+ "historical_id": None,
629
+ "date_document": None,
630
+ "date_entry_in_force": None,
631
+ "titles": {},
632
+ "languages": set(),
633
+ "files": [],
634
+ "cons": None,
635
+ "cons_date": None,
636
+ }
637
+ rec = acts[uri]
638
+ rec["cons"] = row.get("cons")
639
+ rec["cons_date"] = row.get("date")
640
+ lang = URI_LANG.get(row.get("lang") or "", None)
641
+ fmt = row.get("fmt")
642
+ url = row.get("url")
643
+ if not (lang and fmt and url):
644
+ continue
645
+ key = (uri, lang, fmt, url)
646
+ if key in seen_files:
647
+ continue
648
+ seen_files.add(key)
649
+ rec["languages"].add(lang)
650
+ rec["files"].append({"lang": lang, "fmt": fmt, "url": url, "rank": FMT_RANK.get(fmt, 99)})
651
+
652
+ catalog = []
653
+ n_with = 0
654
+ for rec in acts.values():
655
+ rec["languages"] = sorted(rec["languages"])
656
+ rec["files"].sort(key=lambda x: (x["lang"], x["rank"], x["url"]))
657
+ if rec["files"]:
658
+ n_with += 1
659
+ catalog.append(rec)
660
+ catalog.sort(key=lambda r: tuple(int(p) if p.isdigit() else p for p in re.split(r"(\d+)", r["sr"] or "")))
661
+ CATALOG.write_text(json.dumps(catalog, ensure_ascii=False), encoding="utf-8")
662
+ log.info("Wrote catalog %s (%s acts, %s with files)", CATALOG, len(catalog), n_with)
663
+ return catalog
664
+
665
+
666
+ def pick_files(files: list[dict], lang: str, allow_pdf: bool) -> tuple[str | None, list[str]]:
667
+ ranked: dict[int, list[str]] = {}
668
+ for f in files:
669
+ if f["lang"] != lang:
670
+ continue
671
+ rank = f.get("rank", 99)
672
+ if rank > 6:
673
+ continue
674
+ name = FMT_NAME.get(f["fmt"])
675
+ if name is None:
676
+ continue
677
+ if not allow_pdf and name in {"pdf", "pdf-a", "pdf-x", "doc"}:
678
+ continue
679
+ ranked.setdefault(rank, []).append(f["url"])
680
+ if not ranked:
681
+ return None, []
682
+ best = min(ranked)
683
+ fmt_uri = None
684
+ for uri, r in FMT_RANK.items():
685
+ if r == best:
686
+ fmt_uri = uri
687
+ break
688
+ return FMT_NAME.get(fmt_uri or "", None), sorted(set(ranked[best]))
689
+
690
+
691
+ def sniff_format(claimed: str, raw: bytes, ctype: str) -> str:
692
+ head = raw[:8]
693
+ cl = (ctype or "").lower()
694
+ if head.startswith(b"%PDF"):
695
+ return "pdf"
696
+ if head.startswith(b"PK"):
697
+ return "docx"
698
+ if head.lstrip().startswith(b"<?xml") or head.lstrip().startswith(b"<akn") or head.lstrip().startswith(b"<AKN"):
699
+ return "xml"
700
+ if b"<html" in raw[:4000].lower() or "html" in cl:
701
+ if claimed in {"html", "xml"}:
702
+ return "html" if claimed == "html" or b"<html" in raw[:4000].lower() else claimed
703
+ if "pdf" in cl:
704
+ return "pdf"
705
+ return claimed
706
+
707
+
708
+ def formats_for_lang(files: list[dict], lang: str, allow_pdf: bool) -> list[tuple[str, list[str]]]:
709
+ """Return (fmt_name, urls) groups in rank order so empty XML can fall through to PDF."""
710
+ grouped: dict[int, list[str]] = {}
711
+ rank_name: dict[int, str] = {}
712
+ for f in files:
713
+ if f["lang"] != lang:
714
+ continue
715
+ rank = f.get("rank", 99)
716
+ name = FMT_NAME.get(f["fmt"])
717
+ if name is None:
718
+ continue
719
+ if not allow_pdf and name in {"pdf", "pdf-a", "pdf-x", "doc"}:
720
+ continue
721
+ rank_name[rank] = name
722
+ grouped.setdefault(rank, [])
723
+ if f["url"] not in grouped[rank]:
724
+ grouped[rank].append(f["url"])
725
+ out = []
726
+ for rank in sorted(grouped):
727
+ out.append((rank_name[rank], grouped[rank]))
728
+ return out
729
+
730
+
731
+ def fetch_lang_text(act: dict, lang: str, allow_pdf: bool) -> dict | None:
732
+ sid = safe_id(act["sr"])
733
+ groups = formats_for_lang(act.get("files") or [], lang, allow_pdf=allow_pdf)
734
+ if not groups:
735
+ return None
736
+ last_err = None
737
+ for fmt, urls in groups:
738
+ texts = []
739
+ used = []
740
+ used_fmt = fmt
741
+ for i, url in enumerate(urls):
742
+ try:
743
+ raw, ctype, final = http_get(url)
744
+ except Exception as e:
745
+ last_err = e
746
+ log.warning("GET %s %s %s failed: %s", act["sr"], lang, url, e)
747
+ continue
748
+ actual = sniff_format(fmt, raw, ctype)
749
+ stem = f"{sid}_{lang}_{actual}_{i}"
750
+ try:
751
+ t = extract_text(actual, raw, stem)
752
+ except Exception as e:
753
+ last_err = e
754
+ log.warning("extract %s %s %s failed: %s", act["sr"], lang, actual, e)
755
+ continue
756
+ if t and t.strip():
757
+ texts.append(t.strip())
758
+ used.append(final or url)
759
+ used_fmt = actual
760
+ if texts:
761
+ title = act.get("titles", {}).get(lang) or act.get("titles", {}).get("de") or f"SR {act['sr']}"
762
+ return {
763
+ "id": f"{act['sr']}-{lang}",
764
+ "title": title,
765
+ "text": "\n\n".join(texts),
766
+ "source_url": used[0],
767
+ "metadata": {
768
+ "language": lang,
769
+ "format": used_fmt,
770
+ "source_urls": used,
771
+ "consolidation": act.get("cons"),
772
+ "consolidation_date": act.get("cons_date"),
773
+ "parts": len(used),
774
+ },
775
+ }
776
+ log.info("empty extract %s lang=%s fmt=%s; trying next format", act["sr"], lang, fmt)
777
+ if last_err:
778
+ log.warning("all formats empty for %s lang=%s last_err=%s", act["sr"], lang, last_err)
779
+ return None
780
+
781
+
782
+ def build_record(act: dict) -> dict:
783
+ langs_avail = act.get("languages") or []
784
+ documents = []
785
+ # German first; empty XML/HTML falls through to PDF inside fetch_lang_text
786
+ de_doc = fetch_lang_text(act, "de", allow_pdf=True)
787
+ if de_doc:
788
+ documents.append(de_doc)
789
+ # Other langs: XML/HTML first, then PDF if those are empty
790
+ for lang in ("fr", "it", "rm", "en"):
791
+ if lang not in langs_avail:
792
+ continue
793
+ allow_pdf = True
794
+ try:
795
+ doc = fetch_lang_text(act, lang, allow_pdf=allow_pdf)
796
+ except Exception as e:
797
+ log.warning("lang %s for %s failed: %s", lang, act["sr"], e)
798
+ doc = None
799
+ if doc:
800
+ documents.append(doc)
801
+
802
+ primary = None
803
+ primary_lang = None
804
+ for lang in ("de", "fr", "it", "rm", "en"):
805
+ for d in documents:
806
+ if d["metadata"]["language"] == lang:
807
+ primary = d
808
+ primary_lang = lang
809
+ break
810
+ if primary:
811
+ break
812
+
813
+ if not primary or not (primary.get("text") or "").strip():
814
+ raise RuntimeError("no extractable text in de/fr/it")
815
+
816
+ eli_data = act["abstract"]
817
+ eli_www = eli_data.replace("https://fedlex.data.admin.ch/", "https://www.fedlex.admin.ch/")
818
+ title = (
819
+ act.get("titles", {}).get("de")
820
+ or act.get("titles", {}).get(primary_lang)
821
+ or f"SR {act['sr']}"
822
+ )
823
+ date_issued = None
824
+ dd = act.get("date_document")
825
+ if dd:
826
+ date_issued = str(dd)[:10]
827
+
828
+ rec = {
829
+ "schema_version": "collection_record.v1",
830
+ "record_type": "law",
831
+ "id": act["sr"],
832
+ "title": title,
833
+ "jurisdiction": "CH",
834
+ "country": "Switzerland",
835
+ "language": primary_lang,
836
+ "source_type": "fedlex",
837
+ "source_url": eli_www,
838
+ "eli": eli_data,
839
+ "date": date_issued,
840
+ "date_issued": date_issued,
841
+ "retrieved_at": now_iso(),
842
+ "identifier": act["sr"],
843
+ "official_identifier": act["sr"],
844
+ "law_identifier": act["sr"],
845
+ "law_status": "current",
846
+ "is_current": True,
847
+ "license": "unknown",
848
+ "text": primary["text"],
849
+ "documents": documents,
850
+ "metadata": {
851
+ "license": LICENSE,
852
+ "retrieved_at": now_iso(),
853
+ "official_id": act["sr"],
854
+ "publisher": "Fedlex / Swiss Confederation",
855
+ "source_name": "fedlex.admin.ch",
856
+ "languages": langs_avail,
857
+ "historical_legal_id": act.get("historical_id"),
858
+ "date_entry_in_force": (str(act["date_entry_in_force"])[:10] if act.get("date_entry_in_force") else None),
859
+ "consolidation_date": act.get("cons_date"),
860
+ "consolidation_eli": act.get("cons"),
861
+ "reuse_notice": REUSE_NOTICE,
862
+ "copyright_basis": "URG Art. 5; PublV Art. 48–49",
863
+ "in_force_status": IN_FORCE,
864
+ "primary_format": primary["metadata"].get("format"),
865
+ },
866
+ }
867
+ return rec
868
+
869
+
870
+ def process_act(act: dict) -> tuple[str, str, int, str | None]:
871
+ sr = act.get("sr") or "unknown"
872
+ sid = safe_id(sr)
873
+ path = INSTR / f"{sid}.json"
874
+ rec = build_record(act)
875
+ tmp = path.with_suffix(".json.tmp")
876
+ data = json.dumps(rec, ensure_ascii=False, indent=2).encode("utf-8")
877
+ tmp.write_bytes(data)
878
+ tmp.replace(path)
879
+ fmt = rec["metadata"].get("primary_format") or "?"
880
+ lang = rec.get("language") or "?"
881
+ return sid, fmt, len(data), lang
882
+
883
+
884
+ def main() -> int:
885
+ setup_logging()
886
+ STATS["started_at"] = now_iso()
887
+ log.info("START collector Swiss SR/CC")
888
+ catalog = fetch_catalog()
889
+ STATS["listed"] = len(catalog)
890
+ done = load_done()
891
+ log.info("Catalog %s acts; already ok in index: %s", len(catalog), len(done))
892
+ pending = [a for a in catalog if a.get("sr") and safe_id(a["sr"]) not in done and a["sr"] not in done]
893
+ # resume uses safe_id and raw sr
894
+ pending = []
895
+ for a in catalog:
896
+ sr = a.get("sr") or ""
897
+ sid = safe_id(sr)
898
+ if sid in done or sr in done:
899
+ STATS["skipped_resume"] += 1
900
+ continue
901
+ pending.append(a)
902
+ log.info("Pending: %s", len(pending))
903
+ write_summary()
904
+
905
+ def worker(act: dict) -> None:
906
+ sr = act.get("sr") or "unknown"
907
+ sid = safe_id(sr)
908
+ try:
909
+ time.sleep(random.uniform(0.0, 0.15))
910
+ sid, fmt, nbytes, lang = process_act(act)
911
+ append_index({
912
+ "id": sr,
913
+ "safe_id": sid,
914
+ "file": f"instruments/{sid}.json",
915
+ "status": "ok",
916
+ "bytes": nbytes,
917
+ "format": fmt,
918
+ "language": lang,
919
+ "retrieved_at": now_iso(),
920
+ })
921
+ with stats_lock:
922
+ STATS["collected"] += 1
923
+ STATS["bytes"] += nbytes
924
+ STATS["by_format"][fmt] = STATS["by_format"].get(fmt, 0) + 1
925
+ STATS["by_lang_primary"][lang] = STATS["by_lang_primary"].get(lang, 0) + 1
926
+ n = STATS["collected"] + STATS["failed"]
927
+ if n % 25 == 0:
928
+ log.info("progress collected=%s failed=%s last=%s %s bytes=%s",
929
+ STATS["collected"], STATS["failed"], sr, fmt, nbytes)
930
+ if n % 100 == 0:
931
+ write_summary()
932
+ except Exception as e:
933
+ log.error("FAIL %s: %s", sr, e)
934
+ append_index({
935
+ "id": sr,
936
+ "safe_id": sid,
937
+ "status": "failed",
938
+ "error": str(e)[:500],
939
+ "retrieved_at": now_iso(),
940
+ })
941
+ append_failed({"id": sr, "error": str(e)[:1000], "trace": traceback.format_exc()[-2000:]})
942
+ with stats_lock:
943
+ STATS["failed"] += 1
944
+ if "no extractable text" in str(e):
945
+ STATS["empty_text"] += 1
946
+
947
+ with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as ex:
948
+ futs = [ex.submit(worker, a) for a in pending]
949
+ concurrent.futures.wait(futs)
950
+
951
+ write_summary({"listed": len(catalog), "blockers": "See logs/failed.jsonl for per-act errors."})
952
+ log.info("DONE listed=%s collected=%s failed=%s bytes=%s",
953
+ STATS["listed"], STATS["collected"], STATS["failed"], STATS["bytes"])
954
+ return 0 if STATS["failed"] == 0 else 1
955
+
956
+
957
+ if __name__ == "__main__":
958
+ sys.exit(main())
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/common.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+ # Harvested collector path injection. Do not collect from /workspace.
5
+ import os as _ipfs_os
6
+ from pathlib import Path as _ipfs_Path
7
+ _CORPORA = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_CORPORA_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_corpora")))
8
+ _SCRAPERS = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_COLLECTORS_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_collectors"))) / "shared"
9
+ _HF_TOKEN_PATH = _ipfs_Path(_ipfs_os.environ.get("HF_TOKEN_PATH", str(_ipfs_Path.home() / ".cache" / "huggingface" / "token")))
10
+
11
+ import hashlib
12
+ import html
13
+ import json
14
+ import os
15
+ import re
16
+ import tempfile
17
+ import threading
18
+ import time
19
+ import traceback
20
+ from collections import Counter
21
+ from datetime import datetime, timezone, timedelta
22
+ from html.parser import HTMLParser
23
+ from pathlib import Path
24
+ from typing import Any, Iterable, Optional
25
+ from xml.etree import ElementTree as ET
26
+
27
+ import requests
28
+ from requests.adapters import HTTPAdapter
29
+
30
+ ROOT = _CORPORA
31
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
32
+ PT = timezone(timedelta(hours=-7))
33
+ DEFAULT_UA = (
34
+ "legal-corpora-collector/1.0 "
35
+ "(research archive of official national gazettes; polite; "
36
+ "no commercial scraping; contact via local operator)"
37
+ )
38
+ INDEX_FIELDS = (
39
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
40
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
41
+ "article_count", "bytes",
42
+ )
43
+
44
+ _tls = threading.local()
45
+ _index_lock = threading.Lock()
46
+ _fail_lock = threading.Lock()
47
+ _schema = None
48
+ _schema_lock = threading.Lock()
49
+
50
+
51
+ def utcnow() -> str:
52
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
53
+
54
+
55
+ def pt_from_iso(iso: str) -> str:
56
+ try:
57
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
58
+ except Exception:
59
+ return iso
60
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
61
+
62
+
63
+ def localtag(tag: str) -> str:
64
+ return tag.rsplit("}", 1)[-1]
65
+
66
+
67
+ def slug_id(cc: str, official: str) -> str:
68
+ s = (official or "").strip()
69
+ s = s.replace("https://", "").replace("http://", "")
70
+ s = re.sub(r"[/\\]+", "__", s)
71
+ s = re.sub(r"\s+", "_", s)
72
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
73
+ s = s.strip("-._")
74
+ if not s:
75
+ s = "unknown"
76
+ s = s.lower()
77
+ if not s.startswith(cc.lower() + "-"):
78
+ s = f"{cc.lower()}-{s}"
79
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
80
+ s = "x" + s
81
+ return s[:180]
82
+
83
+
84
+ def atomic_write(path: Path, text: str) -> None:
85
+ path.parent.mkdir(parents=True, exist_ok=True)
86
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
87
+ try:
88
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
89
+ handle.write(text)
90
+ os.replace(tmp, path)
91
+ except Exception:
92
+ try:
93
+ os.unlink(tmp)
94
+ except OSError:
95
+ pass
96
+ raise
97
+
98
+
99
+ def sha256_text(s: str) -> str:
100
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
101
+
102
+
103
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
104
+ s = getattr(_tls, "session", None)
105
+ if s is None or getattr(_tls, "ua", None) != ua:
106
+ s = requests.Session()
107
+ s.headers.update({
108
+ "User-Agent": ua,
109
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
110
+ "Accept-Language": "en,*;q=0.8",
111
+ })
112
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
113
+ s.mount("https://", ad)
114
+ s.mount("http://", ad)
115
+ _tls.session = s
116
+ _tls.ua = ua
117
+ return s
118
+
119
+
120
+ def http_get(
121
+ url: str,
122
+ *,
123
+ ua: str = DEFAULT_UA,
124
+ timeout: tuple = (20, 90),
125
+ retries: int = 5,
126
+ sleep: float = 0.35,
127
+ headers: Optional[dict] = None,
128
+ params: Optional[dict] = None,
129
+ allow_empty: bool = False,
130
+ ) -> requests.Response:
131
+ last = None
132
+ hdrs = headers or {}
133
+ for attempt in range(1, retries + 1):
134
+ try:
135
+ if sleep:
136
+ time.sleep(sleep)
137
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
138
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
139
+ time.sleep(min(30, 2 ** attempt))
140
+ last = resp
141
+ continue
142
+ if resp.status_code == 200 and (allow_empty or resp.content):
143
+ return resp
144
+ if resp.status_code in (404, 410, 403, 401):
145
+ return resp
146
+ last = resp
147
+ if attempt < retries:
148
+ time.sleep(min(20, 1.5 * attempt))
149
+ continue
150
+ return resp
151
+ except requests.RequestException as exc:
152
+ last = exc
153
+ time.sleep(min(20, 1.5 * attempt))
154
+ if isinstance(last, requests.Response):
155
+ return last
156
+ raise RuntimeError(f"GET failed {url}: {last}")
157
+
158
+
159
+ class _HTMLText(HTMLParser):
160
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
161
+
162
+ def __init__(self) -> None:
163
+ super().__init__(convert_charrefs=True)
164
+ self.parts: list[str] = []
165
+ self.skip = 0
166
+ self._block = {
167
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
168
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
169
+ }
170
+
171
+ def handle_starttag(self, tag, attrs):
172
+ if tag in self.SKIP:
173
+ self.skip += 1
174
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_endtag(self, tag):
178
+ if tag in self.SKIP and self.skip:
179
+ self.skip -= 1
180
+ if tag in self._block and self.skip == 0:
181
+ self.parts.append("\n")
182
+
183
+ def handle_data(self, data):
184
+ if self.skip == 0:
185
+ self.parts.append(data)
186
+
187
+
188
+ def html_to_text(raw: str) -> str:
189
+ if not raw:
190
+ return ""
191
+ p = _HTMLText()
192
+ try:
193
+ p.feed(raw)
194
+ p.close()
195
+ except Exception:
196
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
197
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
198
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
199
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
200
+ text = "".join(p.parts)
201
+ text = html.unescape(text)
202
+ text = text.replace("\xa0", " ")
203
+ text = re.sub(r"[ \t]+", " ", text)
204
+ text = re.sub(r"\n[ \t]+", "\n", text)
205
+ text = re.sub(r"\n{3,}", "\n\n", text)
206
+ return text.strip()
207
+
208
+
209
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
210
+ skip_tags = skip_tags or {
211
+ "meta", "identification", "references", "classification",
212
+ "workflow", "analysis", "proprietary", "presentation",
213
+ }
214
+ try:
215
+ root = ET.fromstring(raw)
216
+ except ET.ParseError:
217
+ return html_to_text(raw)
218
+ parts: list[str] = []
219
+
220
+ def walk(el: ET.Element) -> None:
221
+ tag = localtag(el.tag).lower()
222
+ if tag in skip_tags:
223
+ return
224
+ if el.text and el.text.strip():
225
+ parts.append(el.text.strip())
226
+ for child in list(el):
227
+ walk(child)
228
+ if child.tail and child.tail.strip():
229
+ parts.append(child.tail.strip())
230
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
231
+ parts.append("\n")
232
+
233
+ walk(root)
234
+ text = " ".join(parts)
235
+ text = re.sub(r"[ \t]+", " ", text)
236
+ text = re.sub(r" *\n *", "\n", text)
237
+ text = re.sub(r"\n{3,}", "\n\n", text)
238
+ return text.strip()
239
+
240
+
241
+ ARTICLE_SPLIT = re.compile(
242
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
243
+ r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"
244
+ r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"
245
+ r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b"
246
+ )
247
+
248
+
249
+
250
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
251
+ if not text or len(text) < 40:
252
+ return []
253
+ matches = list(ARTICLE_SPLIT.finditer(text))
254
+ if len(matches) < 2:
255
+ return []
256
+ docs = []
257
+ for i, m in enumerate(matches):
258
+ start = m.start()
259
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
260
+ chunk = text[start:end].strip()
261
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
262
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
263
+ heading = chunk.split("\n", 1)[0][:200]
264
+ docs.append({
265
+ "id": f"{law_id}-{aid}"[:180],
266
+ "title": heading,
267
+ "text": chunk,
268
+ "date_filed": date,
269
+ "document_number": num,
270
+ "source_url": source_url,
271
+ "record_type": "article",
272
+ "article_number": num,
273
+ "law_identifier": law_id,
274
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
275
+ })
276
+ if len(docs) >= 4000:
277
+ break
278
+ return docs
279
+
280
+
281
+ def load_schema():
282
+ global _schema
283
+ with _schema_lock:
284
+ if _schema is None:
285
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
286
+ _schema = json.load(f)
287
+ return _schema
288
+
289
+
290
+ def validate_record(record: dict) -> Optional[str]:
291
+ try:
292
+ import jsonschema
293
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
294
+ return None
295
+ except Exception as exc:
296
+ return str(exc)
297
+
298
+
299
+ def existing_ids(cc: str) -> set[str]:
300
+ d = ROOT / cc / "instruments"
301
+ if not d.exists():
302
+ return set()
303
+ return {p.stem for p in d.glob("*.json")}
304
+
305
+
306
+ def _quality_reject(cc: str, record: dict):
307
+ """env-gated quality filter (QUALITY_FILTER=1; module via QUALITY_FILTER_MODULE, default tip+29q). Fail-open on errors."""
308
+ if os.environ.get("QUALITY_FILTER") != "1":
309
+ return None
310
+ try:
311
+ import sys as _sys
312
+ _lp = "{_SCRAPERS.parent}/logs"
313
+ if _lp not in _sys.path:
314
+ _sys.path.append(_lp)
315
+ import importlib as _il
316
+ _qf = _il.import_module(os.environ.get("QUALITY_FILTER_MODULE", "quality_filter_tip30a"))
317
+ return _qf.classify_new(cc, record, None) # classify + exact-duplicate vs tip+29p LIVE baseline
318
+ except Exception:
319
+ return None
320
+
321
+
322
+ # tip+29t WRITE-ONCE SAFETY: a closer must NEVER overwrite/modify an existing instrument file (baseline text or title).
323
+ # Active for the tip-pipeline CCs always (and for any CC when WRITE_ONCE=1). If the target exists, the record is written
324
+ # under a NEW unique id (<id>-wN) instead; the quality filter then judges the new row (dup_url/dup_content -> quarantine).
325
+ _WRITE_ONCE_CCS = {"bo", "az", "al", "ao", "do", "et", "ir", "mw", "zm", "la", "lk", "tn", "rs"}
326
+ _WRITE_ONCE_LOG = "{_SCRAPERS.parent}/logs/write_once_guard.log"
327
+
328
+
329
+ def _write_once_ident(cc: str, ident: str) -> str:
330
+ if cc not in _WRITE_ONCE_CCS and os.environ.get("WRITE_ONCE") != "1":
331
+ return ident
332
+ idir = ROOT / cc / "instruments"
333
+ if not (idir / f"{ident}.json").exists():
334
+ return ident
335
+ n = 2
336
+ while (idir / f"{ident}-w{n}.json").exists():
337
+ n += 1
338
+ new_ident = f"{ident}-w{n}"
339
+ try:
340
+ with open(_WRITE_ONCE_LOG, "a", encoding="utf-8") as _fh:
341
+ _fh.write(json.dumps({"ts": utcnow(), "cc": cc, "refused_overwrite": ident, "written_as": new_ident,
342
+ "argv": " ".join(__import__("sys").argv)[:200]}, ensure_ascii=False) + "\n")
343
+ except Exception:
344
+ pass
345
+ return new_ident
346
+
347
+
348
+ def write_instrument(cc: str, record: dict) -> Path:
349
+ ident = _write_once_ident(cc, record["id"])
350
+ if ident != record["id"]:
351
+ record = dict(record, id=ident)
352
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
353
+ if dest.exists(): # hard guard (race): never overwrite
354
+ return dest
355
+ _qr = _quality_reject(cc, record)
356
+ if _qr and not dest.exists():
357
+ qdest = ROOT / cc / os.environ.get("QUALITY_QDIR", "quarantine_quality_tip29q") / f"{ident}.json"
358
+ qdest.parent.mkdir(parents=True, exist_ok=True)
359
+ atomic_write(qdest, json.dumps(record, ensure_ascii=False, indent=2) + "\n")
360
+ try:
361
+ with open(os.environ.get("QUALITY_REJECT_LOG", "{_SCRAPERS.parent}/logs/quality_reject_tip29q.log"), "a", encoding="utf-8") as _fh:
362
+ _fh.write(json.dumps({"cc": cc, "id": ident, "reason": _qr, "url": record.get("source_url")}, ensure_ascii=False) + "\n")
363
+ except Exception:
364
+ pass
365
+ return qdest
366
+ if _qr:
367
+ return dest
368
+ dest.parent.mkdir(parents=True, exist_ok=True)
369
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
370
+ atomic_write(dest, body)
371
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
372
+ index_line["path"] = f"instruments/{ident}.json"
373
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
374
+ index_line["bytes"] = dest.stat().st_size
375
+ index_line["id"] = ident
376
+ with _index_lock:
377
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
378
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
379
+ return dest
380
+
381
+
382
+ def log_failure(cc: str, payload: dict) -> None:
383
+ path = ROOT / cc / "failures.jsonl"
384
+ path.parent.mkdir(parents=True, exist_ok=True)
385
+ payload = dict(payload)
386
+ payload.setdefault("retrieved_at", utcnow())
387
+ with _fail_lock:
388
+ with path.open("a", encoding="utf-8") as handle:
389
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
390
+
391
+
392
+ def append_catalog(cc: str, row: dict) -> None:
393
+ path = ROOT / cc / "raw" / "catalog.jsonl"
394
+ path.parent.mkdir(parents=True, exist_ok=True)
395
+ with _index_lock:
396
+ with path.open("a", encoding="utf-8") as handle:
397
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
398
+
399
+
400
+ def law_status_hist(cc: str) -> Counter:
401
+ c: Counter = Counter()
402
+ d = ROOT / cc / "instruments"
403
+ if not d.exists():
404
+ return c
405
+ for p in d.glob("*.json"):
406
+ try:
407
+ rec = json.loads(p.read_text(encoding="utf-8"))
408
+ c[rec.get("law_status") or "unknown"] += 1
409
+ except Exception:
410
+ c["unknown"] += 1
411
+ return c
412
+
413
+
414
+ def corpus_bytes(cc: str) -> int:
415
+ d = ROOT / cc / "instruments"
416
+ if not d.exists():
417
+ return 0
418
+ return sum(p.stat().st_size for p in d.glob("*.json"))
419
+
420
+
421
+ def count_jsonl(path: Path) -> int:
422
+ if not path.exists():
423
+ return 0
424
+ n = 0
425
+ with path.open(encoding="utf-8") as f:
426
+ for _ in f:
427
+ n += 1
428
+ return n
429
+
430
+
431
+ def write_summary(
432
+ cc: str,
433
+ *,
434
+ country: str,
435
+ source: str,
436
+ source_urls: Iterable[str],
437
+ license_text: str,
438
+ discovered: int,
439
+ fetched: int,
440
+ skipped: int,
441
+ failed: int,
442
+ coverage: str,
443
+ notes: str,
444
+ last_run: Optional[str] = None,
445
+ extra: Optional[str] = None,
446
+ ) -> None:
447
+ last_run = last_run or utcnow()
448
+ instr = ROOT / cc / "instruments"
449
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
450
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
451
+ hist = law_status_hist(cc)
452
+ nbytes = corpus_bytes(cc)
453
+ lines = [
454
+ f"# {country} legislation corpus",
455
+ "",
456
+ f"- jurisdiction: {cc.upper()}",
457
+ f"- source: {source}",
458
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
459
+ f"- instruments_json: {n_json}",
460
+ f"- index_jsonl_lines: {n_index}",
461
+ f"- discovered: {discovered}",
462
+ f"- fetched: {fetched}",
463
+ f"- skipped: {skipped}",
464
+ f"- failed: {failed}",
465
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
466
+ f"- coverage: {coverage}",
467
+ f"- total_json_bytes: {nbytes}",
468
+ f"- license: {license_text}",
469
+ "- source_urls:",
470
+ ]
471
+ for u in source_urls:
472
+ lines.append(f" - {u}")
473
+ lines.append("- notes:")
474
+ for n in (notes or "").splitlines():
475
+ lines.append(f" {n}")
476
+ if extra:
477
+ lines.append("")
478
+ lines.append(extra)
479
+ lines.append("")
480
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
481
+
482
+
483
+ def base_record(
484
+ *,
485
+ cc: str,
486
+ country: str,
487
+ language: str,
488
+ ident: str,
489
+ title: str,
490
+ text: str,
491
+ source_url: str,
492
+ source_type: str,
493
+ license_text: str,
494
+ collector: str,
495
+ eli: Optional[str] = None,
496
+ date: Optional[str] = None,
497
+ official_identifier: Optional[str] = None,
498
+ document_type: str = "statute",
499
+ law_status: str = "current",
500
+ is_current: Optional[bool] = True,
501
+ documents: Optional[list] = None,
502
+ extra_meta: Optional[dict] = None,
503
+ extra_fields: Optional[dict] = None,
504
+ ) -> dict:
505
+ rid = slug_id(cc, ident)
506
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
507
+ rec = {
508
+ "schema_version": "collection_record.v1",
509
+ "record_type": "law",
510
+ "id": rid,
511
+ "title": title or ident,
512
+ "text": text or "",
513
+ "source_url": source_url,
514
+ "source_type": source_type,
515
+ "date": date,
516
+ "jurisdiction": cc.upper(),
517
+ "country": country,
518
+ "language": language,
519
+ "eli": eli,
520
+ "license": license_text,
521
+ "retrieved_at": utcnow(),
522
+ "identifier": official_identifier or ident,
523
+ "official_identifier": official_identifier or ident,
524
+ "law_identifier": official_identifier or ident,
525
+ "document_type": document_type,
526
+ "law_status": law_status,
527
+ "is_current": is_current,
528
+ "canonical_law_url": source_url,
529
+ "article_count": len(docs),
530
+ "article_extraction_status": "ok" if docs else "missing",
531
+ "documents": docs,
532
+ "metadata": {
533
+ "collector": collector,
534
+ "schema": "collection_record.v1",
535
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
536
+ "content_sha256": sha256_text(text or ""),
537
+ "rights": {
538
+ "not_legal_advice": True,
539
+ "official_reuse_url": source_url,
540
+ "license": license_text,
541
+ },
542
+ "text_extraction": {"source": "official", "backend": "collector"},
543
+ },
544
+ }
545
+ if extra_meta:
546
+ rec["metadata"].update(extra_meta)
547
+ if extra_fields:
548
+ rec.update(extra_fields)
549
+ return rec
550
+
551
+
552
+ def ensure_dirs(cc: str) -> Path:
553
+ root = ROOT / cc
554
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
555
+ (root / "raw").mkdir(parents=True, exist_ok=True)
556
+ (root / "logs").mkdir(parents=True, exist_ok=True)
557
+ return root
558
+
559
+
560
+ def iso_date(val: Optional[str]) -> Optional[str]:
561
+ if not val:
562
+ return None
563
+ val = str(val).strip()
564
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
565
+ if m:
566
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
567
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
568
+ if m:
569
+ return m.group(1)
570
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
571
+ if m:
572
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
573
+ return None
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/pdf_extract_lib.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "af": [
296
+ ("mada_mid", re.compile(
297
+ r"(?im)((?:Article|Art\.?|المادة|ماد[هۀٔة]|مادة)\s*[-–—:..]?\s*"
298
+ r"(?:واحده|\(?\s*[0-9۰-۹٠-٩]{1,4}\s*\)?|"
299
+ r"اولی?|اوله|دوم|دوهمه?|سومم?|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|"
300
+ r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم))"
301
+ ), "article"),
302
+ ("mada_line", re.compile(
303
+ r"(?im)^\s*((?:Article|Art\.?|المادة|ماد[هۀٔة]|مادة)\s*[0-9۰-۹٠-٩]+)"
304
+ ), "article"),
305
+ ],
306
+ "ir": [
307
+ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"),
308
+ ("mada_prefixed", re.compile(
309
+ r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)"
310
+ ), "article"),
311
+ ("fasl_bab", re.compile(
312
+ r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))"
313
+ ), "section"),
314
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
315
+ ],
316
+ "mz": [
317
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
318
+ ],
319
+ }
320
+
321
+
322
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
323
+ if cc in ("tn", "iq", "ir", "af", "dz", "lb", "ma", "eg", "sa", "ae"):
324
+ text_n = normalize_rtl_text(text)
325
+ else:
326
+ text_n = text
327
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
328
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
329
+ if docs:
330
+ return docs, name
331
+ # shared fallback
332
+ from common import split_articles
333
+ docs = split_articles(text_n, law_id, source_url)
334
+ if len(docs) >= 2:
335
+ return docs, "common_article_split"
336
+ return [], "none"
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_lib.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Normalize bidi + eastern digits so Arabic/Persian article markers match
109
+ try:
110
+ from pdf_extract_lib import normalize_rtl_text
111
+ work = normalize_rtl_text(text or "")
112
+ except Exception:
113
+ work = text or ""
114
+ matches = list(pattern.finditer(work))
115
+ if len(matches) < 2:
116
+ return docs if len(docs) >= 2 else []
117
+ out = []
118
+ for i, m in enumerate(matches):
119
+ start = m.start()
120
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(work)
121
+ chunk = work[start:end].strip()
122
+ if len(chunk) < 20:
123
+ continue
124
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
125
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F\u0600-\u06FF-]+", "-", num.lower()).strip("-")[:80]
126
+ heading = chunk.split("\n", 1)[0][:200]
127
+ out.append({
128
+ "id": f"{law_id}-{aid}"[:180],
129
+ "title": heading,
130
+ "text": chunk,
131
+ "date_filed": date,
132
+ "document_number": num,
133
+ "source_url": source_url,
134
+ "record_type": "article",
135
+ "article_number": num,
136
+ "law_identifier": law_id,
137
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
138
+ })
139
+ if len(out) >= 4000:
140
+ break
141
+ return out if len(out) >= 2 else docs
142
+
143
+
144
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (12, 25), verify: bool = True, retries: int = 2):
145
+ import requests
146
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
147
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
148
+ last = None
149
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
150
+ for attempt in range(1, retries + 1):
151
+ try:
152
+ time.sleep(0.2)
153
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
154
+ return resp
155
+ except Exception as exc:
156
+ last = exc
157
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
158
+ try:
159
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
160
+ return resp
161
+ except Exception as exc2:
162
+ last = exc2
163
+ time.sleep(min(8, 1.5 * attempt))
164
+ raise RuntimeError(f"live_get failed {url}: {last}")
165
+
166
+
167
+ def fetch_official(
168
+ url: str,
169
+ *,
170
+ ua: str = DEFAULT_UA,
171
+ verify: bool = True,
172
+ wayback: bool = True,
173
+ wayback_ts: Optional[str] = None,
174
+ min_text: int = MIN_TEXT,
175
+ ) -> dict:
176
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
177
+ out = {
178
+ "status": "error",
179
+ "text": "",
180
+ "content": b"",
181
+ "source_url": url,
182
+ "method": "",
183
+ "content_type": "",
184
+ "error": "",
185
+ }
186
+ body = b""
187
+ ctype = ""
188
+ skip_live = os.environ.get("SKIP_LIVE", "0") not in ("0", "false", "False", "")
189
+ try:
190
+ if skip_live:
191
+ raise RuntimeError("skip_live")
192
+ r = live_get(url, ua=ua, verify=verify)
193
+ body = r.content or b""
194
+ ctype = r.headers.get("content-type") or ""
195
+ if r.status_code == 200 and body:
196
+ is_pdf = (
197
+ body[:4] == b"%PDF"
198
+ or (0 <= body.find(b"%PDF") <= 64)
199
+ or "pdf" in ctype.lower()
200
+ )
201
+ if is_pdf:
202
+ text = pdf_to_text(body)
203
+ if len(text) >= min_text:
204
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
205
+ return out
206
+ text = ""
207
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
208
+ raw = body.decode(r.encoding or "utf-8", "replace")
209
+ if af.is_challenge(raw, r.status_code):
210
+ out["error"] = "challenge_or_shell"
211
+ else:
212
+ text = html_to_text(raw) if "<" in raw[:500] else raw
213
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
214
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
215
+ return out
216
+ if len(text) < min_text:
217
+ out["error"] = "short_or_spa"
218
+ elif body[:4] == b"%PDF" or (0 <= body.find(b"%PDF") <= 64):
219
+ # Keep bytes so callers (OCR) can work without a second download
220
+ pdf_body = body if body[:4] == b"%PDF" else body[body.find(b"%PDF"):]
221
+ out["error"] = "pdf_extract_failed"
222
+ out["content"] = pdf_body
223
+ out["content_type"] = ctype or "application/pdf"
224
+ elif len(body) > min_text:
225
+ try:
226
+ text = body.decode("utf-8", "replace")
227
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
228
+ out["error"] = "raw_pdf_bytes"
229
+ elif len(text) >= min_text:
230
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
231
+ return out
232
+ except Exception:
233
+ pass
234
+ else:
235
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
236
+ except Exception as exc:
237
+ out["error"] = f"live:{exc}"
238
+
239
+ if wayback:
240
+ try:
241
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
242
+ if w.get("status") == "success":
243
+ raw_b = w.get("content") or b""
244
+ raw_t = w.get("text") or ""
245
+ pdf_bytes = b""
246
+ if isinstance(raw_b, (bytes, bytearray)) and raw_b:
247
+ if raw_b[:4] == b"%PDF":
248
+ pdf_bytes = bytes(raw_b)
249
+ else:
250
+ _idx = raw_b.find(b"%PDF", 0, 8192)
251
+ if _idx >= 0:
252
+ pdf_bytes = bytes(raw_b[_idx:])
253
+ if not pdf_bytes and raw_t:
254
+ enc = raw_t.encode("latin-1", "replace")
255
+ if enc[:4] == b"%PDF":
256
+ pdf_bytes = enc
257
+ else:
258
+ _idx = enc.find(b"%PDF", 0, 8192)
259
+ if _idx >= 0:
260
+ pdf_bytes = enc[_idx:]
261
+ if pdf_bytes or (isinstance(raw_b, bytes) and (w.get("content_type") or "").lower().find("pdf") >= 0):
262
+ if not pdf_bytes and isinstance(raw_b, bytes):
263
+ pdf_bytes = raw_b
264
+ text = pdf_to_text(pdf_bytes)
265
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
266
+ out.update(
267
+ status="success",
268
+ text=text,
269
+ content=pdf_bytes,
270
+ method="wayback_pdf",
271
+ source_url=w.get("wayback_url") or w.get("url") or url,
272
+ content_type="application/pdf",
273
+ )
274
+ return out
275
+ # Keep PDF bytes so callers (OCR) can work without a second download
276
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
277
+ out["content"] = pdf_bytes
278
+ out["content_type"] = "application/pdf"
279
+ out["source_url"] = w.get("wayback_url") or w.get("url") or url
280
+ return out
281
+ if not raw_t and isinstance(raw_b, bytes):
282
+ raw_t = raw_b.decode("utf-8", "replace")
283
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:400] or "startxref" in raw_t[:800]:
284
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
285
+ return out
286
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
287
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
288
+ out.update(
289
+ status="success",
290
+ text=text,
291
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
292
+ method="wayback_html",
293
+ source_url=w.get("url") or url,
294
+ content_type=w.get("content_type") or "text/html",
295
+ )
296
+ return out
297
+ out["error"] = (out.get("error") or "") + ";wayback_short"
298
+ else:
299
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
300
+ except Exception as exc:
301
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
302
+ return out
303
+
304
+
305
+
306
+ def best_cdx_pdf_timestamp(url: str) -> Optional[str]:
307
+ """Pick a CDX snapshot timestamp that looks like a real PDF (status 200)."""
308
+ try:
309
+ # Prefer exact URL match via prefix of the path
310
+ from urllib.parse import urlsplit
311
+ parts = urlsplit(url)
312
+ host = (parts.hostname or "").replace("www.", "")
313
+ path = parts.path or "/"
314
+ # try a few URL variants
315
+ candidates = []
316
+ for u in (url, url.replace("https://", "http://"), url.replace("http://", "https://")):
317
+ u2 = u.replace(":80/", "/")
318
+ for h in cdx_urls(u2, limit=20, match_type="exact"):
319
+ candidates.append(h)
320
+ # also prefix on host+path
321
+ prefix = f"{host}{path}".lstrip("/")
322
+ if prefix:
323
+ for h in cdx_urls(prefix, limit=30, match_type="prefix",
324
+ extra_filters=["mimetype:application/pdf"]):
325
+ candidates.append(h)
326
+ for h in cdx_urls("www." + prefix, limit=30, match_type="prefix",
327
+ extra_filters=["mimetype:application/pdf"]):
328
+ candidates.append(h)
329
+ best = None
330
+ for h in candidates:
331
+ ts = h.get("timestamp") or ""
332
+ sc = str(h.get("statuscode") or h.get("status") or "")
333
+ mt = (h.get("mimetype") or "").lower()
334
+ orig = (h.get("original") or "").lower()
335
+ if not ts:
336
+ continue
337
+ if sc and sc not in ("200", "226", "-"):
338
+ continue
339
+ score = 0
340
+ if "pdf" in mt or orig.endswith(".pdf"):
341
+ score += 2
342
+ if sc == "200":
343
+ score += 1
344
+ if best is None or score > best[0] or (score == best[0] and ts > best[1]):
345
+ best = (score, ts)
346
+ return best[1] if best else None
347
+ except Exception as exc:
348
+ log.info("best_cdx_pdf_timestamp fail %s: %s", url[:80], exc)
349
+ return None
350
+
351
+
352
+ def fetch_official_prefer_pdf(
353
+ url: str,
354
+ *,
355
+ ua: str = DEFAULT_UA,
356
+ verify: bool = True,
357
+ min_text: int = MIN_TEXT,
358
+ wayback_ts: Optional[str] = None,
359
+ ) -> dict:
360
+ """Live first; on failure, Wayback with CDX PDF timestamp when available."""
361
+ got = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=wayback_ts, min_text=min_text)
362
+ if got.get("status") == "success" and not (got.get("text") or "").lstrip().startswith("%PDF"):
363
+ # reject obvious HTML shells mistaken for success when URL is a PDF
364
+ if url.lower().endswith(".pdf") and got.get("method") == "wayback_html":
365
+ pass # try timestamped below
366
+ else:
367
+ return got
368
+ ts = wayback_ts or best_cdx_pdf_timestamp(url)
369
+ if ts:
370
+ got2 = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
371
+ if got2.get("status") == "success":
372
+ return got2
373
+ # try http variant with same ts
374
+ alt = url.replace("https://", "http://") if url.startswith("https://") else url.replace("http://", "https://")
375
+ got3 = fetch_official(alt, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
376
+ if got3.get("status") == "success":
377
+ return got3
378
+ return got
379
+
380
+ def first_title(text: str, fallback: str) -> str:
381
+ for line in (text or "").splitlines():
382
+ s = line.strip()
383
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
384
+ return s[:240]
385
+ return fallback[:240]
386
+
387
+
388
+ def save_instrument(
389
+ *,
390
+ cc: str,
391
+ country: str,
392
+ language: str,
393
+ ident: str,
394
+ title: str,
395
+ text: str,
396
+ source_url: str,
397
+ source_type: str,
398
+ license_text: str,
399
+ collector: str,
400
+ date: Optional[str] = None,
401
+ article_re: Optional[re.Pattern] = None,
402
+ extra_meta: Optional[dict] = None,
403
+ ) -> bool:
404
+ if not text or len(text) < MIN_TEXT:
405
+ return False
406
+ rid = slug_id(cc, ident)
407
+ docs = split_custom(text, rid, source_url, date, article_re)
408
+ rec = base_record(
409
+ cc=cc,
410
+ country=country,
411
+ language=language,
412
+ ident=ident,
413
+ title=title or first_title(text, ident),
414
+ text=text,
415
+ source_url=source_url,
416
+ source_type=source_type,
417
+ license_text=license_text,
418
+ collector=collector,
419
+ date=iso_date(date) or date,
420
+ documents=docs,
421
+ extra_meta=extra_meta,
422
+ )
423
+ _dest = write_instrument(cc, rec)
424
+ # tip+30u fix (executor 06:4x PT Oct 2): a quality-filter reject returns the quarantine path -> report False so MAX_NEW counts only real saves
425
+ return bool(_dest) and Path(_dest).parent.name == "instruments" and Path(_dest).exists()
426
+
427
+
428
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
429
+ try:
430
+ hits = af.search_wayback_machine(
431
+ host_or_url,
432
+ limit=limit,
433
+ match_type=match_type,
434
+ collapse="urlkey",
435
+ extra_filters=extra_filters,
436
+ )
437
+ except Exception as exc:
438
+ log.info("cdx err %s: %s", host_or_url, exc)
439
+ return []
440
+ return hits or []
441
+
442
+
443
+ def env_int(name: str, default: int) -> int:
444
+ try:
445
+ return int(os.environ.get(name, str(default)) or default)
446
+ except Exception:
447
+ return default
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_package.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Package instruments -> parquet + README and upload ipfs_<slug>_laws datasets."""
3
+ from __future__ import annotations
4
+ # Harvested collector path injection. Do not collect from /workspace.
5
+ import os as _ipfs_os
6
+ from pathlib import Path as _ipfs_Path
7
+ _CORPORA = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_CORPORA_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_corpora")))
8
+ _SCRAPERS = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_COLLECTORS_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_collectors"))) / "shared"
9
+ _HF_TOKEN_PATH = _ipfs_Path(_ipfs_os.environ.get("HF_TOKEN_PATH", str(_ipfs_Path.home() / ".cache" / "huggingface" / "token")))
10
+ import json, shutil, sys
11
+ from datetime import datetime, timezone, timedelta
12
+ from pathlib import Path
13
+
14
+ import pandas as pd
15
+ from huggingface_hub import HfApi
16
+
17
+ ROOT = _CORPORA
18
+ SCRAPERS = _SCRAPERS
19
+ PT = timezone(timedelta(hours=-7))
20
+
21
+ META = {
22
+ "am": ("endomorphosis/ipfs_armenia_laws", "Armenia", "hy", "ARLIS (arlis.am)", "scrapers/collect_am.py", "am-arlis"),
23
+ "al": ("endomorphosis/ipfs_albania_laws", "Albania", "sq", "QPZ/QBZ Fletorja Zyrtare PDFs", "scrapers/collect_al.py", "al-qbz-fletore"),
24
+ "ba": ("endomorphosis/ipfs_bosnia_laws", "Bosnia and Herzegovina", "bs", "Sluzbeni list BiH PdfDownload", "scrapers/collect_ba.py", "ba-sluzbeni-list"),
25
+ "mk": ("endomorphosis/ipfs_northmacedonia_laws", "North Macedonia", "mk", "Sluzben vesnik", "scrapers/collect_mk.py", "mk-slvesnik"),
26
+ "me": ("endomorphosis/ipfs_montenegro_laws", "Montenegro", "sr", "Sluzbeni list Crne Gore", "scrapers/collect_me.py", "me-sluzbeni-list"),
27
+ "md": ("endomorphosis/ipfs_moldova_laws", "Moldova", "ro", "legis.md State Register", "scrapers/collect_md.py", "md-legis"),
28
+ "ge": ("endomorphosis/ipfs_georgia_laws", "Georgia", "ka", "matsne.gov.ge PDF download", "scrapers/collect_ge.py", "ge-matsne-pdf"),
29
+ "ec": ("endomorphosis/ipfs_ecuador_laws", "Ecuador", "es", "gob.ec / Registro Oficial", "scrapers/collect_ec.py", "ec-registro-oficial"),
30
+ "bo": ("endomorphosis/ipfs_bolivia_laws", "Bolivia", "es", "Gaceta Oficial de Bolivia", "scrapers/collect_bo.py", "bo-gaceta-oficial"),
31
+ "py": ("endomorphosis/ipfs_paraguay_laws", "Paraguay", "es", "BACN leyes paraguayas", "scrapers/collect_py.py", "py-bacn"),
32
+ "pa": ("endomorphosis/ipfs_panama_laws", "Panama", "es", "Gaceta Oficial de Panama", "scrapers/collect_pa.py", "pa-gaceta-oficial"),
33
+ "dz": ("endomorphosis/ipfs_algeria_laws", "Algeria", "fr", "JORADP Journal Officiel", "scrapers/collect_dz.py", "dz-joradp"),
34
+ "tn": ("endomorphosis/ipfs_tunisia_laws", "Tunisia", "ar", "IORT Journal Officiel", "scrapers/collect_tn.py", "tn-iort"),
35
+ "gh": ("endomorphosis/ipfs_ghana_laws", "Ghana", "en", "Parliament of Ghana / ir.parliament.gh", "scrapers/collect_gh.py", "ghana-official"),
36
+ "et": ("endomorphosis/ipfs_ethiopia_laws", "Ethiopia", "am", "Federal Negarit Gazette", "scrapers/collect_et.py", "et-negarit"),
37
+ "tz": ("endomorphosis/ipfs_tanzania_laws", "Tanzania", "en", "OAG MIS Acts PDFs", "scrapers/collect_tz.py", "tz-oagmis"),
38
+ "rs": ("endomorphosis/ipfs_serbia_laws", "Serbia", "sr", "PIS + parlament.gov.rs zakoni PDFs", "scrapers/collect_rs.py", "rs-pis-parlament"),
39
+ "is": ("endomorphosis/ipfs_iceland_laws", "Iceland", "is", "Althingi Lagasafn", "scrapers/collect_is.py", "is-althingi-lagasafn"),
40
+ "xk": ("endomorphosis/ipfs_kosovo_laws", "Kosovo", "sq", "Gazeta Zyrtare GZK", "scrapers/collect_xk.py", "xk-gzk"),
41
+ "uz": ("endomorphosis/ipfs_uzbekistan_laws", "Uzbekistan", "uz", "lex.uz National Database", "scrapers/collect_uz.py", "uz-lex"),
42
+ "rw": ("endomorphosis/ipfs_rwanda_laws", "Rwanda", "en", "MINIJUST Official Gazette", "scrapers/collect_rw.py", "rw-minijust-og"),
43
+ "by": ("endomorphosis/ipfs_belarus_laws", "Belarus", "ru", "pravo.by National Legal Portal", "scrapers/collect_by.py", "by-pravo"),
44
+ "mn": ("endomorphosis/ipfs_mongolia_laws", "Mongolia", "mn", "legalinfo.mn", "scrapers/collect_mn.py", "mn-legalinfo"),
45
+ "np": ("endomorphosis/ipfs_nepal_laws", "Nepal", "ne", "Nepal Law Commission", "scrapers/collect_np.py", "np-lawcommission"),
46
+ "jm": ("endomorphosis/ipfs_jamaica_laws", "Jamaica", "en", "MOJ Jamaica / Parliament", "scrapers/collect_jm.py", "jm-moj"),
47
+ "ug": ("endomorphosis/ipfs_uganda_laws", "Uganda", "en", "Parliament of Uganda", "scrapers/collect_ug.py", "ug-parliament"),
48
+ "sn": ("endomorphosis/ipfs_senegal_laws", "Senegal", "fr", "Journal Officiel du Senegal", "scrapers/collect_sn.py", "sn-jo"),
49
+ "cm": ("endomorphosis/ipfs_cameroon_laws", "Cameroon", "fr", "Présidence / Primature Cameroun (prc.cm / spm.gov.cm)", "scrapers/collect_cm.py", "cm-prc-spm"),
50
+ "mz": ("endomorphosis/ipfs_mozambique_laws", "Mozambique", "pt", "Boletim da República / MIREME / Parlamento", "scrapers/collect_mz.py", "mz-boletim-mireme"),
51
+ "ao": ("endomorphosis/ipfs_angola_laws", "Angola", "pt", "Diario da Republica / GUE / Portal do Governo", "scrapers/collect_ao.py", "ao-diario-republica"),
52
+ "az": ("endomorphosis/ipfs_azerbaijan_laws", "Azerbaijan", "az", "e-qanun.az downloadDetailPdf", "scrapers/collect_az.py", "az-eqanun"),
53
+ "do": ("endomorphosis/ipfs_dominicanrepublic_laws", "Dominican Republic", "es", "Consultoria Juridica / consultoria.gov.do", "scrapers/collect_do.py", "do-consultoria"),
54
+ "fj": ("endomorphosis/ipfs_fiji_laws", "Fiji", "en", "laws.gov.fj LawsAsMade", "scrapers/collect_fj.py", "fj-laws"),
55
+ "sv": ("endomorphosis/ipfs_elsalvador_laws", "El Salvador", "es", "Diario Oficial de El Salvador", "scrapers/collect_sv.py", "sv-diario-oficial"),
56
+ "gt": ("endomorphosis/ipfs_guatemala_laws", "Guatemala", "es", "Congreso de la Republica (congreso.gob.gt)", "scrapers/collect_gt.py", "gt-congreso"),
57
+ "kh": ("endomorphosis/ipfs_cambodia_laws", "Cambodia", "km", "Ministry of Justice Cambodia (moj.gov.kh)", "scrapers/collect_kh.py", "kh-moj"),
58
+ "la": ("endomorphosis/ipfs_laos_laws", "Laos", "lo", "Lao Official Gazette", "scrapers/collect_la.py", "la-official-gazette"),
59
+ "cu": ("endomorphosis/ipfs_cuba_laws", "Cuba", "es", "Gaceta Oficial de Cuba", "scrapers/collect_cu.py", "cu-gaceta-oficial"),
60
+ "ni": ("endomorphosis/ipfs_nicaragua_laws", "Nicaragua", "es", "Asamblea Nacional legislacion.asamblea.gob.ni", "scrapers/collect_ni.py", "ni-asamblea"),
61
+ "hn": ("endomorphosis/ipfs_honduras_laws", "Honduras", "es", "TSC / La Gaceta tsc.gob.hn/web/leyes", "scrapers/collect_hn.py", "hn-tsc-gaceta"),
62
+ "ve": ("endomorphosis/ipfs_venezuela_laws", "Venezuela", "es", "Gaceta Oficial gacetaoficial.gob.ve", "scrapers/collect_ve.py", "ve-gaceta-oficial"),
63
+ "tt": ("endomorphosis/ipfs_trinidad_laws", "Trinidad and Tobago", "en", "TT Parliament / laws.gov.tt", "scrapers/collect_tt.py", "tt-parliament-laws"),
64
+ "bn": ("endomorphosis/ipfs_brunei_laws", "Brunei", "en", "AGC Laws of Brunei", "scrapers/collect_bn.py", "bn-agc-laws"),
65
+ "pg": ("endomorphosis/ipfs_papuanewguinea_laws", "Papua New Guinea", "en", "PNG Parliament uploads/acts", "scrapers/collect_pg.py", "pg-parliament-acts"),
66
+ "iq": ("endomorphosis/ipfs_iraq_laws", "Iraq", "ar", "Ministry of Justice moj.gov.iq", "scrapers/collect_iq.py", "iq-moj"),
67
+ "ir": ("endomorphosis/ipfs_iran_laws", "Iran", "fa", "DOTIC dotic.ir", "scrapers/collect_ir.py", "ir-dotic"),
68
+ "lk": ("endomorphosis/ipfs_srilanka_laws", "Sri Lanka", "en", "documents.gov.lk / parliament.lk", "scrapers/collect_lk.py", "lk-documents-gov"),
69
+ "lb": ("endomorphosis/ipfs_lebanon_laws", "Lebanon", "ar", "JO pcm.gov.lb Official Gazette", "scrapers/collect_lb.py", "lb-jo-pcm"),
70
+ "zw": ("endomorphosis/ipfs_zimbabwe_laws", "Zimbabwe", "en", "Parliament of Zimbabwe (parlzim.gov.zw)", "scrapers/collect_zw.py", "zw-parliament-acts"),
71
+ "na": ("endomorphosis/ipfs_namibia_laws", "Namibia", "en", "Parliament of Namibia / laws.parliament.na / Bank of Namibia", "scrapers/collect_na.py", "na-parliament-bon"),
72
+ "bw": ("endomorphosis/ipfs_botswana_laws", "Botswana", "en", "gov.bw / Parliament / BURS / statutory agencies", "scrapers/collect_bw.py", "bw-gov-parliament-burs"),
73
+ }
74
+
75
+ LAW_COLS = [
76
+ "id", "title", "text", "source_url", "source_type", "jurisdiction", "country",
77
+ "language", "eli", "date", "date_issued", "retrieved_at", "license", "law_status",
78
+ "identifier", "official_identifier", "article_count", "json_path", "metadata_json",
79
+ ]
80
+ ART_COLS = [
81
+ "law_id", "id", "title", "text", "source_url", "document_number",
82
+ "article_number", "record_type", "metadata_json",
83
+ ]
84
+
85
+
86
+ def token() -> str:
87
+ return _HF_TOKEN_PATH.read_text().strip()
88
+
89
+
90
+ def instruments_to_frames(cc: str):
91
+ instr = ROOT / cc / "instruments"
92
+ laws, arts = [], []
93
+ if not instr.exists():
94
+ return pd.DataFrame(columns=LAW_COLS), pd.DataFrame(columns=ART_COLS)
95
+ for p in sorted(instr.glob("*.json")):
96
+ try:
97
+ rec = json.loads(p.read_text(encoding="utf-8"))
98
+ except Exception:
99
+ continue
100
+ text = rec.get("text") or ""
101
+ min_txt = int(__import__("os").environ.get("MIN_PACKAGE_TEXT", "80"))
102
+ if len(text) < min_txt:
103
+ continue
104
+ meta = rec.get("metadata") or {}
105
+ laws.append({
106
+ "id": rec.get("id"),
107
+ "title": rec.get("title"),
108
+ "text": text,
109
+ "source_url": rec.get("source_url"),
110
+ "source_type": rec.get("source_type"),
111
+ "jurisdiction": rec.get("jurisdiction"),
112
+ "country": rec.get("country"),
113
+ "language": rec.get("language"),
114
+ "eli": rec.get("eli"),
115
+ "date": rec.get("date"),
116
+ "date_issued": rec.get("date"),
117
+ "retrieved_at": rec.get("retrieved_at"),
118
+ "license": rec.get("license"),
119
+ "law_status": rec.get("law_status"),
120
+ "identifier": rec.get("identifier"),
121
+ "official_identifier": rec.get("official_identifier"),
122
+ "article_count": rec.get("article_count") or len(rec.get("documents") or []),
123
+ "json_path": f"instruments/{p.name}",
124
+ "metadata_json": json.dumps(meta, ensure_ascii=False),
125
+ })
126
+ for d in rec.get("documents") or []:
127
+ arts.append({
128
+ "law_id": rec.get("id"),
129
+ "id": d.get("id"),
130
+ "title": d.get("title"),
131
+ "text": d.get("text") or "",
132
+ "source_url": d.get("source_url") or rec.get("source_url"),
133
+ "document_number": d.get("document_number"),
134
+ "article_number": d.get("article_number"),
135
+ "record_type": d.get("record_type") or "article",
136
+ "metadata_json": json.dumps(d.get("metadata") or {}, ensure_ascii=False),
137
+ })
138
+ return pd.DataFrame(laws, columns=LAW_COLS), pd.DataFrame(arts, columns=ART_COLS)
139
+
140
+
141
+ def write_readme(cc: str, out: Path, n_laws: int, n_arts: int, notes: str) -> None:
142
+ repo, country, lang, source, collector, lic = META[cc]
143
+ pretty = f"Laws of {country}"
144
+ size = (
145
+ "n<1K" if n_laws < 1000 else
146
+ "1K<n<10K" if n_laws < 10000 else
147
+ "10K<n<100K" if n_laws < 100000 else
148
+ "100K<n<1M"
149
+ )
150
+ today = datetime.now(PT).strftime("%Y-%m-%d")
151
+ body = f"""---
152
+ pretty_name: {pretty}
153
+ license: other
154
+ license_name: {lic}
155
+ language:
156
+ - {lang}
157
+ task_categories:
158
+ - text-retrieval
159
+ tags:
160
+ - legal
161
+ - law
162
+ - {country.lower().replace(' ', '-')}
163
+ - official-texts
164
+ size_categories:
165
+ - {size}
166
+ configs:
167
+ - config_name: laws
168
+ data_files: data/laws.parquet
169
+ default: true
170
+ - config_name: articles
171
+ data_files: data/articles.parquet
172
+ ---
173
+
174
+ # {pretty}
175
+
176
+ Research snapshot of official legislation collected from **{source}**.
177
+
178
+ **Not legal advice.** Official gazettes / government portals prevail over this corpus.
179
+
180
+ ## Snapshot
181
+
182
+ | Field | Value |
183
+ | --- | --- |
184
+ | Snapshot date | {today} |
185
+ | Coverage | catalog-backed incomplete |
186
+ | Source | {source} |
187
+ | Collector | `{collector}` |
188
+ | Laws / instruments | {n_laws} |
189
+ | Articles | {n_arts} |
190
+ | Language | {lang} |
191
+ | Jurisdiction | {country} |
192
+ | License | `{lic}` |
193
+
194
+ ## Contents
195
+
196
+ - `data/laws.parquet` — one row per instrument (id, title, full text, dates, status, identifiers, article count, source URL).
197
+ - `data/articles.parquet` — one row per article/section (`law_id`, article number, title, text, source URL).
198
+ - `{collector}` — research collector used to build this snapshot.
199
+ - `scrapers/common.py` — shared collector helpers.
200
+ - `scrapers/world_lib.py` — shared fetch (live official URL, Wayback fallback).
201
+ - `scrapers/archive_fallbacks.py` — Wayback / Common Crawl CDX helpers.
202
+
203
+ ## License / reuse
204
+
205
+ Official government / gazette texts; reuse per public-sector terms of the
206
+ source portal. This packaging, metadata, and collector script are provided
207
+ for research.
208
+
209
+ This dataset is **not** an official consolidation and is **not legal advice**.
210
+ The official source prevails.
211
+
212
+ ## Notes
213
+
214
+ {notes}
215
+ """
216
+ out.write_text(body, encoding="utf-8")
217
+
218
+
219
+ def write_manifest(out: Path, n_laws: int, n_arts: int, files: dict) -> None:
220
+ now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
221
+ lines = ["# MANIFEST", "", f"- generated_at: {now}", f"- laws: {n_laws}", f"- articles: {n_arts}", "- files:"]
222
+ for k, v in files.items():
223
+ lines.append(f" - {k}: {v} bytes")
224
+ lines.append("")
225
+ out.write_text("\n".join(lines), encoding="utf-8")
226
+
227
+
228
+ def package(cc: str, staging: Path, notes: str) -> tuple[int, int]:
229
+ staging.mkdir(parents=True, exist_ok=True)
230
+ (staging / "data").mkdir(exist_ok=True)
231
+ (staging / "scrapers").mkdir(exist_ok=True)
232
+ ldf, adf = instruments_to_frames(cc)
233
+ if len(ldf) == 0:
234
+ raise SystemExit(f"{cc}: no laws with text>=80 to package")
235
+ lpath = staging / "data" / "laws.parquet"
236
+ apath = staging / "data" / "articles.parquet"
237
+ ldf.to_parquet(lpath, index=False)
238
+ adf.to_parquet(apath, index=False)
239
+ write_readme(cc, staging / "README.md", len(ldf), len(adf), notes)
240
+ collector = Path(META[cc][4]).name
241
+ for name in [collector, "common.py", "archive_fallbacks.py", "world_lib.py"]:
242
+ src = SCRAPERS / name
243
+ if src.exists():
244
+ shutil.copy2(src, staging / "scrapers" / name)
245
+ files = {
246
+ "data/laws.parquet": lpath.stat().st_size,
247
+ "data/articles.parquet": apath.stat().st_size,
248
+ "README.md": (staging / "README.md").stat().st_size,
249
+ }
250
+ write_manifest(staging / "MANIFEST.md", len(ldf), len(adf), files)
251
+ return len(ldf), len(adf)
252
+
253
+
254
+ def upload(cc: str, staging: Path) -> str:
255
+ repo = META[cc][0]
256
+ api = HfApi(token=token())
257
+ api.create_repo(repo_id=repo, repo_type="dataset", exist_ok=True, private=False)
258
+ api.upload_folder(
259
+ folder_path=str(staging),
260
+ repo_id=repo,
261
+ repo_type="dataset",
262
+ commit_message=f"Add/update {cc} official laws snapshot",
263
+ allow_patterns=["data/*.parquet", "README.md", "MANIFEST.md", "scrapers/*"],
264
+ )
265
+ return f"https://huggingface.co/datasets/{repo}"
266
+
267
+
268
+ if __name__ == "__main__":
269
+ cmd = sys.argv[1] if len(sys.argv) > 1 else "help"
270
+ if cmd == "package":
271
+ cc = sys.argv[2]
272
+ notes = sys.argv[3] if len(sys.argv) > 3 else "Partial official scrape. Not legal advice."
273
+ staging = _SCRAPERS.parent / f"staging_{cc}"
274
+ n_l, n_a = package(cc, staging, notes)
275
+ print(f"packaged {cc}: laws={n_l} arts={n_a} -> {staging}")
276
+ elif cmd == "upload":
277
+ cc = sys.argv[2]
278
+ staging = _SCRAPERS.parent / f"staging_{cc}"
279
+ url = upload(cc, staging)
280
+ print("uploaded", url)
281
+ elif cmd == "package-upload":
282
+ cc = sys.argv[2]
283
+ notes = sys.argv[3] if len(sys.argv) > 3 else "Partial official scrape. Not legal advice."
284
+ staging = _SCRAPERS.parent / f"staging_{cc}"
285
+ n_l, n_a = package(cc, staging, notes)
286
+ url = upload(cc, staging)
287
+ print(f"{cc}: laws={n_l} arts={n_a} {url}")
288
+ else:
289
+ print("usage: package|upload|package-upload <cc> [notes]")
scrapers_and_normalizers/scripts/normalize_offline.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Offline normalize/structure job (NO network). Streaming gz line-by-line, resumes by chunk, atomic outputs, sources never touched.
3
+ nl : scan/*.jsonl.gz + rescan_bom/*.jsonl.gz -> normalized/nl_municipal/<chunk>.jsonl.gz (dedupe by id; rescan_bom record wins over scan stub;
4
+ real record wins over manifest_parse_fail/stop stubs). Output = normalized index record (id, status, jur, dates, creator, rtype, counts).
5
+ cz : t2/index/laws_shards/*.jsonl.gz (+t1 shards) -> normalized/cz_sbirkapp/<shard>.jsonl.gz (NFC text, whitespace-collapsed, sha256 of text, article stats; dedupe by law id)
6
+ Run: MALLOC_ARENA_MAX=2 nice -n 19 ionice -c3 python normalize_offline.py {nl|cz} [--limit N] [--out DIR]
7
+ Guards: refuses to start if MemAvail < 3584; self-checks RSS every 500 lines (cap 200MB -> exit 4, resumable); pauses if MemAvail < 3584; STOP file normalized/STOP_NORM.
8
+ """
9
+ import os, sys, gzip, json, glob, hashlib, unicodedata, re, time, resource
10
+ R='/workspace/legal-corpora'; OUT=f'{R}/normalized'; RSS_CAP=200
11
+ def memavail():
12
+ for l in open('/proc/meminfo'):
13
+ if l.startswith('MemAvailable'): return int(l.split()[1])//1024
14
+ def rss():
15
+ for l in open('/proc/self/status'):
16
+ if l.startswith('VmRSS'): return int(l.split()[1])//1024
17
+ def gate(n):
18
+ if os.path.exists(f'{OUT}/STOP_NORM'): print('STOP_NORM present; exiting clean'); sys.exit(0)
19
+ if n%500==0:
20
+ if rss()>RSS_CAP: print('RSS cap exceeded',rss()); sys.exit(4)
21
+ t=time.time()
22
+ while memavail()<3584:
23
+ if os.path.exists(f'{OUT}/STOP_NORM') or time.time()-t>900: print('mem pause exit'); sys.exit(5)
24
+ time.sleep(5)
25
+ def aw(path, lines):
26
+ tmp=path+'.tmp'
27
+ with gzip.open(tmp,'wt',encoding='utf-8',compresslevel=6) as f:
28
+ for l in lines: f.write(l)
29
+ os.replace(tmp,path)
30
+ RANK={'ok':5,'in_force_no_text_in_xml':4,'expired':3,'future_only':3,'in_force_out_of_scope':3,'absent':2}
31
+ def nl_norm(d):
32
+ s=d.get('s')
33
+ o=dict(id=d['id'],status=s)
34
+ for k in ('creator','scheme','jur','auth','atype','rtype','rubriek','inw','uit','n_article','n_annex','n_section','oper_chars','title'):
35
+ if d.get(k) is not None: o[k]=d[k]
36
+ if d.get('rescan'): o['rescan']=d['rescan']
37
+ return o
38
+ def run_nl(limit,out):
39
+ out=out or f'{OUT}/nl_municipal'; os.makedirs(out,exist_ok=True)
40
+ chunks={}
41
+ for sub in ('scan','rescan_bom'):
42
+ for f in glob.glob(f'{R}/nl_municipal/index/{sub}/*.jsonl.gz'):
43
+ chunks.setdefault(os.path.basename(f),[]).append((sub,f))
44
+ done=0; n=0
45
+ for name in sorted(chunks, reverse=True):
46
+ dst=f'{out}/{name}'
47
+ # resume by chunk: skip if output newer than all sources
48
+ if os.path.exists(dst) and os.path.getmtime(dst)>=max(os.path.getmtime(f) for _,f in chunks[name]): continue
49
+ recs={}
50
+ for sub,f in chunks[name]:
51
+ try:
52
+ with gzip.open(f,'rt',encoding='utf-8-sig') as fh:
53
+ for l in fh:
54
+ n+=1; gate(n)
55
+ try: d=json.loads(l.lstrip('\ufeff'))
56
+ except Exception: continue
57
+ i=d.get('id');
58
+ if i is None: continue
59
+ r=(RANK.get(d.get('s'),1), 1 if sub=='rescan_bom' else 0)
60
+ if i not in recs or r>=recs[i][0]: recs[i]=(r,nl_norm(d))
61
+ except (EOFError,OSError) as e: print('skip unreadable',f,e)
62
+ aw(dst,(json.dumps(v[1],ensure_ascii=False,separators=(',',':'))+'\n' for _,v in sorted(recs.items(),reverse=True)))
63
+ done+=1
64
+ if limit and done>=limit: break
65
+ print('nl chunks written',done,'lines',n,'peak_rss_mb',resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024)
66
+ WS=re.compile(r'[ \t\u00a0]+'); NL3=re.compile(r'\n{3,}')
67
+ def clean(t):
68
+ if not isinstance(t,str): return t
69
+ t=unicodedata.normalize('NFC',t).replace('\r\n','\n').replace('\r','\n'); t=WS.sub(' ',t)
70
+ return NL3.sub('\n\n',t).strip()
71
+ def run_cz(limit,out):
72
+ out=out or f'{OUT}/cz_sbirkapp'; os.makedirs(out,exist_ok=True)
73
+ seen=set(); done=0; n=0
74
+ files=sorted(glob.glob(f'{R}/cz_sbirkapp/t2/index/laws_shards/*.jsonl.gz')+glob.glob(f'{R}/cz_sbirkapp/t1/index/laws_shards/*.jsonl.gz'))
75
+ for f in files:
76
+ dst=f'{out}/{os.path.basename(f)}'
77
+ # ids from already-normalized shards still feed the dedupe set (streamed ids only)
78
+ if os.path.exists(dst) and os.path.getmtime(dst)>=os.path.getmtime(f):
79
+ with gzip.open(dst,'rt',encoding='utf-8') as fh:
80
+ for l in fh:
81
+ try: seen.add(json.loads(l)['law']['id'])
82
+ except Exception: pass
83
+ continue
84
+ tmp=dst+'.tmp'
85
+ with gzip.open(f,'rt',encoding='utf-8') as fh, gzip.open(tmp,'wt',encoding='utf-8',compresslevel=6) as oh:
86
+ for l in fh:
87
+ n+=1; gate(n)
88
+ try: d=json.loads(l)
89
+ except Exception: continue
90
+ law=d.get('law') or {}; lid=law.get('id')
91
+ if lid in seen: continue
92
+ seen.add(lid)
93
+ law['text']=clean(law.get('text')); law['text_sha256']=hashlib.sha256((law['text'] or '').encode()).hexdigest()
94
+ arts=d.get('articles') or []
95
+ for a in arts: a['text']=clean(a.get('text'))
96
+ law['article_count_norm']=len(arts); law['text_chars']=len(law['text'] or '')
97
+ oh.write(json.dumps(dict(law=law,articles=arts),ensure_ascii=False,separators=(',',':'))+'\n')
98
+ os.replace(tmp,dst); done+=1
99
+ if limit and done>=limit: break
100
+ print('cz shards written',done,'lines',n,'peak_rss_mb',resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024)
101
+ if __name__=='__main__':
102
+ a=sys.argv; lim=int(a[a.index('--limit')+1]) if '--limit' in a else 0; out=a[a.index('--out')+1] if '--out' in a else None
103
+ if memavail()<3584: print('REFUSED MemAvail low'); sys.exit(3)
104
+ {'nl':run_nl,'cz':run_cz}[a[1]](lim,out)
scrapers_and_normalizers/scripts/pa_exit_guard.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """pa_exit_guard - safe process exit for scripts that read parquet with pyarrow in /workspace/venv (pandas 3.0.6, numpy 2.5.3, pyarrow 25.0.1, Python 3.13.5).
3
+
4
+ Problem: after pq.read_table() (which lazily imports pandas), normal interpreter shutdown can abort in a C++ destructor with
5
+ 'terminate called without an active exception' (SIGABRT, exit 134) although all work has finished. Measured 2026-10-06: it is a shutdown
6
+ race - most runs abort even after the Table was freed; `del` + gc.collect() lowers the rate but does not remove it; os._exit() after
7
+ flushing removes it. So: release objects (safe part) AND leave through os._exit with the REAL exit code (this module).
8
+
9
+ Entrypoint (function-style script):
10
+ import pa_exit_guard as EG
11
+ if __name__ == '__main__': EG.run_guarded(main) # or EG.run_guarded(fn, arg1, ...)
12
+ Module-level script (no main()): `pa_exit_guard.install()` near the top, `pa_exit_guard.finish(0)` as the last line.
13
+ Build/verify/push functions: close writers, `del` Tables / ParquetFile objects / readers / writers, then `release()` (gc.collect()).
14
+
15
+ Exit code = what the interpreter would have used:
16
+ return None, sys.exit(), sys.exit(None) -> 0
17
+ return <int>, sys.exit(<int>) -> that int (other return values are ignored -> 0, as Python ignores them)
18
+ sys.exit('message') -> message printed to stderr, 1
19
+ uncaught exception -> traceback printed to stderr, 1 (KeyboardInterrupt: traceback, 130)
20
+ Before os._exit: non-daemon threads are joined and atexit handlers run (as in a normal shutdown), still-open writable file objects are
21
+ flushed, logging handlers and the given log files are closed, stdout/stderr are flushed (stdout flush failure on success -> 120, as Python).
22
+ Never hard-codes 0.
23
+ """
24
+ import atexit, gc, io, logging, os, sys, threading, traceback
25
+
26
+ __all__ = ['release', 'run_guarded', 'finish', 'install', 'exit_code_of']
27
+
28
+
29
+ def release(*objs):
30
+ """close() every given object that has a close() (pass writers first: ParquetWriter, then ParquetFile/readers/file handles), then gc.collect().
31
+ A failing close() of a writer is a real failure and is NOT swallowed. The caller must still `del` its own names."""
32
+ for o in objs:
33
+ c = getattr(o, 'close', None)
34
+ if callable(c):
35
+ c()
36
+ del objs
37
+ gc.collect()
38
+
39
+
40
+ def exit_code_of(code):
41
+ """SystemExit.code -> process exit status, same rules as CPython (non-int: printed to stderr, status 1)."""
42
+ if code is None:
43
+ return 0
44
+ if isinstance(code, int):
45
+ return int(code) if -2 ** 31 <= code < 2 ** 31 else 1
46
+ try:
47
+ print(code, file=sys.stderr, flush=True)
48
+ except Exception:
49
+ pass
50
+ return 1
51
+
52
+
53
+ def _flush_open_files():
54
+ """flush still-open writable file objects (a normal shutdown would flush them while finalizing; os._exit does not). Returns failures."""
55
+ bad = []
56
+ skip = {id(sys.stdout), id(sys.stderr), id(sys.__stdout__), id(sys.__stderr__)}
57
+ for o in gc.get_objects():
58
+ try:
59
+ if isinstance(o, io.IOBase) and id(o) not in skip and not o.closed and o.writable():
60
+ o.flush()
61
+ except ValueError:
62
+ pass # closed in the meantime / detached
63
+ except Exception as e:
64
+ bad.append(f'{getattr(o, "name", type(o).__name__)}: {e!r}')
65
+ return bad
66
+
67
+
68
+ def finish(code, logs=()):
69
+ """orderly end: join non-daemon threads, run atexit handlers, flush open files, close logging + the given log files, flush stdio, os._exit(code)."""
70
+ try:
71
+ me = threading.current_thread()
72
+ for t in threading.enumerate():
73
+ if t is not me and not t.daemon and t.is_alive():
74
+ t.join()
75
+ except BaseException:
76
+ traceback.print_exc()
77
+ try:
78
+ atexit._run_exitfuncs() # exceptions inside are reported by atexit itself; like Python they do not change the code
79
+ except BaseException:
80
+ traceback.print_exc()
81
+ for f in logs or ():
82
+ try:
83
+ f.flush(); f.close()
84
+ except Exception as e:
85
+ print(f'pa_exit_guard: closing log {getattr(f, "name", f)!r} failed: {e!r}', file=sys.stderr)
86
+ try:
87
+ logging.shutdown()
88
+ except Exception:
89
+ traceback.print_exc()
90
+ bad = _flush_open_files()
91
+ if bad:
92
+ print('pa_exit_guard: flush failed for ' + '; '.join(bad[:10]), file=sys.stderr)
93
+ if code == 0:
94
+ code = 1
95
+ try:
96
+ sys.stderr.flush()
97
+ except Exception:
98
+ pass
99
+ try:
100
+ sys.stdout.flush()
101
+ except Exception:
102
+ if code == 0:
103
+ code = 120 # CPython: exit status 120 when flushing stdout fails at shutdown
104
+ for s in (sys.__stdout__, sys.__stderr__):
105
+ try:
106
+ if s is not None:
107
+ s.flush()
108
+ except Exception:
109
+ pass
110
+ os._exit(code)
111
+
112
+
113
+ def run_guarded(main_fn, *args, logs=(), **kwargs):
114
+ """run main_fn(*args, **kwargs), compute the real exit code, then finish(code). Does not return."""
115
+ code = 1
116
+ try:
117
+ r = main_fn(*args, **kwargs)
118
+ code = int(r) if isinstance(r, int) and not isinstance(r, bool) else 0
119
+ except SystemExit as e:
120
+ code = exit_code_of(e.code)
121
+ except KeyboardInterrupt:
122
+ traceback.print_exc(); code = 130
123
+ except BaseException:
124
+ traceback.print_exc(); code = 1
125
+ finish(code, logs)
126
+
127
+
128
+ def _excepthook(tp, val, tb):
129
+ traceback.print_exception(tp, val, tb)
130
+ finish(130 if issubclass(tp, KeyboardInterrupt) else 1)
131
+
132
+
133
+ def install():
134
+ """for module-level scripts: an uncaught exception prints its traceback and exits 1 via finish(); end the script with finish(0)."""
135
+ sys.excepthook = _excepthook
scrapers_and_normalizers/scripts/polite_collect_lib.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared polite-collector runtime for IS B-deild and AU-SA (written 2026-10-17, same conventions as ee_t2_collect.py).
3
+ - official host only (host lock), TLS verify ON (default urllib context, never disabled), no Wayback/CDX
4
+ - robots.txt fetched at start and honoured (Allow/Disallow with * and $, longest match; Crawl-delay raises the delay); robots fetch 403/5xx => REFUSE (never assume allow); 404 => no rules
5
+ - delay floor per collector, StrictGuard memory guard (pause<3584/resume>=4200x30s/TERM<1500x10s/instant<1000/RSS 300MB), 3-strike 403/429/503 => HOLD file + stop
6
+ - transient errors retried 3x with 5/10/20s backoff; atomic 200-record chunks + fsynced append-only ledger; resume skips ledger ids; NOCHUNK3 is enforced by the guarded launcher
7
+ - never deletes anything; no network at import time"""
8
+ import os, sys, re, io, json, time, gzip, subprocess, resource, urllib.request, urllib.error, urllib.parse
9
+ sys.path.insert(0, '/workspace/scripts')
10
+ import strict_mem_guard as SG
11
+
12
+ GUARD_OVR = dict(hard_term_memavail=1500, hard_term_sustain_s=10.0, instant_term_memavail=1000, pause_memavail=3584, resume_memavail=4200, resume_hold_s=30, rss_limit_mb=300, max_pause_s=900)
13
+ class Strike(Exception): pass
14
+ class Refuse(Exception): pass
15
+ def now(): return time.strftime('%Y-%m-%dT%H:%M:%S%z')
16
+ def atomic_write(path, data):
17
+ t = str(path) + '.tmp'
18
+ with open(t, 'w') as f: f.write(data); f.flush(); os.fsync(f.fileno())
19
+ os.replace(t, str(path))
20
+
21
+ class Robots:
22
+ """RFC 9309-style: groups by user-agent. Applicable groups = '*' group AND every UA-specific group whose product token is a substring of `ua`.
23
+ MOST RESTRICTIVE applies: a path is allowed only if allowed under EVERY applicable group (longest match, tie -> allow within a group). Crawl-delay = max over applicable groups."""
24
+ def __init__(self, text, ua='*'):
25
+ self.ua = (ua or '*').lower(); groups = []; cur = None; seen_rule = False
26
+ for raw in text.splitlines():
27
+ l = raw.split('#')[0].strip()
28
+ if ':' not in l: continue
29
+ k, v = [x.strip() for x in l.split(':', 1)]; k = k.lower()
30
+ if k == 'user-agent':
31
+ if cur is None or seen_rule: cur = dict(agents=[], rules=[], delay=0.0); groups.append(cur); seen_rule = False
32
+ cur['agents'].append(v.lower())
33
+ elif cur is None: continue
34
+ elif k in ('disallow', 'allow'):
35
+ seen_rule = True
36
+ if v: cur['rules'].append((k, v))
37
+ elif k == 'crawl-delay':
38
+ seen_rule = True
39
+ try: cur['delay'] = float(v)
40
+ except ValueError: pass
41
+ def applies(g): return any(a == '*' or (a and a in self.ua) for a in g['agents'])
42
+ self.groups = [g for g in groups if applies(g)]
43
+ self.matched_agents = sorted({a for g in self.groups for a in g['agents'] if a == '*' or a in self.ua})
44
+ self.rules = [r for g in self.groups for r in g['rules']]; self.delay = max([g['delay'] for g in self.groups] + [0.0])
45
+ @staticmethod
46
+ def _rx(p):
47
+ end = p.endswith('$'); p = p[:-1] if end else p
48
+ return re.compile('^' + '.*'.join(re.escape(x) for x in p.split('*')) + ('$' if end else ''))
49
+ @classmethod
50
+ def _grp_allowed(cls, rules, path):
51
+ m = [(len(p), k == 'allow') for k, p in rules if cls._rx(p).match(path)]
52
+ if not m: return True
53
+ L = max(x[0] for x in m)
54
+ return any(a for l, a in m if l == L) # longest match wins; tie -> allow
55
+ def allowed(self, path):
56
+ return all(self._grp_allowed(g['rules'], path) for g in self.groups)
57
+
58
+ class Http:
59
+ def __init__(self, guard, host, delay_floor, delay, hold_path, ua, robots=None, extra_stop=None, log=print):
60
+ self.g = guard; self.host = host; self.delay = max(delay_floor, float(delay)); self.floor = delay_floor; self.hold = hold_path; self.ua = ua
61
+ self.robots = robots; self.extra_stop = extra_stop; self.log = log; self.last = 0.0; self.strikes = 0; self.n = 0; self.codes = {}; self.times = []
62
+ def set_robots(self, r):
63
+ self.robots = r
64
+ if r and r.delay: self.delay = max(self.delay, r.delay)
65
+ def _wait(self):
66
+ while True:
67
+ self.g.check()
68
+ if self.extra_stop and os.path.exists(self.extra_stop): raise SG.Stopped('extra stopfile')
69
+ r = self.last + self.delay - time.time()
70
+ if r <= 0: return
71
+ time.sleep(min(r, 0.5))
72
+ def req(self, url, accept='*/*', robots_exempt=False):
73
+ u = urllib.parse.urlsplit(url)
74
+ if u.scheme != 'https' or u.hostname != self.host: raise Refuse('host/scheme lock: ' + url)
75
+ if self.robots and not robots_exempt and not self.robots.allowed(u.path + ('?' + u.query if u.query else '')):
76
+ return 'ROBOTS_DISALLOW', b''
77
+ for att in range(4):
78
+ code, buf = self._req1(url, accept)
79
+ if not ((isinstance(code, str) and code.startswith('ERR:')) or code in (500, 502, 504)) or att == 3: return code, buf
80
+ self.log('TRANSIENT', code, url[:90], 'retry', att + 1, 'backoff', 5 * 2 ** att)
81
+ end = time.time() + 5 * 2 ** att
82
+ while time.time() < end: self.g.check(); time.sleep(0.5)
83
+ def _req1(self, url, accept):
84
+ self._wait(); t0 = time.time(); self.last = t0; code = None; buf = b''
85
+ try:
86
+ with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': self.ua, 'Accept': accept}), timeout=30) as r: # TLS verify ON (default context)
87
+ code = r.status; buf = r.read(30 * 1024 * 1024 + 1)
88
+ except urllib.error.HTTPError as e: code = e.code
89
+ except Exception as e: code = 'ERR:' + type(e).__name__
90
+ self.n += 1; self.times.append(round(time.time() - t0, 3)); self.codes[str(code)] = self.codes.get(str(code), 0) + 1
91
+ if code in (403, 429, 503):
92
+ self.strikes += 1; self.log('STRIKE', self.strikes, 'HTTP', code, url[:100])
93
+ if self.strikes >= 3:
94
+ atomic_write(self.hold, 'HOLD 3-strike %s at %s last=%s\n' % (code, now(), url)); raise Strike('3-strike HTTP %s' % code)
95
+ elif code == 200: self.strikes = 0
96
+ return code, buf
97
+
98
+ def load_robots(http, host, log):
99
+ code, buf = http.req('https://%s/robots.txt' % host, robots_exempt=True)
100
+ if code == 404: log('robots.txt 404 -> no rules'); return Robots('', http.ua)
101
+ if code != 200: raise Refuse('robots.txt fetch failed HTTP %s: refusing (never assume allow)' % code)
102
+ txt = buf.decode('utf-8', 'replace'); r = Robots(txt, http.ua); log('robots.txt loaded: %d rules (groups %s), crawl-delay %s' % (len(r.rules), r.matched_agents, r.delay)); return r, txt
103
+
104
+ def write_chunk(outdir, prefix, k, recs):
105
+ name = '%s_%04d.jsonl.gz' % (prefix, k); p = str(outdir / name); t = p + '.tmp'
106
+ with open(t, 'wb') as raw:
107
+ with gzip.GzipFile(fileobj=raw, mode='wb', compresslevel=6, mtime=0) as g:
108
+ for r in recs: g.write((json.dumps(r, ensure_ascii=False) + '\n').encode())
109
+ raw.flush(); os.fsync(raw.fileno())
110
+ os.replace(t, p); return name
111
+ def ledger_load(p):
112
+ d = {}
113
+ if p.exists():
114
+ for l in open(p, encoding='utf-8'):
115
+ try: x = json.loads(l); d[x['id']] = x
116
+ except Exception: pass
117
+ return d
118
+ def ledger_add(p, d):
119
+ with open(p, 'a', encoding='utf-8') as lf: lf.write(json.dumps(d, ensure_ascii=False) + '\n'); lf.flush(); os.fsync(lf.fileno())
120
+ def pgrep(pat):
121
+ return [l for l in subprocess.run(['pgrep', '-af', pat], capture_output=True, text=True).stdout.splitlines() if 'pgrep' not in l and str(os.getpid()) != l.split()[0] and 'python' in ' '.join(l.split()[1:3])]
122
+ def other_collectors():
123
+ pats = [r'nl_municipal_collect\.py (full|collect)', r'ee_t2_(collect|refetch)\.py (collect|--dry)', r'cz_sbirkapp_collect\.py (t1|t2|full)', r'id_bpk_collect\.py', r'(is_bdeild|is_bdise)_collect\.py (collect|--dry)', r'au_sa_collect\.py (collect|--dry)', r'de_.*collect.*\.py (collect|full)']
124
+ out = []
125
+ for p in pats: out += pgrep(p)
126
+ return out
127
+ def reexec_env(tag):
128
+ if os.environ.get('MALLOC_ARENA_MAX') != '2' or os.environ.get(tag) != '1':
129
+ os.nice(10); os.execve(sys.executable, [sys.executable, '-u'] + sys.argv, dict(os.environ, MALLOC_ARENA_MAX='2', **{tag: '1'}))
130
+
131
+ def run(spec, mode, scratch=None, want=None):
132
+ """spec: dict(label, root, prefix, host, floor, ua, discover(http,state_dir,log,want)->[items{id,...}], fetch(http,item)->(rec|None, reason), chunk_n, stop, pause, hold, memterm, cfg_path).
133
+ mode 'collect' (production dirs) | 'dry' (scratch). Returns rc."""
134
+ log = lambda *a: print(time.strftime('%Y-%m-%d %H:%M:%S'), '[' + spec['label'] + ']', *a, flush=True)
135
+ base = scratch if mode == 'dry' else spec['root']; base.mkdir(parents=True, exist_ok=True)
136
+ outdir = base / 'out'; outdir.mkdir(exist_ok=True); ledger = base / 'ledger.jsonl'; stfile = base / 'state.json'; rl = 0
137
+ cfg = SG.load_cfg(str(spec['cfg_path']), overrides=dict(GUARD_OVR, delay_s=spec['floor']), delay_floor=spec['floor'])
138
+ guard = SG.StrictGuard(cfg, stop_file=None if mode == 'dry' else str(spec['stop']), pause_file=str(spec['pause']), log=log)
139
+ def state(**kw):
140
+ s = json.load(open(stfile)) if stfile.exists() else dict(slug=spec['label'], mode=mode)
141
+ s.update(kw); s['ts'] = now(); SG.atomic_json(str(stfile), s)
142
+ http = Http(guard, spec['host'], spec['floor'], cfg['delay_s'], str(spec['hold'] if mode == 'collect' else base / 'HOLD_DRYRUN'), spec['ua'], extra_stop=str(base / 'STOP_DRYRUN') if mode == 'dry' else None, log=log)
143
+ done = ledger_load(ledger); pend = []; n_ok = n_fail = 0; chunk_n = spec.get('chunk_n', 200)
144
+ k = len([p for p in os.listdir(outdir) if p.startswith(spec['prefix']) and p.endswith('.jsonl.gz')])
145
+ guard.start_watcher(); samples = []
146
+ def flush():
147
+ nonlocal pend, k
148
+ if not pend: return
149
+ name = write_chunk(outdir, spec['prefix'], k, pend); k += 1
150
+ for r in pend: ledger_add(ledger, dict(id=r['law']['id'], status='ok', chunk=name))
151
+ log('CHUNK', name, len(pend)); pend = []
152
+ try:
153
+ state(status='RUNNING', pid=os.getpid(), started=now())
154
+ rob = load_robots(http, spec['host'], log); rob, rtxt = rob if isinstance(rob, tuple) else (rob, ''); http.set_robots(rob)
155
+ atomic_write(str(base / 'robots_live.txt'), rtxt); log('effective delay', http.delay, 's (floor', spec['floor'], ')')
156
+ items = spec['discover'](http, base, log, want)
157
+ items = [i for i in items if done.get(i['id'], {}).get('status') not in ('ok', 'skip')]
158
+ if want: items = items[:want]
159
+ log('to fetch', len(items)); state(total_todo=len(items))
160
+ for it in items:
161
+ rec, why = spec['fetch'](http, it)
162
+ if rec is None:
163
+ n_fail += 1; ledger_add(ledger, dict(id=it['id'], status='skip' if why.startswith('skip:') else 'fail', reason=why)); continue
164
+ n_ok += 1; pend.append(rec)
165
+ if mode == 'dry' and len(samples) < 3: samples.append(rec)
166
+ if len(pend) >= chunk_n: flush(); state(packed=len(done) + n_ok, last_id=it['id'])
167
+ flush(); state(status='DONE_DRYRUN' if mode == 'dry' else 'BATCH_DONE', packed=len(done) + n_ok)
168
+ except SG.MemShed as e:
169
+ atomic_write(str(spec['memterm']), 'MEMTERM %s at %s\n' % (e, now())); flush(); state(status='MEMTERM_crash_tolerant'); log('MEMTERM', e); rl = 75
170
+ except SG.Stopped as e:
171
+ flush(); state(status='STOPPED'); log('STOPPED', e)
172
+ except Strike as e:
173
+ flush(); state(status='HOLD_3STRIKE'); log('HOLD', e); rl = 76
174
+ except Refuse as e:
175
+ state(status='REFUSED'); log('REFUSE', e); rl = 3
176
+ except Exception as e:
177
+ try: flush()
178
+ except Exception: pass
179
+ state(status='CRASH_resumable'); log('CRASH', type(e).__name__, e); rl = 77
180
+ finally: guard.stop_watcher()
181
+ log('end rc', rl, 'ok', n_ok, 'fail/skip', n_fail, 'requests', http.n, http.codes, 'maxrss_mb', round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1))
182
+ if mode == 'dry':
183
+ SG.atomic_json(str(base / 'dryrun_report.json'), dict(rc=rl, ok=n_ok, fail=n_fail, requests=http.n, codes=http.codes, samples=[dict(law={k_: (v[:300] if isinstance(v, str) else v) for k_, v in s['law'].items()}, n_articles=len(s['articles']), first_article={k_: (v[:200] if isinstance(v, str) else v) for k_, v in s['articles'][0].items()} if s['articles'] else None) for s in samples]))
184
+ return rl
185
+
186
+ def common_main(spec, argv, doc):
187
+ """Shared CLI: collect (--i-have-cos-go or COS token) | --dry-run-ids N [--scratch D] | selftest | status"""
188
+ cmd = argv[0] if argv else ''
189
+ log = lambda *a: print(time.strftime('%Y-%m-%d %H:%M:%S'), '[' + spec['label'] + ']', *a, flush=True)
190
+ root = spec['root']
191
+ for p in (root, root / 'index', root / 'out', root / 'review', root / 'ref'): p.mkdir(parents=True, exist_ok=True)
192
+ if cmd == 'status': print(open(root / 'state.json').read()); return 0
193
+ if cmd == 'selftest':
194
+ SG.load_cfg(str(spec['cfg_path']), overrides=dict(GUARD_OVR, delay_s=spec['floor']), delay_floor=spec['floor'])
195
+ r = Robots('User-agent: *\nCrawl-delay: 10\nDisallow: /search\nDisallow: /*_admin\nAllow: /search/ok$'); assert r.delay == 10 and not r.allowed('/search') and not r.allowed('/x_admin') and r.allowed('/legislation') and r.allowed('/search/ok')
196
+ ua = 'Mozilla/5.0 (compatible; legal-corpus-build/1.0; polite research crawler)'; t = 'User-agent: *\nDisallow: /a\n\nUser-agent: legal-corpus-build\nDisallow: /b\nCrawl-delay: 5\n\nUser-agent: otherbot\nDisallow: /\n'
197
+ r2 = Robots(t, ua); assert not r2.allowed('/a') and not r2.allowed('/b/x') and r2.allowed('/c') and r2.delay == 5 and r2.matched_agents == ['*', 'legal-corpus-build']
198
+ r3 = Robots('User-agent: *\nAllow: /\n\nUser-agent: legal-corpus-build\nDisallow: /\n', ua); assert not r3.allowed('/x') # UA group more restrictive than *
199
+ r4 = Robots('User-agent: otherbot\nUser-agent: legal-corpus-build\nDisallow: /z\n', ua); assert not r4.allowed('/z') and r4.allowed('/y'); assert Robots('', ua).allowed('/q')
200
+ log('selftest OK (offline)'); return 0
201
+ if cmd == 'collect':
202
+ if any(p.exists() for p in (spec['stop'], spec['hold'])): log('REFUSE marker present', [p.name for p in (spec['stop'], spec['hold']) if p.exists()]); return 2
203
+ if not spec['token'].exists() and '--i-have-cos-go' not in argv: log('REFUSE: no CoS GO token', spec['token']); return 3
204
+ if pgrep(r'%s collect' % spec['script']): log('REFUSE: already running'); return 7
205
+ oc = other_collectors()
206
+ if len(oc) >= 2: log('REFUSE: max two collectors already running', oc); return 7
207
+ if os.path.exists('/workspace/legal-corpora/cz_sbirkapp/FALLBACK_ONE_COLLECTOR'): log('REFUSE: FALLBACK_ONE_COLLECTOR present'); return 2
208
+ if SG.memavail() < 4200: log('REFUSE MemAvail', SG.memavail()); return 8
209
+ reexec_env(spec['label'].upper() + '_NICED')
210
+ if spec['memterm'].exists(): spec['memterm'].rename(str(spec['memterm']) + '.prev_' + time.strftime('%Y%m%dT%H%M%S'))
211
+ return run(spec, 'collect')
212
+ if cmd == '--dry-run-ids':
213
+ n = int(argv[1]); scratch = Path_(argv[argv.index('--scratch') + 1]) if '--scratch' in argv else Path_('/workspace/scratch/%s_dryrun_%s' % (spec['label'], time.strftime('%Y%m%dT%H%M%S')))
214
+ if not 1 <= n <= 20: log('REFUSE: --dry-run-ids must be 1..20'); return 2
215
+ if str(scratch.resolve()).startswith('/workspace/legal-corpora'): log('REFUSE: scratch must be outside legal-corpora'); return 2
216
+ if len(other_collectors()) >= 2: log('REFUSE: max two collectors running'); return 7
217
+ if SG.memavail() < 4200: log('REFUSE MemAvail', SG.memavail()); return 8
218
+ reexec_env(spec['label'].upper() + '_NICED'); return run(spec, 'dry', scratch=scratch, want=n)
219
+ print(doc); return 1
220
+ from pathlib import Path as Path_