endomorphosis commited on
Commit
b2afb69
·
verified ·
1 Parent(s): 1785b59

Add Namibia official snapshot (80 laws / 491 articles; parliament.gov.na)

Browse files
MANIFEST.md CHANGED
@@ -1,9 +1,26 @@
1
- # MANIFEST
2
 
3
- - generated_at: 2026-09-05T10:17:38Z
4
- - laws: 165
5
- - articles: 650
6
- - files:
7
- - data/laws.parquet: 2987233 bytes
8
- - data/articles.parquet: 1809346 bytes
9
- - README.md: 1861 bytes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_namibia_laws manifest
2
 
3
+ generated_utc: 2026-09-09T07:49:21Z
4
+ cc: na
5
+ laws_rows: 80
6
+ articles_rows: 491
7
+ laws_bytes: 895564
8
+ articles_bytes: 733354
9
+ laws_sha256: dcd1094c496a92cb7ca5cfca5490294bbe9c7a9092c3420498f48db7e0a059a0
10
+ articles_sha256: aa8c57ca99695413c69bd0036138938d0a96668a3eeac86061f4162f52f71089
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_namibia_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_namibia_laws/data/articles.parquet
13
+ compression: zstd
14
+ collector: scrapers/collect_na.py
15
+ license: Republic of Namibia — parliament.gov.na / laws.parliament.na / parliament.na / gov.na / moj.gov.na / opm.gov.na. Authentic Government Gazette / Act text prevails. Not legal advice.
16
+ retrieval: live-and-wayback-of-official
17
+ live_instruments: 80
18
+ archive_instruments: 0
19
+ wayback_instruments: 0
20
+ common_crawl_instruments: 0
21
+ archive_is_instruments: 0
22
+ constitution_present: false
23
+ catalog_expected: None
24
+ catalog_gap:
25
+ gaps: Official Namibia law PDFs from parliament.gov.na, laws.parliament.na, parliament.na, gov.na, moj.gov.na, opm.gov.na and related *.gov.na hosts. Live-first; Wayback/CDX of official URLs on fail. Not AfricanLII / NamibLII / lac.org.na. No WAF bypass. Not legal advice.
26
+ uploaded: false
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
- pretty_name: Laws of Namibia
3
  license: other
4
- license_name: na-parliament-laws
5
  language:
6
  - en
7
  task_categories:
@@ -10,6 +10,12 @@ tags:
10
  - legal
11
  - law
12
  - namibia
 
 
 
 
 
 
13
  - official-texts
14
  size_categories:
15
  - n<1K
@@ -21,44 +27,42 @@ configs:
21
  data_files: data/articles.parquet
22
  ---
23
 
24
- # Laws of Namibia
25
 
26
- Research snapshot of official legislation collected from **Parliament of Namibia / Laws of Namibia (parliament.na, laws.parliament.na)**.
27
 
28
- **Not legal advice.** Official gazettes / government portals prevail over this corpus.
29
 
30
  ## Snapshot
31
 
32
  | Field | Value |
33
  | --- | --- |
34
- | Snapshot date | 2026-09-05 |
35
- | Coverage | catalog-backed incomplete |
36
- | Source | Parliament of Namibia / Laws of Namibia (parliament.na, laws.parliament.na) |
37
  | Collector | `scrapers/collect_na.py` |
38
- | Laws / instruments | 165 |
39
- | Articles | 650 |
40
  | Language | en |
41
  | Jurisdiction | Namibia |
42
- | License | `na-parliament-laws` |
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_na.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
- Refreshed freeze after CC deepen. instruments=165.
 
 
 
 
 
1
  ---
2
+ pretty_name: Namibia Acts and Official Gazettes (Parliament / Gov.na / MoJ / OPM)
3
  license: other
4
+ license_name: na-parliament-gov-moj-official-texts
5
  language:
6
  - en
7
  task_categories:
 
10
  - legal
11
  - law
12
  - namibia
13
+ - parliament
14
+ - gov-na
15
+ - moj
16
+ - opm
17
+ - gazette
18
+ - acts
19
  - official-texts
20
  size_categories:
21
  - n<1K
 
27
  data_files: data/articles.parquet
28
  ---
29
 
30
+ # Namibia Acts and Official Gazettes (Parliament / Gov.na / MoJ / OPM)
31
 
32
+ Research snapshot of official national legislation from **Parliament (parliament.gov.na / laws.parliament.na / parliament.na) / Government Portal (gov.na) / Ministry of Justice (moj.gov.na) / Office of the Prime Minister (opm.gov.na) and other *.gov.na gazette hosts**.
33
 
34
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
35
 
36
  ## Snapshot
37
 
38
  | Field | Value |
39
  | --- | --- |
40
+ | Snapshot date | 2026-09-09 |
41
+ | Coverage | catalog-backed incomplete (parliament/gov/moj/opm live + CDX Acts/gazettes PDFs) |
42
+ | Source | Parliament (parliament.gov.na / laws.parliament.na / parliament.na) / Government Portal (gov.na) / Ministry of Justice (moj.gov.na) / Office of the Prime Minister (opm.gov.na) and other *.gov.na gazette hosts |
43
  | Collector | `scrapers/collect_na.py` |
44
+ | Laws / instruments | 80 |
45
+ | Articles | 491 |
46
  | Language | en |
47
  | Jurisdiction | Namibia |
48
+ | License | `na-parliament-gov-moj-official-texts` |
49
 
50
  ## Contents
51
 
52
+ - `data/laws.parquet` — one row per instrument.
53
+ - `data/articles.parquet` — article/section rows for the same snapshot.
54
  - `scrapers/collect_na.py` — research collector used to build this snapshot.
 
 
 
55
 
56
  ## License / reuse
57
 
58
+ Republic of Namibia — parliament.gov.na / laws.parliament.na / parliament.na / gov.na / moj.gov.na / opm.gov.na. Authentic Government Gazette / Act text prevails. Not legal advice..
 
 
59
 
60
+ This dataset is **not legal advice**. The official source prevails.
 
61
 
62
+ ## Source
63
 
64
+ - https://www.parliament.gov.na/
65
+
66
+ ## Known gaps
67
+
68
+ Official Namibia law PDFs from parliament.gov.na, laws.parliament.na, parliament.na, gov.na, moj.gov.na, opm.gov.na and related *.gov.na hosts. Live-first; Wayback/CDX of official URLs on fail. Not AfricanLII / NamibLII / lac.org.na. No WAF bypass. Not legal advice.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:56e2f6b042b5b8c46a89cb08bdd04c7aadbbb4a440fabdfc1960150fd55de2fc
3
- size 1809346
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa8c57ca99695413c69bd0036138938d0a96668a3eeac86061f4162f52f71089
3
+ size 733354
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0371cb4c8096307944c343acbcdd099dde0ac7e69d22ccaaed4b38a83385ef41
3
- size 2987233
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcd1094c496a92cb7ca5cfca5490294bbe9c7a9092c3420498f48db7e0a059a0
3
+ size 895564
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_na.py CHANGED
@@ -1,591 +1,208 @@
1
  #!/usr/bin/env python3
