endomorphosis commited on
Commit
bd40bf9
·
verified ·
1 Parent(s): b372e71

Refresh Kuwait official e.gov.kw Forms via Wayback (93 laws; was thin ~54)

Browse files
MANIFEST.md CHANGED
@@ -1,21 +1,26 @@
1
  # ipfs_kuwait_laws manifest
2
 
3
- generated_utc: 2026-09-04T18:06:18Z
4
  cc: kw
5
- slug: kuwait
6
- laws_rows: 69
7
  articles_rows: 0
8
- laws_bytes: 4474479
9
- articles_bytes: 1607
10
- laws_sha256: 67e8883263c212a949874d85fc58ad3612ccf6682c77cdc68d1b8dbf52d5dda8
11
- articles_sha256: 22806421f93c50153de0a7c5a04022ed12bee1b183d3b90c19b4e9be46c75fd7
12
- laws_parquet: /workspace/legal-corpora-releases/kuwait/data/laws.parquet
13
- articles_parquet: /workspace/legal-corpora-releases/kuwait/data/articles.parquet
14
  compression: zstd
15
  collector: scrapers/collect_kuwaitalyawm.py
16
- source: Kuwait Alyawm / e.gov.kw official PDFs
17
- coverage: kuwait alyawm / e.gov.kw snapshot
18
- snapshot_date: 2026-09-04
 
 
 
 
 
 
 
 
19
  uploaded: false
20
- gaps:
21
- Research snapshot of Kuwait official e.gov.kw / Kuwait Alyawm-linked PDFs. Incomplete; subscriber viewer texts limited. Official source prevails. Not legal advice.
 
1
  # ipfs_kuwait_laws manifest
2
 
3
+ generated_utc: 2026-09-09T14:14:48Z
4
  cc: kw
5
+ laws_rows: 93
 
6
  articles_rows: 0
7
+ laws_bytes: 1499937
8
+ articles_bytes: 986
9
+ laws_sha256: e769dc99505be9d81c51c34711a0581b898310b037176d936293273d8337ff11
10
+ articles_sha256: cc851f16b1aa2815fb071b0f5c25300be24bc6c697df8b5dea3efe80f72ea276
11
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_kuwait_laws/data/laws.parquet
12
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_kuwait_laws/data/articles.parquet
13
  compression: zstd
14
  collector: scrapers/collect_kuwaitalyawm.py
15
+ license: Ministry of Information / official gazette terms; not legal advice
16
+ retrieval: official
17
+ live_instruments: 93
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: Gazette flip viewer is subscriber-only; full texts from official e.gov.kw PDFs and Wayback of official URLs.
26
  uploaded: false
 
 
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
- pretty_name: Laws of Kuwait
3
  license: other
4
- license_name: kuwait-official
5
  language:
6
  - ar
7
  task_categories:
@@ -22,44 +22,42 @@ configs:
22
  data_files: data/articles.parquet
23
  ---
24
 
25
- # Laws of Kuwait
26
 
27
- Research snapshot of official legislation collected from **Kuwait Alyawm / e.gov.kw official PDFs**.
28
 
29
- **Not legal advice.** Official gazettes / government portals prevail over this corpus.
30
 
31
  ## Snapshot
32
 
33
  | Field | Value |
34
  | --- | --- |
35
- | Snapshot date | 2026-09-04 |
36
- | Coverage | kuwait alyawm / e.gov.kw snapshot |
37
- | Source | Kuwait Alyawm / e.gov.kw official PDFs |
38
  | Collector | `scrapers/collect_kuwaitalyawm.py` |
39
- | Laws / instruments | 69 |
40
  | Articles | 0 |
41
  | Language | ar |
42
  | Jurisdiction | Kuwait |
43
- | License | `kuwait-official` |
44
 
45
  ## Contents
46
 
47
- - `data/laws.parquet` — one row per instrument (id, title, full text, ELI,
48
- dates, status, identifiers, article count, source URL).
49
- - `data/articles.parquet` — one row per article/section (`law_id`, article
50
- number, title, text, source URL).
51
  - `scrapers/collect_kuwaitalyawm.py` — research collector used to build this snapshot.
52
- - `scrapers/common.py` — shared collector helpers.
53
 
54
  ## License / reuse
55
 
56
- Official government / gazette texts; reuse per public-sector terms of the
57
- source portal. This packaging, metadata, and collector script are provided
58
- for research.
59
 
60
- This dataset is **not** an official consolidation and is **not legal advice**.
61
- The official source prevails.
62
 
63
- ## Notes
64
 
65
- Research snapshot of Kuwait official e.gov.kw / Kuwait Alyawm-linked PDFs. Incomplete; subscriber viewer texts limited. Official source prevails. Not legal advice.
 
 
 
 
 
1
  ---
2
+ pretty_name: Kuwait Official Gazette Laws (الكويت اليوم)
3
  license: other
4
+ license_name: kuwait-gazette-terms
5
  language:
6
  - ar
7
  task_categories:
 
22
  data_files: data/articles.parquet
23
  ---
24
 
25
+ # Kuwait Official Gazette Laws (الكويت اليوم)
26
 
27
+ Research snapshot of official national legislation from **الكويت اليوم (Ministry of Information) + e.gov.kw official PDFs**.
28
 
29
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
30
 
31
  ## Snapshot
32
 
33
  | Field | Value |
34
  | --- | --- |
