endomorphosis commited on
Commit
49fedca
·
verified ·
1 Parent(s): 69f11ea

Add Gabon official Wayback snapshot (42 laws / 5510 articles; dgi/finances/assemblee; thin)

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_gabon_laws manifest
2
+
3
+ generated_utc: 2026-09-09T12:59:16Z
4
+ cc: ga
5
+ laws_rows: 42
6
+ articles_rows: 5510
7
+ laws_bytes: 1047031
8
+ articles_bytes: 839174
9
+ laws_sha256: e1eb6365d272de99bf9bbcad59aaf173068612b32a842aa621396ca13204563d
10
+ articles_sha256: 3703dfad1ef405d3ce52b239e006e6d5df7490f5a0057e1420802ccdf516b73a
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_gabon_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_gabon_laws/data/articles.parquet
13
+ compression: zstd
14
+ collector: scrapers/collect_ga.py
15
+ license: République Gabonaise — sgg.ga / presidence.ga / assemblee.ga / primature.gouv.ga / finances.gouv.ga / justice.gouv.ga. Authentic Journal Officiel / official text prevails. Not legal advice. Not Congo-Brazzaville (cg) / DRC (cd).
16
+ retrieval: live-and-wayback-of-official
17
+ live_instruments: 42
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 Gabon (cc=ga) law / JO PDFs from *.ga / *.gouv.ga only (SGG, Présidence, Assemblée, Primature, Finances, Justice, Gouvernement, JO). Live-first; Wayback/CDX of official URLs on fail; OCR fra for scanned PDFs. Not AfricanLII / Droit-Afrique. No WAF bypass. Distinct from Congo-Brazzaville (cg), DRC (cd), Equatorial Guinea. Not legal advice.
26
+ uploaded: false
README.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Gabon Laws and Journal Officiel (sgg.ga / Présidence / Assemblée / Primature)
3
+ license: other
4
+ license_name: ga-sgg-presidence-assemblee-official-texts
5
+ language:
6
+ - fr
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - gabon
13
+ - journal-officiel
14
+ - jo
15
+ - sgg
16
+ - primature
17
+ - presidence
18
+ - assemblee
19
+ - constitution
20
+ - official-texts
21
+ size_categories:
22
+ - 1K<n<10K
23
+ configs:
24
+ - config_name: laws
25
+ data_files: data/laws.parquet
26
+ default: true
27
+ - config_name: articles
28
+ data_files: data/articles.parquet
29
+ ---
30
+
31
+ # Gabon Laws and Journal Officiel (sgg.ga / Présidence / Assemblée / Primature)
32
+
33
+ Research snapshot of official national legislation from **SGG (sgg.ga) + Présidence (presidence.ga) + Assemblée nationale (assemblee.ga) + Primature / Finances / Justice / Gouvernement / JO (*.ga / *.gouv.ga)**.
34
+
35
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
36
+
37
+ ## Snapshot
38
+
39
+ | Field | Value |
40
+ | --- | --- |
41
+ | Snapshot date | 2026-09-09 |
42
+ | Coverage | catalog-backed incomplete (live crawl sgg.ga / presidence.ga / assemblee.ga / primature.gouv.ga / finances.gouv.ga / justice.gouv.ga + CDX of official *.ga / *.gouv.ga PDFs) |
43
+ | Source | SGG (sgg.ga) + Présidence (presidence.ga) + Assemblée nationale (assemblee.ga) + Primature / Finances / Justice / Gouvernement / JO (*.ga / *.gouv.ga) |
44
+ | Collector | `scrapers/collect_ga.py` |
45
+ | Laws / instruments | 42 |
46
+ | Articles | 5,510 |
47
+ | Language | fr |
48
+ | Jurisdiction | Gabon |
49
+ | License | `ga-sgg-presidence-assemblee-official-texts` |
50
+
51
+ ## Contents
52
+
53
+ - `data/laws.parquet` — one row per instrument.
54
+ - `data/articles.parquet` — article/section rows for the same snapshot.
55
+ - `scrapers/collect_ga.py` — research collector used to build this snapshot.
56
+
57
+ ## License / reuse
58
+
59
+ République Gabonaise — sgg.ga / presidence.ga / assemblee.ga / primature.gouv.ga / finances.gouv.ga / justice.gouv.ga. Authentic Journal Officiel / official text prevails. Not legal advice. Not Congo-Brazzaville (cg) / DRC (cd)..
60
+
61
+ This dataset is **not legal advice**. The official source prevails.
62
+
63
+ ## Source
64
+
65
+ - https://sgg.ga/
66
+
67
+ ## Known gaps
68
+
69
+ Official Gabon (cc=ga) law / JO PDFs from *.ga / *.gouv.ga only (SGG, Présidence, Assemblée, Primature, Finances, Justice, Gouvernement, JO). Live-first; Wayback/CDX of official URLs on fail; OCR fra for scanned PDFs. Not AfricanLII / Droit-Afrique. No WAF bypass. Distinct from Congo-Brazzaville (cg), DRC (cd), Equatorial Guinea. Not legal advice.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3703dfad1ef405d3ce52b239e006e6d5df7490f5a0057e1420802ccdf516b73a
3
+ size 839174
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1eb6365d272de99bf9bbcad59aaf173068612b32a842aa621396ca13204563d
3
+ size 1047031
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
296
+ import subprocess
297
+
298
+ if timestamp:
299
+ path = f"/{timestamp}id_/{url}"
300
+ else:
301
+ path = f"/2id_/{url}"
302
+ target = WAYBACK_WEB_HTTP + path
303
+ last_err = None
304
+ body = b""
305
+ ctype = ""
306
+ final_url = target
307
+ status = 0
308
+ for attempt in range(1, 4):
309
+ _sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))
310
+ try:
311
+ # Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
312
+ proc = subprocess.run(
313
+ [
314
+ "curl", "-fsS", "--max-time", "90",
315
+ "-A", UA,
316
+ "-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}",
317
+ "--output", "-",
318
+ target,
319
+ ],
320
+ capture_output=True,
321
+ timeout=100,
322
+ )
323
+ raw = proc.stdout or b""
324
+ # Trailer is text appended after body when -w is used with --output -
325
+ # With --output -, -w goes to stdout after body. Split on trailer markers.
326
+ marker = b"\n__HTTP_STATUS__"
327
+ if marker in raw:
328
+ body, rest = raw.rsplit(marker, 1)
329
+ trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
330
+ mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
331
+ mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
332
+ murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
333
+ status = int(mstat.group(1)) if mstat else 0
334
+ ctype = (mctype.group(1) if mctype else "") or ""
335
+ final_url = (murl.group(1) if murl else target) or target
336
+ else:
337
+ body = raw
338
+ status = 200 if proc.returncode == 0 and raw else 0
339
+ if proc.returncode != 0 and not body:
340
+ last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
341
+ log.info("wayback replay curl fail %s: %s", url, last_err)
342
+ continue
343
+ if status in (403, 429, 503, 502, 504) and attempt < 3:
344
+ log.info("wayback replay HTTP %s %s attempt=%s", status, url, attempt)
345
+ continue
346
+ break
347
+ except Exception as exc:
348
+ last_err = str(exc)
349
+ log.info("wayback replay fail %s: %s", url, exc)
350
+ continue
351
+ else:
352
+ # fallback: requests without following redirects to https
353
+ try:
354
+ r = session().get(target, timeout=(20, 90), allow_redirects=False)
355
+ status = r.status_code
356
+ body = r.content or b""
357
+ ctype = r.headers.get("content-type") or ""
358
+ final_url = r.url or target
359
+ if status in (301, 302, 303, 307, 308):
360
+ loc = r.headers.get("Location") or ""
361
+ if loc.startswith("https://web.archive.org/"):
362
+ loc = "http://" + loc[len("https://"):]
363
+ if loc.startswith("http://web.archive.org/"):
364
+ r2 = session().get(loc, timeout=(20, 90), allow_redirects=False)
365
+ status = r2.status_code
366
+ body = r2.content or b""
367
+ ctype = r2.headers.get("content-type") or ""
368
+ final_url = r2.url or loc
369
+ except requests.RequestException as exc:
370
+ return {"status": "error", "error": last_err or str(exc), "url": url}
371
+
372
+ if not body and status != 200:
373
+ return {"status": "error", "error": last_err or f"http_{status}", "url": url}
374
+ cap_ts = timestamp or ""
375
+ m = re.search(r"/web/(\d{14})", final_url or "")
376
+ if m:
377
+ cap_ts = m.group(1)
378
+ text = ""
379
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
380
+ try:
381
+ text = body.decode("utf-8", "replace")
382
+ except Exception:
383
+ text = ""
384
+ if status != 200 or not body:
385
+ return {
386
+ "status": "error",
387
+ "error": f"http_{status}",
388
+ "http_status": status,
389
+ "wayback_url": final_url,
390
+ "original_url": url,
391
+ }
392
+ if text and is_challenge(text, status):
393
+ return {
394
+ "status": "error",
395
+ "error": "challenge_or_shell",
396
+ "http_status": status,
397
+ "wayback_url": final_url,
398
+ "original_url": url,
399
+ "content": text[:2000],
400
+ }
401
+ return {
402
+ "status": "success",
403
+ "content": body,
404
+ "text": text,
405
+ "content_type": ctype,
406
+ "wayback_url": final_url,
407
+ "capture_timestamp": cap_ts,
408
+ "original_url": url,
409
+ "http_status": status,
410
+ "method": "wayback_curl_http",
411
+ }
412
+
413
+
414
+ # --- Common Crawl ---
415
+
416
+ def _http_cc_index(url: str) -> str:
417
+ if url.startswith("https://index.commoncrawl.org"):
418
+ return "http://" + url[len("https://"):]
419
+ return url
420
+
421
+
422
+ def cc_indexes(n: int = 6) -> list[str]:
423
+ global _cc_indexes
424
+ if _cc_indexes is None:
425
+ cols = []
426
+ last_exc = None
427
+ for coll in (CC_COLLINFO, CC_COLLINFO.replace("https://", "http://", 1)):
428
+ try:
429
+ r = session().get(coll, timeout=30)
430
+ if r.status_code == 200:
431
+ cols = r.json() or []
432
+ break
433
+ except Exception as exc:
434
+ last_exc = exc
435
+ log.warning("cc collinfo %s: %s", coll, exc)
436
+ ids = []
437
+ for c in cols:
438
+ cid = c.get("id") or ""
439
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
440
+ if cid:
441
+ ids.append(_http_cc_index(cdx or f"http://index.commoncrawl.org/{cid}-index"))
442
+ # collinfo is newest-first. Do not drop crawls that 404 a
443
+ # specific URL (that means "no captures", not a dead index).
444
+ _cc_indexes = ids or [
445
+ "http://index.commoncrawl.org/CC-MAIN-2026-34-index",
446
+ "http://index.commoncrawl.org/CC-MAIN-2024-33-index",
447
+ ]
448
+ if last_exc and not ids:
449
+ log.warning("cc collinfo fallback indexes after %s", last_exc)
450
+ return _cc_indexes[:n]
451
+
452
+
453
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
454
+ """Query public CC CDX (https://index.commoncrawl.org/).
455
+
456
+ Do not send filter=status:200 — on some shards that returns a false
457
+ 404 "No Captures found". Filter status client-side instead.
458
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
459
+ """
460
+ out = []
461
+ seen = set()
462
+ empty = 0
463
+ for idx in (indexes or cc_indexes(12)):
464
+ if idx in _cc_dead:
465
+ continue
466
+ params = {
467
+ "url": url,
468
+ "output": "json",
469
+ "limit": str(limit),
470
+ }
471
+ _sleep_cc(0.3)
472
+ try:
473
+ r = session().get(idx, params=params, timeout=(12, 25))
474
+ except requests.RequestException as exc:
475
+ alt = _http_cc_index(idx) if idx.startswith("https://") else idx.replace("http://", "https://", 1)
476
+ try:
477
+ r = session().get(alt, params=params, timeout=(12, 25))
478
+ except requests.RequestException as exc2:
479
+ log.info("cc cdx %s fail %s / %s", idx, exc, exc2)
480
+ continue
481
+ if r.status_code == 404:
482
+ msg = (r.text or "")[:80]
483
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
484
+ empty += 1
485
+ if empty >= 8 and not out:
486
+ continue
487
+ continue
488
+ if r.status_code in (410,):
489
+ _cc_dead.add(idx)
490
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
491
+ continue
492
+ if r.status_code != 200 or not r.content:
493
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
494
+ continue
495
+ for line in r.text.splitlines():
496
+ line = line.strip()
497
+ if not line or line[0] not in "{[":
498
+ continue
499
+ try:
500
+ rec = json.loads(line)
501
+ except Exception:
502
+ continue
503
+ orig = rec.get("url") or rec.get("original") or ""
504
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
505
+ if st and st not in ("200", "201", "206"):
506
+ continue
507
+ key = (orig, rec.get("filename"), rec.get("offset"))
508
+ if not orig or key in seen:
509
+ continue
510
+ seen.add(key)
511
+ rec["original"] = orig
512
+ rec["source"] = "common_crawl"
513
+ rec["cc_index"] = idx
514
+ out.append(rec)
515
+ if out:
516
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
517
+ if len(out) >= limit or out:
518
+ break
519
+ return out[:limit]
520
+
521
+
522
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
523
+ data = raw
524
+ if data[:2] == b"\x1f\x8b":
525
+ try:
526
+ data = gzip.decompress(data)
527
+ except Exception:
528
+ try:
529
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
530
+ except Exception:
531
+ pass
532
+ # WARC record: headers, then HTTP payload
533
+ split = data.split(b"\r\n\r\n", 1)
534
+ if len(split) < 2:
535
+ return 0, "", data
536
+ warc_headers, rest = split
537
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
538
+ http_split = rest.split(b"\r\n\r\n", 1)
539
+ http_head = http_split[0].decode("latin-1", "replace")
540
+ body = http_split[1] if len(http_split) > 1 else b""
541
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
542
+ status = int(m.group(1)) if m else 0
543
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
544
+ ctype = cm.group(1).strip() if cm else ""
545
+ return status, ctype, body
546
+ return 0, "", rest
547
+
548
+
549
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
550
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
551
+ try:
552
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
553
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
554
+ except Exception:
555
+ return {"status": "error", "error": "bad_pointer"}
556
+ if not fn or ln <= 0:
557
+ return {"status": "error", "error": "missing_pointer"}
558
+ ln = min(ln, max_bytes)
559
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
560
+ _sleep_cc(0.25)
561
+ try:
562
+ r = session().get(
563
+ url,
564
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
565
+ timeout=(20, 90),
566
+ )
567
+ except requests.RequestException as exc:
568
+ return {"status": "error", "error": str(exc)}
569
+ if r.status_code not in (200, 206) or not r.content:
570
+ return {"status": "error", "error": f"http_{r.status_code}"}
571
+ status, ctype, body = _parse_warc_http(r.content)
572
+ text = ""
573
+ if body and (
574
+ "html" in (ctype or "")
575
+ or "xml" in (ctype or "")
576
+ or "text/" in (ctype or "")
577
+ or not ctype
578
+ ):
579
+ text = body.decode("utf-8", "replace")
580
+ orig = rec.get("original") or rec.get("url") or ""
581
+ if text and is_challenge(text, status or 200):
582
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
583
+ return {
584
+ "status": "success",
585
+ "content": body,
586
+ "text": text,
587
+ "content_type": ctype,
588
+ "original_url": orig,
589
+ "http_status": status or 200,
590
+ "method": "common_crawl",
591
+ "cc_record": {
592
+ "filename": fn,
593
+ "offset": off,
594
+ "length": ln,
595
+ "timestamp": rec.get("timestamp"),
596
+ },
597
+ }
598
+
599
+
600
+ # --- archive.is ---
601
+
602
+ def get_archive_is_content(url: str) -> dict:
603
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
604
+ try:
605
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
606
+ except requests.RequestException as exc:
607
+ log.info("archive.is %s", exc)
608
+ continue
609
+ if r.status_code != 200 or not r.content:
610
+ continue
611
+ if "archive." not in (r.url or ""):
612
+ continue
613
+ text = r.text or ""
614
+ if is_challenge(text, r.status_code):
615
+ continue
616
+ return {
617
+ "status": "success",
618
+ "content": r.content,
619
+ "text": text,
620
+ "content_type": r.headers.get("content-type") or "text/html",
621
+ "archive_url": r.url,
622
+ "original_url": url,
623
+ "http_status": r.status_code,
624
+ "method": "archive_is",
625
+ }
626
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
627
+
628
+
629
+ # --- Direct HTTP last ---
630
+
631
+ def get_http(url: str) -> dict:
632
+ try:
633
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
634
+ except requests.RequestException as exc:
635
+ return {"status": "error", "error": str(exc), "original_url": url}
636
+ text = ""
637
+ ctype = r.headers.get("content-type") or ""
638
+ body = r.content or b""
639
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
640
+ text = body.decode(r.encoding or "utf-8", "replace")
641
+ if r.status_code != 200 or not body:
642
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
643
+ if text and is_challenge(text, r.status_code):
644
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
645
+ return {
646
+ "status": "success",
647
+ "content": body,
648
+ "text": text,
649
+ "content_type": ctype,
650
+ "original_url": url,
651
+ "http_status": r.status_code,
652
+ "method": "http",
653
+ "final_url": r.url,
654
+ }
655
+
656
+
657
+ def fetch_with_fallbacks(
658
+ url: str,
659
+ *,
660
+ cc_record: Optional[dict] = None,
661
+ wayback_ts: Optional[str] = None,
662
+ try_archive_is: bool = False,
663
+ try_http: bool = True,
664
+ try_cc: bool = True,
665
+ ) -> dict:
666
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
667
+
668
+ Brave Search skipped (no API key in this environment).
669
+ Playwright is attempted by the caller when this returns a SPA shell.
670
+ Does not run Wayback CDX search; Wayback is replay only.
671
+ """
672
+ errors = []
673
+ cc_recs: list[dict] = []
674
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
675
+ cc_recs = [cc_record]
676
+ elif try_cc:
677
+ try:
678
+ cc_recs = search_common_crawl(url, limit=4)
679
+ except Exception as exc:
680
+ errors.append(f"common_crawl:{exc}")
681
+ cc_recs = []
682
+ for rec in cc_recs:
683
+ res = fetch_common_crawl_warc(rec)
684
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
685
+ return res
686
+ errors.append(f"common_crawl:{res.get('error')}")
687
+ if wayback_ts or url:
688
+ res = get_wayback_content(url, timestamp=wayback_ts)
689
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
690
+ return res
691
+ errors.append(f"wayback:{res.get('error')}")
692
+ if try_archive_is:
693
+ res = get_archive_is_content(url)
694
+ if res.get("status") == "success":
695
+ return res
696
+ errors.append(f"archive_is:{res.get('error')}")
697
+ if try_http:
698
+ res = get_http(url)
699
+ if res.get("status") == "success":
700
+ return res
701
+ errors.append(f"http:{res.get('error')}")
702
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_ga.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Gabon (ga): official law / JO PDFs from *.ga / *.gouv.ga.
3
+
4
+ Official only:
5
+ - https://sgg.ga/ (Secrétariat Général du Gouvernement)
6
+ - https://presidence.ga/
7
+ - https://www.assemblee.ga/ / assemblee.ga
8
+ - primature / finances / justice / gouvernement / journal-officiel (*.ga / *.gouv.ga)
9
+ - Wayback/CDX of the same official *.ga / *.gouv.ga URLs
10
+
11
+ Filter: prefer loi/ordonnance/décret/constitution/code/JO; skip PDFs >12MB.
12
+ Not AfricanLII / Droit-Afrique. No WAF bypass. Not legal advice.
13
+ NOTE: country code ga = Gabon (not Congo-Brazzaville cg, not DRC cd, not Equatorial Guinea).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import html as html_lib
18
+ import logging
19
+ import re
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import time
24
+ from pathlib import Path
25
+ from urllib.parse import unquote, urljoin, urlsplit, urlunsplit, quote
26
+
27
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
28
+ from common import existing_ids, log_failure, utcnow, write_summary
29
+ from world_lib import (
30
+ cdx_urls,
31
+ env_int,
32
+ fetch_official,
33
+ live_get,
34
+ pdf_to_text,
35
+ save_instrument,
36
+ setup_log,
37
+ slug_id,
38
+ )
39
+
40
+ CC, COUNTRY, LANG = "ga", "Gabon", "fr"
41
+ SOURCE_TYPE = "jo_gabon_official"
42
+ LICENSE = (
43
+ "République Gabonaise — SGG (sgg.ga) / Présidence (presidence.ga) / "
44
+ "Assemblée nationale (assemblee.ga) / Primature / Finances / Justice / "
45
+ "Gouvernement / Journal Officiel (*.ga / *.gouv.ga). Authentic Journal "
46
+ "Officiel / official text prevails. Not legal advice. Not Congo-Brazzaville "
47
+ "(cg) / DRC (cd) / Equatorial Guinea."
48
+ )
49
+ UA = (
50
+ "legal-corpora-collector/1.0 (research; source=https://sgg.ga/; "
51
+ "Gabon=ga not cg/cd/gq)"
52
+ )
53
+ ART = re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+[a-zA-Zº°]?)\b")
54
+ log = logging.getLogger("ga")
55
+
56
+ MAX_PDF_BYTES = 12 * 1024 * 1024
57
+
58
+ ALLOWED = (
59
+ "sgg.ga",
60
+ "www.sgg.ga",
61
+ "sgg.gouv.ga",
62
+ "www.sgg.gouv.ga",
63
+ "gouv.ga",
64
+ "www.gouv.ga",
65
+ "gov.ga",
66
+ "www.gov.ga",
67
+ "gouvernement.ga",
68
+ "www.gouvernement.ga",
69
+ "gouvernement.gouv.ga",
70
+ "primature.ga",
71
+ "www.primature.ga",
72
+ "primature.gouv.ga",
73
+ "www.primature.gouv.ga",
74
+ "presidence.ga",
75
+ "www.presidence.ga",
76
+ "presidence.gouv.ga",
77
+ "www.presidence.gouv.ga",
78
+ "assemblee.ga",
79
+ "www.assemblee.ga",
80
+ "assemblee-nationale.ga",
81
+ "www.assemblee-nationale.ga",
82
+ "assembleenationale.ga",
83
+ "www.assembleenationale.ga",
84
+ "an.ga",
85
+ "an.gouv.ga",
86
+ "senat.ga",
87
+ "www.senat.ga",
88
+ "senat.gouv.ga",
89
+ "finances.gouv.ga",
90
+ "www.finances.gouv.ga",
91
+ "finances.ga",
92
+ "economie.gouv.ga",
93
+ "www.economie.gouv.ga",
94
+ "budget.gouv.ga",
95
+ "www.budget.gouv.ga",
96
+ "justice.gouv.ga",
97
+ "www.justice.gouv.ga",
98
+ "justice.ga",
99
+ "www.justice.ga",
100
+ "journal-officiel.ga",
101
+ "www.journal-officiel.ga",
102
+ "journalofficiel.ga",
103
+ "www.journalofficiel.ga",
104
+ "journalofficiel.gouv.ga",
105
+ "www.journalofficiel.gouv.ga",
106
+ "jo.gouv.ga",
107
+ "www.jo.gouv.ga",
108
+ "jo.ga",
109
+ "lois.gouv.ga",
110
+ "www.lois.gouv.ga",
111
+ "dgi.ga",
112
+ "www.dgi.ga",
113
+ "dgi.gouv.ga",
114
+ "courconstitutionnelle.ga",
115
+ "www.courconstitutionnelle.ga",
116
+ "cour-constitutionnelle.ga",
117
+ "travail.gouv.ga",
118
+ "mines.gouv.ga",
119
+ "petrole.gouv.ga",
120
+ "habitat.gouv.ga",
121
+ "sante.gouv.ga",
122
+ "education.gouv.ga",
123
+ "interieur.gouv.ga",
124
+ "environnement.gouv.ga",
125
+ "eaux-forets.gouv.ga",
126
+ "communication.gouv.ga",
127
+ "numerique.gouv.ga",
128
+ )
129
+
130
+ KEEP_RE = re.compile(
131
+ r"(loi|ordonnance|ordonn|d[eé]cret|decret|arr[eê]t[eé]|arrete|constitution|code|"
132
+ r"journal.?officiel|\bjos?\b|\bjo\b|organique|r[eè]glement|charte|statut|"
133
+ r"wp-content/uploads|/uploads/|/documents?/|/jo/|textes?|"
134
+ r"gabon|gabonaise)",
135
+ re.I,
136
+ )
137
+ DROP_RE = re.compile(
138
+ r"(africanlii|gabonlii|droit-afrique|gazettes\.africa|law\.africa|"
139
+ r"discours|allocution|communique|photo|banner|logo|cv[-_]|"
140
+ r"biographie|rapport[-_ ]annuel|presentation|organigramme|"
141
+ r"newsletter|recrutement|facebook|twitter|linkedin|"
142
+ r"album|actualites|appel.?d.?offres|"
143
+ r"kinshasa|brazzaville|\.cd/|\.cg/|journalofficiel\.cd|presidence\.cd|"
144
+ r"equatorial|guinea|malabo|\.gq)",
145
+ re.I,
146
+ )
147
+ TEXT_KEEP_RE = re.compile(
148
+ r"\b(loi|ordonnance|d[eé]cret|decret|constitution|journal\s+officiel|"
149
+ r"code|r[eé]publique\s+gabonaise|assembl[eé]e\s+nationale|"
150
+ r"pr[eé]sident\s+de\s+la\s+r[eé]publique|promulgue|partie\s+officielle|"
151
+ r"conseil\s+des\s+ministres|gabon)\b",
152
+ re.I,
153
+ )
154
+
155
+ SEED_PDFS = [
156
+ # Seeds filled / expanded from live crawl + CDX of official hosts at collect time
157
+ ]
158
+
159
+ HOMES = [
160
+ "https://sgg.ga/",
161
+ "https://www.sgg.ga/",
162
+ "https://presidence.ga/",
163
+ "https://www.presidence.ga/",
164
+ "https://assemblee.ga/",
165
+ "https://www.assemblee.ga/",
166
+ "https://assemblee-nationale.ga/",
167
+ "https://www.assemblee-nationale.ga/",
168
+ "https://senat.ga/",
169
+ "https://www.senat.ga/",
170
+ "https://primature.gouv.ga/",
171
+ "https://www.primature.gouv.ga/",
172
+ "https://finances.gouv.ga/",
173
+ "https://www.finances.gouv.ga/",
174
+ "https://justice.gouv.ga/",
175
+ "https://www.justice.gouv.ga/",
176
+ "https://gouvernement.ga/",
177
+ "https://www.gouvernement.ga/",
178
+ "https://journal-officiel.ga/",
179
+ "https://www.journal-officiel.ga/",
180
+ "https://journalofficiel.ga/",
181
+ "https://courconstitutionnelle.ga/",
182
+ "https://sgg.gouv.ga/",
183
+ ]
184
+
185
+ CDX_PREFIXES = (
186
+ "sgg.ga/",
187
+ "www.sgg.ga/",
188
+ "sgg.gouv.ga/",
189
+ "www.sgg.gouv.ga/",
190
+ "gouv.ga/",
191
+ "www.gouv.ga/",
192
+ "gouvernement.ga/",
193
+ "www.gouvernement.ga/",
194
+ "primature.gouv.ga/",
195
+ "www.primature.gouv.ga/",
196
+ "presidence.ga/",
197
+ "www.presidence.ga/",
198
+ "presidence.gouv.ga/",
199
+ "assemblee.ga/",
200
+ "www.assemblee.ga/",
201
+ "assemblee-nationale.ga/",
202
+ "www.assemblee-nationale.ga/",
203
+ "assembleenationale.ga/",
204
+ "senat.ga/",
205
+ "www.senat.ga/",
206
+ "finances.gouv.ga/",
207
+ "www.finances.gouv.ga/",
208
+ "economie.gouv.ga/",
209
+ "budget.gouv.ga/",
210
+ "justice.gouv.ga/",
211
+ "www.justice.gouv.ga/",
212
+ "justice.ga/",
213
+ "journal-officiel.ga/",
214
+ "www.journal-officiel.ga/",
215
+ "journalofficiel.ga/",
216
+ "journalofficiel.gouv.ga/",
217
+ "jo.gouv.ga/",
218
+ "jo.ga/",
219
+ "lois.gouv.ga/",
220
+ "dgi.ga/",
221
+ "www.dgi.ga/",
222
+ "courconstitutionnelle.ga/",
223
+ "www.courconstitutionnelle.ga/",
224
+ "travail.gouv.ga/",
225
+ "mines.gouv.ga/",
226
+ "petrole.gouv.ga/",
227
+ "environnement.gouv.ga/",
228
+ )
229
+
230
+
231
+ def _host_ok(url: str) -> bool:
232
+ host = (urlsplit(url).hostname or "").lower()
233
+ if any(
234
+ x in host
235
+ for x in (
236
+ "africanlii",
237
+ "gabonlii",
238
+ "droit-afrique",
239
+ "gazettes.africa",
240
+ "law.africa",
241
+ )
242
+ ):
243
+ return False
244
+ # Never harvest Congo-Brazzaville (cg), DRC (cd), Equatorial Guinea (gq)
245
+ if host.endswith(".cd") or host.endswith(".cg") or host.endswith(".gq"):
246
+ return False
247
+ if "kinshasa" in host or "brazzaville" in host or "equatorial" in host:
248
+ return False
249
+ if not (host.endswith(".ga") or host == "ga"):
250
+ return False
251
+ return any(host == s or host.endswith("." + s) for s in ALLOWED)
252
+
253
+
254
+ def _norm_url(url: str) -> str:
255
+ url = html_lib.unescape((url or "").split("#")[0].strip())
256
+ if not url:
257
+ return ""
258
+ url = url.replace(":80/", "/").replace(":80?", "?")
259
+ if url.startswith("http://"):
260
+ url = "https://" + url[len("http://") :]
261
+ try:
262
+ p = urlsplit(url)
263
+ host = (p.hostname or "").lower()
264
+ parts = []
265
+ for seg in p.path.split("/"):
266
+ if not seg:
267
+ parts.append(seg)
268
+ continue
269
+ parts.append(seg if "%" in seg else quote(seg, safe="._-()[]',"))
270
+ url = urlunsplit((p.scheme or "https", host, "/".join(parts), "", ""))
271
+ except Exception:
272
+ url = url.replace(" ", "%20")
273
+ return url
274
+
275
+
276
+ def _ident_from_url(url: str, title: str | None = None) -> str:
277
+ path = unquote(urlsplit(url).path)
278
+ if title:
279
+ t = re.sub(r"\W+", "-", title).strip("-").lower()[:100]
280
+ if t and len(t) > 8:
281
+ return t
282
+ name = Path(path).name or path
283
+ stem = Path(name).stem
284
+ return re.sub(r"\W+", "-", stem).strip("-").lower()[:160] or re.sub(r"\W+", "-", url)[-80:]
285
+
286
+
287
+ def _is_jo(url: str) -> bool:
288
+ host = (urlsplit(url).hostname or "").lower()
289
+ path = unquote(urlsplit(url).path).lower()
290
+ return (
291
+ "journalofficiel" in host
292
+ or "journal-officiel" in host
293
+ or host.startswith("jo.")
294
+ or host == "jo.ga"
295
+ or "/jo/" in path
296
+ or "journal-officiel" in path
297
+ or re.search(r"(?i)(jo[-_]?\d|journal.?officiel)", path)
298
+ or ("sgg.ga" in host and re.search(r"(?i)(jo|journal)", path))
299
+ )
300
+
301
+
302
+ def _keep(url: str, title: str | None = None) -> bool:
303
+ if not _host_ok(url):
304
+ return False
305
+ blob = unquote(urlsplit(url).path) + " " + url + " " + (title or "")
306
+ if DROP_RE.search(blob):
307
+ return False
308
+ low = url.lower().split("?")[0]
309
+ if not (low.endswith(".pdf") or "/download" in low or "/document/" in low):
310
+ return False
311
+ if _is_jo(url):
312
+ return True
313
+ return bool(KEEP_RE.search(blob))
314
+
315
+
316
+ def ocr_pdf(raw: bytes) -> str:
317
+ max_pages = env_int("MAX_OCR_PAGES", 12)
318
+ dpi = env_int("OCR_DPI", 140)
319
+ try:
320
+ with tempfile.TemporaryDirectory() as td:
321
+ pdf = Path(td) / "doc.pdf"
322
+ pdf.write_bytes(raw)
323
+ proc = subprocess.run(
324
+ [
325
+ "pdftoppm", "-png", "-r", str(dpi),
326
+ "-f", "1", "-l", str(max_pages),
327
+ str(pdf), str(Path(td) / "p"),
328
+ ],
329
+ check=False, capture_output=True, timeout=240,
330
+ )
331
+ if proc.returncode != 0:
332
+ return ""
333
+ chunks = []
334
+ for img in sorted(Path(td).glob("p*.png")):
335
+ tproc = subprocess.run(
336
+ ["tesseract", str(img), "stdout", "-l", "fra", "--psm", "6"],
337
+ check=False, capture_output=True, timeout=120,
338
+ )
339
+ if tproc.returncode == 0 and tproc.stdout:
340
+ chunks.append(tproc.stdout.decode("utf-8", "replace").strip())
341
+ return "\n\n".join(c for c in chunks if c).strip()
342
+ except Exception as exc:
343
+ log.warning("ocr_pdf: %s", exc)
344
+ return ""
345
+
346
+
347
+ def fetch_ga(url: str, wayback_ts: str | None = None) -> dict:
348
+ got = fetch_official(url, ua=UA, verify=False, min_text=120, wayback=True, wayback_ts=wayback_ts)
349
+ if got.get("status") == "success" and len(got.get("text") or "") >= 120:
350
+ return got
351
+ body = got.get("content") or b""
352
+ if not (isinstance(body, bytes) and body[:4] == b"%PDF"):
353
+ try:
354
+ r = live_get(url, ua=UA, verify=False, timeout=(20, 90), retries=2)
355
+ if getattr(r, "status_code", 0) == 200 and (r.content or b"")[:4] == b"%PDF":
356
+ body = r.content
357
+ got["method"] = "live_pdf"
358
+ except Exception as exc:
359
+ got["error"] = (got.get("error") or "") + f";live_pdf:{exc}"
360
+ return got
361
+ if not (isinstance(body, bytes) and body[:4] == b"%PDF"):
362
+ return got
363
+ if len(body) > MAX_PDF_BYTES:
364
+ got["error"] = f"pdf_too_large:{len(body)}"
365
+ return got
366
+ text = pdf_to_text(body)
367
+ if len(text) >= 120:
368
+ got.update(status="success", text=text, content=body, method=got.get("method") or "http_pdf")
369
+ return got
370
+ max_ocr_bytes = env_int("MAX_OCR_BYTES", 8 * 1024 * 1024)
371
+ if len(body) > max_ocr_bytes:
372
+ got["error"] = (got.get("error") or "") + f";skip_ocr_large:{len(body)}"
373
+ return got
374
+ log.info("OCR fra %s bytes=%s", _ident_from_url(url)[:40], len(body))
375
+ ocr = ocr_pdf(body)
376
+ if len(ocr) >= 120:
377
+ got.update(status="success", text=ocr, content=body, method="ocr_fra")
378
+ return got
379
+ got["error"] = (got.get("error") or "") + ";ocr_short"
380
+ return got
381
+
382
+
383
+ def _add(items, seen, ident, url, ts=None, priority=50, size_hint=None, title=None):
384
+ url = _norm_url(url)
385
+ if not url or not _keep(url, title=title):
386
+ return
387
+ key = url.lower().split("?")[0]
388
+ key2 = key.replace("://www.", "://")
389
+ if key in seen or key2 in seen:
390
+ return
391
+ if size_hint and size_hint > MAX_PDF_BYTES:
392
+ return
393
+ seen.add(key)
394
+ seen.add(key2)
395
+ ident = re.sub(r"\W+", "-", (ident or _ident_from_url(url, title)).strip("-")).lower()[:160]
396
+ items.append((priority, ident, url, ts, size_hint, title))
397
+
398
+
399
+ def discover():
400
+ items = []
401
+ seen = set()
402
+
403
+ for seed in SEED_PDFS:
404
+ pri = 5 if "CONSTITUTION" in seed.upper() else 8
405
+ _add(items, seen, _ident_from_url(seed), seed, ts=None, priority=pri)
406
+
407
+ for home in HOMES:
408
+ try:
409
+ r = live_get(home, ua=UA, verify=False, timeout=(12, 40), retries=1)
410
+ if getattr(r, "status_code", 0) != 200:
411
+ log.info("home status=%s %s", getattr(r, "status_code", None), home)
412
+ continue
413
+ text = r.text or ""
414
+ n = 0
415
+ for href in re.findall(r'href=["\']([^"\']+)["\']', text, re.I):
416
+ full = urljoin(home, html_lib.unescape(href))
417
+ if ".pdf" in full.lower() or "/download" in full.lower():
418
+ pri = 15
419
+ low = unquote(full).lower()
420
+ if "constitut" in low:
421
+ pri = 5
422
+ elif re.search(r"(?i)(loi|ordonnance|code)", low):
423
+ pri = 10
424
+ elif _is_jo(full):
425
+ pri = 12
426
+ _add(items, seen, _ident_from_url(full), full, ts=None, priority=pri)
427
+ n += 1
428
+ for href in re.findall(r'(https?://[^\s"\'<>]+\.pdf)', text, re.I):
429
+ _add(items, seen, _ident_from_url(href), href, ts=None, priority=18)
430
+ n += 1
431
+ # shallow crawl of promising subpages (max 8 per home)
432
+ sub = []
433
+ for href in re.findall(r'href=["\']([^"\']+)["\']', text, re.I):
434
+ full = urljoin(home, html_lib.unescape(href))
435
+ if not _host_ok(full):
436
+ continue
437
+ low = unquote(full).lower()
438
+ if any(
439
+ k in low
440
+ for k in (
441
+ "loi", "jo", "journal", "decret", "code", "constitut",
442
+ "texte", "document", "download", "upload", "sgg",
443
+ "legislation", "juridique",
444
+ )
445
+ ):
446
+ if full not in sub and not low.endswith(".pdf"):
447
+ sub.append(full)
448
+ for sub_url in sub[:8]:
449
+ try:
450
+ r2 = live_get(sub_url, ua=UA, verify=False, timeout=(10, 30), retries=1)
451
+ if getattr(r2, "status_code", 0) != 200:
452
+ continue
453
+ t2 = r2.text or ""
454
+ for href in re.findall(r'href=["\']([^"\']+)["\']', t2, re.I):
455
+ full = urljoin(sub_url, html_lib.unescape(href))
456
+ if ".pdf" in full.lower():
457
+ pri = 16
458
+ low = unquote(full).lower()
459
+ if "constitut" in low:
460
+ pri = 5
461
+ elif re.search(r"(?i)(loi|ordonnance|code)", low):
462
+ pri = 10
463
+ _add(items, seen, _ident_from_url(full), full, ts=None, priority=pri)
464
+ n += 1
465
+ except Exception as exc:
466
+ log.info("sub %s %s", sub_url[:80], exc)
467
+ log.info("home %s links=%s", home, n)
468
+ except Exception as exc:
469
+ log.info("home %s %s", home, exc)
470
+
471
+ for prefix in CDX_PREFIXES:
472
+ try:
473
+ hits = cdx_urls(
474
+ prefix,
475
+ limit=env_int("CDX_LIMIT", 200),
476
+ match_type="prefix",
477
+ extra_filters=["statuscode:200", "mimetype:application/pdf"],
478
+ ) or []
479
+ except Exception as exc:
480
+ log.info("cdx %s %s", prefix, exc)
481
+ hits = []
482
+ if len(hits) < 5:
483
+ try:
484
+ hits2 = cdx_urls(
485
+ prefix,
486
+ limit=env_int("CDX_LIMIT", 200),
487
+ match_type="prefix",
488
+ extra_filters=["statuscode:200"],
489
+ ) or []
490
+ for h in hits2:
491
+ orig = (h.get("original") or "").lower()
492
+ if ".pdf" in orig:
493
+ hits.append(h)
494
+ except Exception as exc:
495
+ log.info("cdx2 %s %s", prefix, exc)
496
+ for h in hits:
497
+ orig = h.get("original") or ""
498
+ ts = (h.get("timestamp") or "")[:14] or None
499
+ try:
500
+ length = int(h.get("length") or 0)
501
+ except Exception:
502
+ length = 0
503
+ if length and length > MAX_PDF_BYTES:
504
+ continue
505
+ if not _keep(orig):
506
+ continue
507
+ pri = 28
508
+ low = unquote(orig).lower()
509
+ if "constitut" in low:
510
+ pri = 5
511
+ elif _is_jo(orig):
512
+ pri = 14
513
+ elif re.search(r"(?i)(loi|ordonnance|code)", low):
514
+ pri = 12
515
+ elif re.search(r"(?i)(decret|d[eé]cret|arrete)", low):
516
+ pri = 20
517
+ _add(items, seen, _ident_from_url(orig), orig, ts=ts, priority=pri, size_hint=length or None)
518
+
519
+ items.sort(key=lambda x: (x[0], x[1]))
520
+ out = [(ident, url, ts, size, title) for _, ident, url, ts, size, title in items]
521
+ log.info("catalog %s", len(out))
522
+ return out
523
+
524
+
525
+ def main():
526
+ setup_log(CC)
527
+ t0 = utcnow()
528
+ max_new = env_int("MAX_NEW", 80)
529
+ max_seconds = env_int("MAX_SECONDS", 2400)
530
+ t_start = time.time()
531
+ done = existing_ids(CC)
532
+ already = len(done)
533
+ target_total = env_int("TARGET_TOTAL", 0)
534
+ ok = skip = fail = 0
535
+ for ident, url, ts, size_hint, title in discover():
536
+ if max_new and ok >= max_new:
537
+ break
538
+ if target_total and (already + ok) >= target_total:
539
+ break
540
+ if time.time() - t_start > max_seconds:
541
+ break
542
+ if size_hint and size_hint > MAX_PDF_BYTES:
543
+ skip += 1
544
+ continue
545
+ rid = slug_id(CC, ident)
546
+ if rid in done:
547
+ skip += 1
548
+ continue
549
+ if not _host_ok(url):
550
+ fail += 1
551
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "host_not_ga"})
552
+ continue
553
+ got = fetch_ga(url, wayback_ts=ts)
554
+ text = got.get("text") or ""
555
+ if got.get("status") != "success":
556
+ fail += 1
557
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error"), "wayback_ts": ts})
558
+ continue
559
+ if len(text) > 2_500_000:
560
+ log.info("skip huge text chars=%s %s", len(text), ident[:50])
561
+ fail += 1
562
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_too_large", "chars": len(text)})
563
+ continue
564
+ if not TEXT_KEEP_RE.search(text[:8000]) and not _is_jo(url):
565
+ if not re.search(r"(?i)(loi|ordonnance|decret|constitut|code|jo-)", ident):
566
+ fail += 1
567
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_not_legal"})
568
+ continue
569
+ use_title = title
570
+ if not use_title:
571
+ for line in text.splitlines():
572
+ if len(line.strip()) > 18:
573
+ use_title = line.strip()[:240]
574
+ break
575
+ if save_instrument(
576
+ cc=CC, country=COUNTRY, language=LANG, ident=ident,
577
+ title=use_title or ident, text=text, source_url=url,
578
+ source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_ga.py",
579
+ article_re=ART,
580
+ extra_meta={"fetch_method": got.get("method"), "wayback_ts": ts, "size_hint": size_hint},
581
+ ):
582
+ ok += 1
583
+ done.add(rid)
584
+ log.info("ok %s method=%s chars=%s ts=%s", ident[:60], got.get("method"), len(text), ts)
585
+ else:
586
+ fail += 1
587
+ write_summary(
588
+ CC, country=COUNTRY,
589
+ source="Gabon / République Gabonaise (sgg.ga / Présidence / Assemblée / Primature / Finances / JO)",
590
+ source_urls=[
591
+ "https://sgg.ga/",
592
+ "https://presidence.ga/",
593
+ "https://www.assemblee.ga/",
594
+ "https://primature.gouv.ga/",
595
+ "https://finances.gouv.ga/",
596
+ "https://justice.gouv.ga/",
597
+ "https://gouvernement.ga/",
598
+ "https://journal-officiel.ga/",
599
+ ],
600
+ license_text=LICENSE, discovered=ok + skip + fail, fetched=ok, skipped=skip, failed=fail,
601
+ coverage="catalog-backed incomplete (live crawl *.gouv.ga / *.ga + CDX PDF / JO)",
602
+ notes=(
603
+ "Official *.ga / *.gouv.ga JO/SGG/justice/primature/présidence PDFs only (Gabon). "
604
+ "OCR fra for scans. Not AfricanLII. No WAF bypass. Not legal advice. "
605
+ "ga=Gabon (not Congo-Brazzaville/cg, not DRC/cd, not Equatorial Guinea)."
606
+ ),
607
+ last_run=t0,
608
+ )
609
+ log.info("done ok=%s skip=%s fail=%s total_instruments=%s", ok, skip, fail, len(done))
610
+
611
+
612
+ if __name__ == "__main__":
613
+ 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