2
- """Namibia: official Bills / Acts / Gazette instruments from Parliament + BoN.
3
 
4
- Primary: laws.parliament.na (Online Bill Tracking — embedded official Bill PDFs),
5
- www.parliament.na (wp-content Bill / Act PDFs + wp-json media), Bank of Namibia
6
- (bon.com.na Regulations / Determinations / Act getattachment PDFs).
7
-
8
- Skips: lac.org.na (entirely), namiblii.org, SAFLII, gazettes.africa, speeches,
9
- motivations, contributions, tenders, minutes, notices of award.
10
-
11
- Live official URL first; Wayback of the same official URL on failure.
12
- OCR=1 enables pdftoppm+tesseract for image-only official PDFs. No WAF bypass.
13
-
14
- Gaps (recorded): www.gov.na SSL EOF from collector host; moj.gov.na timeout;
15
- mfpe.gov.na DNS fail; laws.parliament.na/cms_documents live often 404 → Wayback; full Government Gazette series not mirrored on parliament.na.
16
  """
17
  from __future__ import annotations
18
-
19
- import base64
20
- import logging
21
- import os
22
- import re
23
- import subprocess
24
- import sys
25
- import tempfile
26
- import time
27
  from pathlib import Path
28
- from urllib.parse import unquote, urljoin, urlparse
29
-
30
  sys.path.insert(0, str(Path(__file__).resolve().parent))
31
- from common import existing_ids, log_failure, utcnow, write_summary
32
- from world_lib import cdx_urls, env_int, fetch_official, fetch_official_prefer_pdf, live_get, save_instrument, setup_log, slug_id
33
 
34
  CC, COUNTRY, LANG = "na", "Namibia", "en"
35
- SOURCE_TYPE = "namibia_official_parliament_bon"
36
  LICENSE = (
37
- "Laws / Bills / Gazette instruments of Namibia as published on official "
38
- "Parliament portals (parliament.na / laws.parliament.na) and Bank of Namibia "
39
- "(bon.com.na) statutory hosts. Authentic Government Gazette / Parliament text "
40
- "prevails. Not legal advice."
 
41
  )
42
- UA = "legal-corpora-collector/1.0 (research; source=https://www.parliament.na/)"
43
  ART = re.compile(
44
- r"(?im)^\s*((?:Section|Sec\.|Article|Art\.|Regulation|Reg\.)\s+\d+[A-Za-z]?\.?)\b"
45
  )
46
  log = logging.getLogger("na")
47
-
48
- BLOCK_HOST = re.compile(
49
- r"(lac\.org\.na|namiblii\.org|saflii\.org|gazettes\.africa|"
50
- r"africanlii\.org|commonlii\.org|ulii\.org)",
51
- re.I,
52
- )
53
- SKIP_NAME = re.compile(
54
- r"(contribution|motivation|response|speech|report[_\-\s]|NOTICE[_\-\s]?OF|"
55
- r"minutes|tender|award|vacancy|advert|newsletter|workshop|consultative|"
56
- r"stakeholder|explanatory[_\-\s]?memorandum|budget[_\-\s]?statement|"
57
- r"vote\d|sofa|upholstery|procurement[_\-\s]?notice|selection[_\-\s]?for|"
58
- r"cancellation[_\-\s]?of[_\-\s]?a[_\-\s]?bid|facilitator|travel[_\-\s]?management|"
59
- r"supply[_\-\s]?and[_\-\s]?delivery|service[_\-\s]?level[_\-\s]?agreement|"
60
- r"strategy[_\-\s]?advert|mefmi[_\-\s]?advertisement)",
61
- re.I,
62
  )
63
- LAWISH_NAME = re.compile(
64
- r"("
65
- r"\bbill\b|_bill_|-bill-|bill\.pdf|"
66
- r"\bact\b|_act_|-act-|act\.pdf|"
67
- r"gazette|regulation|regulations|determination|"
68
- r"constitution|statutory[_\-\s]?instrument|"
69
- r"\bb\.?\s*\d+|amendment"
70
- r")",
 
71
  re.I,
72
  )
73
- LAW_MARK = re.compile(
74
- r"(BE IT ENACTED|AN ACT\b|A BILL\b|BILL\b|Short title|"
75
- r"This Act may be cited|GOVERNMENT GAZETTE|REPUBLIC OF NAMIBIA|"
76
- r"ARRANGEMENT OF SECTIONS|NATIONAL ASSEMBLY|PROMULGATION OF ACT|"
77
- r"No\.\s*\d+\s+of\s+20\d{2}|\[B\.\s*\d+)",
78
  re.I,
79
  )
80
-
81
- CDX_PREFIXES = [
82
- "laws.parliament.na/cms_documents/",
83
- "www.parliament.na/wp-content/uploads/",
84
- "parliament.na/wp-content/uploads/",
85
- "www.bon.com.na/CMSTemplates/Bon/Files/",
86
- "bon.com.na/CMSTemplates/Bon/Files/",
87
- ]
88
-
89
- LIVE_SEEDS = [
90
- "https://www.parliament.na/bills/",
91
- "https://www.parliament.na/acts-of-parliament/",
92
- "https://laws.parliament.na/Bill-register",
93
- "https://www.bon.com.na/Regulations.aspx",
94
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks.aspx",
95
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Determinations.aspx",
96
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Regulations.aspx",
97
- ]
98
-
99
- BON_SEED_PAGES = [
100
- "https://www.bon.com.na/Regulations.aspx",
101
- "https://www.bon.com.na/Regulations/Bank-of-Namibia-Act-2020.aspx",
102
- "https://www.bon.com.na/Regulations/Banking-Institutions-Act-2023.aspx",
103
- "https://www.bon.com.na/Regulations/Virtual-Assets-Act-2023.aspx",
104
- "https://www.bon.com.na/Regulations/Financial-Intelligence-Act-2012.aspx",
105
- "https://www.bon.com.na/Regulations/Namibia-Deposit-Guarantee-Act-2018.aspx",
106
- "https://www.bon.com.na/Regulations/Payment-System-Management-Act-2003.aspx",
107
- "https://www.bon.com.na/Regulations/Payment-System-Management-Amendment-Act-2023.aspx",
108
- "https://www.bon.com.na/Regulations/Currencies-and-Exchanges-Act-1933.aspx",
109
- "https://www.bon.com.na/Regulations/Prevention-of-Counterfeiting-of-Currency-Act-1965.aspx",
110
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Determinations.aspx",
111
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Regulations.aspx",
112
- "https://www.bon.com.na/Bank/Banking-Supervision/Legal-Frameworks/Other-Bylaws.aspx",
113
- "https://www.bon.com.na/Bank/National-Payment-System/Legal-Framework.aspx",
114
- "https://www.bon.com.na/Bank/Financial-Stability/Determinations-Regulations-and-Guidance-Notes.aspx",
115
- ]
116
-
117
-
118
- def _norm(url: str) -> str:
119
- u = (url or "").split("#")[0]
120
- u = u.replace("http://", "https://")
121
- u = re.sub(r":80/", "/", u)
122
- u = re.sub(r"https://parliament\.na/", "https://www.parliament.na/", u)
123
- u = re.sub(r"https://bon\.com\.na/", "https://www.bon.com.na/", u)
124
- # Drop tracking query junk; keep empty for getattachment
125
- parts = urlparse(u)
126
- path = parts.path or ""
127
- if " " in unquote(path) or "%" in path:
128
- from urllib.parse import quote
129
-
130
- path = quote(unquote(path), safe="/%")
131
- return parts._replace(path=path, query="", params="", fragment="").geturl().rstrip("?")
132
-
133
-
134
- def _ident_from_url(url: str) -> str:
135
- path = unquote(urlparse(url.split("?")[0]).path)
136
- name = Path(path).name
137
- if name.lower() in ("", ".aspx", ".aspx/") or name.lower() == ".aspx":
138
- # BoN getattachment/<uuid>/.aspx
139
- m = re.search(r"getattachment/([0-9a-f-]{36})", url, re.I)
140
- if m:
141
- name = f"bon-{m.group(1)[:12]}"
142
- else:
143
- name = Path(path.rstrip("/")).name or "na-doc"
144
- if name.lower().endswith(".pdf"):
145
- name = name[:-4]
146
- if name.lower().endswith(".aspx"):
147
- name = name[:-5]
148
- name = re.sub(r"\s+", " ", name).strip()
149
- return re.sub(r"[^\w.\-]+", "-", name)[:160] or "na-doc"
150
 