35
+ | Snapshot date | 2026-09-09 |
36
+ | Coverage | partial-official-fulltext |
37
+ | Source | الكويت اليوم (Ministry of Information) + e.gov.kw official PDFs |
38
  | Collector | `scrapers/collect_kuwaitalyawm.py` |
39
+ | Laws / instruments | 93 |
40
  | Articles | 0 |
41
  | Language | ar |
42
  | Jurisdiction | Kuwait |
43
+ | License | `kuwait-gazette-terms` |
44
 
45
  ## Contents
46
 
47
+ - `data/laws.parquet` — one row per instrument.
48
+ - `data/articles.parquet` article/section rows for the same snapshot.
 
 
49
  - `scrapers/collect_kuwaitalyawm.py` — research collector used to build this snapshot.
 
50
 
51
  ## License / reuse
52
 
53
+ Ministry of Information / official gazette terms; not legal advice.
 
 
54
 
55
+ This dataset is **not legal advice**. The official source prevails.
 
56
 
57
+ ## Source
58
 
59
+ - https://kuwaitalyawm.media.gov.kw/online/AdsCategory/9
60
+
61
+ ## Known gaps
62
+
63
+ Gazette flip viewer is subscriber-only; full texts from official e.gov.kw PDFs and Wayback of official URLs.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:22806421f93c50153de0a7c5a04022ed12bee1b183d3b90c19b4e9be46c75fd7
3
- size 1607
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc851f16b1aa2815fb071b0f5c25300be24bc6c697df8b5dea3efe80f72ea276
3
+ size 986
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:67e8883263c212a949874d85fc58ad3612ccf6682c77cdc68d1b8dbf52d5dda8
3
- size 4474479
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e769dc99505be9d81c51c34711a0581b898310b037176d936293273d8337ff11
3
+ size 1499937
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 = "https://web.archive.org/cdx/search/cdx"
28
- WAYBACK_WEB = "https://web.archive.org/web"
 
 
29
  CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
  CC_DATA = "https://data.commoncrawl.org"
31
  ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
