Refresh Gambia densify (94 laws / 3997 articles; was 80/670; Commonwealth splitter; official .gov.gm)
Browse filesFiles changed (7)
- MANIFEST.md+8-8
- README.md+4-4
- data/articles.parquet+2-2
- data/laws.parquet+2-2
- scrapers/archive_fallbacks.py+69-22
- scrapers/collect_gm.py+305-32
- scrapers/world_lib.py+14-1
1234567891011121314151617181920# ipfs_gambia_laws manifestgenerated_utc: 2026-09-09T10:14:12Zcc: gmlaws_rows: 80articles_rows: 670laws_bytes: 2649252articles_bytes: 1747393laws_sha256: 53c05035dfba196c4648322efadce34d7422cd2654277a8392c73728908dd189articles_sha256: 7535ae3c054549d84195d74593c90460505391d4d6f5fdf83d7ad68c462aa971laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_gambia_laws/data/laws.parquetarticles_parquet: /workspace/legal-corpora/hf-staging/ipfs_gambia_laws/data/articles.parquetcompression: zstdcollector: scrapers/collect_gm.pylicense: Republic of The Gambia — assembly.gov.gm / moj.gov.gm / justice.gov.gm / judiciary.gov.gm. Authentic Official Gazette / Act text prevails. Not legal advice.retrieval: live-and-wayback-of-officiallive_instruments: 80archive_instruments: 0wayback_instruments: 0common_crawl_instruments: 01234567891011121314151617181920# ipfs_gambia_laws manifestgenerated_utc: 2026-09-10T05:06:35Zcc: gmlaws_rows: 94articles_rows: 3997laws_bytes: 1790381articles_bytes: 1677667laws_sha256: 6b769c334a5fbc8cf2ea345df9e98a075829d2a4462b805c266e9022c48d0dbfarticles_sha256: 3fcc6d4a8666bcd7051d4de9ff54826cf27da9b30f902f579a99ea86317fb816laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_gambia_laws/data/laws.parquetarticles_parquet: /workspace/legal-corpora/hf-staging/ipfs_gambia_laws/data/articles.parquetcompression: zstdcollector: scrapers/collect_gm.pylicense: Republic of The Gambia — assembly.gov.gm / moj.gov.gm / justice.gov.gm / judiciary.gov.gm. Authentic Official Gazette / Act text prevails. Not legal advice.retrieval: live-and-wayback-of-officiallive_instruments: 94archive_instruments: 0wayback_instruments: 0common_crawl_instruments: 0
17 unmodified lines1819202122232412 unmodified lines37383940414243444546474817 unmodified lines- acts- official-textssize_categories:- n<1Kconfigs:- config_name: lawsdata_files: data/laws.parquet12 unmodified lines| Field | Value || --- | --- || Snapshot date | 2026-09-09 || Coverage | catalog-backed incomplete (assembly/justice/judiciary/moj live + CDX Acts/gazettes PDFs) || Source | National Assembly (assembly.gov.gm / nationalassembly.gov.gm) / MoJ (moj.gov.gm / justice.gov.gm) / Judiciary (judiciary.gov.gm) / State House / Office of the President / other *.gov.gm gazette hosts || Collector | `scrapers/collect_gm.py` || Laws / instruments | 80 || Articles | 670 || Language | en || Jurisdiction | Gambia || License | `gm-assembly-justice-judiciary-official-texts` |17 unmodified lines1819202122232412 unmodified lines37383940414243444546474817 unmodified lines- acts- official-textssize_categories:- 1K<n<10Kconfigs:- config_name: lawsdata_files: data/laws.parquet12 unmodified lines| Field | Value || --- | --- || Snapshot date | 2026-09-10 || Coverage | catalog-backed incomplete (assembly/justice/judiciary/moj live + CDX Acts/gazettes PDFs) || Source | National Assembly (assembly.gov.gm / nationalassembly.gov.gm) / MoJ (moj.gov.gm / justice.gov.gm) / Judiciary (judiciary.gov.gm) / State House / Office of the President / other *.gov.gm gazette hosts || Collector | `scrapers/collect_gm.py` || Laws / instruments | 94 || Articles | 3,997 || Language | en || Jurisdiction | Gambia || License | `gm-assembly-justice-judiciary-official-texts` |
123version https://git-lfs.github.com/spec/v1oid sha256:7535ae3c054549d84195d74593c90460505391d4d6f5fdf83d7ad68c462aa971size 1747393123version https://git-lfs.github.com/spec/v1oid sha256:3fcc6d4a8666bcd7051d4de9ff54826cf27da9b30f902f579a99ea86317fb816size 1677667
123version https://git-lfs.github.com/spec/v1oid sha256:53c05035dfba196c4648322efadce34d7422cd2654277a8392c73728908dd189size 2649252123version https://git-lfs.github.com/spec/v1oid sha256:6b769c334a5fbc8cf2ea345df9e98a075829d2a4462b805c266e9022c48d0dbfsize 1790381
287 unmodified lines2882892902912922932942952962977 unmodified lines3053063073083093103113123133143153163173183191 unmodified line321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375287 unmodified linesreturn out[:target]def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:"""Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here)."""import subprocess7 unmodified linesctype = ""final_url = targetstatus = 0for attempt in range(1, 4):_sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))try:# Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)proc = subprocess.run(["curl", "-fsS", "--max-time", "90","-A", UA,"-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}","--output", "-",target,],1 unmodified linetimeout=100,)raw = proc.stdout or b""# Trailer is text appended after body when -w is used with --output -# With --output -, -w goes to stdout after body. Split on trailer markers.marker = b"\n__HTTP_STATUS__"if marker in raw:body, rest = raw.rsplit(marker, 1)trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)status = int(mstat.group(1)) if mstat else 0ctype = (mctype.group(1) if mctype else "") or ""final_url = (murl.group(1) if murl else target) or targetelse:body = rawstatus = 200 if proc.returncode == 0 and raw else 0if proc.returncode != 0 and not body:last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"log.info("wayback replay curl fail %s: %s", url, last_err)continueif status in (403, 429, 503, 502, 504) and attempt < 3:log.info("wayback replay HTTP %s %s attempt=%s", status, url, attempt)continuebreakexcept Exception as exc:last_err = str(exc)log.info("wayback replay fail %s: %s", url, exc)continueelse:# fallback: requests without following redirects to httpstry:r = session().get(target, timeout=(20, 90), allow_redirects=False)status = r.status_codebody = r.content or b""ctype = r.headers.get("content-type") or ""final_url = r.url or targetif status in (301, 302, 303, 307, 308):loc = r.headers.get("Location") or ""if loc.startswith("https://web.archive.org/"):loc = "http://" + loc[len("https://"):]if loc.startswith("http://web.archive.org/"):r2 = session().get(loc, timeout=(20, 90), allow_redirects=False)status = r2.status_codebody = r2.content or b""ctype = r2.headers.get("content-type") or ""final_url = r2.url or locexcept requests.RequestException as exc:return {"status": "error", "error": last_err or str(exc), "url": url}if not body and status != 200:return {"status": "error", "error": last_err or f"http_{status}", "url": url}cap_ts = timestamp or ""m = re.search(r"/web/(\d{14})", final_url or "")287 unmodified lines2882892902912922932942952962972982993007 unmodified lines3083093103113123133143153163173183193203213223233243253261 unmodified line328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422287 unmodified linesreturn out[:target]def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:"""Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).Follow 3xx Location only after rewriting https://web.archive.org → http://.Redirect hops do not consume the HTTP retry budget."""import subprocess7 unmodified linesctype = ""final_url = targetstatus = 0redirects_left = 8attempts_left = 5first = Truewhile attempts_left > 0:_sleep_wayback(0.35 if not first and redirects_left < 8 else (0.8 if first else min(8.0, 1.8 * (6 - attempts_left))))first = Falsetry:# Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)proc = subprocess.run(["curl", "-sS", "--max-time", "90","-A", UA,"-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}\n__REDIRECT_URL__%{redirect_url}","--output", "-",target,],1 unmodified linetimeout=100,)raw = proc.stdout or b""marker = b"\n__HTTP_STATUS__"redirect_url = ""if marker in raw:body, rest = raw.rsplit(marker, 1)trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)mredir = re.search(r"__REDIRECT_URL__([^\n]*)", trailer)status = int(mstat.group(1)) if mstat else 0ctype = (mctype.group(1) if mctype else "") or ""final_url = (murl.group(1) if murl else target) or targetredirect_url = (mredir.group(1) if mredir else "") or ""else:body = rawstatus = 200 if proc.returncode == 0 and raw else 0if status in (301, 302, 303, 307, 308):loc = (redirect_url or "").strip()if loc.startswith("/"):loc = "http://web.archive.org" + locif loc.startswith("https://web.archive.org/"):loc = "http://" + loc[len("https://"):]if loc.startswith("http://web.archive.org/") and redirects_left > 0:log.info("wayback replay follow HTTP redirect %s -> %s", status, loc[:120])target = locfinal_url = locredirects_left -= 1continue # redirect hop: do not consume attempts_leftlast_err = f"http_{status}_bad_redirect"log.info("wayback replay HTTP %s bad redirect %s", status, (loc or "")[:160])attempts_left -= 1continueif proc.returncode != 0 and not body:last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"log.info("wayback replay curl fail %s: %s", url, last_err)attempts_left -= 1continueif status in (403, 429, 503, 502, 504) and attempts_left > 1:log.info("wayback replay HTTP %s %s attempts_left=%s", status, url, attempts_left)attempts_left -= 1continuebreakexcept Exception as exc:last_err = str(exc)log.info("wayback replay fail %s: %s", url, exc)attempts_left -= 1continueelse:# fallback: requests without following redirects to httpstry:hops = 0while hops < 8:r = session().get(target, timeout=(20, 90), allow_redirects=False)status = r.status_codebody = r.content or b""ctype = r.headers.get("content-type") or ""final_url = r.url or targetif status not in (301, 302, 303, 307, 308):breakloc = (r.headers.get("Location") or "").strip()if loc.startswith("/"):loc = "http://web.archive.org" + locif loc.startswith("https://web.archive.org/"):loc = "http://" + loc[len("https://"):]if not loc.startswith("http://web.archive.org/"):last_err = f"http_{status}_bad_redirect"breaktarget = locfinal_url = lochops += 1except requests.RequestException as exc:return {"status": "error", "error": last_err or str(exc), "url": url}if (not body and status != 200) or status == 404:# /2id_/ sometimes lands on a missing capture; pick an explicit CDX 200 snapshot.if not timestamp:try:hits = search_wayback_machine(url, limit=5, filter_status="200", collapse="digest")for hit in hits:ts = hit.get("timestamp") or ""orig = hit.get("original") or urlif not ts:continuealt = get_wayback_content(orig, timestamp=ts)if alt.get("status") == "success" and (alt.get("content") or b""):return alt# also try original host/path casing from CDXexcept Exception as exc:log.info("wayback cdx retry after http_%s: %s", status, exc)return {"status": "error", "error": last_err or f"http_{status}", "url": url}cap_ts = timestamp or ""m = re.search(r"/web/(\d{14})", final_url or "")
11 unmodified lines121314151617181920211 unmodified line2324252627282930313233343536375 unmodified lines434445464748495051525354555657585960616263646566676869707172737436 unmodified lines11111211311411511611711811964 unmodified lines18418518618718818919019119240 unmodified lines23323423523623723823948 unmodified lines2882892902912922932942952962973 unmodified lines30130230330430530630723 unmodified lines3313323333343353363373383393403413423433443453463473483493503513523533543553563573 unmodified lines3613623633643653663 unmodified lines3703713723733743753763773786 unmodified lines38538638738838939039139239339439539639739811 unmodified linesNOT GambiaLII / AfricanLII / commercial DBs as source text.No WAF bypass. Skip PDFs >12MB. Not legal advice."""from __future__ import annotationsimport loggingimport reimport sysimport time1 unmodified linefrom urllib.parse import urljoin, urlsplit, unquotesys.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 = "gm", "Gambia", "en"5 unmodified lines"President / other *.gov.gm gazette hosts. Authentic Official Gazette / Act text ""prevails. Not GambiaLII as LII source text. Not AfricanLII. Not legal advice.")UA = "legal-corpora-collector/1.0 (research; source=https://assembly.gov.gm/)"ART = re.compile(r"(?im)^\s*((?:Article|Art\.?|Section|Sec\.?|Cap\.?|Chapter|Part)\s*[0-9]+)\b")log = logging.getLogger("gm")HOMES = ["https://assembly.gov.gm/","https://www.assembly.gov.gm/","https://nationalassembly.gov.gm/","https://www.nationalassembly.gov.gm/","https://www.moj.gov.gm/","https://moj.gov.gm/","https://www.justice.gov.gm/","https://justice.gov.gm/","https://www.attorneygeneral.gov.gm/","https://attorneygeneral.gov.gm/","https://judiciary.gov.gm/","https://www.judiciary.gov.gm/","https://www.statehouse.gov.gm/","https://statehouse.gov.gm/","https://www.op.gov.gm/","https://op.gov.gm/","https://www.gov.gm/","https://gov.gm/","https://www.mofea.gov.gm/","https://mofea.gov.gm/","https://www.gra.gov.gm/","https://gra.gov.gm/",36 unmodified linesMAX_PDF_BYTES = 12 * 1024 * 1024SEED_PDFS = [# Common National Assembly / ministry Act PDF paths (may 404; CDX fills catalog)"https://assembly.gov.gm/wp-content/uploads/2021/12/Constitution-of-the-Republic-of-The-Gambia-1997.pdf","https://www.assembly.gov.gm/wp-content/uploads/2021/12/Constitution-of-the-Republic-of-The-Gambia-1997.pdf",]CDX_PREFIXES = (64 unmodified linesif url.startswith("http://"):url = "https://" + url[len("http://") :]url = re.sub(r"(https?://[^/:]+):80/", r"\1/", url)return urldef discover():"""Return list of (ident, url, wayback_ts|None). Live homes + CDX PDFs."""items = [] # (priority, ident, url, ts)40 unmodified linesitems.append((priority, ident, url, ts))for seed in SEED_PDFS:add(seed, ts=None, priority=5)for home in HOMES:try:48 unmodified linest0 = utcnow()max_new = env_int("MAX_NEW", 80)max_seconds = env_int("MAX_SECONDS", 2400)t_start = time.time()done = existing_ids(CC)already = len(done)target_total = env_int("TARGET_TOTAL", 0)ok = skip = fail = 0for ident, url, ts in discover():if max_new and ok >= max_new:3 unmodified linesif time.time() - t_start > max_seconds:breakrid = slug_id(CC, ident)if rid in done:skip += 1continuegot = fetch_official(url, ua=UA, min_text=200, wayback_ts=ts, verify=False)23 unmodified lines},)continuetitle = Nonefor line in text.splitlines():if len(line.strip()) > 18:title = line.strip()[:240]breakif save_instrument(cc=CC,country=COUNTRY,language=LANG,ident=ident,title=title or ident,text=text,source_url=url,source_type=SOURCE_TYPE,license_text=LICENSE,collector="collect_gm.py",article_re=ART,extra_meta={"fetch_method": got.get("method"), "wayback_ts": ts},):ok += 1done.add(rid)log.info("ok %s method=%s chars=%s ts=%s",ident[:60],3 unmodified lines)else:fail += 1write_summary(CC,country=COUNTRY,3 unmodified lines"justice.gov.gm / judiciary.gov.gm / statehouse.gov.gm / gov.gm)"),source_urls=["https://assembly.gov.gm/","https://nationalassembly.gov.gm/","https://www.moj.gov.gm/","https://www.justice.gov.gm/","https://judiciary.gov.gm/","https://www.statehouse.gov.gm/",6 unmodified linesfetched=ok,skipped=skip,failed=fail,coverage="catalog-backed incomplete (PDF-first CDX *.gov.gm + live probes)",notes=("Official *.gov.gm PDFs only. Not GambiaLII/AfricanLII as source text. ""No WAF bypass. Not legal advice."),last_run=t0,)log.info("done ok=%s skip=%s fail=%s total_instruments=%s", ok, skip, fail, len(done))if __name__ == "__main__":11 unmodified lines121314151617181920212223242526271 unmodified line29303132333435363738394041424344454647484950515253545 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212336 unmodified lines16016116216316416516616716864 unmodified lines23323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943040 unmodified lines47147247347447547647747848 unmodified lines5275285295305315325335345355365375385395405415425435445455465475485495505513 unmodified lines55555655755855956056156223 unmodified lines5865875885895905915925935945955965975985996006016026036046056066073 unmodified lines6116126136146156166176186196206216226236246256266276283 unmodified lines6326336346356366376386396406 unmodified lines64764864965065165265365465565665765865966066166266366466566666766866967067111 unmodified linesNOT GambiaLII / AfricanLII / commercial DBs as source text.No WAF bypass. Skip PDFs >12MB. Not legal advice.Densify: Gambia Acts use Commonwealth ``1. Short title.`` section numbering(not only ``Section N``). Prefer enacting body after ``BE IT ENACTED`` / TOC(ug/mu/na/sl pattern) to avoid double-counting arrangement schedules."""from __future__ import annotationsimport jsonimport loggingimport osimport reimport sysimport time1 unmodified linefrom urllib.parse import urljoin, urlsplit, unquotesys.path.insert(0, str(Path(__file__).resolve().parent))from common import (INDEX_FIELDS,ROOT,atomic_write,base_record,existing_ids,log_failure,utcnow,write_instrument,write_summary,)from world_lib import (cdx_urls,env_int,fetch_official,first_title,live_get,setup_log,slug_id,split_custom,)CC, COUNTRY, LANG = "gm", "Gambia", "en"5 unmodified lines"President / other *.gov.gm gazette hosts. Authentic Official Gazette / Act text ""prevails. Not GambiaLII as LII source text. Not AfricanLII. Not legal advice.")UA = "legal-corpora-collector/1.0 (research; source=https://www.moj.gov.gm/)"# Commonwealth body: "1. Short title." / "12A. Interpretation." PLUS classic Section/ArticleART = re.compile(r"(?im)^\s*((?:Article|Art\.?|Section|Sec\.?|Cap\.?|Chapter|Part)\s*[0-9]+[A-Za-z]?|"r"\d+[A-Za-z]?\.)(?=\s*(?:[A-Z\"'(]|In |This |These |The |For ))")ART_ONLY = re.compile(r"(?im)^\s*((?:Article|Art\.?)\s+[0-9]+[A-Za-z]?)\b")ACT_TEXT_RE = re.compile(r"(?i)(?:BE IT ENACTED|ARRANGEMENT OF SECTIONS|STATUTORY INSTRUMENTS?|"r"SUPPLEMENT No\.|Act No\.|This Act may be cited|Short title|"r"I assent|Date of commencement|AN ACT\b|A BILL\b|"r"THE\s+[A-Z][A-Z0-9 \-',()]{6,90}\s+ACT,?\s*\d{4})")ACT_URL_RE = re.compile(r"(?i)(?:_act\.pdf|act\.pdf|act%20|/acts?/|constitution|statutory|gazette|"r"wp-content/uploads|sites/default/files)")JUNK_RE = re.compile(r"(?i)annual.?report|strategic.?plan|press.?release|speech|budget.?speech|"r"workshop|seminar|brochure|flyer|vacancy|tender|procurement|"r"manifesto|powerpoint|\bppt\b|newsletter|progress.?report|"r"implementation.?plan|monitoring.?tool|white.?paper.?on.?the.?recommendations|"r"aid.?bulletin|audit.?report|sentinel.?surveillance|climate.?financing|"r"windstorm|urban.?tran?sport|mrc.?the.?gambia|national.?commitment.?for.?education|"r"pfm.?annual|pfm.?cc|abridged.?version.?of.?the.?rf|concession.?contracts|"r"lawreport|sharia.?law.?report|recommendation.?for.?acting|"r"job.?description|confirmation.?form|surety.?bond|personnel.?procedures|"r"directory of government|communique|ict profile|policy statement|"r"broadband (policy|strategy)|cybersecurity (policy|strategy)|e-government|"r"civil service reform|application.?form|scholarship.?form|"r"cadre|biodata|facts.?and.?figures|scheme.?of.?service|action.?plan|"r"health.?compact|mtds|resilience.?inclusion|covid-19.?impacts|"r"employment.?policy|judgment_|swearing.?in")log = logging.getLogger("gm")HOMES = ["https://moj.gov.gm/","https://judiciary.gov.gm/","https://www.statehouse.gov.gm/","https://www.mofea.gov.gm/","https://assembly.gov.gm/","https://www.assembly.gov.gm/","https://nationalassembly.gov.gm/","https://www.nationalassembly.gov.gm/","https://www.justice.gov.gm/","https://justice.gov.gm/","https://www.attorneygeneral.gov.gm/","https://attorneygeneral.gov.gm/","https://www.judiciary.gov.gm/","https://statehouse.gov.gm/","https://www.op.gov.gm/","https://op.gov.gm/","https://www.gov.gm/","https://gov.gm/","https://mofea.gov.gm/","https://www.gra.gov.gm/","https://gra.gov.gm/",36 unmodified linesMAX_PDF_BYTES = 12 * 1024 * 1024SEED_PDFS = ["https://assembly.gov.gm/wp-content/uploads/2021/12/Constitution-of-the-Republic-of-The-Gambia-1997.pdf","https://www.assembly.gov.gm/wp-content/uploads/2021/12/Constitution-of-the-Republic-of-The-Gambia-1997.pdf","https://www.moj.gov.gm/",]CDX_PREFIXES = (64 unmodified linesif url.startswith("http://"):url = "https://" + url[len("http://") :]url = re.sub(r"(https?://[^/:]+):80/", r"\1/", url)url = re.sub(r"(https?://[^/:]+):80(/|$)", r"\1\2", url)return urldef prefer_enacting_body(text: str) -> str:"""Skip arrangement/TOC so article split targets operative sections."""if not text:return textm = re.search(r"(?is)BE IT ENACTED[^\n]*\n", text)if m and m.end() < len(text) - 200:rest = text[m.end() :]arr = re.search(r"(?i)ARRANGEMENT OF (?:SECTIONS|RULES|ORDERS)", rest[:2500])if not arr:return resttext = restbody_ones = list(re.finditer(r"(?im)^\s*1\.\s*(?:This Act|In this Act|These Regulations|These regulations|"r"Unless the context|For the purposes)\b",text,))if body_ones:return text[body_ones[-1].start() :] if len(body_ones) >= 2 else text[body_ones[0].start() :]ones = list(re.finditer(r"(?im)^\s*1\.\s*(?:Short title|Citation|Interpretation|Definitions)\b",text,))if len(ones) >= 2:return text[ones[1].start() :]if len(ones) == 1:arr = re.search(r"(?i)ARRANGEMENT OF", text)if arr and ones[0].start() > arr.start():return text[ones[0].start() :]m = re.search(r"(?i)ARRANGEMENT OF (?:SECTIONS|RULES|ORDERS)|Arrangement of Sections", text)if m:after = text[m.end() :]body = list(re.finditer(r"(?im)^\s*1\.\s*(?:Short title|Citation|Interpretation|Definitions|"r"This Act|In this Act|The Republic)\b",after,))if len(body) >= 2:return after[body[-1].start() :]if len(body) == 1:# single post-TOC "1. …" may still be TOC line; prefer CHAPTER I secondpasschapters = list(re.finditer(r"(?im)^\s*CHAPTER\s+I\b", text))if len(chapters) >= 2:return text[chapters[1].start() :]parts = list(re.finditer(r"(?im)^\s*PART\s+I\b", after))if len(parts) >= 2:return after[parts[1].start() :]if body:return after[body[0].start() :]return textdef split_gm_articles(text: str, rid: str, source_url: str, date=None) -> list:"""Commonwealth ``1. Title.`` body split by default; constitutions prefer Article N."""body = prefer_enacting_body(text)docs_sec = split_custom(body, rid, source_url, date, ART)docs_art = split_custom(body, rid, source_url, date, ART_ONLY)blob = f"{rid}|{source_url}"is_const = bool(re.search(r"(?i)constitution", blob)) and not bool(re.search(r"(?i)amm?endment", blob))if is_const:if len(docs_art) >= 20:return docs_artif len(docs_art) >= 2 and len(docs_sec) > max(20, len(docs_art) * 3):return docs_artif len(docs_art) < 2:# Gambia 1997 reprints use bare ``1. The Republic`` (not Article N)return docs_sec if docs_sec else docs_artif len(docs_art) >= 50 and len(docs_art) > len(docs_sec) * 1.2:return docs_artreturn docs_secdef save_gm_instrument(*,ident: str,title: str,text: str,source_url: str,extra_meta: dict | None = None,) -> bool:if not text or len(text) < 80:return Falserid = slug_id(CC, ident)docs = split_gm_articles(text, rid, source_url, None)meta = {"fetch_method": (extra_meta or {}).get("fetch_method"),"article_split": "commonwealth-body",}if extra_meta:meta.update(extra_meta)rec = base_record(cc=CC,country=COUNTRY,language=LANG,ident=ident,title=title or first_title(text, ident),text=text,source_url=source_url,source_type=SOURCE_TYPE,license_text=LICENSE,collector="collect_gm.py",documents=docs,extra_meta=meta,)write_instrument(CC, rec)return Truedef _is_act_like(rec: dict, name: str) -> bool:text = rec.get("text") or ""blob = f"{name}|{rec.get('title') or ''}|{rec.get('source_url') or ''}|{text[:3000]}"if JUNK_RE.search(blob) and not ACT_TEXT_RE.search(blob):return Falsereturn bool(ACT_TEXT_RE.search(blob)or (ACT_URL_RE.search(blob) and ACT_TEXT_RE.search(text[:8000])))def reprocess_existing() -> int:"""Re-split articles on Act-like instruments with Commonwealth section regex."""inst = ROOT / CC / "instruments"improved = 0for p in sorted(inst.glob("*.json")):try:rec = json.loads(p.read_text(encoding="utf-8"))except Exception:continuetext = rec.get("text") or ""if len(text) < 200:continueif not _is_act_like(rec, p.name):continuerid = rec.get("id") or p.stemurl = rec.get("source_url") or ""date = rec.get("date")docs = split_gm_articles(text, rid, url, date)old = int(rec.get("article_count") or len(rec.get("documents") or []) or 0)new = len(docs)if new <= old and old > 0:continueif new < 2 and old >= new:continuerec["documents"] = docsrec["article_count"] = newrec["article_extraction_status"] = "ok" if docs else "missing"meta = rec.get("metadata") or {}meta["article_reprocess"] = "collect_gm.py-commonwealth-sections"meta["article_split"] = "commonwealth-body"rec["metadata"] = metaatomic_write(p, json.dumps(rec, ensure_ascii=False, indent=2) + "\n")improved += 1log.info("reprocess %s %s->%s", rid[:70], old, new)return improveddef rebuild_index() -> int:inst = ROOT / CC / "instruments"rows = []for p in sorted(inst.glob("*.json")):try:rec = json.loads(p.read_text(encoding="utf-8"))except Exception:continueline = {k: rec.get(k) for k in INDEX_FIELDS if k not in ("path", "bytes", "article_count")}line["path"] = f"instruments/{p.name}"line["article_count"] = rec.get("article_count") or len(rec.get("documents") or [])line["bytes"] = p.stat().st_sizeline["id"] = rec.get("id") or p.stemrows.append(line)out = ROOT / CC / "index.jsonl"atomic_write(out, "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))log.info("rebuilt index lines=%s", len(rows))return len(rows)def discover():"""Return list of (ident, url, wayback_ts|None). Live homes + CDX PDFs."""items = [] # (priority, ident, url, ts)40 unmodified linesitems.append((priority, ident, url, ts))for seed in SEED_PDFS:if seed.rstrip("/").endswith(".pdf") or ".pdf" in seed.lower():add(seed, ts=None, priority=5)for home in HOMES:try:48 unmodified linest0 = utcnow()max_new = env_int("MAX_NEW", 80)max_seconds = env_int("MAX_SECONDS", 2400)do_reprocess = os.environ.get("REPROCESS", "1") not in ("0", "false", "no")if do_reprocess:n = reprocess_existing()log.info("reprocess improved=%s", n)t_start = time.time()done = existing_ids(CC)already = len(done)target_total = env_int("TARGET_TOTAL", 0)have_urls = set()for p in (ROOT / CC / "instruments").glob("*.json"):try:u = _norm_url(json.loads(p.read_text(encoding="utf-8")).get("source_url") or "")if u:have_urls.add(u.lower())except Exception:passok = skip = fail = 0for ident, url, ts in discover():if max_new and ok >= max_new:3 unmodified linesif time.time() - t_start > max_seconds:breakrid = slug_id(CC, ident)nu = _norm_url(url).lower()if rid in done or nu in have_urls:skip += 1continuegot = fetch_official(url, ua=UA, min_text=200, wayback_ts=ts, verify=False)23 unmodified lines},)continuetitle = first_title(text, ident)blob = f"{ident}|{title}|{url}|{text[:2500]}"if JUNK_RE.search(blob) and not ACT_TEXT_RE.search(blob):skip += 1log.info("skip junk post-fetch %s", ident[:60])continueif save_gm_instrument(ident=ident,title=title,text=text,source_url=_norm_url(url),extra_meta={"fetch_method": got.get("method"), "wayback_ts": ts},):ok += 1done.add(rid)have_urls.add(nu)log.info("ok %s method=%s chars=%s ts=%s",ident[:60],3 unmodified lines)else:fail += 1rebuild_index()arts = 0n_inst = 0for p in (ROOT / CC / "instruments").glob("*.json"):try:rec = json.loads(p.read_text(encoding="utf-8"))except Exception:continuen_inst += 1arts += int(rec.get("article_count") or len(rec.get("documents") or []) or 0)write_summary(CC,country=COUNTRY,3 unmodified lines"justice.gov.gm / judiciary.gov.gm / statehouse.gov.gm / gov.gm)"),source_urls=["https://www.moj.gov.gm/","https://assembly.gov.gm/","https://nationalassembly.gov.gm/","https://www.justice.gov.gm/","https://judiciary.gov.gm/","https://www.statehouse.gov.gm/",6 unmodified linesfetched=ok,skipped=skip,failed=fail,coverage=("catalog-backed incomplete (PDF-first CDX *.gov.gm + live probes; ""commonwealth section densify)"),notes=(f"Official *.gov.gm PDFs only. Commonwealth 1. Section split + enacting-body prefer. "f"instruments={n_inst} articles={arts}. Not GambiaLII/AfricanLII as source text. "f"No WAF bypass. Not legal advice."),last_run=t0,)log.info("done ok=%s skip=%s fail=%s total_instruments=%s articles=%s",ok,skip,fail,n_inst,arts,)if __name__ == "__main__":
216 unmodified lines217218219220221222223224225226227228229230231216 unmodified linestext=text,content=pdf_bytes,method="wayback_pdf",source_url=w.get("url") or url,content_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")if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"return outtext = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t216 unmodified lines217218219220221222223224225226227228229230231232233234235236237238239240241242243244216 unmodified linestext=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 caller can OCR (image-only / bad text layer)out.update(content=pdf_bytes,content_type="application/pdf",method="wayback_pdf_bytes",source_url=w.get("wayback_url") or w.get("url") or url,)out["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")if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:# Treat as PDF bytes for OCR upstreampdf_bytes = raw_b if isinstance(raw_b, bytes) else raw_t.encode("latin-1", "replace")if isinstance(pdf_bytes, bytes) and b"%PDF" in pdf_bytes[:8192]:if pdf_bytes[:4] != b"%PDF":pdf_bytes = pdf_bytes[pdf_bytes.find(b"%PDF"):]out.update(content=pdf_bytes, content_type="application/pdf", method="wayback_pdf_bytes")out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"return outtext = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
MANIFEST.md+8-8
README.md+4-4
data/articles.parquet+2-2
data/laws.parquet+2-2
scrapers/archive_fallbacks.py+69-22
scrapers/collect_gm.py+305-32
scrapers/world_lib.py+14-1