151
 
152
  def _host_ok(url: str) -> bool:
153
- if not url or not url.startswith("http"):
154
- return False
155
- if BLOCK_HOST.search(url):
156
- return False
157
- host = (urlparse(url).hostname or "").lower()
158
- ok = (
159
- "parliament.na",
160
- "bon.com.na",
161
- "gov.na",
162
- "moj.gov.na",
163
- "mfpe.gov.na",
164
- "opm.gov.na",
165
- )
166
- return any(host == s or host.endswith("." + s) for s in ok)
167
-
168
-
169
- def _is_law_url(url: str) -> bool:
170
- u = _norm(url)
171
- if not _host_ok(u):
172
- return False
173
- low = unquote(u).lower()
174
- if SKIP_NAME.search(low):
175
  return False
176
- # Historic laws.parliament.na statute book (live often 404 → Wayback)
177
- if "laws.parliament.na" in low and "/cms_documents/" in low and ".pdf" in low:
178
- return True
179
- # BoN getattachment — accepted when discovered from Act/Determination pages
180
- if "parliament.gov.na" in low and "/acts_documents/" in low and ".pdf" in low:
181
- return True
182
- if "bon.com.na" in low and "/getattachment/" in low:
183
- return True
184
- if "bon.com.na" in low and "/cmstemplates/bon/files/" in low and ".pdf" in low:
185
- return True
186
- if ".pdf" not in low:
187
- return False
188
- name = unquote(urlparse(u.split("?")[0]).path).split("/")[-1]
189
- if SKIP_NAME.search(name):
190
- return False
191
- if LAWISH_NAME.search(name) or LAWISH_NAME.search(low):
192
  return True
193
  return False
194
 
195
 
196
- def _title_from_text(text: str, fallback: str) -> str:
197
- lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
198
- for ln in lines[:60]:
199
- if re.search(r"\b(ACT|BILL|REGULATIONS?|GAZETTE|DETERMINATION)\b", ln) and 8 <= len(ln) <= 180:
200
- if not re.match(r"^(TITLE|PREVIOUS|NEXT|CONTENTS|EXPLANATORY)\b", ln, re.I):
201
- return ln[:240]
202
- for ln in lines:
203
- if len(ln) >= 12 and not ln.lower().startswith("just a moment"):
204
- return ln[:240]
205
- return fallback[:240]
206
-
207
-
208
- def _looks_like_law(text: str) -> bool:
209
- if not text or len(text) < 200:
210
- return False
211
- head = text[:10000]
212
- if LAW_MARK.search(head):
213
- return True
214
- secs = len(re.findall(r"(?im)^\s*Section\s+\d+", text[:25000]))
215
- return secs >= 5
216
-
217
-
218
- def _add(items: list, seen: set, url: str, ident: str | None = None) -> None:
219
- url = _norm(url)
220
- if not url or url in seen or not _is_law_url(url):
221
- return
222
- seen.add(url)
223
- items.append((ident or _ident_from_url(url), url))
224
-
225
-
226
- def pdf_ocr_text(raw: bytes, *, max_pages: int = 30, dpi: int = 160) -> str:
227
- """OCR scanned / image-only official PDFs via pdftoppm + tesseract (eng)."""
228
- if not raw or raw[:4] != b"%PDF":
229
- return ""
230
- max_pages = env_int("OCR_MAX_PAGES", max_pages)
231
- try:
232
- with tempfile.TemporaryDirectory() as d:
233
- pdf = Path(d) / "in.pdf"
234
- pdf.write_bytes(raw)
235
- subprocess.run(
236
- [
237
- "pdftoppm",
238
- "-png",
239
- "-r",
240
- str(dpi),
241
- "-f",
242
- "1",
243
- "-l",
244
- str(max_pages),
245
- str(pdf),
246
- str(Path(d) / "p"),
247
- ],
248
- check=False,
249
- capture_output=True,
250
- timeout=300,
251
- )
252
- pages = sorted(Path(d).glob("p*.png"))
253
- chunks = []
254
- for page in pages:
255
- proc = subprocess.run(
256
- ["tesseract", str(page), "stdout", "-l", "eng", "--psm", "6"],
257
- capture_output=True,
258
- timeout=180,
259
- )
260
- if proc.stdout:
261
- chunks.append(proc.stdout.decode("utf-8", "replace"))
262
- return "\n".join(chunks).strip()
263
- except Exception as exc:
264
- log.info("ocr fail: %s", exc)
265
- return ""
266
-
267
-
268
- def fetch_na(url: str) -> dict:
269
- """Live (+Wayback of same official URL); OCR when OCR=1 for image-only PDFs."""
270
- got = fetch_official_prefer_pdf(url, ua=UA, verify=False, min_text=180)
271
- if got.get("status") == "success":
272
- return got
273
- if os.environ.get("OCR", "0") != "1":
274
- return got
275
- err = got.get("error") or ""
276
- body = got.get("content") if isinstance(got.get("content"), (bytes, bytearray)) else b""
277
- if not body or body[:4] != b"%PDF":
278
- try:
279
- r = live_get(url, ua=UA, verify=False, timeout=(15, 90), retries=2)
280
- body = r.content or b""
281
- except Exception:
282
- body = b""
283
- if (not body or body[:4] != b"%PDF") and "wayback" not in err:
284
- try:
285
- import archive_fallbacks as af
286
-
287
- w = af.get_wayback_content(url)
288
- if w.get("status") == "success":
289
- body = w.get("content") or b""
290
- if isinstance(body, str):
291
- body = body.encode("latin-1", "replace")
292
- except Exception:
293
- pass
294
- if body and body[:4] == b"%PDF":
295
- text = pdf_ocr_text(bytes(body))
296
- if len(text) >= 180:
297
- got.update(
298
- status="success",
299
- text=text,
300
- content=bytes(body),
301
- method=(got.get("method") or "http") + "+ocr",
302
- error="",
303
- )
304
- return got
305
- got["error"] = (err or "") + ";ocr_short_or_failed"
306
- return got
307
-
308
-
309
- def _decode_data_pdf(html: str) -> bytes:
310
- m = re.search(r"data:application/pdf;base64,([A-Za-z0-9+/=\s&#x0-9a-fA-F;]+)", html or "")
311
- if not m:
312
- return b""
313
- b64 = m.group(1)
314
- b64 = (
315
- b64.replace("&#x2B;", "+")
316
- .replace("&#x2F;", "/")
317
- .replace("&#x3D;", "=")
318
- .replace("&amp;", "&")
319
- .replace("&#43;", "+")
320
- )
321
- b64 = re.sub(r"\s+", "", b64)
322
- # strip residual HTML entities
323
- b64 = re.sub(r"&#x[0-9a-fA-F]+;", "", b64)
324
- b64 = re.sub(r"&#\d+;", "", b64)
325
- try:
326
- raw = base64.b64decode(b64, validate=False)
327
- except Exception:
328
- return b""
329
- return raw if raw[:4] == b"%PDF" else b""
330
-
331
-
332
- def _harvest_html(url: str) -> list[str]:
333
- out = []
334
- try:
335
- r = live_get(url, ua=UA, verify=False, timeout=(20, 50))
336
- except Exception as exc:
337
- log.info("seed fail %s: %s", url[:90], exc)
338
- return out
339
- text = r.text or ""
340
- for href in re.findall(r'href=["\']([^"\']+)["\']', text, re.I):
341
- full = urljoin(url, href)
342
- if ".pdf" in full.lower() or "/getattachment/" in full.lower():
343
- out.append(full)
344
- for m in re.findall(r'(https?://[^"\'\s>]+\.pdf)', text, re.I):
345
- out.append(m)
346
- return out
347
-
348
-
349
- def _laws_parliament_bills() -> list[tuple[str, str, str]]:
350
- """Return (ident, synthetic_source_url, detail_url) for Bill Tracking PDFs.
351
-
352
- Instruments are stored against the Public/Bills/Details/<uuid> official URL;
353
- PDF bytes are embedded as data:application/pdf;base64 on that page.
354
- """
355
- items, seen = [], set()
356
- register = "https://laws.parliament.na/Bill-register"
357
- try:
358
- r = live_get(register, ua=UA, verify=False, timeout=(25, 70))
359
- except Exception as exc:
360
- log.info("bill register fail: %s", exc)
361
- return items
362
- ids = sorted(set(re.findall(r"/Public/Bills/Details/([0-9a-f-]{36})", r.text or "", re.I)))
363
- log.info("laws.parliament.na bill ids %s", len(ids))
364
- cap = env_int("BILL_DETAILS", 120)
365
- for bid in ids[:cap]:
366
- detail = f"https://laws.parliament.na/Public/Bills/Details/{bid}"
367
- if detail in seen:
368
- continue
369
- seen.add(detail)
370
- # Title from register table if present
371
- m = re.search(
372
- rf'href=["\']/Public/Bills/Details/{bid}["\'][^>]*>([^<]{{3,120}})',
373
- r.text or "",
374
- re.I,
375
- )
376
- label = (m.group(1).strip() if m else "") or f"bill-{bid[:8]}"
377
- ident = re.sub(r"[^\w.\-]+", "-", label)[:120] or f"bill-{bid[:8]}"
378
- items.append((ident, detail, detail))
379
- return items
380
-
381
-
382
- def _fetch_embedded_bill(detail_url: str) -> dict:
383
- out = {
384
- "status": "error",
385
- "text": "",
386
- "content": b"",
387
- "source_url": detail_url,
388
- "method": "",
389
- "error": "",
390
- }
391
- try:
392
- r = live_get(detail_url, ua=UA, verify=False, timeout=(30, 120), retries=2)
393
- except Exception as exc:
394
- out["error"] = f"live:{exc}"
395
- return out
396
- html = r.text or ""
397
- title_m = re.search(r'<h2[^>]*class="[^"]*page-title[^"]*"[^>]*>([^<]+)', html, re.I)
398
- page_title = (title_m.group(1).strip() if title_m else "")
399
- raw = _decode_data_pdf(html)
400
- if not raw:
401
- out["error"] = "no_embedded_pdf"
402
- return out
403
- # text extract
404
- from world_lib import pdf_to_text
405
 