@@ -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,127 @@ 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 +418,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 +487,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
+ Follow 3xx Location only after rewriting https://web.archive.org → http://.
296
+ """
297
+ import subprocess
298
+
299
  if timestamp:
300
+ path = f"/{timestamp}id_/{url}"
301
  else:
302
+ path = f"/2id_/{url}"
303
+ target = WAYBACK_WEB_HTTP + path
304
  last_err = None
305
+ body = b""
306
+ ctype = ""
307
+ final_url = target
308
+ status = 0
309
+ for attempt in range(1, 6):
310
+ _sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))
311
  try:
312
+ # Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
313
+ proc = subprocess.run(
314
+ [
315
+ "curl", "-sS", "--max-time", "90",
316
+ "-A", UA,
317
+ "-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}\n__REDIRECT_URL__%{redirect_url}",
318
+ "--output", "-",
319
+ target,
320
+ ],
321
+ capture_output=True,
322
+ timeout=100,
323
+ )
324
+ raw = proc.stdout or b""
325
+ # Trailer is text appended after body when -w is used with --output -
326
+ marker = b"\n__HTTP_STATUS__"
327
+ redirect_url = ""
328
+ if marker in raw:
329
+ body, rest = raw.rsplit(marker, 1)
330
+ trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
331
+ mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
332
+ mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
333
+ murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
334
+ mredir = re.search(r"__REDIRECT_URL__([^\n]*)", trailer)
335
+ status = int(mstat.group(1)) if mstat else 0
336
+ ctype = (mctype.group(1) if mctype else "") or ""
337
+ final_url = (murl.group(1) if murl else target) or target
338
+ redirect_url = (mredir.group(1) if mredir else "") or ""
339
+ else:
340
+ body = raw
341
+ status = 200 if proc.returncode == 0 and raw else 0
342
+ if status in (301, 302, 303, 307, 308):
343
+ loc = redirect_url or ""
344
+ if loc.startswith("https://web.archive.org/"):
345
+ loc = "http://" + loc[len("https://"):]
346
+ if loc.startswith("http://web.archive.org/"):
347
+ log.info("wayback replay follow HTTP redirect %s -> %s", status, loc[:120])
348
+ target = loc
349
+ final_url = loc
350
+ continue
351
+ last_err = f"http_{status}_bad_redirect"
352
+ log.info("wayback replay HTTP %s bad redirect %s", status, (loc or "")[:160])
353
+ continue
354
+ if proc.returncode != 0 and not body:
355
+ last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
356
+ log.info("wayback replay curl fail %s: %s", url, last_err)
357
+ continue
358
+ if status in (403, 429, 503, 502, 504) and attempt < 5:
359
+ log.info("wayback replay HTTP %s %s attempt=%s", status, url, attempt)
360
+ continue
361
+ break
362
+ except Exception as exc:
363
  last_err = str(exc)
364
  log.info("wayback replay fail %s: %s", url, exc)
365
  continue
366
+ else:
367
+ # fallback: requests without following redirects to https
368
+ try:
369
+ r = session().get(target, timeout=(20, 90), allow_redirects=False)
370
+ status = r.status_code
371
+ body = r.content or b""
372
+ ctype = r.headers.get("content-type") or ""
373
+ final_url = r.url or target
374
+ if status in (301, 302, 303, 307, 308):
375
+ loc = r.headers.get("Location") or ""
376
+ if loc.startswith("https://web.archive.org/"):
377
+ loc = "http://" + loc[len("https://"):]
378
+ if loc.startswith("http://web.archive.org/"):
379
+ r2 = session().get(loc, timeout=(20, 90), allow_redirects=False)
380
+ status = r2.status_code
381
+ body = r2.content or b""
382
+ ctype = r2.headers.get("content-type") or ""
383
+ final_url = r2.url or loc
384
+ except requests.RequestException as exc:
385
+ return {"status": "error", "error": last_err or str(exc), "url": url}
386
+
387
+ if not body and status != 200:
388
+ return {"status": "error", "error": last_err or f"http_{status}", "url": url}
389
  cap_ts = timestamp or ""
390
+ m = re.search(r"/web/(\d{14})", final_url or "")
391
  if m:
392
  cap_ts = m.group(1)
 
 
393
  text = ""
394
  if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
 
395
  try:
 
 
396
  text = body.decode("utf-8", "replace")
397
+ except Exception:
398
+ text = ""
399
+ if status != 200 or not body:
400
  return {
401
  "status": "error",
402
+ "error": f"http_{status}",
403
+ "http_status": status,
404
+ "wayback_url": final_url,
405
  "original_url": url,
406
  }
407
+ if text and is_challenge(text, status):
408
  return {
409
  "status": "error",
410
  "error": "challenge_or_shell",
411
+ "http_status": status,
412
+ "wayback_url": final_url,
413
  "original_url": url,
414
  "content": text[:2000],
415
  }
 
418
  "content": body,
419
  "text": text,
420
  "content_type": ctype,
421
+ "wayback_url": final_url,
422
  "capture_timestamp": cap_ts,
423
  "original_url": url,
424
+ "http_status": status,
425
+ "method": "wayback_curl_http",
426
  }
427
 
428
 
429
  # --- Common Crawl ---
430
 
431
+ def _http_cc_index(url: str) -> str:
432
+ if url.startswith("https://index.commoncrawl.org"):
433
+ return "http://" + url[len("https://"):]
434
+ return url
435
+
436
+
437
  def cc_indexes(n: int = 6) -> list[str]:
438
  global _cc_indexes
439
  if _cc_indexes is None:
440
+ cols = []
441
+ last_exc = None
442
+ for coll in (CC_COLLINFO, CC_COLLINFO.replace("https://", "http://", 1)):
443
+ try:
444
+ r = session().get(coll, timeout=30)
445
+ if r.status_code == 200:
446
+ cols = r.json() or []
447
+ break
448
+ except Exception as exc:
449
+ last_exc = exc
450
+ log.warning("cc collinfo %s: %s", coll, exc)
451
+ ids = []
452
+ for c in cols:
453
+ cid = c.get("id") or ""
454
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
455
+ if cid:
456
+ ids.append(_http_cc_index(cdx or f"http://index.commoncrawl.org/{cid}-index"))
457
+ # collinfo is newest-first. Do not drop crawls that 404 a
458
+ # specific URL (that means "no captures", not a dead index).
459
+ _cc_indexes = ids or [
460
+ "http://index.commoncrawl.org/CC-MAIN-2026-34-index",
461
+ "http://index.commoncrawl.org/CC-MAIN-2024-33-index",
462
+ ]
463
+ if last_exc and not ids:
464
+ log.warning("cc collinfo fallback indexes after %s", last_exc)
465
  return _cc_indexes[:n]
466
 
467
 
 
487
  try:
488
  r = session().get(idx, params=params, timeout=(12, 25))
489
  except requests.RequestException as exc:
490
+ alt = _http_cc_index(idx) if idx.startswith("https://") else idx.replace("http://", "https://", 1)
491
+ try:
492
+ r = session().get(alt, params=params, timeout=(12, 25))
493
+ except requests.RequestException as exc2:
494
+ log.info("cc cdx %s fail %s / %s", idx, exc, exc2)
495
+ continue
496
  if r.status_code == 404:
497
  msg = (r.text or "")[:80]
498
  log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
scrapers/collect_kuwaitalyawm.py CHANGED
@@ -51,6 +51,41 @@ EGOV_PDFS = [
51
  "https://www.e.gov.kw/sites/kgoArabic/Forms/DastoorKuwaity.pdf",
52
  ]
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  def setup():
56
  ensure_dirs(CC)
@@ -218,30 +253,49 @@ def write_law(ident, title, text, source_url, date, extra_meta, doc_type="statut
218
  def add_egov_pdfs() -> tuple[int, int]:
219
  ok = fail = 0
220
  urls = list(EGOV_PDFS)
 
221
  extra = search_wayback_machine(
222
  "https://www.e.gov.kw/sites/kgoArabic/Forms/", match_type="prefix",
223
- limit=80, extra_filters=["mimetype:application/pdf"],
224
  )
225
  extra += search_wayback_machine(
226
  "https://e.gov.kw/sites/kgoEnglish/Forms/", match_type="prefix",
227
- limit=80, extra_filters=["mimetype:application/pdf"],
 
 
 
 
228
  )
229
  log.info("egov wayback pdf cdx=%s", len(extra))
230
  seen = set()
231
  jobs = []
232
  for u in urls:
233
  jobs.append({"original": u, "timestamp": None, "source": "live-or-wayback"})
 
234
  for rec in extra:
235
  orig = rec.get("original") or ""
236
  if not orig.lower().endswith(".pdf"):
237
  continue
 
 
 
238
  if orig in seen:
239
  continue
240
  seen.add(orig)
241
  jobs.append({"original": orig, "timestamp": rec.get("timestamp"), "source": "wayback"})
 
 
 
 
 
242
  for job in jobs:
 
 
243
  orig = job["original"]
244
  ident = Path(orig.split("?")[0]).stem[:80] or "egov-pdf"
 
 
 
245
  text = ""
246
  src = orig
247
  # live
@@ -272,10 +326,14 @@ def add_egov_pdfs() -> tuple[int, int]:
272
  }, doc_type=doc_type)
273
  if st == "ok":
274
  ok += 1
 
 
275
  log.info("egov pdf ok %s chars=%s", ident, len(text))
276
  elif st == "fail":
277
  fail += 1
278
  log_failure(CC, {"identifier": ident, "source_url": orig, "status": "failed", "reason": "empty_pdf"})
 
 
279
  return ok, fail
280
 
281
 
@@ -298,7 +356,8 @@ def add_wayback_gazette_html() -> tuple[int, int]:
298
  if ln >= 8000:
299
  keep.append(rec)
300
  seen = set()
301
- for rec in keep[:80]:
 
302
  orig = rec.get("original")
303
  if orig in seen:
304
  continue
 
51
  "https://www.e.gov.kw/sites/kgoArabic/Forms/DastoorKuwaity.pdf",
52
  ]
53
 
54
+ # Administrative form stubs (نموذج) — not legislation; drop from harvest.
55
+ FORM_RE = re.compile(
56
+ r"(?i)(%D9%86%D9%85%D8%A7%D8%B0%D8%AC|%D9%86%D9%85%D9%88%D8%B0%D8%AC|"
57
+ r"namothaj|namothage|namothg|estimara|talab|form[_-]?0|awqaf-form|"
58
+ r"student_support|authorizeda|bulletinlabour|annualextern|"
59
+ r"caitauthorized|/Forms/[^/]*form)"
60
+ )
61
+
62
+ LAWISH_RE = re.compile(
63
+ r"(?i)(dastoor|dastor|cma|qawan|qanun|law|tashree|tashrea|jamarek|"
64
+ r"monadham|khass|amateurradio|constitution|مرسوم|قانون|دستور)"
65
+ )
66
+
67
+
68
+ def is_form_stub(url: str) -> bool:
69
+ from urllib.parse import unquote
70
+ u = unquote(url or "")
71
+ if FORM_RE.search(url or "") or FORM_RE.search(u):
72
+ # keep if clearly a law compilation despite form-ish tokens
73
+ if LAWISH_RE.search(url or "") or LAWISH_RE.search(u):
74
+ return False
75
+ return True
76
+ # Arabic نموذج / نماذج in path
77
+ if "نموذج" in u or "نماذج" in u:
78
+ return True
79
+ return False
80
+
81
+
82
+ def env_int(name: str, default: int) -> int:
83
+ import os
84
+ try:
85
+ return int(os.environ.get(name, str(default)) or default)
86
+ except Exception:
87
+ return default
88
+
89
 
90
  def setup():
91
  ensure_dirs(CC)
 
253
  def add_egov_pdfs() -> tuple[int, int]:
254
  ok = fail = 0
255
  urls = list(EGOV_PDFS)
256
+ cdx_lim = env_int("CDX_LIMIT", 400)
257
  extra = search_wayback_machine(
258
  "https://www.e.gov.kw/sites/kgoArabic/Forms/", match_type="prefix",
259
+ limit=cdx_lim, extra_filters=["mimetype:application/pdf"],
260
  )
261
  extra += search_wayback_machine(
262
  "https://e.gov.kw/sites/kgoEnglish/Forms/", match_type="prefix",
263
+ limit=cdx_lim, extra_filters=["mimetype:application/pdf"],
264
+ )
265
+ extra += search_wayback_machine(
266
+ "https://www.e.gov.kw/sites/kgoarabic/Forms/", match_type="prefix",
267
+ limit=cdx_lim, extra_filters=["mimetype:application/pdf"],
268
  )
269
  log.info("egov wayback pdf cdx=%s", len(extra))
270
  seen = set()
271
  jobs = []
272
  for u in urls:
273
  jobs.append({"original": u, "timestamp": None, "source": "live-or-wayback"})
274
+ skipped_forms = 0
275
  for rec in extra:
276
  orig = rec.get("original") or ""
277
  if not orig.lower().endswith(".pdf"):
278
  continue
279
+ if is_form_stub(orig):
280
+ skipped_forms += 1
281
+ continue
282
  if orig in seen:
283
  continue
284
  seen.add(orig)
285
  jobs.append({"original": orig, "timestamp": rec.get("timestamp"), "source": "wayback"})
286
+ log.info("egov jobs=%s skipped_forms=%s", len(jobs), skipped_forms)
287
+ jobs.sort(key=lambda j: (0 if LAWISH_RE.search(j["original"] or "") else 1, j["original"]))
288
+ max_new = env_int("MAX_NEW", 120)
289
+ got = 0
290
+ known = existing_ids(CC)
291
  for job in jobs:
292
+ if max_new and got >= max_new:
293
+ break
294
  orig = job["original"]
295
  ident = Path(orig.split("?")[0]).stem[:80] or "egov-pdf"
296
+ rid = slug_id(CC, ident)
297
+ if rid in known:
298
+ continue
299
  text = ""
300
  src = orig
301
  # live
 
326
  }, doc_type=doc_type)
327
  if st == "ok":
328
  ok += 1
329
+ got += 1
330
+ known.add(rid)
331
  log.info("egov pdf ok %s chars=%s", ident, len(text))
332
  elif st == "fail":
333
  fail += 1
334
  log_failure(CC, {"identifier": ident, "source_url": orig, "status": "failed", "reason": "empty_pdf"})
335
+ elif st == "skip":
336
+ pass
337
  return ok, fail
338
 
339
 
 
356
  if ln >= 8000:
357
  keep.append(rec)
358
  seen = set()
359
+ max_wb = env_int("MAX_WAYBACK_HTML", 40)
360
+ for rec in keep[:max_wb]:
361
  orig = rec.get("original")
362
  if orig in seen:
363
  continue
scrapers/common.py CHANGED
@@ -509,8 +509,13 @@ def iso_date(val: Optional[str]) -> Optional[str]:
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 or raw[:4] != b"%PDF":
513
  return ""
 
 
 
 
 
514
  try:
515
  with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
516
  tmp.write(raw)
 
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)
scrapers/pdf_extract_lib.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PDF text extraction helpers mirroring ipfs_datasets_py IntegratedPDFProcessor.
3
+
4
+ Prefer pdfplumber -> pymupdf -> pdftotext; OCR (tesseract) only when text layer
5
+ is missing or garbage. Honest article splits require >=2 heading matches.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import logging
11
+ import re
12
+ import subprocess
13
+ import tempfile
14
+ from typing import Optional
15
+
16
+ log = logging.getLogger("pdf_extract_lib")
17
+
18
+ # Spaced-out OCR garbage like "D IA R IO"
19
+ _GARBAGE_SPACING = re.compile(r"(?:^[A-Za-z]\s+){6,}", re.M)
20
+
21
+
22
+ def is_garbage_text(text: str) -> bool:
23
+ if not text or len(text) < 40:
24
+ return True
25
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
26
+ return True
27
+ if "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:
28
+ return True
29
+ sample = text[:8000]
30
+ # Broken ToUnicode / CID font dumps from Arabic/Persian PDFs
31
+ if sample.count("(cid:") >= 8:
32
+ return True
33
+ arabic = sum(1 for ch in sample if "\u0600" <= ch <= "\u06FF")
34
+ ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t\x0c")
35
+ n = max(1, len(sample))
36
+ # Encoding-corrupt Arabic/Persian PDFs: many controls / almost no Arabic script
37
+ if len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05:
38
+ return True
39
+ if len(sample) > 800 and arabic < 80 and sample.count("@") > 30:
40
+ return True
41
+ letters = sum(ch.isalpha() for ch in sample)
42
+ spaces = sample.count(" ")
43
+ if letters < 80 and arabic < 40:
44
+ return True
45
+ # Mojibake Latin stand-in for Arabic (common in old MoJ PDFs)
46
+ ascii_letters = sum(ch.isalpha() and ord(ch) < 128 for ch in sample)
47
+ if len(sample) > 500 and arabic < 20 and ascii_letters > 400:
48
+ return True
49
+ if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):
50
+ return True
51
+ singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))
52
+ if singles > 30 and singles > letters * 0.15:
53
+ return True
54
+ return False
55
+
56
+
57
+ def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
58
+ import pdfplumber
59
+ with pdfplumber.open(io.BytesIO(raw)) as pdf:
60
+ n = len(pdf.pages)
61
+ parts = []
62
+ for page in pdf.pages[:max_pages]:
63
+ try:
64
+ parts.append(page.extract_text() or "")
65
+ except Exception:
66
+ continue
67
+ text = "\n".join(parts)
68
+ text = re.sub(r"[ \t]+", " ", text)
69
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
70
+ return text, n
71
+
72
+
73
+ def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]:
74
+ import pymupdf
75
+ doc = pymupdf.open(stream=raw, filetype="pdf")
76
+ n = doc.page_count
77
+ parts = [page.get_text() for page in doc[:max_pages]]
78
+ text = "\n".join(parts)
79
+ text = re.sub(r"[ \t]+", " ", text)
80
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
81
+ return text, n
82
+
83
+
84
+ def extract_pdftotext(raw: bytes) -> str:
85
+ if not raw or raw[:4] != b"%PDF":
86
+ return ""
87
+ try:
88
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
89
+ tmp.write(raw)
90
+ tmp.flush()
91
+ proc = subprocess.run(
92
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
93
+ check=False, capture_output=True, timeout=180,
94
+ )
95
+ if proc.returncode == 0 and proc.stdout:
96
+ return proc.stdout.decode("utf-8", "replace").strip()
97
+ except Exception as exc:
98
+ log.warning("pdftotext: %s", exc)
99
+ return ""
100
+
101
+
102
+ def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]:
103
+ """Render pages with pymupdf and OCR via tesseract CLI."""
104
+ import pymupdf
105
+ doc = pymupdf.open(stream=raw, filetype="pdf")
106
+ n = doc.page_count
107
+ parts = []
108
+ mat = pymupdf.Matrix(dpi / 72, dpi / 72)
109
+ for i, page in enumerate(doc):
110
+ if i >= max_pages:
111
+ break
112
+ pix = page.get_pixmap(matrix=mat, alpha=False)
113
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img:
114
+ pix.save(img.name)
115
+ img_path = img.name
116
+ try:
117
+ env = dict(**__import__("os").environ)
118
+ env["OMP_THREAD_LIMIT"] = "1"
119
+ env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata")
120
+ proc = subprocess.run(
121
+ ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"],
122
+ capture_output=True, text=True, timeout=180, env=env,
123
+ )
124
+ if proc.returncode == 0 and proc.stdout:
125
+ parts.append(proc.stdout)
126
+ except Exception as exc:
127
+ log.debug("ocr page %s: %s", i, exc)
128
+ finally:
129
+ try:
130
+ import os
131
+ os.unlink(img_path)
132
+ except Exception:
133
+ pass
134
+ text = "\n".join(parts)
135
+ text = re.sub(r"[ \t]+", " ", text)
136
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
137
+ return text, n
138
+
139
+
140
+ def extract_pdf_text(
141
+ raw: bytes,
142
+ *,
143
+ enable_ocr: bool = True,
144
+ ocr_lang: str = "eng",
145
+ ocr_max_pages: int = 40,
146
+ ) -> tuple[str, str, int]:
147
+ """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order."""
148
+ if not raw:
149
+ return "", "not_pdf", 0
150
+ if raw[:4] != b"%PDF":
151
+ idx = raw.find(b"%PDF", 0, 65536)
152
+ if idx < 0:
153
+ return "", "not_pdf", 0
154
+ raw = raw[idx:]
155
+ best_text, best_method, pages = "", "failed", 0
156
+ for name, fn in (
157
+ ("pdfplumber", lambda: extract_pdfplumber(raw)),
158
+ ("pymupdf", lambda: extract_pymupdf(raw)),
159
+ ):
160
+ try:
161
+ text, pages = fn()
162
+ if text and not is_garbage_text(text) and len(text) >= 80:
163
+ return text, name, pages
164
+ if len(text) > len(best_text):
165
+ best_text, best_method = text, name
166
+ except Exception as exc:
167
+ log.debug("%s failed: %s", name, exc)
168
+ try:
169
+ text = extract_pdftotext(raw)
170
+ if text and not is_garbage_text(text) and len(text) >= 80:
171
+ return text, "pdftotext", pages
172
+ if len(text) > len(best_text):
173
+ best_text, best_method = text, "pdftotext"
174
+ except Exception:
175
+ pass
176
+ if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120):
177
+ try:
178
+ text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages)
179
+ if text and len(text) >= 80 and not is_garbage_text(text):
180
+ return text, "ocr_tesseract", pages
181
+ if len(text) > len(best_text):
182
+ best_text, best_method = text, "ocr_tesseract"
183
+ except Exception as exc:
184
+ log.debug("ocr failed: %s", exc)
185
+ return best_text, best_method if best_text else "failed", pages
186
+
187
+
188
+ def normalize_bidi(text: str) -> str:
189
+ return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200c\u200d\ufeff]", "", text or "")
190
+
191
+
192
+ _EASTERN_DIGITS = str.maketrans(
193
+ "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669"
194
+ "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9",
195
+ "01234567890123456789",
196
+ )
197
+
198
+
199
+ def normalize_rtl_text(text: str) -> str:
200
+ """Strip bidi marks and map Arabic/Persian digits to ASCII for heading regexes."""
201
+ t = normalize_bidi(text or "")
202
+ t = re.sub(r"[\u00ad\u200b]", "", t)
203
+ return t.translate(_EASTERN_DIGITS)
204
+
205
+
206
+
207
+ def split_by_pattern(
208
+ text: str,
209
+ law_id: str,
210
+ source_url: str,
211
+ pat: re.Pattern,
212
+ record_type: str = "article",
213
+ min_chunk: int = 40,
214
+ max_docs: int = 4000,
215
+ ) -> list[dict]:
216
+ matches = list(pat.finditer(text or ""))
217
+ if len(matches) < 2:
218
+ return []
219
+ docs = []
220
+ for i, m in enumerate(matches):
221
+ start = m.start()
222
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
223
+ chunk = text[start:end].strip()
224
+ if len(chunk) < min_chunk:
225
+ continue
226
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
227
+ aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80]
228
+ heading = chunk.split("\n", 1)[0][:200]
229
+ docs.append({
230
+ "id": f"{law_id}-{aid}"[:180],
231
+ "title": heading,
232
+ "text": chunk,
233
+ "date_filed": None,
234
+ "document_number": num,
235
+ "source_url": source_url,
236
+ "record_type": record_type,
237
+ "article_number": num,
238
+ "law_identifier": law_id,
239
+ "metadata": {
240
+ "text_extraction": {
241
+ "source": "official",
242
+ "backend": "honest_heading_split",
243
+ "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split",
244
+ "pattern": pat.pattern[:100],
245
+ }
246
+ },
247
+ })
248
+ if len(docs) >= max_docs:
249
+ break
250
+ return docs if len(docs) >= 2 else []
251
+
252
+
253
+ # Country-specific honest patterns (tried in order)
254
+ COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = {
255
+ "sv": [
256
+ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"),
257
+ ],
258
+ "tn": [
259
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"),
260
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
261
+ ],
262
+ "et": [
263
+ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"),
264
+ ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"),
265
+ ("article_inline", re.compile(r"(?im)((?:Article|Art\.)\s+\d+)(?![\d])"), "article"),
266
+ ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"),
267
+ ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"),
268
+ ],
269
+ "jm": [
270
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"),
271
+ ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"),
272
+ ],
273
+ "fj": [
274
+ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"),
275
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"),
276
+ ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"),
277
+ ],
278
+ "la": [
279
+ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"),
280
+ ],
281
+ "lk": [
282
+ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"),
283
+ ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"),
284
+ ],
285
+ "md": [
286
+ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"),
287
+ ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"),
288
+ ],
289
+ "iq": [
290
+ ("mada", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:]*\s*\d+)(?!\d)"), "article"),
291
+ ("mada_ocr", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:\s]*\d+)(?!\d)"), "article"),
292
+ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|الباب)\s+\S+)"), "section"),
293
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
294
+ ],
295
+ "ir": [
296
+ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"),
297
+ ("mada_prefixed", re.compile(
298
+ r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)"
299
+ ), "article"),
300
+ ("fasl_bab", re.compile(
301
+ r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))"
302
+ ), "section"),
303
+ ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"),
304
+ ],
305
+ "mz": [
306
+ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),
307
+ ],
308
+ }
309
+
310
+
311
+ def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:
312
+ if cc in ("tn", "iq", "ir", "dz", "lb", "ma", "eg", "sa", "ae"):
313
+ text_n = normalize_rtl_text(text)
314
+ else:
315
+ text_n = text
316
+ for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):
317
+ docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)
318
+ if docs:
319
+ return docs, name
320
+ # shared fallback
321
+ from common import split_articles
322
+ docs = split_articles(text_n, law_id, source_url)
323
+ if len(docs) >= 2:
324
+ return docs, "common_article_split"
325
+ return [], "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for new-country official gazette collectors."""
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import time
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Optional
14
+ from urllib.parse import urljoin, urlparse
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ from common import (
18
+ ROOT,
19
+ DEFAULT_UA,
20
+ base_record,
21
+ ensure_dirs,
22
+ existing_ids,
23
+ html_to_text,
24
+ http_get,
25
+ iso_date,
26
+ log_failure,
27
+ slug_id,
28
+ split_articles,
29
+ utcnow,
30
+ write_instrument,
31
+ write_summary,
32
+ )
33
+ import archive_fallbacks as af
34
+
35
+ log = logging.getLogger("world_lib")
36
+
37
+ MIN_TEXT = 80
38
+ MAX_PDF = 35 * 1024 * 1024
39
+
40
+
41
+ def setup_log(cc: str, name: str | None = None) -> None:
42
+ ensure_dirs(cc)
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s %(levelname)s %(message)s",
46
+ handlers=[
47
+ logging.FileHandler(ROOT / cc / "logs" / "collector.log", encoding="utf-8"),
48
+ logging.StreamHandler(sys.stdout),
49
+ ],
50
+ force=True,
51
+ )
52
+
53
+
54
+ def pdf_to_text(raw: bytes) -> str:
55
+ if not raw or raw[:4] != b"%PDF":
56
+ return ""
57
+ try:
58
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
59
+ tmp.write(raw)
60
+ tmp.flush()
61
+ proc = subprocess.run(
62
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
63
+ check=False,
64
+ capture_output=True,
65
+ timeout=180,
66
+ )
67
+ if proc.returncode == 0 and proc.stdout:
68
+ return proc.stdout.decode("utf-8", "replace").strip()
69
+ except Exception as exc:
70
+ log.warning("pdftotext: %s", exc)
71
+ return ""
72
+
73
+
74
+ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]:
75
+ docs = split_articles(text, law_id, source_url, date)
76
+ if not pattern:
77
+ return docs
78
+ matches = list(pattern.finditer(text or ""))
79
+ if len(matches) < 2:
80
+ return docs if len(docs) >= 2 else []
81
+ out = []
82
+ for i, m in enumerate(matches):
83
+ start = m.start()
84
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
85
+ chunk = text[start:end].strip()
86
+ if len(chunk) < 20:
87
+ continue
88
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
89
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]
90
+ heading = chunk.split("\n", 1)[0][:200]
91
+ out.append({
92
+ "id": f"{law_id}-{aid}"[:180],
93
+ "title": heading,
94
+ "text": chunk,
95
+ "date_filed": date,
96
+ "document_number": num,
97
+ "source_url": source_url,
98
+ "record_type": "article",
99
+ "article_number": num,
100
+ "law_identifier": law_id,
101
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
102
+ })
103
+ if len(out) >= 4000:
104
+ break
105
+ return out if len(out) >= 2 else docs
106
+
107
+
108
+
109
+ def normalize_official_url(url: str) -> str:
110
+ """Fix CDX quirks: https://host:80/... breaks TLS (WRONG_VERSION_NUMBER)."""
111
+ if not url:
112
+ return url
113
+ url = url.replace("http://", "https://", 1) if "lawcommission.gov.np" in url and url.startswith("http://") else url
114
+ url = url.replace("https://www.lawcommission.gov.np:80/", "https://www.lawcommission.gov.np/")
115
+ url = url.replace("https://lawcommission.gov.np:80/", "https://lawcommission.gov.np/")
116
+ url = url.replace(":80/", "/") if url.startswith("https://") and ":80/" in url else url
117
+ url = url.replace(":80?", "?") if url.startswith("https://") and ":80?" in url else url
118
+ return url
119
+
120
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
121
+ url = normalize_official_url(url)
122
+ import requests
123
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
124
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
125
+ last = None
126
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ time.sleep(0.2)
130
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
131
+ return resp
132
+ except Exception as exc:
133
+ last = exc
134
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
135
+ try:
136
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
137
+ return resp
138
+ except Exception as exc2:
139
+ last = exc2
140
+ time.sleep(min(8, 1.5 * attempt))
141
+ raise RuntimeError(f"live_get failed {url}: {last}")
142
+
143
+
144
+ def fetch_official(
145
+ url: str,
146
+ *,
147
+ ua: str = DEFAULT_UA,
148
+ verify: bool = True,
149
+ wayback: bool = True,
150
+ wayback_ts: Optional[str] = None,
151
+ min_text: int = MIN_TEXT,
152
+ ) -> dict:
153
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
154
+ url = normalize_official_url(url)
155
+ out = {
156
+ "status": "error",
157
+ "text": "",
158
+ "content": b"",
159
+ "source_url": url,
160
+ "method": "",
161
+ "content_type": "",
162
+ "error": "",
163
+ }
164
+ body = b""
165
+ ctype = ""
166
+ try:
167
+ r = live_get(url, ua=ua, verify=verify)
168
+ body = r.content or b""
169
+ ctype = r.headers.get("content-type") or ""
170
+ if r.status_code == 200 and body:
171
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
172
+ text = pdf_to_text(body)
173
+ if len(text) >= min_text:
174
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
175
+ return out
176
+ text = ""
177
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
178
+ raw = body.decode(r.encoding or "utf-8", "replace")
179
+ if af.is_challenge(raw, r.status_code):
180
+ out["error"] = "challenge_or_shell"
181
+ else:
182
+ text = html_to_text(raw) if "<" in raw[:500] else raw
183
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
184
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
185
+ return out
186
+ if len(text) < min_text:
187
+ out["error"] = "short_or_spa"
188
+ elif body[:4] == b"%PDF":
189
+ out["error"] = "pdf_extract_failed"
190
+ elif len(body) > min_text:
191
+ try:
192
+ text = body.decode("utf-8", "replace")
193
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
194
+ out["error"] = "raw_pdf_bytes"
195
+ elif len(text) >= min_text:
196
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
197
+ return out
198
+ except Exception:
199
+ pass
200
+ else:
201
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
202
+ except Exception as exc:
203
+ out["error"] = f"live:{exc}"
204
+
205
+ if wayback:
206
+ try:
207
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
208
+ if w.get("status") == "success":
209
+ raw_b = w.get("content") or b""
210
+ raw_t = w.get("text") or ""
211
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
212
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
213
+ text = pdf_to_text(pdf_bytes)
214
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
215
+ out.update(
216
+ status="success",
217
+ text=text,
218
+ content=pdf_bytes,
219
+ method="wayback_pdf",
220
+ source_url=w.get("url") or url,
221
+ content_type="application/pdf",
222
+ )
223
+ return out
224
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
225
+ return out
226
+ if not raw_t and isinstance(raw_b, bytes):
227
+ raw_t = raw_b.decode("utf-8", "replace")
228
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
229
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
230
+ return out
231
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
232
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
233
+ out.update(
234
+ status="success",
235
+ text=text,
236
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
237
+ method="wayback_html",
238
+ source_url=w.get("url") or url,
239
+ content_type=w.get("content_type") or "text/html",
240
+ )
241
+ return out
242
+ out["error"] = (out.get("error") or "") + ";wayback_short"
243
+ else:
244
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
245
+ except Exception as exc:
246
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
247
+ return out
248
+
249
+
250
+ def first_title(text: str, fallback: str) -> str:
251
+ for line in (text or "").splitlines():
252
+ s = line.strip()
253
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
254
+ return s[:240]
255
+ return fallback[:240]
256
+
257
+
258
+ def save_instrument(
259
+ *,
260
+ cc: str,
261
+ country: str,
262
+ language: str,
263
+ ident: str,
264
+ title: str,
265
+ text: str,
266
+ source_url: str,
267
+ source_type: str,
268
+ license_text: str,
269
+ collector: str,
270
+ date: Optional[str] = None,
271
+ article_re: Optional[re.Pattern] = None,
272
+ extra_meta: Optional[dict] = None,
273
+ ) -> bool:
274
+ if not text or len(text) < MIN_TEXT:
275
+ return False
276
+ rid = slug_id(cc, ident)
277
+ docs = split_custom(text, rid, source_url, date, article_re)
278
+ rec = base_record(
279
+ cc=cc,
280
+ country=country,
281
+ language=language,
282
+ ident=ident,
283
+ title=title or first_title(text, ident),
284
+ text=text,
285
+ source_url=source_url,
286
+ source_type=source_type,
287
+ license_text=license_text,
288
+ collector=collector,
289
+ date=iso_date(date) or date,
290
+ documents=docs,
291
+ extra_meta=extra_meta,
292
+ )
293
+ write_instrument(cc, rec)
294
+ return True
295
+
296
+
297
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
298
+ try:
299
+ hits = af.search_wayback_machine(
300
+ host_or_url,
301
+ limit=limit,
302
+ match_type=match_type,
303
+ collapse="urlkey",
304
+ extra_filters=extra_filters,
305
+ )
306
+ except Exception as exc:
307
+ log.info("cdx err %s: %s", host_or_url, exc)
308
+ return []
309
+ return hits or []
310
+
311
+
312
+ def env_int(name: str, default: int) -> int:
313
+ try:
314
+ return int(os.environ.get(name, str(default)) or default)
315
+ except Exception:
316
+ return default