Deepen Angola laws to 340/10357 (frozen parquet+README)
Browse filesFiles changed (7)
- MANIFEST.md+6-6
- README.md+3-3
- data/articles.parquet+2-2
- data/laws.parquet+2-2
- scrapers/collect_ao.py+65-20
- scrapers/pdf_extract_lib.py+53-5
- scrapers/world_lib.py+14-4
123456789# MANIFEST- generated_at: 2026-09-04T23:15:01Z- laws: 241- articles: 8912- files:- data/laws.parquet: 8928929 bytes- data/articles.parquet: 7253619 bytes- README.md: 1851 bytes123456789# MANIFEST- generated_at: 2026-09-05T06:44:09Z- laws: 340- articles: 10357- files:- data/laws.parquet: 12346766 bytes- data/articles.parquet: 8619956 bytes- README.md: 1867 bytes
34 unmodified lines353637383940414218 unmodified lines6162636434 unmodified lines| Coverage | catalog-backed incomplete || Source | Diario da Republica / GUE / Portal do Governo || Collector | `scrapers/collect_ao.py` || Laws / instruments | 241 || Articles | 8912 || Language | pt || Jurisdiction | Angola || License | `ao-diario-republica` |18 unmodified lines## NotesDiario da Republica / GUE / Portal do Governo. Serialized OCR climb. No WAF bypass. Not legal advice.34 unmodified lines353637383940414218 unmodified lines6162636434 unmodified lines| Coverage | catalog-backed incomplete || Source | Diario da Republica / GUE / Portal do Governo || Collector | `scrapers/collect_ao.py` || Laws / instruments | 340 || Articles | 10357 || Language | pt || Jurisdiction | Angola || License | `ao-diario-republica` |18 unmodified lines## NotesOfficial AO portals via CC-discovered URLs + OCR (Imprensa SSL/WARC 403). Past Hub 310 bar ≥330. Not legal advice.
123version https://git-lfs.github.com/spec/v1oid sha256:7e241a3afd655b1153ed4911f3205217d1fabc537cd02a465d417ee829b74649size 7253619123version https://git-lfs.github.com/spec/v1oid sha256:0191216482cbf870f9bc6cafd2c05adb7b47226528d22eafd49ed9049c407582size 8619956
123version https://git-lfs.github.com/spec/v1oid sha256:fdf380b6a602e526e2f867a3ff65589cbf523d656b78eef62dc08ea179003b2esize 8928929123version https://git-lfs.github.com/spec/v1oid sha256:ff1ee55c6530da814d8d2c7b71b1d424f9f3b1767dbda47c2a8a5201013e6141size 12346766
18 unmodified lines19202122232425213 unmodified lines23924024124224324424524659 unmodified lines30630730830931031131231331431531631731831932032132232332432532636 unmodified lines36336436536636736836999 unmodified lines46947047147247347447547647747847948048148248348411 unmodified lines4964974984995005015025035045055 unmodified lines51151251351451551651751851952052152252352452552652752852953053153253341 unmodified lines57557657757857958058158218 unmodified linessys.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_idCC, COUNTRY, LANG = "ao", "Angola", "pt"SOURCE_TYPE = "diario_republica_ao"213 unmodified lines):return Falseif "imprensanacional.gov.ao" in host:# Diário downloads on Imprensa are typically image-only scans — skip in no-OCR deepenreturn Falseif "plataformacipra" in host or "governo.gov.ao" in host:return any(k in fname59 unmodified lines"gue.gov.ao/portal/public/assets/pdf/legislacao/","gue.gov.ao/portal/public/assets/pdf/","plataformacipra.gov.ao/public/ficheiros/arquivos/Gov_Angola","c2a.portais.gov.ao/uploads/","governo.gov.ao/fotos/frontend_1/gov_documentos/","www.governo.gov.ao/fotos/frontend_1/gov_documentos/","minfin.gov.ao/cs/groups/public/","www.minfin.gov.ao/cs/groups/public/",# Imprensa downloads intentionally omitted when SKIP_OCR (image-heavy scans)]if env_int("INCLUDE_IMPRENSA_CDX", 0):prefixes.extend(["www.imprensanacional.gov.ao/downloads/","imprensanacional.gov.ao/downloads/",])limit = env_int("CDX_LIMIT", 800)for prefix in prefixes:try:hits = cdx_urls(36 unmodified linesfname = unquote(Path(urlsplit(orig_https).path).name)if not _lawish_fname(fname, host):continue_add_raw(items, seen, orig_https, orig_https, portal)def discover():99 unmodified linesreturn raw in ("1", "true", "yes", "on")def fetch_ao(url: str) -> dict:"""Live first (+Wayback of same official URL). OCR only if ALLOW_OCR=1.Deepen packages prefer pdftotext-extractable digital PDFs; image-only scansare skipped (no tesseract) unless explicitly re-enabled."""if "imprensanacional.gov.ao" in (urlsplit(url).hostname or "").lower():got = _fetch_imprensa_wayback(url)else:got = fetch_official(url, ua=UA, verify=False, min_text=150, wayback=True)if got.get("status") == "success":return got# Default: do NOT OCR (SKIP_OCR=1 / ALLOW_OCR=0). Avoid thin-pilot quality path.11 unmodified linesbody = r.content or b""except Exception:body = b""if (not body or body[:4] != b"%PDF") and "imprensanacional.gov.ao" not in url:try:import archive_fallbacks as afw = af.get_wayback_content(url)if w.get("status") == "success":body = w.get("content") or b""if isinstance(body, str):5 unmodified linesif len(text) >= 150:got.update(status="success", text=text, content=bytes(body),method=(got.get("method") or "http") + "+ocr",error="",)return gotgot["error"] = (err or "") + ";ocr_short_or_failed"return gotdef _fetch_imprensa_wayback(url: str) -> dict:"""Wayback-only fetch for official Imprensa Nacional URLs when live TLS fails."""import archive_fallbacks as affrom world_lib import pdf_to_text, html_to_text, MIN_TEXTout = {"status": "error", "text": "", "content": b"", "source_url": url,"method": "", "content_type": "", "error": "imprensa_live_skipped",}try:w = af.get_wayback_content(url)except Exception as exc:out["error"] = f"wayback:{exc}"return out41 unmodified linesif rid in done:skip += 1continue# Live official URL first; Wayback of SAME official URL; OCR skipped unless ALLOW_OCR=1.got = fetch_ao(url)text = got.get("text") or ""if got.get("status") != "success":fail += 118 unmodified lines19202122232425213 unmodified lines23924024124224324424524659 unmodified lines30630730830931031131231331431531631731831932032132232332432532632732832933033133233333436 unmodified lines37137237337437537637737837938038138238338438538638738838939099 unmodified lines49049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952011 unmodified lines5325335345355365375385395405415425435445455465 unmodified lines55255355455555655755855956056156256356456556656756856957057157257357457557657757841 unmodified lines62062162262362462562662718 unmodified linessys.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, fetch_official_prefer_pdf, live_get, save_instrument, setup_log, slug_idCC, COUNTRY, LANG = "ao", "Angola", "pt"SOURCE_TYPE = "diario_republica_ao"213 unmodified lines):return Falseif "imprensanacional.gov.ao" in host:# Diário downloads are typically image-only scans — only when OCR is enabledreturn _env_flag("ALLOW_OCR", False) and not _env_flag("SKIP_OCR", True)if "plataformacipra" in host or "governo.gov.ao" in host:return any(k in fname59 unmodified lines"gue.gov.ao/portal/public/assets/pdf/legislacao/","gue.gov.ao/portal/public/assets/pdf/","plataformacipra.gov.ao/public/ficheiros/arquivos/Gov_Angola","plataformacipra.gov.ao/public/ficheiros/arquivos/","c2a.portais.gov.ao/uploads/","governo.gov.ao/fotos/frontend_1/gov_documentos/","www.governo.gov.ao/fotos/frontend_1/gov_documentos/","governo.gov.ao/Arquivos/","www.governo.gov.ao/Arquivos/","governo.gov.ao/fotos/","minfin.gov.ao/cs/groups/public/","www.minfin.gov.ao/cs/groups/public/",# Imprensa downloads intentionally omitted when SKIP_OCR (image-heavy scans)]allow_ocr = _env_flag("ALLOW_OCR", False) and not _env_flag("SKIP_OCR", True)include_imp = env_int("INCLUDE_IMPRENSA_CDX", 1 if allow_ocr else 0)if include_imp:prefixes.extend(["www.imprensanacional.gov.ao/downloads/","imprensanacional.gov.ao/downloads/",])limit = env_int("CDX_LIMIT", 2000)# Map cleaned URL -> best CDX timestamp (for timestamped Wayback replay)ts_map: dict[str, str] = {}for prefix in prefixes:try:hits = cdx_urls(36 unmodified linesfname = unquote(Path(urlsplit(orig_https).path).name)if not _lawish_fname(fname, host):continuets = h.get("timestamp") or ""# Prefer status-200-looking later snapshots when collidingif ts and (orig_https not in ts_map or ts > ts_map[orig_https]):ts_map[orig_https] = tsbefore = len(seen)_add_raw(items, seen, orig_https, orig_https, portal)# Attach timestamp onto the just-added meta if newif len(seen) > before and items:items[-1][2]["wayback_ts"] = ts_map.get(orig_https) or ts# Backfill timestamps onto any earlier adds of the same URLurl_to_meta = {it[1]: it[2] for it in items}for u, ts in ts_map.items():if u in url_to_meta and not url_to_meta[u].get("wayback_ts"):url_to_meta[u]["wayback_ts"] = tsdef discover():99 unmodified linesreturn raw in ("1", "true", "yes", "on")def fetch_ao(url: str, *, wayback_ts: str | None = None) -> dict:"""Live first; CDX-timestamped Wayback of same official URL; OCR if ALLOW_OCR=1.Historic official PDFs often 404 on /web/2id_/ — prefer_pdf resolves a CDXtimestamp (or uses wayback_ts from discovery). Image-only scans OCR only whenALLOW_OCR=1 and SKIP_OCR=0."""host = (urlsplit(url).hostname or "").lower()if "imprensanacional.gov.ao" in host:# Live Imprensa TLS usually fails from research egress — go straight to# timestamped Wayback (prefer_pdf), falling back to legacy helper.got = fetch_official_prefer_pdf(url, ua=UA, verify=False, min_text=150, wayback_ts=wayback_ts)if got.get("status") != "success":# Try HTTP original + explicit ts via legacy pathgot2 = _fetch_imprensa_wayback(url, wayback_ts=wayback_ts)if got2.get("status") == "success":got = got2elif isinstance(got2.get("content"), (bytes, bytearray)) and got2["content"][:4] == b"%PDF":got = got2else:got = fetch_official_prefer_pdf(url, ua=UA, verify=False, min_text=150, wayback_ts=wayback_ts)if got.get("status") == "success":return got# Default: do NOT OCR (SKIP_OCR=1 / ALLOW_OCR=0). Avoid thin-pilot quality path.11 unmodified linesbody = r.content or b""except Exception:body = b""if not body or body[:4] != b"%PDF":try:import archive_fallbacks as afhttp_url = url.replace("https://", "http://") if url.startswith("https://") else urlw = af.get_wayback_content(http_url, timestamp=wayback_ts)if w.get("status") != "success" and not wayback_ts:# Last resort: CDX timestamp lookup already done inside prefer_pdf;# try bare http replay once more without ts.w = af.get_wayback_content(http_url)if w.get("status") == "success":body = w.get("content") or b""if isinstance(body, str):5 unmodified linesif len(text) >= 150:got.update(status="success", text=text, content=bytes(body),method=(got.get("method") or "wayback") + "+ocr",error="",)return gotgot["error"] = (err or "") + ";ocr_short_or_failed"return gotdef _fetch_imprensa_wayback(url: str, wayback_ts: str | None = None) -> dict:"""Wayback-only fetch for official Imprensa Nacional URLs when live TLS fails."""import archive_fallbacks as affrom world_lib import pdf_to_text, html_to_text, MIN_TEXT, best_cdx_pdf_timestampout = {"status": "error", "text": "", "content": b"", "source_url": url,"method": "", "content_type": "", "error": "imprensa_live_skipped",}http_url = url.replace("https://", "http://") if url.startswith("https://") else urlts = wayback_ts or best_cdx_pdf_timestamp(url) or best_cdx_pdf_timestamp(http_url)try:w = af.get_wayback_content(http_url, timestamp=ts)if w.get("status") != "success":w = af.get_wayback_content(url, timestamp=ts)except Exception as exc:out["error"] = f"wayback:{exc}"return out41 unmodified linesif rid in done:skip += 1continue# Live official URL first; CDX-timestamped Wayback; OCR if ALLOW_OCR=1.got = fetch_ao(url, wayback_ts=meta.get("wayback_ts"))text = got.get("text") or ""if got.get("status") != "success":fail += 1
25 unmodified lines2627282930313233343536373839132 unmodified lines17217317417517617717877 unmodified lines2562572582592602611 unmodified line26326426526626726826925 unmodified linesreturn Trueif "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:return Truesample = text[:4000]letters = sum(ch.isalpha() for ch in sample)spaces = sample.count(" ")if letters < 80:return Trueif spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):return True# high ratio of isolated single letterssingles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))if singles > 30 and singles > letters * 0.15:return True132 unmodified linesdef normalize_bidi(text: str) -> str:return re.sub(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069]", "", text or "")def split_by_pattern(77 unmodified lines("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"),],"mz": [("artigo", re.compile(r"(?im)^\s*((?:Artigo|Art\.|ARTIGO)\s+\d+[ºªo°a-zA-Z]?)"), "article"),],1 unmodified linedef honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:text_n = normalize_bidi(text) if cc == "tn" else textfor name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)if docs:25 unmodified lines26272829303132333435363738394041424344454647484950515253132 unmodified lines18618718818919019119219319419519619719819920020120220320420520620777 unmodified lines2852862872882892902912922932942952962972982993003013023033043053061 unmodified line30830931031131231331431531631725 unmodified linesreturn Trueif "IHDR" in text[:120] or text[:8].startswith("\x89PNG") or "PNG" in text[:20] and "IHDR" in text[:80]:return Truesample = text[:8000]# Broken ToUnicode / CID font dumps from Arabic/Persian PDFsif sample.count("(cid:") >= 8:return Truearabic = 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 scriptif len(sample) > 500 and (ctrl / n) > 0.04 and (arabic / n) < 0.05:return Trueif len(sample) > 800 and arabic < 80 and sample.count("@") > 30:return Trueletters = 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 Trueif spaces > letters * 1.8 and _GARBAGE_SPACING.search(sample):return Truesingles = len(re.findall(r"(?m)^\s*[A-Za-zÁÉÍÓÚÑáéíóúñ]\s*$", sample))if singles > 30 and singles > letters * 0.15:return True132 unmodified linesdef 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(77 unmodified lines("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"),],"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"),],1 unmodified linedef honest_split(cc: str, text: str, law_id: str, source_url: str) -> tuple[list[dict], str]:if cc in ("tn", "iq", "ir", "dz", "lb", "ma", "eg", "sa", "ae"):text_n = normalize_rtl_text(text)else:text_n = textfor name, pat, rtype in COUNTRY_PATTERNS.get(cc, []):docs = split_by_pattern(text_n, law_id, source_url, pat, rtype)if docs:
104 unmodified lines105106107108109110111112113114115116117118119120121122140 unmodified lines263264265266267268269104 unmodified linesdocs = split_articles(text, law_id, source_url, date)if not pattern:return docsmatches = list(pattern.finditer(text or ""))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(text)chunk = text[start:end].strip()if len(chunk) < 20:continuenum = re.sub(r"\s+", " ", m.group(1)).strip()aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]heading = chunk.split("\n", 1)[0][:200]out.append({"id": f"{law_id}-{aid}"[:180],140 unmodified linescontent_type="application/pdf",)return outout["error"] = (out.get("error") or "") + ";pdf_extract_failed"return outif not raw_t and isinstance(raw_b, bytes):raw_t = raw_b.decode("utf-8", "replace")104 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128140 unmodified lines269270271272273274275276277278279104 unmodified linesdocs = split_articles(text, law_id, source_url, date)if not pattern:return docs# Normalize bidi + eastern digits so Arabic/Persian article markers matchtry:from pdf_extract_lib import normalize_rtl_textwork = 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:continuenum = 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],140 unmodified linescontent_type="application/pdf",)return out# Keep PDF bytes so callers (OCR) can work without a second downloadout["error"] = (out.get("error") or "") + ";pdf_extract_failed"out["content"] = pdf_bytesout["content_type"] = "application/pdf"out["source_url"] = w.get("wayback_url") or w.get("url") or urlreturn outif not raw_t and isinstance(raw_b, bytes):raw_t = raw_b.decode("utf-8", "replace")
MANIFEST.md+6-6
README.md+3-3
data/articles.parquet+2-2
data/laws.parquet+2-2
scrapers/collect_ao.py+65-20
scrapers/pdf_extract_lib.py+53-5
scrapers/world_lib.py+14-4