Refresh Namibia densify (160 laws / 4927 articles; was 80/491; *.gov.na / parliament)
Browse files- MANIFEST.md +9 -9
- README.md +4 -4
- data/articles.parquet +2 -2
- data/laws.parquet +2 -2
- scrapers/archive_fallbacks.py +69 -22
- scrapers/collect_na.py +334 -34
- scrapers/world_lib.py +14 -1
MANIFEST.md
CHANGED
|
@@ -1,25 +1,25 @@
|
|
| 1 |
# ipfs_namibia_laws manifest
|
| 2 |
|
| 3 |
-
generated_utc: 2026-09-
|
| 4 |
cc: na
|
| 5 |
-
laws_rows:
|
| 6 |
-
articles_rows:
|
| 7 |
-
laws_bytes:
|
| 8 |
-
articles_bytes:
|
| 9 |
-
laws_sha256:
|
| 10 |
-
articles_sha256:
|
| 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:
|
| 18 |
archive_instruments: 0
|
| 19 |
wayback_instruments: 0
|
| 20 |
common_crawl_instruments: 0
|
| 21 |
archive_is_instruments: 0
|
| 22 |
-
constitution_present:
|
| 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.
|
|
|
|
| 1 |
# ipfs_namibia_laws manifest
|
| 2 |
|
| 3 |
+
generated_utc: 2026-09-10T03:14:29Z
|
| 4 |
cc: na
|
| 5 |
+
laws_rows: 160
|
| 6 |
+
articles_rows: 4927
|
| 7 |
+
laws_bytes: 1372965
|
| 8 |
+
articles_bytes: 1370997
|
| 9 |
+
laws_sha256: 39a97d99dd998503eaf73ba00a35b9e0ced1bcf0c8ef7db6f2fad15476f95b72
|
| 10 |
+
articles_sha256: 09272c95ccf068735ffd883401ef02f307f6ef0c7870ca030b98ef2850c40287
|
| 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: 160
|
| 18 |
archive_instruments: 0
|
| 19 |
wayback_instruments: 0
|
| 20 |
common_crawl_instruments: 0
|
| 21 |
archive_is_instruments: 0
|
| 22 |
+
constitution_present: true
|
| 23 |
catalog_expected: None
|
| 24 |
catalog_gap:
|
| 25 |
gaps: Official 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.
|
README.md
CHANGED
|
@@ -18,7 +18,7 @@ tags:
|
|
| 18 |
- acts
|
| 19 |
- official-texts
|
| 20 |
size_categories:
|
| 21 |
-
- n<
|
| 22 |
configs:
|
| 23 |
- config_name: laws
|
| 24 |
data_files: data/laws.parquet
|
|
@@ -37,12 +37,12 @@ Research snapshot of official national legislation from **Parliament (parliament
|
|
| 37 |
|
| 38 |
| Field | Value |
|
| 39 |
| --- | --- |
|
| 40 |
-
| Snapshot date | 2026-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 |
|
| 45 |
-
| Articles |
|
| 46 |
| Language | en |
|
| 47 |
| Jurisdiction | Namibia |
|
| 48 |
| License | `na-parliament-gov-moj-official-texts` |
|
|
|
|
| 18 |
- acts
|
| 19 |
- official-texts
|
| 20 |
size_categories:
|
| 21 |
+
- 1K<n<10K
|
| 22 |
configs:
|
| 23 |
- config_name: laws
|
| 24 |
data_files: data/laws.parquet
|
|
|
|
| 37 |
|
| 38 |
| Field | Value |
|
| 39 |
| --- | --- |
|
| 40 |
+
| Snapshot date | 2026-09-10 |
|
| 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 | 160 |
|
| 45 |
+
| Articles | 4,927 |
|
| 46 |
| Language | en |
|
| 47 |
| Jurisdiction | Namibia |
|
| 48 |
| License | `na-parliament-gov-moj-official-texts` |
|
data/articles.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:09272c95ccf068735ffd883401ef02f307f6ef0c7870ca030b98ef2850c40287
|
| 3 |
+
size 1370997
|
data/laws.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:39a97d99dd998503eaf73ba00a35b9e0ced1bcf0c8ef7db6f2fad15476f95b72
|
| 3 |
+
size 1372965
|
scrapers/archive_fallbacks.py
CHANGED
|
@@ -288,10 +288,13 @@ def search_wayback_machine(
|
|
| 288 |
return out[:target]
|
| 289 |
|
| 290 |
|
|
|
|
| 291 |
def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
|
| 292 |
"""Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
|
| 293 |
|
| 294 |
Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).
|
|
|
|
|
|
|
| 295 |
"""
|
| 296 |
import subprocess
|
| 297 |
|
|
@@ -305,15 +308,19 @@ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
|
|
| 305 |
ctype = ""
|
| 306 |
final_url = target
|
| 307 |
status = 0
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
try:
|
| 311 |
# Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
|
| 312 |
proc = subprocess.run(
|
| 313 |
[
|
| 314 |
-
"curl", "-
|
| 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 |
],
|
|
@@ -321,55 +328,95 @@ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
|
|
| 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
|
| 344 |
-
log.info("wayback replay HTTP %s %s
|
|
|
|
| 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 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
if loc.startswith("https://web.archive.org/"):
|
| 362 |
loc = "http://" + loc[len("https://"):]
|
| 363 |
-
if loc.startswith("http://web.archive.org/"):
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 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 "")
|
|
|
|
| 288 |
return out[:target]
|
| 289 |
|
| 290 |
|
| 291 |
+
|
| 292 |
def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
|
| 293 |
"""Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
|
| 294 |
|
| 295 |
Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).
|
| 296 |
+
Follow 3xx Location only after rewriting https://web.archive.org → http://.
|
| 297 |
+
Redirect hops do not consume the HTTP retry budget.
|
| 298 |
"""
|
| 299 |
import subprocess
|
| 300 |
|
|
|
|
| 308 |
ctype = ""
|
| 309 |
final_url = target
|
| 310 |
status = 0
|
| 311 |
+
redirects_left = 8
|
| 312 |
+
attempts_left = 5
|
| 313 |
+
first = True
|
| 314 |
+
while attempts_left > 0:
|
| 315 |
+
_sleep_wayback(0.35 if not first and redirects_left < 8 else (0.8 if first else min(8.0, 1.8 * (6 - attempts_left))))
|
| 316 |
+
first = False
|
| 317 |
try:
|
| 318 |
# Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
|
| 319 |
proc = subprocess.run(
|
| 320 |
[
|
| 321 |
+
"curl", "-sS", "--max-time", "90",
|
| 322 |
"-A", UA,
|
| 323 |
+
"-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}\n__REDIRECT_URL__%{redirect_url}",
|
| 324 |
"--output", "-",
|
| 325 |
target,
|
| 326 |
],
|
|
|
|
| 328 |
timeout=100,
|
| 329 |
)
|
| 330 |
raw = proc.stdout or b""
|
|
|
|
|
|
|
| 331 |
marker = b"\n__HTTP_STATUS__"
|
| 332 |
+
redirect_url = ""
|
| 333 |
if marker in raw:
|
| 334 |
body, rest = raw.rsplit(marker, 1)
|
| 335 |
trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
|
| 336 |
mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
|
| 337 |
mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
|
| 338 |
murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
|
| 339 |
+
mredir = re.search(r"__REDIRECT_URL__([^\n]*)", trailer)
|
| 340 |
status = int(mstat.group(1)) if mstat else 0
|
| 341 |
ctype = (mctype.group(1) if mctype else "") or ""
|
| 342 |
final_url = (murl.group(1) if murl else target) or target
|
| 343 |
+
redirect_url = (mredir.group(1) if mredir else "") or ""
|
| 344 |
else:
|
| 345 |
body = raw
|
| 346 |
status = 200 if proc.returncode == 0 and raw else 0
|
| 347 |
+
if status in (301, 302, 303, 307, 308):
|
| 348 |
+
loc = (redirect_url or "").strip()
|
| 349 |
+
if loc.startswith("/"):
|
| 350 |
+
loc = "http://web.archive.org" + loc
|
| 351 |
+
if loc.startswith("https://web.archive.org/"):
|
| 352 |
+
loc = "http://" + loc[len("https://"):]
|
| 353 |
+
if loc.startswith("http://web.archive.org/") and redirects_left > 0:
|
| 354 |
+
log.info("wayback replay follow HTTP redirect %s -> %s", status, loc[:120])
|
| 355 |
+
target = loc
|
| 356 |
+
final_url = loc
|
| 357 |
+
redirects_left -= 1
|
| 358 |
+
continue # redirect hop: do not consume attempts_left
|
| 359 |
+
last_err = f"http_{status}_bad_redirect"
|
| 360 |
+
log.info("wayback replay HTTP %s bad redirect %s", status, (loc or "")[:160])
|
| 361 |
+
attempts_left -= 1
|
| 362 |
+
continue
|
| 363 |
if proc.returncode != 0 and not body:
|
| 364 |
last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
|
| 365 |
log.info("wayback replay curl fail %s: %s", url, last_err)
|
| 366 |
+
attempts_left -= 1
|
| 367 |
continue
|
| 368 |
+
if status in (403, 429, 503, 502, 504) and attempts_left > 1:
|
| 369 |
+
log.info("wayback replay HTTP %s %s attempts_left=%s", status, url, attempts_left)
|
| 370 |
+
attempts_left -= 1
|
| 371 |
continue
|
| 372 |
break
|
| 373 |
except Exception as exc:
|
| 374 |
last_err = str(exc)
|
| 375 |
log.info("wayback replay fail %s: %s", url, exc)
|
| 376 |
+
attempts_left -= 1
|
| 377 |
continue
|
| 378 |
else:
|
| 379 |
# fallback: requests without following redirects to https
|
| 380 |
try:
|
| 381 |
+
hops = 0
|
| 382 |
+
while hops < 8:
|
| 383 |
+
r = session().get(target, timeout=(20, 90), allow_redirects=False)
|
| 384 |
+
status = r.status_code
|
| 385 |
+
body = r.content or b""
|
| 386 |
+
ctype = r.headers.get("content-type") or ""
|
| 387 |
+
final_url = r.url or target
|
| 388 |
+
if status not in (301, 302, 303, 307, 308):
|
| 389 |
+
break
|
| 390 |
+
loc = (r.headers.get("Location") or "").strip()
|
| 391 |
+
if loc.startswith("/"):
|
| 392 |
+
loc = "http://web.archive.org" + loc
|
| 393 |
if loc.startswith("https://web.archive.org/"):
|
| 394 |
loc = "http://" + loc[len("https://"):]
|
| 395 |
+
if not loc.startswith("http://web.archive.org/"):
|
| 396 |
+
last_err = f"http_{status}_bad_redirect"
|
| 397 |
+
break
|
| 398 |
+
target = loc
|
| 399 |
+
final_url = loc
|
| 400 |
+
hops += 1
|
| 401 |
except requests.RequestException as exc:
|
| 402 |
return {"status": "error", "error": last_err or str(exc), "url": url}
|
| 403 |
|
| 404 |
+
if (not body and status != 200) or status == 404:
|
| 405 |
+
# /2id_/ sometimes lands on a missing capture; pick an explicit CDX 200 snapshot.
|
| 406 |
+
if not timestamp:
|
| 407 |
+
try:
|
| 408 |
+
hits = search_wayback_machine(url, limit=5, filter_status="200", collapse="digest")
|
| 409 |
+
for hit in hits:
|
| 410 |
+
ts = hit.get("timestamp") or ""
|
| 411 |
+
orig = hit.get("original") or url
|
| 412 |
+
if not ts:
|
| 413 |
+
continue
|
| 414 |
+
alt = get_wayback_content(orig, timestamp=ts)
|
| 415 |
+
if alt.get("status") == "success" and (alt.get("content") or b""):
|
| 416 |
+
return alt
|
| 417 |
+
# also try original host/path casing from CDX
|
| 418 |
+
except Exception as exc:
|
| 419 |
+
log.info("wayback cdx retry after http_%s: %s", status, exc)
|
| 420 |
return {"status": "error", "error": last_err or f"http_{status}", "url": url}
|
| 421 |
cap_ts = timestamp or ""
|
| 422 |
m = re.search(r"/web/(\d{14})", final_url or "")
|
scrapers/collect_na.py
CHANGED
|
@@ -5,14 +5,45 @@ 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
CC, COUNTRY, LANG = "na", "Namibia", "en"
|
| 18 |
SOURCE_TYPE = "namibia_official_gazette_acts"
|
|
@@ -24,9 +55,29 @@ LICENSE = (
|
|
| 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*(
|
|
|
|
|
|
|
|
|
|
| 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.
|
|
@@ -36,7 +87,6 @@ HOMES = [
|
|
| 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",
|
|
@@ -66,16 +116,23 @@ MAX_PDF_BYTES = 12 * 1024 * 1024
|
|
| 66 |
|
| 67 |
def _host_ok(url: str) -> bool:
|
| 68 |
host = (urlsplit(url).hostname or "").lower()
|
| 69 |
-
if any(
|
| 70 |
-
|
| 71 |
-
|
| 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
|
|
@@ -86,11 +143,199 @@ def _norm_url(url: str) -> str:
|
|
| 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)
|
|
@@ -137,6 +382,8 @@ def discover():
|
|
| 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/",
|
|
@@ -154,12 +401,13 @@ def discover():
|
|
| 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",
|
| 163 |
match_type="prefix",
|
| 164 |
extra_filters=["statuscode:200", "mimetype:application/pdf"],
|
| 165 |
) or []
|
|
@@ -176,11 +424,21 @@ def discover():
|
|
| 176 |
if length and length > MAX_PDF_BYTES:
|
| 177 |
continue
|
| 178 |
pri = 20
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
):
|
| 183 |
-
pri =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
add(orig, ts=ts, priority=pri)
|
| 185 |
|
| 186 |
items.sort(key=lambda x: (x[0], x[1]))
|
|
@@ -194,10 +452,25 @@ def main():
|
|
| 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:
|
|
@@ -207,7 +480,8 @@ def main():
|
|
| 207 |
if time.time() - t_start > max_seconds:
|
| 208 |
break
|
| 209 |
rid = slug_id(CC, ident)
|
| 210 |
-
|
|
|
|
| 211 |
skip += 1
|
| 212 |
continue
|
| 213 |
got = fetch_official(url, ua=UA, min_text=200, wayback_ts=ts)
|
|
@@ -221,24 +495,42 @@ def main():
|
|
| 221 |
fail += 1
|
| 222 |
log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_too_large", "chars": len(text)})
|
| 223 |
continue
|
| 224 |
-
title =
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
|
|
|
| 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/",
|
|
@@ -248,12 +540,20 @@ def main():
|
|
| 248 |
"https://www.moj.gov.na/",
|
| 249 |
"https://www.opm.gov.na/",
|
| 250 |
],
|
| 251 |
-
license_text=LICENSE,
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
last_run=t0,
|
| 255 |
)
|
| 256 |
-
log.info("done ok=%s skip=%s fail=%s
|
| 257 |
|
| 258 |
|
| 259 |
if __name__ == "__main__":
|
|
|
|
| 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 |
+
Densify: Namibia Acts use Commonwealth ``1. Definitions`` / ``1. Short title.``
|
| 10 |
+
section numbering (not only ``Section N`` / ``PART N``). Prefer enacting body
|
| 11 |
+
after BE IT ENACTED / ARRANGEMENT OF SECTIONS to avoid TOC double-count
|
| 12 |
+
(Namibia often places the arrangement *after* the enacting formula).
|
| 13 |
"""
|
| 14 |
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
from pathlib import Path
|
| 23 |
from urllib.parse import urljoin, urlsplit, unquote
|
| 24 |
+
|
| 25 |
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 26 |
+
from common import (
|
| 27 |
+
INDEX_FIELDS,
|
| 28 |
+
ROOT,
|
| 29 |
+
atomic_write,
|
| 30 |
+
base_record,
|
| 31 |
+
existing_ids,
|
| 32 |
+
http_get,
|
| 33 |
+
log_failure,
|
| 34 |
+
utcnow,
|
| 35 |
+
write_instrument,
|
| 36 |
+
write_summary,
|
| 37 |
+
)
|
| 38 |
+
from world_lib import (
|
| 39 |
+
cdx_urls,
|
| 40 |
+
env_int,
|
| 41 |
+
fetch_official,
|
| 42 |
+
first_title,
|
| 43 |
+
setup_log,
|
| 44 |
+
slug_id,
|
| 45 |
+
split_custom,
|
| 46 |
+
)
|
| 47 |
|
| 48 |
CC, COUNTRY, LANG = "na", "Namibia", "en"
|
| 49 |
SOURCE_TYPE = "namibia_official_gazette_acts"
|
|
|
|
| 55 |
"Not AfricanLII / NamibLII / lac.org.na / commercial DBs. Not legal advice."
|
| 56 |
)
|
| 57 |
UA = "legal-corpora-collector/1.0 (research; source=https://www.parliament.gov.na/)"
|
| 58 |
+
|
| 59 |
+
# Commonwealth body: "1. Definitions" / "12A. Interpretation." / margin "Definitions. 1. In this Act"
|
| 60 |
+
# PLUS classic Section/Article/Regulation N
|
| 61 |
ART = re.compile(
|
| 62 |
+
r"(?im)^\s*(?:[A-Z][A-Za-z0-9 \-]{1,45}\.\s+)?"
|
| 63 |
+
r"((?:Article|Art\.?|Section|Sec\.?|Regulation|Reg\.)\s+[0-9]+[A-Za-z]?|"
|
| 64 |
+
r"\d+[A-Za-z]?\.)"
|
| 65 |
+
r"(?=\s+(?:[A-Z\"'(]|In |This |These |The |For ))"
|
| 66 |
)
|
| 67 |
+
ART_ONLY = re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+[0-9]+[A-Za-z]?)\b")
|
| 68 |
+
|
| 69 |
+
ACT_TEXT_RE = re.compile(
|
| 70 |
+
r"(?i)(AN ACT\b|A BILL\b|BE IT ENACTED|ARRANGEMENT OF|"
|
| 71 |
+
r"This Act (?:may be cited|is called|shall be called)|Short title|"
|
| 72 |
+
r"GOVERNMENT GAZETTE|Annotated Statutes|"
|
| 73 |
+
r"CONSTITUTION OF|Republic of Namibia)"
|
| 74 |
+
)
|
| 75 |
+
ACT_URL_RE = re.compile(
|
| 76 |
+
r"(?i)(/act[-_ ]|\bact[-_ ]|_act\.|-act\.|act\.pdf|constitution|"
|
| 77 |
+
r"/bill[-_ ]|_bill\.|-bill\.|regulation|gazette|statutory|"
|
| 78 |
+
r"acts_documents|cms_documents|promulgation)"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
log = logging.getLogger("na")
|
| 82 |
HOMES = [
|
| 83 |
# Live SSL flaky on many *.gov.na / parliament.gov.na; lean live set, lean on CDX/Wayback.
|
|
|
|
| 87 |
"https://www.parliament.na/bills/",
|
| 88 |
"https://www.parliament.na/acts-of-parliament/",
|
| 89 |
]
|
|
|
|
| 90 |
ALLOWED = (
|
| 91 |
"gov.na",
|
| 92 |
"parliament.gov.na",
|
|
|
|
| 116 |
|
| 117 |
def _host_ok(url: str) -> bool:
|
| 118 |
host = (urlsplit(url).hostname or "").lower()
|
| 119 |
+
if any(
|
| 120 |
+
x in host
|
| 121 |
+
for x in (
|
| 122 |
+
"africanlii",
|
| 123 |
+
"namiblii",
|
| 124 |
+
"namlii",
|
| 125 |
+
"gazettes.africa",
|
| 126 |
+
"law.africa",
|
| 127 |
+
"lac.org.na",
|
| 128 |
+
"saflii",
|
| 129 |
+
"commonlii",
|
| 130 |
+
)
|
| 131 |
+
):
|
| 132 |
return False
|
|
|
|
| 133 |
for s in ALLOWED:
|
| 134 |
if host == s or host.endswith("." + s):
|
| 135 |
return True
|
|
|
|
| 136 |
if host.endswith(".gov.na") or host == "gov.na":
|
| 137 |
return True
|
| 138 |
return False
|
|
|
|
| 143 |
if url.startswith("http://"):
|
| 144 |
url = "https://" + url[len("http://") :]
|
| 145 |
url = re.sub(r"(https?://[^/:]+):80/", r"\1/", url)
|
|
|
|
| 146 |
url = re.sub(r"(https?://[^/:]+):80(/|$)", r"\1\2", url)
|
| 147 |
return url
|
| 148 |
|
| 149 |
|
| 150 |
+
def prefer_enacting_body(text: str) -> str:
|
| 151 |
+
"""Skip arrangement/TOC so article split targets operative sections.
|
| 152 |
+
|
| 153 |
+
Namibia often: BE IT ENACTED … then ARRANGEMENT OF SECTIONS (TOC), then body.
|
| 154 |
+
Older gazettes wrap the enacting formula across lines.
|
| 155 |
+
"""
|
| 156 |
+
if not text:
|
| 157 |
+
return text
|
| 158 |
+
|
| 159 |
+
arr = list(re.finditer(r"(?i)ARRANGEMENT OF (?:SECTIONS|ACT|REGULATIONS)", text))
|
| 160 |
+
if arr:
|
| 161 |
+
after = text[arr[-1].end() :]
|
| 162 |
+
body_ones = list(
|
| 163 |
+
re.finditer(
|
| 164 |
+
r"(?im)^\s*(?:[A-Z][A-Za-z0-9 \-]{1,45}\.\s+)?"
|
| 165 |
+
r"1\.\s+(?:In this Act|This Act|These Regulations|These regulations|"
|
| 166 |
+
r"Unless the context|For the purposes|\(1\))",
|
| 167 |
+
after,
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
if body_ones:
|
| 171 |
+
return after[body_ones[0].start() :]
|
| 172 |
+
parts = list(re.finditer(r"(?im)^\s*PART\s+(?:1|I)\b", after))
|
| 173 |
+
if len(parts) >= 2:
|
| 174 |
+
return after[parts[1].start() :]
|
| 175 |
+
ones = list(
|
| 176 |
+
re.finditer(
|
| 177 |
+
r"(?im)^\s*1\.\s+(?:Short title|Citation|Definitions|Interpretation)\b",
|
| 178 |
+
after,
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
if len(ones) >= 2:
|
| 182 |
+
return after[ones[1].start() :]
|
| 183 |
+
heads = list(
|
| 184 |
+
re.finditer(
|
| 185 |
+
r"(?im)^\s*(Definitions|Interpretation|Short title(?: and commencement)?)\s*$",
|
| 186 |
+
after,
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
if len(heads) >= 2:
|
| 190 |
+
return after[heads[1].start() :]
|
| 191 |
+
m = re.search(r"(?im)^\s*1\.\s+\(1\)", after)
|
| 192 |
+
if m:
|
| 193 |
+
return after[m.start() :]
|
| 194 |
+
|
| 195 |
+
m = re.search(
|
| 196 |
+
r"(?is)BE IT ENACTED\b.{0,160}?as follows\s*[:-]?",
|
| 197 |
+
text,
|
| 198 |
+
)
|
| 199 |
+
if m and m.end() < len(text) - 200:
|
| 200 |
+
rest = text[m.end() :]
|
| 201 |
+
if not re.search(r"(?i)ARRANGEMENT OF", rest[:1500]):
|
| 202 |
+
return rest
|
| 203 |
+
|
| 204 |
+
body_ones = list(
|
| 205 |
+
re.finditer(
|
| 206 |
+
r"(?im)^\s*(?:[A-Z][A-Za-z0-9 \-]{1,45}\.\s+)?"
|
| 207 |
+
r"1\.\s+(?:In this Act|This Act|These Regulations|These regulations)\b",
|
| 208 |
+
text,
|
| 209 |
+
)
|
| 210 |
+
)
|
| 211 |
+
if body_ones:
|
| 212 |
+
return text[body_ones[-1].start() :] if len(body_ones) >= 2 else text[body_ones[0].start() :]
|
| 213 |
+
|
| 214 |
+
ones = list(re.finditer(r"(?im)^\s*1\.\s+(?:Short title|Citation|Definitions)\b", text))
|
| 215 |
+
if len(ones) >= 2:
|
| 216 |
+
return text[ones[1].start() :]
|
| 217 |
+
parts = list(re.finditer(r"(?im)^\s*PART\s+(?:1|I)\b", text))
|
| 218 |
+
if len(parts) >= 2:
|
| 219 |
+
return text[parts[1].start() :]
|
| 220 |
+
return text
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def split_na_articles(text: str, rid: str, source_url: str, date=None) -> list:
|
| 224 |
+
"""Commonwealth ``1. Title.`` body split by default; constitutions prefer Article N."""
|
| 225 |
+
body = prefer_enacting_body(text)
|
| 226 |
+
docs_sec = split_custom(body, rid, source_url, date, ART)
|
| 227 |
+
docs_art = split_custom(body, rid, source_url, date, ART_ONLY)
|
| 228 |
+
blob = f"{rid}|{source_url}"
|
| 229 |
+
is_const = bool(re.search(r"(?i)constitution", blob)) and not bool(
|
| 230 |
+
re.search(r"(?i)amm?endment", blob)
|
| 231 |
+
)
|
| 232 |
+
if is_const:
|
| 233 |
+
if len(docs_art) >= 20:
|
| 234 |
+
return docs_art
|
| 235 |
+
if len(docs_art) >= 2 and len(docs_sec) > max(20, len(docs_art) * 3):
|
| 236 |
+
return docs_art
|
| 237 |
+
if len(docs_art) < 2:
|
| 238 |
+
return docs_art
|
| 239 |
+
if len(docs_art) >= 50 and len(docs_art) > len(docs_sec) * 1.2:
|
| 240 |
+
return docs_art
|
| 241 |
+
return docs_sec
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def save_na_instrument(
|
| 245 |
+
*,
|
| 246 |
+
ident: str,
|
| 247 |
+
title: str,
|
| 248 |
+
text: str,
|
| 249 |
+
source_url: str,
|
| 250 |
+
extra_meta: dict | None = None,
|
| 251 |
+
) -> bool:
|
| 252 |
+
if not text or len(text) < 80:
|
| 253 |
+
return False
|
| 254 |
+
rid = slug_id(CC, ident)
|
| 255 |
+
docs = split_na_articles(text, rid, source_url, None)
|
| 256 |
+
meta = {
|
| 257 |
+
"fetch_method": (extra_meta or {}).get("fetch_method"),
|
| 258 |
+
"article_split": "commonwealth-body",
|
| 259 |
+
}
|
| 260 |
+
if extra_meta:
|
| 261 |
+
meta.update(extra_meta)
|
| 262 |
+
rec = base_record(
|
| 263 |
+
cc=CC,
|
| 264 |
+
country=COUNTRY,
|
| 265 |
+
language=LANG,
|
| 266 |
+
ident=ident,
|
| 267 |
+
title=title or first_title(text, ident),
|
| 268 |
+
text=text,
|
| 269 |
+
source_url=source_url,
|
| 270 |
+
source_type=SOURCE_TYPE,
|
| 271 |
+
license_text=LICENSE,
|
| 272 |
+
collector="collect_na.py",
|
| 273 |
+
documents=docs,
|
| 274 |
+
extra_meta=meta,
|
| 275 |
+
)
|
| 276 |
+
write_instrument(CC, rec)
|
| 277 |
+
return True
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def reprocess_existing() -> int:
|
| 281 |
+
"""Re-split articles on Act-like instruments with Commonwealth section regex."""
|
| 282 |
+
inst = ROOT / CC / "instruments"
|
| 283 |
+
improved = 0
|
| 284 |
+
for p in sorted(inst.glob("*.json")):
|
| 285 |
+
try:
|
| 286 |
+
rec = json.loads(p.read_text(encoding="utf-8"))
|
| 287 |
+
except Exception:
|
| 288 |
+
continue
|
| 289 |
+
text = rec.get("text") or ""
|
| 290 |
+
if len(text) < 200:
|
| 291 |
+
continue
|
| 292 |
+
name = p.name
|
| 293 |
+
blob = f"{name}|{rec.get('title') or ''}|{rec.get('source_url') or ''}|{text[:2500]}"
|
| 294 |
+
if not (ACT_TEXT_RE.search(blob) or ACT_URL_RE.search(blob)):
|
| 295 |
+
continue
|
| 296 |
+
rid = rec.get("id") or p.stem
|
| 297 |
+
url = rec.get("source_url") or ""
|
| 298 |
+
date = rec.get("date")
|
| 299 |
+
docs = split_na_articles(text, rid, url, date)
|
| 300 |
+
old = int(rec.get("article_count") or len(rec.get("documents") or []) or 0)
|
| 301 |
+
new = len(docs)
|
| 302 |
+
if new <= old and old > 0:
|
| 303 |
+
continue
|
| 304 |
+
if new < 2 and old >= new:
|
| 305 |
+
continue
|
| 306 |
+
rec["documents"] = docs
|
| 307 |
+
rec["article_count"] = new
|
| 308 |
+
rec["article_extraction_status"] = "ok" if docs else "missing"
|
| 309 |
+
meta = rec.get("metadata") or {}
|
| 310 |
+
meta["article_reprocess"] = "collect_na.py-commonwealth-sections"
|
| 311 |
+
meta["article_split"] = "commonwealth-body"
|
| 312 |
+
rec["metadata"] = meta
|
| 313 |
+
atomic_write(p, json.dumps(rec, ensure_ascii=False, indent=2) + "\n")
|
| 314 |
+
improved += 1
|
| 315 |
+
log.info("reprocess %s %s->%s", rid[:70], old, new)
|
| 316 |
+
return improved
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def rebuild_index() -> int:
|
| 320 |
+
inst = ROOT / CC / "instruments"
|
| 321 |
+
rows = []
|
| 322 |
+
for p in sorted(inst.glob("*.json")):
|
| 323 |
+
try:
|
| 324 |
+
rec = json.loads(p.read_text(encoding="utf-8"))
|
| 325 |
+
except Exception:
|
| 326 |
+
continue
|
| 327 |
+
line = {k: rec.get(k) for k in INDEX_FIELDS if k not in ("path", "bytes", "article_count")}
|
| 328 |
+
line["path"] = f"instruments/{p.name}"
|
| 329 |
+
line["article_count"] = rec.get("article_count") or len(rec.get("documents") or [])
|
| 330 |
+
line["bytes"] = p.stat().st_size
|
| 331 |
+
line["id"] = rec.get("id") or p.stem
|
| 332 |
+
rows.append(line)
|
| 333 |
+
out = ROOT / CC / "index.jsonl"
|
| 334 |
+
atomic_write(out, "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
|
| 335 |
+
log.info("rebuilt index lines=%s", len(rows))
|
| 336 |
+
return len(rows)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
def discover():
|
| 340 |
"""Return list of (ident, url, wayback_ts|None). Live homes first; CDX with timestamps."""
|
| 341 |
items = [] # (priority, ident, url, ts)
|
|
|
|
| 382 |
cdx_prefixes = (
|
| 383 |
"www.parliament.gov.na/acts_documents/",
|
| 384 |
"parliament.gov.na/acts_documents/",
|
| 385 |
+
"www.parliament.gov.na/bills_documents/",
|
| 386 |
+
"parliament.gov.na/bills_documents/",
|
| 387 |
"www.parliament.gov.na/",
|
| 388 |
"parliament.gov.na/",
|
| 389 |
"laws.parliament.na/cms_documents/",
|
|
|
|
| 401 |
"www.mti.gov.na/",
|
| 402 |
"www.mhss.gov.na/",
|
| 403 |
"www.npc.gov.na/",
|
| 404 |
+
"www.lac.gov.na/", # only if *.gov.na — lac.org.na blocked by host check
|
| 405 |
)
|
| 406 |
for prefix in cdx_prefixes:
|
| 407 |
try:
|
| 408 |
hits = cdx_urls(
|
| 409 |
prefix,
|
| 410 |
+
limit=env_int("CDX_LIMIT", 280),
|
| 411 |
match_type="prefix",
|
| 412 |
extra_filters=["statuscode:200", "mimetype:application/pdf"],
|
| 413 |
) or []
|
|
|
|
| 424 |
if length and length > MAX_PDF_BYTES:
|
| 425 |
continue
|
| 426 |
pri = 20
|
| 427 |
+
blob = unquote(orig)
|
| 428 |
+
if re.search(r"(?i)acts_documents|/_?act[_-]?\d|act_\d+_of_\d{4}|constitution", blob):
|
| 429 |
+
pri = 5
|
| 430 |
+
elif re.search(r"(?i)(bill|gazette|statutory|/laws?/|/legislation)", blob):
|
| 431 |
+
pri = 12
|
| 432 |
+
elif re.search(r"(?i)cms_documents", blob):
|
| 433 |
+
# Prefer post-independence / Act-labelled CMS; bury colonial-era noise
|
| 434 |
+
if re.search(r"(?i)(act|amendment|constitution|proclamation)", blob) and not re.search(
|
| 435 |
+
r"(?i)(15[0-9]{2}|16[0-9]{2}|17[0-9]{2}|18[0-9]{2}|19[0-5][0-9])", blob
|
| 436 |
+
):
|
| 437 |
+
pri = 14
|
| 438 |
+
else:
|
| 439 |
+
pri = 35
|
| 440 |
+
elif re.search(r"(?i)(act|regulation)", blob):
|
| 441 |
+
pri = 18
|
| 442 |
add(orig, ts=ts, priority=pri)
|
| 443 |
|
| 444 |
items.sort(key=lambda x: (x[0], x[1]))
|
|
|
|
| 452 |
t0 = utcnow()
|
| 453 |
max_new = env_int("MAX_NEW", 80)
|
| 454 |
max_seconds = env_int("MAX_SECONDS", 2400)
|
| 455 |
+
do_reprocess = os.environ.get("REPROCESS", "1") not in ("0", "false", "no")
|
| 456 |
+
|
| 457 |
+
if do_reprocess:
|
| 458 |
+
n = reprocess_existing()
|
| 459 |
+
log.info("reprocess improved=%s", n)
|
| 460 |
+
|
| 461 |
t_start = time.time()
|
| 462 |
done = existing_ids(CC)
|
| 463 |
already = len(done)
|
| 464 |
target_total = env_int("TARGET_TOTAL", 0)
|
| 465 |
+
have_urls = set()
|
| 466 |
+
for p in (ROOT / CC / "instruments").glob("*.json"):
|
| 467 |
+
try:
|
| 468 |
+
u = _norm_url(json.loads(p.read_text(encoding="utf-8")).get("source_url") or "")
|
| 469 |
+
if u:
|
| 470 |
+
have_urls.add(u.lower())
|
| 471 |
+
except Exception:
|
| 472 |
+
pass
|
| 473 |
+
|
| 474 |
ok = skip = fail = 0
|
| 475 |
for ident, url, ts in discover():
|
| 476 |
if max_new and ok >= max_new:
|
|
|
|
| 480 |
if time.time() - t_start > max_seconds:
|
| 481 |
break
|
| 482 |
rid = slug_id(CC, ident)
|
| 483 |
+
nu = _norm_url(url).lower()
|
| 484 |
+
if rid in done or nu in have_urls:
|
| 485 |
skip += 1
|
| 486 |
continue
|
| 487 |
got = fetch_official(url, ua=UA, min_text=200, wayback_ts=ts)
|
|
|
|
| 495 |
fail += 1
|
| 496 |
log_failure(CC, {"identifier": ident, "source_url": url, "reason": "text_too_large", "chars": len(text)})
|
| 497 |
continue
|
| 498 |
+
title = first_title(text, ident)
|
| 499 |
+
blob = f"{ident}|{title}|{url}|{text[:2500]}"
|
| 500 |
+
# Prefer Act-ish PDFs; skip obvious non-law once we have a base set
|
| 501 |
+
if ok >= 10 and not ACT_TEXT_RE.search(blob) and not ACT_URL_RE.search(url):
|
| 502 |
+
if not re.search(r"(?i)\b(ACT|BILL|STATUTE|ORDINANCE|CONSTITUTION|GAZETTE|REGULATION)\b", text[:3000]):
|
| 503 |
+
skip += 1
|
| 504 |
+
log.info("skip non-act post-fetch %s", ident[:60])
|
| 505 |
+
continue
|
| 506 |
+
if save_na_instrument(
|
| 507 |
+
ident=ident,
|
| 508 |
+
title=title,
|
| 509 |
+
text=text,
|
| 510 |
+
source_url=_norm_url(url),
|
| 511 |
+
extra_meta={"fetch_method": got.get("method"), "wayback_ts": ts},
|
| 512 |
):
|
| 513 |
ok += 1
|
| 514 |
done.add(rid)
|
| 515 |
+
have_urls.add(nu)
|
| 516 |
log.info("ok %s method=%s chars=%s ts=%s", ident[:60], got.get("method"), len(text), ts)
|
| 517 |
else:
|
| 518 |
fail += 1
|
| 519 |
+
|
| 520 |
+
rebuild_index()
|
| 521 |
+
arts = 0
|
| 522 |
+
n_inst = 0
|
| 523 |
+
for p in (ROOT / CC / "instruments").glob("*.json"):
|
| 524 |
+
try:
|
| 525 |
+
rec = json.loads(p.read_text(encoding="utf-8"))
|
| 526 |
+
except Exception:
|
| 527 |
+
continue
|
| 528 |
+
n_inst += 1
|
| 529 |
+
arts += int(rec.get("article_count") or len(rec.get("documents") or []) or 0)
|
| 530 |
+
|
| 531 |
write_summary(
|
| 532 |
+
CC,
|
| 533 |
+
country=COUNTRY,
|
| 534 |
source="Namibia Official Gazette / Acts (parliament.gov.na / laws.parliament.na / gov.na / moj.gov.na / opm.gov.na)",
|
| 535 |
source_urls=[
|
| 536 |
"https://www.parliament.gov.na/",
|
|
|
|
| 540 |
"https://www.moj.gov.na/",
|
| 541 |
"https://www.opm.gov.na/",
|
| 542 |
],
|
| 543 |
+
license_text=LICENSE,
|
| 544 |
+
discovered=ok + skip + fail,
|
| 545 |
+
fetched=ok,
|
| 546 |
+
skipped=skip,
|
| 547 |
+
failed=fail,
|
| 548 |
+
coverage="catalog-backed incomplete (PDF-first live+CDX *.gov.na / parliament.na; commonwealth section densify)",
|
| 549 |
+
notes=(
|
| 550 |
+
f"Official *.gov.na / parliament.na PDFs only. Commonwealth 1. section split + "
|
| 551 |
+
f"enacting-body prefer. instruments={n_inst} articles={arts}. "
|
| 552 |
+
f"Not AfricanLII/NamibLII/lac.org.na. No WAF bypass. Not legal advice."
|
| 553 |
+
),
|
| 554 |
last_run=t0,
|
| 555 |
)
|
| 556 |
+
log.info("done ok=%s skip=%s fail=%s instruments=%s articles=%s", ok, skip, fail, n_inst, arts)
|
| 557 |
|
| 558 |
|
| 559 |
if __name__ == "__main__":
|
scrapers/world_lib.py
CHANGED
|
@@ -217,15 +217,28 @@ def fetch_official(
|
|
| 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
|
|
|
|
| 217 |
text=text,
|
| 218 |
content=pdf_bytes,
|
| 219 |
method="wayback_pdf",
|
| 220 |
+
source_url=w.get("wayback_url") or w.get("url") or url,
|
| 221 |
content_type="application/pdf",
|
| 222 |
)
|
| 223 |
return out
|
| 224 |
+
# Keep PDF bytes so caller can OCR (image-only / bad text layer)
|
| 225 |
+
out.update(
|
| 226 |
+
content=pdf_bytes,
|
| 227 |
+
content_type="application/pdf",
|
| 228 |
+
method="wayback_pdf_bytes",
|
| 229 |
+
source_url=w.get("wayback_url") or w.get("url") or url,
|
| 230 |
+
)
|
| 231 |
out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
|
| 232 |
return out
|
| 233 |
if not raw_t and isinstance(raw_b, bytes):
|
| 234 |
raw_t = raw_b.decode("utf-8", "replace")
|
| 235 |
if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
|
| 236 |
+
# Treat as PDF bytes for OCR upstream
|
| 237 |
+
pdf_bytes = raw_b if isinstance(raw_b, bytes) else raw_t.encode("latin-1", "replace")
|
| 238 |
+
if isinstance(pdf_bytes, bytes) and b"%PDF" in pdf_bytes[:8192]:
|
| 239 |
+
if pdf_bytes[:4] != b"%PDF":
|
| 240 |
+
pdf_bytes = pdf_bytes[pdf_bytes.find(b"%PDF"):]
|
| 241 |
+
out.update(content=pdf_bytes, content_type="application/pdf", method="wayback_pdf_bytes")
|
| 242 |
out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
|
| 243 |
return out
|
| 244 |
text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
|