endomorphosis commited on
Commit
6dcb2bc
·
verified ·
1 Parent(s): c99a35f

Add Cabo Verde official snapshot (80 laws / 548 articles; 100% boe.incv.cv)

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_caboverde_laws manifest
2
+
3
+ generated_utc: 2026-09-09T16:13:07Z
4
+ cc: cv
5
+ laws_rows: 80
6
+ articles_rows: 548
7
+ laws_bytes: 423440
8
+ articles_bytes: 177487
9
+ laws_sha256: f8974a4cbf0e6d5904e5281f1ccea1d5593dd9135a8c19212c95686c2d739659
10
+ articles_sha256: 776e3299f4163bb4f8bceab62bc0545bceafbcbd724419927ac8a435cd1dafb8
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_caboverde_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_caboverde_laws/data/articles.parquet
13
+ compression: zstd
14
+ collector: scrapers/collect_cv.py
15
+ license: República de Cabo Verde — boe.incv.cv / incv.cv / governo.cv / parlamento.cv / justica.gov.cv / mf.gov.cv / gov.cv. Authentic Boletim Oficial / official text prevails. Not legal advice. Not Portugal (pt) / Angola (ao) / São Tomé (st).
16
+ retrieval: live-and-wayback-of-official
17
+ live_instruments: 80
18
+ archive_instruments: 0
19
+ wayback_instruments: 0
20
+ common_crawl_instruments: 0
21
+ archive_is_instruments: 0
22
+ constitution_present: true
23
+ catalog_expected: None
24
+ catalog_gap:
25
+ gaps: Official Cabo Verde / Cape Verde (cc=cv) law / Boletim Oficial from *.cv / *.gov.cv only (boe.incv.cv primary). Live-first; Wayback/CDX of official URLs on fail; OCR por+fra+spa for scanned PDFs. Not AfricanLII / Droit-Afrique. No WAF bypass. Distinct from Portugal (pt), Angola (ao), São Tomé (st). Not legal advice.
26
+ uploaded: false
README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Cabo Verde Laws and Boletim Oficial (boe.incv.cv / Governo / Parlamento / Justiça / Finanças)
3
+ license: other
4
+ license_name: cv-boe-incv-governo-parlamento-official-texts
5
+ language:
6
+ - pt
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - cabo-verde
13
+ - cape-verde
14
+ - boletim-oficial
15
+ - boe
16
+ - incv
17
+ - governo
18
+ - parlamento
19
+ - justica
20
+ - constitucao
21
+ - official-texts
22
+ size_categories:
23
+ - n<1K
24
+ configs:
25
+ - config_name: laws
26
+ data_files: data/laws.parquet
27
+ default: true
28
+ - config_name: articles
29
+ data_files: data/articles.parquet
30
+ ---
31
+
32
+ # Cabo Verde Laws and Boletim Oficial (boe.incv.cv / Governo / Parlamento / Justiça / Finanças)
33
+
34
+ Research snapshot of official national legislation from **Imprensa Nacional / Boletim Oficial (boe.incv.cv / incv.cv) + Portal do Governo (governo.cv) + Assembleia Nacional (parlamento.cv) + Justiça (justica.gov.cv) + Finanças (mf.gov.cv) / gov.cv / BCV / Tribunal Constitucional (*.cv / *.gov.cv)**.
35
+
36
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
37
+
38
+ ## Snapshot
39
+
40
+ | Field | Value |
41
+ | --- | --- |
42
+ | Snapshot date | 2026-09-09 |
43
+ | Coverage | catalog-backed incomplete (BOE ActFilter HTML + Bulletin PDF downloads + live crawl governo.cv / parlamento.cv / justica.gov.cv / mf.gov.cv + CDX of official *.cv / *.gov.cv) |
44
+ | Source | Imprensa Nacional / Boletim Oficial (boe.incv.cv / incv.cv) + Portal do Governo (governo.cv) + Assembleia Nacional (parlamento.cv) + Justiça (justica.gov.cv) + Finanças (mf.gov.cv) / gov.cv / BCV / Tribunal Constitucional (*.cv / *.gov.cv) |
45
+ | Collector | `scrapers/collect_cv.py` |
46
+ | Laws / instruments | 80 |
47
+ | Articles | 548 |
48
+ | Language | pt |
49
+ | Jurisdiction | Cabo Verde |
50
+ | License | `cv-boe-incv-governo-parlamento-official-texts` |
51
+
52
+ ## Contents
53
+
54
+ - `data/laws.parquet` — one row per instrument.
55
+ - `data/articles.parquet` — article/section rows for the same snapshot.
56
+ - `scrapers/collect_cv.py` — research collector used to build this snapshot.
57
+
58
+ ## License / reuse
59
+
60
+ República de Cabo Verde — boe.incv.cv / incv.cv / governo.cv / parlamento.cv / justica.gov.cv / mf.gov.cv / gov.cv. Authentic Boletim Oficial / official text prevails. Not legal advice. Not Portugal (pt) / Angola (ao) / São Tomé (st)..
61
+
62
+ This dataset is **not legal advice**. The official source prevails.
63
+
64
+ ## Source
65
+
66
+ - https://boe.incv.cv/
67
+
68
+ ## Known gaps
69
+
70
+ Official Cabo Verde / Cape Verde (cc=cv) law / Boletim Oficial from *.cv / *.gov.cv only (boe.incv.cv primary). Live-first; Wayback/CDX of official URLs on fail; OCR por+fra+spa for scanned PDFs. Not AfricanLII / Droit-Afrique. No WAF bypass. Distinct from Portugal (pt), Angola (ao), São Tomé (st). Not legal advice.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:776e3299f4163bb4f8bceab62bc0545bceafbcbd724419927ac8a435cd1dafb8
3
+ size 177487
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8974a4cbf0e6d5904e5281f1ccea1d5593dd9135a8c19212c95686c2d739659
3
+ size 423440
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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" # https SSLEOF from collector host
28
+ WAYBACK_WEB = "http://web.archive.org/web" # https SSLEOF from collector host
29
+ WAYBACK_CDX_HTTP = "http://web.archive.org/cdx/search/cdx"
30
+ WAYBACK_WEB_HTTP = "http://web.archive.org/web"
31
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
32
+ CC_DATA = "https://data.commoncrawl.org"
33
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
34
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
35
+
36
+ UA = (
37
+ "legal-corpora-collector/1.0 "
38
+ "(research archive of official national gazettes; polite; "
39
+ "contact via local operator)"
40
+ )
41
+
42
+ CHALLENGE_RE = re.compile(
43
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
44
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
45
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
46
+ r"request\s+rejected|access\s+denied",
47
+ re.I,
48
+ )
49
+ SPA_SHELL_RE = re.compile(
50
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
51
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
52
+ re.I,
53
+ )
54
+
55
+ _session: Optional[requests.Session] = None
56
+ _cc_indexes: Optional[list[str]] = None
57
+ _cc_dead: set[str] = set()
58
+ _last_wayback = 0.0
59
+ _last_cc = 0.0
60
+
61
+
62
+ def session() -> requests.Session:
63
+ global _session
64
+ if _session is None:
65
+ s = requests.Session()
66
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
67
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
68
+ s.mount("https://", ad)
69
+ s.mount("http://", ad)
70
+ _session = s
71
+ return _session
72
+
73
+
74
+ def _sleep_wayback(delay: float = 1.0) -> None:
75
+ global _last_wayback
76
+ now = time.time()
77
+ wait = delay - (now - _last_wayback)
78
+ if wait > 0:
79
+ time.sleep(wait)
80
+ _last_wayback = time.time()
81
+
82
+
83
+ def _sleep_cc(delay: float = 0.35) -> None:
84
+ global _last_cc
85
+ now = time.time()
86
+ wait = delay - (now - _last_cc)
87
+ if wait > 0:
88
+ time.sleep(wait)
89
+ _last_cc = time.time()
90
+
91
+
92
+ def has_brave_key() -> bool:
93
+ return bool(
94
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
95
+ )
96
+
97
+
98
+ def is_challenge(html: str, status: int = 200) -> bool:
99
+ if status in (401, 403, 429, 503):
100
+ return True
101
+ if not html:
102
+ return False
103
+ head = html[:8000]
104
+ if CHALLENGE_RE.search(head):
105
+ return True
106
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
107
+ return True
108
+ return False
109
+
110
+
111
+ def is_spa_shell(html: str, text: str) -> bool:
112
+ if not html:
113
+ return False
114
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
115
+ return True
116
+ return False
117
+
118
+
119
+ # --- Wayback ---
120
+
121
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
122
+
123
+
124
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
125
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
126
+ if not isinstance(data, list) or len(data) <= 1:
127
+ return [], None
128
+ resume = None
129
+ rows = data
130
+ # Trailer: ..., [], ["resumeKey"]
131
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
132
+ resume = str(data[-1][0]) if data[-1][0] else None
133
+ rows = data[:-2]
134
+ headers = rows[0] if rows else []
135
+ out: list[dict] = []
136
+ for row in rows[1:]:
137
+ if not row:
138
+ continue
139
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
140
+ if not rec and isinstance(row, list) and len(row) >= 5:
141
+ rec = {
142
+ "urlkey": row[0],
143
+ "timestamp": row[1],
144
+ "original": row[2],
145
+ "mimetype": row[3],
146
+ "statuscode": row[4],
147
+ "digest": row[5] if len(row) > 5 else "",
148
+ "length": row[6] if len(row) > 6 else "0",
149
+ }
150
+ orig = rec.get("original") or rec.get("url") or ""
151
+ ts = rec.get("timestamp") or ""
152
+ mime = rec.get("mimetype") or ""
153
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
154
+ "application/pdf",
155
+ "application/xml",
156
+ "text/xml",
157
+ "application/xhtml+xml",
158
+ "text/html",
159
+ "application/json",
160
+ ):
161
+ continue
162
+ if not orig or not ts:
163
+ continue
164
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
165
+ rec["source"] = "wayback"
166
+ out.append(rec)
167
+ return out, resume
168
+
169
+
170
+ def _wayback_cdx_page(
171
+ url: str,
172
+ *,
173
+ limit: int,
174
+ collapse: str,
175
+ filter_status: str,
176
+ from_date: Optional[str],
177
+ to_date: Optional[str],
178
+ match_type: Optional[str],
179
+ extra_filters: Optional[list[str]],
180
+ resume_key: Optional[str],
181
+ mime_prefix: Optional[str],
182
+ page_size: int,
183
+ ) -> tuple[list[dict], Optional[str]]:
184
+ items: list[tuple[str, Any]] = [
185
+ ("url", url),
186
+ ("output", "json"),
187
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
188
+ ("limit", int(page_size)),
189
+ ("showResumeKey", "true"),
190
+ ]
191
+ if collapse:
192
+ items.append(("collapse", collapse))
193
+ if from_date:
194
+ items.append(("from", from_date))
195
+ if to_date:
196
+ items.append(("to", to_date))
197
+ if match_type:
198
+ items.append(("matchType", match_type))
199
+ if filter_status:
200
+ items.append(("filter", f"statuscode:{filter_status}"))
201
+ for flt in extra_filters or []:
202
+ items.append(("filter", flt))
203
+ if resume_key:
204
+ items.append(("resumeKey", resume_key))
205
+ _sleep_wayback(1.0)
206
+ last_err = None
207
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
208
+ if attempt > 1:
209
+ items = [(k, psz if k == "limit" else v) for k, v in items]
210
+ _sleep_wayback(1.5)
211
+ try:
212
+ try:
213
+ # Prefer HTTP CDX — HTTPS to archive.org often SSLEOF from this host
214
+ r = session().get(WAYBACK_CDX_HTTP, params=items, timeout=(20, 90))
215
+ except requests.RequestException:
216
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
217
+ except requests.RequestException as exc:
218
+ last_err = exc
219
+ log.warning("wayback cdx fail %s: %s", url, exc)
220
+ continue
221
+ if r.status_code in (502, 503, 504) or not r.content:
222
+ last_err = f"http_{r.status_code}"
223
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
224
+ continue
225
+ if r.status_code != 200:
226
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
227
+ return [], None
228
+ try:
229
+ data = r.json()
230
+ except Exception:
231
+ return [], None
232
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
233
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
234
+ return [], None
235
+
236
+
237
+ def search_wayback_machine(
238
+ url: str,
239
+ *,
240
+ from_date: Optional[str] = None,
241
+ to_date: Optional[str] = None,
242
+ limit: int = 100,
243
+ collapse: str = "urlkey",
244
+ filter_status: str = "200",
245
+ match_type: Optional[str] = None,
246
+ mime_prefix: Optional[str] = None,
247
+ extra_filters: Optional[list[str]] = None,
248
+ ) -> list[dict]:
249
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
250
+ target = max(1, int(limit))
251
+ page_size = CDX_PAGE if target > CDX_PAGE else target
252
+ out: list[dict] = []
253
+ seen = set()
254
+ resume: Optional[str] = None
255
+ empty = 0
256
+ while len(out) < target:
257
+ need = min(page_size, target - len(out))
258
+ batch, resume = _wayback_cdx_page(
259
+ url,
260
+ limit=need,
261
+ collapse=collapse,
262
+ filter_status=filter_status,
263
+ from_date=from_date,
264
+ to_date=to_date,
265
+ match_type=match_type,
266
+ extra_filters=extra_filters,
267
+ resume_key=resume,
268
+ mime_prefix=mime_prefix,
269
+ page_size=need,
270
+ )
271
+ added = 0
272
+ for rec in batch:
273
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
274
+ if key in seen:
275
+ continue
276
+ seen.add(key)
277
+ out.append(rec)
278
+ added += 1
279
+ if added == 0:
280
+ empty += 1
281
+ if empty >= 2 or not resume:
282
+ break
283
+ else:
284
+ empty = 0
285
+ if not resume:
286
+ break
287
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
288
+ return out[:target]
289
+
290
+
291
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
292
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
293
+
294
+ Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).
295
+ Follow 3xx Location only after rewriting https://web.archive.org → http://.
296
+ """
297
+ import subprocess
298
+
299
+ if timestamp:
300
+ path = f"/{timestamp}id_/{url}"
301
+ else:
302
+ path = f"/2id_/{url}"
303
+ target = WAYBACK_WEB_HTTP + path
304
+ last_err = None
305
+ body = b""
306
+ ctype = ""
307
+ final_url = target
308
+ status = 0
309
+ for attempt in range(1, 6):
310
+ _sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))
311
+ try:
312
+ # Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
313
+ proc = subprocess.run(
314
+ [
315
+ "curl", "-sS", "--max-time", "90",
316
+ "-A", UA,
317
+ "-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}\n__REDIRECT_URL__%{redirect_url}",
318
+ "--output", "-",
319
+ target,
320
+ ],
321
+ capture_output=True,
322
+ timeout=100,
323
+ )
324
+ raw = proc.stdout or b""
325
+ # Trailer is text appended after body when -w is used with --output -
326
+ marker = b"\n__HTTP_STATUS__"
327
+ redirect_url = ""
328
+ if marker in raw:
329
+ body, rest = raw.rsplit(marker, 1)
330
+ trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
331
+ mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
332
+ mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
333
+ murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
334
+ mredir = re.search(r"__REDIRECT_URL__([^\n]*)", trailer)
335
+ status = int(mstat.group(1)) if mstat else 0
336
+ ctype = (mctype.group(1) if mctype else "") or ""
337
+ final_url = (murl.group(1) if murl else target) or target
338
+ redirect_url = (mredir.group(1) if mredir else "") or ""
339
+ else:
340
+ body = raw
341
+ status = 200 if proc.returncode == 0 and raw else 0
342
+ if status in (301, 302, 303, 307, 308):
343
+ loc = redirect_url or ""
344
+ if loc.startswith("https://web.archive.org/"):
345
+ loc = "http://" + loc[len("https://"):]
346
+ if loc.startswith("http://web.archive.org/"):
347
+ log.info("wayback replay follow HTTP redirect %s -> %s", status, loc[:120])
348
+ target = loc
349
+ final_url = loc
350
+ continue
351
+ last_err = f"http_{status}_bad_redirect"
352
+ log.info("wayback replay HTTP %s bad redirect %s", status, (loc or "")[:160])
353
+ continue
354
+ if proc.returncode != 0 and not body:
355
+ last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
356
+ log.info("wayback replay curl fail %s: %s", url, last_err)
357
+ continue
358
+ if status in (403, 429, 503, 502, 504) and attempt < 5:
359
+ log.info("wayback replay HTTP %s %s attempt=%s", status, url, attempt)
360
+ continue
361
+ break
362
+ except Exception as exc:
363
+ last_err = str(exc)
364
+ log.info("wayback replay fail %s: %s", url, exc)
365
+ continue
366
+ else:
367
+ # fallback: requests without following redirects to https
368
+ try:
369
+ r = session().get(target, timeout=(20, 90), allow_redirects=False)
370
+ status = r.status_code
371
+ body = r.content or b""
372
+ ctype = r.headers.get("content-type") or ""
373
+ final_url = r.url or target
374
+ if status in (301, 302, 303, 307, 308):
375
+ loc = r.headers.get("Location") or ""
376
+ if loc.startswith("https://web.archive.org/"):
377
+ loc = "http://" + loc[len("https://"):]
378
+ if loc.startswith("http://web.archive.org/"):
379
+ r2 = session().get(loc, timeout=(20, 90), allow_redirects=False)
380
+ status = r2.status_code
381
+ body = r2.content or b""
382
+ ctype = r2.headers.get("content-type") or ""
383
+ final_url = r2.url or loc
384
+ except requests.RequestException as exc:
385
+ return {"status": "error", "error": last_err or str(exc), "url": url}
386
+
387
+ if not body and status != 200:
388
+ return {"status": "error", "error": last_err or f"http_{status}", "url": url}
389
+ cap_ts = timestamp or ""
390
+ m = re.search(r"/web/(\d{14})", final_url or "")
391
+ if m:
392
+ cap_ts = m.group(1)
393
+ text = ""
394
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
395
+ try:
396
+ text = body.decode("utf-8", "replace")
397
+ except Exception:
398
+ text = ""
399
+ if status != 200 or not body:
400
+ return {
401
+ "status": "error",
402
+ "error": f"http_{status}",
403
+ "http_status": status,
404
+ "wayback_url": final_url,
405
+ "original_url": url,
406
+ }
407
+ if text and is_challenge(text, status):
408
+ return {
409
+ "status": "error",
410
+ "error": "challenge_or_shell",
411
+ "http_status": status,
412
+ "wayback_url": final_url,
413
+ "original_url": url,
414
+ "content": text[:2000],
415
+ }
416
+ return {
417
+ "status": "success",
418
+ "content": body,
419
+ "text": text,
420
+ "content_type": ctype,
421
+ "wayback_url": final_url,
422
+ "capture_timestamp": cap_ts,
423
+ "original_url": url,
424
+ "http_status": status,
425
+ "method": "wayback_curl_http",
426
+ }
427
+
428
+
429
+ # --- Common Crawl ---
430
+
431
+ def _http_cc_index(url: str) -> str:
432
+ if url.startswith("https://index.commoncrawl.org"):
433
+ return "http://" + url[len("https://"):]
434
+ return url
435
+
436
+
437
+ def cc_indexes(n: int = 6) -> list[str]:
438
+ global _cc_indexes
439
+ if _cc_indexes is None:
440
+ cols = []
441
+ last_exc = None
442
+ for coll in (CC_COLLINFO, CC_COLLINFO.replace("https://", "http://", 1)):
443
+ try:
444
+ r = session().get(coll, timeout=30)
445
+ if r.status_code == 200:
446
+ cols = r.json() or []
447
+ break
448
+ except Exception as exc:
449
+ last_exc = exc
450
+ log.warning("cc collinfo %s: %s", coll, exc)
451
+ ids = []
452
+ for c in cols:
453
+ cid = c.get("id") or ""
454
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
455
+ if cid:
456
+ ids.append(_http_cc_index(cdx or f"http://index.commoncrawl.org/{cid}-index"))
457
+ # collinfo is newest-first. Do not drop crawls that 404 a
458
+ # specific URL (that means "no captures", not a dead index).
459
+ _cc_indexes = ids or [
460
+ "http://index.commoncrawl.org/CC-MAIN-2026-34-index",
461
+ "http://index.commoncrawl.org/CC-MAIN-2024-33-index",
462
+ ]
463
+ if last_exc and not ids:
464
+ log.warning("cc collinfo fallback indexes after %s", last_exc)
465
+ return _cc_indexes[:n]
466
+
467
+
468
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
469
+ """Query public CC CDX (https://index.commoncrawl.org/).
470
+
471
+ Do not send filter=status:200 — on some shards that returns a false
472
+ 404 "No Captures found". Filter status client-side instead.
473
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
474
+ """
475
+ out = []
476
+ seen = set()
477
+ empty = 0
478
+ for idx in (indexes or cc_indexes(12)):
479
+ if idx in _cc_dead:
480
+ continue
481
+ params = {
482
+ "url": url,
483
+ "output": "json",
484
+ "limit": str(limit),
485
+ }
486
+ _sleep_cc(0.3)
487
+ try:
488
+ r = session().get(idx, params=params, timeout=(12, 25))
489
+ except requests.RequestException as exc:
490
+ alt = _http_cc_index(idx) if idx.startswith("https://") else idx.replace("http://", "https://", 1)
491
+ try:
492
+ r = session().get(alt, params=params, timeout=(12, 25))
493
+ except requests.RequestException as exc2:
494
+ log.info("cc cdx %s fail %s / %s", idx, exc, exc2)
495
+ continue
496
+ if r.status_code == 404:
497
+ msg = (r.text or "")[:80]
498
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
499
+ empty += 1
500
+ if empty >= 8 and not out:
501
+ continue
502
+ continue
503
+ if r.status_code in (410,):
504
+ _cc_dead.add(idx)
505
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
506
+ continue
507
+ if r.status_code != 200 or not r.content:
508
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
509
+ continue
510
+ for line in r.text.splitlines():
511
+ line = line.strip()
512
+ if not line or line[0] not in "{[":
513
+ continue
514
+ try:
515
+ rec = json.loads(line)
516
+ except Exception:
517
+ continue
518
+ orig = rec.get("url") or rec.get("original") or ""
519
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
520
+ if st and st not in ("200", "201", "206"):
521
+ continue
522
+ key = (orig, rec.get("filename"), rec.get("offset"))
523
+ if not orig or key in seen:
524
+ continue
525
+ seen.add(key)
526
+ rec["original"] = orig
527
+ rec["source"] = "common_crawl"
528
+ rec["cc_index"] = idx
529
+ out.append(rec)
530
+ if out:
531
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
532
+ if len(out) >= limit or out:
533
+ break
534
+ return out[:limit]
535
+
536
+
537
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
538
+ data = raw
539
+ if data[:2] == b"\x1f\x8b":
540
+ try:
541
+ data = gzip.decompress(data)
542
+ except Exception:
543
+ try:
544
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
545
+ except Exception:
546
+ pass
547
+ # WARC record: headers, then HTTP payload
548
+ split = data.split(b"\r\n\r\n", 1)
549
+ if len(split) < 2:
550
+ return 0, "", data
551
+ warc_headers, rest = split
552
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
553
+ http_split = rest.split(b"\r\n\r\n", 1)
554
+ http_head = http_split[0].decode("latin-1", "replace")
555
+ body = http_split[1] if len(http_split) > 1 else b""
556
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
557
+ status = int(m.group(1)) if m else 0
558
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
559
+ ctype = cm.group(1).strip() if cm else ""
560
+ return status, ctype, body
561
+ return 0, "", rest
562
+
563
+
564
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
565
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
566
+ try:
567
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
568
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
569
+ except Exception:
570
+ return {"status": "error", "error": "bad_pointer"}
571
+ if not fn or ln <= 0:
572
+ return {"status": "error", "error": "missing_pointer"}
573
+ ln = min(ln, max_bytes)
574
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
575
+ _sleep_cc(0.25)
576
+ try:
577
+ r = session().get(
578
+ url,
579
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
580
+ timeout=(20, 90),
581
+ )
582
+ except requests.RequestException as exc:
583
+ return {"status": "error", "error": str(exc)}
584
+ if r.status_code not in (200, 206) or not r.content:
585
+ return {"status": "error", "error": f"http_{r.status_code}"}
586
+ status, ctype, body = _parse_warc_http(r.content)
587
+ text = ""
588
+ if body and (
589
+ "html" in (ctype or "")
590
+ or "xml" in (ctype or "")
591
+ or "text/" in (ctype or "")
592
+ or not ctype
593
+ ):
594
+ text = body.decode("utf-8", "replace")
595
+ orig = rec.get("original") or rec.get("url") or ""
596
+ if text and is_challenge(text, status or 200):
597
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
598
+ return {
599
+ "status": "success",
600
+ "content": body,
601
+ "text": text,
602
+ "content_type": ctype,
603
+ "original_url": orig,
604
+ "http_status": status or 200,
605
+ "method": "common_crawl",
606
+ "cc_record": {
607
+ "filename": fn,
608
+ "offset": off,
609
+ "length": ln,
610
+ "timestamp": rec.get("timestamp"),
611
+ },
612
+ }
613
+
614
+
615
+ # --- archive.is ---
616
+
617
+ def get_archive_is_content(url: str) -> dict:
618
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
619
+ try:
620
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
621
+ except requests.RequestException as exc:
622
+ log.info("archive.is %s", exc)
623
+ continue
624
+ if r.status_code != 200 or not r.content:
625
+ continue
626
+ if "archive." not in (r.url or ""):
627
+ continue
628
+ text = r.text or ""
629
+ if is_challenge(text, r.status_code):
630
+ continue
631
+ return {
632
+ "status": "success",
633
+ "content": r.content,
634
+ "text": text,
635
+ "content_type": r.headers.get("content-type") or "text/html",
636
+ "archive_url": r.url,
637
+ "original_url": url,
638
+ "http_status": r.status_code,
639
+ "method": "archive_is",
640
+ }
641
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
642
+
643
+
644
+ # --- Direct HTTP last ---
645
+
646
+ def get_http(url: str) -> dict:
647
+ try:
648
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
649
+ except requests.RequestException as exc:
650
+ return {"status": "error", "error": str(exc), "original_url": url}
651
+ text = ""
652
+ ctype = r.headers.get("content-type") or ""
653
+ body = r.content or b""
654
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
655
+ text = body.decode(r.encoding or "utf-8", "replace")
656
+ if r.status_code != 200 or not body:
657
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
658
+ if text and is_challenge(text, r.status_code):
659
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
660
+ return {
661
+ "status": "success",
662
+ "content": body,
663
+ "text": text,
664
+ "content_type": ctype,
665
+ "original_url": url,
666
+ "http_status": r.status_code,
667
+ "method": "http",
668
+ "final_url": r.url,
669
+ }
670
+
671
+
672
+ def fetch_with_fallbacks(
673
+ url: str,
674
+ *,
675
+ cc_record: Optional[dict] = None,
676
+ wayback_ts: Optional[str] = None,
677
+ try_archive_is: bool = False,
678
+ try_http: bool = True,
679
+ try_cc: bool = True,
680
+ ) -> dict:
681
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
682
+
683
+ Brave Search skipped (no API key in this environment).
684
+ Playwright is attempted by the caller when this returns a SPA shell.
685
+ Does not run Wayback CDX search; Wayback is replay only.
686
+ """
687
+ errors = []
688
+ cc_recs: list[dict] = []
689
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
690
+ cc_recs = [cc_record]
691
+ elif try_cc:
692
+ try:
693
+ cc_recs = search_common_crawl(url, limit=4)
694
+ except Exception as exc:
695
+ errors.append(f"common_crawl:{exc}")
696
+ cc_recs = []
697
+ for rec in cc_recs:
698
+ res = fetch_common_crawl_warc(rec)
699
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
700
+ return res
701
+ errors.append(f"common_crawl:{res.get('error')}")
702
+ if wayback_ts or url:
703
+ res = get_wayback_content(url, timestamp=wayback_ts)
704
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
705
+ return res
706
+ errors.append(f"wayback:{res.get('error')}")
707
+ if try_archive_is:
708
+ res = get_archive_is_content(url)
709
+ if res.get("status") == "success":
710
+ return res
711
+ errors.append(f"archive_is:{res.get('error')}")
712
+ if try_http:
713
+ res = get_http(url)
714
+ if res.get("status") == "success":
715
+ return res
716
+ errors.append(f"http:{res.get('error')}")
717
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_cv.py ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cabo Verde / Cape Verde (cv): official Boletim Oficial + law texts from *.cv / *.gov.cv.
3
+
4
+ Official only (Portuguese primary):
5
+ - https://boe.incv.cv/ (Imprensa Nacional — BOE / Boletim Oficial; /api/v1)
6
+ - https://incv.cv/ / kiosk.incv.cv (redirects to boe.incv.cv)
7
+ - https://www.governo.cv/ / governo.cv
8
+ - https://www.parlamento.cv/ / parlamento.cv (Assembleia Nacional)
9
+ - https://justica.gov.cv/ / www.justica.gov.cv
10
+ - https://www.mf.gov.cv/ / mf.gov.cv (Finanças)
11
+ - https://www.gov.cv/ / gov.cv
12
+ - https://www.bcv.cv/ / https://www.ine.cv/
13
+ - https://www.tribunalconstitucional.cv/
14
+ - Wayback/CDX of the same official *.cv / *.gov.cv URLs
15
+
16
+ Filter: prefer lei/decreto/constituição/código/Boletim; skip PDFs >12MB.
17
+ Not AfricanLII / Droit-Afrique. No WAF bypass. Not legal advice.
18
+ NOTE: Leave Lesotho / Eswatini / Burundi / Portugal alone.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import html as html_lib
23
+ import json
24
+ import logging
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import time
30
+ from datetime import date, timedelta
31
+ from pathlib import Path
32
+ from urllib.parse import quote, unquote, urlencode, urljoin, urlsplit, urlunsplit
33
+
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+ from common import existing_ids, html_to_text, http_get, log_failure, utcnow, write_summary
36
+ from world_lib import (
37
+ cdx_urls,
38
+ env_int,
39
+ fetch_official,
40
+ live_get,
41
+ pdf_to_text,
42
+ save_instrument,
43
+ setup_log,
44
+ slug_id,
45
+ )
46
+
47
+ CC, COUNTRY, LANG = "cv", "Cabo Verde", "pt"
48
+ SOURCE_TYPE = "caboverde_official_boletim_oficial_laws"
49
+ LICENSE = (
50
+ "República de Cabo Verde — Imprensa Nacional / Boletim Oficial (boe.incv.cv / incv.cv) / "
51
+ "Portal do Governo (governo.cv) / Assembleia Nacional (parlamento.cv) / "
52
+ "Justiça (justica.gov.cv) / Finanças (mf.gov.cv) / gov.cv / BCV / INE / "
53
+ "Tribunal Constitucional and other *.cv / *.gov.cv gazette hosts. Authentic Boletim "
54
+ "Oficial / official text prevails. Not legal advice. Not Portugal (pt) / Angola (ao) / "
55
+ "São Tomé (st)."
56
+ )
57
+ UA = (
58
+ "legal-corpora-collector/1.0 (research; source=https://boe.incv.cv/; "
59
+ "CaboVerde=cv not pt/ao/st)"
60
+ )
61
+ ART = re.compile(
62
+ r"(?im)^\s*((?:Artigo|Art\.?|Secção|Secao|Capítulo|Capitulo|Cap\.?|"
63
+ r"Título|Titulo|Parte|Disposição|Disposicao)\s*[IVXLC0-9º°a-zA-Z]*)\b"
64
+ )
65
+ log = logging.getLogger("cv")
66
+
67
+ MAX_PDF_BYTES = 12 * 1024 * 1024
68
+ API = "https://boe.incv.cv/api/v1"
69
+ API_HEADERS = {
70
+ "User-Agent": UA,
71
+ "Accept": "application/json",
72
+ "Ankira-App-Version": "1.0.0",
73
+ }
74
+
75
+ ALLOWED = (
76
+ "boe.incv.cv",
77
+ "incv.cv",
78
+ "www.incv.cv",
79
+ "kiosk.incv.cv",
80
+ "governo.cv",
81
+ "www.governo.cv",
82
+ "parlamento.cv",
83
+ "www.parlamento.cv",
84
+ "assembleianacional.cv",
85
+ "www.assembleianacional.cv",
86
+ "presidencia.cv",
87
+ "www.presidencia.cv",
88
+ "gov.cv",
89
+ "www.gov.cv",
90
+ "justica.gov.cv",
91
+ "www.justica.gov.cv",
92
+ "mf.gov.cv",
93
+ "www.mf.gov.cv",
94
+ "bcv.cv",
95
+ "www.bcv.cv",
96
+ "ine.cv",
97
+ "www.ine.cv",
98
+ "tribunalconstitucional.cv",
99
+ "www.tribunalconstitucional.cv",
100
+ "stj.cv",
101
+ "www.stj.cv",
102
+ "pgr.cv",
103
+ "www.pgr.cv",
104
+ "anac.cv",
105
+ "www.anac.cv",
106
+ "are.cv",
107
+ "www.are.cv",
108
+ )
109
+
110
+ KEEP_RE = re.compile(
111
+ r"(lei|leis|decreto|diploma|resolu[cç][aã]o|proclama|"
112
+ r"constitui[cç][aã]o|regulamento|portaria|despacho|"
113
+ r"boletim|oficial|gazette|jornal|"
114
+ r"legislacao|legisla[cç][aã]o|normativo|estatuto|codigo|c[oó]digo|"
115
+ r"amendment|altera[cç][aã]o|lei[_/\-]|decreto[_/\-]|"
116
+ r"wp-content/uploads|/uploads/|/files/|/documents?/|/ficheiros?/|"
117
+ r"cabo.?verde|cape.?verde|/Bulletins/Download/)",
118
+ re.I,
119
+ )
120
+ DROP_RE = re.compile(
121
+ r"(africanlii|droit-afrique|gazettes\.africa|law\.africa|"
122
+ r"discurso|allocution|communique|comunicado|nota.?de.?prensa|photo|banner|logo|"
123
+ r"biograf|organigrama|presentacion|newsletter|"
124
+ r"facebook|twitter|linkedin|album|actualites|licitacao|"
125
+ r"favicon|apple-touch|webmanifest|/css/|\.css\b|"
126
+ r"portugal|\.pt/|dre\.pt|diariodarepublica|"
127
+ r"angola|\.ao/|sao.?tome|\.st/|lesotho|eswatini|burundi)",
128
+ re.I,
129
+ )
130
+ TEXT_KEEP_RE = re.compile(
131
+ r"\b(lei|decreto|diploma|constitui[cç][aã]o|boletim\s+oficial|"
132
+ r"c[oó]digo|rep[uú]blica\s+de\s+cabo\s+verde|"
133
+ r"assembleia\s+nacional|presidente\s+da\s+rep[uú]blica|promulga|"
134
+ r"artigo|cabo\s+verde|resolu[cç][aã]o|regulamento|ac[oó]rd[aã]o)\b",
135
+ re.I,
136
+ )
137
+
138
+ ACT_QUERIES = [
139
+ "constituição",
140
+ "código civil",
141
+ "código penal",
142
+ "código comercial",
143
+ "código do trabalho",
144
+ "decreto-lei",
145
+ "decreto legislativo",
146
+ "Lei n.º",
147
+ "Lei Orgânica",
148
+ "Assembleia Nacional",
149
+ "regulamento",
150
+ "estatuto",
151
+ "portaria",
152
+ "resolução",
153
+ "Banco de Cabo Verde",
154
+ "Tribunal Constitucional",
155
+ "Código da Propriedade Industrial",
156
+ "regime jurídico",
157
+ ]
158
+
159
+ HOMES = [
160
+ "https://boe.incv.cv/",
161
+ "https://incv.cv/",
162
+ "https://incv.cv/boletim-oficial/",
163
+ "https://www.governo.cv/",
164
+ "https://www.governo.cv/documentos/",
165
+ "https://www.parlamento.cv/",
166
+ "https://www.parlamento.cv/legislacao.php",
167
+ "https://justica.gov.cv/",
168
+ "https://justica.gov.cv/legisla%C3%A7%C3%B5es",
169
+ "https://www.mf.gov.cv/",
170
+ "https://www.gov.cv/",
171
+ "https://www.gov.cv/legislacao",
172
+ "https://www.gov.cv/lei-justica",
173
+ "https://www.bcv.cv/",
174
+ "https://www.bcv.cv/pt/O%20Banco/Constituicao%20da%20Republica/Paginas/ConstituicaodaRepublica.aspx",
175
+ "https://www.bcv.cv/pt/O%20Banco/Lei%20Organica/Paginas/LeiOrganica.aspx",
176
+ "https://www.ine.cv/",
177
+ "https://www.tribunalconstitucional.cv/",
178
+ ]
179
+
180
+ CDX_PREFIXES = (
181
+ "boe.incv.cv/",
182
+ "incv.cv/",
183
+ "www.incv.cv/",
184
+ "www.governo.cv/",
185
+ "governo.cv/",
186
+ "www.parlamento.cv/",
187
+ "parlamento.cv/",
188
+ "justica.gov.cv/",
189
+ "www.justica.gov.cv/",
190
+ "www.mf.gov.cv/",
191
+ "mf.gov.cv/",
192
+ "www.gov.cv/",
193
+ "gov.cv/",
194
+ "www.bcv.cv/",
195
+ "www.ine.cv/",
196
+ "www.tribunalconstitucional.cv/",
197
+ )
198
+
199
+ SEED_PDFS = [
200
+ # filled dynamically; keep a couple known BO downloads as seeds
201
+ "https://boe.incv.cv/Bulletins/Download/34017",
202
+ "https://boe.incv.cv/Bulletins/Download/23930",
203
+ ]
204
+
205
+
206
+ def _host_ok(url: str) -> bool:
207
+ host = (urlsplit(url).hostname or "").lower()
208
+ if any(
209
+ x in host
210
+ for x in (
211
+ "africanlii",
212
+ "droit-afrique",
213
+ "gazettes.africa",
214
+ "law.africa",
215
+ )
216
+ ):
217
+ return False
218
+ if host.endswith((".pt", ".ao", ".st", ".ls", ".sz", ".bi", ".gq", ".gw")):
219
+ return False
220
+ if any(x in host for x in ("portugal", "angola", "saotome", "lesotho", "eswatini", "burundi")):
221
+ return False
222
+ if host.endswith(".gov.cv") or host in ("gov.cv", "www.gov.cv"):
223
+ return True
224
+ if host.endswith(".cv"):
225
+ return any(host == s or host.endswith("." + s) for s in ALLOWED) or host in ALLOWED
226
+ return any(host == s or host.endswith("." + s) for s in ALLOWED)
227
+
228
+
229
+ def _norm_url(url: str) -> str:
230
+ url = html_lib.unescape((url or "").split("#")[0].strip())
231
+ if not url:
232
+ return ""
233
+ url = url.replace(":80/", "/").replace(":80?", "?")
234
+ if url.startswith("http://"):
235
+ url = "https://" + url[len("http://") :]
236
+ try:
237
+ p = urlsplit(url)
238
+ host = (p.hostname or "").lower()
239
+ parts = []
240
+ for seg in p.path.split("/"):
241
+ if not seg:
242
+ parts.append(seg)
243
+ continue
244
+ parts.append(seg if "%" in seg else quote(seg, safe="._-()[]',"))
245
+ url = urlunsplit((p.scheme or "https", host, "/".join(parts), "", ""))
246
+ except Exception:
247
+ url = url.replace(" ", "%20")
248
+ return url
249
+
250
+
251
+ def _ident_from_url(url: str, title: str | None = None) -> str:
252
+ path = unquote(urlsplit(url).path)
253
+ if title:
254
+ t = re.sub(r"\W+", "-", title).strip("-").lower()[:100]
255
+ if t and len(t) > 8:
256
+ return t
257
+ name = Path(path).name or path
258
+ stem = Path(name).stem
259
+ return re.sub(r"\W+", "-", stem).strip("-").lower()[:160] or re.sub(r"\W+", "-", url)[-80:]
260
+
261
+
262
+ def _is_bo_pdf(url: str) -> bool:
263
+ path = unquote(urlsplit(url).path).lower()
264
+ return "/bulletins/download/" in path or bool(
265
+ re.search(r"(?i)(boletim.?oficial|bo[_/\-]|serie)", path)
266
+ )
267
+
268
+
269
+ def _keep_pdf(url: str, title: str | None = None) -> bool:
270
+ if not _host_ok(url):
271
+ return False
272
+ blob = unquote(urlsplit(url).path) + " " + url + " " + (title or "")
273
+ if DROP_RE.search(blob):
274
+ return False
275
+ path = unquote(urlsplit(url).path).lower()
276
+ if not path.endswith(".pdf") and "/bulletins/download/" not in path:
277
+ return False
278
+ if any(x in path for x in ("/css/", "favicon", "apple-touch", ".css", "webmanifest", "/js/")):
279
+ return False
280
+ if _is_bo_pdf(url):
281
+ return True
282
+ return bool(KEEP_RE.search(blob))
283
+
284
+
285
+ def _api_get(path: str, params: dict | None = None) -> dict | None:
286
+ qs = ("?" + urlencode(params, doseq=True)) if params else ""
287
+ url = f"{API}/{path.lstrip('/')}{qs}"
288
+ try:
289
+ r = http_get(url, ua=UA, timeout=(15, 60), retries=2, sleep=0.2, headers=API_HEADERS)
290
+ if getattr(r, "status_code", 0) != 200:
291
+ log.info("api status=%s %s", getattr(r, "status_code", None), url[:120])
292
+ return None
293
+ raw = (r.text or "").strip()
294
+ if not raw.startswith("{") and not raw.startswith("["):
295
+ return None
296
+ return json.loads(raw)
297
+ except Exception as exc:
298
+ log.info("api %s %s", path, exc)
299
+ return None
300
+
301
+
302
+ def ocr_pdf(raw: bytes) -> str:
303
+ max_pages = env_int("MAX_OCR_PAGES", 12)
304
+ dpi = env_int("OCR_DPI", 140)
305
+ try:
306
+ with tempfile.TemporaryDirectory() as td:
307
+ pdf = Path(td) / "doc.pdf"
308
+ pdf.write_bytes(raw)
309
+ proc = subprocess.run(
310
+ [
311
+ "pdftoppm", "-png", "-r", str(dpi),
312
+ "-f", "1", "-l", str(max_pages),
313
+ str(pdf), str(Path(td) / "p"),
314
+ ],
315
+ check=False, capture_output=True, timeout=240,
316
+ )
317
+ if proc.returncode != 0:
318
+ return ""
319
+ chunks = []
320
+ for img in sorted(Path(td).glob("p*.png")):
321
+ tproc = subprocess.run(
322
+ ["tesseract", str(img), "stdout", "-l", "por+fra+spa", "--psm", "6"],
323
+ check=False, capture_output=True, timeout=120,
324
+ )
325
+ if tproc.returncode == 0 and tproc.stdout:
326
+ chunks.append(tproc.stdout.decode("utf-8", "replace").strip())
327
+ return "\n\n".join(c for c in chunks if c).strip()
328
+ except Exception as exc:
329
+ log.warning("ocr_pdf: %s", exc)
330
+ return ""
331
+
332
+
333
+ def fetch_cv(url: str, wayback_ts: str | None = None) -> dict:
334
+ got = fetch_official(url, ua=UA, verify=False, min_text=120, wayback=True, wayback_ts=wayback_ts)
335
+ if got.get("status") == "success" and len(got.get("text") or "") >= 120:
336
+ return got
337
+ body = got.get("content") or b""
338
+ if not (isinstance(body, bytes) and body[:4] == b"%PDF"):
339
+ try:
340
+ r = live_get(url, ua=UA, verify=False, timeout=(20, 90), retries=2)
341
+ if getattr(r, "status_code", 0) == 200 and (r.content or b"")[:4] == b"%PDF":
342
+ body = r.content
343
+ got["method"] = "live_pdf"
344
+ except Exception as exc:
345
+ got["error"] = (got.get("error") or "") + f";live_pdf:{exc}"
346
+ return got
347
+ if not (isinstance(body, bytes) and body[:4] == b"%PDF"):
348
+ return got
349
+ if len(body) > MAX_PDF_BYTES:
350
+ got["error"] = f"pdf_too_large:{len(body)}"
351
+ return got
352
+ text = pdf_to_text(body)
353
+ if len(text) >= 120:
354
+ got.update(status="success", text=text, content=body, method=got.get("method") or "http_pdf")
355
+ return got
356
+ max_ocr_bytes = env_int("MAX_OCR_BYTES", 8 * 1024 * 1024)
357
+ if len(body) > max_ocr_bytes:
358
+ got["error"] = (got.get("error") or "") + f";skip_ocr_large:{len(body)}"
359
+ return got
360
+ log.info("OCR por %s bytes=%s", _ident_from_url(url)[:40], len(body))
361
+ ocr = ocr_pdf(body)
362
+ if len(ocr) >= 120:
363
+ got.update(status="success", text=ocr, content=body, method="ocr_por")
364
+ return got
365
+ got["error"] = (got.get("error") or "") + ";ocr_short"
366
+ return got
367
+
368
+
369
+ def _add(items, seen, ident, url, ts=None, priority=50, size_hint=None, title=None, kind="pdf", text=None, meta=None):
370
+ url = _norm_url(url) if url else ""
371
+ if kind == "pdf":
372
+ if not url or not _keep_pdf(url, title=title):
373
+ return
374
+ key = url.lower().split("?")[0]
375
+ else:
376
+ # act text from official API
377
+ if not text or len(text) < 120:
378
+ return
379
+ key = f"act:{ident}"
380
+ key2 = key.replace("://www.", "://")
381
+ if key in seen or key2 in seen:
382
+ return
383
+ if size_hint and size_hint > MAX_PDF_BYTES:
384
+ return
385
+ seen.add(key)
386
+ seen.add(key2)
387
+ ident = re.sub(r"\W+", "-", (ident or _ident_from_url(url, title)).strip("-")).lower()[:160]
388
+ items.append((priority, ident, url, ts, size_hint, title, kind, text, meta or {}))
389
+
390
+
391
+ def _discover_acts(items, seen):
392
+ """Primary: official BOE ActFilter JSON with embedded HTML law text."""
393
+ for q in ACT_QUERIES:
394
+ data = _api_get("Filter/ActFilter", {"query": q})
395
+ if not data or not data.get("success"):
396
+ continue
397
+ n = 0
398
+ for act in data.get("content") or []:
399
+ aid = act.get("id")
400
+ if not aid:
401
+ continue
402
+ html = act.get("content") or ""
403
+ text = html_to_text(html)
404
+ summary = (act.get("summary") or "").strip()
405
+ legal = (act.get("legalNorm") or "").strip()
406
+ if len(text) < 200:
407
+ continue
408
+ if not TEXT_KEEP_RE.search(text[:8000]) and not TEXT_KEEP_RE.search(summary + " " + legal):
409
+ continue
410
+ # Prefer substantive instruments
411
+ pri = 18
412
+ blob = (summary + " " + legal + " " + text[:2000]).lower()
413
+ if re.search(r"constitui", blob):
414
+ pri = 4
415
+ elif re.search(r"c[oó]digo", blob):
416
+ pri = 6
417
+ elif re.search(r"\blei\b|decreto.?lei|decreto.?legislativo", blob):
418
+ pri = 8
419
+ elif re.search(r"regulamento|estatuto|portaria", blob):
420
+ pri = 12
421
+ title = summary or legal or f"Acto BOE {aid}"
422
+ title = re.sub(r"\s+", " ", title).strip()[:240]
423
+ source_url = f"https://boe.incv.cv/Bulletins/View/{aid}"
424
+ ident = f"boe-act-{aid}-{_ident_from_url(source_url, title)[:80]}"
425
+ _add(
426
+ items, seen, ident, source_url, ts=None, priority=pri,
427
+ title=title, kind="act", text=text,
428
+ meta={
429
+ "act_id": aid,
430
+ "is_full_text": act.get("isFullText"),
431
+ "query": q,
432
+ "legal_norm": legal[:500] if legal else None,
433
+ },
434
+ )
435
+ n += 1
436
+ log.info("actfilter q=%r hits=%s kept~%s overmax=%s", q, len(data.get("content") or []), n, data.get("overmax"))
437
+
438
+
439
+ def _discover_bo_pdfs(items, seen):
440
+ """Enumerate recent Boletim Oficial PDF downloads via Home API calendar."""
441
+ months_back = env_int("BO_MONTHS", 18)
442
+ today = date.today()
443
+ # walk month starts
444
+ y, m = today.year, today.month
445
+ for _ in range(months_back):
446
+ start = date(y, m, 1)
447
+ if m == 12:
448
+ end = date(y, 12, 31)
449
+ else:
450
+ end = date(y, m + 1, 1) - timedelta(days=1)
451
+ days = _api_get("Home/DaysWithPublications", {"start": start.isoformat(), "end": end.isoformat()})
452
+ content = (days or {}).get("content") or {}
453
+ # Cap days per month to keep lean
454
+ day_keys = sorted(content.keys(), reverse=True)[: env_int("BO_DAYS_PER_MONTH", 8)]
455
+ for day_key in day_keys:
456
+ day_s = day_key[:10]
457
+ for serie in (1, 2): # I Série priority, then II
458
+ bf = _api_get("Home/BulletinFilter", {"serie": serie, "date": day_s})
459
+ for b in (bf or {}).get("content") or []:
460
+ bid = b.get("id")
461
+ if not bid:
462
+ continue
463
+ number = b.get("number")
464
+ series = ((b.get("series") or {}).get("description")) or f"Série {serie}"
465
+ date_fmt = b.get("dateFormat") or day_s
466
+ title = f"Boletim Oficial n.º {number}, {series} de {date_fmt}"
467
+ if b.get("numberSup"):
468
+ title = (
469
+ f"Boletim Oficial n.º {number}, {b.get('numberSup')}.º Suplemento, "
470
+ f"{series} de {date_fmt}"
471
+ )
472
+ url = f"https://boe.incv.cv/Bulletins/Download/{bid}"
473
+ pri = 10 if serie == 1 else 16
474
+ _add(
475
+ items, seen, f"bo-{bid}-{number}-s{serie}", url,
476
+ ts=None, priority=pri, title=title, kind="pdf",
477
+ meta={"bulletin_id": bid, "serie": serie, "number": number},
478
+ )
479
+ # previous month
480
+ m -= 1
481
+ if m == 0:
482
+ m = 12
483
+ y -= 1
484
+ log.info("bo pdf candidates so far=%s", sum(1 for it in items if it[6] == "pdf"))
485
+
486
+
487
+ def discover():
488
+ items = []
489
+ seen = set()
490
+
491
+ for seed in SEED_PDFS:
492
+ _add(items, seen, _ident_from_url(seed), seed, ts=None, priority=9, title="Boletim Oficial seed")
493
+
494
+ _discover_acts(items, seen)
495
+ _discover_bo_pdfs(items, seen)
496
+
497
+ for home in HOMES:
498
+ try:
499
+ r = live_get(home, ua=UA, verify=False, timeout=(12, 40), retries=1)
500
+ if getattr(r, "status_code", 0) != 200:
501
+ log.info("home status=%s %s", getattr(r, "status_code", None), home)
502
+ continue
503
+ text = r.text or ""
504
+ if re.search(r"(?i)(celtabet|gambling|casino|bet365)", text[:2000]):
505
+ log.info("home compromised/skip %s", home)
506
+ continue
507
+ n = 0
508
+ for href in re.findall(r"""href=["']([^"']+)["']""", text, re.I):
509
+ full = urljoin(home, html_lib.unescape(href))
510
+ if ".pdf" in full.lower() or "/Bulletins/Download/" in full:
511
+ pri = 20
512
+ low = unquote(full).lower()
513
+ if re.search(r"(?i)(constitu)", low):
514
+ pri = 5
515
+ elif re.search(r"(?i)(lei|decreto|codigo|regulamento)", low):
516
+ pri = 12
517
+ elif _is_bo_pdf(full):
518
+ pri = 14
519
+ _add(items, seen, _ident_from_url(full), full, ts=None, priority=pri)
520
+ n += 1
521
+ for href in re.findall(r"(https?://[^\s\"'<>]+\.pdf)", text, re.I):
522
+ _add(items, seen, _ident_from_url(href), href, ts=None, priority=22)
523
+ n += 1
524
+ sub = []
525
+ for href in re.findall(r"""href=["']([^"']+)["']""", text, re.I):
526
+ full = urljoin(home, html_lib.unescape(href))
527
+ if not _host_ok(full):
528
+ continue
529
+ low = unquote(full).lower()
530
+ if any(
531
+ k in low
532
+ for k in (
533
+ "lei", "leis", "decreto", "constitu", "boletim", "legisl",
534
+ "documento", "download", "upload", "files", "regulamento",
535
+ "norma", "ficheiros", "codigo",
536
+ )
537
+ ):
538
+ if full not in sub and not low.endswith(".pdf"):
539
+ sub.append(full)
540
+ for sub_url in sub[:6]:
541
+ try:
542
+ r2 = live_get(sub_url, ua=UA, verify=False, timeout=(10, 30), retries=1)
543
+ if getattr(r2, "status_code", 0) != 200:
544
+ continue
545
+ t2 = r2.text or ""
546
+ for href in re.findall(r"""href=["']([^"']+)["']""", t2, re.I):
547
+ full = urljoin(sub_url, html_lib.unescape(href))
548
+ if ".pdf" in full.lower() or "/Bulletins/Download/" in full:
549
+ pri = 18
550
+ low = unquote(full).lower()
551
+ if re.search(r"(?i)(constitu)", low):
552
+ pri = 5
553
+ elif re.search(r"(?i)(lei|decreto|codigo)", low):
554
+ pri = 12
555
+ _add(items, seen, _ident_from_url(full), full, ts=None, priority=pri)
556
+ n += 1
557
+ except Exception as exc:
558
+ log.info("sub %s %s", sub_url[:80], exc)
559
+ log.info("home %s links=%s", home, n)
560
+ except Exception as exc:
561
+ log.info("home %s %s", home, exc)
562
+
563
+ for prefix in CDX_PREFIXES:
564
+ try:
565
+ hits = cdx_urls(
566
+ prefix,
567
+ limit=env_int("CDX_LIMIT", 120),
568
+ match_type="prefix",
569
+ extra_filters=["statuscode:200", "mimetype:application/pdf"],
570
+ ) or []
571
+ except Exception as exc:
572
+ log.info("cdx %s %s", prefix, exc)
573
+ hits = []
574
+ if len(hits) < 3:
575
+ try:
576
+ hits2 = cdx_urls(
577
+ prefix,
578
+ limit=env_int("CDX_LIMIT", 120),
579
+ match_type="prefix",
580
+ extra_filters=["statuscode:200"],
581
+ ) or []
582
+ for h in hits2:
583
+ orig = (h.get("original") or "").lower()
584
+ if ".pdf" in orig or "/bulletins/download/" in orig:
585
+ hits.append(h)
586
+ except Exception as exc:
587
+ log.info("cdx2 %s %s", prefix, exc)
588
+ for h in hits:
589
+ orig = h.get("original") or ""
590
+ ts = (h.get("timestamp") or "")[:14] or None
591
+ try:
592
+ length = int(h.get("length") or 0)
593
+ except Exception:
594
+ length = 0
595
+ if length and length > MAX_PDF_BYTES:
596
+ continue
597
+ if not _keep_pdf(orig):
598
+ continue
599
+ pri = 30
600
+ low = unquote(orig).lower()
601
+ if re.search(r"(?i)(constitu)", low):
602
+ pri = 5
603
+ elif _is_bo_pdf(orig):
604
+ pri = 15
605
+ elif re.search(r"(?i)(lei|codigo|regulamento)", low):
606
+ pri = 14
607
+ elif re.search(r"(?i)(decreto|diploma|resolu|portaria|despacho)", low):
608
+ pri = 22
609
+ _add(items, seen, _ident_from_url(orig), orig, ts=ts, priority=pri, size_hint=length or None)
610
+
611
+ items.sort(key=lambda x: (x[0], x[1]))
612
+ out = [
613
+ (ident, url, ts, size, title, kind, text, meta)
614
+ for _, ident, url, ts, size, title, kind, text, meta in items
615
+ ]
616
+ log.info("catalog %s (acts=%s pdfs=%s)", len(out), sum(1 for x in out if x[5] == "act"), sum(1 for x in out if x[5] == "pdf"))
617
+ return out
618
+
619
+
620
+ def main():
621
+ setup_log(CC)
622
+ t0 = utcnow()
623
+ max_new = env_int("MAX_NEW", 80)
624
+ max_seconds = env_int("MAX_SECONDS", 2400)
625
+ t_start = time.time()
626
+ done = existing_ids(CC)
627
+ already = len(done)
628
+ target_total = env_int("TARGET_TOTAL", 0)
629
+ ok = skip = fail = 0
630
+ for ident, url, ts, size_hint, title, kind, preset_text, meta in discover():
631
+ if max_new and ok >= max_new:
632
+ break
633
+ if target_total and (already + ok) >= target_total:
634
+ break
635
+ if time.time() - t_start > max_seconds:
636
+ break
637
+ if size_hint and size_hint > MAX_PDF_BYTES:
638
+ skip += 1
639
+ continue
640
+ rid = slug_id(CC, ident)
641
+ if rid in done:
642
+ skip += 1
643
+ continue
644
+ if url and not _host_ok(url):
645
+ fail += 1
646
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "host_not_cv"})
647
+ continue
648
+
649
+ if kind == "act" and preset_text:
650
+ text = preset_text
651
+ method = "boe_actfilter_html"
652
+ got = {"status": "success", "method": method, "text": text}
653
+ else:
654
+ got = fetch_cv(url, wayback_ts=ts)
655
+ text = got.get("text") or ""
656
+ method = got.get("method")
657
+
658
+ if got.get("status") != "success":
659
+ fail += 1
660
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error"), "wayback_ts": ts})
661
+ continue
662
+ if len(text) > 2_500_000:
663
+ log.info("skip huge text chars=%s %s", len(text), ident[:50])
664
+ fail += 1
665
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_too_large", "chars": len(text)})
666
+ continue
667
+ if not TEXT_KEEP_RE.search(text[:8000]) and not _is_bo_pdf(url or ""):
668
+ if not re.search(r"(?i)(lei|decreto|constitu|codigo|regulamento|diploma|boletim|acord)", ident):
669
+ fail += 1
670
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_not_legal"})
671
+ continue
672
+ use_title = title
673
+ if not use_title:
674
+ for line in text.splitlines():
675
+ if len(line.strip()) > 18:
676
+ use_title = line.strip()[:240]
677
+ break
678
+ if save_instrument(
679
+ cc=CC, country=COUNTRY, language=LANG, ident=ident,
680
+ title=use_title or ident, text=text, source_url=url or f"https://boe.incv.cv/",
681
+ source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_cv.py",
682
+ article_re=ART,
683
+ extra_meta={
684
+ "fetch_method": method,
685
+ "wayback_ts": ts,
686
+ "size_hint": size_hint,
687
+ **(meta or {}),
688
+ },
689
+ ):
690
+ ok += 1
691
+ done.add(rid)
692
+ log.info("ok %s method=%s chars=%s ts=%s", ident[:60], method, len(text), ts)
693
+ else:
694
+ fail += 1
695
+ write_summary(
696
+ CC, country=COUNTRY,
697
+ source="Cabo Verde Boletim Oficial / Laws (boe.incv.cv / governo.cv / parlamento.cv / justica.gov.cv / mf.gov.cv)",
698
+ source_urls=[
699
+ "https://boe.incv.cv/",
700
+ "https://incv.cv/",
701
+ "https://www.governo.cv/",
702
+ "https://www.parlamento.cv/",
703
+ "https://justica.gov.cv/",
704
+ "https://www.mf.gov.cv/",
705
+ "https://www.gov.cv/",
706
+ "https://www.bcv.cv/",
707
+ "https://www.tribunalconstitucional.cv/",
708
+ ],
709
+ license_text=LICENSE, discovered=ok + skip + fail, fetched=ok, skipped=skip, failed=fail,
710
+ coverage="catalog-backed incomplete (BOE ActFilter HTML + BO PDF downloads + live/CDX *.cv / *.gov.cv)",
711
+ notes=(
712
+ "Official *.cv / *.gov.cv lei/decreto/constituição / Boletim Oficial only "
713
+ "(Cabo Verde). Primary: boe.incv.cv /api/v1 ActFilter + Bulletin Download. "
714
+ "OCR por+fra+spa for scans. Not AfricanLII. No WAF bypass. Not legal advice. "
715
+ "cv=Cabo Verde (not Portugal/pt, not Angola/ao, not São Tomé/st)."
716
+ ),
717
+ last_run=t0,
718
+ )
719
+ log.info("done ok=%s skip=%s fail=%s total_instruments=%s", ok, skip, fail, len(done))
720
+
721
+
722
+ if __name__ == "__main__":
723
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import traceback
14
+ from collections import Counter
15
+ from datetime import datetime, timezone, timedelta
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Any, Iterable, Optional
19
+ from xml.etree import ElementTree as ET
20
+
21
+ import requests
22
+ from requests.adapters import HTTPAdapter
23
+
24
+ ROOT = Path("/workspace/legal-corpora")
25
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
26
+ PT = timezone(timedelta(hours=-7))
27
+ DEFAULT_UA = (
28
+ "legal-corpora-collector/1.0 "
29
+ "(research archive of official national gazettes; polite; "
30
+ "no commercial scraping; contact via local operator)"
31
+ )
32
+ INDEX_FIELDS = (
33
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
34
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
35
+ "article_count", "bytes",
36
+ )
37
+
38
+ _tls = threading.local()
39
+ _index_lock = threading.Lock()
40
+ _fail_lock = threading.Lock()
41
+ _schema = None
42
+ _schema_lock = threading.Lock()
43
+
44
+
45
+ def utcnow() -> str:
46
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
47
+
48
+
49
+ def pt_from_iso(iso: str) -> str:
50
+ try:
51
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
52
+ except Exception:
53
+ return iso
54
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
55
+
56
+
57
+ def localtag(tag: str) -> str:
58
+ return tag.rsplit("}", 1)[-1]
59
+
60
+
61
+ def slug_id(cc: str, official: str) -> str:
62
+ s = (official or "").strip()
63
+ s = s.replace("https://", "").replace("http://", "")
64
+ s = re.sub(r"[/\\]+", "__", s)
65
+ s = re.sub(r"\s+", "_", s)
66
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
67
+ s = s.strip("-._")
68
+ if not s:
69
+ s = "unknown"
70
+ s = s.lower()
71
+ if not s.startswith(cc.lower() + "-"):
72
+ s = f"{cc.lower()}-{s}"
73
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
74
+ s = "x" + s
75
+ return s[:180]
76
+
77
+
78
+ def atomic_write(path: Path, text: str) -> None:
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
81
+ try:
82
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
83
+ handle.write(text)
84
+ os.replace(tmp, path)
85
+ except Exception:
86
+ try:
87
+ os.unlink(tmp)
88
+ except OSError:
89
+ pass
90
+ raise
91
+
92
+
93
+ def sha256_text(s: str) -> str:
94
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
95
+
96
+
97
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
98
+ s = getattr(_tls, "session", None)
99
+ if s is None or getattr(_tls, "ua", None) != ua:
100
+ s = requests.Session()
101
+ s.headers.update({
102
+ "User-Agent": ua,
103
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
104
+ "Accept-Language": "en,*;q=0.8",
105
+ })
106
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
107
+ s.mount("https://", ad)
108
+ s.mount("http://", ad)
109
+ _tls.session = s
110
+ _tls.ua = ua
111
+ return s
112
+
113
+
114
+ def http_get(
115
+ url: str,
116
+ *,
117
+ ua: str = DEFAULT_UA,
118
+ timeout: tuple = (20, 90),
119
+ retries: int = 5,
120
+ sleep: float = 0.35,
121
+ headers: Optional[dict] = None,
122
+ params: Optional[dict] = None,
123
+ allow_empty: bool = False,
124
+ ) -> requests.Response:
125
+ last = None
126
+ hdrs = headers or {}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ if sleep:
130
+ time.sleep(sleep)
131
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
132
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
133
+ time.sleep(min(30, 2 ** attempt))
134
+ last = resp
135
+ continue
136
+ if resp.status_code == 200 and (allow_empty or resp.content):
137
+ return resp
138
+ if resp.status_code in (404, 410, 403, 401):
139
+ return resp
140
+ last = resp
141
+ if attempt < retries:
142
+ time.sleep(min(20, 1.5 * attempt))
143
+ continue
144
+ return resp
145
+ except requests.RequestException as exc:
146
+ last = exc
147
+ time.sleep(min(20, 1.5 * attempt))
148
+ if isinstance(last, requests.Response):
149
+ return last
150
+ raise RuntimeError(f"GET failed {url}: {last}")
151
+
152
+
153
+ class _HTMLText(HTMLParser):
154
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
155
+
156
+ def __init__(self) -> None:
157
+ super().__init__(convert_charrefs=True)
158
+ self.parts: list[str] = []
159
+ self.skip = 0
160
+ self._block = {
161
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
162
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
163
+ }
164
+
165
+ def handle_starttag(self, tag, attrs):
166
+ if tag in self.SKIP:
167
+ self.skip += 1
168
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
169
+ self.parts.append("\n")
170
+
171
+ def handle_endtag(self, tag):
172
+ if tag in self.SKIP and self.skip:
173
+ self.skip -= 1
174
+ if tag in self._block and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_data(self, data):
178
+ if self.skip == 0:
179
+ self.parts.append(data)
180
+
181
+
182
+ def html_to_text(raw: str) -> str:
183
+ if not raw:
184
+ return ""
185
+ p = _HTMLText()
186
+ try:
187
+ p.feed(raw)
188
+ p.close()
189
+ except Exception:
190
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
191
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
192
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
193
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
194
+ text = "".join(p.parts)
195
+ text = html.unescape(text)
196
+ text = text.replace("\xa0", " ")
197
+ text = re.sub(r"[ \t]+", " ", text)
198
+ text = re.sub(r"\n[ \t]+", "\n", text)
199
+ text = re.sub(r"\n{3,}", "\n\n", text)
200
+ return text.strip()
201
+
202
+
203
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
204
+ skip_tags = skip_tags or {
205
+ "meta", "identification", "references", "classification",
206
+ "workflow", "analysis", "proprietary", "presentation",
207
+ }
208
+ try:
209
+ root = ET.fromstring(raw)
210
+ except ET.ParseError:
211
+ return html_to_text(raw)
212
+ parts: list[str] = []
213
+
214
+ def walk(el: ET.Element) -> None:
215
+ tag = localtag(el.tag).lower()
216
+ if tag in skip_tags:
217
+ return
218
+ if el.text and el.text.strip():
219
+ parts.append(el.text.strip())
220
+ for child in list(el):
221
+ walk(child)
222
+ if child.tail and child.tail.strip():
223
+ parts.append(child.tail.strip())
224
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
225
+ parts.append("\n")
226
+
227
+ walk(root)
228
+ text = " ".join(parts)
229
+ text = re.sub(r"[ \t]+", " ", text)
230
+ text = re.sub(r" *\n *", "\n", text)
231
+ text = re.sub(r"\n{3,}", "\n\n", text)
232
+ return text.strip()
233
+
234
+
235
+ ARTICLE_SPLIT = re.compile(
236
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
237
+ r"artigo|artículo|artykuł|art\.|str\.|para(?:graph)?\.?|szakasz)\s+"
238
+ r"[\dIVXLCDM]+[a-zA-Z]?)\b"
239
+ )
240
+
241
+
242
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
243
+ if not text or len(text) < 40:
244
+ return []
245
+ matches = list(ARTICLE_SPLIT.finditer(text))
246
+ if len(matches) < 2:
247
+ return []
248
+ docs = []
249
+ for i, m in enumerate(matches):
250
+ start = m.start()
251
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
252
+ chunk = text[start:end].strip()
253
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
254
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
255
+ heading = chunk.split("\n", 1)[0][:200]
256
+ docs.append({
257
+ "id": f"{law_id}-{aid}"[:180],
258
+ "title": heading,
259
+ "text": chunk,
260
+ "date_filed": date,
261
+ "document_number": num,
262
+ "source_url": source_url,
263
+ "record_type": "article",
264
+ "article_number": num,
265
+ "law_identifier": law_id,
266
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
267
+ })
268
+ if len(docs) >= 4000:
269
+ break
270
+ return docs
271
+
272
+
273
+ def load_schema():
274
+ global _schema
275
+ with _schema_lock:
276
+ if _schema is None:
277
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
278
+ _schema = json.load(f)
279
+ return _schema
280
+
281
+
282
+ def validate_record(record: dict) -> Optional[str]:
283
+ try:
284
+ import jsonschema
285
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
286
+ return None
287
+ except Exception as exc:
288
+ return str(exc)
289
+
290
+
291
+ def existing_ids(cc: str) -> set[str]:
292
+ d = ROOT / cc / "instruments"
293
+ if not d.exists():
294
+ return set()
295
+ return {p.stem for p in d.glob("*.json")}
296
+
297
+
298
+ def write_instrument(cc: str, record: dict) -> Path:
299
+ ident = record["id"]
300
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
301
+ dest.parent.mkdir(parents=True, exist_ok=True)
302
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
303
+ atomic_write(dest, body)
304
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
305
+ index_line["path"] = f"instruments/{ident}.json"
306
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
307
+ index_line["bytes"] = dest.stat().st_size
308
+ index_line["id"] = ident
309
+ with _index_lock:
310
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
311
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
312
+ return dest
313
+
314
+
315
+ def log_failure(cc: str, payload: dict) -> None:
316
+ path = ROOT / cc / "failures.jsonl"
317
+ path.parent.mkdir(parents=True, exist_ok=True)
318
+ payload = dict(payload)
319
+ payload.setdefault("retrieved_at", utcnow())
320
+ with _fail_lock:
321
+ with path.open("a", encoding="utf-8") as handle:
322
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
323
+
324
+
325
+ def append_catalog(cc: str, row: dict) -> None:
326
+ path = ROOT / cc / "raw" / "catalog.jsonl"
327
+ path.parent.mkdir(parents=True, exist_ok=True)
328
+ with _index_lock:
329
+ with path.open("a", encoding="utf-8") as handle:
330
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
331
+
332
+
333
+ def law_status_hist(cc: str) -> Counter:
334
+ c: Counter = Counter()
335
+ d = ROOT / cc / "instruments"
336
+ if not d.exists():
337
+ return c
338
+ for p in d.glob("*.json"):
339
+ try:
340
+ rec = json.loads(p.read_text(encoding="utf-8"))
341
+ c[rec.get("law_status") or "unknown"] += 1
342
+ except Exception:
343
+ c["unknown"] += 1
344
+ return c
345
+
346
+
347
+ def corpus_bytes(cc: str) -> int:
348
+ d = ROOT / cc / "instruments"
349
+ if not d.exists():
350
+ return 0
351
+ return sum(p.stat().st_size for p in d.glob("*.json"))
352
+
353
+
354
+ def count_jsonl(path: Path) -> int:
355
+ if not path.exists():
356
+ return 0
357
+ n = 0
358
+ with path.open(encoding="utf-8") as f:
359
+ for _ in f:
360
+ n += 1
361
+ return n
362
+
363
+
364
+ def write_summary(
365
+ cc: str,
366
+ *,
367
+ country: str,
368
+ source: str,
369
+ source_urls: Iterable[str],
370
+ license_text: str,
371
+ discovered: int,
372
+ fetched: int,
373
+ skipped: int,
374
+ failed: int,
375
+ coverage: str,
376
+ notes: str,
377
+ last_run: Optional[str] = None,
378
+ extra: Optional[str] = None,
379
+ ) -> None:
380
+ last_run = last_run or utcnow()
381
+ instr = ROOT / cc / "instruments"
382
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
383
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
384
+ hist = law_status_hist(cc)
385
+ nbytes = corpus_bytes(cc)
386
+ lines = [
387
+ f"# {country} legislation corpus",
388
+ "",
389
+ f"- jurisdiction: {cc.upper()}",
390
+ f"- source: {source}",
391
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
392
+ f"- instruments_json: {n_json}",
393
+ f"- index_jsonl_lines: {n_index}",
394
+ f"- discovered: {discovered}",
395
+ f"- fetched: {fetched}",
396
+ f"- skipped: {skipped}",
397
+ f"- failed: {failed}",
398
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
399
+ f"- coverage: {coverage}",
400
+ f"- total_json_bytes: {nbytes}",
401
+ f"- license: {license_text}",
402
+ "- source_urls:",
403
+ ]
404
+ for u in source_urls:
405
+ lines.append(f" - {u}")
406
+ lines.append("- notes:")
407
+ for n in (notes or "").splitlines():
408
+ lines.append(f" {n}")
409
+ if extra:
410
+ lines.append("")
411
+ lines.append(extra)
412
+ lines.append("")
413
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
414
+
415
+
416
+ def base_record(
417
+ *,
418
+ cc: str,
419
+ country: str,
420
+ language: str,
421
+ ident: str,
422
+ title: str,
423
+ text: str,
424
+ source_url: str,
425
+ source_type: str,
426
+ license_text: str,
427
+ collector: str,
428
+ eli: Optional[str] = None,
429
+ date: Optional[str] = None,
430
+ official_identifier: Optional[str] = None,
431
+ document_type: str = "statute",
432
+ law_status: str = "current",
433
+ is_current: Optional[bool] = True,
434
+ documents: Optional[list] = None,
435
+ extra_meta: Optional[dict] = None,
436
+ extra_fields: Optional[dict] = None,
437
+ ) -> dict:
438
+ rid = slug_id(cc, ident)
439
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
440
+ rec = {
441
+ "schema_version": "collection_record.v1",
442
+ "record_type": "law",
443
+ "id": rid,
444
+ "title": title or ident,
445
+ "text": text or "",
446
+ "source_url": source_url,
447
+ "source_type": source_type,
448
+ "date": date,
449
+ "jurisdiction": cc.upper(),
450
+ "country": country,
451
+ "language": language,
452
+ "eli": eli,
453
+ "license": license_text,
454
+ "retrieved_at": utcnow(),
455
+ "identifier": official_identifier or ident,
456
+ "official_identifier": official_identifier or ident,
457
+ "law_identifier": official_identifier or ident,
458
+ "document_type": document_type,
459
+ "law_status": law_status,
460
+ "is_current": is_current,
461
+ "canonical_law_url": source_url,
462
+ "article_count": len(docs),
463
+ "article_extraction_status": "ok" if docs else "missing",
464
+ "documents": docs,
465
+ "metadata": {
466
+ "collector": collector,
467
+ "schema": "collection_record.v1",
468
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
469
+ "content_sha256": sha256_text(text or ""),
470
+ "rights": {
471
+ "not_legal_advice": True,
472
+ "official_reuse_url": source_url,
473
+ "license": license_text,
474
+ },
475
+ "text_extraction": {"source": "official", "backend": "collector"},
476
+ },
477
+ }
478
+ if extra_meta:
479
+ rec["metadata"].update(extra_meta)
480
+ if extra_fields:
481
+ rec.update(extra_fields)
482
+ return rec
483
+
484
+
485
+ def ensure_dirs(cc: str) -> Path:
486
+ root = ROOT / cc
487
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
488
+ (root / "raw").mkdir(parents=True, exist_ok=True)
489
+ (root / "logs").mkdir(parents=True, exist_ok=True)
490
+ return root
491
+
492
+
493
+ def iso_date(val: Optional[str]) -> Optional[str]:
494
+ if not val:
495
+ return None
496
+ val = str(val).strip()
497
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
498
+ if m:
499
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
500
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
501
+ if m:
502
+ return m.group(1)
503
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
504
+ if m:
505
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
506
+ return None
507
+
508
+
509
+ def pdf_bytes_to_text(raw: bytes, timeout: int = 180) -> str:
510
+ """Extract text from PDF bytes via pdftotext. Empty on failure."""
511
+ import subprocess
512
+ if not raw:
513
+ return ""
514
+ if raw[:4] != b"%PDF":
515
+ idx = raw.find(b"%PDF", 0, 8192)
516
+ if idx < 0:
517
+ return ""
518
+ raw = raw[idx:]
519
+ try:
520
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
521
+ tmp.write(raw)
522
+ tmp.flush()
523
+ proc = subprocess.run(
524
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
525
+ check=False, capture_output=True, timeout=timeout,
526
+ )
527
+ if proc.returncode == 0 and proc.stdout:
528
+ return proc.stdout.decode("utf-8", "replace").strip()
529
+ except Exception:
530
+ return ""
531
+ return ""
scrapers/pdf_extract_lib.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PDF text extraction helpers mirroring ipfs_datasets_py IntegratedPDFProcessor.
3
+
4
+ Prefer pdfplumber -> pymupdf -> pdftotext; OCR (tesseract) only when text layer
5
+ is missing or garbage. Honest article splits require >=2 heading matches.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import logging
11
+ import re
12
+ import subprocess
13
+ import tempfile
14
+ from typing import Optional
15
+
16
+ log = logging.getLogger("pdf_extract_lib")
17
+
18
+ # Spaced-out OCR garbage like "D IA R IO"
19
+ _GARBAGE_SPACING = re.compile(r"(?:^[A-Za-z]\s+){6,}", re.M)
20
+
21
+
22
+ def is_garbage_text(text: str) -> bool:
23
+ if not text or len(text) < 40:
24
+ return True
25
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
26
+ return True
27
+ if "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:
28
+ return True
29
+ sample = text[:8000]
30
+ # Broken ToUnicode / CID font dumps from Arabic/Persian PDFs
31
+ if sample.count("(cid:") >= 8:
32
+ return True
33
+ arabic = sum(1 for ch in sample if "\u0600" <= ch <= "\u06FF")
34
+ ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t\x0c")
35
+ n = max(1, len(sample))
36
+ # Encoding-corrupt Arabic/Persian PDFs: many controls / almost no Arabic script
37
+ if len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05:
38
+ return True
39
+ if len(sample) > 800 and arabic < 80 and sample.count("@") > 30:
40
+ return True
41
+ letters = sum(ch.isalpha() for ch in sample)
42
+ spaces = sample.count(" ")
43
+ if letters < 80 and arabic < 40:
44
+ return True
45
+ # Mojibake Latin stand-in for Arabic (common in old MoJ PDFs)
46
+ ascii_letters = sum(ch.isalpha() and ord(ch) < 128 for ch in sample)
47
+ if len(sample) > 500 and arabic < 20 and ascii_letters > 400:
48
+ return True
49
+ if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):
50
+ return True
51
+ singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))
52
+ if singles > 30 and singles > letters * 0.15:
53
+ return True
54
+ return False
55
+
56
+
57
+ def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
58
+ import pdfplumber
59
+ with pdfplumber.open(io.BytesIO(raw)) as pdf:
60
+ n = len(pdf.pages)
61
+ parts = []
62
+ for page in pdf.pages[:max_pages]:
63
+ try:
64
+ parts.append(page.extract_text() or "")
65
+ except Exception:
66
+ continue
67
+ text = "\n".join(parts)
68
+ text = re.sub(r"[ \t]+", " ", text)
69
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
70
+ return text, n
71
+
72
+
73
+ def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
74
+ import pymupdf
75
+ doc = pymupdf.open(stream=raw, filetype="pdf")
76
+ n = doc.page_count
77
+ parts = [page.get_text() for page in doc[:max_pages]]
78
+ text = "\n".join(parts)
79
+ text = re.sub(r"[ \t]+", " ", text)
80
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
81
+ return text, n
82
+
83
+
84
+ def extract_pdftotext(raw: bytes) -> str:
85
+ if not raw or raw[:4] != b"%PDF":
86
+ return ""
87
+ try:
88
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
89
+ tmp.write(raw)
90
+ tmp.flush()
91
+ proc = subprocess.run(
92
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
93
+ check=False, capture_output=True, timeout=180,
94
+ )
95
+ if proc.returncode == 0 and proc.stdout:
96
+ return proc.stdout.decode("utf-8", "replace").strip()
97
+ except Exception as exc:
98
+ log.warning("pdftotext: %s", exc)
99
+ return ""
100
+
101
+
102
+ def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]:
103
+ """Render pages with pymupdf and OCR via tesseract CLI."""
104
+ import pymupdf
105
+ doc = pymupdf.open(stream=raw, filetype="pdf")
106
+ n = doc.page_count
107
+ parts = []
108
+ mat = pymupdf.Matrix(dpi / 72, dpi / 72)
109
+ for i, page in enumerate(doc):
110
+ if i >= max_pages:
111
+ break
112
+ pix = page.get_pixmap(matrix=mat, alpha=False)
113
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img:
114
+ pix.save(img.name)
115
+ img_path = img.name
116
+ try:
117
+ env = dict(**__import__("os").environ)
118
+ env["OMP_THREAD_LIMIT"] = "1"
119
+ env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata")
120
+ proc = subprocess.run(
121
+ ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"],
122
+ capture_output=True, text=True, timeout=180, env=env,
123
+ )
124
+ if proc.returncode == 0 and proc.stdout:
125
+ parts.append(proc.stdout)
126
+ except Exception as exc:
127
+ log.debug("ocr page %s: %s", i, exc)
128
+ finally:
129
+ try:
130
+ import os
131
+ os.unlink(img_path)
132
+ except Exception:
133
+ pass
134
+ text = "\n".join(parts)
135
+ text = re.sub(r"[ \t]+", " ", text)
136
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
137
+ return text, n
138
+
139
+
140
+ def extract_pdf_text(
141
+ raw: bytes,
142
+ *,
143
+ enable_ocr: bool = True,
144
+ ocr_lang: str = "eng",
145
+ ocr_max_pages: int = 40,
146
+ ) -> tuple[str, str, int]:
147
+ """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order."""
148
+ if not raw:
149
+ return "", "not_pdf", 0
150
+ if raw[:4] != b"%PDF":
151
+ idx = raw.find(b"%PDF", 0, 65536)
152
+ if idx < 0:
153
+ return "", "not_pdf", 0
154
+ raw = raw[idx:]
155
+ best_text, best_method, pages = "", "failed", 0
156
+ for name, fn in (
157
+ ("pdfplumber", lambda: extract_pdfplumber(raw)),
158
+ ("pymupdf", lambda: extract_pymupdf(raw)),
159
+ ):
160
+ try:
161
+ text, pages = fn()
162
+ if text and not is_garbage_text(text) and len(text) >= 80:
163
+ return text, name, pages
164
+ if len(text) > len(best_text):
165
+ best_text, best_method = text, name
166
+ except Exception as exc:
167
+ log.debug("%s failed: %s", name, exc)
168
+ try:
169
+ text = extract_pdftotext(raw)
170
+ if text and not is_garbage_text(text) and len(text) >= 80:
171
+ return text, "pdftotext", pages
172
+ if len(text) > len(best_text):
173
+ best_text, best_method = text, "pdftotext"
174
+ except Exception:
175
+ pass
176
+ if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120):
177
+ try:
178
+ text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages)
179
+ if text and len(text) >= 80 and not is_garbage_text(text):
180
+ return text, "ocr_tesseract", pages
181
+ if len(text) > len(best_text):
182
+ best_text, best_method = text, "ocr_tesseract"
183
+ except Exception as exc:
184
+ log.debug("ocr failed: %s", exc)
185
+ return best_text, best_method if best_text else "failed", pages
186
+
187
+
188
+ def normalize_bidi(text: str) -> str:
189
+ return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200c\u200d\ufeff]", "", text or "")
190
+
191
+
192
+ _EASTERN_DIGITS = str.maketrans(
193
+ "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669"
194
+ "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9",
195
+ "01234567890123456789",
196
+ )
197
+
198
+
199
+ def normalize_rtl_text(text: str) -> str:
200
+ """Strip bidi marks and map Arabic/Persian digits to ASCII for heading regexes."""
201
+ t = normalize_bidi(text or "")
202
+ t = re.sub(r"[\u00ad\u200b]", "", t)
203
+ return t.translate(_EASTERN_DIGITS)
204
+
205
+
206
+
207
+ def split_by_pattern(
208
+ text: str,
209
+ law_id: str,
210
+ source_url: str,
211
+ pat: re.Pattern,
212
+ record_type: str = "article",
213
+ min_chunk: int = 40,
214
+ max_docs: int = 4000,
215
+ ) -> list[dict]:
216
+ matches = list(pat.finditer(text or ""))
217
+ if len(matches) < 2:
218
+ return []
219
+ docs = []
220
+ for i, m in enumerate(matches):
221
+ start = m.start()
222
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
223
+ chunk = text[start:end].strip()
224
+ if len(chunk) < min_chunk:
225
+ continue
226
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
227
+ aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80]
228
+ heading = chunk.split("\n", 1)[0][:200]
229
+ docs.append({
230
+ "id": f"{law_id}-{aid}"[:180],
231
+ "title": heading,
232
+ "text": chunk,
233
+ "date_filed": None,
234
+ "document_number": num,
235
+ "source_url": source_url,
236
+ "record_type": record_type,
237
+ "article_number": num,
238
+ "law_identifier": law_id,
239
+ "metadata": {
240
+ "text_extraction": {
241
+ "source": "official",
242
+ "backend": "honest_heading_split",
243
+ "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split",
244
+ "pattern": pat.pattern[:100],
245
+ }
246
+ },
247
+ })
248
+ if len(docs) >= max_docs:
249
+ break
250
+ return docs if len(docs) >= 2 else []
251
+
252
+
253
+ # Country-specific honest patterns (tried in order)
254
+ COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = {
255
+ "sv": [
256
+ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"),
257
+ ],
258
+ "tn": [
259
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"),
260
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
261
+ ],
262
+ "et": [
263
+ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"),
264
+ ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
265
+ ("article_inline", re.compile(r"(?im)((?:Article|Art\.)\s+\d+)(?![\d])"), "article"),
266
+ ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"),
267
+ ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"),
268
+ ],
269
+ "jm": [
270
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"),
271
+ ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"),
272
+ ],
273
+ "fj": [
274
+ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"),
275
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"),
276
+ ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"),
277
+ ],
278
+ "la": [
279
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"),
280
+ ],
281
+ "lk": [
282
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"),
283
+ ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"),
284
+ ],
285
+ "md": [
286
+ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"),
287
+ ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"),
288
+ ],
289
+ "iq": [
290
+ ("mada", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:]*\s*\d+)(?!\d)"), "article"),
291
+ ("mada_ocr", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:\s]*\d+)(?!\d)"), "article"),
292
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|الباب)\s+\S+)"), "section"),
293
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
294
+ ],
295
+ "ir": [
296
+ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"),
297
+ ("mada_prefixed", re.compile(
298
+ r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)"
299
+ ), "article"),
300
+ ("fasl_bab", re.compile(
301
+ r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))"
302
+ ), "section"),
303
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
304
+ ],
305
+ "mz": [
306
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
307
+ ],
308
+ }
309
+
310
+
311
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
312
+ if cc in ("tn", "iq", "ir", "dz", "lb", "ma", "eg", "sa", "ae"):
313
+ text_n = normalize_rtl_text(text)
314
+ else:
315
+ text_n = text
316
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
317
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
318
+ if docs:
319
+ return docs, name
320
+ # shared fallback
321
+ from common import split_articles
322
+ docs = split_articles(text_n, law_id, source_url)
323
+ if len(docs) >= 2:
324
+ return docs, "common_article_split"
325
+ return [], "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for new-country official gazette collectors."""
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import time
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Optional
14
+ from urllib.parse import urljoin, urlparse
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ from common import (
18
+ ROOT,
19
+ DEFAULT_UA,
20
+ base_record,
21
+ ensure_dirs,
22
+ existing_ids,
23
+ html_to_text,
24
+ http_get,
25
+ iso_date,
26
+ log_failure,
27
+ slug_id,
28
+ split_articles,
29
+ utcnow,
30
+ write_instrument,
31
+ write_summary,
32
+ )
33
+ import archive_fallbacks as af
34
+
35
+ log = logging.getLogger("world_lib")
36
+
37
+ MIN_TEXT = 80
38
+ MAX_PDF = 35 * 1024 * 1024
39
+
40
+
41
+ def setup_log(cc: str, name: str | None = None) -> None:
42
+ ensure_dirs(cc)
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s %(levelname)s %(message)s",
46
+ handlers=[
47
+ logging.FileHandler(ROOT / cc / "logs" / "collector.log", encoding="utf-8"),
48
+ logging.StreamHandler(sys.stdout),
49
+ ],
50
+ force=True,
51
+ )
52
+
53
+
54
+ def pdf_to_text(raw: bytes) -> str:
55
+ if not raw or raw[:4] != b"%PDF":
56
+ return ""
57
+ try:
58
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
59
+ tmp.write(raw)
60
+ tmp.flush()
61
+ proc = subprocess.run(
62
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
63
+ check=False,
64
+ capture_output=True,
65
+ timeout=180,
66
+ )
67
+ if proc.returncode == 0 and proc.stdout:
68
+ return proc.stdout.decode("utf-8", "replace").strip()
69
+ except Exception as exc:
70
+ log.warning("pdftotext: %s", exc)
71
+ return ""
72
+
73
+
74
+ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]:
75
+ docs = split_articles(text, law_id, source_url, date)
76
+ if not pattern:
77
+ return docs
78
+ matches = list(pattern.finditer(text or ""))
79
+ if len(matches) < 2:
80
+ return docs if len(docs) >= 2 else []
81
+ out = []
82
+ for i, m in enumerate(matches):
83
+ start = m.start()
84
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
85
+ chunk = text[start:end].strip()
86
+ if len(chunk) < 20:
87
+ continue
88
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
89
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]
90
+ heading = chunk.split("\n", 1)[0][:200]
91
+ out.append({
92
+ "id": f"{law_id}-{aid}"[:180],
93
+ "title": heading,
94
+ "text": chunk,
95
+ "date_filed": date,
96
+ "document_number": num,
97
+ "source_url": source_url,
98
+ "record_type": "article",
99
+ "article_number": num,
100
+ "law_identifier": law_id,
101
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
102
+ })
103
+ if len(out) >= 4000:
104
+ break
105
+ return out if len(out) >= 2 else docs
106
+
107
+
108
+
109
+ def normalize_official_url(url: str) -> str:
110
+ """Fix CDX quirks: https://host:80/... breaks TLS (WRONG_VERSION_NUMBER)."""
111
+ if not url:
112
+ return url
113
+ url = url.replace("http://", "https://", 1) if "lawcommission.gov.np" in url and url.startswith("http://") else url
114
+ url = url.replace("https://www.lawcommission.gov.np:80/", "https://www.lawcommission.gov.np/")
115
+ url = url.replace("https://lawcommission.gov.np:80/", "https://lawcommission.gov.np/")
116
+ url = url.replace(":80/", "/") if url.startswith("https://") and ":80/" in url else url
117
+ url = url.replace(":80?", "?") if url.startswith("https://") and ":80?" in url else url
118
+ return url
119
+
120
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
121
+ url = normalize_official_url(url)
122
+ import requests
123
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
124
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
125
+ last = None
126
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ time.sleep(0.2)
130
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
131
+ return resp
132
+ except Exception as exc:
133
+ last = exc
134
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
135
+ try:
136
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
137
+ return resp
138
+ except Exception as exc2:
139
+ last = exc2
140
+ time.sleep(min(8, 1.5 * attempt))
141
+ raise RuntimeError(f"live_get failed {url}: {last}")
142
+
143
+
144
+ def fetch_official(
145
+ url: str,
146
+ *,
147
+ ua: str = DEFAULT_UA,
148
+ verify: bool = True,
149
+ wayback: bool = True,
150
+ wayback_ts: Optional[str] = None,
151
+ min_text: int = MIN_TEXT,
152
+ ) -> dict:
153
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
154
+ url = normalize_official_url(url)
155
+ out = {
156
+ "status": "error",
157
+ "text": "",
158
+ "content": b"",
159
+ "source_url": url,
160
+ "method": "",
161
+ "content_type": "",
162
+ "error": "",
163
+ }
164
+ body = b""
165
+ ctype = ""
166
+ try:
167
+ r = live_get(url, ua=ua, verify=verify)
168
+ body = r.content or b""
169
+ ctype = r.headers.get("content-type") or ""
170
+ if r.status_code == 200 and body:
171
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
172
+ text = pdf_to_text(body)
173
+ if len(text) >= min_text:
174
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
175
+ return out
176
+ text = ""
177
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
178
+ raw = body.decode(r.encoding or "utf-8", "replace")
179
+ if af.is_challenge(raw, r.status_code):
180
+ out["error"] = "challenge_or_shell"
181
+ else:
182
+ text = html_to_text(raw) if "<" in raw[:500] else raw
183
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
184
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
185
+ return out
186
+ if len(text) < min_text:
187
+ out["error"] = "short_or_spa"
188
+ elif body[:4] == b"%PDF":
189
+ out["error"] = "pdf_extract_failed"
190
+ elif len(body) > min_text:
191
+ try:
192
+ text = body.decode("utf-8", "replace")
193
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
194
+ out["error"] = "raw_pdf_bytes"
195
+ elif len(text) >= min_text:
196
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
197
+ return out
198
+ except Exception:
199
+ pass
200
+ else:
201
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
202
+ except Exception as exc:
203
+ out["error"] = f"live:{exc}"
204
+
205
+ if wayback:
206
+ try:
207
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
208
+ if w.get("status") == "success":
209
+ raw_b = w.get("content") or b""
210
+ raw_t = w.get("text") or ""
211
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
212
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
213
+ text = pdf_to_text(pdf_bytes)
214
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
215
+ out.update(
216
+ status="success",
217
+ text=text,
218
+ content=pdf_bytes,
219
+ method="wayback_pdf",
220
+ source_url=w.get("url") or url,
221
+ content_type="application/pdf",
222
+ )
223
+ return out
224
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
225
+ return out
226
+ if not raw_t and isinstance(raw_b, bytes):
227
+ raw_t = raw_b.decode("utf-8", "replace")
228
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
229
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
230
+ return out
231
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
232
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
233
+ out.update(
234
+ status="success",
235
+ text=text,
236
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
237
+ method="wayback_html",
238
+ source_url=w.get("url") or url,
239
+ content_type=w.get("content_type") or "text/html",
240
+ )
241
+ return out
242
+ out["error"] = (out.get("error") or "") + ";wayback_short"
243
+ else:
244
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
245
+ except Exception as exc:
246
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
247
+ return out
248
+
249
+
250
+ def first_title(text: str, fallback: str) -> str:
251
+ for line in (text or "").splitlines():
252
+ s = line.strip()
253
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
254
+ return s[:240]
255
+ return fallback[:240]
256
+
257
+
258
+ def save_instrument(
259
+ *,
260
+ cc: str,
261
+ country: str,
262
+ language: str,
263
+ ident: str,
264
+ title: str,
265
+ text: str,
266
+ source_url: str,
267
+ source_type: str,
268
+ license_text: str,
269
+ collector: str,
270
+ date: Optional[str] = None,
271
+ article_re: Optional[re.Pattern] = None,
272
+ extra_meta: Optional[dict] = None,
273
+ ) -> bool:
274
+ if not text or len(text) < MIN_TEXT:
275
+ return False
276
+ rid = slug_id(cc, ident)
277
+ docs = split_custom(text, rid, source_url, date, article_re)
278
+ rec = base_record(
279
+ cc=cc,
280
+ country=country,
281
+ language=language,
282
+ ident=ident,
283
+ title=title or first_title(text, ident),
284
+ text=text,
285
+ source_url=source_url,
286
+ source_type=source_type,
287
+ license_text=license_text,
288
+ collector=collector,
289
+ date=iso_date(date) or date,
290
+ documents=docs,
291
+ extra_meta=extra_meta,
292
+ )
293
+ write_instrument(cc, rec)
294
+ return True
295
+
296
+
297
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
298
+ try:
299
+ hits = af.search_wayback_machine(
300
+ host_or_url,
301
+ limit=limit,
302
+ match_type=match_type,
303
+ collapse="urlkey",
304
+ extra_filters=extra_filters,
305
+ )
306
+ except Exception as exc:
307
+ log.info("cdx err %s: %s", host_or_url, exc)
308
+ return []
309
+ return hits or []
310
+
311
+
312
+ def env_int(name: str, default: int) -> int:
313
+ try:
314
+ return int(os.environ.get(name, str(default)) or default)
315
+ except Exception:
316
+ return default