endomorphosis commited on
Commit
c5ec941
·
verified ·
1 Parent(s): f34be21

Refresh Honduras official snapshot (200 laws / 4330 articles; tsc.gob.hn La Gaceta)

Browse files
MANIFEST.md CHANGED
@@ -1,9 +1,26 @@
1
- # MANIFEST
2
 
3
- - generated_at: 2026-09-04T20:07:07Z
4
- - laws: 40
5
- - articles: 529
6
- - files:
7
- - data/laws.parquet: 644133 bytes
8
- - data/articles.parquet: 493804 bytes
9
- - README.md: 1817 bytes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_honduras_laws manifest
2
 
3
+ generated_utc: 2026-09-08T23:32:55Z
4
+ cc: hn
5
+ laws_rows: 200
6
+ articles_rows: 4330
7
+ laws_bytes: 2271454
8
+ articles_bytes: 2103036
9
+ laws_sha256: b0361320825423b3c9e1669383a3ed8d45cf3a9b24a8ca8f15463bde04c9a4d9
10
+ articles_sha256: 38060b6ec82b3512a02e47233b2ab47d13a3bdd15351b029dee860f0a6b4a6cd
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_honduras_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_honduras_laws/data/articles.parquet
13
+ compression: zstd
14
+ collector: scrapers/collect_hn.py
15
+ license: Official Honduras La Gaceta texts mirrored by TSC; authentic La Gaceta prevails; not legal advice
16
+ retrieval: live-and-wayback-of-official
17
+ live_instruments: 200
18
+ archive_instruments: 0
19
+ wayback_instruments: 0
20
+ common_crawl_instruments: 0
21
+ archive_is_instruments: 0
22
+ constitution_present: false
23
+ catalog_expected: None
24
+ catalog_gap:
25
+ gaps: Official PDFs from tsc.gob.hn/web/leyes only (live + Wayback). Gap-fill above thin Hub ~40. Not vLex.
26
+ uploaded: false
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
- pretty_name: Laws of Honduras
3
  license: other
4
- license_name: hn-tsc-gaceta
5
  language:
6
  - es
7
  task_categories:
@@ -10,9 +10,11 @@ tags:
10
  - legal
11
  - law
12
  - honduras
 
 
13
  - official-texts
14
  size_categories:
15
- - n<1K
16
  configs:
17
  - config_name: laws
18
  data_files: data/laws.parquet
@@ -21,44 +23,42 @@ configs:
21
  data_files: data/articles.parquet
22
  ---
23
 
24
- # Laws of Honduras
25
 
26
- Research snapshot of official legislation collected from **TSC / La Gaceta tsc.gob.hn/web/leyes**.
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 | TSC / La Gaceta tsc.gob.hn/web/leyes |
37
  | Collector | `scrapers/collect_hn.py` |
38
- | Laws / instruments | 40 |
39
- | Articles | 529 |
40
  | Language | es |
41
  | Jurisdiction | Honduras |
42
- | License | `hn-tsc-gaceta` |
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_hn.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
- Official gazette/portal PDFs via live+Wayback. Catalog-backed incomplete. Not legal advice.
 
 
 
 
 
1
  ---
2
+ pretty_name: Honduras La Gaceta Laws (TSC / tsc.gob.hn)
3
  license: other
4
+ license_name: hn-la-gaceta
5
  language:
6
  - es
7
  task_categories:
 
10
  - legal
11
  - law
12
  - honduras
13
+ - la-gaceta
14
+ - tsc
15
  - official-texts
16
  size_categories:
17
+ - 1K<n<10K
18
  configs:
19
  - config_name: laws
20
  data_files: data/laws.parquet
 
23
  data_files: data/articles.parquet
24
  ---
25
 
26
+ # Honduras La Gaceta Laws (TSC / tsc.gob.hn)
27
 
28
+ Research snapshot of official national legislation from **Tribunal Superior de Cuentas / La Gaceta (tsc.gob.hn)**.
29
 
30
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
31
 
32
  ## Snapshot
33
 
34
  | Field | Value |
35
  | --- | --- |
36
+ | Snapshot date | 2026-09-08 |
37
  | Coverage | catalog-backed incomplete |
38
+ | Source | Tribunal Superior de Cuentas / La Gaceta (tsc.gob.hn) |
39
  | Collector | `scrapers/collect_hn.py` |
