endomorphosis commited on
Commit
d3e1683
·
verified ·
1 Parent(s): c775de3

Upload folder using huggingface_hub

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # MANIFEST
2
+
3
+ - generated_at: 2026-09-05T10:46:22Z
4
+ - laws: 429
5
+ - articles: 222050
6
+ - files:
7
+ - data/laws.parquet: 275842343 bytes
8
+ - data/articles.parquet: 254940744 bytes
9
+ - README.md: 1879 bytes
README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Laws of Dominican Republic
3
+ license: other
4
+ license_name: do-consultoria
5
+ language:
6
+ - es
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - dominican-republic
13
+ - official-texts
14
+ size_categories:
15
+ - n<1K
16
+ configs:
17
+ - config_name: laws
18
+ data_files: data/laws.parquet
19
+ default: true
20
+ - config_name: articles
21
+ data_files: data/articles.parquet
22
+ ---
23
+
24
+ # Laws of Dominican Republic
25
+
26
+ Research snapshot of official legislation collected from **Consultoria Juridica / consultoria.gov.do**.
27
+
28
+ **Not legal advice.** Official gazettes / government portals prevail over this corpus.
29
+
30
+ ## Snapshot
31
+
32
+ | Field | Value |
33
+ | --- | --- |
34
+ | Snapshot date | 2026-09-05 |
35
+ | Coverage | catalog-backed incomplete |
36
+ | Source | Consultoria Juridica / consultoria.gov.do |
37
+ | Collector | `scrapers/collect_do.py` |
38
+ | Laws / instruments | 429 |
39
+ | Articles | 222050 |
40
+ | Language | es |
41
+ | Jurisdiction | Dominican Republic |
42
+ | License | `do-consultoria` |
43
+
44
+ ## Contents
45
+
46
+ - `data/laws.parquet` — one row per instrument (id, title, full text, dates, status, identifiers, article count, source URL).
47
+ - `data/articles.parquet` — one row per article/section (`law_id`, article number, title, text, source URL).
48
+ - `scrapers/collect_do.py` — research collector used to build this snapshot.
49
+ - `scrapers/common.py` — shared collector helpers.
50
+ - `scrapers/world_lib.py` — shared fetch (live official URL, Wayback fallback).
51
+ - `scrapers/archive_fallbacks.py` — Wayback / Common Crawl CDX helpers.
52
+
53
+ ## License / reuse
54
+
55
+ Official government / gazette texts; reuse per public-sector terms of the
56
+ source portal. This packaging, metadata, and collector script are provided
57
+ for research.
58
+
59
+ This dataset is **not** an official consolidation and is **not legal advice**.
60
+ The official source prevails.
61
+
62
+ ## Notes
63
+
64
+ tip+20 clear ≥429; Consultoria GetDocument+Wayback CDX + prior gacetas/leyes. Not legal advice.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a381bf11d7e4969e08767ff5149d9104afe2c2a48dc38753f9f08aeb9dd99891
3
+ size 254940744
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f38e971ab67a06b40d1cc22679622194cac755f837d908530df9a791096763a
3
+ size 275842343
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public Wayback CDX + Common Crawl CDX/WARC fetch (ipfs_datasets_py fallback intent).
3
+
4
+ Does not import the full ipfs_datasets_py package. Matches:
5
+ search_wayback_machine / get_wayback_content (wayback_machine_engine.py)
6
+ Common Crawl CDX at https://index.commoncrawl.org/
7
+ archive.is newest lookup
8
+ Brave Search is skipped when no API key is present.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import gzip
13
+ import io
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Optional
20
+ from urllib.parse import quote, urljoin, urlparse
21
+
22
+ import requests
23
+ from requests.adapters import HTTPAdapter
24
+
25
+ log = logging.getLogger("archive_fallbacks")
26
+
27
+ WAYBACK_CDX = "http://web.archive.org/cdx/search/cdx"
28
+ WAYBACK_WEB = "http://web.archive.org/web"
29
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
+ CC_DATA = "https://data.commoncrawl.org"
31
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
32
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
33
+
34
+ UA = (
35
+ "legal-corpora-collector/1.0 "
36
+ "(research archive of official national gazettes; polite; "
37
+ "contact via local operator)"
38
+ )
39
+
40
+ CHALLENGE_RE = re.compile(
41
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
42
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
43
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
44
+ r"request\s+rejected|access\s+denied",
45
+ re.I,
46
+ )
47
+ SPA_SHELL_RE = re.compile(
48
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
49
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
50
+ re.I,
51
+ )
52
+
53
+ _session: Optional[requests.Session] = None
54
+ _cc_indexes: Optional[list[str]] = None
55
+ _cc_dead: set[str] = set()
56
+ _last_wayback = 0.0
57
+ _last_cc = 0.0
58
+
59
+
60
+ def session() -> requests.Session:
61
+ global _session
62
+ if _session is None:
63
+ s = requests.Session()
64
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
65
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
66
+ s.mount("https://", ad)
67
+ s.mount("http://", ad)
68
+ _session = s
69
+ return _session
70
+
71
+
72
+ def _sleep_wayback(delay: float = 1.0) -> None:
73
+ global _last_wayback
74
+ now = time.time()
75
+ wait = delay - (now - _last_wayback)
76
+ if wait > 0:
77
+ time.sleep(wait)
78
+ _last_wayback = time.time()
79
+
80
+
81
+ def _sleep_cc(delay: float = 0.35) -> None:
82
+ global _last_cc
83
+ now = time.time()
84
+ wait = delay - (now - _last_cc)
85
+ if wait > 0:
86
+ time.sleep(wait)
87
+ _last_cc = time.time()
88
+
89
+
90
+ def has_brave_key() -> bool:
91
+ return bool(
92
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
93
+ )
94
+
95
+
96
+ def is_challenge(html: str, status: int = 200) -> bool:
97
+ if status in (401, 403, 429, 503):
98
+ return True
99
+ if not html:
100
+ return False
101
+ head = html[:8000]
102
+ if CHALLENGE_RE.search(head):
103
+ return True
104
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
105
+ return True
106
+ return False
107
+
108
+
109
+ def is_spa_shell(html: str, text: str) -> bool:
110
+ if not html:
111
+ return False
112
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
113
+ return True
114
+ return False
115
+
116
+
117
+ # --- Wayback ---
118
+
119
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
120
+
121
+
122
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
123
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
124
+ if not isinstance(data, list) or len(data) <= 1:
125
+ return [], None
126
+ resume = None
127
+ rows = data
128
+ # Trailer: ..., [], ["resumeKey"]
129
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
130
+ resume = str(data[-1][0]) if data[-1][0] else None
131
+ rows = data[:-2]
132
+ headers = rows[0] if rows else []
133
+ out: list[dict] = []
134
+ for row in rows[1:]:
135
+ if not row:
136
+ continue
137
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
138
+ if not rec and isinstance(row, list) and len(row) >= 5:
139
+ rec = {
140
+ "urlkey": row[0],
141
+ "timestamp": row[1],
142
+ "original": row[2],
143
+ "mimetype": row[3],
144
+ "statuscode": row[4],
145
+ "digest": row[5] if len(row) > 5 else "",
146
+ "length": row[6] if len(row) > 6 else "0",
147
+ }
148
+ orig = rec.get("original") or rec.get("url") or ""
149
+ ts = rec.get("timestamp") or ""
150
+ mime = rec.get("mimetype") or ""
151
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
152
+ "application/pdf",
153
+ "application/xml",
154
+ "text/xml",
155
+ "application/xhtml+xml",
156
+ "text/html",
157
+ "application/json",
158
+ ):
159
+ continue
160
+ if not orig or not ts:
161
+ continue
162
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
163
+ rec["source"] = "wayback"
164
+ out.append(rec)
165
+ return out, resume
166
+
167
+
168
+ def _wayback_cdx_page(
169
+ url: str,
170
+ *,
171
+ limit: int,
172
+ collapse: str,
173
+ filter_status: str,
174
+ from_date: Optional[str],
175
+ to_date: Optional[str],
176
+ match_type: Optional[str],
177
+ extra_filters: Optional[list[str]],
178
+ resume_key: Optional[str],
179
+ mime_prefix: Optional[str],
180
+ page_size: int,
181
+ ) -> tuple[list[dict], Optional[str]]:
182
+ items: list[tuple[str, Any]] = [
183
+ ("url", url),
184
+ ("output", "json"),
185
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
186
+ ("limit", int(page_size)),
187
+ ("showResumeKey", "true"),
188
+ ]
189
+ if collapse:
190
+ items.append(("collapse", collapse))
191
+ if from_date:
192
+ items.append(("from", from_date))
193
+ if to_date:
194
+ items.append(("to", to_date))
195
+ if match_type:
196
+ items.append(("matchType", match_type))
197
+ if filter_status:
198
+ items.append(("filter", f"statuscode:{filter_status}"))
199
+ for flt in extra_filters or []:
200
+ items.append(("filter", flt))
201
+ if resume_key:
202
+ items.append(("resumeKey", resume_key))
203
+ _sleep_wayback(1.0)
204
+ last_err = None
205
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
206
+ if attempt > 1:
207
+ items = [(k, psz if k == "limit" else v) for k, v in items]
208
+ _sleep_wayback(1.5)
209
+ try:
210
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
211
+ except requests.RequestException as exc:
212
+ last_err = exc
213
+ log.warning("wayback cdx fail %s: %s", url, exc)
214
+ continue
215
+ if r.status_code in (502, 503, 504) or not r.content:
216
+ last_err = f"http_{r.status_code}"
217
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
218
+ continue
219
+ if r.status_code != 200:
220
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
221
+ return [], None
222
+ try:
223
+ data = r.json()
224
+ except Exception:
225
+ return [], None
226
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
227
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
228
+ return [], None
229
+
230
+
231
+ def search_wayback_machine(
232
+ url: str,
233
+ *,
234
+ from_date: Optional[str] = None,
235
+ to_date: Optional[str] = None,
236
+ limit: int = 100,
237
+ collapse: str = "urlkey",
238
+ filter_status: str = "200",
239
+ match_type: Optional[str] = None,
240
+ mime_prefix: Optional[str] = None,
241
+ extra_filters: Optional[list[str]] = None,
242
+ ) -> list[dict]:
243
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
244
+ target = max(1, int(limit))
245
+ page_size = CDX_PAGE if target > CDX_PAGE else target
246
+ out: list[dict] = []
247
+ seen = set()
248
+ resume: Optional[str] = None
249
+ empty = 0
250
+ while len(out) < target:
251
+ need = min(page_size, target - len(out))
252
+ batch, resume = _wayback_cdx_page(
253
+ url,
254
+ limit=need,
255
+ collapse=collapse,
256
+ filter_status=filter_status,
257
+ from_date=from_date,
258
+ to_date=to_date,
259
+ match_type=match_type,
260
+ extra_filters=extra_filters,
261
+ resume_key=resume,
262
+ mime_prefix=mime_prefix,
263
+ page_size=need,
264
+ )
265
+ added = 0
266
+ for rec in batch:
267
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
268
+ if key in seen:
269
+ continue
270
+ seen.add(key)
271
+ out.append(rec)
272
+ added += 1
273
+ if added == 0:
274
+ empty += 1
275
+ if empty >= 2 or not resume:
276
+ break
277
+ else:
278
+ empty = 0
279
+ if not resume:
280
+ break
281
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
282
+ return out[:target]
283
+
284
+
285
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
286
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search."""
287
+ if timestamp:
288
+ wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}"
289
+ else:
290
+ wb = f"{WAYBACK_WEB}/2id_/{url}"
291
+ r = None
292
+ last_err = None
293
+ for attempt in range(1, 5):
294
+ _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt))
295
+ try:
296
+ r = session().get(wb, timeout=(20, 90), allow_redirects=True)
297
+ except requests.RequestException as exc:
298
+ last_err = str(exc)
299
+ log.info("wayback replay fail %s: %s", url, exc)
300
+ continue
301
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 4:
302
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
303
+ continue
304
+ break
305
+ if r is None:
306
+ return {"status": "error", "error": last_err or "no_response", "url": url}
307
+ cap_ts = timestamp or ""
308
+ m = re.search(r"/web/(\d{14})", r.url or "")
309
+ if m:
310
+ cap_ts = m.group(1)
311
+ ctype = r.headers.get("content-type") or ""
312
+ body = r.content or b""
313
+ text = ""
314
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
315
+ enc = r.encoding or "utf-8"
316
+ try:
317
+ text = body.decode(enc, "replace")
318
+ except Exception:
319
+ text = body.decode("utf-8", "replace")
320
+ if r.status_code != 200 or not body:
321
+ return {
322
+ "status": "error",
323
+ "error": f"http_{r.status_code}",
324
+ "http_status": r.status_code,
325
+ "wayback_url": r.url,
326
+ "original_url": url,
327
+ }
328
+ if text and is_challenge(text, r.status_code):
329
+ return {
330
+ "status": "error",
331
+ "error": "challenge_or_shell",
332
+ "http_status": r.status_code,
333
+ "wayback_url": r.url,
334
+ "original_url": url,
335
+ "content": text[:2000],
336
+ }
337
+ return {
338
+ "status": "success",
339
+ "content": body,
340
+ "text": text,
341
+ "content_type": ctype,
342
+ "wayback_url": r.url,
343
+ "capture_timestamp": cap_ts,
344
+ "original_url": url,
345
+ "http_status": r.status_code,
346
+ "method": "wayback",
347
+ }
348
+
349
+
350
+ # --- Common Crawl ---
351
+
352
+ def cc_indexes(n: int = 6) -> list[str]:
353
+ global _cc_indexes
354
+ if _cc_indexes is None:
355
+ try:
356
+ r = session().get(CC_COLLINFO, timeout=30)
357
+ cols = r.json() if r.status_code == 200 else []
358
+ ids = []
359
+ for c in cols:
360
+ cid = c.get("id") or ""
361
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
362
+ if cid:
363
+ ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index")
364
+ # collinfo is newest-first. Do not drop crawls that 404 a
365
+ # specific URL (that means "no captures", not a dead index).
366
+ _cc_indexes = ids or [
367
+ "https://index.commoncrawl.org/CC-MAIN-2025-18-index",
368
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
369
+ ]
370
+ except Exception as exc:
371
+ log.warning("cc collinfo: %s", exc)
372
+ _cc_indexes = [
373
+ "https://index.commoncrawl.org/CC-MAIN-2026-34-index",
374
+ "https://index.commoncrawl.org/CC-MAIN-2026-30-index",
375
+ "https://index.commoncrawl.org/CC-MAIN-2026-25-index",
376
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
377
+ ]
378
+ return _cc_indexes[:n]
379
+
380
+
381
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
382
+ """Query public CC CDX (https://index.commoncrawl.org/).
383
+
384
+ Do not send filter=status:200 — on some shards that returns a false
385
+ 404 "No Captures found". Filter status client-side instead.
386
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
387
+ """
388
+ out = []
389
+ seen = set()
390
+ empty = 0
391
+ for idx in (indexes or cc_indexes(12)):
392
+ if idx in _cc_dead:
393
+ continue
394
+ params = {
395
+ "url": url,
396
+ "output": "json",
397
+ "limit": str(limit),
398
+ }
399
+ _sleep_cc(0.3)
400
+ try:
401
+ r = session().get(idx, params=params, timeout=(12, 25))
402
+ except requests.RequestException as exc:
403
+ log.info("cc cdx %s fail %s", idx, exc)
404
+ continue
405
+ if r.status_code == 404:
406
+ msg = (r.text or "")[:80]
407
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
408
+ empty += 1
409
+ if empty >= 8 and not out:
410
+ continue
411
+ continue
412
+ if r.status_code in (410,):
413
+ _cc_dead.add(idx)
414
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
415
+ continue
416
+ if r.status_code != 200 or not r.content:
417
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
418
+ continue
419
+ for line in r.text.splitlines():
420
+ line = line.strip()
421
+ if not line or line[0] not in "{[":
422
+ continue
423
+ try:
424
+ rec = json.loads(line)
425
+ except Exception:
426
+ continue
427
+ orig = rec.get("url") or rec.get("original") or ""
428
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
429
+ if st and st not in ("200", "201", "206"):
430
+ continue
431
+ key = (orig, rec.get("filename"), rec.get("offset"))
432
+ if not orig or key in seen:
433
+ continue
434
+ seen.add(key)
435
+ rec["original"] = orig
436
+ rec["source"] = "common_crawl"
437
+ rec["cc_index"] = idx
438
+ out.append(rec)
439
+ if out:
440
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
441
+ if len(out) >= limit or out:
442
+ break
443
+ return out[:limit]
444
+
445
+
446
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
447
+ data = raw
448
+ if data[:2] == b"\x1f\x8b":
449
+ try:
450
+ data = gzip.decompress(data)
451
+ except Exception:
452
+ try:
453
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
454
+ except Exception:
455
+ pass
456
+ # WARC record: headers, then HTTP payload
457
+ split = data.split(b"\r\n\r\n", 1)
458
+ if len(split) < 2:
459
+ return 0, "", data
460
+ warc_headers, rest = split
461
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
462
+ http_split = rest.split(b"\r\n\r\n", 1)
463
+ http_head = http_split[0].decode("latin-1", "replace")
464
+ body = http_split[1] if len(http_split) > 1 else b""
465
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
466
+ status = int(m.group(1)) if m else 0
467
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
468
+ ctype = cm.group(1).strip() if cm else ""
469
+ return status, ctype, body
470
+ return 0, "", rest
471
+
472
+
473
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
474
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
475
+ try:
476
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
477
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
478
+ except Exception:
479
+ return {"status": "error", "error": "bad_pointer"}
480
+ if not fn or ln <= 0:
481
+ return {"status": "error", "error": "missing_pointer"}
482
+ ln = min(ln, max_bytes)
483
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
484
+ _sleep_cc(0.25)
485
+ try:
486
+ r = session().get(
487
+ url,
488
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
489
+ timeout=(20, 90),
490
+ )
491
+ except requests.RequestException as exc:
492
+ return {"status": "error", "error": str(exc)}
493
+ if r.status_code not in (200, 206) or not r.content:
494
+ return {"status": "error", "error": f"http_{r.status_code}"}
495
+ status, ctype, body = _parse_warc_http(r.content)
496
+ text = ""
497
+ if body and (
498
+ "html" in (ctype or "")
499
+ or "xml" in (ctype or "")
500
+ or "text/" in (ctype or "")
501
+ or not ctype
502
+ ):
503
+ text = body.decode("utf-8", "replace")
504
+ orig = rec.get("original") or rec.get("url") or ""
505
+ if text and is_challenge(text, status or 200):
506
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
507
+ return {
508
+ "status": "success",
509
+ "content": body,
510
+ "text": text,
511
+ "content_type": ctype,
512
+ "original_url": orig,
513
+ "http_status": status or 200,
514
+ "method": "common_crawl",
515
+ "cc_record": {
516
+ "filename": fn,
517
+ "offset": off,
518
+ "length": ln,
519
+ "timestamp": rec.get("timestamp"),
520
+ },
521
+ }
522
+
523
+
524
+ # --- archive.is ---
525
+
526
+ def get_archive_is_content(url: str) -> dict:
527
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
528
+ try:
529
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
530
+ except requests.RequestException as exc:
531
+ log.info("archive.is %s", exc)
532
+ continue
533
+ if r.status_code != 200 or not r.content:
534
+ continue
535
+ if "archive." not in (r.url or ""):
536
+ continue
537
+ text = r.text or ""
538
+ if is_challenge(text, r.status_code):
539
+ continue
540
+ return {
541
+ "status": "success",
542
+ "content": r.content,
543
+ "text": text,
544
+ "content_type": r.headers.get("content-type") or "text/html",
545
+ "archive_url": r.url,
546
+ "original_url": url,
547
+ "http_status": r.status_code,
548
+ "method": "archive_is",
549
+ }
550
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
551
+
552
+
553
+ # --- Direct HTTP last ---
554
+
555
+ def get_http(url: str) -> dict:
556
+ try:
557
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
558
+ except requests.RequestException as exc:
559
+ return {"status": "error", "error": str(exc), "original_url": url}
560
+ text = ""
561
+ ctype = r.headers.get("content-type") or ""
562
+ body = r.content or b""
563
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
564
+ text = body.decode(r.encoding or "utf-8", "replace")
565
+ if r.status_code != 200 or not body:
566
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
567
+ if text and is_challenge(text, r.status_code):
568
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
569
+ return {
570
+ "status": "success",
571
+ "content": body,
572
+ "text": text,
573
+ "content_type": ctype,
574
+ "original_url": url,
575
+ "http_status": r.status_code,
576
+ "method": "http",
577
+ "final_url": r.url,
578
+ }
579
+
580
+
581
+ def fetch_with_fallbacks(
582
+ url: str,
583
+ *,
584
+ cc_record: Optional[dict] = None,
585
+ wayback_ts: Optional[str] = None,
586
+ try_archive_is: bool = False,
587
+ try_http: bool = True,
588
+ try_cc: bool = True,
589
+ ) -> dict:
590
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
591
+
592
+ Brave Search skipped (no API key in this environment).
593
+ Playwright is attempted by the caller when this returns a SPA shell.
594
+ Does not run Wayback CDX search; Wayback is replay only.
595
+ """
596
+ errors = []
597
+ cc_recs: list[dict] = []
598
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
599
+ cc_recs = [cc_record]
600
+ elif try_cc:
601
+ try:
602
+ cc_recs = search_common_crawl(url, limit=4)
603
+ except Exception as exc:
604
+ errors.append(f"common_crawl:{exc}")
605
+ cc_recs = []
606
+ for rec in cc_recs:
607
+ res = fetch_common_crawl_warc(rec)
608
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
609
+ return res
610
+ errors.append(f"common_crawl:{res.get('error')}")
611
+ if wayback_ts or url:
612
+ res = get_wayback_content(url, timestamp=wayback_ts)
613
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
614
+ return res
615
+ errors.append(f"wayback:{res.get('error')}")
616
+ if try_archive_is:
617
+ res = get_archive_is_content(url)
618
+ if res.get("status") == "success":
619
+ return res
620
+ errors.append(f"archive_is:{res.get('error')}")
621
+ if try_http:
622
+ res = get_http(url)
623
+ if res.get("status") == "success":
624
+ return res
625
+ errors.append(f"http:{res.get('error')}")
626
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_do.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Dominican Republic: Consultoría Jurídica API + Congreso Biblioteca gacetas/leyes."""
3
+ from __future__ import annotations
4
+ import logging
5
+ import re
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+ from urllib.parse import urljoin, unquote
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
12
+ from common import existing_ids, log_failure, utcnow, write_summary
13
+ from world_lib import (
14
+ cdx_urls,
15
+ env_int,
16
+ fetch_official,
17
+ first_title,
18
+ live_get,
19
+ save_instrument,
20
+ setup_log,
21
+ slug_id,
22
+ )
23
+
24
+ CC, COUNTRY, LANG = "do", "Dominican Republic", "es"
25
+ SOURCE_TYPE = "consultoria_congreso_do"
26
+ LICENSE = (
27
+ "Consultoría Jurídica del Poder Ejecutivo (consultoria.gov.do) / "
28
+ "Biblioteca del Congreso Nacional (bibliotecadelcongreso.gob.do). "
29
+ "Official Gaceta Oficial / legal texts. Authentic government text prevails. Not legal advice."
30
+ )
31
+ UA = "legal-corpora-collector/1.0 (research; source=https://www.consultoria.gov.do/)"
32
+ ART = re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.|iculo)?|ART[IÍ]CULO)\s+[\d]+[º°o.]?)\b")
33
+ log = logging.getLogger("do")
34
+
35
+ CONSULTORIA = "https://www.consultoria.gov.do"
36
+ BIBLIO = "https://bibliotecadelcongreso.gob.do"
37
+ SKIP_CATS = {
38
+ "nominas",
39
+ "311-stats",
40
+ "satisfaccion-informes",
41
+ "servicios-carta",
42
+ }
43
+
44
+
45
+ def _ident_from_url(url: str, fallback: str) -> str:
46
+ stem = Path(unquote(url.split("?")[0])).stem
47
+ stem = re.sub(r"[^\w\-]+", "-", stem, flags=re.U).strip("-")[:140]
48
+ return stem or fallback[:140]
49
+
50
+
51
+ def discover():
52
+ items, seen = [], set()
53
+
54
+ def add(url: str, *, ident: str | None = None, title: str | None = None, prefer: bool = False, date: str | None = None):
55
+ url = (url or "").split("#")[0]
56
+ if not url.startswith("http"):
57
+ return
58
+ low = url.lower()
59
+ if ".pdf" not in low:
60
+ return
61
+ if not any(h in low for h in ("consultoria.gov.do", "bibliotecadelcongreso.gob.do")):
62
+ return
63
+ if any(low.endswith(ext) for ext in (".jpg", ".jpeg", ".png", ".gif", ".webp")):
64
+ return
65
+ key = url.lower()
66
+ if key in seen:
67
+ return
68
+ seen.add(key)
69
+ iid = ident or _ident_from_url(url, "doc")
70
+ items.append((iid, url, title, prefer, date))
71
+
72
+ # Consultoría Jurídica official /api/documents
73
+ try:
74
+ r = live_get(f"{CONSULTORIA}/api/documents", ua=UA, verify=False, retries=2, timeout=(20, 90))
75
+ if getattr(r, "status_code", 0) == 200:
76
+ docs = r.json()
77
+ if isinstance(docs, list):
78
+ log.info("consultoria documents=%s", len(docs))
79
+ for d in docs:
80
+ cat = (d.get("category") or "").lower()
81
+ if cat in SKIP_CATS:
82
+ continue
83
+ fu = d.get("fileUrl") or ""
84
+ pdfs = [p.strip() for p in fu.split("|") if p.strip().lower().endswith(".pdf")]
85
+ if not pdfs:
86
+ continue
87
+ title = (d.get("title") or "").strip()
88
+ if cat == "gacetas" and title.isdigit():
89
+ title = f"Gaceta Oficial No. {title}"
90
+ year = d.get("year")
91
+ month = d.get("month") or ""
92
+ if year and month and cat == "gacetas":
93
+ title = f"{title} ({month} {year})"
94
+ for p in pdfs:
95
+ full = urljoin(CONSULTORIA + "/", p)
96
+ add(
97
+ full,
98
+ ident=f"{cat}-{_ident_from_url(full, d.get('id') or 'doc')}",
99
+ title=title or None,
100
+ prefer=True,
101
+ date=str(year) if year else None,
102
+ )
103
+ except Exception as exc:
104
+ log.info("consultoria api documents fail: %s", exc)
105
+
106
+ # Constitutions from /api/settings
107
+ try:
108
+ r = live_get(f"{CONSULTORIA}/api/settings", ua=UA, verify=False, retries=2, timeout=(20, 90))
109
+ if getattr(r, "status_code", 0) == 200:
110
+ settings = r.json() or {}
111
+ constit = settings.get("coleccion_constituciones") or []
112
+ log.info("constitutions=%s", len(constit))
113
+ for c in constit:
114
+ url = c.get("url") or ""
115
+ if not url.lower().endswith(".pdf"):
116
+ continue
117
+ full = urljoin(CONSULTORIA + "/", url)
118
+ add(
119
+ full,
120
+ ident=f"const-{c.get('id') or _ident_from_url(full, 'const')}",
121
+ title=c.get("title") or c.get("detail") or "Constitución",
122
+ prefer=True,
123
+ )
124
+ except Exception as exc:
125
+ log.info("consultoria settings fail: %s", exc)
126
+
127
+ # Biblioteca del Congreso Nacional
128
+ for page, kind in (
129
+ (f"{BIBLIO}/gaceta.htm", "gaceta"),
130
+ (f"{BIBLIO}/leyes.htm", "leyes"),
131
+ ):
132
+ try:
133
+ r = live_get(page, ua=UA, verify=False, retries=2)
134
+ except Exception as exc:
135
+ log.info("biblio fail %s: %s", page, exc)
136
+ continue
137
+ if getattr(r, "status_code", 0) != 200:
138
+ continue
139
+ hrefs = re.findall(r'href="([^"]+\.pdf)"', r.text or "", re.I)
140
+ log.info("biblio %s pdfs=%s", kind, len(hrefs))
141
+ for href in hrefs:
142
+ full = urljoin(page, href)
143
+ prefer = False
144
+ m = re.search(r"(20\d{2})", href)
145
+ if kind == "gaceta" and m and int(m.group(1)) >= 2000:
146
+ prefer = True
147
+ title = Path(unquote(href)).stem.replace("_", " ")
148
+ if kind == "gaceta":
149
+ title = f"Gaceta Oficial {title}"
150
+ else:
151
+ title = f"Leyes decretos resoluciones {title}"
152
+ add(full, ident=_ident_from_url(full, kind), title=title, prefer=prefer)
153
+
154
+ # CDX fallback legacy consultoria PDFs
155
+ for prefix in ("www.consultoria.gov.do/", "consultoria.gov.do/"):
156
+ for h in cdx_urls(
157
+ prefix,
158
+ limit=env_int("CDX_LIMIT", 200),
159
+ match_type="prefix",
160
+ extra_filters=["mimetype:application/pdf"],
161
+ ):
162
+ orig = (h.get("original") or "").replace("http://", "https://").replace(":80/", "/")
163
+ if not orig or ".pdf" not in orig.lower():
164
+ continue
165
+ low = orig.lower()
166
+ if any(x in low for x in ("nomina", "foto", "banner", "logo", ".jpg")):
167
+ continue
168
+ add(orig, prefer=False)
169
+
170
+ def rank(item):
171
+ ident, url, title, prefer, date = item
172
+ low = url.lower()
173
+ # Prefer individual consultoria uploads / constitutions over huge yearly tomos
174
+ if "consultoria.gov.do/uploads/" in low:
175
+ tier = 0
176
+ elif "bibliotecadelcongreso.gob.do/gaceta/" in low:
177
+ tier = 2 # yearly compilations — large but official
178
+ elif "bibliotecadelcongreso.gob.do/leyes/" in low:
179
+ tier = 3
180
+ else:
181
+ tier = 1 if prefer else 4
182
+ # newer years first when present in URL
183
+ import re as _re
184
+ ys = _re.findall(r"(20\d{2})", url)
185
+ year_key = -max(int(y) for y in ys) if ys else 0
186
+ return (tier, year_key, url)
187
+
188
+ items.sort(key=rank)
189
+ out = [(i, u, t, d) for i, u, t, _, d in items]
190
+ log.info("catalog %s", len(out))
191
+ return out
192
+
193
+
194
+ def main():
195
+ setup_log(CC)
196
+ t0 = utcnow()
197
+ max_new = env_int("MAX_NEW", 80)
198
+ max_seconds = env_int("MAX_SECONDS", 3600)
199
+ min_text = env_int("MIN_TEXT", 150)
200
+ t_start = time.time()
201
+ done = existing_ids(CC)
202
+ ok = skip = fail = 0
203
+ for ident, url, title_hint, date in discover():
204
+ if max_new and ok >= max_new:
205
+ break
206
+ if time.time() - t_start > max_seconds:
207
+ break
208
+ rid = slug_id(CC, ident)
209
+ if rid in done:
210
+ skip += 1
211
+ continue
212
+ got = fetch_official(url, ua=UA, verify=False, min_text=min_text)
213
+ text = got.get("text") or ""
214
+ if got.get("status") != "success":
215
+ fail += 1
216
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")})
217
+ continue
218
+ if len(re.sub(r"\s+", "", text)) < 100:
219
+ fail += 1
220
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "thin_ocr_shell"})
221
+ continue
222
+ title = title_hint or first_title(text, ident)
223
+ if title_hint and len(title_hint) > 12:
224
+ title = title_hint
225
+ if save_instrument(
226
+ cc=CC,
227
+ country=COUNTRY,
228
+ language=LANG,
229
+ ident=ident,
230
+ title=title,
231
+ text=text,
232
+ source_url=url,
233
+ source_type=SOURCE_TYPE,
234
+ license_text=LICENSE,
235
+ collector="collect_do.py",
236
+ date=date,
237
+ article_re=ART,
238
+ extra_meta={"fetch_method": got.get("method")},
239
+ ):
240
+ ok += 1
241
+ done.add(rid)
242
+ log.info("ok %s method=%s chars=%s", ident[:70], got.get("method"), len(text))
243
+ else:
244
+ fail += 1
245
+ write_summary(
246
+ CC,
247
+ country=COUNTRY,
248
+ source="Consultoría Jurídica / Biblioteca del Congreso DO",
249
+ source_urls=[
250
+ "https://www.consultoria.gov.do/",
251
+ "https://www.consultoria.gov.do/api/documents",
252
+ "https://bibliotecadelcongreso.gob.do/gaceta.htm",
253
+ "https://bibliotecadelcongreso.gob.do/leyes.htm",
254
+ ],
255
+ license_text=LICENSE,
256
+ discovered=ok + skip + fail,
257
+ fetched=ok,
258
+ skipped=skip,
259
+ failed=fail,
260
+ coverage="catalog-backed incomplete (consultoria API gacetas + Congreso biblioteca)",
261
+ notes=(
262
+ "Official consultoria.gov.do Gaceta/uploads PDFs and Biblioteca del Congreso "
263
+ "Gaceta Oficial / leyes PDFs. Nominas and non-law categories skipped. Not legal advice."
264
+ ),
265
+ last_run=t0,
266
+ )
267
+ log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import traceback
14
+ from collections import Counter
15
+ from datetime import datetime, timezone, timedelta
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Any, Iterable, Optional
19
+ from xml.etree import ElementTree as ET
20
+
21
+ import requests
22
+ from requests.adapters import HTTPAdapter
23
+
24
+ ROOT = Path("/workspace/legal-corpora")
25
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
26
+ PT = timezone(timedelta(hours=-7))
27
+ DEFAULT_UA = (
28
+ "legal-corpora-collector/1.0 "
29
+ "(research archive of official national gazettes; polite; "
30
+ "no commercial scraping; contact via local operator)"
31
+ )
32
+ INDEX_FIELDS = (
33
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
34
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
35
+ "article_count", "bytes",
36
+ )
37
+
38
+ _tls = threading.local()
39
+ _index_lock = threading.Lock()
40
+ _fail_lock = threading.Lock()
41
+ _schema = None
42
+ _schema_lock = threading.Lock()
43
+
44
+
45
+ def utcnow() -> str:
46
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
47
+
48
+
49
+ def pt_from_iso(iso: str) -> str:
50
+ try:
51
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
52
+ except Exception:
53
+ return iso
54
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
55
+
56
+
57
+ def localtag(tag: str) -> str:
58
+ return tag.rsplit("}", 1)[-1]
59
+
60
+
61
+ def slug_id(cc: str, official: str) -> str:
62
+ s = (official or "").strip()
63
+ s = s.replace("https://", "").replace("http://", "")
64
+ s = re.sub(r"[/\\]+", "__", s)
65
+ s = re.sub(r"\s+", "_", s)
66
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
67
+ s = s.strip("-._")
68
+ if not s:
69
+ s = "unknown"
70
+ s = s.lower()
71
+ if not s.startswith(cc.lower() + "-"):
72
+ s = f"{cc.lower()}-{s}"
73
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
74
+ s = "x" + s
75
+ return s[:180]
76
+
77
+
78
+ def atomic_write(path: Path, text: str) -> None:
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
81
+ try:
82
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
83
+ handle.write(text)
84
+ os.replace(tmp, path)
85
+ except Exception:
86
+ try:
87
+ os.unlink(tmp)
88
+ except OSError:
89
+ pass
90
+ raise
91
+
92
+
93
+ def sha256_text(s: str) -> str:
94
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
95
+
96
+
97
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
98
+ s = getattr(_tls, "session", None)
99
+ if s is None or getattr(_tls, "ua", None) != ua:
100
+ s = requests.Session()
101
+ s.headers.update({
102
+ "User-Agent": ua,
103
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
104
+ "Accept-Language": "en,*;q=0.8",
105
+ })
106
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
107
+ s.mount("https://", ad)
108
+ s.mount("http://", ad)
109
+ _tls.session = s
110
+ _tls.ua = ua
111
+ return s
112
+
113
+
114
+ def http_get(
115
+ url: str,
116
+ *,
117
+ ua: str = DEFAULT_UA,
118
+ timeout: tuple = (20, 90),
119
+ retries: int = 5,
120
+ sleep: float = 0.35,
121
+ headers: Optional[dict] = None,
122
+ params: Optional[dict] = None,
123
+ allow_empty: bool = False,
124
+ ) -> requests.Response:
125
+ last = None
126
+ hdrs = headers or {}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ if sleep:
130
+ time.sleep(sleep)
131
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
132
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
133
+ time.sleep(min(30, 2 ** attempt))
134
+ last = resp
135
+ continue
136
+ if resp.status_code == 200 and (allow_empty or resp.content):
137
+ return resp
138
+ if resp.status_code in (404, 410, 403, 401):
139
+ return resp
140
+ last = resp
141
+ if attempt < retries:
142
+ time.sleep(min(20, 1.5 * attempt))
143
+ continue
144
+ return resp
145
+ except requests.RequestException as exc:
146
+ last = exc
147
+ time.sleep(min(20, 1.5 * attempt))
148
+ if isinstance(last, requests.Response):
149
+ return last
150
+ raise RuntimeError(f"GET failed {url}: {last}")
151
+
152
+
153
+ class _HTMLText(HTMLParser):
154
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
155
+
156
+ def __init__(self) -> None:
157
+ super().__init__(convert_charrefs=True)
158
+ self.parts: list[str] = []
159
+ self.skip = 0
160
+ self._block = {
161
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
162
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
163
+ }
164
+
165
+ def handle_starttag(self, tag, attrs):
166
+ if tag in self.SKIP:
167
+ self.skip += 1
168
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
169
+ self.parts.append("\n")
170
+
171
+ def handle_endtag(self, tag):
172
+ if tag in self.SKIP and self.skip:
173
+ self.skip -= 1
174
+ if tag in self._block and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_data(self, data):
178
+ if self.skip == 0:
179
+ self.parts.append(data)
180
+
181
+
182
+ def html_to_text(raw: str) -> str:
183
+ if not raw:
184
+ return ""
185
+ p = _HTMLText()
186
+ try:
187
+ p.feed(raw)
188
+ p.close()
189
+ except Exception:
190
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
191
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
192
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
193
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
194
+ text = "".join(p.parts)
195
+ text = html.unescape(text)
196
+ text = text.replace("\xa0", " ")
197
+ text = re.sub(r"[ \t]+", " ", text)
198
+ text = re.sub(r"\n[ \t]+", "\n", text)
199
+ text = re.sub(r"\n{3,}", "\n\n", text)
200
+ return text.strip()
201
+
202
+
203
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
204
+ skip_tags = skip_tags or {
205
+ "meta", "identification", "references", "classification",
206
+ "workflow", "analysis", "proprietary", "presentation",
207
+ }
208
+ try:
209
+ root = ET.fromstring(raw)
210
+ except ET.ParseError:
211
+ return html_to_text(raw)
212
+ parts: list[str] = []
213
+
214
+ def walk(el: ET.Element) -> None:
215
+ tag = localtag(el.tag).lower()
216
+ if tag in skip_tags:
217
+ return
218
+ if el.text and el.text.strip():
219
+ parts.append(el.text.strip())
220
+ for child in list(el):
221
+ walk(child)
222
+ if child.tail and child.tail.strip():
223
+ parts.append(child.tail.strip())
224
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
225
+ parts.append("\n")
226
+
227
+ walk(root)
228
+ text = " ".join(parts)
229
+ text = re.sub(r"[ \t]+", " ", text)
230
+ text = re.sub(r" *\n *", "\n", text)
231
+ text = re.sub(r"\n{3,}", "\n\n", text)
232
+ return text.strip()
233
+
234
+
235
+ ARTICLE_SPLIT = re.compile(
236
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
237
+ r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"
238
+ r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"
239
+ r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b"
240
+ )
241
+
242
+
243
+
244
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
245
+ if not text or len(text) < 40:
246
+ return []
247
+ matches = list(ARTICLE_SPLIT.finditer(text))
248
+ if len(matches) < 2:
249
+ return []
250
+ docs = []
251
+ for i, m in enumerate(matches):
252
+ start = m.start()
253
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
254
+ chunk = text[start:end].strip()
255
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
256
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
257
+ heading = chunk.split("\n", 1)[0][:200]
258
+ docs.append({
259
+ "id": f"{law_id}-{aid}"[:180],
260
+ "title": heading,
261
+ "text": chunk,
262
+ "date_filed": date,
263
+ "document_number": num,
264
+ "source_url": source_url,
265
+ "record_type": "article",
266
+ "article_number": num,
267
+ "law_identifier": law_id,
268
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
269
+ })
270
+ if len(docs) >= 4000:
271
+ break
272
+ return docs
273
+
274
+
275
+ def load_schema():
276
+ global _schema
277
+ with _schema_lock:
278
+ if _schema is None:
279
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
280
+ _schema = json.load(f)
281
+ return _schema
282
+
283
+
284
+ def validate_record(record: dict) -> Optional[str]:
285
+ try:
286
+ import jsonschema
287
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
288
+ return None
289
+ except Exception as exc:
290
+ return str(exc)
291
+
292
+
293
+ def existing_ids(cc: str) -> set[str]:
294
+ d = ROOT / cc / "instruments"
295
+ if not d.exists():
296
+ return set()
297
+ return {p.stem for p in d.glob("*.json")}
298
+
299
+
300
+ def write_instrument(cc: str, record: dict) -> Path:
301
+ ident = record["id"]
302
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
303
+ dest.parent.mkdir(parents=True, exist_ok=True)
304
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
305
+ atomic_write(dest, body)
306
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
307
+ index_line["path"] = f"instruments/{ident}.json"
308
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
309
+ index_line["bytes"] = dest.stat().st_size
310
+ index_line["id"] = ident
311
+ with _index_lock:
312
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
313
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
314
+ return dest
315
+
316
+
317
+ def log_failure(cc: str, payload: dict) -> None:
318
+ path = ROOT / cc / "failures.jsonl"
319
+ path.parent.mkdir(parents=True, exist_ok=True)
320
+ payload = dict(payload)
321
+ payload.setdefault("retrieved_at", utcnow())
322
+ with _fail_lock:
323
+ with path.open("a", encoding="utf-8") as handle:
324
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
325
+
326
+
327
+ def append_catalog(cc: str, row: dict) -> None:
328
+ path = ROOT / cc / "raw" / "catalog.jsonl"
329
+ path.parent.mkdir(parents=True, exist_ok=True)
330
+ with _index_lock:
331
+ with path.open("a", encoding="utf-8") as handle:
332
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
333
+
334
+
335
+ def law_status_hist(cc: str) -> Counter:
336
+ c: Counter = Counter()
337
+ d = ROOT / cc / "instruments"
338
+ if not d.exists():
339
+ return c
340
+ for p in d.glob("*.json"):
341
+ try:
342
+ rec = json.loads(p.read_text(encoding="utf-8"))
343
+ c[rec.get("law_status") or "unknown"] += 1
344
+ except Exception:
345
+ c["unknown"] += 1
346
+ return c
347
+
348
+
349
+ def corpus_bytes(cc: str) -> int:
350
+ d = ROOT / cc / "instruments"
351
+ if not d.exists():
352
+ return 0
353
+ return sum(p.stat().st_size for p in d.glob("*.json"))
354
+
355
+
356
+ def count_jsonl(path: Path) -> int:
357
+ if not path.exists():
358
+ return 0
359
+ n = 0
360
+ with path.open(encoding="utf-8") as f:
361
+ for _ in f:
362
+ n += 1
363
+ return n
364
+
365
+
366
+ def write_summary(
367
+ cc: str,
368
+ *,
369
+ country: str,
370
+ source: str,
371
+ source_urls: Iterable[str],
372
+ license_text: str,
373
+ discovered: int,
374
+ fetched: int,
375
+ skipped: int,
376
+ failed: int,
377
+ coverage: str,
378
+ notes: str,
379
+ last_run: Optional[str] = None,
380
+ extra: Optional[str] = None,
381
+ ) -> None:
382
+ last_run = last_run or utcnow()
383
+ instr = ROOT / cc / "instruments"
384
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
385
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
386
+ hist = law_status_hist(cc)
387
+ nbytes = corpus_bytes(cc)
388
+ lines = [
389
+ f"# {country} legislation corpus",
390
+ "",
391
+ f"- jurisdiction: {cc.upper()}",
392
+ f"- source: {source}",
393
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
394
+ f"- instruments_json: {n_json}",
395
+ f"- index_jsonl_lines: {n_index}",
396
+ f"- discovered: {discovered}",
397
+ f"- fetched: {fetched}",
398
+ f"- skipped: {skipped}",
399
+ f"- failed: {failed}",
400
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
401
+ f"- coverage: {coverage}",
402
+ f"- total_json_bytes: {nbytes}",
403
+ f"- license: {license_text}",
404
+ "- source_urls:",
405
+ ]
406
+ for u in source_urls:
407
+ lines.append(f" - {u}")
408
+ lines.append("- notes:")
409
+ for n in (notes or "").splitlines():
410
+ lines.append(f" {n}")
411
+ if extra:
412
+ lines.append("")
413
+ lines.append(extra)
414
+ lines.append("")
415
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
416
+
417
+
418
+ def base_record(
419
+ *,
420
+ cc: str,
421
+ country: str,
422
+ language: str,
423
+ ident: str,
424
+ title: str,
425
+ text: str,
426
+ source_url: str,
427
+ source_type: str,
428
+ license_text: str,
429
+ collector: str,
430
+ eli: Optional[str] = None,
431
+ date: Optional[str] = None,
432
+ official_identifier: Optional[str] = None,
433
+ document_type: str = "statute",
434
+ law_status: str = "current",
435
+ is_current: Optional[bool] = True,
436
+ documents: Optional[list] = None,
437
+ extra_meta: Optional[dict] = None,
438
+ extra_fields: Optional[dict] = None,
439
+ ) -> dict:
440
+ rid = slug_id(cc, ident)
441
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
442
+ rec = {
443
+ "schema_version": "collection_record.v1",
444
+ "record_type": "law",
445
+ "id": rid,
446
+ "title": title or ident,
447
+ "text": text or "",
448
+ "source_url": source_url,
449
+ "source_type": source_type,
450
+ "date": date,
451
+ "jurisdiction": cc.upper(),
452
+ "country": country,
453
+ "language": language,
454
+ "eli": eli,
455
+ "license": license_text,
456
+ "retrieved_at": utcnow(),
457
+ "identifier": official_identifier or ident,
458
+ "official_identifier": official_identifier or ident,
459
+ "law_identifier": official_identifier or ident,
460
+ "document_type": document_type,
461
+ "law_status": law_status,
462
+ "is_current": is_current,
463
+ "canonical_law_url": source_url,
464
+ "article_count": len(docs),
465
+ "article_extraction_status": "ok" if docs else "missing",
466
+ "documents": docs,
467
+ "metadata": {
468
+ "collector": collector,
469
+ "schema": "collection_record.v1",
470
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
471
+ "content_sha256": sha256_text(text or ""),
472
+ "rights": {
473
+ "not_legal_advice": True,
474
+ "official_reuse_url": source_url,
475
+ "license": license_text,
476
+ },
477
+ "text_extraction": {"source": "official", "backend": "collector"},
478
+ },
479
+ }
480
+ if extra_meta:
481
+ rec["metadata"].update(extra_meta)
482
+ if extra_fields:
483
+ rec.update(extra_fields)
484
+ return rec
485
+
486
+
487
+ def ensure_dirs(cc: str) -> Path:
488
+ root = ROOT / cc
489
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
490
+ (root / "raw").mkdir(parents=True, exist_ok=True)
491
+ (root / "logs").mkdir(parents=True, exist_ok=True)
492
+ return root
493
+
494
+
495
+ def iso_date(val: Optional[str]) -> Optional[str]:
496
+ if not val:
497
+ return None
498
+ val = str(val).strip()
499
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
500
+ if m:
501
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
502
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
503
+ if m:
504
+ return m.group(1)
505
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
506
+ if m:
507
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
508
+ return None
scrapers/pdf_extract_lib.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PDF text extraction helpers mirroring ipfs_datasets_py IntegratedPDFProcessor.
3
+
4
+ Prefer pdfplumber -> pymupdf -> pdftotext; OCR (tesseract) only when text layer
5
+ is missing or garbage. Honest article splits require >=2 heading matches.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import logging
11
+ import re
12
+ import subprocess
13
+ import tempfile
14
+ from typing import Optional
15
+
16
+ log = logging.getLogger("pdf_extract_lib")
17
+
18
+ # Spaced-out OCR garbage like "D IA R IO"
19
+ _GARBAGE_SPACING = re.compile(r"(?:^[A-Za-z]\s+){6,}", re.M)
20
+
21
+
22
+ def is_garbage_text(text: str) -> bool:
23
+ if not text or len(text) < 40:
24
+ return True
25
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
26
+ return True
27
+ if "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:
28
+ return True
29
+ sample = text[:8000]
30
+ # Broken ToUnicode / CID font dumps from Arabic/Persian PDFs
31
+ if sample.count("(cid:") >= 8:
32
+ return True
33
+ arabic = sum(1 for ch in sample if "\u0600" <= ch <= "\u06FF")
34
+ ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t\x0c")
35
+ n = max(1, len(sample))
36
+ # Encoding-corrupt Arabic/Persian PDFs: many controls / almost no Arabic script
37
+ if len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05:
38
+ return True
39
+ if len(sample) > 800 and arabic < 80 and sample.count("@") > 30:
40
+ return True
41
+ letters = sum(ch.isalpha() for ch in sample)
42
+ spaces = sample.count(" ")
43
+ if letters < 80 and arabic < 40:
44
+ return True
45
+ # Mojibake Latin stand-in for Arabic (common in old MoJ PDFs)
46
+ ascii_letters = sum(ch.isalpha() and ord(ch) < 128 for ch in sample)
47
+ if len(sample) > 500 and arabic < 20 and ascii_letters > 400:
48
+ return True
49
+ if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):
50
+ return True
51
+ singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))
52
+ if singles > 30 and singles > letters * 0.15:
53
+ return True
54
+ return False
55
+
56
+
57
+ def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
58
+ import pdfplumber
59
+ with pdfplumber.open(io.BytesIO(raw)) as pdf:
60
+ n = len(pdf.pages)
61
+ parts = []
62
+ for page in pdf.pages[:max_pages]:
63
+ try:
64
+ parts.append(page.extract_text() or "")
65
+ except Exception:
66
+ continue
67
+ text = "\n".join(parts)
68
+ text = re.sub(r"[ \t]+", " ", text)
69
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
70
+ return text, n
71
+
72
+
73
+ def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
74
+ import pymupdf
75
+ doc = pymupdf.open(stream=raw, filetype="pdf")
76
+ n = doc.page_count
77
+ parts = [page.get_text() for page in doc[:max_pages]]
78
+ text = "\n".join(parts)
79
+ text = re.sub(r"[ \t]+", " ", text)
80
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
81
+ return text, n
82
+
83
+
84
+ def extract_pdftotext(raw: bytes) -> str:
85
+ if not raw or raw[:4] != b"%PDF":
86
+ return ""
87
+ try:
88
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
89
+ tmp.write(raw)
90
+ tmp.flush()
91
+ proc = subprocess.run(
92
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
93
+ check=False, capture_output=True, timeout=180,
94
+ )
95
+ if proc.returncode == 0 and proc.stdout:
96
+ return proc.stdout.decode("utf-8", "replace").strip()
97
+ except Exception as exc:
98
+ log.warning("pdftotext: %s", exc)
99
+ return ""
100
+
101
+
102
+ def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]:
103
+ """Render pages with pymupdf and OCR via tesseract CLI."""
104
+ import pymupdf
105
+ doc = pymupdf.open(stream=raw, filetype="pdf")
106
+ n = doc.page_count
107
+ parts = []
108
+ mat = pymupdf.Matrix(dpi / 72, dpi / 72)
109
+ for i, page in enumerate(doc):
110
+ if i >= max_pages:
111
+ break
112
+ pix = page.get_pixmap(matrix=mat, alpha=False)
113
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img:
114
+ pix.save(img.name)
115
+ img_path = img.name
116
+ try:
117
+ env = dict(**__import__("os").environ)
118
+ env["OMP_THREAD_LIMIT"] = "1"
119
+ env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata")
120
+ proc = subprocess.run(
121
+ ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"],
122
+ capture_output=True, text=True, timeout=180, env=env,
123
+ )
124
+ if proc.returncode == 0 and proc.stdout:
125
+ parts.append(proc.stdout)
126
+ except Exception as exc:
127
+ log.debug("ocr page %s: %s", i, exc)
128
+ finally:
129
+ try:
130
+ import os
131
+ os.unlink(img_path)
132
+ except Exception:
133
+ pass
134
+ text = "\n".join(parts)
135
+ text = re.sub(r"[ \t]+", " ", text)
136
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
137
+ return text, n
138
+
139
+
140
+ def extract_pdf_text(
141
+ raw: bytes,
142
+ *,
143
+ enable_ocr: bool = True,
144
+ ocr_lang: str = "eng",
145
+ ocr_max_pages: int = 40,
146
+ ) -> tuple[str, str, int]:
147
+ """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order."""
148
+ if not raw:
149
+ return "", "not_pdf", 0
150
+ if raw[:4] != b"%PDF":
151
+ idx = raw.find(b"%PDF", 0, 65536)
152
+ if idx < 0:
153
+ return "", "not_pdf", 0
154
+ raw = raw[idx:]
155
+ best_text, best_method, pages = "", "failed", 0
156
+ for name, fn in (
157
+ ("pdfplumber", lambda: extract_pdfplumber(raw)),
158
+ ("pymupdf", lambda: extract_pymupdf(raw)),
159
+ ):
160
+ try:
161
+ text, pages = fn()
162
+ if text and not is_garbage_text(text) and len(text) >= 80:
163
+ return text, name, pages
164
+ if len(text) > len(best_text):
165
+ best_text, best_method = text, name
166
+ except Exception as exc:
167
+ log.debug("%s failed: %s", name, exc)
168
+ try:
169
+ text = extract_pdftotext(raw)
170
+ if text and not is_garbage_text(text) and len(text) >= 80:
171
+ return text, "pdftotext", pages
172
+ if len(text) > len(best_text):
173
+ best_text, best_method = text, "pdftotext"
174
+ except Exception:
175
+ pass
176
+ if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120):
177
+ try:
178
+ text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages)
179
+ if text and len(text) >= 80 and not is_garbage_text(text):
180
+ return text, "ocr_tesseract", pages
181
+ if len(text) > len(best_text):
182
+ best_text, best_method = text, "ocr_tesseract"
183
+ except Exception as exc:
184
+ log.debug("ocr failed: %s", exc)
185
+ return best_text, best_method if best_text else "failed", pages
186
+
187
+
188
+ def normalize_bidi(text: str) -> str:
189
+ return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200c\u200d\ufeff]", "", text or "")
190
+
191
+
192
+ _EASTERN_DIGITS = str.maketrans(
193
+ "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669"
194
+ "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9",
195
+ "01234567890123456789",
196
+ )
197
+
198
+
199
+ def normalize_rtl_text(text: str) -> str:
200
+ """Strip bidi marks and map Arabic/Persian digits to ASCII for heading regexes."""
201
+ t = normalize_bidi(text or "")
202
+ t = re.sub(r"[\u00ad\u200b]", "", t)
203
+ return t.translate(_EASTERN_DIGITS)
204
+
205
+
206
+
207
+ def split_by_pattern(
208
+ text: str,
209
+ law_id: str,
210
+ source_url: str,
211
+ pat: re.Pattern,
212
+ record_type: str = "article",
213
+ min_chunk: int = 40,
214
+ max_docs: int = 4000,
215
+ ) -> list[dict]:
216
+ matches = list(pat.finditer(text or ""))
217
+ if len(matches) < 2:
218
+ return []
219
+ docs = []
220
+ for i, m in enumerate(matches):
221
+ start = m.start()
222
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
223
+ chunk = text[start:end].strip()
224
+ if len(chunk) < min_chunk:
225
+ continue
226
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
227
+ aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80]
228
+ heading = chunk.split("\n", 1)[0][:200]
229
+ docs.append({
230
+ "id": f"{law_id}-{aid}"[:180],
231
+ "title": heading,
232
+ "text": chunk,
233
+ "date_filed": None,
234
+ "document_number": num,
235
+ "source_url": source_url,
236
+ "record_type": record_type,
237
+ "article_number": num,
238
+ "law_identifier": law_id,
239
+ "metadata": {
240
+ "text_extraction": {
241
+ "source": "official",
242
+ "backend": "honest_heading_split",
243
+ "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split",
244
+ "pattern": pat.pattern[:100],
245
+ }
246
+ },
247
+ })
248
+ if len(docs) >= max_docs:
249
+ break
250
+ return docs if len(docs) >= 2 else []
251
+
252
+
253
+ # Country-specific honest patterns (tried in order)
254
+ COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = {
255
+ "sv": [
256
+ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"),
257
+ ],
258
+ "tn": [
259
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"),
260
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
261
+ ],
262
+ "et": [
263
+ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"),
264
+ ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
265
+ ("article_inline", re.compile(r"(?im)((?:Article|Art\.)\s+\d+)(?![\d])"), "article"),
266
+ ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"),
267
+ ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"),
268
+ ],
269
+ "jm": [
270
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"),
271
+ ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"),
272
+ ],
273
+ "fj": [
274
+ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"),
275
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"),
276
+ ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"),
277
+ ],
278
+ "la": [
279
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"),
280
+ ],
281
+ "lk": [
282
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"),
283
+ ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"),
284
+ ],
285
+ "md": [
286
+ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"),
287
+ ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"),
288
+ ],
289
+ "iq": [
290
+ ("mada", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:]*\s*\d+)(?!\d)"), "article"),
291
+ ("mada_ocr", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:\s]*\d+)(?!\d)"), "article"),
292
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|الباب)\s+\S+)"), "section"),
293
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
294
+ ],
295
+ "ir": [
296
+ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"),
297
+ ("mada_prefixed", re.compile(
298
+ r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)"
299
+ ), "article"),
300
+ ("fasl_bab", re.compile(
301
+ r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))"
302
+ ), "section"),
303
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
304
+ ],
305
+ "mz": [
306
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
307
+ ],
308
+ }
309
+
310
+
311
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
312
+ if cc in ("tn", "iq", "ir", "dz", "lb", "ma", "eg", "sa", "ae"):
313
+ text_n = normalize_rtl_text(text)
314
+ else:
315
+ text_n = text
316
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
317
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
318
+ if docs:
319
+ return docs, name
320
+ # shared fallback
321
+ from common import split_articles
322
+ docs = split_articles(text_n, law_id, source_url)
323
+ if len(docs) >= 2:
324
+ return docs, "common_article_split"
325
+ return [], "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ write_instrument(cc, rec)
424
+ return True
425
+
426
+
427
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
428
+ try:
429
+ hits = af.search_wayback_machine(
430
+ host_or_url,
431
+ limit=limit,
432
+ match_type=match_type,
433
+ collapse="urlkey",
434
+ extra_filters=extra_filters,
435
+ )
436
+ except Exception as exc:
437
+ log.info("cdx err %s: %s", host_or_url, exc)
438
+ return []
439
+ return hits or []
440
+
441
+
442
+ def env_int(name: str, default: int) -> int:
443
+ try:
444
+ return int(os.environ.get(name, str(default)) or default)
445
+ except Exception:
446
+ return default