Datasets:
Add scrapers_and_normalizers overlay for BW (data/* untouched)
Browse filesFiles changed (11)
- scrapers_and_normalizers/PROVENANCE_NATIONAL_OVERLAY.jsonAdded+5
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/archive_fallbacks.pyAdded+1366
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collect_bw.pyAdded+440
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collector.pyAdded+958
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/common.pyAdded+573
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/pdf_extract_lib.pyAdded+336
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_lib.pyAdded+447
- scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_package.pyAdded+289
- scrapers_and_normalizers/scripts/normalize_offline.pyAdded+104
- scrapers_and_normalizers/scripts/pa_exit_guard.pyAdded+135
- scrapers_and_normalizers/scripts/polite_collect_lib.pyAdded+220
12345{ "code": "BW", "repo": "endomorphosis/ipfs_botswana_laws", "bundle": "national_scrapers_bundle_20261105"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366#!/usr/bin/env python3"""Public Wayback CDX + Common Crawl CDX/WARC fetch (ipfs_datasets_py fallback intent).
Does not import the full ipfs_datasets_py package. Matches: search_wayback_machine / get_wayback_content (wayback_machine_engine.py) Common Crawl CDX at https://index.commoncrawl.org/ archive.is newest lookupBrave Search is skipped when no API key is present."""from __future__ import annotations
import gzipimport ioimport jsonimport loggingimport osimport reimport timefrom typing import Any, Optionalfrom urllib.parse import quote, urljoin, urlparse
import requestsfrom requests.adapters import HTTPAdapter
log = logging.getLogger("archive_fallbacks")
WAYBACK_CDX = os.environ.get("WAYBACK_CDX", "https://web.archive.org/cdx/search/cdx") # tip+30o 23:2x PT Oct 1: port 80 to web.archive.org times out; https OKWAYBACK_WEB = os.environ.get("WAYBACK_WEB", "https://web.archive.org/web")CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"CC_DATA = "https://data.commoncrawl.org"CC_DATA_HOSTS = ( "https://data.commoncrawl.org", "https://commoncrawl.s3.amazonaws.com",)ARCHIVE_IS_NEWEST = "https://archive.is/newest/"ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
UA = ( "legal-corpora-collector/1.0 " "(research archive of official national gazettes; polite; " "contact via local operator)")
CHALLENGE_RE = re.compile( r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|" r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|" r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|" r"request\s+rejected|access\s+denied", re.I,)SPA_SHELL_RE = re.compile( r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|" r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}", re.I,)
_session: Optional[requests.Session] = None_cc_indexes: Optional[list[str]] = None_cc_dead: set[str] = set()_last_wayback = 0.0_last_cc = 0.0
def session() -> requests.Session: global _session if _session is None: s = requests.Session() s.headers.update({"User-Agent": UA, "Accept": "*/*"}) ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0) s.mount("https://", ad) s.mount("http://", ad) _session = s return _session
def _sleep_wayback(delay: float = 1.0) -> None: global _last_wayback now = time.time() wait = delay - (now - _last_wayback) if wait > 0: time.sleep(wait) _last_wayback = time.time()
def _sleep_cc(delay: float = 0.35) -> None: global _last_cc now = time.time() wait = delay - (now - _last_cc) if wait > 0: time.sleep(wait) _last_cc = time.time()
def has_brave_key() -> bool: return bool( (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip() )
def is_challenge(html: str, status: int = 200) -> bool: if status in (401, 403, 429, 503): return True if not html: return False head = html[:8000] if CHALLENGE_RE.search(head): return True if SPA_SHELL_RE.search(head) and len(html) < 8000: return True return False
def is_spa_shell(html: str, text: str) -> bool: if not html: return False if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400: return True return False
# --- Wayback ---
CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]: """Parse Wayback CDX JSON, including showResumeKey trailer.""" if not isinstance(data, list) or len(data) <= 1: return [], None resume = None rows = data # Trailer: ..., [], ["resumeKey"] if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]: resume = str(data[-1][0]) if data[-1][0] else None rows = data[:-2] headers = rows[0] if rows else [] out: list[dict] = [] for row in rows[1:]: if not row: continue rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {} if not rec and isinstance(row, list) and len(row) >= 5: rec = { "urlkey": row[0], "timestamp": row[1], "original": row[2], "mimetype": row[3], "statuscode": row[4], "digest": row[5] if len(row) > 5 else "", "length": row[6] if len(row) > 6 else "0", } orig = rec.get("original") or rec.get("url") or "" ts = rec.get("timestamp") or "" mime = rec.get("mimetype") or "" if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in ( "application/pdf", "application/xml", "text/xml", "application/xhtml+xml", "text/html", "application/json", ): continue if not orig or not ts: continue rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}" rec["source"] = "wayback" out.append(rec) return out, resume
def _wayback_cdx_page( url: str, *, limit: int, collapse: str, filter_status: str, from_date: Optional[str], to_date: Optional[str], match_type: Optional[str], extra_filters: Optional[list[str]], resume_key: Optional[str], mime_prefix: Optional[str], page_size: int,) -> tuple[list[dict], Optional[str]]: items: list[tuple[str, Any]] = [ ("url", url), ("output", "json"), ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"), ("limit", int(page_size)), ("showResumeKey", "true"), ] if collapse: items.append(("collapse", collapse)) if from_date: items.append(("from", from_date)) if to_date: items.append(("to", to_date)) if match_type: items.append(("matchType", match_type)) if filter_status: items.append(("filter", f"statuscode:{filter_status}")) for flt in extra_filters or []: items.append(("filter", flt)) if resume_key: items.append(("resumeKey", resume_key)) _sleep_wayback(1.0) last_err = None for attempt, psz in enumerate((page_size, 120, 80), 1): if attempt > 1: items = [(k, psz if k == "limit" else v) for k, v in items] _sleep_wayback(1.5) try: r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90)) except requests.RequestException as exc: last_err = exc log.warning("wayback cdx fail %s: %s", url, exc) continue if r.status_code in (502, 503, 504) or not r.content: last_err = f"http_{r.status_code}" log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz) continue if r.status_code != 200: log.info("wayback cdx HTTP %s for %s", r.status_code, url) return [], None try: data = r.json() except Exception: return [], None return _parse_cdx_json(data, mime_prefix=mime_prefix) log.info("wayback cdx gave up %s last=%s", url, last_err) return [], None
def search_wayback_machine( url: str, *, from_date: Optional[str] = None, to_date: Optional[str] = None, limit: int = 100, collapse: str = "urlkey", filter_status: str = "200", match_type: Optional[str] = None, mime_prefix: Optional[str] = None, extra_filters: Optional[list[str]] = None,) -> list[dict]: """CDX search with resumeKey pagination (single-shot limit>=2000 504s).""" target = max(1, int(limit)) page_size = CDX_PAGE if target > CDX_PAGE else target out: list[dict] = [] seen = set() resume: Optional[str] = None empty = 0 while len(out) < target: need = min(page_size, target - len(out)) batch, resume = _wayback_cdx_page( url, limit=need, collapse=collapse, filter_status=filter_status, from_date=from_date, to_date=to_date, match_type=match_type, extra_filters=extra_filters, resume_key=resume, mime_prefix=mime_prefix, page_size=need, ) added = 0 for rec in batch: key = (rec.get("original"), rec.get("timestamp"), rec.get("digest")) if key in seen: continue seen.add(key) out.append(rec) added += 1 if added == 0: empty += 1 if empty >= 2 or not resume: break else: empty = 0 if not resume: break log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target) return out[:target]
def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict: """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.""" if timestamp: wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}" else: wb = f"{WAYBACK_WEB}/2id_/{url}" r = None last_err = None for attempt in range(1, 5): _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt)) try: r = session().get(wb, timeout=(20, 90), allow_redirects=True) except requests.RequestException as exc: last_err = str(exc) log.info("wayback replay fail %s: %s", url, exc) continue if r.status_code in (403, 429, 503, 502, 504) and attempt < 4: log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt) continue break if r is None: return {"status": "error", "error": last_err or "no_response", "url": url} cap_ts = timestamp or "" m = re.search(r"/web/(\d{14})", r.url or "") if m: cap_ts = m.group(1) ctype = r.headers.get("content-type") or "" body = r.content or b"" text = "" if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype: enc = r.encoding or "utf-8" try: text = body.decode(enc, "replace") except Exception: text = body.decode("utf-8", "replace") if r.status_code != 200 or not body: return { "status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code, "wayback_url": r.url, "original_url": url, } if text and is_challenge(text, r.status_code): return { "status": "error", "error": "challenge_or_shell", "http_status": r.status_code, "wayback_url": r.url, "original_url": url, "content": text[:2000], } return { "status": "success", "content": body, "text": text, "content_type": ctype, "wayback_url": r.url, "capture_timestamp": cap_ts, "original_url": url, "http_status": r.status_code, "method": "wayback", }
# --- Common Crawl ---
def cc_indexes(n: int = 6) -> list[str]: global _cc_indexes if _cc_indexes is None: try: r = session().get(CC_COLLINFO, timeout=30) cols = r.json() if r.status_code == 200 else [] ids = [] for c in cols: cid = c.get("id") or "" cdx = c.get("cdx-api") or c.get("cdx_api") or "" if cid: ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index") # collinfo is newest-first. Do not drop crawls that 404 a # specific URL (that means "no captures", not a dead index). _cc_indexes = ids or [ "https://index.commoncrawl.org/CC-MAIN-2025-18-index", "https://index.commoncrawl.org/CC-MAIN-2024-33-index", ] except Exception as exc: log.warning("cc collinfo: %s", exc) _cc_indexes = [ "https://index.commoncrawl.org/CC-MAIN-2026-34-index", "https://index.commoncrawl.org/CC-MAIN-2026-30-index", "https://index.commoncrawl.org/CC-MAIN-2026-25-index", "https://index.commoncrawl.org/CC-MAIN-2024-33-index", ] return _cc_indexes[:n]
def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]: """Query public CC CDX (https://index.commoncrawl.org/).
Prefer S3 cluster.idx+CDXJ harvest (harvest_thin_s3_cc / *_cc_urls.jsonl) over this HTTP index — it often returns 0 hits or stalls. Short timeouts; never blocks on cdx_toolkit.
Do not send filter=status:200 — on some shards that returns a false 404 "No Captures found". Filter status client-side instead. HTTP 404 with that message means no hits in this crawl, not a dead index. """ out = [] seen = set() empty = 0 for idx in (indexes or cc_indexes(int(os.environ.get('CC_INDEX_N', '4') or 4))): if idx in _cc_dead: continue params = { "url": url, "output": "json", "limit": str(limit), } _sleep_cc(0.3) try: r = session().get(idx, params=params, timeout=(8, 15)) except requests.RequestException as exc: log.info("cc cdx %s fail %s", idx, exc) continue if r.status_code == 404: msg = (r.text or "")[:80] log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg) empty += 1 if empty >= 8 and not out: continue continue if r.status_code in (410,): _cc_dead.add(idx) log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1]) continue if r.status_code != 200 or not r.content: log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1]) continue for line in r.text.splitlines(): line = line.strip() if not line or line[0] not in "{[": continue try: rec = json.loads(line) except Exception: continue orig = rec.get("url") or rec.get("original") or "" st = str(rec.get("status") or rec.get("statuscode") or "200") if st and st not in ("200", "201", "206"): continue key = (orig, rec.get("filename"), rec.get("offset")) if not orig or key in seen: continue seen.add(key) rec["original"] = orig rec["source"] = "common_crawl" rec["cc_index"] = idx out.append(rec) if out: log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out)) if len(out) >= limit or out: break return out[:limit]
def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]: data = raw if data[:2] == b"\x1f\x8b": try: data = gzip.decompress(data) except Exception: try: data = gzip.GzipFile(fileobj=io.BytesIO(data)).read() except Exception: pass # WARC record: headers, then HTTP payload split = data.split(b"\r\n\r\n", 1) if len(split) < 2: return 0, "", data warc_headers, rest = split if rest.startswith(b"HTTP/") or rest.startswith(b"http/"): http_split = rest.split(b"\r\n\r\n", 1) http_head = http_split[0].decode("latin-1", "replace") body = http_split[1] if len(http_split) > 1 else b"" m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head) status = int(m.group(1)) if m else 0 cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I) ctype = cm.group(1).strip() if cm else "" return status, ctype, body return 0, "", rest
def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict: """Range-GET a WARC record from data.commoncrawl.org (S3 mirror fallback).
Retries 403/429/5xx with short backoff. Does not use index.commoncrawl.org or cdx_toolkit. API stable for ingest_cc_ts_wb / ingest_cc_warc_fast. """ fn = rec.get("filename") or rec.get("warc_filename") or "" try: off = int(rec.get("offset") or rec.get("warc_offset") or 0) ln = int(rec.get("length") or rec.get("warc_length") or 0) except Exception: return {"status": "error", "error": "bad_pointer"} if not fn or ln <= 0: return {"status": "error", "error": "missing_pointer"} ln = min(ln, max_bytes) if str(fn).startswith("http"): candidates = [fn] else: path = fn.lstrip("/") candidates = [f"{h}/{path}" for h in CC_DATA_HOSTS] headers_base = { "User-Agent": ( "Mozilla/5.0 (compatible; legal-corpora-collector/1.0; " "+https://commoncrawl.org; research)" ), "Accept": "*/*", } last_err = "no_attempt" body_raw = b"" used_url = "" for url in candidates: for attempt in range(3): _sleep_cc(0.2 if attempt == 0 else min(8.0, 1.5 * (2 ** attempt))) try: r = session().get( url, headers={**headers_base, "Range": f"bytes={off}-{off + ln - 1}"}, timeout=(12, 60), ) except requests.RequestException as exc: last_err = str(exc) continue if r.status_code in (403, 429, 500, 502, 503): last_err = f"http_{r.status_code}" continue if r.status_code not in (200, 206) or not r.content: last_err = f"http_{r.status_code}" break body_raw = r.content used_url = url break if body_raw: break if not body_raw: return {"status": "error", "error": last_err or "empty"} # Prefer warcio when available; fall back to lightweight parse status, ctype, body = 0, "", b"" try: from warcio.archiveiterator import ArchiveIterator for warc_rec in ArchiveIterator(io.BytesIO(body_raw)): if warc_rec.rec_type != "response": continue payload = warc_rec.content_stream().read() http_headers = warc_rec.http_headers if http_headers is not None: try: status = int(http_headers.get_statuscode() or 0) except Exception: status = 0 ctype = http_headers.get_header("Content-Type") or "" body = payload break if not body: status, ctype, body = _parse_warc_http(body_raw) except Exception: status, ctype, body = _parse_warc_http(body_raw) text = "" if body and ( "html" in (ctype or "") or "xml" in (ctype or "") or "text/" in (ctype or "") or not ctype ): text = body.decode("utf-8", "replace") orig = rec.get("original") or rec.get("url") or "" if text and is_challenge(text, status or 200): return {"status": "error", "error": "challenge_or_shell", "original_url": orig} return { "status": "success", "content": body, "text": text, "content_type": ctype, "original_url": orig, "http_status": status or 200, "method": "common_crawl", "cc_record": { "filename": fn, "offset": off, "length": ln, "timestamp": rec.get("timestamp"), "fetch_url": used_url, }, }
# --- archive.is ---
def get_archive_is_content(url: str) -> dict: for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST): try: r = session().get(base + url, timeout=(8, 15), allow_redirects=True) except requests.RequestException as exc: log.info("archive.is %s", exc) continue if r.status_code != 200 or not r.content: continue if "archive." not in (r.url or ""): continue text = r.text or "" if is_challenge(text, r.status_code): continue return { "status": "success", "content": r.content, "text": text, "content_type": r.headers.get("content-type") or "text/html", "archive_url": r.url, "original_url": url, "http_status": r.status_code, "method": "archive_is", } return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
# --- Direct HTTP last ---
def get_http(url: str) -> dict: try: r = session().get(url, timeout=(20, 60), allow_redirects=True) except requests.RequestException as exc: return {"status": "error", "error": str(exc), "original_url": url} text = "" ctype = r.headers.get("content-type") or "" body = r.content or b"" if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype): text = body.decode(r.encoding or "utf-8", "replace") if r.status_code != 200 or not body: return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code} if text and is_challenge(text, r.status_code): return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code} return { "status": "success", "content": body, "text": text, "content_type": ctype, "original_url": url, "http_status": r.status_code, "method": "http", "final_url": r.url, }
# --- Fetch ladder (serial + parallel race) ---# Order (2026-09-15):# PARALLEL_LADDER race: WARC/slice pointer + Wayback CDX/replay + archive.is newest# First successful non-empty body wins; losers abandoned.# Then (serial, only on race miss): live HTTP/bs4 → optional Playwright (allowlist).# Cloudflare Browser Rendering / IPWB only when creds/local usable (skipped otherwise).
_last_archive_is = 0.0_archive_is_submit_count = 0_ARCHIVE_IS_SUBMIT_CAP = int(os.environ.get("ARCHIVE_IS_SUBMIT_CAP", "3") or 3)
# Default Playwright allowlist: known JS-heavy Easy/Hard gazette portals_DEFAULT_PLAYWRIGHT_HOSTS = ( "gacetaoficialdebolivia.gob.bo", "eqanun.az", "e-qanun.az", "iort.gov.tn", "dotic.ir", "paragraf.rs", "pravno-informacioni-sistem.rs",)
def _env_truthy(name: str, default: str = "0") -> bool: return os.environ.get(name, default) in ("1", "true", "True", "yes", "YES", "on", "ON")
def _sleep_archive_is(delay: float = 2.0) -> None: global _last_archive_is now = time.time() wait = delay - (now - _last_archive_is) if wait > 0: time.sleep(wait) _last_archive_is = time.time()
def has_cloudflare_creds() -> bool: """Cloudflare Browser Rendering only when API key present.""" tok = ( os.environ.get("CLOUDFLARE_API_TOKEN") or os.environ.get("CF_API_TOKEN") or os.environ.get("CLOUDFLARE_BROWSER_RENDERING_TOKEN") or "" ).strip() acct = ( os.environ.get("CLOUDFLARE_ACCOUNT_ID") or os.environ.get("CF_ACCOUNT_ID") or "" ).strip() return bool(tok and acct)
def has_ipwb_local() -> bool: """IPWB only if local package already usable — never install/start from tip.""" if not _env_truthy("TRY_IPWB", "0"): return False try: import ipwb # noqa: F401 return True except Exception: return False
def playwright_host_ok(url: str) -> bool: raw = (os.environ.get("PLAYWRIGHT_HOSTS") or "").strip() hosts = [h.strip().lower() for h in raw.split(",") if h.strip()] if raw else list(_DEFAULT_PLAYWRIGHT_HOSTS) try: host = (urlparse(url).hostname or "").lower().lstrip(".") except Exception: return False if not host: return False for h in hosts: if host == h or host.endswith("." + h): return True return False
def _body_nonempty(res: Optional[dict], min_text: int = 0) -> bool: if not res or res.get("status") != "success": return False text = res.get("text") or "" content = res.get("content") or b"" if isinstance(content, (bytes, bytearray)) and len(content) >= 64: if content[:4] == b"%PDF" or b"%PDF" in content[:8192]: return True if len(text) >= max(min_text, 1) or len(content) >= max(min_text, 256): return True if len(text) >= max(min_text, 1): return True return False
def get_wayback_cdx_then_replay(url: str, timestamp: Optional[str] = None, min_text: int = 0) -> dict: """Wayback: use given ts, else CDX newest then id_ replay. Honors global Wayback delay.""" ts = timestamp if not ts and not _env_truthy("SKIP_WAYBACK_CDX", "0"): try: hits = search_wayback_machine(url, limit=3, collapse="digest") if hits: ts = hits[0].get("timestamp") or None except Exception as exc: log.info("wayback cdx search fail %s: %s", url[:80], exc) res = get_wayback_content(url, timestamp=ts) if _body_nonempty(res, min_text=min_text): res["method"] = "wayback_cdx_replay" if ts and not timestamp else (res.get("method") or "wayback") if ts: res["capture_timestamp"] = res.get("capture_timestamp") or ts return res return res if res else {"status": "error", "error": "wayback_empty", "original_url": url}
def submit_archive_is(url: str, *, wait: bool = False, timeout: int = 45) -> dict: """Sparse archive.is submit (rate-limited + session cap). Prefer newest lookup first.""" global _archive_is_submit_count if _archive_is_submit_count >= _ARCHIVE_IS_SUBMIT_CAP: return {"status": "error", "error": "archive_is_submit_cap", "original_url": url} if not _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0"): return {"status": "error", "error": "archive_is_submit_disabled", "original_url": url} _sleep_archive_is(float(os.environ.get("ARCHIVE_IS_SUBMIT_DELAY", "5") or 5)) _archive_is_submit_count += 1 try: r = session().post( "https://archive.is/submit/", data={"url": url, "anyway": "1"}, timeout=(10, timeout), allow_redirects=True, ) except requests.RequestException as exc: return {"status": "error", "error": f"archive_is_submit:{exc}", "original_url": url} if "archive." in (r.url or "") and r.url and "submit" not in (r.url or ""): text = r.text or "" if not is_challenge(text, r.status_code): return { "status": "success", "content": r.content or b"", "text": text, "content_type": r.headers.get("content-type") or "text/html", "archive_url": r.url, "original_url": url, "method": "archive_is_submit", "http_status": r.status_code, } # Non-blocking: return pending; caller may re-hit newest later if not wait: return {"status": "error", "error": "archive_is_submit_pending", "original_url": url, "http_status": r.status_code} time.sleep(3) return get_archive_is_content(url)
def get_archive_is_content_ladder(url: str, *, submit_on_miss: Optional[bool] = None) -> dict: """archive.is newest (+ optional sparse submit). Always rate-limited.""" _sleep_archive_is(float(os.environ.get("ARCHIVE_IS_DELAY", "2") or 2)) res = get_archive_is_content(url) if _body_nonempty(res): return res do_submit = ( submit_on_miss if submit_on_miss is not None else _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0") ) if do_submit: sub = submit_archive_is(url, wait=_env_truthy("ARCHIVE_IS_SUBMIT_WAIT", "0")) if _body_nonempty(sub): return sub # One more newest lookup after submit _sleep_archive_is(2.0) res2 = get_archive_is_content(url) if _body_nonempty(res2): res2["method"] = "archive_is_after_submit" return res2 return sub if sub.get("error") else res return res
def get_http_bs4(url: str) -> dict: """Live HTTP with BeautifulSoup text extraction when available.""" res = get_http(url) if res.get("status") != "success": return res text = res.get("text") or "" ctype = (res.get("content_type") or "").lower() if "html" in ctype or (text[:200].lstrip().startswith("<")): try: from bs4 import BeautifulSoup
soup = BeautifulSoup(text, "html.parser") for tag in soup(["script", "style", "noscript"]): tag.decompose() extracted = " ".join(soup.get_text(" ", strip=True).split()) if len(extracted) > len(text) * 0.05 and len(extracted) >= 80: res = dict(res) res["text"] = extracted res["method"] = "http_bs4" except Exception as exc: log.info("bs4 extract skip %s: %s", url[:60], exc) return res
def get_playwright_content(url: str, *, timeout_ms: int = 45000) -> dict: """Optional Playwright for allowlisted JS portals. Skip if package/browser missing.""" if not playwright_host_ok(url): return {"status": "error", "error": "playwright_host_not_allowlisted", "original_url": url} try: from playwright.sync_api import sync_playwright except Exception as exc: return {"status": "error", "error": f"playwright_unavailable:{exc}", "original_url": url} try: with sync_playwright() as p: browser = p.chromium.launch(headless=True) try: page = browser.new_page() page.goto(url, wait_until="networkidle", timeout=timeout_ms) page.wait_for_timeout(1500) html = page.content() or "" content = html.encode("utf-8", "replace") finally: browser.close() except Exception as exc: return {"status": "error", "error": f"playwright:{exc}", "original_url": url} if not html or is_challenge(html, 200): return {"status": "error", "error": "playwright_challenge_or_empty", "original_url": url} text = html try: from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser") for tag in soup(["script", "style", "noscript"]): tag.decompose() text = " ".join(soup.get_text(" ", strip=True).split()) except Exception: pass return { "status": "success", "content": content, "text": text, "content_type": "text/html", "original_url": url, "method": "playwright", "http_status": 200, }
def _race_fetch_one(name: str, fn, winner_event: "threading.Event") -> tuple[str, dict]: if winner_event.is_set(): return name, {"status": "error", "error": "abandoned_after_winner"} try: res = fn() except Exception as exc: return name, {"status": "error", "error": f"{name}:{exc}"} return name, res if isinstance(res, dict) else {"status": "error", "error": f"{name}:bad_result"}
def parse_parallel_ladder_sources() -> list[str]: """Parse PARALLEL_LADDER env into ordered source names.
PARALLEL_LADDER=1 / true / all → full five-way race. PARALLEL_LADDER=0 / false / serial → empty (caller uses serial path). PARALLEL_LADDER=warc,wayback,archive_is,live,playwright → explicit set. """ raw = (os.environ.get("PARALLEL_LADDER", "1") or "1").strip() low = raw.lower() if low in ("0", "false", "no", "off", "serial"): return [] all5 = ["warc", "wayback", "archive_is", "live", "playwright"] if low in ("1", "true", "yes", "on", "all", "full"): return all5 parts = [x.strip().lower().replace("-", "_") for x in raw.split(",") if x.strip()] alias = { "ais": "archive_is", "archiveis": "archive_is", "ia": "wayback", "wb": "wayback", "http": "live", "http_live": "live", "bs4": "live", "pw": "playwright", "cc": "warc", "common_crawl": "warc", } out: list[str] = [] for p in parts: name = alias.get(p, p) if name in all5 and name not in out: out.append(name) return out or all5
_playwright_jobs_this_process = 0_playwright_lock = None
def _get_playwright_lock(): global _playwright_lock if _playwright_lock is None: import threading _playwright_lock = threading.Lock() return _playwright_lock
def _mem_avail_gi() -> float: try: with open("/proc/meminfo") as f: for line in f: if line.startswith("MemAvailable:"): return int(line.split()[1]) / 1024 / 1024 except Exception: pass return 99.0
def _playwright_soft_ok() -> bool: """≤1 Playwright per country job (process); box ≤2 via PLAYWRIGHT_BOX_MAX; Mem≥6Gi.""" global _playwright_jobs_this_process if _mem_avail_gi() < float(os.environ.get("PLAYWRIGHT_MIN_MEM_GI", "6") or 6): return False per_job = int(os.environ.get("PLAYWRIGHT_PER_JOB", "1") or 1) if _playwright_jobs_this_process >= per_job: return False # Soft box-wide cap via lockfile count (best-effort, no kill) box_max = int(os.environ.get("PLAYWRIGHT_BOX_MAX", "2") or 2) lock_dir = os.environ.get("PLAYWRIGHT_LOCK_DIR", "/tmp/legal_scrapers_pw_locks") try: os.makedirs(lock_dir, exist_ok=True) active = 0 for entry in os.listdir(lock_dir): if not entry.endswith(".pw"): continue path = os.path.join(lock_dir, entry) try: pid = int(entry.split("_", 1)[0]) os.kill(pid, 0) active += 1 except ProcessLookupError: try: os.unlink(path) except OSError: pass except (ValueError, PermissionError, OSError): active += 1 # fail closed for unknown/foreign lock if active >= box_max: return False except Exception: pass return True
def _playwright_acquire_slot() -> Optional[str]: """Create a lockfile slot; return path or None.""" global _playwright_jobs_this_process if not _playwright_soft_ok(): return None with _get_playwright_lock(): if not _playwright_soft_ok(): return None lock_dir = os.environ.get("PLAYWRIGHT_LOCK_DIR", "/tmp/legal_scrapers_pw_locks") os.makedirs(lock_dir, exist_ok=True) path = os.path.join(lock_dir, f"{os.getpid()}_{int(time.time() * 1000)}.pw") try: with open(path, "w") as f: f.write(str(os.getpid())) except Exception: return None _playwright_jobs_this_process += 1 return path
def _playwright_release_slot(path: Optional[str]) -> None: if not path: return try: os.unlink(path) except Exception: pass
def fetch_ladder_parallel_race( url: str, *, cc_record: Optional[dict] = None, wayback_ts: Optional[str] = None, min_text: int = 150, sources: Optional[list[str]] = None, try_cc: bool = True, try_wayback: bool = True, try_archive_is: bool = True, try_http: bool = True, try_playwright: bool = True,) -> dict: """Five-way race: WARC ∥ Wayback ∥ archive.is ∥ live ∥ Playwright.
First successful non-empty body wins; losers abandoned (cancel futures best-effort). Soft caps: ≤1 Playwright/job, box ≤2, skip PW if MemAvail<6Gi. archive.is submit_on_miss stays sparse (newest lookup races; submit not in race). Shared global Wayback delay via get_wayback_*. """ import concurrent.futures import threading
errors: list[str] = [] winner_event = threading.Event() srcs = sources if sources is not None else parse_parallel_ladder_sources() if not srcs: return {"status": "error", "error": "no_parallel_sources", "original_url": url, "ladder": "parallel_race"}
def _warc_job() -> dict: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} recs: list[dict] = [] if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")): recs = [cc_record] elif try_cc and _env_truthy("LADDER_CC_SEARCH", "0"): try: recs = search_common_crawl(url, limit=2) except Exception as exc: return {"status": "error", "error": f"common_crawl_search:{exc}"} if not recs: return {"status": "error", "error": "no_warc_pointer"} last = {"status": "error", "error": "warc_miss"} for rec in recs: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} last = fetch_common_crawl_warc(rec) if _body_nonempty(last, min_text=0): last = dict(last) last["method"] = last.get("method") or "common_crawl_warc" return last return last
def _wb_job() -> dict: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} return get_wayback_cdx_then_replay(url, timestamp=wayback_ts, min_text=0)
def _ais_job() -> dict: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} # Newest lookup only in race; submit_on_miss stays sparse / out-of-race return get_archive_is_content_ladder(url, submit_on_miss=False)
def _live_job() -> dict: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} res = get_http_bs4(url) if res.get("status") == "success": raw = res.get("text") or "" if is_challenge(raw, res.get("http_status") or 200) or is_spa_shell(raw, raw): return {"status": "error", "error": "live_challenge_or_spa", "original_url": url} return res
def _pw_job() -> dict: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} if not playwright_host_ok(url): return {"status": "error", "error": "playwright_host_not_allowlisted", "original_url": url} slot = _playwright_acquire_slot() if not slot: return {"status": "error", "error": "playwright_soft_cap", "original_url": url} try: if winner_event.is_set(): return {"status": "error", "error": "abandoned_after_winner"} return get_playwright_content(url) finally: _playwright_release_slot(slot)
tasks: list[tuple[str, Any]] = [] if "warc" in srcs and (try_cc or (cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")))): tasks.append(("warc", _warc_job)) if "wayback" in srcs and try_wayback and not _env_truthy("SKIP_WAYBACK", "0"): tasks.append(("wayback", _wb_job)) if "archive_is" in srcs and try_archive_is and _env_truthy("TRY_ARCHIVE_IS", "1"): tasks.append(("archive_is", _ais_job)) if "live" in srcs and try_http: tasks.append(("live", _live_job)) # Playwright: include in race when listed; TRY_PLAYWRIGHT default 1 if listed in PARALLEL_LADDER pw_wanted = "playwright" in srcs and ( try_playwright or _env_truthy("TRY_PLAYWRIGHT", "1" if "playwright" in srcs else "0") ) if pw_wanted: tasks.append(("playwright", _pw_job))
if not tasks: return {"status": "error", "error": "no_race_tasks", "original_url": url, "ladder": "parallel_race", "sources": srcs}
winner: Optional[dict] = None max_workers = min(5, len(tasks)) ex = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="ladder") futs = {ex.submit(_race_fetch_one, name, fn, winner_event): name for name, fn in tasks} try: for fut in concurrent.futures.as_completed( futs, timeout=float(os.environ.get("LADDER_RACE_TIMEOUT", "90") or 90) ): name = futs[fut] try: _n, res = fut.result() except Exception as exc: errors.append(f"{name}:{exc}") continue if _body_nonempty(res, min_text=0): winner_event.set() winner = dict(res) winner["ladder"] = "parallel_race" winner["ladder_winner"] = name winner["ladder_sources"] = srcs winner["method"] = winner.get("method") or name for other in futs: if other is not fut and not other.done(): other.cancel() break errors.append(f"{name}:{res.get('error') or 'empty'}") except concurrent.futures.TimeoutError: errors.append("race_timeout") winner_event.set() for other in futs: if not other.done(): other.cancel() finally: # Critical: do not wait for in-flight losers. They see winner_event where possible; # already-blocked HTTP calls are abandoned and finish in background. ex.shutdown(wait=False, cancel_futures=True)
if winner and _body_nonempty(winner, min_text=min_text if min_text else 0): winner["ladder_errors"] = errors return winner if winner and _body_nonempty(winner, min_text=0): winner["ladder_errors"] = errors winner["warning"] = "below_min_text" return winner return { "status": "error", "error": "; ".join(errors) or "parallel_race_miss", "original_url": url, "ladder": "parallel_race", "ladder_sources": srcs, "ladder_errors": errors, }
def fetch_ladder( url: str, *, cc_record: Optional[dict] = None, wayback_ts: Optional[str] = None, min_text: int = 150, try_cc: Optional[bool] = None, try_wayback: Optional[bool] = None, try_archive_is: Optional[bool] = None, try_http: Optional[bool] = None, try_playwright: Optional[bool] = None, parallel: Optional[bool] = None, sources: Optional[list[str]] = None,) -> dict: """Unified fetch ladder for tip climb.
PARALLEL_LADDER default = warc,wayback,archive_is,live,playwright (five-way race). First good body wins. Soft-cap Playwright; sparse archive.is submit (newest races). PARALLEL_LADDER=0 → serial: WARC → Wayback → archive.is → live → Playwright. Skips: Cloudflare unless creds; IPWB unless local+TRY_IPWB; Brave without key. """ if try_cc is None: try_cc = True if try_wayback is None: try_wayback = not _env_truthy("SKIP_WAYBACK", "0") if try_archive_is is None: try_archive_is = _env_truthy("TRY_ARCHIVE_IS", "1") srcs = sources if sources is not None else parse_parallel_ladder_sources() if try_http is None: # Listing live in PARALLEL_LADDER opts into live race even if SKIP_LIVE=1 if "live" in srcs: try_http = not _env_truthy("LADDER_SKIP_LIVE", "0") else: try_http = not _env_truthy("SKIP_LIVE", "0") if try_playwright is None: # If playwright listed in PARALLEL_LADDER, default on unless TRY_PLAYWRIGHT=0 if "playwright" in srcs: try_playwright = _env_truthy("TRY_PLAYWRIGHT", "1") else: try_playwright = _env_truthy("TRY_PLAYWRIGHT", "0") if parallel is None: parallel = bool(srcs)
errors: list[str] = [] steps: list[str] = []
if parallel and srcs: steps.append("parallel_race:" + ",".join(srcs)) res = fetch_ladder_parallel_race( url, cc_record=cc_record, wayback_ts=wayback_ts, min_text=min_text, sources=srcs, try_cc=try_cc, try_wayback=try_wayback, try_archive_is=try_archive_is, try_http=try_http, try_playwright=try_playwright, ) if _body_nonempty(res, min_text=0): res = dict(res) res["ladder_steps"] = steps return res errors.append(f"race:{res.get('error')}") # Sparse submit only after race miss (not inside race) if try_archive_is and _env_truthy("ARCHIVE_IS_SUBMIT_ON_MISS", "0"): steps.append("archive_is_submit") sub = submit_archive_is(url, wait=_env_truthy("ARCHIVE_IS_SUBMIT_WAIT", "0")) if _body_nonempty(sub, min_text=0): sub = dict(sub) sub["ladder"] = "after_race_submit" sub["ladder_steps"] = steps return sub errors.append(f"archive_is_submit:{sub.get('error')}") else: # Serial fallback if try_cc or (cc_record and (cc_record.get("filename") or cc_record.get("warc_filename"))): steps.append("warc") cc_recs: list[dict] = [] if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")): cc_recs = [cc_record] elif try_cc and _env_truthy("LADDER_CC_SEARCH", "0"): try: cc_recs = search_common_crawl(url, limit=4) except Exception as exc: errors.append(f"common_crawl:{exc}") for rec in cc_recs: res = fetch_common_crawl_warc(rec) if _body_nonempty(res, min_text=0): res = dict(res) res["method"] = res.get("method") or "common_crawl_warc" res["ladder"] = "serial" res["ladder_steps"] = steps return res errors.append(f"common_crawl:{res.get('error')}") if try_wayback: steps.append("wayback") res = get_wayback_cdx_then_replay(url, timestamp=wayback_ts, min_text=0) if _body_nonempty(res, min_text=0): res = dict(res) res["ladder"] = "serial" res["ladder_steps"] = steps return res errors.append(f"wayback:{res.get('error')}") if try_archive_is: steps.append("archive_is") res = get_archive_is_content_ladder(url) if _body_nonempty(res, min_text=0): res = dict(res) res["ladder"] = "serial" res["ladder_steps"] = steps return res errors.append(f"archive_is:{res.get('error')}") if try_http: steps.append("live_http") res = get_http_bs4(url) if _body_nonempty(res, min_text=0): raw = res.get("text") or "" if not is_challenge(raw, res.get("http_status") or 200): res = dict(res) res["ladder"] = "serial" res["ladder_steps"] = steps return res errors.append(f"http:{res.get('error') or 'empty'}") if try_playwright and playwright_host_ok(url): steps.append("playwright") if _playwright_soft_ok(): slot = _playwright_acquire_slot() try: res = get_playwright_content(url) finally: _playwright_release_slot(slot) if _body_nonempty(res, min_text=0): res = dict(res) res["ladder"] = "serial" res["ladder_steps"] = steps return res errors.append(f"playwright:{res.get('error')}") else: errors.append("playwright:soft_cap")
if has_cloudflare_creds() and _env_truthy("TRY_CLOUDFLARE", "0"): errors.append("cloudflare:no_sync_tip_impl") if has_ipwb_local(): errors.append("ipwb:not_wired_in_tip_ladder")
return { "status": "error", "error": "; ".join(errors) or "ladder_all_failed", "original_url": url, "ladder": "parallel" if (parallel and srcs) else "serial", "ladder_steps": steps, "ladder_errors": errors, }
def fetch_with_fallbacks( url: str, *, cc_record: Optional[dict] = None, wayback_ts: Optional[str] = None, try_archive_is: bool = False, try_http: bool = True, try_cc: bool = True,) -> dict: """Back-compat wrapper → fetch_ladder.
Historical default was serial WARC→Wayback→(optional archive.is)→HTTP. When PARALLEL_LADDER=1 (default for new tip paths), races archive sources first. Pass try_archive_is=True or set TRY_ARCHIVE_IS=1 to include archive.is. """ # Preserve prior call-site semantics for try_archive_is default False unless env set ais = try_archive_is or _env_truthy("TRY_ARCHIVE_IS", "0") return fetch_ladder( url, cc_record=cc_record, wayback_ts=wayback_ts, try_cc=try_cc, try_archive_is=ais, try_http=try_http, # Back-compat callers stay serial unless env explicitly opts into race. parallel=bool(parse_parallel_ladder_sources()) if "PARALLEL_LADDER" in os.environ else False, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440#!/usr/bin/env python3"""Botswana: official Acts / Bills / Gazette / SI PDFs from government portals.
Primary: gov.bw, parliament.gov.bw / botswanaspeaks.gov.bw (Parliament Bills &Extraordinary Gazettes), BURS tax Acts, Attorney-General-linked portal PDFs,and statutory agency hosts that publish official Acts/Regulations/SIs(Bank of Botswana, BOCRA, BERA, CAAB, NBFIRA, PPADB, Competition Authority,HRDC, justice.gov.bw).
Skips: botswanalaws.com, SAFLII, laws.co.bw (private), drafts, order/noticepapers, press releases. elaws.gov.bw is preferred by gov.bw but unreachablefrom this collector environment (recorded as a coverage gap).Live official URL first; Wayback of the same official URL on failure.No WAF bypass."""from __future__ import annotations
import loggingimport reimport sysimport timefrom pathlib import Pathfrom urllib.parse import unquote, urljoin, urlparse
sys.path.insert(0, str(Path(__file__).resolve().parent))from common import existing_ids, log_failure, utcnow, write_summaryfrom world_lib import cdx_urls, env_int, fetch_official, live_get, save_instrument, setup_log, slug_id
CC, COUNTRY, LANG = "bw", "Botswana", "en"SOURCE_TYPE = "botswana_official_gazettes_acts"LICENSE = ( "Laws / Bills / Gazette instruments of Botswana as published on official " "government and statutory-agency portals (gov.bw, parliament.gov.bw, " "botswanaspeaks.gov.bw, burs.org.bw, and related .gov.bw / statutory hosts). " "Authentic Government Printer / e-Laws text prevails. Not legal advice.")UA = "legal-corpora-collector/1.0 (research; source=https://www.gov.bw/)"ART = re.compile( r"(?im)^\s*((?:Section|Sec\.|Article|Art\.|Regulation|Reg\.)\s+\d+[A-Za-z]?\.?)\b")log = logging.getLogger("bw")
BLOCK_HOST = re.compile( r"(botswanalaws\.com|saflii\.org|laws\.co\.bw|gazettes\.africa|" r"africanlii\.org|commonlii\.org|ulii\.org)", re.I,)SKIP_NAME = re.compile( r"(draft|press[_\-\s]?release|order[_\-\s]?paper|notice[_\-\s]?paper|" r"ordpap|notpap|fact[_\-\s]?sheet|brochure|application[_\-\s]?form|" r"form[_\-\s]?ita|tin[_\-\s]?application|action[_\-\s]?plan|" r"bill[_\-\s]?shock|committee[_\-\s]?of[_\-\s]?supply|speech|" r"statement|monetary[_\-\s]?policy|financial[_\-\s]?position|" r"business[_\-\s]?expectations|external[_\-\s]?sector|" r"data[_\-\s]?protection[_\-\s]?and[_\-\s]?privacy[_\-\s]?statement|" r"privacy[_\-\s]?statement|manual[_\-\s]?of[_\-\s]?operating|" r"roll[_\-\s]?out|schedule[_\-\s]?roll|contacts?\.pdf|" r"advert|newsletter|vacancy|tender|annual[_\-\s]?report|" r"abstract|fruit[_\-\s]?ninja|leather[_\-\s]?and[_\-\s]?leather|" r"manufacturers[_\-\s]?directory|call[_\-\s]?for[_\-\s]?research|" r"audit[_\-\s]?of[_\-\s]?billing|broadcaster.?s[_\-\s]?code|" r"interactive\.pdf|corrigendum[_\-\s]?-[_\-\s]?ordpap|" r"addendum[_\-\s]?-[_\-\s]?ordpap|addendum[_\-\s]?-[_\-\s]?notpap|" r"winter[_\-\s]?session|parliament[_\-\s]?business[_\-\s]?update)", re.I,)LAWISH_NAME = re.compile( r"(" r"\bact\b|_act_|-act-|act\.pdf|act%20|" r"\bbill\b|_bill_|-bill-|bill\.pdf|" r"regulation|regulations|" r"gazette|statutory[_\-\s]?instrument|\bsi[_\-\s]?\d|" r"chapter[_\-\s]?\d|cap[_\-\s\.]?\d|" r"enacted|supplement[_\-\s]?[abc]\b" r")", re.I,)LAW_MARK = re.compile( r"(ENACTED by the Parliament of Botswana|AN ACT\b|A BILL\b|" r"Short title|This Act may be cited|GOVERNMENT GAZETTE|" r"ARRANGEMENT OF SECTIONS|Statutory Instrument|supplement [ABC]\b|" r"Date of Assent|No\.\s*\d+\s+of\s+20\d{2})", re.I,)
CDX_PREFIXES = [ "www.gov.bw/sites/default/files/", "gov.bw/sites/default/files/", "botswanaspeaks.gov.bw/media/BILLS/", "www.botswanaspeaks.gov.bw/media/BILLS/", "www.burs.org.bw/", "www.bankofbotswana.bw/assets/", "www.bocra.org.bw/sites/default/files/", "www.bera.co.bw/downloads/", "www.caab.co.bw/wp-content/uploads/", "www.nbfira.org.bw/sites/default/files/", "www.ppadb.co.bw/Act_Reg/", "www.competitionauthority.co.bw/sites/default/files/", "www.hrdc.org.bw/sites/default/files/", "www.justice.gov.bw/sites/default/files/", "www.parliament.gov.bw/documents/",]
LIVE_SEEDS = [ "https://www.gov.bw/law-crime-and-justice/access-laws-botswana", "https://www.botswanaspeaks.gov.bw/category/4/parliament-business", "https://www.burs.org.bw/index.php/tax/tax-laws-2026", "https://www.burs.org.bw/index.php/tax/tax-downloads", "https://www.bocra.org.bw/legislation", "https://www.caab.co.bw/regulations/", "https://www.bankofbotswana.bw/", "https://www.competitionauthority.co.bw/", "https://www.hrdc.org.bw/", "https://www.ppadb.co.bw/", "https://www.nbfira.org.bw/", "https://www.justice.gov.bw/", "https://www.parliament.gov.bw/",]
BURS_ACT_PAGES = [ "https://www.burs.org.bw/index.php/tax/tax-laws-2026", "https://www.burs.org.bw/index.php/tax/tax-downloads",]
def _norm(url: str) -> str: u = (url or "").split("#")[0] u = u.replace("http://", "https://") u = re.sub(r":80/", "/", u) u = re.sub(r"https://gov\.bw/", "https://www.gov.bw/", u) u = re.sub(r"https://parliament\.gov\.bw/", "https://www.parliament.gov.bw/", u) u = re.sub(r"https://botswanaspeaks\.gov\.bw/", "https://www.botswanaspeaks.gov.bw/", u) parts = urlparse(u) # Keep only download= query params (BURS phocadownload); drop tracking junk q = parts.query or "" if "download=" in q: m = re.search(r"(download=\d+:[a-z0-9\-]+)", q, re.I) q = m.group(1) if m else "" else: q = "" path = quote_path(unquote(parts.path)) if (" " in unquote(parts.path) or "%" in parts.path) else parts.path # Prefer percent-encoded spaces for fetch reliability if " " in path: path = quote_path(path) u = parts._replace(path=path, query=q, params="", fragment="").geturl() return u.rstrip("?")
def quote_path(path: str) -> str: from urllib.parse import quote
return quote(path, safe="/%")
def _ident_from_url(url: str) -> str: path = unquote(urlparse(url.split("?")[0]).path) name = Path(path).name if "download=" in url: m = re.search(r"download=(\d+):([a-z0-9\-]+)", url, re.I) if m: name = f"{m.group(2)}-{m.group(1)}" if name.lower().endswith(".pdf"): name = name[:-4] name = re.sub(r"\s+", " ", name).strip() return re.sub(r"[^\w.\-]+", "-", name)[:160] or "bw-doc"
def _host_ok(url: str) -> bool: if not url or not url.startswith("http"): return False if BLOCK_HOST.search(url): return False host = (urlparse(url).hostname or "").lower() # official / statutory agency hosts only ok_suffixes = ( ".gov.bw", "gov.bw", "burs.org.bw", "bankofbotswana.bw", "bocra.org.bw", "bera.co.bw", "caab.co.bw", "nbfira.org.bw", "ppadb.co.bw", "competitionauthority.co.bw", "hrdc.org.bw", "botswanaspeaks.gov.bw", ) return any(host == s or host.endswith("." + s) or host.endswith(s) for s in ok_suffixes)
def _is_law_url(url: str) -> bool: u = _norm(url) if not _host_ok(u): return False low = unquote(u).lower() if SKIP_NAME.search(low): return False # BURS phocadownload acts if "burs.org.bw" in low and "download=" in low: if re.search(r"(act|bill|regulation|gazette|cap[-_ ]?\d|statutory)", low): return True return False if ".pdf" not in low and "download=" not in low: return False name = unquote(urlparse(u.split("?")[0]).path).split("/")[-1] if SKIP_NAME.search(name): return False # Prefer explicit lawish filenames; allow /BILLS/ folder and Act_Reg/ if "/bills/" in low or "/act_reg/" in low or "extraordinary" in low and "gazette" in low: return not SKIP_NAME.search(name) if LAWISH_NAME.search(name) or LAWISH_NAME.search(low): return True return False
def _title_from_text(text: str, fallback: str) -> str: lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()] for ln in lines[:50]: if re.search(r"\b(ACT|BILL|REGULATIONS?|GAZETTE)\b", ln) and 8 <= len(ln) <= 180: if not re.match(r"^(TITLE|PREVIOUS|NEXT|CONTENTS)\b", ln, re.I): return ln[:240] for ln in lines: if len(ln) >= 12 and not ln.lower().startswith("just a moment"): return ln[:240] return fallback[:240]
def _looks_like_law(text: str) -> bool: if not text or len(text) < 200: return False head = text[:8000] if LAW_MARK.search(head): return True # section-dense statutes without classic preamble secs = len(re.findall(r"(?im)^\s*Section\s+\d+", text[:20000])) return secs >= 5
def _add(items: list, seen: set, url: str, ident: str | None = None) -> None: url = _norm(url) if not url or url in seen or not _is_law_url(url): return seen.add(url) items.append((ident or _ident_from_url(url), url))
def _harvest_html(url: str) -> list[str]: out = [] try: r = live_get(url, ua=UA, verify=False, timeout=(20, 50)) except Exception as exc: log.info("seed fail %s: %s", url[:90], exc) return out text = r.text or "" for href in re.findall(r'href=["\']([^"\']+)["\']', text, re.I): full = urljoin(url, href) if ".pdf" in full.lower() or "download=" in full.lower(): out.append(full) for m in re.findall(r'(https?://[^"\'\s>]+\.pdf)', text, re.I): out.append(m) return out
def _botswanaspeaks_bills() -> list[tuple[str, str]]: """Crawl Parliament Business articles for Bill / Gazette PDFs only.""" items, seen_u, seen_a = [], set(), set() seeds = ["https://www.botswanaspeaks.gov.bw/category/4/parliament-business"] articles = [] for su in seeds: try: r = live_get(su, ua=UA, verify=False, timeout=(20, 60)) except Exception as exc: log.info("speaks category fail: %s", exc) continue for href in re.findall(r'href=["\']([^"\']+)["\']', r.text or "", re.I): full = urljoin(su, href).split("#")[0] if "/article/" in full and full not in seen_a: seen_a.add(full) articles.append(full) log.info("speaks articles %s", len(articles)) for au in articles[: env_int("SPEAKS_ARTICLES", 120)]: try: r = live_get(au, ua=UA, verify=False, timeout=(15, 40)) except Exception: continue for href in re.findall(r'href=["\']([^"\']+\.pdf[^"\']*)["\']', r.text or "", re.I): full = _norm(urljoin(au, href)) low = unquote(full).lower() # only BILLS / gazette paths — skip order/notice papers if "/bills/" not in low and "gazette" not in low and "extraordinary" not in low: continue if full in seen_u: continue if not _is_law_url(full): continue seen_u.add(full) items.append((_ident_from_url(full), full)) log.info("speaks bill/gazette pdfs %s", len(items)) return items
def _burs_downloads() -> list[tuple[str, str]]: items, seen = [], set() for page in BURS_ACT_PAGES: try: r = live_get(page, ua=UA, verify=False, timeout=(20, 50)) except Exception as exc: log.info("burs page fail %s: %s", page, exc) continue for m in re.findall(r"(download=\d+:[a-z0-9\-]+)", r.text or "", re.I): slug = m.split(":", 1)[-1] if not re.search(r"(act|bill|regulation|gazette|cap-|statutory|order)", slug, re.I): continue if re.search(r"(form|faq|guidance|guideline|table|certificate|application)", slug, re.I): continue url = urljoin(page, f"?{m}" if "?" not in page else f"&{m}") # Prefer clean absolute download URLs on same path if "tax-laws-2026" in page: url = f"https://www.burs.org.bw/index.php/tax/tax-laws-2026?{m}" elif "tax-downloads" in page: url = f"https://www.burs.org.bw/index.php/tax/tax-downloads?{m}" else: url = urljoin(page.split("?")[0], "?" + m) if url in seen: continue if not _is_law_url(url): continue seen.add(url) items.append((_ident_from_url(url), url)) log.info("burs act downloads %s", len(items)) return items
def discover(): items, seen = [], set()
# 1) Parliament Bills / Extraordinary Gazettes (botswanaspeaks) for ident, url in _botswanaspeaks_bills(): _add(items, seen, url, ident)
# 2) BURS official tax Acts for ident, url in _burs_downloads(): _add(items, seen, url, ident)
# 3) Live seed page PDF harvest for su in LIVE_SEEDS: for href in _harvest_html(su): _add(items, seen, href)
# 4) CDX of official hosts (Wayback index of live official URLs) limit = env_int("CDX_LIMIT", 180) for prefix in CDX_PREFIXES: for h in cdx_urls(prefix, limit=limit, match_type="prefix", extra_filters=["mimetype:application/pdf"]): orig = (h.get("original") or "").replace("http://", "https://") _add(items, seen, orig) if len(items) >= env_int("CATALOG_CAP", 400): break
log.info("catalog %s", len(items)) return items
def main(): setup_log(CC) t0 = utcnow() max_new = env_int("MAX_NEW", 80) max_seconds = env_int("MAX_SECONDS", 3600) t_start = time.time() done = existing_ids(CC) ok = skip = fail = 0 for ident, url in discover(): if max_new and ok >= max_new: break if time.time() - t_start > max_seconds: break rid = slug_id(CC, ident) if rid in done: skip += 1 continue got = fetch_official(url, ua=UA, verify=False, min_text=180) text = got.get("text") or "" if got.get("status") != "success": fail += 1 log_failure(CC, {"identifier": ident, "source_url": url, "reason": got.get("error")}) continue if not _looks_like_law(text): fail += 1 log_failure(CC, {"identifier": ident, "source_url": url, "reason": "not_law_like"}) continue title = _title_from_text(text, ident) if save_instrument( cc=CC, country=COUNTRY, language=LANG, ident=ident, title=title, text=text, source_url=url, source_type=SOURCE_TYPE, license_text=LICENSE, collector="collect_bw.py", article_re=ART, extra_meta={"fetch_method": got.get("method")}, ): ok += 1 done.add(rid) log.info("ok %s chars=%s method=%s", ident[:70], len(text), got.get("method")) else: fail += 1 write_summary( CC, country=COUNTRY, source="Botswana official portals (gov.bw / Parliament / BURS / statutory agencies)", source_urls=[ "https://www.gov.bw/", "https://www.parliament.gov.bw/", "https://www.botswanaspeaks.gov.bw/", "https://www.burs.org.bw/", "https://www.elaws.gov.bw/", ], license_text=LICENSE, discovered=ok + skip + fail, fetched=ok, skipped=skip, failed=fail, coverage="catalog-backed incomplete; elaws.gov.bw unreachable from collector host", notes=( "Official Acts/Bills/Gazette/SI PDFs from gov.bw, Parliament Speaks, " "BURS, and statutory agency hosts. Skipped botswanalaws.com / SAFLII / " "laws.co.bw. elaws.gov.bw (AGC e-Laws) preferred by gov.bw but not " "reachable here. Not legal advice." ), last_run=t0, ) log.info("done ok=%s skip=%s fail=%s", ok, skip, fail)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958#!/usr/bin/env python3"""Collect current Swiss federal classified compilation (SR) from Fedlex."""from __future__ import annotations
import concurrent.futuresimport hashlibimport htmlimport ioimport jsonimport loggingimport osimport randomimport reimport subprocessimport sysimport threadingimport timeimport tracebackimport urllib.errorimport urllib.parseimport urllib.requestimport zipfilefrom datetime import datetime, timezonefrom html.parser import HTMLParserfrom pathlib import Pathfrom xml.etree import ElementTree as ET
ROOT = Path("/workspace/legal-corpora/ch")INSTR = ROOT / "instruments"LOGS = ROOT / "logs"TMP = ROOT / "tmp"INDEX = ROOT / "index.jsonl"SUMMARY = ROOT / "SUMMARY.md"CATALOG = TMP / "catalog.json"FAILED = LOGS / "failed.jsonl"
SPARQL_ENDPOINT = "https://fedlex.data.admin.ch/sparqlendpoint"TODAY = "2026-09-02"USER_AGENT = "legal-corpora-ch-collector/1.0 (research corpus; polite; contact via local operator)"IN_FORCE = "https://fedlex.data.admin.ch/vocabulary/enforcement-status/0"LANG_URI = { "de": "http://publications.europa.eu/resource/authority/language/DEU", "fr": "http://publications.europa.eu/resource/authority/language/FRA", "it": "http://publications.europa.eu/resource/authority/language/ITA", "rm": "http://publications.europa.eu/resource/authority/language/ROH", "en": "http://publications.europa.eu/resource/authority/language/ENG",}URI_LANG = {v: k for k, v in LANG_URI.items()}FMT_RANK = { "https://fedlex.data.admin.ch/vocabulary/user-format/xml": 0, "https://fedlex.data.admin.ch/vocabulary/user-format/html": 1, "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a": 2, "https://fedlex.data.admin.ch/vocabulary/user-format/pdf": 3, "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-x": 4, "https://fedlex.data.admin.ch/vocabulary/user-format/docx": 5, "https://fedlex.data.admin.ch/vocabulary/user-format/doc": 6,}FMT_NAME = { "https://fedlex.data.admin.ch/vocabulary/user-format/xml": "xml", "https://fedlex.data.admin.ch/vocabulary/user-format/html": "html", "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a": "pdf-a", "https://fedlex.data.admin.ch/vocabulary/user-format/pdf": "pdf", "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-x": "pdf-x", "https://fedlex.data.admin.ch/vocabulary/user-format/docx": "docx", "https://fedlex.data.admin.ch/vocabulary/user-format/doc": "doc",}LICENSE = ( "Official legislative texts are not protected by copyright (URG Art. 5; " "https://www.fedlex.admin.ch/eli/cc/1993/1798_1798_1798/de). " "Consultation and download for reuse are free (PublG Art. 19; PublV Art. 48). " "Reuse is subject to PublV Art. 49 (SR 170.512.1): do not alter the wording; " "visually distinguish the text from commentary; include the notice " "'Dies ist keine amtliche Veröffentlichung. Massgebend ist allein die " "Veröffentlichung durch die Bundeskanzlei.'; do not present the copy as an " "official publication; paid redistribution only in added-value form. " "See https://www.fedlex.admin.ch/de/legal-information and " "https://www.fedlex.admin.ch/de/broadcasters")REUSE_NOTICE = ( "Dies ist keine amtliche Veröffentlichung. Massgebend ist allein die " "Veröffentlichung durch die Bundeskanzlei.")
WORKERS = 8HTTP_TIMEOUT = 90SPARQL_TIMEOUT = 180MAX_BYTES = 80 * 1024 * 1024RETRIES = 5
log = logging.getLogger("collector")index_lock = threading.Lock()fail_lock = threading.Lock()stats_lock = threading.Lock()STATS = { "listed": 0, "collected": 0, "failed": 0, "skipped_resume": 0, "bytes": 0, "empty_text": 0, "started_at": None, "by_format": {}, "by_lang_primary": {},}
def setup_logging() -> None: LOGS.mkdir(parents=True, exist_ok=True) INSTR.mkdir(parents=True, exist_ok=True) TMP.mkdir(parents=True, exist_ok=True) log.setLevel(logging.INFO) fmt = logging.Formatter("%(asctime)sZ %(levelname)s %(message)s", "%Y-%m-%dT%H:%M:%S") fh = logging.FileHandler(LOGS / "collector.log", encoding="utf-8") fh.setFormatter(fmt) sh = logging.StreamHandler(sys.stdout) sh.setFormatter(fmt) log.addHandler(fh) log.addHandler(sh)
def now_iso() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def strip_markup(s: str | None) -> str | None: if not s: return s s = re.sub(r"<[^>]+>", " ", s) s = html.unescape(s) s = re.sub(r"\s+", " ", s).strip() return s
def safe_id(sr: str) -> str: sid = re.sub(r"[^0-9A-Za-z._-]+", "_", sr.strip()) sid = sid.strip("._") or "unknown" if len(sid) > 180: sid = sid[:160] + "_" + hashlib.sha1(sr.encode()).hexdigest()[:10] return sid
def sparql(query: str, timeout: int = SPARQL_TIMEOUT) -> list[dict]: last = None for attempt in range(1, RETRIES + 1): try: data = urllib.parse.urlencode({"query": query}).encode("utf-8") req = urllib.request.Request( SPARQL_ENDPOINT, data=data, headers={ "Accept": "application/sparql-results+json", "Content-Type": "application/x-www-form-urlencoded", "User-Agent": USER_AGENT, }, method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as resp: payload = json.loads(resp.read().decode("utf-8")) rows = [] for b in payload.get("results", {}).get("bindings", []): rows.append({k: v.get("value") for k, v in b.items()}) return rows except Exception as e: last = e wait = min(60, 2 ** attempt) + random.random() log.warning("SPARQL attempt %s failed: %s; sleep %.1fs", attempt, e, wait) time.sleep(wait) raise RuntimeError(f"SPARQL failed after retries: {last}")
def http_get(url: str, timeout: int = HTTP_TIMEOUT) -> tuple[bytes, str, str]: last = None for attempt in range(1, RETRIES + 1): try: req = urllib.request.Request( url, headers={ "User-Agent": USER_AGENT, "Accept": "*/*", "Accept-Encoding": "identity", }, ) with urllib.request.urlopen(req, timeout=timeout) as resp: ctype = resp.headers.get("Content-Type") or "" final = resp.geturl() chunks = [] total = 0 while True: buf = resp.read(256 * 1024) if not buf: break total += len(buf) if total > MAX_BYTES: raise RuntimeError(f"response exceeds {MAX_BYTES} bytes") chunks.append(buf) return b"".join(chunks), ctype, final except Exception as e: last = e wait = min(45, 1.5 ** attempt) + random.random() log.warning("GET %s attempt %s failed: %s; sleep %.1fs", url, attempt, e, wait) time.sleep(wait) raise RuntimeError(f"GET failed {url}: {last}")
class HTMLTextParser(HTMLParser): SKIP = {"script", "style", "noscript", "svg", "head"}
def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: list[str] = [] self.skip = 0 self.seen_lawcontent = False self.in_law = False self.capture_all = False
def handle_starttag(self, tag: str, attrs) -> None: tag = tag.lower() ad = {k.lower(): (v or "") for k, v in attrs} if tag in self.SKIP: self.skip += 1 return if ad.get("id") == "lawcontent": self.seen_lawcontent = True self.in_law = True if tag in {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr", "article", "section", "br", "dt", "blockquote", "pre", "figcaption"}: self.parts.append("\n") elif tag in {"td", "th", "dd"}: self.parts.append("\t")
def handle_endtag(self, tag: str) -> None: tag = tag.lower() if tag in self.SKIP and self.skip: self.skip -= 1 return if tag in {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr", "article", "section"}: self.parts.append("\n") if tag == "div" and self.in_law: # keep capturing nested; parser is not stack-precise for lawcontent end pass
def handle_data(self, data: str) -> None: if self.skip: return if self.seen_lawcontent and not self.in_law and not self.capture_all: return if data and data.strip(): self.parts.append(data) elif data: self.parts.append(" ")
def html_to_text(raw: bytes) -> str: text = raw.decode("utf-8", "replace") p = HTMLTextParser() try: p.feed(text) p.close() except Exception: pass if p.seen_lawcontent and not any(x.strip() for x in p.parts): p = HTMLTextParser() p.capture_all = True p.in_law = True p.feed(text) out = "".join(p.parts) out = re.sub(r"[ \t]+\n", "\n", out) out = re.sub(r"\n{3,}", "\n\n", out) out = re.sub(r"[ \t]{2,}", " ", out) return out.strip()
def localname(tag: str) -> str: if "}" in tag: return tag.rsplit("}", 1)[-1] if tag.startswith("{") is False and ":" in tag: return tag.split(":", 1)[-1] return tag
SKIP_XML = { "meta", "identification", "publication", "lifecycle", "workflow", "analysis", "references", "classification", "proprietary",}
def xml_to_text(raw: bytes) -> str: try: root = ET.fromstring(raw) except ET.ParseError: # try recovering by taking inner well-known start txt = raw.decode("utf-8", "replace") txt = re.sub(r"&(?!#|amp;|lt;|gt;|quot;|apos;)", "&", txt) root = ET.fromstring(txt.encode("utf-8")) parts: list[str] = []
def walk(el: ET.Element, skip_depth: int = 0) -> None: name = localname(el.tag).lower() if name in SKIP_XML: return if name in {"p", "paragraph", "article", "chapter", "section", "book", "title", "subtitle", "formula", "preamble", "preface", "conclusion", "alinea", "list", "point", "recital", "heading", "num", "content"}: parts.append("\n") if el.text and el.text.strip(): parts.append(el.text) elif el.text and "\n" in el.text: parts.append("\n") for child in list(el): walk(child) if child.tail and child.tail.strip(): parts.append(child.tail) elif child.tail and "\n" in child.tail: parts.append("\n")
walk(root) out = " ".join(parts) out = re.sub(r"[ \t]+\n", "\n", out) out = re.sub(r"\n{3,}", "\n\n", out) out = re.sub(r"[ \t]{2,}", " ", out) out = re.sub(r" *\n *", "\n", out) out = out.strip() if len(out) < 40: fallback = [] for el in root.iter(): if el.text and el.text.strip(): fallback.append(el.text.strip()) if el.tail and el.tail.strip(): fallback.append(el.tail.strip()) fb = "\n".join(fallback).strip() if len(fb) > len(out): out = fb return out
def pdf_to_text(raw: bytes, stem: str) -> str: pdf_path = TMP / f"{stem}.pdf" pdf_path.write_bytes(raw) try: r = subprocess.run( ["pdftotext", "-layout", "-enc", "UTF-8", str(pdf_path), "-"], capture_output=True, timeout=120, ) if r.returncode != 0: r = subprocess.run( ["pdftotext", "-enc", "UTF-8", str(pdf_path), "-"], capture_output=True, timeout=120, ) text = r.stdout.decode("utf-8", "replace") return text.strip() finally: try: pdf_path.unlink(missing_ok=True) except Exception: pass
def docx_to_text(raw: bytes) -> str: with zipfile.ZipFile(io.BytesIO(raw)) as zf: xml = zf.read("word/document.xml") root = ET.fromstring(xml) parts: list[str] = [] for el in root.iter(): name = localname(el.tag) if name == "tab": parts.append("\t") elif name == "br": parts.append("\n") elif name == "p": parts.append("\n") if el.text: parts.append(el.text) if el.tail: parts.append(el.tail) out = "".join(parts) out = re.sub(r"\n{3,}", "\n\n", out) return out.strip()
def extract_text(fmt_name: str, raw: bytes, stem: str) -> str: if fmt_name == "xml": return xml_to_text(raw) if fmt_name == "html": return html_to_text(raw) if fmt_name in {"pdf", "pdf-a", "pdf-x"}: return pdf_to_text(raw, stem) if fmt_name == "docx": return docx_to_text(raw) if fmt_name == "doc": raise RuntimeError("doc binary skipped (no converter); use pdf/html/xml)") raise RuntimeError(f"unknown format {fmt_name}")
def load_done() -> set[str]: done: set[str] = set() if not INDEX.exists(): return done with INDEX.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: rec = json.loads(line) except json.JSONDecodeError: continue rid = rec.get("id") st = rec.get("status") if rid and st == "ok": done.add(rid) elif rid and st == "failed": done.discard(rid) # retry failed return done
def append_index(rec: dict) -> None: line = json.dumps(rec, ensure_ascii=False) + "\n" with index_lock: with INDEX.open("a", encoding="utf-8") as f: f.write(line) f.flush() os.fsync(f.fileno())
def append_failed(rec: dict) -> None: line = json.dumps(rec, ensure_ascii=False) + "\n" with fail_lock: with FAILED.open("a", encoding="utf-8") as f: f.write(line)
def write_summary(extra: dict | None = None) -> None: extra = extra or {} with stats_lock: s = dict(STATS) collected_bytes = 0 n_files = 0 if INSTR.exists(): for p in INSTR.glob("*.json"): n_files += 1 try: collected_bytes += p.stat().st_size except OSError: pass listed = s.get("listed") or extra.get("listed") or 0 body = f"""# Switzerland — Classified Compilation (SR / Classified Compilation)
**Retrieved:** {now_iso()} (UTC) / {datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")}**Source:** Fedlex (Federal Chancellery / Swiss Confederation)- Portal: https://www.fedlex.admin.ch/- SPARQL/LINDAS: https://fedlex.data.admin.ch/sparqlendpoint- ELI CC: https://www.fedlex.admin.ch/eli/cc- Legal info: https://www.fedlex.admin.ch/de/legal-information
## ScopeCurrent **in-force** entries of the **Systematische Rechtssammlung (SR)** /**Classified Compilation (CC)**, including domestic federal law andinternational-law texts classified in the SR (chapter 0). HistoricalOfficial Compilation (AS / OC) amending acts are **not** stored as separateinstruments; their effect is already consolidated in the current SR text.
In-force filter: `jolux:inForceStatus` =`https://fedlex.data.admin.ch/vocabulary/enforcement-status/0` ("In force")as of {TODAY}.
## Counts- Listed (in-force SR instruments): **{listed}**- Collected (JSON with non-empty primary text): **{s.get("collected", 0)}**- Failed: **{s.get("failed", 0)}**- Resumed/skipped already-ok: **{s.get("skipped_resume", 0)}**- Empty-text: **{s.get("empty_text", 0)}**- Instrument JSON files on disk: **{n_files}**- Instrument JSON bytes: **{collected_bytes}** ({collected_bytes/1024/1024:.1f} MiB)
## Formats used (primary text){json.dumps(s.get("by_format") or {}, ensure_ascii=False, indent=2)}
## Primary language of stored record{json.dumps(s.get("by_lang_primary") or {}, ensure_ascii=False, indent=2)}
## Record layout- `instruments/{{safe_id}}.json` — one file per SR number- `index.jsonl` — append-only collection log (resume key: `id` + `status=ok`)- German is the primary `text` when available; French/Italian (and RM/EN if present) are listed in `metadata.languages` and stored under `documents` when XML/HTML could be fetched without extra PDF-only downloads.
## Copyright / reuse{LICENSE}
Required reuse notice: {REUSE_NOTICE}
## Collector- Script: `/workspace/legal-corpora/ch/collector.py`- Log: `/workspace/legal-corpora/ch/logs/collector.log`- Started (UTC): {s.get("started_at")}- Workers: {WORKERS}- No git clone; no git commit; streamed to disk.
## Blockers{extra.get("blockers", "None at summary write.")}""" SUMMARY.write_text(body, encoding="utf-8")
def fetch_catalog() -> list[dict]: if CATALOG.exists(): try: data = json.loads(CATALOG.read_text(encoding="utf-8")) if isinstance(data, list) and len(data) >= 5000: with_files = sum(1 for a in data if a.get("files")) if with_files >= 5000: log.info("Loaded cached catalog: %s acts (%s with files)", len(data), with_files) return data log.info("Cached catalog incomplete (%s/%s with files); rebuilding", with_files, len(data)) except Exception as e: log.warning("Catalog cache unreadable: %s", e)
log.info("SPARQL: listing in-force ConsolidationAbstracts + titles") meta_q = f"""PREFIX jolux: <http://data.legilux.public.lu/resource/ontology/jolux#>PREFIX skos: <http://www.w3.org/2004/02/skos/core#>SELECT DISTINCT ?abstract ?sr ?lang ?title ?dateDocument ?dateEntryInForce ?historicalIdWHERE {{ ?abstract a jolux:ConsolidationAbstract ; jolux:inForceStatus <{IN_FORCE}> ; jolux:classifiedByTaxonomyEntry ?tax . ?tax skos:notation ?sr . OPTIONAL {{ ?abstract jolux:dateDocument ?dateDocument }} OPTIONAL {{ ?abstract jolux:dateEntryInForce ?dateEntryInForce }} OPTIONAL {{ ?abstract jolux:historicalLegalId ?historicalId }} ?abstract jolux:isRealizedBy ?expr . ?expr jolux:language ?lang . OPTIONAL {{ ?expr jolux:title ?title }}}}""" meta_rows = sparql(meta_q, timeout=180) log.info("Title rows: %s", len(meta_rows))
acts: dict[str, dict] = {} for row in meta_rows: uri = row.get("abstract") if not uri: continue rec = acts.setdefault( uri, { "abstract": uri, "sr": row.get("sr") or "", "historical_id": row.get("historicalId"), "date_document": row.get("dateDocument"), "date_entry_in_force": row.get("dateEntryInForce"), "titles": {}, "languages": set(), "files": [], "cons": None, "cons_date": None, }, ) lang = URI_LANG.get(row.get("lang") or "", None) if lang: rec["languages"].add(lang) title = strip_markup(row.get("title")) if title: rec["titles"].setdefault(lang, title) if row.get("sr") and not rec["sr"]: rec["sr"] = row["sr"]
log.info("Distinct in-force abstracts from titles: %s", len(acts))
# One SPARQL per (language, format) to stay under Virtuoso result-size caps. fmt_list = [ ("xml", "https://fedlex.data.admin.ch/vocabulary/user-format/xml"), ("html", "https://fedlex.data.admin.ch/vocabulary/user-format/html"), ("pdf-a", "https://fedlex.data.admin.ch/vocabulary/user-format/pdf-a"), ] lang_list = [("de", LANG_URI["de"]), ("fr", LANG_URI["fr"]), ("it", LANG_URI["it"])] url_rows: list[dict] = [] for lang_code, lang_uri in lang_list: for fmt_name, fmt_uri in fmt_list: log.info("SPARQL: latest manifestations lang=%s fmt=%s", lang_code, fmt_name) url_q = f"""PREFIX jolux: <http://data.legilux.public.lu/resource/ontology/jolux#>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>SELECT DISTINCT ?abstract ?cons ?date ?urlWHERE {{ ?abstract a jolux:ConsolidationAbstract ; jolux:inForceStatus <{IN_FORCE}> . ?cons jolux:isMemberOf ?abstract ; jolux:dateApplicability ?date ; jolux:isRealizedBy ?expr . FILTER(?date <= xsd:date("{TODAY}")) FILTER NOT EXISTS {{ ?c2 jolux:isMemberOf ?abstract ; jolux:dateApplicability ?d2 . FILTER(?d2 <= xsd:date("{TODAY}") && ?d2 > ?date) ?c2 jolux:isRealizedBy ?e2 . ?e2 jolux:isEmbodiedBy ?m2 . ?m2 jolux:isExemplifiedBy ?x . }} ?expr jolux:language <{lang_uri}> ; jolux:isEmbodiedBy ?manif . ?manif jolux:userFormat <{fmt_uri}> ; jolux:isExemplifiedBy ?url .}}""" rows = sparql(url_q, timeout=180) log.info(" %s/%s -> %s rows", lang_code, fmt_name, len(rows)) for row in rows: row["lang"] = lang_uri row["fmt"] = fmt_uri url_rows.extend(rows)
log.info("Total manifestation rows: %s", len(url_rows)) seen_files = set() for row in url_rows: uri = row.get("abstract") if not uri: continue if uri not in acts: acts[uri] = { "abstract": uri, "sr": "", "historical_id": None, "date_document": None, "date_entry_in_force": None, "titles": {}, "languages": set(), "files": [], "cons": None, "cons_date": None, } rec = acts[uri] rec["cons"] = row.get("cons") rec["cons_date"] = row.get("date") lang = URI_LANG.get(row.get("lang") or "", None) fmt = row.get("fmt") url = row.get("url") if not (lang and fmt and url): continue key = (uri, lang, fmt, url) if key in seen_files: continue seen_files.add(key) rec["languages"].add(lang) rec["files"].append({"lang": lang, "fmt": fmt, "url": url, "rank": FMT_RANK.get(fmt, 99)})
catalog = [] n_with = 0 for rec in acts.values(): rec["languages"] = sorted(rec["languages"]) rec["files"].sort(key=lambda x: (x["lang"], x["rank"], x["url"])) if rec["files"]: n_with += 1 catalog.append(rec) catalog.sort(key=lambda r: tuple(int(p) if p.isdigit() else p for p in re.split(r"(\d+)", r["sr"] or ""))) CATALOG.write_text(json.dumps(catalog, ensure_ascii=False), encoding="utf-8") log.info("Wrote catalog %s (%s acts, %s with files)", CATALOG, len(catalog), n_with) return catalog
def pick_files(files: list[dict], lang: str, allow_pdf: bool) -> tuple[str | None, list[str]]: ranked: dict[int, list[str]] = {} for f in files: if f["lang"] != lang: continue rank = f.get("rank", 99) if rank > 6: continue name = FMT_NAME.get(f["fmt"]) if name is None: continue if not allow_pdf and name in {"pdf", "pdf-a", "pdf-x", "doc"}: continue ranked.setdefault(rank, []).append(f["url"]) if not ranked: return None, [] best = min(ranked) fmt_uri = None for uri, r in FMT_RANK.items(): if r == best: fmt_uri = uri break return FMT_NAME.get(fmt_uri or "", None), sorted(set(ranked[best]))
def sniff_format(claimed: str, raw: bytes, ctype: str) -> str: head = raw[:8] cl = (ctype or "").lower() if head.startswith(b"%PDF"): return "pdf" if head.startswith(b"PK"): return "docx" if head.lstrip().startswith(b"<?xml") or head.lstrip().startswith(b"<akn") or head.lstrip().startswith(b"<AKN"): return "xml" if b"<html" in raw[:4000].lower() or "html" in cl: if claimed in {"html", "xml"}: return "html" if claimed == "html" or b"<html" in raw[:4000].lower() else claimed if "pdf" in cl: return "pdf" return claimed
def formats_for_lang(files: list[dict], lang: str, allow_pdf: bool) -> list[tuple[str, list[str]]]: """Return (fmt_name, urls) groups in rank order so empty XML can fall through to PDF.""" grouped: dict[int, list[str]] = {} rank_name: dict[int, str] = {} for f in files: if f["lang"] != lang: continue rank = f.get("rank", 99) name = FMT_NAME.get(f["fmt"]) if name is None: continue if not allow_pdf and name in {"pdf", "pdf-a", "pdf-x", "doc"}: continue rank_name[rank] = name grouped.setdefault(rank, []) if f["url"] not in grouped[rank]: grouped[rank].append(f["url"]) out = [] for rank in sorted(grouped): out.append((rank_name[rank], grouped[rank])) return out
def fetch_lang_text(act: dict, lang: str, allow_pdf: bool) -> dict | None: sid = safe_id(act["sr"]) groups = formats_for_lang(act.get("files") or [], lang, allow_pdf=allow_pdf) if not groups: return None last_err = None for fmt, urls in groups: texts = [] used = [] used_fmt = fmt for i, url in enumerate(urls): try: raw, ctype, final = http_get(url) except Exception as e: last_err = e log.warning("GET %s %s %s failed: %s", act["sr"], lang, url, e) continue actual = sniff_format(fmt, raw, ctype) stem = f"{sid}_{lang}_{actual}_{i}" try: t = extract_text(actual, raw, stem) except Exception as e: last_err = e log.warning("extract %s %s %s failed: %s", act["sr"], lang, actual, e) continue if t and t.strip(): texts.append(t.strip()) used.append(final or url) used_fmt = actual if texts: title = act.get("titles", {}).get(lang) or act.get("titles", {}).get("de") or f"SR {act['sr']}" return { "id": f"{act['sr']}-{lang}", "title": title, "text": "\n\n".join(texts), "source_url": used[0], "metadata": { "language": lang, "format": used_fmt, "source_urls": used, "consolidation": act.get("cons"), "consolidation_date": act.get("cons_date"), "parts": len(used), }, } log.info("empty extract %s lang=%s fmt=%s; trying next format", act["sr"], lang, fmt) if last_err: log.warning("all formats empty for %s lang=%s last_err=%s", act["sr"], lang, last_err) return None
def build_record(act: dict) -> dict: langs_avail = act.get("languages") or [] documents = [] # German first; empty XML/HTML falls through to PDF inside fetch_lang_text de_doc = fetch_lang_text(act, "de", allow_pdf=True) if de_doc: documents.append(de_doc) # Other langs: XML/HTML first, then PDF if those are empty for lang in ("fr", "it", "rm", "en"): if lang not in langs_avail: continue allow_pdf = True try: doc = fetch_lang_text(act, lang, allow_pdf=allow_pdf) except Exception as e: log.warning("lang %s for %s failed: %s", lang, act["sr"], e) doc = None if doc: documents.append(doc)
primary = None primary_lang = None for lang in ("de", "fr", "it", "rm", "en"): for d in documents: if d["metadata"]["language"] == lang: primary = d primary_lang = lang break if primary: break
if not primary or not (primary.get("text") or "").strip(): raise RuntimeError("no extractable text in de/fr/it")
eli_data = act["abstract"] eli_www = eli_data.replace("https://fedlex.data.admin.ch/", "https://www.fedlex.admin.ch/") title = ( act.get("titles", {}).get("de") or act.get("titles", {}).get(primary_lang) or f"SR {act['sr']}" ) date_issued = None dd = act.get("date_document") if dd: date_issued = str(dd)[:10]
rec = { "schema_version": "collection_record.v1", "record_type": "law", "id": act["sr"], "title": title, "jurisdiction": "CH", "country": "Switzerland", "language": primary_lang, "source_type": "fedlex", "source_url": eli_www, "eli": eli_data, "date": date_issued, "date_issued": date_issued, "retrieved_at": now_iso(), "identifier": act["sr"], "official_identifier": act["sr"], "law_identifier": act["sr"], "law_status": "current", "is_current": True, "license": "unknown", "text": primary["text"], "documents": documents, "metadata": { "license": LICENSE, "retrieved_at": now_iso(), "official_id": act["sr"], "publisher": "Fedlex / Swiss Confederation", "source_name": "fedlex.admin.ch", "languages": langs_avail, "historical_legal_id": act.get("historical_id"), "date_entry_in_force": (str(act["date_entry_in_force"])[:10] if act.get("date_entry_in_force") else None), "consolidation_date": act.get("cons_date"), "consolidation_eli": act.get("cons"), "reuse_notice": REUSE_NOTICE, "copyright_basis": "URG Art. 5; PublV Art. 48–49", "in_force_status": IN_FORCE, "primary_format": primary["metadata"].get("format"), }, } return rec
def process_act(act: dict) -> tuple[str, str, int, str | None]: sr = act.get("sr") or "unknown" sid = safe_id(sr) path = INSTR / f"{sid}.json" rec = build_record(act) tmp = path.with_suffix(".json.tmp") data = json.dumps(rec, ensure_ascii=False, indent=2).encode("utf-8") tmp.write_bytes(data) tmp.replace(path) fmt = rec["metadata"].get("primary_format") or "?" lang = rec.get("language") or "?" return sid, fmt, len(data), lang
def main() -> int: setup_logging() STATS["started_at"] = now_iso() log.info("START collector Swiss SR/CC") catalog = fetch_catalog() STATS["listed"] = len(catalog) done = load_done() log.info("Catalog %s acts; already ok in index: %s", len(catalog), len(done)) pending = [a for a in catalog if a.get("sr") and safe_id(a["sr"]) not in done and a["sr"] not in done] # resume uses safe_id and raw sr pending = [] for a in catalog: sr = a.get("sr") or "" sid = safe_id(sr) if sid in done or sr in done: STATS["skipped_resume"] += 1 continue pending.append(a) log.info("Pending: %s", len(pending)) write_summary()
def worker(act: dict) -> None: sr = act.get("sr") or "unknown" sid = safe_id(sr) try: time.sleep(random.uniform(0.0, 0.15)) sid, fmt, nbytes, lang = process_act(act) append_index({ "id": sr, "safe_id": sid, "file": f"instruments/{sid}.json", "status": "ok", "bytes": nbytes, "format": fmt, "language": lang, "retrieved_at": now_iso(), }) with stats_lock: STATS["collected"] += 1 STATS["bytes"] += nbytes STATS["by_format"][fmt] = STATS["by_format"].get(fmt, 0) + 1 STATS["by_lang_primary"][lang] = STATS["by_lang_primary"].get(lang, 0) + 1 n = STATS["collected"] + STATS["failed"] if n % 25 == 0: log.info("progress collected=%s failed=%s last=%s %s bytes=%s", STATS["collected"], STATS["failed"], sr, fmt, nbytes) if n % 100 == 0: write_summary() except Exception as e: log.error("FAIL %s: %s", sr, e) append_index({ "id": sr, "safe_id": sid, "status": "failed", "error": str(e)[:500], "retrieved_at": now_iso(), }) append_failed({"id": sr, "error": str(e)[:1000], "trace": traceback.format_exc()[-2000:]}) with stats_lock: STATS["failed"] += 1 if "no extractable text" in str(e): STATS["empty_text"] += 1
with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as ex: futs = [ex.submit(worker, a) for a in pending] concurrent.futures.wait(futs)
write_summary({"listed": len(catalog), "blockers": "See logs/failed.jsonl for per-act errors."}) log.info("DONE listed=%s collected=%s failed=%s bytes=%s", STATS["listed"], STATS["collected"], STATS["failed"], STATS["bytes"]) return 0 if STATS["failed"] == 0 else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573#!/usr/bin/env python3"""Shared helpers for national legislation collectors."""from __future__ import annotations# Harvested collector path injection. Do not collect from /workspace.import os as _ipfs_osfrom pathlib import Path as _ipfs_Path_CORPORA = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_CORPORA_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_corpora")))_SCRAPERS = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_COLLECTORS_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_collectors"))) / "shared"_HF_TOKEN_PATH = _ipfs_Path(_ipfs_os.environ.get("HF_TOKEN_PATH", str(_ipfs_Path.home() / ".cache" / "huggingface" / "token")))
import hashlibimport htmlimport jsonimport osimport reimport tempfileimport threadingimport timeimport tracebackfrom collections import Counterfrom datetime import datetime, timezone, timedeltafrom html.parser import HTMLParserfrom pathlib import Pathfrom typing import Any, Iterable, Optionalfrom xml.etree import ElementTree as ET
import requestsfrom requests.adapters import HTTPAdapter
ROOT = _CORPORASCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"PT = timezone(timedelta(hours=-7))DEFAULT_UA = ( "legal-corpora-collector/1.0 " "(research archive of official national gazettes; polite; " "no commercial scraping; contact via local operator)")INDEX_FIELDS = ( "id", "path", "title", "identifier", "eli", "source_url", "source_type", "jurisdiction", "language", "law_status", "date", "retrieved_at", "article_count", "bytes",)
_tls = threading.local()_index_lock = threading.Lock()_fail_lock = threading.Lock()_schema = None_schema_lock = threading.Lock()
def utcnow() -> str: return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def pt_from_iso(iso: str) -> str: try: dt = datetime.fromisoformat(iso.replace("Z", "+00:00")) except Exception: return iso return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
def localtag(tag: str) -> str: return tag.rsplit("}", 1)[-1]
def slug_id(cc: str, official: str) -> str: s = (official or "").strip() s = s.replace("https://", "").replace("http://", "") s = re.sub(r"[/\\]+", "__", s) s = re.sub(r"\s+", "_", s) s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s) s = s.strip("-._") if not s: s = "unknown" s = s.lower() if not s.startswith(cc.lower() + "-"): s = f"{cc.lower()}-{s}" if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789": s = "x" + s return s[:180]
def atomic_write(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp") try: with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(text) os.replace(tmp, path) except Exception: try: os.unlink(tmp) except OSError: pass raise
def sha256_text(s: str) -> str: return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session: s = getattr(_tls, "session", None) if s is None or getattr(_tls, "ua", None) != ua: s = requests.Session() s.headers.update({ "User-Agent": ua, "Accept": "application/json, application/xml, text/xml, text/html, */*", "Accept-Language": "en,*;q=0.8", }) ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0) s.mount("https://", ad) s.mount("http://", ad) _tls.session = s _tls.ua = ua return s
def http_get( url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), retries: int = 5, sleep: float = 0.35, headers: Optional[dict] = None, params: Optional[dict] = None, allow_empty: bool = False,) -> requests.Response: last = None hdrs = headers or {} for attempt in range(1, retries + 1): try: if sleep: time.sleep(sleep) resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params) if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries: time.sleep(min(30, 2 ** attempt)) last = resp continue if resp.status_code == 200 and (allow_empty or resp.content): return resp if resp.status_code in (404, 410, 403, 401): return resp last = resp if attempt < retries: time.sleep(min(20, 1.5 * attempt)) continue return resp except requests.RequestException as exc: last = exc time.sleep(min(20, 1.5 * attempt)) if isinstance(last, requests.Response): return last raise RuntimeError(f"GET failed {url}: {last}")
class _HTMLText(HTMLParser): SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: list[str] = [] self.skip = 0 self._block = { "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6", "article", "section", "blockquote", "pre", "td", "th", "dt", "dd", }
def handle_starttag(self, tag, attrs): if tag in self.SKIP: self.skip += 1 if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0: self.parts.append("\n")
def handle_endtag(self, tag): if tag in self.SKIP and self.skip: self.skip -= 1 if tag in self._block and self.skip == 0: self.parts.append("\n")
def handle_data(self, data): if self.skip == 0: self.parts.append(data)
def html_to_text(raw: str) -> str: if not raw: return "" p = _HTMLText() try: p.feed(raw) p.close() except Exception: raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw) raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw) raw = re.sub(r"(?is)<[^>]+>", " ", raw) return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip() text = "".join(p.parts) text = html.unescape(text) text = text.replace("\xa0", " ") text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n[ \t]+", "\n", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip()
def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str: skip_tags = skip_tags or { "meta", "identification", "references", "classification", "workflow", "analysis", "proprietary", "presentation", } try: root = ET.fromstring(raw) except ET.ParseError: return html_to_text(raw) parts: list[str] = []
def walk(el: ET.Element) -> None: tag = localtag(el.tag).lower() if tag in skip_tags: return if el.text and el.text.strip(): parts.append(el.text.strip()) for child in list(el): walk(child) if child.tail and child.tail.strip(): parts.append(child.tail.strip()) if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}: parts.append("\n")
walk(root) text = " ".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r" *\n *", "\n", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip()
ARTICLE_SPLIT = re.compile( r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|" r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|" r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+" r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b")
def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]: if not text or len(text) < 40: return [] matches = list(ARTICLE_SPLIT.finditer(text)) if len(matches) < 2: return [] docs = [] for i, m in enumerate(matches): start = m.start() end = matches[i + 1].start() if i + 1 < len(matches) else len(text) chunk = text[start:end].strip() num = re.sub(r"\s+", " ", m.group(1)).strip() aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-") heading = chunk.split("\n", 1)[0][:200] docs.append({ "id": f"{law_id}-{aid}"[:180], "title": heading, "text": chunk, "date_filed": date, "document_number": num, "source_url": source_url, "record_type": "article", "article_number": num, "law_identifier": law_id, "metadata": {"text_extraction": {"source": "official", "backend": "collector"}}, }) if len(docs) >= 4000: break return docs
def load_schema(): global _schema with _schema_lock: if _schema is None: with SCHEMA_PATH.open(encoding="utf-8") as f: _schema = json.load(f) return _schema
def validate_record(record: dict) -> Optional[str]: try: import jsonschema jsonschema.Draft202012Validator(load_schema()).validate(record) return None except Exception as exc: return str(exc)
def existing_ids(cc: str) -> set[str]: d = ROOT / cc / "instruments" if not d.exists(): return set() return {p.stem for p in d.glob("*.json")}
def _quality_reject(cc: str, record: dict): """env-gated quality filter (QUALITY_FILTER=1; module via QUALITY_FILTER_MODULE, default tip+29q). Fail-open on errors.""" if os.environ.get("QUALITY_FILTER") != "1": return None try: import sys as _sys _lp = "{_SCRAPERS.parent}/logs" if _lp not in _sys.path: _sys.path.append(_lp) import importlib as _il _qf = _il.import_module(os.environ.get("QUALITY_FILTER_MODULE", "quality_filter_tip30a")) return _qf.classify_new(cc, record, None) # classify + exact-duplicate vs tip+29p LIVE baseline except Exception: return None
# tip+29t WRITE-ONCE SAFETY: a closer must NEVER overwrite/modify an existing instrument file (baseline text or title).# Active for the tip-pipeline CCs always (and for any CC when WRITE_ONCE=1). If the target exists, the record is written# under a NEW unique id (<id>-wN) instead; the quality filter then judges the new row (dup_url/dup_content -> quarantine)._WRITE_ONCE_CCS = {"bo", "az", "al", "ao", "do", "et", "ir", "mw", "zm", "la", "lk", "tn", "rs"}_WRITE_ONCE_LOG = "{_SCRAPERS.parent}/logs/write_once_guard.log"
def _write_once_ident(cc: str, ident: str) -> str: if cc not in _WRITE_ONCE_CCS and os.environ.get("WRITE_ONCE") != "1": return ident idir = ROOT / cc / "instruments" if not (idir / f"{ident}.json").exists(): return ident n = 2 while (idir / f"{ident}-w{n}.json").exists(): n += 1 new_ident = f"{ident}-w{n}" try: with open(_WRITE_ONCE_LOG, "a", encoding="utf-8") as _fh: _fh.write(json.dumps({"ts": utcnow(), "cc": cc, "refused_overwrite": ident, "written_as": new_ident, "argv": " ".join(__import__("sys").argv)[:200]}, ensure_ascii=False) + "\n") except Exception: pass return new_ident
def write_instrument(cc: str, record: dict) -> Path: ident = _write_once_ident(cc, record["id"]) if ident != record["id"]: record = dict(record, id=ident) dest = ROOT / cc / "instruments" / f"{ident}.json" if dest.exists(): # hard guard (race): never overwrite return dest _qr = _quality_reject(cc, record) if _qr and not dest.exists(): qdest = ROOT / cc / os.environ.get("QUALITY_QDIR", "quarantine_quality_tip29q") / f"{ident}.json" qdest.parent.mkdir(parents=True, exist_ok=True) atomic_write(qdest, json.dumps(record, ensure_ascii=False, indent=2) + "\n") try: with open(os.environ.get("QUALITY_REJECT_LOG", "{_SCRAPERS.parent}/logs/quality_reject_tip29q.log"), "a", encoding="utf-8") as _fh: _fh.write(json.dumps({"cc": cc, "id": ident, "reason": _qr, "url": record.get("source_url")}, ensure_ascii=False) + "\n") except Exception: pass return qdest if _qr: return dest dest.parent.mkdir(parents=True, exist_ok=True) body = json.dumps(record, ensure_ascii=False, indent=2) + "\n" atomic_write(dest, body) index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"} index_line["path"] = f"instruments/{ident}.json" index_line["article_count"] = record.get("article_count") or len(record.get("documents") or []) index_line["bytes"] = dest.stat().st_size index_line["id"] = ident with _index_lock: with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle: handle.write(json.dumps(index_line, ensure_ascii=False) + "\n") return dest
def log_failure(cc: str, payload: dict) -> None: path = ROOT / cc / "failures.jsonl" path.parent.mkdir(parents=True, exist_ok=True) payload = dict(payload) payload.setdefault("retrieved_at", utcnow()) with _fail_lock: with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
def append_catalog(cc: str, row: dict) -> None: path = ROOT / cc / "raw" / "catalog.jsonl" path.parent.mkdir(parents=True, exist_ok=True) with _index_lock: with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(row, ensure_ascii=False) + "\n")
def law_status_hist(cc: str) -> Counter: c: Counter = Counter() d = ROOT / cc / "instruments" if not d.exists(): return c for p in d.glob("*.json"): try: rec = json.loads(p.read_text(encoding="utf-8")) c[rec.get("law_status") or "unknown"] += 1 except Exception: c["unknown"] += 1 return c
def corpus_bytes(cc: str) -> int: d = ROOT / cc / "instruments" if not d.exists(): return 0 return sum(p.stat().st_size for p in d.glob("*.json"))
def count_jsonl(path: Path) -> int: if not path.exists(): return 0 n = 0 with path.open(encoding="utf-8") as f: for _ in f: n += 1 return n
def write_summary( cc: str, *, country: str, source: str, source_urls: Iterable[str], license_text: str, discovered: int, fetched: int, skipped: int, failed: int, coverage: str, notes: str, last_run: Optional[str] = None, extra: Optional[str] = None,) -> None: last_run = last_run or utcnow() instr = ROOT / cc / "instruments" n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0 n_index = count_jsonl(ROOT / cc / "index.jsonl") hist = law_status_hist(cc) nbytes = corpus_bytes(cc) lines = [ f"# {country} legislation corpus", "", f"- jurisdiction: {cc.upper()}", f"- source: {source}", f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})", f"- instruments_json: {n_json}", f"- index_jsonl_lines: {n_index}", f"- discovered: {discovered}", f"- fetched: {fetched}", f"- skipped: {skipped}", f"- failed: {failed}", "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)", f"- coverage: {coverage}", f"- total_json_bytes: {nbytes}", f"- license: {license_text}", "- source_urls:", ] for u in source_urls: lines.append(f" - {u}") lines.append("- notes:") for n in (notes or "").splitlines(): lines.append(f" {n}") if extra: lines.append("") lines.append(extra) lines.append("") atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
def base_record( *, cc: str, country: str, language: str, ident: str, title: str, text: str, source_url: str, source_type: str, license_text: str, collector: str, eli: Optional[str] = None, date: Optional[str] = None, official_identifier: Optional[str] = None, document_type: str = "statute", law_status: str = "current", is_current: Optional[bool] = True, documents: Optional[list] = None, extra_meta: Optional[dict] = None, extra_fields: Optional[dict] = None,) -> dict: rid = slug_id(cc, ident) docs = documents if documents is not None else split_articles(text, rid, source_url, date) rec = { "schema_version": "collection_record.v1", "record_type": "law", "id": rid, "title": title or ident, "text": text or "", "source_url": source_url, "source_type": source_type, "date": date, "jurisdiction": cc.upper(), "country": country, "language": language, "eli": eli, "license": license_text, "retrieved_at": utcnow(), "identifier": official_identifier or ident, "official_identifier": official_identifier or ident, "law_identifier": official_identifier or ident, "document_type": document_type, "law_status": law_status, "is_current": is_current, "canonical_law_url": source_url, "article_count": len(docs), "article_extraction_status": "ok" if docs else "missing", "documents": docs, "metadata": { "collector": collector, "schema": "collection_record.v1", "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "", "content_sha256": sha256_text(text or ""), "rights": { "not_legal_advice": True, "official_reuse_url": source_url, "license": license_text, }, "text_extraction": {"source": "official", "backend": "collector"}, }, } if extra_meta: rec["metadata"].update(extra_meta) if extra_fields: rec.update(extra_fields) return rec
def ensure_dirs(cc: str) -> Path: root = ROOT / cc (root / "instruments").mkdir(parents=True, exist_ok=True) (root / "raw").mkdir(parents=True, exist_ok=True) (root / "logs").mkdir(parents=True, exist_ok=True) return root
def iso_date(val: Optional[str]) -> Optional[str]: if not val: return None val = str(val).strip() m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val) if m: return f"{m.group(1)}-{m.group(2)}-{m.group(3)}" m = re.match(r"^(\d{4}-\d{2}-\d{2})", val) if m: return m.group(1) m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val) if m: return f"{m.group(3)}-{m.group(2)}-{m.group(1)}" return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336#!/usr/bin/env python3"""PDF text extraction helpers mirroring ipfs_datasets_py IntegratedPDFProcessor.
Prefer pdfplumber -> pymupdf -> pdftotext; OCR (tesseract) only when text layeris missing or garbage. Honest article splits require >=2 heading matches."""from __future__ import annotations
import ioimport loggingimport reimport subprocessimport tempfilefrom typing import Optional
log = logging.getLogger("pdf_extract_lib")
# Spaced-out OCR garbage like "D IA R IO"_GARBAGE_SPACING = re.compile(r"(?:^[A-Za-z]\s+){6,}", re.M)
def is_garbage_text(text: str) -> bool: if not text or len(text) < 40: return True if text.lstrip().startswith("%PDF") or "endobj" in text[:200]: return True if "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]: return True sample = text[:8000] # Broken ToUnicode / CID font dumps from Arabic/Persian PDFs if sample.count("(cid:") >= 8: return True arabic = sum(1 for ch in sample if "\u0600" <= ch <= "\u06FF") ctrl = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t\x0c") n = max(1, len(sample)) # Encoding-corrupt Arabic/Persian PDFs: many controls / almost no Arabic script if len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05: return True if len(sample) > 800 and arabic < 80 and sample.count("@") > 30: return True letters = sum(ch.isalpha() for ch in sample) spaces = sample.count(" ") if letters < 80 and arabic < 40: return True # Mojibake Latin stand-in for Arabic (common in old MoJ PDFs) ascii_letters = sum(ch.isalpha() and ord(ch) < 128 for ch in sample) if len(sample) > 500 and arabic < 20 and ascii_letters > 400: return True if spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample): return True singles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample)) if singles > 30 and singles > letters * 0.15: return True return False
def extract_pdfplumber(raw: bytes, max_pages: int = 200) -> tuple[str, int]: import pdfplumber with pdfplumber.open(io.BytesIO(raw)) as pdf: n = len(pdf.pages) parts = [] for page in pdf.pages[:max_pages]: try: parts.append(page.extract_text() or "") except Exception: continue text = "\n".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text).strip() return text, n
def extract_pymupdf(raw: bytes, max_pages: int = 200) -> tuple[str, int]: import pymupdf doc = pymupdf.open(stream=raw, filetype="pdf") n = doc.page_count parts = [page.get_text() for page in doc[:max_pages]] text = "\n".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text).strip() return text, n
def extract_pdftotext(raw: bytes) -> str: if not raw or raw[:4] != b"%PDF": return "" try: with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp: tmp.write(raw) tmp.flush() proc = subprocess.run( ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"], check=False, capture_output=True, timeout=180, ) if proc.returncode == 0 and proc.stdout: return proc.stdout.decode("utf-8", "replace").strip() except Exception as exc: log.warning("pdftotext: %s", exc) return ""
def extract_ocr(raw: bytes, lang: str = "eng", max_pages: int = 40, dpi: int = 120) -> tuple[str, int]: """Render pages with pymupdf and OCR via tesseract CLI.""" import pymupdf doc = pymupdf.open(stream=raw, filetype="pdf") n = doc.page_count parts = [] mat = pymupdf.Matrix(dpi / 72, dpi / 72) for i, page in enumerate(doc): if i >= max_pages: break pix = page.get_pixmap(matrix=mat, alpha=False) with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as img: pix.save(img.name) img_path = img.name try: env = dict(**__import__("os").environ) env["OMP_THREAD_LIMIT"] = "1" env["TESSDATA_PREFIX"] = env.get("TESSDATA_PREFIX", "/usr/share/tesseract-ocr/5/tessdata") proc = subprocess.run( ["tesseract", img_path, "stdout", "-l", lang, "--psm", "6"], capture_output=True, text=True, timeout=180, env=env, ) if proc.returncode == 0 and proc.stdout: parts.append(proc.stdout) except Exception as exc: log.debug("ocr page %s: %s", i, exc) finally: try: import os os.unlink(img_path) except Exception: pass text = "\n".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text).strip() return text, n
def extract_pdf_text( raw: bytes, *, enable_ocr: bool = True, ocr_lang: str = "eng", ocr_max_pages: int = 40,) -> tuple[str, str, int]: """Return (text, method, page_count). Mirrors IntegratedPDFProcessor order.""" if not raw: return "", "not_pdf", 0 if raw[:4] != b"%PDF": idx = raw.find(b"%PDF", 0, 65536) if idx < 0: return "", "not_pdf", 0 raw = raw[idx:] best_text, best_method, pages = "", "failed", 0 for name, fn in ( ("pdfplumber", lambda: extract_pdfplumber(raw)), ("pymupdf", lambda: extract_pymupdf(raw)), ): try: text, pages = fn() if text and not is_garbage_text(text) and len(text) >= 80: return text, name, pages if len(text) > len(best_text): best_text, best_method = text, name except Exception as exc: log.debug("%s failed: %s", name, exc) try: text = extract_pdftotext(raw) if text and not is_garbage_text(text) and len(text) >= 80: return text, "pdftotext", pages if len(text) > len(best_text): best_text, best_method = text, "pdftotext" except Exception: pass if enable_ocr and (is_garbage_text(best_text) or len(best_text) < 120): try: text, pages = extract_ocr(raw, lang=ocr_lang, max_pages=ocr_max_pages) if text and len(text) >= 80 and not is_garbage_text(text): return text, "ocr_tesseract", pages if len(text) > len(best_text): best_text, best_method = text, "ocr_tesseract" except Exception as exc: log.debug("ocr failed: %s", exc) return best_text, best_method if best_text else "failed", pages
def normalize_bidi(text: str) -> str: return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200c\u200d\ufeff]", "", text or "")
_EASTERN_DIGITS = str.maketrans( "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669" "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9", "01234567890123456789",)
def normalize_rtl_text(text: str) -> str: """Strip bidi marks and map Arabic/Persian digits to ASCII for heading regexes.""" t = normalize_bidi(text or "") t = re.sub(r"[\u00ad\u200b]", "", t) return t.translate(_EASTERN_DIGITS)
def split_by_pattern( text: str, law_id: str, source_url: str, pat: re.Pattern, record_type: str = "article", min_chunk: int = 40, max_docs: int = 4000,) -> list[dict]: matches = list(pat.finditer(text or "")) if len(matches) < 2: return [] docs = [] for i, m in enumerate(matches): start = m.start() end = matches[i + 1].start() if i + 1 < len(matches) else len(text) chunk = text[start:end].strip() if len(chunk) < min_chunk: continue num = re.sub(r"\s+", " ", m.group(1)).strip() aid = re.sub(r"[^\w\u0600-\u06FF\u1200-\u137F]+", "-", num.lower(), flags=re.U).strip("-")[:80] heading = chunk.split("\n", 1)[0][:200] docs.append({ "id": f"{law_id}-{aid}"[:180], "title": heading, "text": chunk, "date_filed": None, "document_number": num, "source_url": source_url, "record_type": record_type, "article_number": num, "law_identifier": law_id, "metadata": { "text_extraction": { "source": "official", "backend": "honest_heading_split", "parser": "ipfs_datasets_py.IntegratedPDFProcessor+heading_split", "pattern": pat.pattern[:100], } }, }) if len(docs) >= max_docs: break return docs if len(docs) >= 2 else []
# Country-specific honest patterns (tried in order)COUNTRY_PATTERNS: dict[str, list[tuple[str, re.Pattern, str]]] = { "sv": [ ("articulo", re.compile(r"(?im)^\s*((?:Art(?:[íi]culo|\.)?|ART[IÍ]CULO)\s+\d+[º°a-z.]*)"), "article"), ], "tn": [ ("fasl", re.compile(r"(?m)^\s*((?:الفصل|المادة)\s+\S+)"), "article"), ("article", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"), ], "et": [ ("article_heading", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+\.?)\s*(?:[.\-–—:]|\s+[A-Z\"“])"), "article"), ("article_loose", re.compile(r"(?im)^\s*((?:Article|Art\.)\s+\d+)"), "article"), ("article_inline", re.compile(r"(?im)((?:Article|Art\.)\s+\d+)(?![\d])"), "article"), ("anqets", re.compile(r"(?m)^\s*((?:አንቀጽ|አንቀፅ)\s*[/\.]?\s*\d+)"), "article"), ("anqets_inline", re.compile(r"(?m)((?:አንቀጽ|አንቀፅ)\s*[/.]?\s*\d+)"), "article"), ], "jm": [ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?\.?)"), "section"), ("part", re.compile(r"(?im)^\s*((?:PART|Part)\s+[IVXLC\d]+)"), "section"), ], "fj": [ ("numbered_emdash", re.compile(r"(?m)^\s*((?:\d+)\.—)"), "article"), ("section", re.compile(r"(?im)^\s*((?:Section|SECTION|Article|ARTICLE)\s+\d+)"), "article"), ("chapter", re.compile(r"(?im)^\s*((?:CHAPTER|Chapter)\s+\d+)"), "section"), ], "la": [ ("article", re.compile(r"(?im)^\s*((?:Article|Art\.|ມາດຕາ)\s*\d+)"), "article"), ], "lk": [ ("section", re.compile(r"(?im)^\s*((?:Section|SECTION)\s+\d+[A-Za-z]?)"), "section"), ("article", re.compile(r"(?im)^\s*((?:Article|ARTICLE)\s+\d+)"), "article"), ], "md": [ ("articolul", re.compile(r"(?im)^\s*((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)"), "article"), ("articolul_inline", re.compile(r"(?im)((?:Articolul|Art\.)\s*\d+(?:\^[0-9]+)?)\s*[.\-–—:]"), "article"), ], "iq": [ ("mada", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:]*\s*\d+)(?!\d)"), "article"), ("mada_ocr", re.compile(r"(?m)^\s*((?:المادة|مادة)\s*[-–—:\s]*\d+)(?!\d)"), "article"), ("fasl", re.compile(r"(?m)^\s*((?:الفصل|الباب)\s+\S+)"), "section"), ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"), ], "af": [ ("mada_mid", re.compile( r"(?im)((?:Article|Art\.?|المادة|ماد[هۀٔة]|مادة)\s*[-–—:..]?\s*" r"(?:واحده|\(?\s*[0-9۰-۹٠-٩]{1,4}\s*\)?|" r"اولی?|اوله|دوم|دوهمه?|سومم?|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|" r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم))" ), "article"), ("mada_line", re.compile( r"(?im)^\s*((?:Article|Art\.?|المادة|ماد[هۀٔة]|مادة)\s*[0-9۰-۹٠-٩]+)" ), "article"), ], "ir": [ ("mada", re.compile(r"(?m)^\s*((?:ماده)\s*(?:واحده|\d+))(?!\d)"), "article"), ("mada_prefixed", re.compile( r"(?m)^\s*(?:\d+[\-–—ـ.)\]]*\s*)?((?:ماده)\s*(?:واحده|\d+))(?!\d)" ), "article"), ("fasl_bab", re.compile( r"(?m)^\s*((?:فصل|باب)\s*(?:اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|\d+))" ), "section"), ("article_en", re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+\d+)(?!\d)"), "article"), ], "mz": [ ("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"), ],}
def honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]: if cc in ("tn", "iq", "ir", "af", "dz", "lb", "ma", "eg", "sa", "ae"): text_n = normalize_rtl_text(text) else: text_n = text for name, pat, rtype in COUNTRY_PATTERNS.get(cc, []): docs = split_by_pattern(text_n, law_id, source_url, pat, rtype) if docs: return docs, name # shared fallback from common import split_articles docs = split_articles(text_n, law_id, source_url) if len(docs) >= 2: return docs, "common_article_split" return [], "none"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447#!/usr/bin/env python3"""Shared helpers for new-country official gazette collectors."""from __future__ import annotations
import loggingimport osimport reimport timeimport subprocessimport sysimport tempfilefrom pathlib import Pathfrom typing import Optionalfrom urllib.parse import urljoin, urlparse
sys.path.insert(0, str(Path(__file__).resolve().parent))from common import ( ROOT, DEFAULT_UA, base_record, ensure_dirs, existing_ids, html_to_text, http_get, iso_date, log_failure, slug_id, split_articles, utcnow, write_instrument, write_summary,)import archive_fallbacks as af
log = logging.getLogger("world_lib")
MIN_TEXT = 80MAX_PDF = 35 * 1024 * 1024
def setup_log(cc: str, name: str | None = None) -> None: ensure_dirs(cc) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", handlers=[ logging.FileHandler(ROOT / cc / "logs" / "collector.log", encoding="utf-8"), logging.StreamHandler(sys.stdout), ], force=True, )
def pdf_to_text(raw: bytes) -> str: """Extract text via pdftotext. Tries qpdf --decrypt first for copy-restricted digital PDFs (still not OCR — image-only scans stay empty).""" if not raw: return "" if raw[:4] != b"%PDF": idx = raw.find(b"%PDF") if idx < 0 or idx > 8192: return "" raw = raw[idx:] try: with tempfile.TemporaryDirectory() as d: dpath = Path(d) src = dpath / "in.pdf" src.write_bytes(raw) candidates = [src] dec = dpath / "dec.pdf" try: q = subprocess.run( ["qpdf", "--decrypt", str(src), str(dec)], check=False, capture_output=True, timeout=120, ) if q.returncode == 0 and dec.exists() and dec.stat().st_size > 1000: candidates.insert(0, dec) except Exception: pass best = "" for cand in candidates: for args in ( ["pdftotext", "-layout", "-enc", "UTF-8", str(cand), "-"], ["pdftotext", "-raw", "-enc", "UTF-8", str(cand), "-"], ): proc = subprocess.run( args, check=False, capture_output=True, timeout=180 ) if proc.returncode == 0 and proc.stdout: text = proc.stdout.decode("utf-8", "replace").strip() # Ignore form-feed-only / tiny junk from image-only pages if len(text) > len(best): best = text if len(best) >= 150: break return best except Exception as exc: log.warning("pdftotext: %s", exc) return ""
def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]: docs = split_articles(text, law_id, source_url, date) if not pattern: return docs # Normalize bidi + eastern digits so Arabic/Persian article markers match try: from pdf_extract_lib import normalize_rtl_text work = normalize_rtl_text(text or "") except Exception: work = text or "" matches = list(pattern.finditer(work)) if len(matches) < 2: return docs if len(docs) >= 2 else [] out = [] for i, m in enumerate(matches): start = m.start() end = matches[i + 1].start() if i + 1 < len(matches) else len(work) chunk = work[start:end].strip() if len(chunk) < 20: continue num = re.sub(r"\s+", " ", m.group(1)).strip() aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F\u0600-\u06FF-]+", "-", num.lower()).strip("-")[:80] heading = chunk.split("\n", 1)[0][:200] out.append({ "id": f"{law_id}-{aid}"[:180], "title": heading, "text": chunk, "date_filed": date, "document_number": num, "source_url": source_url, "record_type": "article", "article_number": num, "law_identifier": law_id, "metadata": {"text_extraction": {"source": "official", "backend": "collector"}}, }) if len(out) >= 4000: break return out if len(out) >= 2 else docs
def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (12, 25), verify: bool = True, retries: int = 2): import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) last = None headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"} for attempt in range(1, retries + 1): try: time.sleep(0.2) resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True) return resp except Exception as exc: last = exc if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)): try: resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True) return resp except Exception as exc2: last = exc2 time.sleep(min(8, 1.5 * attempt)) raise RuntimeError(f"live_get failed {url}: {last}")
def fetch_official( url: str, *, ua: str = DEFAULT_UA, verify: bool = True, wayback: bool = True, wayback_ts: Optional[str] = None, min_text: int = MIN_TEXT,) -> dict: """Live official URL first; Wayback of the same official URL on failure. No WAF bypass.""" out = { "status": "error", "text": "", "content": b"", "source_url": url, "method": "", "content_type": "", "error": "", } body = b"" ctype = "" skip_live = os.environ.get("SKIP_LIVE", "0") not in ("0", "false", "False", "") try: if skip_live: raise RuntimeError("skip_live") r = live_get(url, ua=ua, verify=verify) body = r.content or b"" ctype = r.headers.get("content-type") or "" if r.status_code == 200 and body: is_pdf = ( body[:4] == b"%PDF" or (0 <= body.find(b"%PDF") <= 64) or "pdf" in ctype.lower() ) if is_pdf: text = pdf_to_text(body) if len(text) >= min_text: out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype) return out text = "" if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["): raw = body.decode(r.encoding or "utf-8", "replace") if af.is_challenge(raw, r.status_code): out["error"] = "challenge_or_shell" else: text = html_to_text(raw) if "<" in raw[:500] else raw if len(text) >= min_text and not af.is_spa_shell(raw, text): out.update(status="success", text=text, content=body, method="http_html", content_type=ctype) return out if len(text) < min_text: out["error"] = "short_or_spa" elif body[:4] == b"%PDF" or (0 <= body.find(b"%PDF") <= 64): # Keep bytes so callers (OCR) can work without a second download pdf_body = body if body[:4] == b"%PDF" else body[body.find(b"%PDF"):] out["error"] = "pdf_extract_failed" out["content"] = pdf_body out["content_type"] = ctype or "application/pdf" elif len(body) > min_text: try: text = body.decode("utf-8", "replace") if text.lstrip().startswith("%PDF") or "endobj" in text[:200]: out["error"] = "raw_pdf_bytes" elif len(text) >= min_text: out.update(status="success", text=text, content=body, method="http_text", content_type=ctype) return out except Exception: pass else: out["error"] = f"http_{getattr(r, 'status_code', '?')}" except Exception as exc: out["error"] = f"live:{exc}"
if wayback: try: w = af.get_wayback_content(url, timestamp=wayback_ts) if w.get("status") == "success": raw_b = w.get("content") or b"" raw_t = w.get("text") or "" pdf_bytes = b"" if isinstance(raw_b, (bytes, bytearray)) and raw_b: if raw_b[:4] == b"%PDF": pdf_bytes = bytes(raw_b) else: _idx = raw_b.find(b"%PDF", 0, 8192) if _idx >= 0: pdf_bytes = bytes(raw_b[_idx:]) if not pdf_bytes and raw_t: enc = raw_t.encode("latin-1", "replace") if enc[:4] == b"%PDF": pdf_bytes = enc else: _idx = enc.find(b"%PDF", 0, 8192) if _idx >= 0: pdf_bytes = enc[_idx:] if pdf_bytes or (isinstance(raw_b, bytes) and (w.get("content_type") or "").lower().find("pdf") >= 0): if not pdf_bytes and isinstance(raw_b, bytes): pdf_bytes = raw_b text = pdf_to_text(pdf_bytes) if len(text) >= min_text and not text.lstrip().startswith("%PDF"): out.update( status="success", text=text, content=pdf_bytes, method="wayback_pdf", source_url=w.get("wayback_url") or w.get("url") or url, content_type="application/pdf", ) return out # Keep PDF bytes so callers (OCR) can work without a second download out["error"] = (out.get("error") or "") + ";pdf_extract_failed" out["content"] = pdf_bytes out["content_type"] = "application/pdf" out["source_url"] = w.get("wayback_url") or w.get("url") or url return out if not raw_t and isinstance(raw_b, bytes): raw_t = raw_b.decode("utf-8", "replace") if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:400] or "startxref" in raw_t[:800]: out["error"] = (out.get("error") or "") + ";raw_pdf_bytes" return out text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t if len(text) >= min_text and not af.is_challenge(raw_t, 200): out.update( status="success", text=text, content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"), method="wayback_html", source_url=w.get("url") or url, content_type=w.get("content_type") or "text/html", ) return out out["error"] = (out.get("error") or "") + ";wayback_short" else: out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}" except Exception as exc: out["error"] = (out.get("error") or "") + f";wayback:{exc}" return out
def best_cdx_pdf_timestamp(url: str) -> Optional[str]: """Pick a CDX snapshot timestamp that looks like a real PDF (status 200).""" try: # Prefer exact URL match via prefix of the path from urllib.parse import urlsplit parts = urlsplit(url) host = (parts.hostname or "").replace("www.", "") path = parts.path or "/" # try a few URL variants candidates = [] for u in (url, url.replace("https://", "http://"), url.replace("http://", "https://")): u2 = u.replace(":80/", "/") for h in cdx_urls(u2, limit=20, match_type="exact"): candidates.append(h) # also prefix on host+path prefix = f"{host}{path}".lstrip("/") if prefix: for h in cdx_urls(prefix, limit=30, match_type="prefix", extra_filters=["mimetype:application/pdf"]): candidates.append(h) for h in cdx_urls("www." + prefix, limit=30, match_type="prefix", extra_filters=["mimetype:application/pdf"]): candidates.append(h) best = None for h in candidates: ts = h.get("timestamp") or "" sc = str(h.get("statuscode") or h.get("status") or "") mt = (h.get("mimetype") or "").lower() orig = (h.get("original") or "").lower() if not ts: continue if sc and sc not in ("200", "226", "-"): continue score = 0 if "pdf" in mt or orig.endswith(".pdf"): score += 2 if sc == "200": score += 1 if best is None or score > best[0] or (score == best[0] and ts > best[1]): best = (score, ts) return best[1] if best else None except Exception as exc: log.info("best_cdx_pdf_timestamp fail %s: %s", url[:80], exc) return None
def fetch_official_prefer_pdf( url: str, *, ua: str = DEFAULT_UA, verify: bool = True, min_text: int = MIN_TEXT, wayback_ts: Optional[str] = None,) -> dict: """Live first; on failure, Wayback with CDX PDF timestamp when available.""" got = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=wayback_ts, min_text=min_text) if got.get("status") == "success" and not (got.get("text") or "").lstrip().startswith("%PDF"): # reject obvious HTML shells mistaken for success when URL is a PDF if url.lower().endswith(".pdf") and got.get("method") == "wayback_html": pass # try timestamped below else: return got ts = wayback_ts or best_cdx_pdf_timestamp(url) if ts: got2 = fetch_official(url, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text) if got2.get("status") == "success": return got2 # try http variant with same ts alt = url.replace("https://", "http://") if url.startswith("https://") else url.replace("http://", "https://") got3 = fetch_official(alt, ua=ua, verify=verify, wayback=True, wayback_ts=ts, min_text=min_text) if got3.get("status") == "success": return got3 return got
def first_title(text: str, fallback: str) -> str: for line in (text or "").splitlines(): s = line.strip() if len(s) >= 12 and not s.lower().startswith("just a moment"): return s[:240] return fallback[:240]
def save_instrument( *, cc: str, country: str, language: str, ident: str, title: str, text: str, source_url: str, source_type: str, license_text: str, collector: str, date: Optional[str] = None, article_re: Optional[re.Pattern] = None, extra_meta: Optional[dict] = None,) -> bool: if not text or len(text) < MIN_TEXT: return False rid = slug_id(cc, ident) docs = split_custom(text, rid, source_url, date, article_re) rec = base_record( cc=cc, country=country, language=language, ident=ident, title=title or first_title(text, ident), text=text, source_url=source_url, source_type=source_type, license_text=license_text, collector=collector, date=iso_date(date) or date, documents=docs, extra_meta=extra_meta, ) _dest = write_instrument(cc, rec) # tip+30u fix (executor 06:4x PT Oct 2): a quality-filter reject returns the quarantine path -> report False so MAX_NEW counts only real saves return bool(_dest) and Path(_dest).parent.name == "instruments" and Path(_dest).exists()
def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]: try: hits = af.search_wayback_machine( host_or_url, limit=limit, match_type=match_type, collapse="urlkey", extra_filters=extra_filters, ) except Exception as exc: log.info("cdx err %s: %s", host_or_url, exc) return [] return hits or []
def env_int(name: str, default: int) -> int: try: return int(os.environ.get(name, str(default)) or default) except Exception: return default123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289#!/usr/bin/env python3"""Package instruments -> parquet + README and upload ipfs_<slug>_laws datasets."""from __future__ import annotations# Harvested collector path injection. Do not collect from /workspace.import os as _ipfs_osfrom pathlib import Path as _ipfs_Path_CORPORA = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_CORPORA_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_corpora")))_SCRAPERS = _ipfs_Path(_ipfs_os.environ.get("IPFS_DATASETS_LEGAL_COLLECTORS_ROOT", str(_ipfs_Path.home() / ".ipfs_datasets" / "legal_collectors"))) / "shared"_HF_TOKEN_PATH = _ipfs_Path(_ipfs_os.environ.get("HF_TOKEN_PATH", str(_ipfs_Path.home() / ".cache" / "huggingface" / "token")))import json, shutil, sysfrom datetime import datetime, timezone, timedeltafrom pathlib import Path
import pandas as pdfrom huggingface_hub import HfApi
ROOT = _CORPORASCRAPERS = _SCRAPERSPT = timezone(timedelta(hours=-7))
META = { "am": ("endomorphosis/ipfs_armenia_laws", "Armenia", "hy", "ARLIS (arlis.am)", "scrapers/collect_am.py", "am-arlis"), "al": ("endomorphosis/ipfs_albania_laws", "Albania", "sq", "QPZ/QBZ Fletorja Zyrtare PDFs", "scrapers/collect_al.py", "al-qbz-fletore"), "ba": ("endomorphosis/ipfs_bosnia_laws", "Bosnia and Herzegovina", "bs", "Sluzbeni list BiH PdfDownload", "scrapers/collect_ba.py", "ba-sluzbeni-list"), "mk": ("endomorphosis/ipfs_northmacedonia_laws", "North Macedonia", "mk", "Sluzben vesnik", "scrapers/collect_mk.py", "mk-slvesnik"), "me": ("endomorphosis/ipfs_montenegro_laws", "Montenegro", "sr", "Sluzbeni list Crne Gore", "scrapers/collect_me.py", "me-sluzbeni-list"), "md": ("endomorphosis/ipfs_moldova_laws", "Moldova", "ro", "legis.md State Register", "scrapers/collect_md.py", "md-legis"), "ge": ("endomorphosis/ipfs_georgia_laws", "Georgia", "ka", "matsne.gov.ge PDF download", "scrapers/collect_ge.py", "ge-matsne-pdf"), "ec": ("endomorphosis/ipfs_ecuador_laws", "Ecuador", "es", "gob.ec / Registro Oficial", "scrapers/collect_ec.py", "ec-registro-oficial"), "bo": ("endomorphosis/ipfs_bolivia_laws", "Bolivia", "es", "Gaceta Oficial de Bolivia", "scrapers/collect_bo.py", "bo-gaceta-oficial"), "py": ("endomorphosis/ipfs_paraguay_laws", "Paraguay", "es", "BACN leyes paraguayas", "scrapers/collect_py.py", "py-bacn"), "pa": ("endomorphosis/ipfs_panama_laws", "Panama", "es", "Gaceta Oficial de Panama", "scrapers/collect_pa.py", "pa-gaceta-oficial"), "dz": ("endomorphosis/ipfs_algeria_laws", "Algeria", "fr", "JORADP Journal Officiel", "scrapers/collect_dz.py", "dz-joradp"), "tn": ("endomorphosis/ipfs_tunisia_laws", "Tunisia", "ar", "IORT Journal Officiel", "scrapers/collect_tn.py", "tn-iort"), "gh": ("endomorphosis/ipfs_ghana_laws", "Ghana", "en", "Parliament of Ghana / ir.parliament.gh", "scrapers/collect_gh.py", "ghana-official"), "et": ("endomorphosis/ipfs_ethiopia_laws", "Ethiopia", "am", "Federal Negarit Gazette", "scrapers/collect_et.py", "et-negarit"), "tz": ("endomorphosis/ipfs_tanzania_laws", "Tanzania", "en", "OAG MIS Acts PDFs", "scrapers/collect_tz.py", "tz-oagmis"), "rs": ("endomorphosis/ipfs_serbia_laws", "Serbia", "sr", "PIS + parlament.gov.rs zakoni PDFs", "scrapers/collect_rs.py", "rs-pis-parlament"), "is": ("endomorphosis/ipfs_iceland_laws", "Iceland", "is", "Althingi Lagasafn", "scrapers/collect_is.py", "is-althingi-lagasafn"), "xk": ("endomorphosis/ipfs_kosovo_laws", "Kosovo", "sq", "Gazeta Zyrtare GZK", "scrapers/collect_xk.py", "xk-gzk"), "uz": ("endomorphosis/ipfs_uzbekistan_laws", "Uzbekistan", "uz", "lex.uz National Database", "scrapers/collect_uz.py", "uz-lex"), "rw": ("endomorphosis/ipfs_rwanda_laws", "Rwanda", "en", "MINIJUST Official Gazette", "scrapers/collect_rw.py", "rw-minijust-og"), "by": ("endomorphosis/ipfs_belarus_laws", "Belarus", "ru", "pravo.by National Legal Portal", "scrapers/collect_by.py", "by-pravo"), "mn": ("endomorphosis/ipfs_mongolia_laws", "Mongolia", "mn", "legalinfo.mn", "scrapers/collect_mn.py", "mn-legalinfo"), "np": ("endomorphosis/ipfs_nepal_laws", "Nepal", "ne", "Nepal Law Commission", "scrapers/collect_np.py", "np-lawcommission"), "jm": ("endomorphosis/ipfs_jamaica_laws", "Jamaica", "en", "MOJ Jamaica / Parliament", "scrapers/collect_jm.py", "jm-moj"), "ug": ("endomorphosis/ipfs_uganda_laws", "Uganda", "en", "Parliament of Uganda", "scrapers/collect_ug.py", "ug-parliament"), "sn": ("endomorphosis/ipfs_senegal_laws", "Senegal", "fr", "Journal Officiel du Senegal", "scrapers/collect_sn.py", "sn-jo"), "cm": ("endomorphosis/ipfs_cameroon_laws", "Cameroon", "fr", "Présidence / Primature Cameroun (prc.cm / spm.gov.cm)", "scrapers/collect_cm.py", "cm-prc-spm"), "mz": ("endomorphosis/ipfs_mozambique_laws", "Mozambique", "pt", "Boletim da República / MIREME / Parlamento", "scrapers/collect_mz.py", "mz-boletim-mireme"), "ao": ("endomorphosis/ipfs_angola_laws", "Angola", "pt", "Diario da Republica / GUE / Portal do Governo", "scrapers/collect_ao.py", "ao-diario-republica"), "az": ("endomorphosis/ipfs_azerbaijan_laws", "Azerbaijan", "az", "e-qanun.az downloadDetailPdf", "scrapers/collect_az.py", "az-eqanun"), "do": ("endomorphosis/ipfs_dominicanrepublic_laws", "Dominican Republic", "es", "Consultoria Juridica / consultoria.gov.do", "scrapers/collect_do.py", "do-consultoria"), "fj": ("endomorphosis/ipfs_fiji_laws", "Fiji", "en", "laws.gov.fj LawsAsMade", "scrapers/collect_fj.py", "fj-laws"), "sv": ("endomorphosis/ipfs_elsalvador_laws", "El Salvador", "es", "Diario Oficial de El Salvador", "scrapers/collect_sv.py", "sv-diario-oficial"), "gt": ("endomorphosis/ipfs_guatemala_laws", "Guatemala", "es", "Congreso de la Republica (congreso.gob.gt)", "scrapers/collect_gt.py", "gt-congreso"), "kh": ("endomorphosis/ipfs_cambodia_laws", "Cambodia", "km", "Ministry of Justice Cambodia (moj.gov.kh)", "scrapers/collect_kh.py", "kh-moj"), "la": ("endomorphosis/ipfs_laos_laws", "Laos", "lo", "Lao Official Gazette", "scrapers/collect_la.py", "la-official-gazette"), "cu": ("endomorphosis/ipfs_cuba_laws", "Cuba", "es", "Gaceta Oficial de Cuba", "scrapers/collect_cu.py", "cu-gaceta-oficial"), "ni": ("endomorphosis/ipfs_nicaragua_laws", "Nicaragua", "es", "Asamblea Nacional legislacion.asamblea.gob.ni", "scrapers/collect_ni.py", "ni-asamblea"), "hn": ("endomorphosis/ipfs_honduras_laws", "Honduras", "es", "TSC / La Gaceta tsc.gob.hn/web/leyes", "scrapers/collect_hn.py", "hn-tsc-gaceta"), "ve": ("endomorphosis/ipfs_venezuela_laws", "Venezuela", "es", "Gaceta Oficial gacetaoficial.gob.ve", "scrapers/collect_ve.py", "ve-gaceta-oficial"), "tt": ("endomorphosis/ipfs_trinidad_laws", "Trinidad and Tobago", "en", "TT Parliament / laws.gov.tt", "scrapers/collect_tt.py", "tt-parliament-laws"), "bn": ("endomorphosis/ipfs_brunei_laws", "Brunei", "en", "AGC Laws of Brunei", "scrapers/collect_bn.py", "bn-agc-laws"), "pg": ("endomorphosis/ipfs_papuanewguinea_laws", "Papua New Guinea", "en", "PNG Parliament uploads/acts", "scrapers/collect_pg.py", "pg-parliament-acts"), "iq": ("endomorphosis/ipfs_iraq_laws", "Iraq", "ar", "Ministry of Justice moj.gov.iq", "scrapers/collect_iq.py", "iq-moj"), "ir": ("endomorphosis/ipfs_iran_laws", "Iran", "fa", "DOTIC dotic.ir", "scrapers/collect_ir.py", "ir-dotic"), "lk": ("endomorphosis/ipfs_srilanka_laws", "Sri Lanka", "en", "documents.gov.lk / parliament.lk", "scrapers/collect_lk.py", "lk-documents-gov"), "lb": ("endomorphosis/ipfs_lebanon_laws", "Lebanon", "ar", "JO pcm.gov.lb Official Gazette", "scrapers/collect_lb.py", "lb-jo-pcm"), "zw": ("endomorphosis/ipfs_zimbabwe_laws", "Zimbabwe", "en", "Parliament of Zimbabwe (parlzim.gov.zw)", "scrapers/collect_zw.py", "zw-parliament-acts"), "na": ("endomorphosis/ipfs_namibia_laws", "Namibia", "en", "Parliament of Namibia / laws.parliament.na / Bank of Namibia", "scrapers/collect_na.py", "na-parliament-bon"), "bw": ("endomorphosis/ipfs_botswana_laws", "Botswana", "en", "gov.bw / Parliament / BURS / statutory agencies", "scrapers/collect_bw.py", "bw-gov-parliament-burs"),}
LAW_COLS = [ "id", "title", "text", "source_url", "source_type", "jurisdiction", "country", "language", "eli", "date", "date_issued", "retrieved_at", "license", "law_status", "identifier", "official_identifier", "article_count", "json_path", "metadata_json",]ART_COLS = [ "law_id", "id", "title", "text", "source_url", "document_number", "article_number", "record_type", "metadata_json",]
def token() -> str: return _HF_TOKEN_PATH.read_text().strip()
def instruments_to_frames(cc: str): instr = ROOT / cc / "instruments" laws, arts = [], [] if not instr.exists(): return pd.DataFrame(columns=LAW_COLS), pd.DataFrame(columns=ART_COLS) for p in sorted(instr.glob("*.json")): try: rec = json.loads(p.read_text(encoding="utf-8")) except Exception: continue text = rec.get("text") or "" min_txt = int(__import__("os").environ.get("MIN_PACKAGE_TEXT", "80")) if len(text) < min_txt: continue meta = rec.get("metadata") or {} laws.append({ "id": rec.get("id"), "title": rec.get("title"), "text": text, "source_url": rec.get("source_url"), "source_type": rec.get("source_type"), "jurisdiction": rec.get("jurisdiction"), "country": rec.get("country"), "language": rec.get("language"), "eli": rec.get("eli"), "date": rec.get("date"), "date_issued": rec.get("date"), "retrieved_at": rec.get("retrieved_at"), "license": rec.get("license"), "law_status": rec.get("law_status"), "identifier": rec.get("identifier"), "official_identifier": rec.get("official_identifier"), "article_count": rec.get("article_count") or len(rec.get("documents") or []), "json_path": f"instruments/{p.name}", "metadata_json": json.dumps(meta, ensure_ascii=False), }) for d in rec.get("documents") or []: arts.append({ "law_id": rec.get("id"), "id": d.get("id"), "title": d.get("title"), "text": d.get("text") or "", "source_url": d.get("source_url") or rec.get("source_url"), "document_number": d.get("document_number"), "article_number": d.get("article_number"), "record_type": d.get("record_type") or "article", "metadata_json": json.dumps(d.get("metadata") or {}, ensure_ascii=False), }) return pd.DataFrame(laws, columns=LAW_COLS), pd.DataFrame(arts, columns=ART_COLS)
def write_readme(cc: str, out: Path, n_laws: int, n_arts: int, notes: str) -> None: repo, country, lang, source, collector, lic = META[cc] pretty = f"Laws of {country}" size = ( "n<1K" if n_laws < 1000 else "1K<n<10K" if n_laws < 10000 else "10K<n<100K" if n_laws < 100000 else "100K<n<1M" ) today = datetime.now(PT).strftime("%Y-%m-%d") body = f"""---pretty_name: {pretty}license: otherlicense_name: {lic}language:- {lang}task_categories:- text-retrievaltags:- legal- law- {country.lower().replace(' ', '-')}- official-textssize_categories:- {size}configs:- config_name: laws data_files: data/laws.parquet default: true- config_name: articles data_files: data/articles.parquet---
# {pretty}
Research snapshot of official legislation collected from **{source}**.
**Not legal advice.** Official gazettes / government portals prevail over this corpus.
## Snapshot
| Field | Value || --- | --- || Snapshot date | {today} || Coverage | catalog-backed incomplete || Source | {source} || Collector | `{collector}` || Laws / instruments | {n_laws} || Articles | {n_arts} || Language | {lang} || Jurisdiction | {country} || License | `{lic}` |
## Contents
- `data/laws.parquet` — one row per instrument (id, title, full text, dates, status, identifiers, article count, source URL).- `data/articles.parquet` — one row per article/section (`law_id`, article number, title, text, source URL).- `{collector}` — research collector used to build this snapshot.- `scrapers/common.py` — shared collector helpers.- `scrapers/world_lib.py` — shared fetch (live official URL, Wayback fallback).- `scrapers/archive_fallbacks.py` — Wayback / Common Crawl CDX helpers.
## License / reuse
Official government / gazette texts; reuse per public-sector terms of thesource portal. This packaging, metadata, and collector script are providedfor research.
This dataset is **not** an official consolidation and is **not legal advice**.The official source prevails.
## Notes
{notes}""" out.write_text(body, encoding="utf-8")
def write_manifest(out: Path, n_laws: int, n_arts: int, files: dict) -> None: now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") lines = ["# MANIFEST", "", f"- generated_at: {now}", f"- laws: {n_laws}", f"- articles: {n_arts}", "- files:"] for k, v in files.items(): lines.append(f" - {k}: {v} bytes") lines.append("") out.write_text("\n".join(lines), encoding="utf-8")
def package(cc: str, staging: Path, notes: str) -> tuple[int, int]: staging.mkdir(parents=True, exist_ok=True) (staging / "data").mkdir(exist_ok=True) (staging / "scrapers").mkdir(exist_ok=True) ldf, adf = instruments_to_frames(cc) if len(ldf) == 0: raise SystemExit(f"{cc}: no laws with text>=80 to package") lpath = staging / "data" / "laws.parquet" apath = staging / "data" / "articles.parquet" ldf.to_parquet(lpath, index=False) adf.to_parquet(apath, index=False) write_readme(cc, staging / "README.md", len(ldf), len(adf), notes) collector = Path(META[cc][4]).name for name in [collector, "common.py", "archive_fallbacks.py", "world_lib.py"]: src = SCRAPERS / name if src.exists(): shutil.copy2(src, staging / "scrapers" / name) files = { "data/laws.parquet": lpath.stat().st_size, "data/articles.parquet": apath.stat().st_size, "README.md": (staging / "README.md").stat().st_size, } write_manifest(staging / "MANIFEST.md", len(ldf), len(adf), files) return len(ldf), len(adf)
def upload(cc: str, staging: Path) -> str: repo = META[cc][0] api = HfApi(token=token()) api.create_repo(repo_id=repo, repo_type="dataset", exist_ok=True, private=False) api.upload_folder( folder_path=str(staging), repo_id=repo, repo_type="dataset", commit_message=f"Add/update {cc} official laws snapshot", allow_patterns=["data/*.parquet", "README.md", "MANIFEST.md", "scrapers/*"], ) return f"https://huggingface.co/datasets/{repo}"
if __name__ == "__main__": cmd = sys.argv[1] if len(sys.argv) > 1 else "help" if cmd == "package": cc = sys.argv[2] notes = sys.argv[3] if len(sys.argv) > 3 else "Partial official scrape. Not legal advice." staging = _SCRAPERS.parent / f"staging_{cc}" n_l, n_a = package(cc, staging, notes) print(f"packaged {cc}: laws={n_l} arts={n_a} -> {staging}") elif cmd == "upload": cc = sys.argv[2] staging = _SCRAPERS.parent / f"staging_{cc}" url = upload(cc, staging) print("uploaded", url) elif cmd == "package-upload": cc = sys.argv[2] notes = sys.argv[3] if len(sys.argv) > 3 else "Partial official scrape. Not legal advice." staging = _SCRAPERS.parent / f"staging_{cc}" n_l, n_a = package(cc, staging, notes) url = upload(cc, staging) print(f"{cc}: laws={n_l} arts={n_a} {url}") else: print("usage: package|upload|package-upload <cc> [notes]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104#!/usr/bin/env python3"""Offline normalize/structure job (NO network). Streaming gz line-by-line, resumes by chunk, atomic outputs, sources never touched. nl : scan/*.jsonl.gz + rescan_bom/*.jsonl.gz -> normalized/nl_municipal/<chunk>.jsonl.gz (dedupe by id; rescan_bom record wins over scan stub; real record wins over manifest_parse_fail/stop stubs). Output = normalized index record (id, status, jur, dates, creator, rtype, counts). cz : t2/index/laws_shards/*.jsonl.gz (+t1 shards) -> normalized/cz_sbirkapp/<shard>.jsonl.gz (NFC text, whitespace-collapsed, sha256 of text, article stats; dedupe by law id)Run: MALLOC_ARENA_MAX=2 nice -n 19 ionice -c3 python normalize_offline.py {nl|cz} [--limit N] [--out DIR]Guards: refuses to start if MemAvail < 3584; self-checks RSS every 500 lines (cap 200MB -> exit 4, resumable); pauses if MemAvail < 3584; STOP file normalized/STOP_NORM."""import os, sys, gzip, json, glob, hashlib, unicodedata, re, time, resourceR='/workspace/legal-corpora'; OUT=f'{R}/normalized'; RSS_CAP=200def memavail(): for l in open('/proc/meminfo'): if l.startswith('MemAvailable'): return int(l.split()[1])//1024def rss(): for l in open('/proc/self/status'): if l.startswith('VmRSS'): return int(l.split()[1])//1024def gate(n): if os.path.exists(f'{OUT}/STOP_NORM'): print('STOP_NORM present; exiting clean'); sys.exit(0) if n%500==0: if rss()>RSS_CAP: print('RSS cap exceeded',rss()); sys.exit(4) t=time.time() while memavail()<3584: if os.path.exists(f'{OUT}/STOP_NORM') or time.time()-t>900: print('mem pause exit'); sys.exit(5) time.sleep(5)def aw(path, lines): tmp=path+'.tmp' with gzip.open(tmp,'wt',encoding='utf-8',compresslevel=6) as f: for l in lines: f.write(l) os.replace(tmp,path)RANK={'ok':5,'in_force_no_text_in_xml':4,'expired':3,'future_only':3,'in_force_out_of_scope':3,'absent':2}def nl_norm(d): s=d.get('s') o=dict(id=d['id'],status=s) for k in ('creator','scheme','jur','auth','atype','rtype','rubriek','inw','uit','n_article','n_annex','n_section','oper_chars','title'): if d.get(k) is not None: o[k]=d[k] if d.get('rescan'): o['rescan']=d['rescan'] return odef run_nl(limit,out): out=out or f'{OUT}/nl_municipal'; os.makedirs(out,exist_ok=True) chunks={} for sub in ('scan','rescan_bom'): for f in glob.glob(f'{R}/nl_municipal/index/{sub}/*.jsonl.gz'): chunks.setdefault(os.path.basename(f),[]).append((sub,f)) done=0; n=0 for name in sorted(chunks, reverse=True): dst=f'{out}/{name}' # resume by chunk: skip if output newer than all sources if os.path.exists(dst) and os.path.getmtime(dst)>=max(os.path.getmtime(f) for _,f in chunks[name]): continue recs={} for sub,f in chunks[name]: try: with gzip.open(f,'rt',encoding='utf-8-sig') as fh: for l in fh: n+=1; gate(n) try: d=json.loads(l.lstrip('\ufeff')) except Exception: continue i=d.get('id'); if i is None: continue r=(RANK.get(d.get('s'),1), 1 if sub=='rescan_bom' else 0) if i not in recs or r>=recs[i][0]: recs[i]=(r,nl_norm(d)) except (EOFError,OSError) as e: print('skip unreadable',f,e) aw(dst,(json.dumps(v[1],ensure_ascii=False,separators=(',',':'))+'\n' for _,v in sorted(recs.items(),reverse=True))) done+=1 if limit and done>=limit: break print('nl chunks written',done,'lines',n,'peak_rss_mb',resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024)WS=re.compile(r'[ \t\u00a0]+'); NL3=re.compile(r'\n{3,}')def clean(t): if not isinstance(t,str): return t t=unicodedata.normalize('NFC',t).replace('\r\n','\n').replace('\r','\n'); t=WS.sub(' ',t) return NL3.sub('\n\n',t).strip()def run_cz(limit,out): out=out or f'{OUT}/cz_sbirkapp'; os.makedirs(out,exist_ok=True) seen=set(); done=0; n=0 files=sorted(glob.glob(f'{R}/cz_sbirkapp/t2/index/laws_shards/*.jsonl.gz')+glob.glob(f'{R}/cz_sbirkapp/t1/index/laws_shards/*.jsonl.gz')) for f in files: dst=f'{out}/{os.path.basename(f)}' # ids from already-normalized shards still feed the dedupe set (streamed ids only) if os.path.exists(dst) and os.path.getmtime(dst)>=os.path.getmtime(f): with gzip.open(dst,'rt',encoding='utf-8') as fh: for l in fh: try: seen.add(json.loads(l)['law']['id']) except Exception: pass continue tmp=dst+'.tmp' with gzip.open(f,'rt',encoding='utf-8') as fh, gzip.open(tmp,'wt',encoding='utf-8',compresslevel=6) as oh: for l in fh: n+=1; gate(n) try: d=json.loads(l) except Exception: continue law=d.get('law') or {}; lid=law.get('id') if lid in seen: continue seen.add(lid) law['text']=clean(law.get('text')); law['text_sha256']=hashlib.sha256((law['text'] or '').encode()).hexdigest() arts=d.get('articles') or [] for a in arts: a['text']=clean(a.get('text')) law['article_count_norm']=len(arts); law['text_chars']=len(law['text'] or '') oh.write(json.dumps(dict(law=law,articles=arts),ensure_ascii=False,separators=(',',':'))+'\n') os.replace(tmp,dst); done+=1 if limit and done>=limit: break print('cz shards written',done,'lines',n,'peak_rss_mb',resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024)if __name__=='__main__': a=sys.argv; lim=int(a[a.index('--limit')+1]) if '--limit' in a else 0; out=a[a.index('--out')+1] if '--out' in a else None if memavail()<3584: print('REFUSED MemAvail low'); sys.exit(3) {'nl':run_nl,'cz':run_cz}[a[1]](lim,out)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135#!/usr/bin/env python3"""pa_exit_guard - safe process exit for scripts that read parquet with pyarrow in /workspace/venv (pandas 3.0.6, numpy 2.5.3, pyarrow 25.0.1, Python 3.13.5).
Problem: after pq.read_table() (which lazily imports pandas), normal interpreter shutdown can abort in a C++ destructor with'terminate called without an active exception' (SIGABRT, exit 134) although all work has finished. Measured 2026-10-06: it is a shutdownrace - most runs abort even after the Table was freed; `del` + gc.collect() lowers the rate but does not remove it; os._exit() afterflushing removes it. So: release objects (safe part) AND leave through os._exit with the REAL exit code (this module).
Entrypoint (function-style script): import pa_exit_guard as EG if __name__ == '__main__': EG.run_guarded(main) # or EG.run_guarded(fn, arg1, ...)Module-level script (no main()): `pa_exit_guard.install()` near the top, `pa_exit_guard.finish(0)` as the last line.Build/verify/push functions: close writers, `del` Tables / ParquetFile objects / readers / writers, then `release()` (gc.collect()).
Exit code = what the interpreter would have used: return None, sys.exit(), sys.exit(None) -> 0 return <int>, sys.exit(<int>) -> that int (other return values are ignored -> 0, as Python ignores them) sys.exit('message') -> message printed to stderr, 1 uncaught exception -> traceback printed to stderr, 1 (KeyboardInterrupt: traceback, 130)Before os._exit: non-daemon threads are joined and atexit handlers run (as in a normal shutdown), still-open writable file objects areflushed, logging handlers and the given log files are closed, stdout/stderr are flushed (stdout flush failure on success -> 120, as Python).Never hard-codes 0."""import atexit, gc, io, logging, os, sys, threading, traceback
__all__ = ['release', 'run_guarded', 'finish', 'install', 'exit_code_of']
def release(*objs): """close() every given object that has a close() (pass writers first: ParquetWriter, then ParquetFile/readers/file handles), then gc.collect(). A failing close() of a writer is a real failure and is NOT swallowed. The caller must still `del` its own names.""" for o in objs: c = getattr(o, 'close', None) if callable(c): c() del objs gc.collect()
def exit_code_of(code): """SystemExit.code -> process exit status, same rules as CPython (non-int: printed to stderr, status 1).""" if code is None: return 0 if isinstance(code, int): return int(code) if -2 ** 31 <= code < 2 ** 31 else 1 try: print(code, file=sys.stderr, flush=True) except Exception: pass return 1
def _flush_open_files(): """flush still-open writable file objects (a normal shutdown would flush them while finalizing; os._exit does not). Returns failures.""" bad = [] skip = {id(sys.stdout), id(sys.stderr), id(sys.__stdout__), id(sys.__stderr__)} for o in gc.get_objects(): try: if isinstance(o, io.IOBase) and id(o) not in skip and not o.closed and o.writable(): o.flush() except ValueError: pass # closed in the meantime / detached except Exception as e: bad.append(f'{getattr(o, "name", type(o).__name__)}: {e!r}') return bad
def finish(code, logs=()): """orderly end: join non-daemon threads, run atexit handlers, flush open files, close logging + the given log files, flush stdio, os._exit(code).""" try: me = threading.current_thread() for t in threading.enumerate(): if t is not me and not t.daemon and t.is_alive(): t.join() except BaseException: traceback.print_exc() try: atexit._run_exitfuncs() # exceptions inside are reported by atexit itself; like Python they do not change the code except BaseException: traceback.print_exc() for f in logs or (): try: f.flush(); f.close() except Exception as e: print(f'pa_exit_guard: closing log {getattr(f, "name", f)!r} failed: {e!r}', file=sys.stderr) try: logging.shutdown() except Exception: traceback.print_exc() bad = _flush_open_files() if bad: print('pa_exit_guard: flush failed for ' + '; '.join(bad[:10]), file=sys.stderr) if code == 0: code = 1 try: sys.stderr.flush() except Exception: pass try: sys.stdout.flush() except Exception: if code == 0: code = 120 # CPython: exit status 120 when flushing stdout fails at shutdown for s in (sys.__stdout__, sys.__stderr__): try: if s is not None: s.flush() except Exception: pass os._exit(code)
def run_guarded(main_fn, *args, logs=(), **kwargs): """run main_fn(*args, **kwargs), compute the real exit code, then finish(code). Does not return.""" code = 1 try: r = main_fn(*args, **kwargs) code = int(r) if isinstance(r, int) and not isinstance(r, bool) else 0 except SystemExit as e: code = exit_code_of(e.code) except KeyboardInterrupt: traceback.print_exc(); code = 130 except BaseException: traceback.print_exc(); code = 1 finish(code, logs)
def _excepthook(tp, val, tb): traceback.print_exception(tp, val, tb) finish(130 if issubclass(tp, KeyboardInterrupt) else 1)
def install(): """for module-level scripts: an uncaught exception prints its traceback and exits 1 via finish(); end the script with finish(0).""" sys.excepthook = _excepthook123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220#!/usr/bin/env python3"""Shared polite-collector runtime for IS B-deild and AU-SA (written 2026-10-17, same conventions as ee_t2_collect.py). - official host only (host lock), TLS verify ON (default urllib context, never disabled), no Wayback/CDX - robots.txt fetched at start and honoured (Allow/Disallow with * and $, longest match; Crawl-delay raises the delay); robots fetch 403/5xx => REFUSE (never assume allow); 404 => no rules - delay floor per collector, StrictGuard memory guard (pause<3584/resume>=4200x30s/TERM<1500x10s/instant<1000/RSS 300MB), 3-strike 403/429/503 => HOLD file + stop - transient errors retried 3x with 5/10/20s backoff; atomic 200-record chunks + fsynced append-only ledger; resume skips ledger ids; NOCHUNK3 is enforced by the guarded launcher - never deletes anything; no network at import time"""import os, sys, re, io, json, time, gzip, subprocess, resource, urllib.request, urllib.error, urllib.parsesys.path.insert(0, '/workspace/scripts')import strict_mem_guard as SG
GUARD_OVR = dict(hard_term_memavail=1500, hard_term_sustain_s=10.0, instant_term_memavail=1000, pause_memavail=3584, resume_memavail=4200, resume_hold_s=30, rss_limit_mb=300, max_pause_s=900)class Strike(Exception): passclass Refuse(Exception): passdef now(): return time.strftime('%Y-%m-%dT%H:%M:%S%z')def atomic_write(path, data): t = str(path) + '.tmp' with open(t, 'w') as f: f.write(data); f.flush(); os.fsync(f.fileno()) os.replace(t, str(path))
class Robots: """RFC 9309-style: groups by user-agent. Applicable groups = '*' group AND every UA-specific group whose product token is a substring of `ua`. MOST RESTRICTIVE applies: a path is allowed only if allowed under EVERY applicable group (longest match, tie -> allow within a group). Crawl-delay = max over applicable groups.""" def __init__(self, text, ua='*'): self.ua = (ua or '*').lower(); groups = []; cur = None; seen_rule = False for raw in text.splitlines(): l = raw.split('#')[0].strip() if ':' not in l: continue k, v = [x.strip() for x in l.split(':', 1)]; k = k.lower() if k == 'user-agent': if cur is None or seen_rule: cur = dict(agents=[], rules=[], delay=0.0); groups.append(cur); seen_rule = False cur['agents'].append(v.lower()) elif cur is None: continue elif k in ('disallow', 'allow'): seen_rule = True if v: cur['rules'].append((k, v)) elif k == 'crawl-delay': seen_rule = True try: cur['delay'] = float(v) except ValueError: pass def applies(g): return any(a == '*' or (a and a in self.ua) for a in g['agents']) self.groups = [g for g in groups if applies(g)] self.matched_agents = sorted({a for g in self.groups for a in g['agents'] if a == '*' or a in self.ua}) self.rules = [r for g in self.groups for r in g['rules']]; self.delay = max([g['delay'] for g in self.groups] + [0.0]) @staticmethod def _rx(p): end = p.endswith('$'); p = p[:-1] if end else p return re.compile('^' + '.*'.join(re.escape(x) for x in p.split('*')) + ('$' if end else '')) @classmethod def _grp_allowed(cls, rules, path): m = [(len(p), k == 'allow') for k, p in rules if cls._rx(p).match(path)] if not m: return True L = max(x[0] for x in m) return any(a for l, a in m if l == L) # longest match wins; tie -> allow def allowed(self, path): return all(self._grp_allowed(g['rules'], path) for g in self.groups)
class Http: def __init__(self, guard, host, delay_floor, delay, hold_path, ua, robots=None, extra_stop=None, log=print): self.g = guard; self.host = host; self.delay = max(delay_floor, float(delay)); self.floor = delay_floor; self.hold = hold_path; self.ua = ua self.robots = robots; self.extra_stop = extra_stop; self.log = log; self.last = 0.0; self.strikes = 0; self.n = 0; self.codes = {}; self.times = [] def set_robots(self, r): self.robots = r if r and r.delay: self.delay = max(self.delay, r.delay) def _wait(self): while True: self.g.check() if self.extra_stop and os.path.exists(self.extra_stop): raise SG.Stopped('extra stopfile') r = self.last + self.delay - time.time() if r <= 0: return time.sleep(min(r, 0.5)) def req(self, url, accept='*/*', robots_exempt=False): u = urllib.parse.urlsplit(url) if u.scheme != 'https' or u.hostname != self.host: raise Refuse('host/scheme lock: ' + url) if self.robots and not robots_exempt and not self.robots.allowed(u.path + ('?' + u.query if u.query else '')): return 'ROBOTS_DISALLOW', b'' for att in range(4): code, buf = self._req1(url, accept) if not ((isinstance(code, str) and code.startswith('ERR:')) or code in (500, 502, 504)) or att == 3: return code, buf self.log('TRANSIENT', code, url[:90], 'retry', att + 1, 'backoff', 5 * 2 ** att) end = time.time() + 5 * 2 ** att while time.time() < end: self.g.check(); time.sleep(0.5) def _req1(self, url, accept): self._wait(); t0 = time.time(); self.last = t0; code = None; buf = b'' try: with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': self.ua, 'Accept': accept}), timeout=30) as r: # TLS verify ON (default context) code = r.status; buf = r.read(30 * 1024 * 1024 + 1) except urllib.error.HTTPError as e: code = e.code except Exception as e: code = 'ERR:' + type(e).__name__ self.n += 1; self.times.append(round(time.time() - t0, 3)); self.codes[str(code)] = self.codes.get(str(code), 0) + 1 if code in (403, 429, 503): self.strikes += 1; self.log('STRIKE', self.strikes, 'HTTP', code, url[:100]) if self.strikes >= 3: atomic_write(self.hold, 'HOLD 3-strike %s at %s last=%s\n' % (code, now(), url)); raise Strike('3-strike HTTP %s' % code) elif code == 200: self.strikes = 0 return code, buf
def load_robots(http, host, log): code, buf = http.req('https://%s/robots.txt' % host, robots_exempt=True) if code == 404: log('robots.txt 404 -> no rules'); return Robots('', http.ua) if code != 200: raise Refuse('robots.txt fetch failed HTTP %s: refusing (never assume allow)' % code) txt = buf.decode('utf-8', 'replace'); r = Robots(txt, http.ua); log('robots.txt loaded: %d rules (groups %s), crawl-delay %s' % (len(r.rules), r.matched_agents, r.delay)); return r, txt
def write_chunk(outdir, prefix, k, recs): name = '%s_%04d.jsonl.gz' % (prefix, k); p = str(outdir / name); t = p + '.tmp' with open(t, 'wb') as raw: with gzip.GzipFile(fileobj=raw, mode='wb', compresslevel=6, mtime=0) as g: for r in recs: g.write((json.dumps(r, ensure_ascii=False) + '\n').encode()) raw.flush(); os.fsync(raw.fileno()) os.replace(t, p); return namedef ledger_load(p): d = {} if p.exists(): for l in open(p, encoding='utf-8'): try: x = json.loads(l); d[x['id']] = x except Exception: pass return ddef ledger_add(p, d): with open(p, 'a', encoding='utf-8') as lf: lf.write(json.dumps(d, ensure_ascii=False) + '\n'); lf.flush(); os.fsync(lf.fileno())def pgrep(pat): return [l for l in subprocess.run(['pgrep', '-af', pat], capture_output=True, text=True).stdout.splitlines() if 'pgrep' not in l and str(os.getpid()) != l.split()[0] and 'python' in ' '.join(l.split()[1:3])]def other_collectors(): pats = [r'nl_municipal_collect\.py (full|collect)', r'ee_t2_(collect|refetch)\.py (collect|--dry)', r'cz_sbirkapp_collect\.py (t1|t2|full)', r'id_bpk_collect\.py', r'(is_bdeild|is_bdise)_collect\.py (collect|--dry)', r'au_sa_collect\.py (collect|--dry)', r'de_.*collect.*\.py (collect|full)'] out = [] for p in pats: out += pgrep(p) return outdef reexec_env(tag): if os.environ.get('MALLOC_ARENA_MAX') != '2' or os.environ.get(tag) != '1': os.nice(10); os.execve(sys.executable, [sys.executable, '-u'] + sys.argv, dict(os.environ, MALLOC_ARENA_MAX='2', **{tag: '1'}))
def run(spec, mode, scratch=None, want=None): """spec: dict(label, root, prefix, host, floor, ua, discover(http,state_dir,log,want)->[items{id,...}], fetch(http,item)->(rec|None, reason), chunk_n, stop, pause, hold, memterm, cfg_path). mode 'collect' (production dirs) | 'dry' (scratch). Returns rc.""" log = lambda *a: print(time.strftime('%Y-%m-%d %H:%M:%S'), '[' + spec['label'] + ']', *a, flush=True) base = scratch if mode == 'dry' else spec['root']; base.mkdir(parents=True, exist_ok=True) outdir = base / 'out'; outdir.mkdir(exist_ok=True); ledger = base / 'ledger.jsonl'; stfile = base / 'state.json'; rl = 0 cfg = SG.load_cfg(str(spec['cfg_path']), overrides=dict(GUARD_OVR, delay_s=spec['floor']), delay_floor=spec['floor']) guard = SG.StrictGuard(cfg, stop_file=None if mode == 'dry' else str(spec['stop']), pause_file=str(spec['pause']), log=log) def state(**kw): s = json.load(open(stfile)) if stfile.exists() else dict(slug=spec['label'], mode=mode) s.update(kw); s['ts'] = now(); SG.atomic_json(str(stfile), s) http = Http(guard, spec['host'], spec['floor'], cfg['delay_s'], str(spec['hold'] if mode == 'collect' else base / 'HOLD_DRYRUN'), spec['ua'], extra_stop=str(base / 'STOP_DRYRUN') if mode == 'dry' else None, log=log) done = ledger_load(ledger); pend = []; n_ok = n_fail = 0; chunk_n = spec.get('chunk_n', 200) k = len([p for p in os.listdir(outdir) if p.startswith(spec['prefix']) and p.endswith('.jsonl.gz')]) guard.start_watcher(); samples = [] def flush(): nonlocal pend, k if not pend: return name = write_chunk(outdir, spec['prefix'], k, pend); k += 1 for r in pend: ledger_add(ledger, dict(id=r['law']['id'], status='ok', chunk=name)) log('CHUNK', name, len(pend)); pend = [] try: state(status='RUNNING', pid=os.getpid(), started=now()) rob = load_robots(http, spec['host'], log); rob, rtxt = rob if isinstance(rob, tuple) else (rob, ''); http.set_robots(rob) atomic_write(str(base / 'robots_live.txt'), rtxt); log('effective delay', http.delay, 's (floor', spec['floor'], ')') items = spec['discover'](http, base, log, want) items = [i for i in items if done.get(i['id'], {}).get('status') not in ('ok', 'skip')] if want: items = items[:want] log('to fetch', len(items)); state(total_todo=len(items)) for it in items: rec, why = spec['fetch'](http, it) if rec is None: n_fail += 1; ledger_add(ledger, dict(id=it['id'], status='skip' if why.startswith('skip:') else 'fail', reason=why)); continue n_ok += 1; pend.append(rec) if mode == 'dry' and len(samples) < 3: samples.append(rec) if len(pend) >= chunk_n: flush(); state(packed=len(done) + n_ok, last_id=it['id']) flush(); state(status='DONE_DRYRUN' if mode == 'dry' else 'BATCH_DONE', packed=len(done) + n_ok) except SG.MemShed as e: atomic_write(str(spec['memterm']), 'MEMTERM %s at %s\n' % (e, now())); flush(); state(status='MEMTERM_crash_tolerant'); log('MEMTERM', e); rl = 75 except SG.Stopped as e: flush(); state(status='STOPPED'); log('STOPPED', e) except Strike as e: flush(); state(status='HOLD_3STRIKE'); log('HOLD', e); rl = 76 except Refuse as e: state(status='REFUSED'); log('REFUSE', e); rl = 3 except Exception as e: try: flush() except Exception: pass state(status='CRASH_resumable'); log('CRASH', type(e).__name__, e); rl = 77 finally: guard.stop_watcher() log('end rc', rl, 'ok', n_ok, 'fail/skip', n_fail, 'requests', http.n, http.codes, 'maxrss_mb', round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1)) if mode == 'dry': SG.atomic_json(str(base / 'dryrun_report.json'), dict(rc=rl, ok=n_ok, fail=n_fail, requests=http.n, codes=http.codes, samples=[dict(law={k_: (v[:300] if isinstance(v, str) else v) for k_, v in s['law'].items()}, n_articles=len(s['articles']), first_article={k_: (v[:200] if isinstance(v, str) else v) for k_, v in s['articles'][0].items()} if s['articles'] else None) for s in samples])) return rl
def common_main(spec, argv, doc): """Shared CLI: collect (--i-have-cos-go or COS token) | --dry-run-ids N [--scratch D] | selftest | status""" cmd = argv[0] if argv else '' log = lambda *a: print(time.strftime('%Y-%m-%d %H:%M:%S'), '[' + spec['label'] + ']', *a, flush=True) root = spec['root'] for p in (root, root / 'index', root / 'out', root / 'review', root / 'ref'): p.mkdir(parents=True, exist_ok=True) if cmd == 'status': print(open(root / 'state.json').read()); return 0 if cmd == 'selftest': SG.load_cfg(str(spec['cfg_path']), overrides=dict(GUARD_OVR, delay_s=spec['floor']), delay_floor=spec['floor']) r = Robots('User-agent: *\nCrawl-delay: 10\nDisallow: /search\nDisallow: /*_admin\nAllow: /search/ok$'); assert r.delay == 10 and not r.allowed('/search') and not r.allowed('/x_admin') and r.allowed('/legislation') and r.allowed('/search/ok') ua = 'Mozilla/5.0 (compatible; legal-corpus-build/1.0; polite research crawler)'; t = 'User-agent: *\nDisallow: /a\n\nUser-agent: legal-corpus-build\nDisallow: /b\nCrawl-delay: 5\n\nUser-agent: otherbot\nDisallow: /\n' r2 = Robots(t, ua); assert not r2.allowed('/a') and not r2.allowed('/b/x') and r2.allowed('/c') and r2.delay == 5 and r2.matched_agents == ['*', 'legal-corpus-build'] r3 = Robots('User-agent: *\nAllow: /\n\nUser-agent: legal-corpus-build\nDisallow: /\n', ua); assert not r3.allowed('/x') # UA group more restrictive than * r4 = Robots('User-agent: otherbot\nUser-agent: legal-corpus-build\nDisallow: /z\n', ua); assert not r4.allowed('/z') and r4.allowed('/y'); assert Robots('', ua).allowed('/q') log('selftest OK (offline)'); return 0 if cmd == 'collect': if any(p.exists() for p in (spec['stop'], spec['hold'])): log('REFUSE marker present', [p.name for p in (spec['stop'], spec['hold']) if p.exists()]); return 2 if not spec['token'].exists() and '--i-have-cos-go' not in argv: log('REFUSE: no CoS GO token', spec['token']); return 3 if pgrep(r'%s collect' % spec['script']): log('REFUSE: already running'); return 7 oc = other_collectors() if len(oc) >= 2: log('REFUSE: max two collectors already running', oc); return 7 if os.path.exists('/workspace/legal-corpora/cz_sbirkapp/FALLBACK_ONE_COLLECTOR'): log('REFUSE: FALLBACK_ONE_COLLECTOR present'); return 2 if SG.memavail() < 4200: log('REFUSE MemAvail', SG.memavail()); return 8 reexec_env(spec['label'].upper() + '_NICED') if spec['memterm'].exists(): spec['memterm'].rename(str(spec['memterm']) + '.prev_' + time.strftime('%Y%m%dT%H%M%S')) return run(spec, 'collect') if cmd == '--dry-run-ids': n = int(argv[1]); scratch = Path_(argv[argv.index('--scratch') + 1]) if '--scratch' in argv else Path_('/workspace/scratch/%s_dryrun_%s' % (spec['label'], time.strftime('%Y%m%dT%H%M%S'))) if not 1 <= n <= 20: log('REFUSE: --dry-run-ids must be 1..20'); return 2 if str(scratch.resolve()).startswith('/workspace/legal-corpora'): log('REFUSE: scratch must be outside legal-corpora'); return 2 if len(other_collectors()) >= 2: log('REFUSE: max two collectors running'); return 7 if SG.memavail() < 4200: log('REFUSE MemAvail', SG.memavail()); return 8 reexec_env(spec['label'].upper() + '_NICED'); return run(spec, 'dry', scratch=scratch, want=n) print(doc); return 1from pathlib import Path as Path_scrapers_and_normalizers/PROVENANCE_NATIONAL_OVERLAY.jsonAdded+5
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/archive_fallbacks.pyAdded+1366
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collect_bw.pyAdded+440
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/collector.pyAdded+958
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/common.pyAdded+573
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/pdf_extract_lib.pyAdded+336
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_lib.pyAdded+447
scrapers_and_normalizers/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/national_collectors/world_package.pyAdded+289
scrapers_and_normalizers/scripts/normalize_offline.pyAdded+104
scrapers_and_normalizers/scripts/pa_exit_guard.pyAdded+135
scrapers_and_normalizers/scripts/polite_collect_lib.pyAdded+220