endomorphosis commited on
Commit
0ca0445
·
verified ·
1 Parent(s): af06aaf

Add/update by official laws snapshot

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # MANIFEST
2
+
3
+ - generated_at: 2026-09-04T18:40:29Z
4
+ - laws: 40
5
+ - articles: 7335
6
+ - files:
7
+ - data/laws.parquet: 7149158 bytes
8
+ - data/articles.parquet: 5600437 bytes
9
+ - README.md: 1732 bytes
README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Laws of Belarus
3
+ license: other
4
+ license_name: by-pravo
5
+ language:
6
+ - ru
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - belarus
13
+ - official-texts
14
+ size_categories:
15
+ - n<1K
16
+ configs:
17
+ - config_name: laws
18
+ data_files: data/laws.parquet
19
+ default: true
20
+ - config_name: articles
21
+ data_files: data/articles.parquet
22
+ ---
23
+
24
+ # Laws of Belarus
25
+
26
+ Research snapshot of official legislation collected from **pravo.by National Legal Portal**.
27
+
28
+ **Not legal advice.** Official gazettes / government portals prevail over this corpus.
29
+
30
+ ## Snapshot
31
+
32
+ | Field | Value |
33
+ | --- | --- |
34
+ | Snapshot date | 2026-09-04 |
35
+ | Coverage | catalog-backed incomplete |
36
+ | Source | pravo.by National Legal Portal |
37
+ | Collector | `scrapers/collect_by.py` |
38
+ | Laws / instruments | 40 |
39
+ | Articles | 7335 |
40
+ | Language | ru |
41
+ | Jurisdiction | Belarus |
42
+ | License | `by-pravo` |
43
+
44
+ ## Contents
45
+
46
+ - `data/laws.parquet` — one row per instrument (id, title, full text, dates, status, identifiers, article count, source URL).
47
+ - `data/articles.parquet` — one row per article/section (`law_id`, article number, title, text, source URL).
48
+ - `scrapers/collect_by.py` — research collector used to build this snapshot.
49
+ - `scrapers/common.py` — shared collector helpers.
50
+ - `scrapers/world_lib.py` — shared fetch (live official URL, Wayback fallback).
51
+ - `scrapers/archive_fallbacks.py` — Wayback / Common Crawl CDX helpers.
52
+
53
+ ## License / reuse
54
+
55
+ Official government / gazette texts; reuse per public-sector terms of the
56
+ source portal. This packaging, metadata, and collector script are provided
57
+ for research.
58
+
59
+ This dataset is **not** an official consolidation and is **not legal advice**.
60
+ The official source prevails.
61
+
62
+ ## Notes
63
+
64
+ Partial official scrape batch2.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e4c8ade1c04e34453ad6d60f686072de8a2636a9f0fa461dee6323b83bcb5d5
3
+ size 5600437
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fc11fb5cd13d56d40e0ce7e013096bca9ef0e4f9a89c2a96b9ee86030ccabe4
3
+ size 7149158
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public Wayback CDX + Common Crawl CDX/WARC fetch (ipfs_datasets_py fallback intent).
3
+
4
+ Does not import the full ipfs_datasets_py package. Matches:
5
+ search_wayback_machine / get_wayback_content (wayback_machine_engine.py)
6
+ Common Crawl CDX at https://index.commoncrawl.org/
7
+ archive.is newest lookup
8
+ Brave Search is skipped when no API key is present.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import gzip
13
+ import io
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Optional
20
+ from urllib.parse import quote, urljoin, urlparse
21
+
22
+ import requests
23
+ from requests.adapters import HTTPAdapter
24
+
25
+ log = logging.getLogger("archive_fallbacks")
26
+
27
+ WAYBACK_CDX = "https://web.archive.org/cdx/search/cdx"
28
+ WAYBACK_WEB = "https://web.archive.org/web"
29
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
+ CC_DATA = "https://data.commoncrawl.org"
31
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
32
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
33
+
34
+ UA = (
35
+ "legal-corpora-collector/1.0 "
36
+ "(research archive of official national gazettes; polite; "
37
+ "contact via local operator)"
38
+ )
39
+
40
+ CHALLENGE_RE = re.compile(
41
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
42
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
43
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
44
+ r"request\s+rejected|access\s+denied",
45
+ re.I,
46
+ )
47
+ SPA_SHELL_RE = re.compile(
48
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
49
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
50
+ re.I,
51
+ )
52
+
53
+ _session: Optional[requests.Session] = None
54
+ _cc_indexes: Optional[list[str]] = None
55
+ _cc_dead: set[str] = set()
56
+ _last_wayback = 0.0
57
+ _last_cc = 0.0
58
+
59
+
60
+ def session() -> requests.Session:
61
+ global _session
62
+ if _session is None:
63
+ s = requests.Session()
64
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
65
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
66
+ s.mount("https://", ad)
67
+ s.mount("http://", ad)
68
+ _session = s
69
+ return _session
70
+
71
+
72
+ def _sleep_wayback(delay: float = 1.0) -> None:
73
+ global _last_wayback
74
+ now = time.time()
75
+ wait = delay - (now - _last_wayback)
76
+ if wait > 0:
77
+ time.sleep(wait)
78
+ _last_wayback = time.time()
79
+
80
+
81
+ def _sleep_cc(delay: float = 0.35) -> None:
82
+ global _last_cc
83
+ now = time.time()
84
+ wait = delay - (now - _last_cc)
85
+ if wait > 0:
86
+ time.sleep(wait)
87
+ _last_cc = time.time()
88
+
89
+
90
+ def has_brave_key() -> bool:
91
+ return bool(
92
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
93
+ )
94
+
95
+
96
+ def is_challenge(html: str, status: int = 200) -> bool:
97
+ if status in (401, 403, 429, 503):
98
+ return True
99
+ if not html:
100
+ return False
101
+ head = html[:8000]
102
+ if CHALLENGE_RE.search(head):
103
+ return True
104
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
105
+ return True
106
+ return False
107
+
108
+
109
+ def is_spa_shell(html: str, text: str) -> bool:
110
+ if not html:
111
+ return False
112
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
113
+ return True
114
+ return False
115
+
116
+
117
+ # --- Wayback ---
118
+
119
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
120
+
121
+
122
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
123
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
124
+ if not isinstance(data, list) or len(data) <= 1:
125
+ return [], None
126
+ resume = None
127
+ rows = data
128
+ # Trailer: ..., [], ["resumeKey"]
129
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
130
+ resume = str(data[-1][0]) if data[-1][0] else None
131
+ rows = data[:-2]
132
+ headers = rows[0] if rows else []
133
+ out: list[dict] = []
134
+ for row in rows[1:]:
135
+ if not row:
136
+ continue
137
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
138
+ if not rec and isinstance(row, list) and len(row) >= 5:
139
+ rec = {
140
+ "urlkey": row[0],
141
+ "timestamp": row[1],
142
+ "original": row[2],
143
+ "mimetype": row[3],
144
+ "statuscode": row[4],
145
+ "digest": row[5] if len(row) > 5 else "",
146
+ "length": row[6] if len(row) > 6 else "0",
147
+ }
148
+ orig = rec.get("original") or rec.get("url") or ""
149
+ ts = rec.get("timestamp") or ""
150
+ mime = rec.get("mimetype") or ""
151
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
152
+ "application/pdf",
153
+ "application/xml",
154
+ "text/xml",
155
+ "application/xhtml+xml",
156
+ "text/html",
157
+ "application/json",
158
+ ):
159
+ continue
160
+ if not orig or not ts:
161
+ continue
162
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
163
+ rec["source"] = "wayback"
164
+ out.append(rec)
165
+ return out, resume
166
+
167
+
168
+ def _wayback_cdx_page(
169
+ url: str,
170
+ *,
171
+ limit: int,
172
+ collapse: str,
173
+ filter_status: str,
174
+ from_date: Optional[str],
175
+ to_date: Optional[str],
176
+ match_type: Optional[str],
177
+ extra_filters: Optional[list[str]],
178
+ resume_key: Optional[str],
179
+ mime_prefix: Optional[str],
180
+ page_size: int,
181
+ ) -> tuple[list[dict], Optional[str]]:
182
+ items: list[tuple[str, Any]] = [
183
+ ("url", url),
184
+ ("output", "json"),
185
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
186
+ ("limit", int(page_size)),
187
+ ("showResumeKey", "true"),
188
+ ]
189
+ if collapse:
190
+ items.append(("collapse", collapse))
191
+ if from_date:
192
+ items.append(("from", from_date))
193
+ if to_date:
194
+ items.append(("to", to_date))
195
+ if match_type:
196
+ items.append(("matchType", match_type))
197
+ if filter_status:
198
+ items.append(("filter", f"statuscode:{filter_status}"))
199
+ for flt in extra_filters or []:
200
+ items.append(("filter", flt))
201
+ if resume_key:
202
+ items.append(("resumeKey", resume_key))
203
+ _sleep_wayback(1.0)
204
+ last_err = None
205
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
206
+ if attempt > 1:
207
+ items = [(k, psz if k == "limit" else v) for k, v in items]
208
+ _sleep_wayback(1.5)
209
+ try:
210
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
211
+ except requests.RequestException as exc:
212
+ last_err = exc
213
+ log.warning("wayback cdx fail %s: %s", url, exc)
214
+ continue
215
+ if r.status_code in (502, 503, 504) or not r.content:
216
+ last_err = f"http_{r.status_code}"
217
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
218
+ continue
219
+ if r.status_code != 200:
220
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
221
+ return [], None
222
+ try:
223
+ data = r.json()
224
+ except Exception:
225
+ return [], None
226
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
227
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
228
+ return [], None
229
+
230
+
231
+ def search_wayback_machine(
232
+ url: str,
233
+ *,
234
+ from_date: Optional[str] = None,
235
+ to_date: Optional[str] = None,
236
+ limit: int = 100,
237
+ collapse: str = "urlkey",
238
+ filter_status: str = "200",
239
+ match_type: Optional[str] = None,
240
+ mime_prefix: Optional[str] = None,
241
+ extra_filters: Optional[list[str]] = None,
242
+ ) -> list[dict]:
243
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
244
+ target = max(1, int(limit))
245
+ page_size = CDX_PAGE if target > CDX_PAGE else target
246
+ out: list[dict] = []
247
+ seen = set()
248
+ resume: Optional[str] = None
249
+ empty = 0
250
+ while len(out) < target:
251
+ need = min(page_size, target - len(out))
252
+ batch, resume = _wayback_cdx_page(
253
+ url,
254
+ limit=need,
255
+ collapse=collapse,
256
+ filter_status=filter_status,
257
+ from_date=from_date,
258
+ to_date=to_date,
259
+ match_type=match_type,
260
+ extra_filters=extra_filters,
261
+ resume_key=resume,
262
+ mime_prefix=mime_prefix,
263
+ page_size=need,
264
+ )
265
+ added = 0
266
+ for rec in batch:
267
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
268
+ if key in seen:
269
+ continue
270
+ seen.add(key)
271
+ out.append(rec)
272
+ added += 1
273
+ if added == 0:
274
+ empty += 1
275
+ if empty >= 2 or not resume:
276
+ break
277
+ else:
278
+ empty = 0
279
+ if not resume:
280
+ break
281
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
282
+ return out[:target]
283
+
284
+
285
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
286
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search."""
287
+ if timestamp:
288
+ wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}"
289
+ else:
290
+ wb = f"{WAYBACK_WEB}/2id_/{url}"
291
+ r = None
292
+ last_err = None
293
+ for attempt in range(1, 5):
294
+ _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt))
295
+ try:
296
+ r = session().get(wb, timeout=(20, 90), allow_redirects=True)
297
+ except requests.RequestException as exc:
298
+ last_err = str(exc)
299
+ log.info("wayback replay fail %s: %s", url, exc)
300
+ continue
301
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 4:
302
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
303
+ continue
304
+ break
305
+ if r is None:
306
+ return {"status": "error", "error": last_err or "no_response", "url": url}
307
+ cap_ts = timestamp or ""
308
+ m = re.search(r"/web/(\d{14})", r.url or "")
309
+ if m:
310
+ cap_ts = m.group(1)
311
+ ctype = r.headers.get("content-type") or ""
312
+ body = r.content or b""
313
+ text = ""
314
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
315
+ enc = r.encoding or "utf-8"
316
+ try:
317
+ text = body.decode(enc, "replace")
318
+ except Exception:
319
+ text = body.decode("utf-8", "replace")
320
+ if r.status_code != 200 or not body:
321
+ return {
322
+ "status": "error",
323
+ "error": f"http_{r.status_code}",
324
+ "http_status": r.status_code,
325
+ "wayback_url": r.url,
326
+ "original_url": url,
327
+ }
328
+ if text and is_challenge(text, r.status_code):
329
+ return {
330
+ "status": "error",
331
+ "error": "challenge_or_shell",
332
+ "http_status": r.status_code,
333
+ "wayback_url": r.url,
334
+ "original_url": url,
335
+ "content": text[:2000],
336
+ }
337
+ return {
338
+ "status": "success",
339
+ "content": body,
340
+ "text": text,
341
+ "content_type": ctype,
342
+ "wayback_url": r.url,
343
+ "capture_timestamp": cap_ts,
344
+ "original_url": url,
345
+ "http_status": r.status_code,
346
+ "method": "wayback",
347
+ }
348
+
349
+
350
+ # --- Common Crawl ---
351
+
352
+ def cc_indexes(n: int = 6) -> list[str]:
353
+ global _cc_indexes
354
+ if _cc_indexes is None:
355
+ try:
356
+ r = session().get(CC_COLLINFO, timeout=30)
357
+ cols = r.json() if r.status_code == 200 else []
358
+ ids = []
359
+ for c in cols:
360
+ cid = c.get("id") or ""
361
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
362
+ if cid:
363
+ ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index")
364
+ # collinfo is newest-first. Do not drop crawls that 404 a
365
+ # specific URL (that means "no captures", not a dead index).
366
+ _cc_indexes = ids or [
367
+ "https://index.commoncrawl.org/CC-MAIN-2025-18-index",
368
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
369
+ ]
370
+ except Exception as exc:
371
+ log.warning("cc collinfo: %s", exc)
372
+ _cc_indexes = [
373
+ "https://index.commoncrawl.org/CC-MAIN-2026-34-index",
374
+ "https://index.commoncrawl.org/CC-MAIN-2026-30-index",
375
+ "https://index.commoncrawl.org/CC-MAIN-2026-25-index",
376
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
377
+ ]
378
+ return _cc_indexes[:n]
379
+
380
+
381
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
382
+ """Query public CC CDX (https://index.commoncrawl.org/).
383
+
384
+ Do not send filter=status:200 — on some shards that returns a false
385
+ 404 "No Captures found". Filter status client-side instead.
386
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
387
+ """
388
+ out = []
389
+ seen = set()
390
+ empty = 0
391
+ for idx in (indexes or cc_indexes(12)):
392
+ if idx in _cc_dead:
393
+ continue
394
+ params = {
395
+ "url": url,
396
+ "output": "json",
397
+ "limit": str(limit),
398
+ }
399
+ _sleep_cc(0.3)
400
+ try:
401
+ r = session().get(idx, params=params, timeout=(12, 25))
402
+ except requests.RequestException as exc:
403
+ log.info("cc cdx %s fail %s", idx, exc)
404
+ continue
405
+ if r.status_code == 404:
406
+ msg = (r.text or "")[:80]
407
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
408
+ empty += 1
409
+ if empty >= 8 and not out:
410
+ continue
411
+ continue
412
+ if r.status_code in (410,):
413
+ _cc_dead.add(idx)
414
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
415
+ continue
416
+ if r.status_code != 200 or not r.content:
417
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
418
+ continue
419
+ for line in r.text.splitlines():
420
+ line = line.strip()
421
+ if not line or line[0] not in "{[":
422
+ continue
423
+ try:
424
+ rec = json.loads(line)
425
+ except Exception:
426
+ continue
427
+ orig = rec.get("url") or rec.get("original") or ""
428
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
429
+ if st and st not in ("200", "201", "206"):
430
+ continue
431
+ key = (orig, rec.get("filename"), rec.get("offset"))
432
+ if not orig or key in seen:
433
+ continue
434
+ seen.add(key)
435
+ rec["original"] = orig
436
+ rec["source"] = "common_crawl"
437
+ rec["cc_index"] = idx
438
+ out.append(rec)
439
+ if out:
440
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
441
+ if len(out) >= limit or out:
442
+ break
443
+ return out[:limit]
444
+
445
+
446
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
447
+ data = raw
448
+ if data[:2] == b"\x1f\x8b":
449
+ try:
450
+ data = gzip.decompress(data)
451
+ except Exception:
452
+ try:
453
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
454
+ except Exception:
455
+ pass
456
+ # WARC record: headers, then HTTP payload
457
+ split = data.split(b"\r\n\r\n", 1)
458
+ if len(split) < 2:
459
+ return 0, "", data
460
+ warc_headers, rest = split
461
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
462
+ http_split = rest.split(b"\r\n\r\n", 1)
463
+ http_head = http_split[0].decode("latin-1", "replace")
464
+ body = http_split[1] if len(http_split) > 1 else b""
465
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
466
+ status = int(m.group(1)) if m else 0
467
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
468
+ ctype = cm.group(1).strip() if cm else ""
469
+ return status, ctype, body
470
+ return 0, "", rest
471
+
472
+
473
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
474
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
475
+ try:
476
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
477
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
478
+ except Exception:
479
+ return {"status": "error", "error": "bad_pointer"}
480
+ if not fn or ln <= 0:
481
+ return {"status": "error", "error": "missing_pointer"}
482
+ ln = min(ln, max_bytes)
483
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
484
+ _sleep_cc(0.25)
485
+ try:
486
+ r = session().get(
487
+ url,
488
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
489
+ timeout=(20, 90),
490
+ )
491
+ except requests.RequestException as exc:
492
+ return {"status": "error", "error": str(exc)}
493
+ if r.status_code not in (200, 206) or not r.content:
494
+ return {"status": "error", "error": f"http_{r.status_code}"}
495
+ status, ctype, body = _parse_warc_http(r.content)
496
+ text = ""
497
+ if body and (
498
+ "html" in (ctype or "")
499
+ or "xml" in (ctype or "")
500
+ or "text/" in (ctype or "")
501
+ or not ctype
502
+ ):
503
+ text = body.decode("utf-8", "replace")
504
+ orig = rec.get("original") or rec.get("url") or ""
505
+ if text and is_challenge(text, status or 200):
506
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
507
+ return {
508
+ "status": "success",
509
+ "content": body,
510
+ "text": text,
511
+ "content_type": ctype,
512
+ "original_url": orig,
513
+ "http_status": status or 200,
514
+ "method": "common_crawl",
515
+ "cc_record": {
516
+ "filename": fn,
517
+ "offset": off,
518
+ "length": ln,
519
+ "timestamp": rec.get("timestamp"),
520
+ },
521
+ }
522
+
523
+
524
+ # --- archive.is ---
525
+
526
+ def get_archive_is_content(url: str) -> dict:
527
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
528
+ try:
529
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
530
+ except requests.RequestException as exc:
531
+ log.info("archive.is %s", exc)
532
+ continue
533
+ if r.status_code != 200 or not r.content:
534
+ continue
535
+ if "archive." not in (r.url or ""):
536
+ continue
537
+ text = r.text or ""
538
+ if is_challenge(text, r.status_code):
539
+ continue
540
+ return {
541
+ "status": "success",
542
+ "content": r.content,
543
+ "text": text,
544
+ "content_type": r.headers.get("content-type") or "text/html",
545
+ "archive_url": r.url,
546
+ "original_url": url,
547
+ "http_status": r.status_code,
548
+ "method": "archive_is",
549
+ }
550
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
551
+
552
+
553
+ # --- Direct HTTP last ---
554
+
555
+ def get_http(url: str) -> dict:
556
+ try:
557
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
558
+ except requests.RequestException as exc:
559
+ return {"status": "error", "error": str(exc), "original_url": url}
560
+ text = ""
561
+ ctype = r.headers.get("content-type") or ""
562
+ body = r.content or b""
563
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
564
+ text = body.decode(r.encoding or "utf-8", "replace")
565
+ if r.status_code != 200 or not body:
566
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
567
+ if text and is_challenge(text, r.status_code):
568
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
569
+ return {
570
+ "status": "success",
571
+ "content": body,
572
+ "text": text,
573
+ "content_type": ctype,
574
+ "original_url": url,
575
+ "http_status": r.status_code,
576
+ "method": "http",
577
+ "final_url": r.url,
578
+ }
579
+
580
+
581
+ def fetch_with_fallbacks(
582
+ url: str,
583
+ *,
584
+ cc_record: Optional[dict] = None,
585
+ wayback_ts: Optional[str] = None,
586
+ try_archive_is: bool = False,
587
+ try_http: bool = True,
588
+ try_cc: bool = True,
589
+ ) -> dict:
590
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
591
+
592
+ Brave Search skipped (no API key in this environment).
593
+ Playwright is attempted by the caller when this returns a SPA shell.
594
+ Does not run Wayback CDX search; Wayback is replay only.
595
+ """
596
+ errors = []
597
+ cc_recs: list[dict] = []
598
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
599
+ cc_recs = [cc_record]
600
+ elif try_cc:
601
+ try:
602
+ cc_recs = search_common_crawl(url, limit=4)
603
+ except Exception as exc:
604
+ errors.append(f"common_crawl:{exc}")
605
+ cc_recs = []
606
+ for rec in cc_recs:
607
+ res = fetch_common_crawl_warc(rec)
608
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
609
+ return res
610
+ errors.append(f"common_crawl:{res.get('error')}")
611
+ if wayback_ts or url:
612
+ res = get_wayback_content(url, timestamp=wayback_ts)
613
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
614
+ return res
615
+ errors.append(f"wayback:{res.get('error')}")
616
+ if try_archive_is:
617
+ res = get_archive_is_content(url)
618
+ if res.get("status") == "success":
619
+ return res
620
+ errors.append(f"archive_is:{res.get('error')}")
621
+ if try_http:
622
+ res = get_http(url)
623
+ if res.get("status") == "success":
624
+ return res
625
+ errors.append(f"http:{res.get('error')}")
626
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_by.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Belarus: pravo.by official normative documents / codes."""
3
+ from __future__ import annotations
4
+ import logging, re, sys, time
5
+ from pathlib import Path
6
+ from urllib.parse import urljoin
7
+ from bs4 import BeautifulSoup
8
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
9
+ from common import existing_ids, log_failure, utcnow, write_summary
10
+ from world_lib import cdx_urls, env_int, fetch_official, live_get, save_instrument, setup_log, slug_id
11
+
12
+ CC, COUNTRY, LANG = "by", "Belarus", "ru"
13
+ SOURCE_TYPE = "pravo_by"
14
+ LICENSE = (
15
+ "Национальный правовой Интернет-портал Республики Беларусь (pravo.by). "
16
+ "Official texts prevail. Not legal advice."
17
+ )
18
+ UA = "legal-corpora-collector/1.0 (research; source=https://pravo.by/)"
19
+ ART = re.compile(r"(?im)^\s*((?:Статья|Статья\s+)\s*\d+[^\n]{0,30})\b")
20
+ # Known code document IDs on pravo.by (guid+p0 patterns vary; use list pages + CDX)
21
+ SEED = [
22
+ "https://pravo.by/document/?guid=3871&p0=Hk9800218", # often Constitution-related listings
23
+ ]
24
+ log = logging.getLogger("by")
25
+
26
+
27
+ def discover():
28
+ items, seen = [], set()
29
+ list_urls = [
30
+ "https://pravo.by/pravovaya-informatsiya/normativnye-dokumenty/kodeksy-respubliki-belarus/",
31
+ "https://pravo.by/pravovaya-informatsiya/normativnye-dokumenty/",
32
+ "https://pravo.by/",
33
+ ]
34
+ for lu in list_urls:
35
+ try:
36
+ r = live_get(lu, ua=UA, timeout=(20, 50))
37
+ except Exception as exc:
38
+ log.info("list fail %s: %s", lu, exc)
39
+ continue
40
+ for href in re.findall(r'href="([^"]*document/\?[^"]+)"', r.text or ""):
41
+ url = urljoin("https://pravo.by", href.replace("&amp;", "&"))
42
+ if url in seen:
43
+ continue
44
+ seen.add(url)
45
+ ident = re.sub(r"\W+", "-", url.split("p0=")[-1] if "p0=" in url else url)[:120]
46
+ items.append((ident, url))
47
+ for href in re.findall(r'href="([^"]+\.pdf)"', r.text or "", re.I):
48
+ url = urljoin("https://pravo.by", href)
49
+ if url in seen:
50
+ continue
51
+ seen.add(url)
52
+ items.append((Path(url).stem[:120], url))
53
+ for prefix in ("pravo.by/document/", "pravo.by/upload/", "www.pravo.by/upload/"):
54
+ for h in cdx_urls(prefix, limit=env_int("CDX_LIMIT", 100), match_type="prefix"):
55
+ orig = (h.get("original") or "").replace("http://", "https://")
56
+ if not orig or orig in seen:
57
+ continue
58
+ if ".pdf" in orig.lower() or "document/?" in orig:
59
+ seen.add(orig)
60
+ ident = Path(orig.split("?")[0]).stem[:100] or re.sub(r"\W+", "-", orig)[-80:]
61
+ items.append((ident, orig))
62
+ log.info("catalog %s", len(items))
63
+ return items
64
+
65
+
66
+ def main():
67
+ setup_log(CC)
68
+ t0 = utcnow()
69
+ max_new = env_int("MAX_NEW", 40)
70
+ max_seconds = env_int("MAX_SECONDS", 2000)
71
+ t_start = time.time()
72
+ done = existing_ids(CC)
73
+ ok = skip = fail = 0
74
+ for ident, url in discover():
75
+ if max_new and ok >= max_new:
76
+ break
77
+ if time.time() - t_start > max_seconds:
78
+ break
79
+ rid = slug_id(CC, ident)
80
+ if rid in done:
81
+ skip += 1
82
+ continue
83
+ got = fetch_official(url, ua=UA, min_text=300)
84
+ text = got.get("text") or ""
85
+ if got.get("status") != "success":
86
+ fail += 1
87
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")})
88
+ continue
89
+ title = None
90
+ for line in text.splitlines():
91
+ if len(line.strip()) > 20:
92
+ title = line.strip()[:240]
93
+ break
94
+ if save_instrument(
95
+ cc=CC, country=COUNTRY, language=LANG, ident=ident,
96
+ title=title or ident, text=text, source_url=url,
97
+ source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_by.py",
98
+ article_re=ART, extra_meta={"fetch_method": got.get("method")},
99
+ ):
100
+ ok += 1
101
+ done.add(rid)
102
+ log.info("ok %s chars=%s", ident[:60], len(text))
103
+ else:
104
+ fail += 1
105
+ write_summary(
106
+ CC, country=COUNTRY, source="pravo.by National Legal Internet Portal",
107
+ source_urls=["https://pravo.by/"],
108
+ license_text=LICENSE, discovered=ok + skip + fail, fetched=ok, skipped=skip, failed=fail,
109
+ coverage="codes/documents incomplete",
110
+ notes="Official pravo.by documents. Not legal advice.",
111
+ last_run=t0,
112
+ )
113
+ log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
114
+
115
+
116
+ if __name__ == "__main__":
117
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import traceback
14
+ from collections import Counter
15
+ from datetime import datetime, timezone, timedelta
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Any, Iterable, Optional
19
+ from xml.etree import ElementTree as ET
20
+
21
+ import requests
22
+ from requests.adapters import HTTPAdapter
23
+
24
+ ROOT = Path("/workspace/legal-corpora")
25
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
26
+ PT = timezone(timedelta(hours=-7))
27
+ DEFAULT_UA = (
28
+ "legal-corpora-collector/1.0 "
29
+ "(research archive of official national gazettes; polite; "
30
+ "no commercial scraping; contact via local operator)"
31
+ )
32
+ INDEX_FIELDS = (
33
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
34
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
35
+ "article_count", "bytes",
36
+ )
37
+
38
+ _tls = threading.local()
39
+ _index_lock = threading.Lock()
40
+ _fail_lock = threading.Lock()
41
+ _schema = None
42
+ _schema_lock = threading.Lock()
43
+
44
+
45
+ def utcnow() -> str:
46
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
47
+
48
+
49
+ def pt_from_iso(iso: str) -> str:
50
+ try:
51
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
52
+ except Exception:
53
+ return iso
54
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
55
+
56
+
57
+ def localtag(tag: str) -> str:
58
+ return tag.rsplit("}", 1)[-1]
59
+
60
+
61
+ def slug_id(cc: str, official: str) -> str:
62
+ s = (official or "").strip()
63
+ s = s.replace("https://", "").replace("http://", "")
64
+ s = re.sub(r"[/\\]+", "__", s)
65
+ s = re.sub(r"\s+", "_", s)
66
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
67
+ s = s.strip("-._")
68
+ if not s:
69
+ s = "unknown"
70
+ s = s.lower()
71
+ if not s.startswith(cc.lower() + "-"):
72
+ s = f"{cc.lower()}-{s}"
73
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
74
+ s = "x" + s
75
+ return s[:180]
76
+
77
+
78
+ def atomic_write(path: Path, text: str) -> None:
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
81
+ try:
82
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
83
+ handle.write(text)
84
+ os.replace(tmp, path)
85
+ except Exception:
86
+ try:
87
+ os.unlink(tmp)
88
+ except OSError:
89
+ pass
90
+ raise
91
+
92
+
93
+ def sha256_text(s: str) -> str:
94
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
95
+
96
+
97
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
98
+ s = getattr(_tls, "session", None)
99
+ if s is None or getattr(_tls, "ua", None) != ua:
100
+ s = requests.Session()
101
+ s.headers.update({
102
+ "User-Agent": ua,
103
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
104
+ "Accept-Language": "en,*;q=0.8",
105
+ })
106
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
107
+ s.mount("https://", ad)
108
+ s.mount("http://", ad)
109
+ _tls.session = s
110
+ _tls.ua = ua
111
+ return s
112
+
113
+
114
+ def http_get(
115
+ url: str,
116
+ *,
117
+ ua: str = DEFAULT_UA,
118
+ timeout: tuple = (20, 90),
119
+ retries: int = 5,
120
+ sleep: float = 0.35,
121
+ headers: Optional[dict] = None,
122
+ params: Optional[dict] = None,
123
+ allow_empty: bool = False,
124
+ ) -> requests.Response:
125
+ last = None
126
+ hdrs = headers or {}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ if sleep:
130
+ time.sleep(sleep)
131
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
132
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
133
+ time.sleep(min(30, 2 ** attempt))
134
+ last = resp
135
+ continue
136
+ if resp.status_code == 200 and (allow_empty or resp.content):
137
+ return resp
138
+ if resp.status_code in (404, 410, 403, 401):
139
+ return resp
140
+ last = resp
141
+ if attempt < retries:
142
+ time.sleep(min(20, 1.5 * attempt))
143
+ continue
144
+ return resp
145
+ except requests.RequestException as exc:
146
+ last = exc
147
+ time.sleep(min(20, 1.5 * attempt))
148
+ if isinstance(last, requests.Response):
149
+ return last
150
+ raise RuntimeError(f"GET failed {url}: {last}")
151
+
152
+
153
+ class _HTMLText(HTMLParser):
154
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
155
+
156
+ def __init__(self) -> None:
157
+ super().__init__(convert_charrefs=True)
158
+ self.parts: list[str] = []
159
+ self.skip = 0
160
+ self._block = {
161
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
162
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
163
+ }
164
+
165
+ def handle_starttag(self, tag, attrs):
166
+ if tag in self.SKIP:
167
+ self.skip += 1
168
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
169
+ self.parts.append("\n")
170
+
171
+ def handle_endtag(self, tag):
172
+ if tag in self.SKIP and self.skip:
173
+ self.skip -= 1
174
+ if tag in self._block and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_data(self, data):
178
+ if self.skip == 0:
179
+ self.parts.append(data)
180
+
181
+
182
+ def html_to_text(raw: str) -> str:
183
+ if not raw:
184
+ return ""
185
+ p = _HTMLText()
186
+ try:
187
+ p.feed(raw)
188
+ p.close()
189
+ except Exception:
190
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
191
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
192
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
193
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
194
+ text = "".join(p.parts)
195
+ text = html.unescape(text)
196
+ text = text.replace("\xa0", " ")
197
+ text = re.sub(r"[ \t]+", " ", text)
198
+ text = re.sub(r"\n[ \t]+", "\n", text)
199
+ text = re.sub(r"\n{3,}", "\n\n", text)
200
+ return text.strip()
201
+
202
+
203
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
204
+ skip_tags = skip_tags or {
205
+ "meta", "identification", "references", "classification",
206
+ "workflow", "analysis", "proprietary", "presentation",
207
+ }
208
+ try:
209
+ root = ET.fromstring(raw)
210
+ except ET.ParseError:
211
+ return html_to_text(raw)
212
+ parts: list[str] = []
213
+
214
+ def walk(el: ET.Element) -> None:
215
+ tag = localtag(el.tag).lower()
216
+ if tag in skip_tags:
217
+ return
218
+ if el.text and el.text.strip():
219
+ parts.append(el.text.strip())
220
+ for child in list(el):
221
+ walk(child)
222
+ if child.tail and child.tail.strip():
223
+ parts.append(child.tail.strip())
224
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
225
+ parts.append("\n")
226
+
227
+ walk(root)
228
+ text = " ".join(parts)
229
+ text = re.sub(r"[ \t]+", " ", text)
230
+ text = re.sub(r" *\n *", "\n", text)
231
+ text = re.sub(r"\n{3,}", "\n\n", text)
232
+ return text.strip()
233
+
234
+
235
+ ARTICLE_SPLIT = re.compile(
236
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
237
+ r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"
238
+ r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"
239
+ r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b"
240
+ )
241
+
242
+
243
+
244
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
245
+ if not text or len(text) < 40:
246
+ return []
247
+ matches = list(ARTICLE_SPLIT.finditer(text))
248
+ if len(matches) < 2:
249
+ return []
250
+ docs = []
251
+ for i, m in enumerate(matches):
252
+ start = m.start()
253
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
254
+ chunk = text[start:end].strip()
255
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
256
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
257
+ heading = chunk.split("\n", 1)[0][:200]
258
+ docs.append({
259
+ "id": f"{law_id}-{aid}"[:180],
260
+ "title": heading,
261
+ "text": chunk,
262
+ "date_filed": date,
263
+ "document_number": num,
264
+ "source_url": source_url,
265
+ "record_type": "article",
266
+ "article_number": num,
267
+ "law_identifier": law_id,
268
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
269
+ })
270
+ if len(docs) >= 4000:
271
+ break
272
+ return docs
273
+
274
+
275
+ def load_schema():
276
+ global _schema
277
+ with _schema_lock:
278
+ if _schema is None:
279
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
280
+ _schema = json.load(f)
281
+ return _schema
282
+
283
+
284
+ def validate_record(record: dict) -> Optional[str]:
285
+ try:
286
+ import jsonschema
287
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
288
+ return None
289
+ except Exception as exc:
290
+ return str(exc)
291
+
292
+
293
+ def existing_ids(cc: str) -> set[str]:
294
+ d = ROOT / cc / "instruments"
295
+ if not d.exists():
296
+ return set()
297
+ return {p.stem for p in d.glob("*.json")}
298
+
299
+
300
+ def write_instrument(cc: str, record: dict) -> Path:
301
+ ident = record["id"]
302
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
303
+ dest.parent.mkdir(parents=True, exist_ok=True)
304
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
305
+ atomic_write(dest, body)
306
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
307
+ index_line["path"] = f"instruments/{ident}.json"
308
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
309
+ index_line["bytes"] = dest.stat().st_size
310
+ index_line["id"] = ident
311
+ with _index_lock:
312
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
313
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
314
+ return dest
315
+
316
+
317
+ def log_failure(cc: str, payload: dict) -> None:
318
+ path = ROOT / cc / "failures.jsonl"
319
+ path.parent.mkdir(parents=True, exist_ok=True)
320
+ payload = dict(payload)
321
+ payload.setdefault("retrieved_at", utcnow())
322
+ with _fail_lock:
323
+ with path.open("a", encoding="utf-8") as handle:
324
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
325
+
326
+
327
+ def append_catalog(cc: str, row: dict) -> None:
328
+ path = ROOT / cc / "raw" / "catalog.jsonl"
329
+ path.parent.mkdir(parents=True, exist_ok=True)
330
+ with _index_lock:
331
+ with path.open("a", encoding="utf-8") as handle:
332
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
333
+
334
+
335
+ def law_status_hist(cc: str) -> Counter:
336
+ c: Counter = Counter()
337
+ d = ROOT / cc / "instruments"
338
+ if not d.exists():
339
+ return c
340
+ for p in d.glob("*.json"):
341
+ try:
342
+ rec = json.loads(p.read_text(encoding="utf-8"))
343
+ c[rec.get("law_status") or "unknown"] += 1
344
+ except Exception:
345
+ c["unknown"] += 1
346
+ return c
347
+
348
+
349
+ def corpus_bytes(cc: str) -> int:
350
+ d = ROOT / cc / "instruments"
351
+ if not d.exists():
352
+ return 0
353
+ return sum(p.stat().st_size for p in d.glob("*.json"))
354
+
355
+
356
+ def count_jsonl(path: Path) -> int:
357
+ if not path.exists():
358
+ return 0
359
+ n = 0
360
+ with path.open(encoding="utf-8") as f:
361
+ for _ in f:
362
+ n += 1
363
+ return n
364
+
365
+
366
+ def write_summary(
367
+ cc: str,
368
+ *,
369
+ country: str,
370
+ source: str,
371
+ source_urls: Iterable[str],
372
+ license_text: str,
373
+ discovered: int,
374
+ fetched: int,
375
+ skipped: int,
376
+ failed: int,
377
+ coverage: str,
378
+ notes: str,
379
+ last_run: Optional[str] = None,
380
+ extra: Optional[str] = None,
381
+ ) -> None:
382
+ last_run = last_run or utcnow()
383
+ instr = ROOT / cc / "instruments"
384
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
385
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
386
+ hist = law_status_hist(cc)
387
+ nbytes = corpus_bytes(cc)
388
+ lines = [
389
+ f"# {country} legislation corpus",
390
+ "",
391
+ f"- jurisdiction: {cc.upper()}",
392
+ f"- source: {source}",
393
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
394
+ f"- instruments_json: {n_json}",
395
+ f"- index_jsonl_lines: {n_index}",
396
+ f"- discovered: {discovered}",
397
+ f"- fetched: {fetched}",
398
+ f"- skipped: {skipped}",
399
+ f"- failed: {failed}",
400
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
401
+ f"- coverage: {coverage}",
402
+ f"- total_json_bytes: {nbytes}",
403
+ f"- license: {license_text}",
404
+ "- source_urls:",
405
+ ]
406
+ for u in source_urls:
407
+ lines.append(f" - {u}")
408
+ lines.append("- notes:")
409
+ for n in (notes or "").splitlines():
410
+ lines.append(f" {n}")
411
+ if extra:
412
+ lines.append("")
413
+ lines.append(extra)
414
+ lines.append("")
415
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
416
+
417
+
418
+ def base_record(
419
+ *,
420
+ cc: str,
421
+ country: str,
422
+ language: str,
423
+ ident: str,
424
+ title: str,
425
+ text: str,
426
+ source_url: str,
427
+ source_type: str,
428
+ license_text: str,
429
+ collector: str,
430
+ eli: Optional[str] = None,
431
+ date: Optional[str] = None,
432
+ official_identifier: Optional[str] = None,
433
+ document_type: str = "statute",
434
+ law_status: str = "current",
435
+ is_current: Optional[bool] = True,
436
+ documents: Optional[list] = None,
437
+ extra_meta: Optional[dict] = None,
438
+ extra_fields: Optional[dict] = None,
439
+ ) -> dict:
440
+ rid = slug_id(cc, ident)
441
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
442
+ rec = {
443
+ "schema_version": "collection_record.v1",
444
+ "record_type": "law",
445
+ "id": rid,
446
+ "title": title or ident,
447
+ "text": text or "",
448
+ "source_url": source_url,
449
+ "source_type": source_type,
450
+ "date": date,
451
+ "jurisdiction": cc.upper(),
452
+ "country": country,
453
+ "language": language,
454
+ "eli": eli,
455
+ "license": license_text,
456
+ "retrieved_at": utcnow(),
457
+ "identifier": official_identifier or ident,
458
+ "official_identifier": official_identifier or ident,
459
+ "law_identifier": official_identifier or ident,
460
+ "document_type": document_type,
461
+ "law_status": law_status,
462
+ "is_current": is_current,
463
+ "canonical_law_url": source_url,
464
+ "article_count": len(docs),
465
+ "article_extraction_status": "ok" if docs else "missing",
466
+ "documents": docs,
467
+ "metadata": {
468
+ "collector": collector,
469
+ "schema": "collection_record.v1",
470
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
471
+ "content_sha256": sha256_text(text or ""),
472
+ "rights": {
473
+ "not_legal_advice": True,
474
+ "official_reuse_url": source_url,
475
+ "license": license_text,
476
+ },
477
+ "text_extraction": {"source": "official", "backend": "collector"},
478
+ },
479
+ }
480
+ if extra_meta:
481
+ rec["metadata"].update(extra_meta)
482
+ if extra_fields:
483
+ rec.update(extra_fields)
484
+ return rec
485
+
486
+
487
+ def ensure_dirs(cc: str) -> Path:
488
+ root = ROOT / cc
489
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
490
+ (root / "raw").mkdir(parents=True, exist_ok=True)
491
+ (root / "logs").mkdir(parents=True, exist_ok=True)
492
+ return root
493
+
494
+
495
+ def iso_date(val: Optional[str]) -> Optional[str]:
496
+ if not val:
497
+ return None
498
+ val = str(val).strip()
499
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
500
+ if m:
501
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
502
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
503
+ if m:
504
+ return m.group(1)
505
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
506
+ if m:
507
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
508
+ return None
scrapers/world_lib.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
109
+ import requests
110
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
111
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
112
+ last = None
113
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
114
+ for attempt in range(1, retries + 1):
115
+ try:
116
+ time.sleep(0.2)
117
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
118
+ return resp
119
+ except Exception as exc:
120
+ last = exc
121
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
122
+ try:
123
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
124
+ return resp
125
+ except Exception as exc2:
126
+ last = exc2
127
+ time.sleep(min(8, 1.5 * attempt))
128
+ raise RuntimeError(f"live_get failed {url}: {last}")
129
+
130
+
131
+ def fetch_official(
132
+ url: str,
133
+ *,
134
+ ua: str = DEFAULT_UA,
135
+ verify: bool = True,
136
+ wayback: bool = True,
137
+ wayback_ts: Optional[str] = None,
138
+ min_text: int = MIN_TEXT,
139
+ ) -> dict:
140
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
141
+ out = {
142
+ "status": "error",
143
+ "text": "",
144
+ "content": b"",
145
+ "source_url": url,
146
+ "method": "",
147
+ "content_type": "",
148
+ "error": "",
149
+ }
150
+ body = b""
151
+ ctype = ""
152
+ try:
153
+ r = live_get(url, ua=ua, verify=verify)
154
+ body = r.content or b""
155
+ ctype = r.headers.get("content-type") or ""
156
+ if r.status_code == 200 and body:
157
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
158
+ text = pdf_to_text(body)
159
+ if len(text) >= min_text:
160
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
161
+ return out
162
+ text = ""
163
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
164
+ raw = body.decode(r.encoding or "utf-8", "replace")
165
+ if af.is_challenge(raw, r.status_code):
166
+ out["error"] = "challenge_or_shell"
167
+ else:
168
+ text = html_to_text(raw) if "<" in raw[:500] else raw
169
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
170
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
171
+ return out
172
+ if len(text) < min_text:
173
+ out["error"] = "short_or_spa"
174
+ elif body[:4] == b"%PDF":
175
+ out["error"] = "pdf_extract_failed"
176
+ elif len(body) > min_text:
177
+ try:
178
+ text = body.decode("utf-8", "replace")
179
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
180
+ out["error"] = "raw_pdf_bytes"
181
+ elif len(text) >= min_text:
182
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
183
+ return out
184
+ except Exception:
185
+ pass
186
+ else:
187
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
188
+ except Exception as exc:
189
+ out["error"] = f"live:{exc}"
190
+
191
+ if wayback:
192
+ try:
193
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
194
+ if w.get("status") == "success":
195
+ raw_b = w.get("content") or b""
196
+ raw_t = w.get("text") or ""
197
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
198
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
199
+ text = pdf_to_text(pdf_bytes)
200
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
201
+ out.update(
202
+ status="success",
203
+ text=text,
204
+ content=pdf_bytes,
205
+ method="wayback_pdf",
206
+ source_url=w.get("url") or url,
207
+ content_type="application/pdf",
208
+ )
209
+ return out
210
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
211
+ return out
212
+ if not raw_t and isinstance(raw_b, bytes):
213
+ raw_t = raw_b.decode("utf-8", "replace")
214
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
215
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
216
+ return out
217
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
218
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
219
+ out.update(
220
+ status="success",
221
+ text=text,
222
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
223
+ method="wayback_html",
224
+ source_url=w.get("url") or url,
225
+ content_type=w.get("content_type") or "text/html",
226
+ )
227
+ return out
228
+ out["error"] = (out.get("error") or "") + ";wayback_short"
229
+ else:
230
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
231
+ except Exception as exc:
232
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
233
+ return out
234
+
235
+
236
+ def first_title(text: str, fallback: str) -> str:
237
+ for line in (text or "").splitlines():
238
+ s = line.strip()
239
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
240
+ return s[:240]
241
+ return fallback[:240]
242
+
243
+
244
+ def save_instrument(
245
+ *,
246
+ cc: str,
247
+ country: str,
248
+ language: str,
249
+ ident: str,
250
+ title: str,
251
+ text: str,
252
+ source_url: str,
253
+ source_type: str,
254
+ license_text: str,
255
+ collector: str,
256
+ date: Optional[str] = None,
257
+ article_re: Optional[re.Pattern] = None,
258
+ extra_meta: Optional[dict] = None,
259
+ ) -> bool:
260
+ if not text or len(text) < MIN_TEXT:
261
+ return False
262
+ rid = slug_id(cc, ident)
263
+ docs = split_custom(text, rid, source_url, date, article_re)
264
+ rec = base_record(
265
+ cc=cc,
266
+ country=country,
267
+ language=language,
268
+ ident=ident,
269
+ title=title or first_title(text, ident),
270
+ text=text,
271
+ source_url=source_url,
272
+ source_type=source_type,
273
+ license_text=license_text,
274
+ collector=collector,
275
+ date=iso_date(date) or date,
276
+ documents=docs,
277
+ extra_meta=extra_meta,
278
+ )
279
+ write_instrument(cc, rec)
280
+ return True
281
+
282
+
283
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
284
+ try:
285
+ hits = af.search_wayback_machine(
286
+ host_or_url,
287
+ limit=limit,
288
+ match_type=match_type,
289
+ collapse="urlkey",
290
+ extra_filters=extra_filters,
291
+ )
292
+ except Exception as exc:
293
+ log.info("cdx err %s: %s", host_or_url, exc)
294
+ return []
295
+ return hits or []
296
+
297
+
298
+ def env_int(name: str, default: int) -> int:
299
+ try:
300
+ return int(os.environ.get(name, str(default)) or default)
301
+ except Exception:
302
+ return default