406
- text = pdf_to_text(raw)
407
- method = "embedded_pdf"
408
- if len(text) < 180 and os.environ.get("OCR", "0") == "1":
409
- ocr = pdf_ocr_text(raw)
410
- if len(ocr) > len(text):
411
- text, method = ocr, "embedded_pdf+ocr"
412
- if len(text) < 180:
413
- out.update(error="pdf_extract_failed", content=raw)
414
- return out
415
- out.update(
416
- status="success",
417
- text=text,
418
- content=raw,
419
- method=method,
420
- source_url=detail_url,
421
- page_title=page_title,
422
- )
423
- return out
424
 
425
-
426
- def _wp_json_media() -> list[tuple[str, str]]:
427
- items, seen = [], set()
428
- try:
429
- import requests
430
- from requests.packages.urllib3.exceptions import InsecureRequestWarning
431
-
432
- requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
433
- except Exception:
434
- return items
435
- for page in range(1, env_int("WP_MEDIA_PAGES", 8) + 1):
436
- url = (
437
- "https://www.parliament.na/wp-json/wp/v2/media"
438
- f"?per_page=100&page={page}&mime_type=application/pdf"
439
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  try:
441
- r = requests.get(url, timeout=(20, 50), headers={"User-Agent": UA}, verify=False)
442
- except Exception as exc:
443
- log.info("wp media fail page %s: %s", page, exc)
444
- break
445
- if r.status_code != 200:
446
- break
447
- data = r.json() if r.content else []
448
- if not data:
449
- break
450
- for it in data:
451
- su = it.get("source_url") or ""
452
- if not su or su in seen:
453
  continue
454
- if not _is_law_url(su):
455
- continue
456
- seen.add(su)
457
- items.append((_ident_from_url(su), su))
458
- log.info("wp-json lawish pdfs %s", len(items))
459
- return items
460
-
461
-
462
- def _bon_attachments() -> list[tuple[str, str]]:
463
- items, seen = [], set()
464
- pages = list(BON_SEED_PAGES)
465
- # Expand Regulations.aspx child Act pages
466
- try:
467
- r = live_get("https://www.bon.com.na/Regulations.aspx", ua=UA, verify=False, timeout=(20, 50))
468
- for href in re.findall(r'href=["\']([^"\']+)["\']', r.text or "", re.I):
469
- full = urljoin("https://www.bon.com.na/Regulations.aspx", href)
470
- if re.search(r"/Regulations/[^\"']+(Act|Regulation|Determination)", full, re.I):
471
- if full not in pages:
472
- pages.append(full)
473
- except Exception as exc:
474
- log.info("bon regulations index fail: %s", exc)
475
-
476
- for page in pages[: env_int("BON_PAGES", 40)]:
 
 
 
 
 
 
 
 
477
  try:
478
- r = live_get(page, ua=UA, verify=False, timeout=(20, 50))
 
 
 
 
 
479
  except Exception as exc:
480
- log.info("bon page fail %s: %s", page[:80], exc)
481
- continue
482
- # Prefer labelled Act/Determination attachments near lawish anchor text
483
- html = r.text or ""
484
- for href in re.findall(r'href=["\']([^"\']*getattachment[^"\']*)["\']', html, re.I):
485
- full = _norm(urljoin(page, href))
486
- if full in seen:
 
 
 
487
  continue
488
- # Skip obvious image/css attachments by fetching later; filter by nearby text
489
- seen.add(full)
490
- # ident from surrounding context if possible
491
- slug = Path(urlparse(page).path).name.replace(".aspx", "")
492
- m = re.search(r"getattachment/([0-9a-f-]{36})", full, re.I)
493
- uuid = m.group(1)[:12] if m else "att"
494
- ident = f"{slug}-{uuid}"[:140]
495
- items.append((ident, full))
496
- log.info("bon attachments %s", len(items))
497
- return items
498
-
499
-
500
- def discover():
501
- items, seen = [], set()
502
-
503
- # 1) Live seed harvest (parliament + BoN HTML)
504
- for su in LIVE_SEEDS:
505
- for href in _harvest_html(su):
506
- _add(items, seen, href)
507
-
508
- # 2) Parliament wp-json media (Bill/Act PDFs)
509
- for ident, url in _wp_json_media():
510
- _add(items, seen, url, ident)
511
-
512
- # 3) BoN Act / Determination / Regulation attachments
513
- for ident, url in _bon_attachments():
514
- # BoN getattachment always allowed when harvested from Act pages
515
- url = _norm(url)
516
- if not url or url in seen or not _host_ok(url):
517
- continue
518
- if BLOCK_HOST.search(url):
519
- continue
520
- seen.add(url)
521
- items.append((ident, url))
522
-
523
- # 4) CDX of official hosts
524
- limit = env_int("CDX_LIMIT", 500)
525
- for prefix in CDX_PREFIXES:
526
- for h in cdx_urls(prefix, limit=limit, match_type="prefix", extra_filters=["mimetype:application/pdf"]):
527
- orig = (h.get("original") or "").replace("http://", "https://")
528
- _add(items, seen, orig)
529
- if len(items) >= env_int("CATALOG_CAP", 500):
530
- break
531
-
532
- log.info("catalog pdf/attach %s", len(items))
533
- return items
534
 
535
 
536
  def main():
537
  setup_log(CC)
538
  t0 = utcnow()
539
  max_new = env_int("MAX_NEW", 80)
540
- max_seconds = env_int("MAX_SECONDS", 3600)
541
  t_start = time.time()
542
  done = existing_ids(CC)
 
 
543
  ok = skip = fail = 0
544
-
545
- # A) Embedded Bill PDFs from laws.parliament.na (priority — official Bill Tracking)
546
- for ident, source_url, detail in _laws_parliament_bills():
547
  if max_new and ok >= max_new:
548
  break
549
- if time.time() - t_start > max_seconds:
550
- break
551
- rid = slug_id(CC, ident)
552
- if rid in done:
553
- skip += 1
554
- continue
555
- got = _fetch_embedded_bill(detail)
556
- text = got.get("text") or ""
557
- if got.get("status") != "success":
558
- fail += 1
559
- log_failure(CC, {"identifier": ident, "source_url": source_url, "reason": got.get("error")})
560
- continue
561
- if not _looks_like_law(text):
562
- fail += 1
563
- log_failure(CC, {"identifier": ident, "source_url": source_url, "reason": "not_law_like"})
564
- continue
565
- title = got.get("page_title") or _title_from_text(text, ident)
566
- if save_instrument(
567
- cc=CC,
568
- country=COUNTRY,
569
- language=LANG,
570
- ident=ident,
571
- title=title,
572
- text=text,
573
- source_url=source_url,
574
- source_type=SOURCE_TYPE,
575
- license_text=LICENSE,
576
- collector="collect_na.py",
577
- article_re=ART,
578
- extra_meta={"fetch_method": got.get("method"), "portal": "laws.parliament.na"},
579
- ):
580
- ok += 1
581
- done.add(rid)
582
- log.info("ok bill %s chars=%s method=%s", ident[:70], len(text), got.get("method"))
583
- else:
584
- fail += 1
585
-
586
- # B) Direct PDF / BoN attachment catalog
587
- for ident, url in discover():
588
- if max_new and ok >= max_new:
589
  break
590
  if time.time() - t_start > max_seconds:
591
  break
@@ -593,67 +210,51 @@ def main():
593
  if rid in done:
594
  skip += 1
595
  continue
596
- got = fetch_na(url)
597
  text = got.get("text") or ""
598
  if got.get("status") != "success":
599
  fail += 1
600
- log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")})
601
  continue
602
- if not _looks_like_law(text):
 
603
  fail += 1
604
- log_failure(CC, {"identifier": ident, "source_url": url, "reason": "not_law_like"})
605
  continue
606
- title = _title_from_text(text, ident)
 
 
 
 
607
  if save_instrument(
608
- cc=CC,
609
- country=COUNTRY,
610
- language=LANG,
611
- ident=ident,
612
- title=title,
613
- text=text,
614
- source_url=url,
615
- source_type=SOURCE_TYPE,
616
- license_text=LICENSE,
617
- collector="collect_na.py",
618
- article_re=ART,
619
- extra_meta={"fetch_method": got.get("method")},
620
  ):
621
  ok += 1
622
  done.add(rid)
623
- log.info("ok %s chars=%s method=%s", ident[:70], len(text), got.get("method"))
624
  else:
625
  fail += 1
626
-
627
  write_summary(
628
- CC,
629
- country=COUNTRY,
630
- source="Namibia Parliament (parliament.na / laws.parliament.na) + Bank of Namibia",
631
  source_urls=[
632
- "https://www.parliament.na/",
633
  "https://laws.parliament.na/",
634
- "https://laws.parliament.na/Bill-register",
635
- "https://www.bon.com.na/Regulations.aspx",
636
  "https://www.gov.na/",
 
 
637
  ],
638
- license_text=LICENSE,
639
- discovered=ok + skip + fail,
640
- fetched=ok,
641
- skipped=skip,
642
- failed=fail,
643
- coverage=(
644
- "catalog-backed incomplete; lac.org.na skipped by policy; "
645
- "gov.na/moj.gov.na/mfpe.gov.na unreachable or SSL-fail from collector host; "
646
- "full Government Gazette series not on parliament.na"
647
- ),
648
- notes=(
649
- "Official Bills from laws.parliament.na Bill Tracking (embedded PDFs) and "
650
- "parliament.na wp-content; BoN Act/Determination/Regulation getattachment PDFs. "
651
- "Skipped lac.org.na / NamibLII / SAFLII. OCR when OCR=1. Not legal advice."
652
- ),
653
  last_run=t0,
654
  )
655
- log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
656
 
657
 
658
  if __name__ == "__main__":
659
- main()
 
1
  #!/usr/bin/env python3
2
+ """Namibia: official Acts / Bills / Gazette PDFs via *.gov.na + parliament.na.
3
 
4
+ Official hosts only: parliament.gov.na, laws.parliament.na, parliament.na,
5
+ gov.na, moj.gov.na, opm.gov.na and other *.gov.na gazette hosts.
6
+ Not AfricanLII / NamibLII / lac.org.na / commercial DBs as source text.
7
+ No WAF bypass. Live-first; Wayback/CDX of official URLs OK (pass CDX timestamps).
 
 
 
 
 
 
 
 
8
  """
9
  from __future__ import annotations
10
+ import logging, re, sys, time
 
 
 
 
 
 
 
 
11
  from pathlib import Path
12
+ from urllib.parse import urljoin, urlsplit, unquote
 
13
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from common import existing_ids, http_get, log_failure, utcnow, write_summary
15
+ from world_lib import cdx_urls, env_int, fetch_official, save_instrument, setup_log, slug_id
16
 
17
  CC, COUNTRY, LANG = "na", "Namibia", "en"
18
+ SOURCE_TYPE = "namibia_official_gazette_acts"
19
  LICENSE = (
20
+ "Republic of Namibia Parliament (parliament.gov.na / laws.parliament.na / "
21
+ "parliament.na) / Government Portal (gov.na) / Ministry of Justice (moj.gov.na) / "
22
+ "Office of the Prime Minister (opm.gov.na) and other *.gov.na gazette hosts. "
23
+ "Authentic Government Gazette / Act text prevails. "
24
+ "Not AfricanLII / NamibLII / lac.org.na / commercial DBs. Not legal advice."
25
  )
26
+ UA = "legal-corpora-collector/1.0 (research; source=https://www.parliament.gov.na/)"
27
  ART = re.compile(
28
+ r"(?im)^\s*((?:Article|Art\.?|Section|Sec\.?|Cap\.?|Chapter|Part)\s*[0-9]+)\b"
29
  )
30
  log = logging.getLogger("na")
31
+ HOMES = [
32
+ # Live SSL flaky on many *.gov.na / parliament.gov.na; lean live set, lean on CDX/Wayback.
33
+ "https://laws.parliament.na/",
34
+ "https://laws.parliament.na/Bill-register",
35
+ "https://www.parliament.na/",
36
+ "https://www.parliament.na/bills/",
37
+ "https://www.parliament.na/acts-of-parliament/",
38
+ ]
39
+ # Official Namibia government / parliament hosts (NOT lac.org.na, NOT namiblii)
40
+ ALLOWED = (
41
+ "gov.na",
42
+ "parliament.gov.na",
43
+ "parliament.na",
44
+ "laws.parliament.na",
 
45
  )
46
+ DROP_RE = re.compile(
47
+ r"(africanlii|namiblii|namlii|law\.africa|gazettes\.africa|"
48
+ r"lac\.org\.na|saflii|commonlii|"
49
+ r"/news/|/videos?/|interview|"
50
+ r"facebook|youtube|twitter|logo|banner|photo|recruitment|vacancy|newsletter|"
51
+ r"tender|procurement|job[_-]?announcement|press[_-]?release|"
52
+ r"strategic.?plan|annual.?report|brochure|flyer|calendar|factsheet|"
53
+ r"application.?form|speech|budget.?speech|manifesto|hansard|"
54
+ r"speakercv|contribution|motivation|minutes|workshop)",
55
  re.I,
56
  )
57
+ KEEP_RE = re.compile(
58
+ r"(act|acts|bill|statute|ordinance|proclamation|gazette|law|legal|"
59
+ r"constitution|subsidiary|instrument|regulation|order|cap\.?\s*\d|"
60
+ r"amendment|decree|statutory.?instrument|\bSI\b|legislation|"
61
+ r"acts_documents|cms_documents|promulgation)",
62
  re.I,
63
  )
64
+ MAX_PDF_BYTES = 12 * 1024 * 1024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  def _host_ok(url: str) -> bool:
68
+ host = (urlsplit(url).hostname or "").lower()
69
+ if any(x in host for x in (
70
+ "africanlii", "namiblii", "namlii", "gazettes.africa",
71
+ "law.africa", "lac.org.na", "saflii", "commonlii",
72
+ )):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  return False
74
+ # Exact / suffix match for allowed suffixes
75
+ for s in ALLOWED:
76
+ if host == s or host.endswith("." + s):
77
+ return True
78
+ # *.gov.na catch-all (already covered by gov.na suffix, but be explicit)
79
+ if host.endswith(".gov.na") or host == "gov.na":
 
 
 
 
 
 
 
 
 
 
80
  return True
81
  return False
82
 
83
 
84
+ def _norm_url(url: str) -> str:
85
+ url = (url or "").split("#")[0].strip()
86
+ if url.startswith("http://"):
87
+ url = "https://" + url[len("http://") :]
88
+ url = re.sub(r"(https?://[^/:]+):80/", r"\1/", url)
89
+ # Drop :80 port leftovers
90
+ url = re.sub(r"(https?://[^/:]+):80(/|$)", r"\1\2", url)
91
+ return url
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
+ def discover():
95
+ """Return list of (ident, url, wayback_ts|None). Live homes first; CDX with timestamps."""
96
+ items = [] # (priority, ident, url, ts)
97
+ seen = set()
98
+
99
+ def add(url: str, ts: str | None = None, priority: int = 50):
100
+ url = _norm_url(url)
101
+ if not url.startswith("http"):
102
+ return
103
+ if not _host_ok(url) or DROP_RE.search(url):
104
+ return
105
+ if ".pdf" not in url.lower():
106
+ return
107
+ blob = unquote(url)
108
+ if not KEEP_RE.search(blob):
109
+ if not re.search(
110
+ r"(?i)/(acts?|laws?|gazette|legislation|publications?|documents?|"
111
+ r"downloads?|files?|statutory|si[_/\-]|cap[_/\-]|"
112
+ r"acts_documents|cms_documents|uploads)",
113
+ blob,
114
+ ):
115
+ return
116
+ key = url.lower()
117
+ if key in seen:
118
+ return
119
+ seen.add(key)
120
+ ident = re.sub(r"^https?://[^/]+/", "", unquote(url)).replace("/", "-").replace("?", "-")[:160]
121
+ items.append((priority, ident, url, ts))
122
+
123
+ for home in HOMES:
124
  try:
125
+ r = http_get(home, ua=UA, sleep=0.25)
126
+ if getattr(r, "status_code", 0) != 200:
 
 
 
 
 
 
 
 
 
 
127
  continue
128
+ for href in re.findall(r'href=["\']([^"\']+)["\']', r.text or "", re.I):
129
+ add(urljoin(home, href.replace("&amp;", "&")), ts=None, priority=10)
130
+ for href in re.findall(r'(https?://[^\s"\'<>]+\.pdf)', r.text or "", re.I):
131
+ add(href, ts=None, priority=10)
132
+ for href in re.findall(r'["\'](/[^"\']+\.pdf)["\']', r.text or "", re.I):
133
+ add(urljoin(home, href), ts=None, priority=10)
134
+ except Exception as exc:
135
+ log.info("home %s %s", home, exc)
136
+
137
+ cdx_prefixes = (
138
+ "www.parliament.gov.na/acts_documents/",
139
+ "parliament.gov.na/acts_documents/",
140
+ "www.parliament.gov.na/",
141
+ "parliament.gov.na/",
142
+ "laws.parliament.na/cms_documents/",
143
+ "laws.parliament.na/",
144
+ "www.parliament.na/wp-content/uploads/",
145
+ "parliament.na/wp-content/uploads/",
146
+ "www.parliament.na/",
147
+ "www.gov.na/documents/",
148
+ "gov.na/documents/",
149
+ "www.moj.gov.na/",
150
+ "moj.gov.na/",
151
+ "www.opm.gov.na/",
152
+ "opm.gov.na/",
153
+ "www.mof.gov.na/",
154
+ "www.mti.gov.na/",
155
+ "www.mhss.gov.na/",
156
+ "www.npc.gov.na/",
157
+ )
158
+ for prefix in cdx_prefixes:
159
  try:
160
+ hits = cdx_urls(
161
+ prefix,
162
+ limit=env_int("CDX_LIMIT", 220),
163
+ match_type="prefix",
164
+ extra_filters=["statuscode:200", "mimetype:application/pdf"],
165
+ ) or []
166
  except Exception as exc:
167
+ log.info("cdx %s %s", prefix, exc)
168
+ hits = []
169
+ for h in hits:
170
+ orig = h.get("original") or ""
171
+ ts = (h.get("timestamp") or "")[:14] or None
172
+ try:
173
+ length = int(h.get("length") or 0)
174
+ except Exception:
175
+ length = 0
176
+ if length and length > MAX_PDF_BYTES:
177
  continue
178
+ pri = 20
179
+ if re.search(
180
+ r"(?i)(act|gazette|constitution|statutory|bill|/laws?/|/legislation|acts_documents|cms_documents)",
181
+ unquote(orig),
182
+ ):
183
+ pri = 15
184
+ add(orig, ts=ts, priority=pri)
185
+
186
+ items.sort(key=lambda x: (x[0], x[1]))
187
+ out = [(ident, url, ts) for _, ident, url, ts in items]
188
+ log.info("catalog %s", len(out))
189
+ return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
 
192
  def main():
193
  setup_log(CC)
194
  t0 = utcnow()
195
  max_new = env_int("MAX_NEW", 80)
196
+ max_seconds = env_int("MAX_SECONDS", 2400)
197
  t_start = time.time()
198
  done = existing_ids(CC)
199
+ already = len(done)
200
+ target_total = env_int("TARGET_TOTAL", 0)
201
  ok = skip = fail = 0
202
+ for ident, url, ts in discover():
 
 
203
  if max_new and ok >= max_new:
204
  break
205
+ if target_total and (already + ok) >= target_total:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  break
207
  if time.time() - t_start > max_seconds:
208
  break
 
210
  if rid in done:
211
  skip += 1
212
  continue
213
+ got = fetch_official(url, ua=UA, min_text=200, wayback_ts=ts)
214
  text = got.get("text") or ""
215
  if got.get("status") != "success":
216
  fail += 1
217
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error"), "wayback_ts": ts})
218
  continue
219
+ if len(text) > 2_500_000:
220
+ log.info("skip huge text chars=%s %s", len(text), ident[:50])
221
  fail += 1
222
+ log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_too_large", "chars": len(text)})
223
  continue
224
+ title = None
225
+ for line in text.splitlines():
226
+ if len(line.strip()) > 18:
227
+ title = line.strip()[:240]
228
+ break
229
  if save_instrument(
230
+ cc=CC, country=COUNTRY, language=LANG, ident=ident,
231
+ title=title or ident, text=text, source_url=url,
232
+ source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_na.py",
233
+ article_re=ART, extra_meta={"fetch_method": got.get("method"), "wayback_ts": ts},
 
 
 
 
 
 
 
 
234
  ):
235
  ok += 1
236
  done.add(rid)
237
+ log.info("ok %s method=%s chars=%s ts=%s", ident[:60], got.get("method"), len(text), ts)
238
  else:
239
  fail += 1
 
240
  write_summary(
241
+ CC, country=COUNTRY,
242
+ source="Namibia Official Gazette / Acts (parliament.gov.na / laws.parliament.na / gov.na / moj.gov.na / opm.gov.na)",
 
243
  source_urls=[
244
+ "https://www.parliament.gov.na/",
245
  "https://laws.parliament.na/",
246
+ "https://www.parliament.na/",
 
247
  "https://www.gov.na/",
248
+ "https://www.moj.gov.na/",
249
+ "https://www.opm.gov.na/",
250
  ],
251
+ license_text=LICENSE, discovered=ok + skip + fail, fetched=ok, skipped=skip, failed=fail,
252
+ coverage="catalog-backed incomplete (PDF-first live+CDX *.gov.na / parliament.na with timestamps)",
253
+ notes="Official *.gov.na / parliament.na PDFs only. Not AfricanLII/NamibLII/lac.org.na. No WAF bypass. Not legal advice.",
 
 
 
 
 
 
 
 
 
 
 
 
254
  last_run=t0,
255
  )
256
+ log.info("done ok=%s skip=%s fail=%s total_instruments=%s", ok, skip, fail, len(done))
257
 
258
 
259
  if __name__ == "__main__":
260
+ main()
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/world_lib.py CHANGED
@@ -52,50 +52,20 @@ def setup_log(cc: str, name: str | None = None) -> None:
52
 
53
 
54
  def pdf_to_text(raw: bytes) -> str:
55
- """Extract text via pdftotext. Tries qpdf --decrypt first for copy-restricted
56
- digital PDFs (still not OCR — image-only scans stay empty)."""
57
- if not raw:
58
  return ""
59
- if raw[:4] != b"%PDF":
60
- idx = raw.find(b"%PDF")
61
- if idx < 0 or idx > 8192:
62
- return ""
63
- raw = raw[idx:]
64
  try:
65
- with tempfile.TemporaryDirectory() as d:
66
- dpath = Path(d)
67
- src = dpath / "in.pdf"
68
- src.write_bytes(raw)
69
- candidates = [src]
70
- dec = dpath / "dec.pdf"
71
- try:
72
- q = subprocess.run(
73
- ["qpdf", "--decrypt", str(src), str(dec)],
74
- check=False,
75
- capture_output=True,
76
- timeout=120,
77
- )
78
- if q.returncode == 0 and dec.exists() and dec.stat().st_size > 1000:
79
- candidates.insert(0, dec)
80
- except Exception:
81
- pass
82
- best = ""
83
- for cand in candidates:
84
- for args in (
85
- ["pdftotext", "-layout", "-enc", "UTF-8", str(cand), "-"],
86
- ["pdftotext", "-raw", "-enc", "UTF-8", str(cand), "-"],
87
- ):
88
- proc = subprocess.run(
89
- args, check=False, capture_output=True, timeout=180
90
- )
91
- if proc.returncode == 0 and proc.stdout:
92
- text = proc.stdout.decode("utf-8", "replace").strip()
93
- # Ignore form-feed-only / tiny junk from image-only pages
94
- if len(text) > len(best):
95
- best = text
96
- if len(best) >= 150:
97
- break
98
- return best
99
  except Exception as exc:
100
  log.warning("pdftotext: %s", exc)
101
  return ""
@@ -105,24 +75,18 @@ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], p
105
  docs = split_articles(text, law_id, source_url, date)