40
+ | Laws / instruments | 200 |
41
+ | Articles | 4,330 |
42
  | Language | es |
43
  | Jurisdiction | Honduras |
44
+ | License | `hn-la-gaceta` |
45
 
46
  ## Contents
47
 
48
+ - `data/laws.parquet` — one row per instrument.
49
+ - `data/articles.parquet` — article/section rows for the same snapshot.
50
  - `scrapers/collect_hn.py` — research collector used to build this snapshot.
 
 
 
51
 
52
  ## License / reuse
53
 
54
+ Official Honduras La Gaceta texts mirrored by TSC; authentic La Gaceta prevails; not legal advice.
 
 
55
 
56
+ This dataset is **not legal advice**. The official source prevails.
 
57
 
58
+ ## Source
59
 
60
+ - https://www.tsc.gob.hn/web/leyes/
61
+
62
+ ## Known gaps
63
+
64
+ Official PDFs from tsc.gob.hn/web/leyes only (live + Wayback). Gap-fill above thin Hub ~40. Not vLex.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d3b1c8008b0d6dea5212e1ae38b28774b5b1754e60e090cc6adef5a7fa295657
3
- size 493804
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38060b6ec82b3512a02e47233b2ab47d13a3bdd15351b029dee860f0a6b4a6cd
3
+ size 2103036
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c318e67cd24a03157efcafc2114f19d4c3a5d155d2bfc75ca9f27e29bcac925b
3
- size 644133
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0361320825423b3c9e1669383a3ed8d45cf3a9b24a8ca8f15463bde04c9a4d9
3
+ size 2271454
scrapers/archive_fallbacks.py CHANGED
@@ -24,8 +24,10 @@ from requests.adapters import HTTPAdapter
24
 
25
  log = logging.getLogger("archive_fallbacks")
26
 
27
- WAYBACK_CDX = "http://web.archive.org/cdx/search/cdx"
28
- WAYBACK_WEB = "http://web.archive.org/web"
 
 
29
  CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
  CC_DATA = "https://data.commoncrawl.org"
31
  ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
@@ -207,7 +209,11 @@ def _wayback_cdx_page(
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)
@@ -283,54 +289,112 @@ def search_wayback_machine(
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
  }
@@ -339,42 +403,50 @@ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
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
 
@@ -400,8 +472,12 @@ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str
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)
 
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/"
 
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)
 
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
  }
 
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
 
 
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)
scrapers/collect_hn.py CHANGED
@@ -38,7 +38,7 @@ def discover():
38
  "tsc.gob.hn/web/leyes/",
39
  "www.tsc.gob.hn/leyes/",
40
  ):
41
- for h in cdx_urls(prefix, limit=env_int("CDX_LIMIT", 250), match_type="prefix",
42
  extra_filters=["mimetype:application/pdf"]):
43
  orig = h.get("original") or ""
44
  if orig:
@@ -50,8 +50,8 @@ def discover():
50
  def main():
51
  setup_log(CC)
52
  t0 = utcnow()
53
- max_new = env_int("MAX_NEW", 40)
54
- max_seconds = env_int("MAX_SECONDS", 2400)
55
  t_start = time.time()
56
  done = existing_ids(CC)
57
  ok = skip = fail = 0
 
38
  "tsc.gob.hn/web/leyes/",
39
  "www.tsc.gob.hn/leyes/",
40
  ):
41
+ for h in cdx_urls(prefix, limit=env_int("CDX_LIMIT", 2000), match_type="prefix",
42
  extra_filters=["mimetype:application/pdf"]):
43
  orig = h.get("original") or ""
44
  if orig:
 
50
  def main():
51
  setup_log(CC)
52
  t0 = utcnow()
53
+ max_new = env_int("MAX_NEW", 200)
54
+ max_seconds = env_int("MAX_SECONDS", 3600)
55
  t_start = time.time()
56
  done = existing_ids(CC)
57
  ok = skip = fail = 0
scrapers/common.py CHANGED
@@ -234,13 +234,11 @@ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
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 []
@@ -506,3 +504,28 @@ def iso_date(val: Optional[str]) -> Optional[str]:
506
  if m:
507
  return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
508
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 []
 
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 CHANGED
@@ -105,7 +105,20 @@ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], p
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)
@@ -138,6 +151,7 @@ def fetch_official(
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": "",
 
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)
 
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": "",