106
  if not pattern:
107
  return docs
108
- # Normalize bidi + eastern digits so Arabic/Persian article markers match
109
- try:
110
- from pdf_extract_lib import normalize_rtl_text
111
- work = normalize_rtl_text(text or "")
112
- except Exception:
113
- work = text or ""
114
- matches = list(pattern.finditer(work))
115
  if len(matches) < 2:
116
  return docs if len(docs) >= 2 else []
117
  out = []
118
  for i, m in enumerate(matches):
119
  start = m.start()
120
- end = matches[i + 1].start() if i + 1 < len(matches) else len(work)
121
- chunk = work[start:end].strip()
122
  if len(chunk) < 20:
123
  continue
124
  num = re.sub(r"\s+", " ", m.group(1)).strip()
125
- aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F\u0600-\u06FF-]+", "-", num.lower()).strip("-")[:80]
126
  heading = chunk.split("\n", 1)[0][:200]
127
  out.append({
128
  "id": f"{law_id}-{aid}"[:180],
@@ -141,7 +105,20 @@ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], p
141
  return out if len(out) >= 2 else docs
142
 
143
 
144
- def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (12, 25), verify: bool = True, retries: int = 2):
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  import requests
146
  from requests.packages.urllib3.exceptions import InsecureRequestWarning
147
  requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
@@ -174,6 +151,7 @@ def fetch_official(
174
  min_text: int = MIN_TEXT,
175
  ) -> dict:
176
  """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
 
177
  out = {
178
  "status": "error",
179
  "text": "",
@@ -185,20 +163,12 @@ def fetch_official(
185
  }
186
  body = b""
187
  ctype = ""
188
- skip_live = os.environ.get("SKIP_LIVE", "0") not in ("0", "false", "False", "")
189
  try:
190
- if skip_live:
191
- raise RuntimeError("skip_live")
192
  r = live_get(url, ua=ua, verify=verify)
193
  body = r.content or b""
194
  ctype = r.headers.get("content-type") or ""
195
  if r.status_code == 200 and body:
196
- is_pdf = (
197
- body[:4] == b"%PDF"
198
- or (0 <= body.find(b"%PDF") <= 64)
199
- or "pdf" in ctype.lower()
200
- )
201
- if is_pdf:
202
  text = pdf_to_text(body)
203
  if len(text) >= min_text:
204
  out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
@@ -215,12 +185,8 @@ def fetch_official(
215
  return out
216
  if len(text) < min_text:
217
  out["error"] = "short_or_spa"
218
- elif body[:4] == b"%PDF" or (0 <= body.find(b"%PDF") <= 64):
219
- # Keep bytes so callers (OCR) can work without a second download
220
- pdf_body = body if body[:4] == b"%PDF" else body[body.find(b"%PDF"):]
221
  out["error"] = "pdf_extract_failed"
222
- out["content"] = pdf_body
223
- out["content_type"] = ctype or "application/pdf"
224
  elif len(body) > min_text:
225
  try:
226
  text = body.decode("utf-8", "replace")
@@ -242,25 +208,8 @@ def fetch_official(
242
  if w.get("status") == "success":
243
  raw_b = w.get("content") or b""
244
  raw_t = w.get("text") or ""
245
- pdf_bytes = b""
246
- if isinstance(raw_b, (bytes, bytearray)) and raw_b:
247
- if raw_b[:4] == b"%PDF":
248
- pdf_bytes = bytes(raw_b)
249
- else:
250
- _idx = raw_b.find(b"%PDF", 0, 8192)
251
- if _idx >= 0:
252
- pdf_bytes = bytes(raw_b[_idx:])
253
- if not pdf_bytes and raw_t:
254
- enc = raw_t.encode("latin-1", "replace")
255
- if enc[:4] == b"%PDF":
256
- pdf_bytes = enc
257
- else:
258
- _idx = enc.find(b"%PDF", 0, 8192)
259
- if _idx >= 0:
260
- pdf_bytes = enc[_idx:]
261
- if pdf_bytes or (isinstance(raw_b, bytes) and (w.get("content_type") or "").lower().find("pdf") >= 0):
262
- if not pdf_bytes and isinstance(raw_b, bytes):
263
- pdf_bytes = raw_b
264
  text = pdf_to_text(pdf_bytes)
265
  if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
266
  out.update(
@@ -268,19 +217,15 @@ def fetch_official(
268
  text=text,
269
  content=pdf_bytes,
270
  method="wayback_pdf",
271
- source_url=w.get("wayback_url") or w.get("url") or url,
272
  content_type="application/pdf",
273
  )
274
  return out
275
- # Keep PDF bytes so callers (OCR) can work without a second download
276
  out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
277
- out["content"] = pdf_bytes
278
- out["content_type"] = "application/pdf"
279
- out["source_url"] = w.get("wayback_url") or w.get("url") or url
280
  return out
281
  if not raw_t and isinstance(raw_b, bytes):
282
  raw_t = raw_b.decode("utf-8", "replace")
283
- if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:400] or "startxref" in raw_t[:800]:
284
  out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
285
  return out
286
  text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
@@ -302,81 +247,6 @@ def fetch_official(
302
  return out
303
 
304
 
305
-
306
- def best_cdx_pdf_timestamp(url: str) -> Optional[str]:
307
- """Pick a CDX snapshot timestamp that looks like a real PDF (status 200)."""
308
- try:
309
- # Prefer exact URL match via prefix of the path
310
- from urllib.parse import urlsplit
311
- parts = urlsplit(url)
312
- host = (parts.hostname or "").replace("www.", "")
313
- path = parts.path or "/"
314
- # try a few URL variants
315
- candidates = []
316
- for u in (url, url.replace("https://", "http://"), url.replace("http://", "https://")):
317
- u2 = u.replace(":80/", "/")
318
- for h in cdx_urls(u2, limit=20, match_type="exact"):
319
- candidates.append(h)
320
- # also prefix on host+path
321
- prefix = f"{host}{path}".lstrip("/")
322
- if prefix:
323
- for h in cdx_urls(prefix, limit=30, match_type="prefix",
324
- extra_filters=["mimetype:application/pdf"]):
325
- candidates.append(h)
326
- for h in cdx_urls("www." + prefix, limit=30, match_type="prefix",
327
- extra_filters=["mimetype:application/pdf"]):
328
- candidates.append(h)
329
- best = None
330
- for h in candidates:
331
- ts = h.get("timestamp") or ""
332
- sc = str(h.get("statuscode") or h.get("status") or "")
333
- mt = (h.get("mimetype") or "").lower()
334
- orig = (h.get("original") or "").lower()
335
- if not ts:
336
- continue
337
- if sc and sc not in ("200", "226", "-"):
338
- continue
339
- score = 0
340
- if "pdf" in mt or orig.endswith(".pdf"):
341
- score += 2
342
- if sc == "200":
343
- score += 1
344
- if best is None or score > best[0] or (score == best[0] and ts > best[1]):
345
- best = (score, ts)
346
- return best[1] if best else None
347
- except Exception as exc:
348
- log.info("best_cdx_pdf_timestamp fail %s: %s", url[:80], exc)
349
- return None
350
-
351
-
352
- def fetch_official_prefer_pdf(
353
- url: str,
354
- *,
355
- ua: str = DEFAULT_UA,
356
- verify: bool = True,
357
- min_text: int = MIN_TEXT,
358
- wayback_ts: Optional[str] = None,
359
- ) -> dict:
360
- """Live first; on failure, Wayback with CDX PDF timestamp when available."""
361
- got = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=wayback_ts, min_text=min_text)
362
- if got.get("status") == "success" and not (got.get("text") or "").lstrip().startswith("%PDF"):
363
- # reject obvious HTML shells mistaken for success when URL is a PDF
364
- if url.lower().endswith(".pdf") and got.get("method") == "wayback_html":
365
- pass # try timestamped below
366
- else:
367
- return got
368
- ts = wayback_ts or best_cdx_pdf_timestamp(url)
369
- if ts:
370
- got2 = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
371
- if got2.get("status") == "success":
372
- return got2
373
- # try http variant with same ts
374
- alt = url.replace("https://", "http://") if url.startswith("https://") else url.replace("http://", "https://")
375
- got3 = fetch_official(alt, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text)
376
- if got3.get("status") == "success":
377
- return got3
378
- return got
379
-
380
  def first_title(text: str, fallback: str) -> str:
381
  for line in (text or "").splitlines():
382
  s = line.strip()
 
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 ""
 
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],
 
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": "",
 
163
  }
164
  body = b""
165
  ctype = ""
 
166
  try:
 
 
167
  r = live_get(url, ua=ua, verify=verify)
168
  body = r.content or b""
169
  ctype = r.headers.get("content-type") or ""
170
  if r.status_code == 200 and body:
171
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
 
 
 
 
 
172
  text = pdf_to_text(body)
173
  if len(text) >= min_text:
174
  out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
 
185
  return out
186
  if len(text) < min_text:
187
  out["error"] = "short_or_spa"
188
+ elif body[:4] == b"%PDF":
 
 
189
  out["error"] = "pdf_extract_failed"
 
 
190
  elif len(body) > min_text:
191
  try:
192
  text = body.decode("utf-8", "replace")
 
208
  if w.get("status") == "success":
209
  raw_b = w.get("content") or b""
210
  raw_t = w.get("text") or ""
211
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
212
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  text = pdf_to_text(pdf_bytes)
214
  if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
215
  out.update(
 
217
  text=text,
218
  content=pdf_bytes,
219
  method="wayback_pdf",
220
+ source_url=w.get("url") or url,
221
  content_type="application/pdf",
222
  )
223
  return out
 
224
  out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
 
 
 
225
  return out
226
  if not raw_t and isinstance(raw_b, bytes):
227
  raw_t = raw_b.decode("utf-8", "replace")
228
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
229
  out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
230
  return out
231
  text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
 
247
  return out
248
 
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  def first_title(text: str, fallback: str) -> str:
251
  for line in (text or "").splitlines():
252
  s = line.strip()