diff --git a/scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.py b/scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0359561f45fce8bfedd4e015ce35474323178a --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.py @@ -0,0 +1,64 @@ +# AT: RIS OGD API v2.6 Judikatur (keyless, CC BY 4.0). 0.5 req/s, only weekdays 12:00-21:00 America/Los_Angeles (box tz); sleeps outside window. +import sys,os,time,datetime,requests,lxml.html;sys.path.insert(0,'/workspace/caselaw/scrapers/common') +from guard import * +B='/workspace/caselaw'; API='https://data.bka.gv.at/ris/api/v2.6/Judikatur'; OUT=B+'/staging/ipfs_austria_caselaw'; LOG=B+'/logs/at_ris.log' +LIC='CC BY 4.0 (RIS OGD, Bundeskanzleramt Österreich, data.gv.at)' +APPS=['Vfgh','Vwgh','Justiz','Bvwg','Lvwg','Dsk','Gbk','Pvak','Umse','Bks','Verg','Ubas','Dok'] +os.makedirs(OUT,exist_ok=True); st=State(OUT+'/state.json',{'page':{},'done_apps':[]}) +H={'User-Agent':'justicedao-caselaw-research/1.0 (polite 0.5 req/s)'}; last=[0.0] +def in_window(): + n=datetime.datetime.now(); return n.weekday()<5 and 12<=n.hour<21 +def wait_window(): + while not in_window(): + log(LOG,'outside window, paused'); time.sleep(600) +def get(u,params=None): + for a in range(6): + wait_window(); dt=time.time()-last[0] + if dt<2.0: time.sleep(2.0-dt) + last[0]=time.time() + try: + r=requests.get(u,params=params,headers=H,timeout=60) + if 'Security Check' in r.text[:3000]: log(LOG,'WAF page, stopping (no bypass)',u); sys.exit(4) + if r.status_code in(429,503): time.sleep(60*(a+1)); continue + r.raise_for_status(); return r + except requests.RequestException as e: log(LOG,'retry',a,u,e); time.sleep(20*(a+1)) + return None +def L(x): return x if isinstance(x,list) else ([] if x is None else [x]) +def items(x): return [i for i in L(x.get('item') if isinstance(x,dict) else x)] if x else [] +for app in APPS: + if app in st.d['done_apps']: continue + cfg='at_'+app.lower(); w=PartWriter(f'{OUT}/{cfg}',cfg,st,cfg); page=st.d['page'].get(app,0) + while True: + ok,m,d=guard_ok() + if not ok: log(LOG,'GUARD STOP',app,page,m,d); sys.exit(3) + r=get(API,{'Applikation':app,'DokumenteProSeite':'OneHundred','Seitennummer':page+1}) + if r is None: log(LOG,'list failed',app,page); sys.exit(5) + res=r.json()['OgdSearchResult'] + refs=L(res.get('OgdDocumentResults',{}).get('OgdDocumentReference')) + if not refs: break + for ref in refs: + D=ref['Data']; M=D['Metadaten']; T=M['Technisch']; A=M.get('Allgemein',{}); J=M.get('Judikatur',{}) + urls=L(D.get('Dokumentliste',{}).get('ContentReference')); hu=None + for cr in urls: + if cr.get('ContentType')=='MainDocument': + for cu in L(cr['Urls']['ContentUrl']): + if cu['DataType']=='Html': hu=cu['Url'] + txt=None + if hu: + hr=get(hu) + if hr is not None: + try: txt=lxml.html.fromstring(hr.content).text_content() + except Exception: txt=None + gz=J.get('Geschaeftszahl'); gz='; '.join(map(str,items(gz))) if isinstance(gz,dict) else gz + row=dict(jurisdiction='AT',court=T.get('Organ') or app,config=cfg,ecli=J.get('EuropeanCaseLawIdentifier'),court_id=None,chamber=None, + date=J.get('Entscheidungsdatum'),number=gz,title=None,text=txt,source_url=hu or A.get('DokumentUrl'),licence=LIC,licence_flag='attribution_required', + is_archive=False,archive_name=None,retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(), + ris_id=T.get('ID'),ris_app=app,doc_type=J.get('Dokumenttyp'),published=A.get('Veroeffentlicht'),changed=A.get('Geaendert'), + normen='; '.join(map(str,items(J.get('Normen')))),schlagworte=J.get('Schlagworte')) + if w.add(row): w.flush(); log(LOG,app,'page',page,'rows',st.d['rows'][cfg]) + page+=1; st.d['page'][app]=page + if page%5==0: log(LOG,app,'page',page) + # state page only advances with flushed rows: flush on page boundary when buffer big enough handled above; persist page after flush + if not w.buf: st.save() + w.flush(); st.d['done_apps'].append(app); st.save(); log(LOG,'app done',app,st.d['rows'][cfg]) +st.d['done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows']) diff --git a/scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.py b/scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0992a96c707b78f350069cb9861ca455ec28b4 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.py @@ -0,0 +1,74 @@ +"""AU decisions from isaacus/open-australian-legal-corpus@ef45e3f (keyless). Streams corpus.jsonl with HTTP Range resume. +Decisions only. HCA -> au_hca (non-commercial, kept separate). FCA -> au_fca. NSW skipped (blocked_needs_benjamin). zstd parquet, 2000-row parts.""" +import os,sys,json,time,shutil,logging,datetime,requests,pyarrow as pa,pyarrow.parquet as pq +REV='ef45e3fec41a960919a31149eee6dab9aa39f725' +URL=f'https://huggingface.co/datasets/isaacus/open-australian-legal-corpus/resolve/{REV}/corpus.jsonl' +BASE='/workspace/caselaw/staging/ipfs_australia_caselaw'; ST=BASE+'/state.json' +DISK=10.5e9; MEM=4.2e9; BATCH=2000 +MAP={'federal_court_of_australia':'au_fca','high_court_of_australia':'au_hca'} +SKIP={'nsw_caselaw':'blocked_needs_benjamin'} +LIC={'au_fca':'Federal Court of Australia copyright (https://www.fedcourt.gov.au/copyright): judgments may be reproduced unaltered incl. commercially, acknowledged as decisions of the Court, source acknowledged; corpus compilation CC BY 4.0 (Isaacus open-australian-legal-corpus)', + 'au_hca':'NON-COMMERCIAL: High Court of Australia copyright (https://www.hcourt.gov.au/disclaimers/copyright): unaltered reproduction for personal, non-commercial or in-organisation use only, retain HCA notice; corpus compilation CC BY 4.0 (Isaacus)'} +os.makedirs(BASE,exist_ok=True) +logging.basicConfig(filename='/workspace/caselaw/logs/au_oalc.log',level=logging.INFO,format='%(asctime)s %(message)s') +def guard(): + free=shutil.disk_usage('/workspace').free + m=int([l for l in open('/proc/meminfo') if l.startswith('MemAvailable')][0].split()[1])*1024 + if free=BATCH: flush_all(pos) + tries=0 + if rest.strip(): pos+=len(rest) # last line without newline + if rest.strip(): + d=json.loads(rest) + if d.get('type')=='decision' and d.get('source') in MAP: c=MAP[d['source']]; buf[c].append(row(d,c)) + off=pos; break + except SystemExit: raise + except Exception as e: + tries+=1; logging.info('ERR %s retry %d from committed offset %d',e,tries,st['offset']) + buf={c:[] for c in MAP.values()}; pend_skip.clear(); off=st['offset'] + if tries>10: logging.info('giving up'); sys.exit(1) + time.sleep(min(600,10*2**tries)) +flush_all(off); st['done']=True; save(); logging.info('DONE rows=%s skipped=%s',st['rows'],st['skipped']) diff --git a/scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.py b/scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..de56c9be0886450806a23ab49138c823d1026113 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.py @@ -0,0 +1,45 @@ +# CA: a2aj/canadian-case-law (public HF, keyless). Stage-only. Resumable. +import sys,os,time,datetime;sys.path.insert(0,'/workspace/caselaw/scrapers/common') +from guard import * +import guard; guard.DISK_STOP=20e9 # CoS: CA pauses (resumable) below 20G free +import pyarrow.parquet as pq +from huggingface_hub import HfApi,hf_hub_download +B='/workspace/caselaw'; REPO='a2aj/canadian-case-law'; OUT=B+'/staging/ipfs_canada_caselaw'; LOG=B+'/logs/ca_a2aj.log' +st=State(OUT+'/state.json',{'done_courts':[],'offset':{}}); os.makedirs(OUT,exist_ok=True) +api=HfApi(token=False); rev=st.d.setdefault('revision',api.dataset_info(REPO).sha); st.save() +courts=sorted({f.split('/')[0] for f in api.list_repo_files(REPO,repo_type='dataset',revision=rev) if f.endswith('train.parquet')}) +log(LOG,'start rev',rev,'courts',len(courts),'done',len(st.d['done_courts'])) +def lic_flag(l): + l=(l or '').lower(); f=[] + if 'non-commercial' in l or 'noncommercial' in l or 'non commercial' in l: f.append('non_commercial') + if 'artificial intelligence' in l or ' ai ' in l or 'machine learning' in l: f.append('ai_terms_check') + return ';'.join(f) or 'see_upstream_license' +for c in courts: + if c in st.d['done_courts']: continue + ok,m,d=guard_ok() + if not ok: log(LOG,'GUARD STOP before',c,m,d); sys.exit(3) + p=hf_hub_download(REPO,f'{c}/train.parquet',repo_type='dataset',revision=rev,token=False,cache_dir=B+'/work/ca_hfcache') + cfg='ca_'+c.lower(); w=PartWriter(f'{OUT}/{cfg}',cfg,st,cfg); off=st.d['offset'].get(c,0); i=0 + pf=pq.ParquetFile(p,buffer_size=1<<20,pre_buffer=False) + now=datetime.datetime.now(datetime.timezone.utc).isoformat() + for b in pf.iter_batches(batch_size=200): + for r in b.to_pylist(): + i+=1 + if i<=off: continue + lic=r.get('upstream_license') + row=dict(jurisdiction='CA',court=c,config=cfg,ecli=None,court_id=None,chamber=None, + date=str(r.get('document_date_en') or r.get('document_date_fr') or '')[:10] or None, + number=r.get('citation_en') or r.get('citation_fr'),title=r.get('name_en') or r.get('name_fr'), + text=r.get('unofficial_text_en') or r.get('unofficial_text_fr'), + source_url=r.get('url_en') or r.get('url_fr'),licence=('A2AJ compilation MIT; upstream: '+(lic or '')),licence_flag=lic_flag(lic), + is_archive=False,archive_name=None,retrieved_at=now,source_dataset=f'{REPO}@{rev}') + for k,v in r.items(): + if k.startswith(('citation','name_','url_','unofficial_text','document_date','scraped')): row['a2aj_'+k]=v + row['a2aj_cases_cited_en']=r.get('cases_cited_en'); row['a2aj_citing_cases_count']=r.get('citing_cases_count') + if w.add(row): + w.flush(lambda: st.d['offset'].__setitem__(c,i)); log(LOG,c,'rows',i,'total',sum(st.d['rows'].values())) + ok,m,d=guard_ok() + if not ok: log(LOG,'GUARD STOP',c,i,m,d); sys.exit(3) + w.flush(lambda: st.d['offset'].__setitem__(c,i)); st.d['done_courts'].append(c); st.save() + os.remove(os.path.realpath(p)); log(LOG,'done',c,i) +st.d['done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows']) diff --git a/scrapers_and_normalizers/caselaw/scrapers/common/guard.py b/scrapers_and_normalizers/caselaw/scrapers/common/guard.py new file mode 100644 index 0000000000000000000000000000000000000000..bb03216a8ede12f248076d8e0c5b2eaf57193bba --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/common/guard.py @@ -0,0 +1,39 @@ +import os +os.environ.setdefault("MALLOC_ARENA_MAX","2") # memsafe default for all caselaw collectors +import json,shutil,time,datetime,pyarrow as pa,pyarrow.parquet as pq +def _gb(v): + v=float(v); return v*1e9 if v<1e6 else v # accept GB (3.2) or bytes (3.2e9) +MEM_STOP=_gb(os.environ.get("CASELAW_MEM_STOP","3.2")) # stop below 3.2G MemAvailable +DISK_STOP=_gb(os.environ.get("CASELAW_DISK_STOP","20.0")) # stop below 20G free disk +def mem_avail(): + for l in open('/proc/meminfo'): + if l.startswith('MemAvailable:'): return int(l.split()[1])*1024 +def guard_ok(): + m=mem_avail(); d=shutil.disk_usage('/workspace').free + return (m>=MEM_STOP and d>=DISK_STOP), m, d +def log(path,*a): + with open(path,'a') as f: f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')+' '.join(map(str,a))+'\n') +class State: + def __init__(s,path,default): + s.path=path; s.d=json.load(open(path)) if os.path.exists(path) else default + def save(s): + t=s.path+'.tmp'; json.dump(s.d,open(t,'w'),indent=1); os.replace(t,s.path) +class PartWriter: + """2000-row zstd parquet parts; all columns string except bools.""" + def __init__(s,outdir,prefix,state,key): + os.makedirs(outdir,exist_ok=True); s.outdir=outdir; s.prefix=prefix; s.st=state; s.key=key; s.buf=[] + s.st.d.setdefault('parts',{}).setdefault(key,0); s.st.d.setdefault('rows',{}).setdefault(key,0) + def add(s,row): + s.buf.append(row) + return len(s.buf)>=2000 + def flush(s,extra_state=None): + if not s.buf: + if extra_state: extra_state(); s.st.save() + return + n=s.st.d['parts'][s.key]; p=f'{s.outdir}/{s.prefix}.part{n:05d}.parquet' + cols=sorted({k for r in s.buf for k in r}) + t=pa.table({c:pa.array([None if r.get(c) is None else (r[c] if isinstance(r[c],bool) else str(r[c])) for r in s.buf]) for c in cols}) + pq.write_table(t,p+'.tmp',compression='zstd'); os.replace(p+'.tmp',p) + s.st.d['parts'][s.key]=n+1; s.st.d['rows'][s.key]+=len(s.buf); s.buf=[] + if extra_state: extra_state() + s.st.save() diff --git a/scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.py b/scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.py new file mode 100644 index 0000000000000000000000000000000000000000..7529a28383e732a3d1963c197b5fdaba3dad1a17 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.py @@ -0,0 +1,99 @@ +"""ipfs_datasets_py-backed case-law normalizer (JusticeDAO world_law caselaw scrapers). + +Normalizes staged case-law parquet rows into the shared world_law caselaw schema: + * standard core fields always present (string-typed, nullable) so HF `load_dataset` + streaming never hits null-type/schema-cast failures across parts; + * `licence`, `licence_flag`, `flag` columns; source provenance (`source_host`, + `source_dataset`, `normalizer`), `country`, `legal_branch`; + * `court_id` linkage (Courthouse-scraper ids where a mapping is supplied); + * a deterministic `doc_id` (sha256 of config+source_url/number+text prefix). +Uses ipfs_datasets_py.processors.legal_data.canonical_legal_corpora (from +/workspace/ipfs_datasets_py_latest or an installed ipfs_datasets_py) to tag the legal +branch and to refuse targets that are Caselaw Access Project corpora (CAP exclusion). +No network access, no secrets. +""" +import os, sys, hashlib +import pyarrow as pa +IPFS_DATASETS_PATH = os.environ.get("IPFS_DATASETS_PY_PATH", "/workspace/ipfs_datasets_py_latest") +if os.path.isdir(IPFS_DATASETS_PATH) and IPFS_DATASETS_PATH not in sys.path: + sys.path.insert(0, IPFS_DATASETS_PATH) +try: + from ipfs_datasets_py.processors.legal_data import canonical_legal_corpora as _clc +except Exception: # pragma: no cover - library optional at read time + _clc = None + +NORMALIZER_VERSION = "caselaw-normalize/1.0" +CORE = ["doc_id", "country", "jurisdiction", "config", "court", "court_id", "chamber", "date", + "number", "ecli", "title", "text", "source_url", "source_host", "source_dataset", + "licence", "licence_flag", "flag", "retrieved_at", "legal_branch", "normalizer"] +BOOL = {"is_archive"} + +def ipfs_datasets_available(): + return _clc is not None + +def assert_not_cap(dataset_id): + """Refuse to (re)publish anything ipfs_datasets_py maps to the Caselaw Access Project.""" + if _clc is None: + return + try: + c = _clc.infer_canonical_legal_corpus_for_dataset_id(dataset_id) + if c and c.key == "caselaw_access_project": + raise ValueError(f"{dataset_id} maps to CAP; excluded by policy") + except KeyError: + pass + except ValueError as e: + if "CAP" in str(e): raise + +def legal_branch(dataset_id): + if _clc is not None: + try: + return _clc.infer_canonical_legal_corpus_for_dataset_id(dataset_id).normalized_branch() or "caselaw" + except Exception: + pass + return "caselaw" + +def _doc_id(cfg, r): + key = "|".join(str(r.get(k) or "") for k in ("source_url", "number", "ris_id", "date")) + "|" + str(r.get("text") or "")[:2000] + return hashlib.sha256(f"{cfg}|{key}".encode("utf-8", "replace")).hexdigest() + +def normalize_table(t, *, dataset_id, config, country, source_host, source_dataset, + licence=None, licence_flag=None, flags=None, court_ids=None): + """Return a normalized pyarrow Table. `flags`: list (aligned to rows) of flag str/None. + `court_ids`: dict court-name -> Courthouse court_id (optional linkage).""" + assert_not_cap(dataset_id) + branch = legal_branch(dataset_id) + rows = t.to_pylist() + if flags is not None and len(flags) != len(rows): + raise ValueError("flags length mismatch") + out = [] + for i, r in enumerate(rows): + r = dict(r) + r.setdefault("config", config); r["config"] = r.get("config") or config + r["country"] = country + r["source_host"] = r.get("source_host") or source_host + r["source_dataset"] = r.get("source_dataset") or source_dataset + if licence and not r.get("licence"): r["licence"] = licence + if licence_flag and not r.get("licence_flag"): r["licence_flag"] = licence_flag + if flags is not None: r["flag"] = flags[i] + if court_ids and not r.get("court_id"): r["court_id"] = court_ids.get(r.get("court")) + r["legal_branch"] = branch; r["normalizer"] = NORMALIZER_VERSION + r["doc_id"] = _doc_id(config, r) + out.append(r) + cols = CORE + sorted({k for r in out for k in r} - set(CORE)) + arrs = {} + for c in cols: + if c in BOOL: + arrs[c] = pa.array([r.get(c) for r in out], pa.bool_()) + else: + arrs[c] = pa.array([None if r.get(c) is None else str(r.get(c)) for r in out], pa.string()) + return pa.table(arrs) + +if __name__ == "__main__": + import argparse, pyarrow.parquet as pq + ap = argparse.ArgumentParser(description="Normalize one staged caselaw parquet file") + for a in ("src", "dst", "--dataset-id", "--config", "--country", "--source-host", "--source-dataset", "--licence", "--licence-flag"): + ap.add_argument(a) + x = ap.parse_args() + tb = normalize_table(pq.read_table(x.src), dataset_id=x.dataset_id, config=x.config, country=x.country, + source_host=x.source_host, source_dataset=x.source_dataset, licence=x.licence, licence_flag=x.licence_flag) + pq.write_table(tb, x.dst, compression="zstd"); print(x.dst, tb.num_rows, "ipfs_datasets_py:", ipfs_datasets_available()) diff --git a/scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.py b/scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..09db7d4f0bd712725f1c5bcbf9a640a8589453c3 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.py @@ -0,0 +1,67 @@ +"""DE Rechtsprechung im Internet collector -> zstd parquet staging. Text only, 0.5 req/s, resumable.""" +import os,io,re,sys,json,time,zipfile,shutil,datetime,logging +import requests,lxml.etree as ET,lxml.html as LH,pyarrow as pa,pyarrow.parquet as pq +OUT='/workspace/caselaw/staging/ipfs_germany_caselaw/de_bund'; ST='/workspace/caselaw/staging/ipfs_germany_caselaw/state.json' +TOC='https://www.rechtsprechung-im-internet.de/rii-toc.xml'; UA='justicedao-caselaw-research/0.1 (Benjamin Barber; 0.5 req/s)' +LIC='Free use and re-use (rechtsprechung-im-internet.de, BMJ/BfJ); attribution: Rechtsprechung im Internet' +DISK=10.5e9; MEM=4.2e9; BATCH=2000; GAP=2.0 +logging.basicConfig(filename='/workspace/caselaw/logs/de_rii.log',level=logging.INFO,format='%(asctime)s %(message)s') +os.makedirs(OUT,exist_ok=True); S=requests.Session(); S.headers['User-Agent']=UA; last=[0.0] +def get(u): + for a in range(8): + w=GAP-(time.time()-last[0]); time.sleep(max(0,w)); last[0]=time.time() + try: + r=S.get(u,timeout=120) + if r.status_code==200: return r.content + if r.status_code in (403,429) or b'captcha' in r.content[:5000].lower(): logging.info('BLOCK %s %s',r.status_code,u); sys.exit(3) + logging.info('HTTP %s %s',r.status_code,u) + if r.status_code==404: return None + except Exception as e: logging.info('ERR %s %s',u,e) + time.sleep(min(600,5*2**a)) + return None +def guards(): + while True: + free=shutil.disk_usage('/workspace').free + if free=MEM: return + logging.info('MEM GUARD %.2fG wait',m/1e9); time.sleep(60) +def txt(el): + if el is None: return '' + s=ET.tostring(el,encoding='unicode',method='html') + try: return LH.fromstring('
'+s+'
').text_content().strip() + except Exception: return '' +def parse(b,link): + z=zipfile.ZipFile(io.BytesIO(b)); x=[n for n in z.namelist() if n.endswith('.xml')][0] + d=ET.fromstring(z.read(x),ET.XMLParser(load_dtd=False,no_network=True,resolve_entities=False)) + g=lambda t:(d.findtext(t) or '').strip() + parts=[] + for t,h in [('leitsatz','Leitsatz'),('sonstosatz','Orientierungssatz'),('tenor','Tenor'),('tatbestand','Tatbestand'),('entscheidungsgruende','Entscheidungsgründe'),('gruende','Gründe'),('abwmeinung','Abweichende Meinung'),('sonstlt','Sonstiger Langtext')]: + v=txt(d.find(t)) + if v: parts.append(h+'\n'+v) + dt=g('entsch-datum'); dt=f'{dt[:4]}-{dt[4:6]}-{dt[6:8]}' if len(dt)==8 else dt + court=(g('gertyp')+' '+g('spruchkoerper')).strip() + return dict(ecli=g('ecli') or None,jurisdiction='de',court=court,chamber=g('spruchkoerper') or None,date=dt,number=g('aktenzeichen'), + title=txt(d.find('titelzeile')) or (g('doktyp')+' '+g('aktenzeichen')).strip(),text='\n\n'.join(parts),source_url=link, + archive_name=None,is_archive=False,licence=LIC,retrieved_at=datetime.datetime.utcnow().isoformat()+'Z',court_id=None, + rii_doknr=g('doknr'),doctype=g('doktyp'),norm=g('norm'),config='de_bund') +def save(st): + t=ST+'.tmp'; json.dump(st,open(t,'w')); os.replace(t,ST) +def flush(rows,st): + if not rows: return + fn=f'{OUT}/de_bund.part{st["part"]:05d}.parquet'; tmp=fn+'.tmp' + pq.write_table(pa.Table.from_pylist(rows),tmp,compression='zstd'); os.replace(tmp,fn) + st['part']+=1; st['rows']+=len(rows); st['done']=st['pending']; save(st); logging.info('wrote %s rows=%d total=%d',fn,len(rows),st['rows']) +def main(): + st=json.load(open(ST)) if os.path.exists(ST) else {'part':0,'rows':0,'done':0} + toc=get(TOC); links=[re.sub('^http:','https:',l.decode()) for l in re.findall(rb'([^<]+)',toc)] + logging.info('toc %d items, resume at %d',len(links),st['done']); rows=[] + for i in range(st['done'],len(links)): + guards(); b=get(links[i]) + if b: + try: rows.append(parse(b,links[i])) + except Exception as e: logging.info('PARSE %s %s',links[i],e) + st['pending']=i+1 + if len(rows)>=BATCH: flush(rows,st); rows=[] + st['pending']=len(links); flush(rows,st); st['done']=len(links); save(st); logging.info('DONE rows=%d',st['rows']) +main() diff --git a/scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.py b/scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3355785e7e6bd4b165684c7e813c4acaf7b5a5 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.py @@ -0,0 +1,159 @@ +"""Streaming adapter for DILA open-data case-law dumps (CASS, CAPP, JADE, CONSTIT, INCA). +Streams .tar.gz over HTTPS (verify on), parses XML members on the fly; never writes archives. +Usage: python adapter.py --fond CASS --archive --out DIR [--limit N] + python adapter.py --full --out DIR --state state.json (resumable, guarded) +""" +import argparse, datetime as dt, json, os, re, shutil, sys, tarfile, time +import requests +from lxml import etree + +BASE = "https://echanges.dila.gouv.fr/OPENDATA/" +UA = "JusticeDAO-caselaw-collector/0.1 (open-data research; ipfs_datasets_py)" +FONDS = {"CASS": "fr_cass", "CAPP": "fr_capp", "JADE": "fr_jade", "CONSTIT": "fr_constit", "INCA": "fr_inca"} +PAUSE = 2.0 +S = requests.Session(); S.headers["User-Agent"] = UA + +def guard(min_mem_gb=4.2, min_disk_gb=10.5, path="/workspace"): + mem = int(re.search(r"MemAvailable:\s+(\d+)", open("/proc/meminfo").read()).group(1)) / 1024**2 + disk = shutil.disk_usage(path).free / 1024**3 + return mem >= min_mem_gb and disk >= min_disk_gb, mem, disk + +def list_archives(fond): + time.sleep(PAUSE) + r = S.get(f"{BASE}{fond}/", timeout=60, verify=True); r.raise_for_status() + return sorted(set(re.findall(r'href="([^"]+\.tar\.gz)"', r.text))) + +def _t(root, *paths): + for p in paths: + v = root.findtext(p) + if v: return v.strip() + return None + +def parse(xml_bytes, fond, url, archive): + root = etree.fromstring(xml_bytes) + meta = ".//META_JURI" + text_el = root.find(".//CONTENU") + text = " ".join(text_el.itertext()).strip() if text_el is not None else None + return { + "ecli": _t(root, ".//ECLI"), + "jurisdiction": "FR", + "court": _t(root, f"{meta}/JURIDICTION"), + "chamber": _t(root, ".//FORMATION"), + "date": _t(root, f"{meta}/DATE_DEC"), + "number": _t(root, f"{meta}/NUMERO", ".//NUMEROS_AFFAIRES/NUMERO_AFFAIRE"), + "title": _t(root, f"{meta}/TITRE"), + "text": text, + "source_url": url, "archive_name": archive, "is_archive": False, + "licence": "Licence Ouverte 2.0", + "retrieved_at": dt.datetime.now(dt.timezone.utc).isoformat(), + "court_id": None, "dila_id": _t(root, ".//META_COMMUN/ID"), "config": FONDS[fond], + } + +class ResumableRaw: + """File-like over an HTTP body; on IncompleteRead/reset reopens with Range from the current + byte offset (server sends Accept-Ranges: bytes), up to `retries` times with backoff.""" + def __init__(self, url, retries=5): + self.url, self.retries, self.pos, self.r = url, retries, 0, None + self._open() + def _open(self): + h = {"Range": f"bytes={self.pos}-"} if self.pos else {} + time.sleep(PAUSE) + self.r = S.get(self.url, stream=True, timeout=120, verify=True, headers=h) + self.r.raise_for_status() + if self.pos and self.r.status_code != 206: + self.r.close(); raise IOError(f"server ignored Range at {self.pos}") + self.r.raw.decode_content = False + def read(self, n=-1): + for attempt in range(self.retries + 1): + try: + b = self.r.raw.read(n); self.pos += len(b); return b + except Exception as e: + if attempt >= self.retries: raise + wait = min(300, 10 * 2 ** attempt) + print(f"stream error at byte {self.pos}: {type(e).__name__}: {str(e)[:160]}; retry {attempt+1}/{self.retries} in {wait}s (Range)", flush=True) + try: self.r.close() + except Exception: pass + time.sleep(wait) + try: self._open() + except Exception as e2: print(f"reopen failed: {e2}", flush=True) + def close(self): + try: self.r.close() + except Exception: pass + +def stream(fond, archive): + url = f"{BASE}{fond}/{archive}" + raw = ResumableRaw(url) + try: + with tarfile.open(fileobj=raw, mode="r|gz") as tf: + for m in tf: + if m.isfile() and m.name.endswith(".xml"): + try: yield parse(tf.extractfile(m).read(), fond, url, archive) + except etree.XMLSyntaxError: continue + finally: raw.close() + +def write_parquet(rows, path): + import pyarrow as pa, pyarrow.parquet as pq + pq.write_table(pa.Table.from_pylist(rows), path, compression="zstd") + +def existing_ids(base): + import glob, pyarrow.parquet as pq + ids = set() + for f in glob.glob(f"{base}.*parquet"): + ids.update(x for x in pq.read_table(f, columns=["dila_id"]).column(0).to_pylist() if x) + return ids + +def save_state(st, path): + tmp = path + ".tmp"; json.dump(st, open(tmp, "w")); os.replace(tmp, path) + +def full(out, state_path, check_every=180, batch=2000): + st = json.load(open(state_path)) if os.path.exists(state_path) else {"done": []} + st.setdefault("failed", {}); run = dt.datetime.now().strftime("r%Y%m%d%H%M") + print(f"run {run} start; done={len(st['done'])} failed={len(st['failed'])}", flush=True) + last = 0 + for fond, cfg in FONDS.items(): + os.makedirs(f"{out}/{cfg}", exist_ok=True) + for a in list_archives(fond): + key = f"{fond}/{a}" + if key in st["done"]: continue + rows, part, total, skipped = [], 0, 0, 0 + base = f"{out}/{cfg}/{a.replace('.tar.gz','')}" + seen = existing_ids(base) # partial output from an interrupted run: skip by dila_id + if seen: print(f"{key}: {len(seen)} ids already staged; new parts tagged .{run}.", flush=True) + pfx = f"{base}.{run}.part" # run id in name: never overwrites earlier parts + try: + for rec in stream(fond, a): + if rec["dila_id"] and rec["dila_id"] in seen: skipped += 1; continue + rows.append(rec) + if len(rows) >= batch: + write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows); part += 1; rows = [] + if time.time() - last > check_every: + ok, mem, disk = guard(); last = time.time() + print(f"guard mem={mem:.1f}G disk={disk:.1f}G", flush=True) + if not ok: + if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet") + print("GUARD STOP", flush=True); sys.exit(3) + if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows) + except Exception as e: + if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows) + st["failed"][key] = {"error": f"{type(e).__name__}: {str(e)[:300]}", "run": run, "rows_written": total} + save_state(st, state_path) + print(f"FAILED {key} rows={total}: {type(e).__name__}: {str(e)[:200]}; continuing", flush=True) + continue + st["done"].append(key); st["failed"].pop(key, None); save_state(st, state_path) + print(f"done {key} rows={total} skipped_existing={skipped} parts={part + (1 if rows else 0)}", flush=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--fond"); ap.add_argument("--archive"); ap.add_argument("--out", required=True) + ap.add_argument("--limit", type=int, default=20); ap.add_argument("--full", action="store_true") + ap.add_argument("--state") + a = ap.parse_args() + ok, mem, disk = guard() + if not ok: sys.exit(f"ABORT: MemAvailable={mem:.2f}G disk={disk:.1f}G below thresholds") + if a.full: full(a.out, a.state) + else: + rows = list(stream(a.fond, a.archive)) + write_parquet(rows, f"{a.out}/sample.parquet") + with open(f"{a.out}/preview.jsonl", "w") as f: + for r in rows[:a.limit]: f.write(json.dumps({**r, "text": (r["text"] or "")[:500]}, ensure_ascii=False) + "\n") + print(f"records={len(rows)}") diff --git a/scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.py b/scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..1888637beb3a4d4305fe627b33e673b97ae41d39 --- /dev/null +++ b/scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.py @@ -0,0 +1,54 @@ +# IN: AWS Open Data indian-supreme-court-judgments (CC-BY-4.0), keyless S3 HTTPS. PDFs streamed, text extracted in-memory, never stored. +import sys,os,io,re,json,time,tarfile,subprocess,datetime,requests;sys.path.insert(0,'/workspace/caselaw/scrapers/common') +from guard import * +import pyarrow.parquet as pq +B='/workspace/caselaw'; S3='https://indian-supreme-court-judgments.s3.amazonaws.com'; OUT=B+'/staging/ipfs_india_caselaw'; LOG=B+'/logs/in_aws.log' +LIC='CC-BY-4.0 (AWS Open Data: indian-supreme-court-judgments, from ecourts/SCI)' +os.makedirs(OUT,exist_ok=True); st=State(OUT+'/state.json',{'done':[],'members_done':{}}) +H={'User-Agent':'justicedao-caselaw-research/1.0'} +def get(u,**k): + for a in range(6): + try: + r=requests.get(u,headers=H,timeout=120,**k); r.raise_for_status(); return r + except Exception as e: log(LOG,'retry',a,u,e); time.sleep(10*(a+1)) + raise RuntimeError(u) +years=list(range(1950,datetime.date.today().year+1)) +w=PartWriter(OUT+'/in_sc','in_sc',st,'in_sc') +for y in years: + key=f'{y}/english' + if key in st.d['done']: continue + ok,m,d=guard_ok() + if not ok: log(LOG,'GUARD STOP',y,m,d); sys.exit(3) + try: idx=get(f'{S3}/data/tar/year={y}/english/english.index.json').json() + except Exception: log(LOG,'no index',y); st.d['done'].append(key); st.save(); continue + meta={} + try: + t=pq.read_table(io.BytesIO(get(f'{S3}/metadata/parquet/year={y}/metadata.parquet').content)) + for r in t.drop_columns([c for c in ['raw_html'] if c in t.schema.names]).to_pylist(): meta[r.get('path')]=r + except Exception as e: log(LOG,'no meta',y,e) + done=set(st.d['members_done'].get(key,[])) + for part in idx.get('parts',[{'name':'english.tar'}]): + u=f"{S3}/data/tar/year={y}/english/{part['name']}" + r=get(u,stream=True); tf=tarfile.open(fileobj=r.raw,mode='r|') + for mem in tf: + if not mem.isfile() or not mem.name.lower().endswith('.pdf'): continue + nm=os.path.basename(mem.name) + if nm in done: continue + data=tf.extractfile(mem).read() + try: txt=subprocess.run(['pdftotext','-enc','UTF-8','-layout','-','-'],input=data,capture_output=True,timeout=120).stdout.decode('utf-8','replace') + except Exception as e: txt=None; log(LOG,'pdftotext fail',nm,e) + del data + pth=re.sub(r'_EN\.pdf$','',nm,flags=re.I); md=meta.get(pth,{}) + row=dict(jurisdiction='IN',court='Supreme Court of India',config='in_sc',ecli=None,court_id=None,chamber=None, + date=md.get('decision_date'),number=md.get('case_id') or md.get('citation'),title=md.get('title'),text=txt, + source_url=f'{u}#{nm}',licence=LIC,licence_flag='attribution_required',is_archive=False,archive_name=part['name'], + retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),pdf_member=nm,text_extraction='pdftotext', + **{'in_'+k:v for k,v in md.items() if k not in('title','year')}) + done.add(nm) + if w.add(row): + w.flush(lambda: st.d['members_done'].__setitem__(key,sorted(done))); log(LOG,y,'rows total',st.d['rows']['in_sc']) + ok,m,d=guard_ok() + if not ok: log(LOG,'GUARD STOP',y,m,d); sys.exit(3) + r.close() + w.flush(lambda: st.d['members_done'].__setitem__(key,sorted(done))); st.d['done'].append(key); st.d['members_done'].pop(key,None); st.save(); log(LOG,'year done',y,len(done)) +st.d['all_done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows']) diff --git a/scrapers_and_normalizers/courts/collector/archive_resume.py b/scrapers_and_normalizers/courts/collector/archive_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..bd43ec82ffa49681185570ebd2c380b9de90014b --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/archive_resume.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Resume CC archive recovery from state: cached CDX per state, skip URLs already staged. Stage only.""" +import sys,os,json,re,datetime +sys.path.insert(0,'/workspace/courts/collector') +import archive_rules as A +from us_fed import log,sid,now +O=A.O;ST=O+'/resume_state.json';C=O+'/cdx_cache' +os.makedirs(C,exist_ok=True) +def save(s):json.dump(s,open(ST+'.tmp','w'),indent=1);os.replace(ST+'.tmp',ST) +s=json.load(open(ST)) if os.path.exists(ST) else dict(done=['TN','LA','MI','SD','OK'],todo=['DE','WY']) +save(s) +log('RESUME START pid',os.getpid(),s) +for st in list(s['todo']): + cf=f'{C}/{st}.json' + if os.path.exists(cf):best=json.load(open(cf));log('STATE',st,'cdx from cache',len(best)) + else: + best={};complete=True + for idx in A.IDX: + for pat in A.STATES[st]: + got=False + for c in A.cdx(idx,pat): + got=True;u=c['url'] + if not u.startswith('https://'):continue + if not re.search(r'rule|pdf|download|Statutes|STOKRU|DocumentID',u,re.I):continue + k=u.split('#')[0] + if k not in best or c['timestamp']>best[k]['timestamp']:best[k]=dict(c,_idx=idx) + if best:json.dump(best,open(cf,'w')) + log('STATE',st,'cdx unique urls',len(best),'cached') + if not best: + open(O+'/skips.jsonl','a').write(json.dumps(dict(state=st,reason='no Common Crawl captures matched'))+'\n') + have=set() + if os.path.exists(f'{O}/{st}.jsonl'): + for l in open(f'{O}/{st}.jsonl'): + try:have.add(json.loads(l)['original_url']) + except Exception:pass + n=0 + with open(f'{O}/{st}.jsonl','a') as o: + for k,c in sorted(best.items())[:A.CAP]: + if k in have:continue + fn=f'{O}/files/{st}_{sid(k)}';g=A.fetch_warc(c,fn) + if not g:continue + sha,nb=g;cap=datetime.datetime.strptime(c['timestamp'],'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat() + o.write(json.dumps(dict(rule_id=sid(st,k),rule_set=f'{st} court rules',citation='',title='',text=None,court_id=None,subdivision_iso='US-'+st,effective_date=None,version='',file_url=k,original_url=k,file_sha256=sha,file_bytes=nb,mime=c.get('mime'),local_path=fn,content_sha256=sha,source='archive',source_url=k,fetched_at=now(),archive_source='commoncrawl',archive_timestamp=cap,archive_index=c['_idx'],warc_filename=c['filename'],warc_offset=int(c['offset']),warc_length=int(c['length']),cc_digest=c.get('digest'),license='see source terms (state-specific; archived copy)',terms_note='Common Crawl terms of use apply to archive access',robots_note='archive fetch (CC); original site robots not applicable',transport='https'))+'\n');o.flush();n+=1;have.add(k) + log('STATE',st,'new rows',n,'total',len(have)) + s['todo'].remove(st);s['done'].append(st);save(s) +log('ARCHIVE RESUME DONE') diff --git a/scrapers_and_normalizers/courts/collector/archive_rules.py b/scrapers_and_normalizers/courts/collector/archive_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..decd39f8131f4e7fb2dff90df43822c9d9c7aead --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/archive_rules.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Archive recovery of state court rules via Common Crawl (CDX + WARC range). Stage only. Wayback content host unreachable (probe 2026-10-27).""" +import sys,os,json,re,time,zlib,hashlib,urllib.request,urllib.parse,datetime +sys.path.insert(0,'/workspace/courts/collector') +import us_fed as U +from us_fed import log,memguard,sid,now +O='/workspace/courts/staging/state_rules_archive';os.makedirs(O+'/files',exist_ok=True) +UA='Mozilla/5.0 (compatible; court-research-collector/0.1)' +IDX=['CC-MAIN-2026-43','CC-MAIN-2026-30','CC-MAIN-2025-51'] +STATES={'TN':['tncourts.gov/rules'],'OK':['oscn.net/applications/oscn/'],'LA':['lasc.org/rules','lasc.org/Rules'],'MI':['courts.michigan.gov/rules-administrative-orders-and-jury-instructions','courts.michigan.gov/siteassets/rules-instructions-administrative-orders'],'SD':['sdlegislature.gov/Statutes/15','sdlegislature.gov/api/Statutes/15'],'DE':['courts.delaware.gov/rules','courts.delaware.gov/forms/download.aspx'],'WY':['courts.state.wy.us/court-rules','wyocourts.gov/court-rules','www.wyocourts.gov/court_rules']} +OKSEL={'OK':re.compile(r'STOKRU|ftdb=STOKRU|DocumentID',re.I)} +CAP=int(os.environ.get('ARCH_CAP','300'));DELAY=6;last=0 +def get(u,rng=None,tries=5): + global last + for i in range(tries): + memguard();w=last+DELAY-time.time() + if w>0:time.sleep(w) + last=time.time();h={'User-Agent':UA} + if rng:h['Range']=rng + try:return urllib.request.urlopen(urllib.request.Request(u,headers=h),timeout=120) + except urllib.error.HTTPError as e: + if e.code in(429,500,502,503,504):b=60*(2**i);log('BACKOFF',e.code,b,u[:100]);time.sleep(b);continue + if e.code==404:return None + log('HTTP_ERR',e.code,u[:120]);return None + except Exception as e:log('NET_ERR',repr(e)[:120],u[:100]);time.sleep(30) + return None +def cdx(idx,pat): + u=f'https://index.commoncrawl.org/{idx}-index?'+urllib.parse.urlencode(dict(url=pat+'*',output='json',filter='status:200')) + r=get(u) + if not r:return + for l in r: + try:yield json.loads(l) + except Exception:pass +def fetch_warc(c,fn): + off,ln=int(c['offset']),int(c['length']) + r=get('https://data.commoncrawl.org/'+c['filename'],rng=f'bytes={off}-{off+ln-1}') + if not r:return None + d=zlib.decompressobj(16+zlib.MAX_WBITS);buf=b'';hdr_done=False;h=hashlib.sha256();n=0;out=open(fn,'wb') + while True: + ch=r.read(65536) + if not ch:break + x=d.decompress(ch) + if not hdr_done: + buf+=x;p=buf.find(b'\r\n\r\n') + q=buf.find(b'\r\n\r\n',p+4) if p>=0 else -1 + if q<0:continue + x=buf[q+4:];hdr_done=True;buf=b'' + h.update(x);out.write(x);n+=len(x) + out.close();return h.hexdigest(),n +if __name__=='__main__': + only=sys.argv[1:] or list(STATES) + log('ARCHIVE START pid',os.getpid(),only,'cap',CAP) + sk=open(O+'/skips.jsonl','a');sk.write(json.dumps(dict(source='wayback',reason='web.archive.org unreachable from box (probe 2026-10-27 19:48 PT: connection fail); archive.org availability API reachable but content host not; Wayback not used'))+'\n');sk.flush() + for st in only: + best={} + for idx in IDX: + for pat in STATES[st]: + for c in cdx(idx,pat): + u=c['url'] + if not u.startswith('https://'):continue + if st in OKSEL and not OKSEL[st].search(u):continue + if not re.search(r'rule|pdf|download|Statutes|STOKRU|DocumentID',u,re.I):continue + k=u.split('#')[0] + if k not in best or c['timestamp']>best[k]['timestamp']:best[k]=dict(c,_idx=idx) + log('STATE',st,'cdx unique urls',len(best)) + if not best:sk.write(json.dumps(dict(state=st,reason='no Common Crawl captures matched'))+'\n');sk.flush();continue + n=0 + with open(f'{O}/{st}.jsonl','a') as o: + for k,c in sorted(best.items(),key=lambda kv:kv[0])[:CAP]: + fn=f'{O}/files/{st}_{sid(k)}';g=fetch_warc(c,fn) + if not g:continue + sha,nb=g;ts=c['timestamp'];cap=datetime.datetime.strptime(ts,'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat() + o.write(json.dumps(dict(rule_id=sid(st,k),rule_set=f'{st} court rules',citation='',title='',text=None,court_id=None,subdivision_iso='US-'+st,effective_date=None,version='',file_url=k,original_url=k,file_sha256=sha,file_bytes=nb,mime=c.get('mime'),local_path=fn,content_sha256=sha,source='archive',source_url=k,fetched_at=now(),archive_source='commoncrawl',archive_timestamp=cap,archive_index=c['_idx'],warc_filename=c['filename'],warc_offset=int(c['offset']),warc_length=int(c['length']),cc_digest=c.get('digest'),license='see source terms (state-specific; archived copy)',terms_note='Common Crawl terms of use apply to archive access',robots_note='archive fetch (CC); original site robots not applicable',transport='https'))+'\n');o.flush();n+=1 + log('STATE',st,'rows',n) + log('ARCHIVE DONE') diff --git a/scrapers_and_normalizers/courts/collector/cc_gapfill.py b/scrapers_and_normalizers/courts/collector/cc_gapfill.py new file mode 100644 index 0000000000000000000000000000000000000000..4e539788382a3e690256a63d9c12834ff9fb0b6b --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/cc_gapfill.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""CC gap-fill for state/county courthouse data: AL ND WV PA. CDX + WARC range fetch only (index.commoncrawl.org, data.commoncrawl.org). +Stage only, no push. memguard 4.2G/3 strikes -> exit 3. disk free<12G -> exit 4. Every row: source=archive, archive_source=commoncrawl.""" +import sys,os,json,re,time,zlib,hashlib,datetime,urllib.parse as up,collections +sys.path.insert(0,'/workspace/courts/collector') +import requests +from bs4 import BeautifulSoup +import state_county as S +B='/workspace/courts';O=f'{B}/staging/state_county_cc';os.makedirs(O,exist_ok=True) +S.LOG=open(f'{B}/logs/cc_gapfill.log','a',buffering=1);log=S.log +HL=open(f'{O}/page_filter_log.jsonl','a',buffering=1) +IDX=['CC-MAIN-2026-43','CC-MAIN-2026-30','CC-MAIN-2025-51'] +HOSTS={'AL':['judicial.alabama.gov','www.alacourt.gov','alacourt.gov'],'ND':['www.ndcourts.gov','ndcourts.gov'], + 'WV':['www.courtswv.gov','courtswv.gov'],'PA':['www.pacourts.us','pacourts.us'], + 'CO':['www.coloradojudicial.gov','coloradojudicial.gov'],'MS':['courts.ms.gov','www.courts.ms.gov'],'MN':['mncourts.gov','www.mncourts.gov'], + 'NM':['nmcourts.gov','www.nmcourts.gov'],'FL':['www.flcourts.gov','flcourts.gov']} +STATES=sys.argv[1:] or ['AL','ND','WV','PA'] +CAP_HTML=int(os.environ.get('CC_CAP_HTML','120'));CAP_FORMS=250;MAXB=5*2**20;DELAY=10;MEMFLOOR=float(os.environ.get('SC_MEMFLOOR','4.2'));MAXSTRIKES=int(os.environ.get('SC_MAXSTRIKES','3'));last=[0];strikes=[0] +sess=requests.Session();sess.headers['User-Agent']='Mozilla/5.0 (compatible; justicedao-court-research/0.2; archive gap-fill)' +def guard(): + while True: + ma=S.memavail() + if ma>=MEMFLOOR: break + strikes[0]+=1;S.strikes[0]=strikes[0];log(f'MEMGUARD strike {strikes[0]} MemAvailable={ma:.2f}G');S.memstrike_top5() + if strikes[0]>=MAXSTRIKES: log(f'MEMGUARD {MAXSTRIKES} strikes: clean stop');sys.exit(3) + time.sleep(60) + st=os.statvfs(B) + if st.f_bavail*st.f_frsize0: time.sleep(w) + last[0]=time.time();h={'Range':rng} if rng else {} + try: + r=sess.get(u,headers=h,stream=stream,timeout=(15,60)) + if r.status_code in (429,500,502,503,504): + b=min(60*2**i,1800);log('BACKOFF',r.status_code,b,u[:110]);r.close();time.sleep(b);continue + if r.status_code not in (200,206): log('HTTP',r.status_code,u[:110]);r.close();return None + return r + except requests.RequestException as e: + b=min(30*2**i,900);log('NETERR',repr(e)[:100],'sleep',b);time.sleep(b) + log('GIVEUP',u[:110]);return None +FORM_RX=re.compile(r'\.(pdf|docx?|rtf|xlsx?|odt)$',re.I) +FORM_HINT=re.compile(r'form',re.I) +TAB_RX={'judges':re.compile(r'judge|justice|magistrate|roster|bench|biograph',re.I), + 'courthouses':re.compile(r'courthouse|location|directory|county|contact|address|find-?a-?court|district|circuit|magisterial',re.I)} +NEG=re.compile(r'opinion|calendar|docket|news|press|career|job|employ|search|login|event|rule|order|\?.*page=',re.I) +def cdx(host): + best={} + for idx in IDX: + u=f'https://index.commoncrawl.org/{idx}-index?'+up.urlencode(dict(url=host+'/*',output='json',filter='status:200',limit='20000')) + r=get(u,stream=True) + if not r: continue + try: + for l in r.iter_lines(): + try:c=json.loads(l) + except Exception:continue + k=c['url'].split('#')[0] + if not k.startswith('https://'): continue + if k not in best or c['timestamp']>best[k]['timestamp']: best[k]=dict(c,_idx=idx) + except Exception as e: log('CDXSTREAMERR',idx,host,repr(e)[:120],'kept partial',len(best)) + r.close() + return best +def warc_body(c,limit=None,sink=None): + off,ln=int(c['offset']),int(c['length']) + r=get('https://data.commoncrawl.org/'+c['filename'],rng=f'bytes={off}-{off+ln-1}',stream=True) + if not r: return None + d=zlib.decompressobj(16+zlib.MAX_WBITS);buf=b'';hd=False;h=hashlib.sha256();n=0;keep=[] + for ch in r.iter_content(65536): + x=d.decompress(ch) + if not hd: + buf+=x;p=buf.find(b'\r\n\r\n');q=buf.find(b'\r\n\r\n',p+4) if p>=0 else -1 + if q<0: continue + x=buf[q+4:];hd=True;buf=b'' + h.update(x);n+=len(x) + if limit is not None and n<=limit: keep.append(x) + r.close();return h.hexdigest(),n,b''.join(keep) +def arch(c,sha): + ts=datetime.datetime.strptime(c['timestamp'],'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat() + u=c['url'].split('#')[0] + return dict(source='archive',source_url=u,original_url=u,fetched_at=S.now(),archive_source='commoncrawl',archive_timestamp=ts, + archive_index=c['_idx'],warc_filename=c['filename'],warc_offset=int(c['offset']),warc_length=int(c['length']),cc_digest=c.get('digest'), + license=S.LIC+'; archived copy',terms_note='Common Crawl terms of use apply to archive access',robots_note='archive fetch (CC); original host not contacted', + transport='https',content_sha256=sha,sha256=sha,coverage='archive_gapfill') +def page_decision(soup,nrows): + for x in soup(['script','style','noscript','nav','header','footer']): x.decompose() + t=soup.get_text(' ');tw=len(t.split()) or 1;aw=sum(len(a.get_text().split()) for a in soup.find_all('a'));ld=aw/tw + if tw<80: return False,'too_short(<80 words)',tw,ld + if nrows==0: return False,'no_extractable_rows',tw,ld + if ld>0.5 and nrows<3: return False,'navigation(link_density>0.5 and <3 rows)',tw,ld + return True,'kept(rows>0, not nav)',tw,ld +STF=f'{O}/state.json' +state=json.load(open(STF)) if os.path.exists(STF) else {'done':[]} +log('CC GAPFILL START pid',os.getpid(),STATES,'done',state['done']) +for st in STATES: + if st in state['done']: continue + cf=f'{O}/cdx_{st}.json' + if os.path.exists(cf): best=json.load(open(cf)) + else: + best={} + for h in HOSTS[st]: best.update(cdx(h)) + json.dump(best,open(cf,'w')) + log('STATE',st,'cdx unique https urls',len(best)) + forms=[(k,c) for k,c in sorted(best.items()) if FORM_RX.search(up.urlparse(k).path) and FORM_HINT.search(k)][:CAP_FORMS] + html=[] + for k,c in sorted(best.items()): + if 'html' not in (c.get('mime') or '') or NEG.search(k): continue + if TAB_RX['judges'].search(k) or TAB_RX['courthouses'].search(k): html.append((k,c)) + html=html[:CAP_HTML] + out={t:open(f'{O}/{st}_{t}.jsonl','w') for t in ('courts','courthouses','judges','forms')} + cnt=collections.Counter();courts={} + for k,c in html: + g=warc_body(c,limit=MAXB) + if not g: continue + sha,n,body=g + if n>MAXB: HL.write(json.dumps(dict(state=st,url=k,keep=False,reason='too_large(>5MB)'))+'\n');continue + soup=BeautifulSoup(body,'html.parser');A=arch(c,sha) + js=S.ext_judges(st,k,sha,soup);ch=S.ext_courthouses(st,k,sha,soup) + keep,why,tw,ld=page_decision(BeautifulSoup(body,'html.parser'),len(js)+len(ch)) + HL.write(json.dumps(dict(state=st,url=k,archive_timestamp=A['archive_timestamp'],keep=keep,reason=why,words=tw,link_density=round(ld,3),judges=len(js),courthouses=len(ch)))+'\n') + if not keep: cnt['pages_dropped']+=1;continue + cnt['pages_kept']+=1 + for t,rs in (('judges',js),('courthouses',ch)): + for r in rs: + r.update(A);r['role_type']='justice' if 'justice' in (r.get('title') or '').lower() else ('magistrate' if re.search('magistrate|commissioner',r.get('title') or '',re.I) else ('judge' if t=='judges' else None)) + if t!='judges': r.pop('role_type') + out[t].write(json.dumps(r,ensure_ascii=False)+'\n');cnt[t]+=1 + nm=r.get('court_name') if t=='judges' else r.get('name') + if r.get('court_id') and nm and r['court_id'] not in courts: + courts[r['court_id']]=dict(court_id=r['court_id'],name=nm,name_local=nm,country='US',subdivision_iso=f'US-{st}',level=S.classify_level(nm),court_type=None,parent_court_id=None,url=k,**A) + for r in courts.values(): out['courts'].write(json.dumps(r,ensure_ascii=False)+'\n');cnt['courts']+=1 + for k,c in forms: + g=warc_body(c,limit=0) + if not g: continue + sha,n,_=g;A=arch(c,sha);fn=up.unquote(up.urlparse(k).path.rsplit('/',1)[-1]);m=S.FNUM.search(fn) + out['forms'].write(json.dumps(dict(form_id=S.sid(st,k),form_number=m.group(1) if m else None,title=re.sub(r'\.[a-z]+$','',fn,flags=re.I),court_id=None,subdivision_iso=f'US-{st}',language='en', + file_url=k,file_format=fn.rsplit('.',1)[-1].lower(),file_sha256=sha,file_cid=None,file_bytes=n,effective_date=None,last_modified=None,file_stored=False,**A),ensure_ascii=False)+'\n');cnt['forms']+=1 + for f in out.values(): f.close() + log('STATE',st,'DONE',dict(cnt));state['done'].append(st);state[st]=dict(cnt) + json.dump(state,open(STF+'.tmp','w'));os.replace(STF+'.tmp',STF) +log('CC GAPFILL DONE',state) diff --git a/scrapers_and_normalizers/courts/collector/cc_gapfill_review.py b/scrapers_and_normalizers/courts/collector/cc_gapfill_review.py new file mode 100644 index 0000000000000000000000000000000000000000..74de4210a83f3a87766336aba4449ac3c8434617 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/cc_gapfill_review.py @@ -0,0 +1,19 @@ +import json,glob,collections,os,hashlib,random +B='/workspace/courts';O=f'{B}/staging/state_county_cc';R=f'{B}/review_state_county/cc_gapfill';os.makedirs(R,exist_ok=True) +c=collections.Counter();bad=collections.Counter();samp={} +REQ=['source','archive_source','archive_timestamp','original_url','sha256','warc_filename','warc_offset','warc_length'] +for f in sorted(glob.glob(f'{O}/[A-Z][A-Z]_*.jsonl')): + st,t=os.path.basename(f)[:-6].split('_',1);rows=[json.loads(l) for l in open(f)];c[(st,t)]=len(rows) + for r in rows: + for k in REQ: + if r.get(k) in (None,''): bad[(st,t,k)]+=1 + if r.get('source')!='archive' or r.get('archive_source')!='commoncrawl': bad[(st,t,'flag')]+=1 + if rows: samp[f'{st}_{t}']=random.sample(rows,min(2,len(rows))) +pf=collections.Counter() +if os.path.exists(f'{O}/page_filter_log.jsonl'): + for l in open(f'{O}/page_filter_log.jsonl'): d=json.loads(l);pf[(d['state'],d['reason'])]+=1 +md=['# CC gap-fill review (AL ND WV PA CO MS MN NM FL — 9 states) — STAGED, NOT PUSHED','','## Rows by state x table']+[f'- {s} {t}: {n}' for (s,t),n in sorted(c.items())]+['','## Page filter (index/nav heuristic) by state x reason']+[f'- {s} {r}: {n}' for (s,r),n in sorted(pf.items())]+['','Heuristic: drop HTML page if <80 words (scripts/nav/header/footer stripped), or no judge/courthouse rows extracted, or link_density>0.5 with <3 rows. Forms: archived file URLs with form in path and doc extension, sha256 of WARC payload only, not stored.','','## Validation (missing required archive fields)',str(dict(bad)) or 'none','','## Samples']+[f'- {k}: '+json.dumps(v,ensure_ascii=False)[:1500] for k,v in samp.items()] +open(f'{R}/REVIEW.md','w').write('\n'.join(md)+'\n') +json.dump(dict(rows={f'{s}_{t}':n for (s,t),n in c.items()},filter={f'{s}|{r}':n for (s,r),n in pf.items()},invalid={'|'.join(k):v for k,v in bad.items()}),open(f'{R}/report.json','w'),indent=1) +open(f'{R}/MANIFEST.sha256','w').write(''.join(hashlib.sha256(open(p,'rb').read()).hexdigest()+' '+p+'\n' for p in sorted(glob.glob(f'{O}/*.jsonl'))+[f'{R}/REVIEW.md',f'{R}/report.json'])) +print(md[:20]) diff --git a/scrapers_and_normalizers/courts/collector/dedupe_stage_archive.py b/scrapers_and_normalizers/courts/collector/dedupe_stage_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..01a101097c448ca861e3f9bbbd5200cc674cee58 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/dedupe_stage_archive.py @@ -0,0 +1,30 @@ +import json,hashlib,collections,glob +B='/workspace/courts';RV=f'{B}/review_state_rules_archive';H=f'{B}/hf_stage/data/state_rules.jsonl' +nu=lambda u:(u or '').strip().lower().split('#')[0].rstrip('/').replace('http://','https://') +sh=set();urls=set();th=set() +for l in open(H): + r=json.loads(l);rec=r['record'] + for k in('content_sha256','file_sha256'): + if rec.get(k):sh.add(rec[k]) + for k in('file_url','original_url'): + if rec.get(k):urls.add(nu(rec[k])) + if rec.get('file_url') is None and rec.get('source_url'):urls.add(nu(rec['source_url'])) # page-level rows + t=rec.get('full_text') or rec.get('text') + if t:th.add(hashlib.sha256(t.encode()).hexdigest()) +seen=set();out=[];log=[];c=collections.Counter() +for l in open(f'{RV}/filter_survivors.jsonl'): + r=json.loads(l);st=r['subdivision_iso'][3:];u=nu(r['original_url']) + why=('dup_hf_sha256' if r['content_sha256'] in sh or r['file_sha256'] in sh else + 'dup_hf_url' if u in urls or nu(r['source_url']) in urls else + 'dup_hf_text_sha256' if r['text_sha256'] in th else + 'dup_within_batch' if r['content_sha256'] in seen or r['text_sha256'] in seen else None) + c[(st,why or 'kept')]+=1;log.append(dict(rule_id=r['rule_id'],state=st,original_url=r['original_url'],result=why or 'kept')) + if why:continue + seen|={r['content_sha256'],r['text_sha256']} + rec={k:v for k,v in r.items() if k!='local_path'} + out.append(dict(subdivision_iso=r['subdivision_iso'],license='see source terms',archive_source='commoncrawl',source_collection='commoncrawl_archive_20261028',record=rec)) +with open(f'{RV}/dedupe_log.jsonl','w') as f: + for x in log:f.write(json.dumps(x)+'\n') +with open(f'{RV}/archive_new_unique.jsonl','w') as f: + for x in out:f.write(json.dumps(x)+'\n') +print(dict(c),len(out)) diff --git a/scrapers_and_normalizers/courts/collector/filter_archive.py b/scrapers_and_normalizers/courts/collector/filter_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..a586a5be6bb448d4eff3bee6fb8608c267f0a75a --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/filter_archive.py @@ -0,0 +1,48 @@ +import json,glob,re,subprocess,hashlib,collections,os,zipfile +from bs4 import BeautifulSoup +B='/workspace/courts'; A=f'{B}/staging/state_rules_archive'; RV=f'{B}/review_state_rules_archive' +CUE=re.compile(r'\b(?:Rule|RULE|Rules|§|Section|SECTION|Sec\.)\s*\d+[A-Za-z]?(?:[.\-:]\d+)*') +SUB=re.compile(r'(?m)^\s*\((?:[a-z]|\d{1,2}|[ivx]{1,4})\)\s') +TITLE=re.compile(r'(?i)\b(rules? of|court rules?|procedure|order amending|amend(?:ment|ing)|administrative (?:order|directive)|standing order|rule \d)') +def ext(r): + p=r['local_path'];b=open(p,'rb').read();ld=None + if b[:5]==b'%PDF-': + t=subprocess.run(['pdftotext','-layout',p,'-'],capture_output=True,timeout=120).stdout.decode('utf-8','replace');k='pdf' + elif b[:2]==b'PK': + try: + import docx; t='\n'.join(x.text for x in docx.Document(p).paragraphs);k='docx' + except Exception: t='';k='zip_unparsed' + elif b.lstrip()[:1]==b'<' or 'html' in r['mime']: + s=BeautifulSoup(b,'html.parser') + for x in s(['script','style','noscript','nav','header','footer','form']):x.decompose() + t=s.get_text('\n');k='html' + aw=sum(len(a.get_text().split()) for a in s.find_all('a'));tw=len(t.split()) or 1;ld=aw/tw + else: + t='';k='binary_unparsed' # .doc/.ppt OLE: no extractor on box + t=re.sub(r'[ \t]+',' ',re.sub(r'\n\s*\n+','\n\n',t)).strip() + return k,t,ld +def decide(r,k,t,ld): + w=len(t.split());cues=len(CUE.findall(t));subs=len(SUB.findall(t)) + tc=bool(TITLE.search(t[:600]+' '+r['original_url'])) + m=dict(kind=k,words=w,link_density=None if ld is None else round(ld,3),rule_cues=cues,subsection_marks=subs,title_cue=tc) + if not t: return False,'no_text_extracted',m + if w<150: return False,'too_short(<150 words)',m + if ld is not None and ld>0.4: return False,'navigation(link_density>0.4)',m + blanks=len(re.findall(r'_{5,}',t));m['form_blanks']=blanks + if blanks>=8 and not re.search(r'(?i)\brules? of\b|order amending|administrative order',t[:800]): return False,'form_not_rule(>=8 fill-in blanks, no rule/order title)',m + h=t[:700] + if (re.match(r'(?i)\s*form\s+\d',t) or (re.search(r'(?i)plaintiff',h) and re.search(r'(?i)defendant',h) and re.search(r'(?i)C\.\s*A\.\s*No|Case No|Civil Action No',h))) and not re.search(r'(?i)standing order|administrative order|order amending|rules? of',h): return False,'case_caption_template(form/pleading template, not a rule)',m + if re.match(r'(?i)\s*memorandum\b',t): return False,'memorandum_not_rule',m + if cues+subs>=5: return True,'rule_structure(cues+subsections>=5)',m + if tc and w>=300 and (ld is None or ld<=0.25): return True,'title_cue+>=300 words+low link density',m + return False,'no_rule_structure',m +out=[];log=open(f'{RV}/filter_log.jsonl','w');cnt=collections.Counter() +for f in sorted(glob.glob(f'{A}/[A-Z][A-Z].jsonl')): + for l in open(f): + r=json.loads(l);k,t,ld=ext(r);keep,why,m=decide(r,k,t,ld);st=r['subdivision_iso'][3:] + cnt[(st,keep)]+=1 + log.write(json.dumps(dict(rule_id=r['rule_id'],state=st,original_url=r['original_url'],content_sha256=r['content_sha256'],keep=keep,reason=why,**m,text_sha256=hashlib.sha256(t.encode()).hexdigest()))+'\n') + if keep: r['text']=t;r['text_extraction']=k;r['text_sha256']=hashlib.sha256(t.encode()).hexdigest();out.append(r) +with open(f'{RV}/filter_survivors.jsonl','w') as o: + for r in out:o.write(json.dumps(r)+'\n') +print({f'{s}':(cnt[(s,True)],cnt[(s,False)]) for s in sorted({s for s,_ in cnt})}) diff --git a/scrapers_and_normalizers/courts/collector/fixup_phase1.py b/scrapers_and_normalizers/courts/collector/fixup_phase1.py new file mode 100644 index 0000000000000000000000000000000000000000..36116bf51eb19d71bb86dcbef6978ea82daf39f5 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/fixup_phase1.py @@ -0,0 +1,81 @@ +import json,re,collections,shutil,os,hashlib,random +SRC='hf_stage';DST='hf_stage_fixup';REV='review_state_county/phase1_fixup' +if os.path.exists(DST): shutil.rmtree(DST) +shutil.copytree(SRC,DST) +log=open(f'{REV}/rules_applied.log','w') +RULES=[ # (name, field, regex, role_type) first match wins; applied to court_id-null rows + ('R0_ut_senior_board','court_name',r'^board of senior judges$','senior_judge'), + ('R1_committee','court_name',r'committee|association|education|bench book|legislat|technology|probate|juvenile services|criminal procedure|waivers|caseload|ethics|personnel|salary|pension|board of','committee_member'), + ('R2_nav_heading','court_name',r'responsibilities of','other'), + ('R3_justice','title',r'justice','justice'), + ('R4_magistrate','title',r'magistrate|commissioner|referee','magistrate'), + ('R5_staff','title',r'clerk|administrator|staff|secretary|director','staff'), + ('R6_judge_seat','court_name',r'^district \d+$|circuit judges|presiding judges','judge'), +] +def classify_null(x): + for n,f,rx,rt in RULES: + if re.search(rx,(x.get(f) or ''),re.I): return rt,n + return 'other','R9_default' +def classify_linked(x): + t=(x.get('title') or '').lower() + if 'justice' in t: return 'justice','L1_title_justice' + if re.search('magistrate|commissioner|referee',t): return 'magistrate','L2_title_magistrate' + return 'judge','L3_linked_seat' +before={} +# (1) AL coverage +al=collections.Counter() +for f in ['courts','courthouses','forms','judges']: + p=f'{DST}/data/{f}.jsonl';rows=[json.loads(l) for l in open(p)];before[f]=len(rows) + for r in rows: + if r.get('subdivision_iso')=='US-AL': + if r.get('coverage')=='complete': r['coverage']='partial_guard_stop';al[f]+=1 + else: al[f+'_untouched_cov_'+str(r.get('coverage'))]+=1 + if f!='judges': open(p,'w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in rows)) +# (2) judges +p=f'{DST}/data/judges.jsonl';rows=[json.loads(l) for l in open(p)] +cnt=collections.Counter();bystate=collections.Counter();rulec=collections.Counter() +for r in rows: + if r.get('court_id'): rt,n=classify_linked(r) + else: + rt,n=classify_null(r);bystate[(r['subdivision_iso'],rt)]+=1 + log.write(f"{r['judge_id']}\t{r['subdivision_iso']}\t{r['court_name']!r}\t{r['title']!r}\t{n}\t{rt}\n") + r['role_type']=rt;rulec[n]+=1;cnt[(bool(r.get('court_id')),rt)]+=1 +REMOVE={'committee_member','staff','other'} +keep=[r for r in rows if not (not r.get('court_id') and r['role_type'] in REMOVE)] +removed=[r for r in rows if r not in keep] +# names removed that also survive as a seat in same state +seat={(r['subdivision_iso'],' '.join(r['full_name'].split()).lower()) for r in keep} +dup=sum(((r['subdivision_iso'],' '.join(r['full_name'].split()).lower()) in seat) for r in removed) +open(p,'w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in keep)) +open(f'{REV}/removed_judges.jsonl','w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in removed)) +after={f:sum(1 for _ in open(f'{DST}/data/{f}.jsonl')) for f in before} +# card +card=open(f'{DST}/README.md').read() +card+=f""" + +## Fix-up (staged 2026-10-28, on top of f12c757) +- Alabama state/county rows: coverage changed `complete` -> `partial_guard_stop` (the AL collection was cut by the memory guard). +- `judges` now has a `role_type` field on every row (judge, justice, magistrate, senior_judge; for unlinked rows also committee_member, other). `senior_judge` = 7 Utah Board of Senior Judges members, kept, assigned by explicit logged rules. +- **Removed** {len(removed)} unlinked rows (court_id null) whose role_type was committee_member/staff/other: these were committee, association or board memberships (mostly Nebraska Judicial Branch committee pages), not judicial seats. Removed rows are saved for audit (removed_judges.jsonl, not published). {dup} of them name a person who still appears in this state as a seat row. Kept unlinked rows with role_type judge/justice/senior_judge ({sum(1 for r in keep if not r.get('court_id'))}) remain without a court_id. +""" +open(f'{DST}/README.md','w').write(card) +open(f'{DST}/ROWCOUNTS.txt','w').write(''.join(f'data/{f}.jsonl {sum(1 for _ in open(f"{DST}/data/{f}.jsonl"))}\n' for f in sorted(os.listdir(f'{DST}/data')) for f in [f[:-6]])) +man='' +for root,_,fs in os.walk(DST): + for f in sorted(fs): + if f=='MANIFEST.sha256':continue + q=os.path.join(root,f);man+=hashlib.sha256(open(q,'rb').read()).hexdigest()+' '+os.path.relpath(q,DST)+'\n' +open(f'{DST}/MANIFEST.sha256','w').write(man) +random.seed(7) +samp={rt:random.sample([r for r in rows if r['role_type']==rt and not r.get('court_id')],min(3,sum(1 for r in rows if r['role_type']==rt and not r.get('court_id')))) for rt in set(r['role_type'] for r in rows if not r.get('court_id'))} +nl=collections.Counter(r['role_type'] for r in rows if not r.get('court_id')) +md=["# Phase 1 fix-up review (STAGED, NOT PUSHED)","Base: justicedao/ipfs_us_courts f12c75717a852dc2d81f1f293a7005251c52dd5f. Staged copy: hf_stage_fixup/","", +"## (1) AL coverage", f"Changed complete->partial_guard_stop: {dict(al)}. AL rows with coverage null are pre-existing non-state-county rows and were left unchanged.","", +"## (2) role_type rules (first match wins, unlinked rows)"]+[f"- {n}: `{f}` ~ /{rx}/i -> {rt}" for n,f,rx,rt in RULES]+["- R9_default -> other","Linked rows (court_id set): title~justice->justice; magistrate|commissioner|referee->magistrate; else judge.","", +"## Counts: unlinked (court_id null, n=%d) by role_type"%sum(nl.values())]+[f"- {k}: {v}" for k,v in nl.most_common()]+["","## Unlinked by state x role_type"]+[f"- {s} {rt}: {v}" for (s,rt),v in sorted(bystate.items())]+["","## All judges by (linked, role_type)"]+[f"- linked={a} {rt}: {v}" for (a,rt),v in sorted(cnt.items())]+["","## Rule hits"]+[f"- {k}: {v}" for k,v in sorted(rulec.items())]+["", +"## Recommendation / action","Flag every judge row with role_type AND remove unlinked committee_member/staff/other rows from `judges` (they are memberships, not seats; %d of %d removed duplicate a person kept as a seat). Removed rows saved in removed_judges.jsonl for audit."%(dup,len(removed)),"", +"## Row counts before -> after"]+[f"- {f}: {before[f]} -> {after[f]}" for f in before]+["","## Samples (unlinked)"]+[f"- {rt}: "+json.dumps([{k:r[k] for k in ('full_name','subdivision_iso','court_name','title','source_url')} for r in v],ensure_ascii=False) for rt,v in samp.items()]+["","Rule log: rules_applied.log. Card text appended in hf_stage_fixup/README.md."] +open(f'{REV}/REVIEW.md','w').write('\n'.join(md)+'\n') +m=''.join(hashlib.sha256(open(f'{REV}/{f}','rb').read()).hexdigest()+' '+f+'\n' for f in sorted(os.listdir(REV)) if f!='MANIFEST.sha256') +open(f'{REV}/MANIFEST.sha256','w').write(m) +print('\n'.join(md)) diff --git a/scrapers_and_normalizers/courts/collector/hf_push.py b/scrapers_and_normalizers/courts/collector/hf_push.py new file mode 100644 index 0000000000000000000000000000000000000000..3239872c8e9f5f02b7bfcda80f301d909f4b137d --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push.py @@ -0,0 +1,6 @@ +import sys;sys.path.insert(0,'/workspace/scripts');import _hf_env # sets HF_TOKEN env from existing connector secret; never printed +from huggingface_hub import HfApi +api=HfApi();R='justicedao/ipfs_us_courts' +api.create_repo(R,repo_type='dataset',exist_ok=True) +c=api.upload_folder(folder_path='/workspace/courts/hf_stage',repo_id=R,repo_type='dataset',commit_message='Initial US courts: federal courts/courthouses/judges/forms/rules + state_rules (11 states)') +print('COMMIT',c.oid);print('URL',c.commit_url) diff --git a/scrapers_and_normalizers/courts/collector/hf_push2.py b/scrapers_and_normalizers/courts/collector/hf_push2.py new file mode 100644 index 0000000000000000000000000000000000000000..cc095f20cab3033cad6bac70c1570436c074bb05 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push2.py @@ -0,0 +1,12 @@ +import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env +from huggingface_hub import HfApi,snapshot_download +api=HfApi();R='justicedao/ipfs_us_courts' +c=api.upload_folder(folder_path='/workspace/courts/hf_stage',repo_id=R,repo_type='dataset',allow_patterns=['README.md','ROWCOUNTS.txt','data/state_rules.jsonl'],commit_message='state_rules: merge 274 rerun docs (NE 22, DE 93, KS 159); total 2713, licence see source terms') +print('COMMIT',c.oid) +p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv3');ok=True +for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'): + h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256() + with open(os.path.join(p,f),'rb') as fh: + for b in iter(lambda:fh.read(1<<20),b''):h2.update(b) + m=h2.hexdigest()==h;ok&=m;print(f,'ok' if m else 'MISMATCH',sum(1 for _ in open(os.path.join(p,f))) if f.endswith('.jsonl') else '') +print('ALL_OK',ok);shutil.rmtree('/tmp/hfv3') diff --git a/scrapers_and_normalizers/courts/collector/hf_push3.py b/scrapers_and_normalizers/courts/collector/hf_push3.py new file mode 100644 index 0000000000000000000000000000000000000000..bde9126c97d948829ee6077602c0534cee0d525e --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push3.py @@ -0,0 +1,15 @@ +import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_env +from huggingface_hub import HfApi,snapshot_download +api=HfApi();R='justicedao/ipfs_us_courts' +c=api.upload_folder(folder_path='/workspace/courts/hf_stage',repo_id=R,repo_type='dataset',allow_patterns=['README.md','ROWCOUNTS.txt','MANIFEST.sha256','data/state_rules.jsonl'],commit_message='state_rules: add 90 Common Crawl archive docs (DE 87, MI 3; source=archive, archive_source=commoncrawl); filtered+deduped; total 2803') +print('COMMIT',c.oid) +p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv4');ok=True +for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'): + h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256() + with open(os.path.join(p,f),'rb') as fh: + for b in iter(lambda:fh.read(1<<20),b''):h2.update(b) + m=h2.hexdigest()==h;ok&=m;print(f,'ok' if m else 'MISMATCH',sum(1 for _ in open(os.path.join(p,f))) if f.endswith('.jsonl') else '') +rows=[json.loads(l) for l in open(os.path.join(p,'data/state_rules.jsonl'))] +a=[r for r in rows if r.get('source_collection')=='commoncrawl_archive_20261028'] +print('archive_rows',len(a),'flags_ok',all(r['record']['source']=='archive' and r['record']['archive_source']=='commoncrawl' and r['record']['warc_filename'] and r['record']['archive_timestamp'] for r in a)) +print('ALL_OK',ok);shutil.rmtree('/tmp/hfv4') diff --git a/scrapers_and_normalizers/courts/collector/hf_push_phase1.py b/scrapers_and_normalizers/courts/collector/hf_push_phase1.py new file mode 100644 index 0000000000000000000000000000000000000000..9397c46d00b8c51c32a4dfb952cea532e6cf21a7 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push_phase1.py @@ -0,0 +1,18 @@ +import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_env +from huggingface_hub import HfApi,snapshot_download +api=HfApi();R='justicedao/ipfs_us_courts' +c=api.upload_folder(folder_path='/workspace/courts/hf_stage',repo_id=R,repo_type='dataset',allow_patterns=['README.md','ROWCOUNTS.txt','MANIFEST.sha256','schema.json','data/courts.jsonl','data/courthouses.jsonl','data/judges.jsonl','data/forms.jsonl'],commit_message='state/county judiciary Phase 1: +71 courts, +413 courthouses, +860 judges, +2300 forms (coverage field; gaps DE MT CT VA KS WA WI ND listed on card)') +print('COMMIT',c.oid,flush=True) +p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv5');ok=True +for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'): + h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256() + with open(os.path.join(p,f),'rb') as fh: + for b in iter(lambda:fh.read(1<<20),b''):h2.update(b) + m=h2.hexdigest()==h;ok&=m;print(f,'ok' if m else 'MISMATCH',sum(1 for _ in open(os.path.join(p,f))) if f.endswith('.jsonl') else '') +print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv5') +from datasets import load_dataset +for cfg in ['courts','courthouses','judges','forms']: + d=load_dataset(R,cfg,split='train',revision=c.oid,cache_dir='/tmp/hfds5') + n=[r for r in d if r.get('coverage')][:2] + print('SMOKE',cfg,len(d),[(r.get('name') or r.get('full_name') or r.get('title'),r['subdivision_iso'],r['coverage']) for r in n]) +shutil.rmtree('/tmp/hfds5',ignore_errors=True) diff --git a/scrapers_and_normalizers/courts/collector/hf_push_phase2.py b/scrapers_and_normalizers/courts/collector/hf_push_phase2.py new file mode 100644 index 0000000000000000000000000000000000000000..dff11d6ce2b2af8c63fb0e130dc38b8ba8a321e8 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push_phase2.py @@ -0,0 +1,17 @@ +import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env +from huggingface_hub import HfApi,snapshot_download +api=HfApi();R='justicedao/ipfs_us_courts';S='/workspace/courts/hf_stage_phase2';PARENT='587b1e2a7e0e6dc3f95380e1c604df629af080e7' +head=api.dataset_info(R).sha;print('HEAD',head,flush=True) +assert head==PARENT,'head moved' +c=api.upload_folder(folder_path=S,repo_id=R,repo_type='dataset',parent_commit=PARENT,allow_patterns=['README.md','ROWCOUNTS.txt','MANIFEST.sha256','schema.json','data/courts.jsonl','data/courthouses.jsonl','data/forms.jsonl'],commit_message='state/county judiciary Phase 2: +77 courts, +102 courthouses, +936 forms (KY WY ID complete; NV MN partial host-stopped; IA judges dropped; CO MS ND blocked; NM FL no usable pages; SC deferred)') +print('COMMIT',c.oid,flush=True) +p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv6');ok=True +for l in open(S+'/MANIFEST.sha256'): + h,f=l.split(None,1);f=f.strip();h2=hashlib.sha256() + with open(os.path.join(p,f),'rb') as fh: + for b in iter(lambda:fh.read(1<<20),b''):h2.update(b) + m=h2.hexdigest()==h;ok&=m;print(f,'ok' if m else 'MISMATCH',sum(1 for _ in open(os.path.join(p,f))) if f.endswith('.jsonl') else '') +rc=open(os.path.join(p,'ROWCOUNTS.txt')).read() +for l in rc.split('\n'): + if l: f,n=l.split();a=sum(1 for _ in open(os.path.join(p,f)));ok&=a==int(n);print('ROWCOUNT',f,n,a) +print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv6') diff --git a/scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.py b/scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.py new file mode 100644 index 0000000000000000000000000000000000000000..4162d80dddd7049d235385ce942b9a7c7d714426 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.py @@ -0,0 +1,17 @@ +import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env +from huggingface_hub import HfApi,snapshot_download +api=HfApi();R='justicedao/ipfs_us_courts';S='/workspace/courts/hf_stage_phase2';PARENT='dca3bf749a865c39badc4fe186608200f6fc29f4' +head=api.dataset_info(R).sha;print('HEAD',head,flush=True) +assert head==PARENT,'head moved' +c=api.upload_folder(folder_path=S,repo_id=R,repo_type='dataset',parent_commit=PARENT,allow_patterns=['README.md','MANIFEST.sha256','data/state_rules.jsonl'],commit_message='state_rules schema fix: record as JSON string + explicit features; values unchanged (2803 rows)') +print('COMMIT',c.oid,flush=True) +p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv7');ok=True +for l in open(S+'/MANIFEST.sha256'): + h,f=l.split(None,1);f=f.strip();h2=hashlib.sha256() + with open(os.path.join(p,f),'rb') as fh: + for b in iter(lambda:fh.read(1<<20),b''):h2.update(b) + m=h2.hexdigest()==h;ok&=m;print(f,'ok' if m else 'MISMATCH',sum(1 for _ in open(os.path.join(p,f))) if f.endswith('.jsonl') else '') +rc=open(os.path.join(p,'ROWCOUNTS.txt')).read() +for l in rc.split('\n'): + if l: f,n=l.split();a=sum(1 for _ in open(os.path.join(p,f)));ok&=a==int(n);print('ROWCOUNT',f,n,a) +print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv7') diff --git a/scrapers_and_normalizers/courts/collector/phase3gap.py b/scrapers_and_normalizers/courts/collector/phase3gap.py new file mode 100644 index 0000000000000000000000000000000000000000..ac37f40beeb9e576a7cc1edb381dd30fa7f15485 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/phase3gap.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Phase3 gap collector: reuses state_county.py; sitemap-assisted discovery for JS-rendered/thin states. Stage only. GO: COS_GO_COURTS_PHASE3GAP_20261103""" +import sys,os,re,json,urllib.parse as up +sys.path.insert(0,'/workspace/courts/collector') +import state_county as m +from bs4 import BeautifulSoup +B=m.BASE; m.ST_DIR=f'{B}/staging/state_county_phase3gap'; m.RV=f'{B}/review_state_county_phase3gap' +m.LOG=open(f'{B}/logs/phase3gap.log','a',buffering=1); m.BLF=f'{m.ST_DIR}/blocked_hosts.json' +m.NEVER|=set('CO MS ND NV MN DC MA NC NH NJ NY LA PR TN MO OK'.split()) +STATES='MI SD VT DE MT FL NM GA IN'.split() +def phase0(st): + out=f'{m.ST_DIR}/phase0/{st}.json' + if os.path.exists(out): return + url=m.landing_urls()[st]; host=up.urlparse(url).netloc + res={'state':st,'subdivision_iso':f'US-{st}','landing':url,'candidates':{},'chosen':{},'status':'ok','notes':['sitemap-assisted discovery']} + try: + L=[] + f=m.fetch(url) + if f and f[0].status_code==200 and f[1]: + L+=m.links(f[0].url,BeautifulSoup(f[1],'lxml')); host=up.urlparse(f[0].url).netloc + sms=[f'https://{host}/sitemap.xml'] + H=m.gethost(host) + sms=[l.split(':',1)[1].strip() for l in (H.robots or '').splitlines() if l.lower().startswith('sitemap:')][:2] or sms + n=0 + while sms and n<4: + s=sms.pop(0); n+=1; g=m.fetch(s) + if not g or g[0].status_code!=200: res['notes'].append(f'sitemap {s} unavailable'); continue + g2=m.fetch(s) if False else g + body=(g2[1] or b'').decode('utf-8','ignore') + if not body: + continue + locs=re.findall(r'\s*([^<\s]+)\s*',body) + if '0 and not up.urlparse(u).path.lower().endswith(m.FILEEXT)},reverse=True)[:5] + res['candidates'][cat]=[{'score':s,'url':u,'text':t} for s,u,t in c] + for cand in res['candidates'][cat][:2]: + if not cand['url'].startswith('https://'): continue + g=m.fetch(cand['url']) + if g and g[0].status_code==200: res['chosen'][cat]=g[0].url; break + except m.HostBlocked as e: res['status']=f'blocked: {e}' + json.dump(res,open(out,'w'),indent=1); m.log('P3G P0',st,res['status'],res['chosen']) +def main(): + m.load_blocks(); m.log('P3G START pid',os.getpid(),STATES) + for st in STATES: + if m.STOP.is_set(): return m.STOPRC[0] + phase0(st) + if m.STOP.is_set(): return m.STOPRC[0] + m.collect_state(3,st) + if m.STOP.is_set(): return m.STOPRC[0] + m.review(3,STATES); return 0 +if __name__=='__main__': + try: rc=main() + except Exception: + import traceback; m.log('CRASH',traceback.format_exc()); rc=1 + m.log('P3G EXIT rc',rc); sys.exit(rc) diff --git a/scrapers_and_normalizers/courts/collector/procedure_rules_collect.py b/scrapers_and_normalizers/courts/collector/procedure_rules_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..44f8fae2d3a597eb2d5e558a68dca64854f5454e --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/procedure_rules_collect.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Memsafe wrapper for state_procedure_rules_scraper source registry (CoS GO 2026-11-04). +Reads the scraper's per-state source tables via AST (no import: no fallbacks, no scrape_state_laws, +no IPFS cache, no curl). Single worker, HTTPS only, TLS verify on, robots honored, >=10s/host, +stop host on first 403/429/challenge, no retries. Stores url+sha256+metadata only.""" +import ast,hashlib,json,os,re,shutil,sys,threading,time,urllib.parse as up,urllib.robotparser as rp +from datetime import datetime +import requests +SRC='/workspace/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/state_procedure_rules_scraper.py' +OUT=os.environ.get('PR_OUT','/workspace/courts/staging/procedure_rules'); os.makedirs(OUT,exist_ok=True) +LOG=open(os.environ.get('PR_LOG','/workspace/courts/logs/procedure_rules.log'),'a',buffering=1) +UA='justicedao-courts-collector/1.0 (public court data; polite 1 req/10s)' +EXCL=set('CA IL OR WA WI CT VA KS CO MS ND NV MN SC DC MA NC NH NJ NY LA PR TN MO OK'.split()) +PRIVATE=('westlaw.com','lexis','casetext','justia.com','findlaw','fastcase') +MEMFLOOR=float(os.environ.get('SC_MEMFLOOR','4.2')); MAXSTRIKES=int(os.environ.get('SC_MAXSTRIKES','3')); DISKFLOOR=float(os.environ.get('CC_DISKFLOOR_G','20')) +MINDELAY=10.0; STOP=threading.Event(); RC=[0] +def now(): return datetime.now().astimezone().isoformat(timespec='seconds') +def log(*a): LOG.write(now()+' '+' '.join(map(str,a))+'\n') +def memavail(): return int(next(l for l in open('/proc/meminfo') if l.startswith('MemAvailable')).split()[1])/1048576 +def guard(): + s=0 + while not STOP.is_set(): + m=memavail(); d=shutil.disk_usage('/workspace').free/2**30 + if d=MAXSTRIKES: log('MEMGUARD 3 strikes: clean stop'); RC[0]=3; STOP.set(); return + time.sleep(20) +def sources(): + t=ast.parse(open(SRC).read()); res={} + for n in t.body: + tg=n.targets[0] if isinstance(n,ast.Assign) else (n.target if isinstance(n,ast.AnnAssign) else None) + if not isinstance(tg,ast.Name) or n.value is None: continue + mm=re.match(r'_([A-Z]{2})_',tg.id) + if not mm: continue + try: v=ast.literal_eval(n.value) + except Exception: continue + st=mm.group(1); items=[] + if isinstance(v,str) and v.startswith('http'): items=[{'name':tg.id,'url':v}] + elif isinstance(v,list): items=[dict(x,_var=tg.id) for x in v if isinstance(x,dict) and isinstance(x.get('url'),str)] + for it in items: res.setdefault(st,[]).append(it) + return res +HOSTS={}; BLK=f'{OUT}/blocked_hosts.json' +blocked=json.load(open(BLK)) if os.path.exists(BLK) else {} +def hostinfo(h): + if h in HOSTS: return HOSTS[h] + H={'last':0,'delay':MINDELAY,'rp':None}; HOSTS[h]=H + wait(H) + try: + r=requests.get(f'https://{h}/robots.txt',headers={'User-Agent':UA},timeout=30); H['last']=time.time() + log('ROBOTS',h,r.status_code) + if r.status_code in (403,429): block(h,f'robots {r.status_code}') + elif r.status_code==200: + p=rp.RobotFileParser(); p.parse(r.text.splitlines()); H['rp']=p + cd=p.crawl_delay(UA) or p.crawl_delay('*') + if cd: H['delay']=max(MINDELAY,float(cd)) + except requests.RequestException as e: H['last']=time.time(); log('ROBOTSERR',h,type(e).__name__) + return H +def wait(H): + dt=H['last']+H['delay']-time.time() + while dt>0 and not STOP.is_set(): time.sleep(min(dt,5)); dt=H['last']+H['delay']-time.time() +def block(h,why): blocked[h]=why; json.dump(blocked,open(BLK,'w'),indent=1); log('BLOCK',h,why) +CHAL=re.compile(rb'captcha|cf-challenge|challenge-platform|Just a moment|Access Denied|Request Rejected|incapsula|px-captcha',re.I) +def fetch(url): + p=up.urlparse(url); h=p.netloc.lower() + if p.scheme!='https': return None,'non_https_skipped' + if any(x in h for x in PRIVATE): return None,'private_publisher_skipped' + if h in blocked: return None,'host_blocked' + H=hostinfo(h) + if h in blocked: return None,'host_blocked' + if H['rp'] and not H['rp'].can_fetch(UA,url): return None,'robots_disallow' + wait(H) + if STOP.is_set(): return None,'stopped' + try: + r=requests.get(url,headers={'User-Agent':UA},timeout=90,stream=True,verify=True); H['last']=time.time() + sha=hashlib.sha256(); n=0; head=b'' + for c in r.iter_content(65536): + sha.update(c); n+=len(c) + if len(head)<20000: head+=c[:20000-len(head)] + if n>80*2**20: break + r.close() + except requests.RequestException as e: H['last']=time.time(); log('NETERR',url,type(e).__name__); return None,'neterr' + log('GET',r.status_code,n,url) + if r.status_code in (403,429) or (r.status_code!=200 and CHAL.search(head)) or (b' /homepage (removed, not a block); archive fallback not attempted in-run (Wayback 429 earlier)') +elif st=='state_rules':S.state_rules() +elif st=='review': + import review;review.build() diff --git a/scrapers_and_normalizers/courts/collector/review.py b/scrapers_and_normalizers/courts/collector/review.py new file mode 100644 index 0000000000000000000000000000000000000000..501147e7dc333cc3830d2eb0c8e9970588fca050 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/review.py @@ -0,0 +1,29 @@ +import json,glob,os,hashlib,collections,csv,random +C='/workspace/courts';ST=C+'/staging';RV=C+'/review' +def build(): + os.makedirs(RV,exist_ok=True);S=json.load(open(C+'/schema.json'))['tables'] + tmap={'judges':'judges','courts':'courts','courthouses':'courthouses','forms':'forms','rules':'rules','ncsc_state_links':None} + counts={};val={};samp={};tr=collections.Counter();lic=collections.Counter();rob=collections.Counter() + for f in sorted(glob.glob(ST+'/*.jsonl')): + n=os.path.basename(f)[:-6];rows=[json.loads(l) for l in open(f) if l.strip()];counts[n]=len(rows) + samp[n]=random.Random(0).sample(rows,min(5,len(rows))) + for r in rows:tr[r.get('transport')]+=1;lic[r.get('license')]+=1;rob[r.get('robots_note')]+=1 + t=tmap.get(n) + if t: + req=[k for k in S[t] if not k.startswith('_')];miss=collections.Counter(k for r in rows for k in req if k not in r) + val[n]=dict(required_fields=len(req),rows=len(rows),missing_field_counts=dict(miss),ok=not miss) + sr=glob.glob(ST+'/state_rules/**/*.json*',recursive=True);counts['state_rules_files']=len(sr) + man=open(RV+'/sha256_manifest.csv','w');w=csv.writer(man);w.writerow(['path','bytes','sha256']) + for p in sorted(glob.glob(ST+'/**/*',recursive=True)): + if os.path.isfile(p) and '/_home/' not in p: + h=hashlib.sha256() + with open(p,'rb') as fh: + for c in iter(lambda:fh.read(1<<20),b''):h.update(c) + w.writerow([p,os.path.getsize(p),h.hexdigest()]) + man.close() + errs=[l for lf in glob.glob(C+'/logs/*.log') for l in open(lf,errors='ignore') if any(k in l for k in ('ERR','FAIL','DISALLOW','MEMGUARD','Traceback'))] + open(RV+'/errors_skips.txt','w').writelines(errs+[l for l in open(ST+'/skips.jsonl')] if os.path.exists(ST+'/skips.jsonl') else errs) + for k,v in [('row_counts',counts),('schema_validation',val),('samples',samp),('robots_terms_transport',dict(transport=dict(tr),license=dict(lic),robots=dict(rob)))]:json.dump(v,open(f'{RV}/{k}.json','w'),indent=1,default=str) + md=['# Courts US federal review package','Staged only; nothing pushed to HF.','## Row counts']+[f'- {k}: {v}' for k,v in counts.items()]+['## Schema validation']+[f"- {k}: {'OK' if v['ok'] else 'MISSING '+str(v['missing_field_counts'])}" for k,v in val.items()]+['## Transport',str(dict(tr)),'## Licences',str(dict(lic)),f'## Errors/skips: {len(errs)} log lines (errors_skips.txt)','Files: row_counts.json, samples.json, schema_validation.json, sha256_manifest.csv, robots_terms_transport.json'] + open(RV+'/REVIEW.md','w').write('\n'.join(md)+'\n') +if __name__=='__main__':build() diff --git a/scrapers_and_normalizers/courts/collector/review_archive.py b/scrapers_and_normalizers/courts/collector/review_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..4312cc7f3ce0fbcc02359f1af486f2801b07d0ef --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/review_archive.py @@ -0,0 +1,22 @@ +import json,glob,os,hashlib,csv,collections +O='/workspace/courts/staging/state_rules_archive';RV='/workspace/courts/review_state_rules_archive';os.makedirs(RV,exist_ok=True) +S=[k for k in json.load(open('/workspace/courts/schema.json'))['tables']['rules'] if not k.startswith('_')]+['source','original_url','archive_source','archive_timestamp','file_sha256'] +cnt={};rng={};miss=collections.Counter();samp={};bad=collections.Counter() +for f in sorted(glob.glob(O+'/[A-Z][A-Z].jsonl')): + st=os.path.basename(f)[:2];ts=[];n=0 + for l in open(f): + r=json.loads(l);n+=1;miss.update(k for k in S if k not in r);ts.append(r['archive_timestamp']) + if r.get('source')!='archive' or r.get('archive_source')!='commoncrawl':bad[st]+=1 + if n<=2:samp.setdefault(st,[]).append(r) + cnt[st]=n;rng[st]=[min(ts),max(ts)] if ts else None +w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256']) +for p in sorted(glob.glob(O+'/**/*',recursive=True)): + if os.path.isfile(p): + h=hashlib.sha256() + with open(p,'rb') as fh: + for c in iter(lambda:fh.read(1<<20),b''):h.update(c) + w.writerow([p,os.path.getsize(p),h.hexdigest()]) +sk=[json.loads(l) for l in open(O+'/skips.jsonl')] if os.path.exists(O+'/skips.jsonl') else [] +ok=not miss and not bad +for k,v in [('row_counts',cnt),('capture_ranges',rng),('samples',samp),('validation',dict(missing=dict(miss),bad_flags=dict(bad),ok=ok)),('skips',sk)]:json.dump(v,open(f'{RV}/{k}.json','w'),indent=1) +open(RV+'/REVIEW.md','w').write('# State court rules: archive recovery (Common Crawl) review\nStage only, not pushed. Every row: source=archive, archive_source=commoncrawl, archive_timestamp, original_url, sha256. Licence: see source terms.\n## Rows / capture range per state\n'+'\n'.join(f'- {k}: {v} rows, {rng[k]}' for k,v in cnt.items())+f'\n## Validation: {"OK" if ok else "FAIL "+str(dict(miss))+str(dict(bad))}\n## Skips\n'+'\n'.join(f"- {s.get('state',s.get('source'))}: {s.get('reason')}" for s in sk)+'\nNote: payloads are HTTP bodies as stored in WARC (may be HTML index pages, not only rule documents).\n') diff --git a/scrapers_and_normalizers/courts/collector/review_resume.py b/scrapers_and_normalizers/courts/collector/review_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..eac6a23072521c417207f47281467c231402462f --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/review_resume.py @@ -0,0 +1,26 @@ +import json,glob,os,hashlib,csv,collections +O='/workspace/courts/staging/state_rules_rerun';OFF='/workspace/courts/staging/state_rules/official';RV='/workspace/courts/review_state_rules_rerun';os.makedirs(RV,exist_ok=True) +S=[k for k in json.load(open('/workspace/courts/schema.json'))['tables']['rules'] if not k.startswith('_')] +def rows(f):return [json.loads(l) for l in open(f)] if os.path.exists(f) else [] +orig={st:{r['file_sha256'] for r in rows(f'{OFF}/{st}.jsonl')}|{r['rule_id'] for r in rows(f'{OFF}/{st}.jsonl')} for st in ['KS','NE','DE']} +cnt={};dd={};miss=collections.Counter();samp={} +for st in ['KS','NE','DE']: + allr=rows(f'{O}/{st}.jsonl')+rows(f'{O}/{st}_resume.jsonl');seen=set();uniq=[];dup_orig=dup_int=0 + for r in allr: + miss.update(k for k in S if k not in r) + if r['rule_id'] in orig[st] or r['file_sha256'] in orig[st]:dup_orig+=1;continue + if r['file_sha256'] in seen:dup_int+=1;continue + seen.add(r['file_sha256']);uniq.append(r) + with open(f'{RV}/{st}_new_unique.jsonl','w') as o: + for r in uniq:o.write(json.dumps(r)+'\n') + cnt[st]=len(allr);dd[st]=dict(staged=len(allr),dup_vs_original=dup_orig,dup_internal=dup_int,new_unique=len(uniq));samp[st]=uniq[:2] +w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256']) +for p in sorted(glob.glob(O+'/**/*',recursive=True)+glob.glob(RV+'/*_new_unique.jsonl')): + if os.path.isfile(p): + h=hashlib.sha256() + with open(p,'rb') as fh: + for c in iter(lambda:fh.read(1<<20),b''):h.update(c) + w.writerow([p,os.path.getsize(p),h.hexdigest()]) +sk=rows(O+'/skips.jsonl') +for k,v in [('row_counts',cnt),('dedupe',dd),('samples',samp),('schema_validation',dict(missing=dict(miss),ok=not miss)),('skips',sk)]:json.dump(v,open(f'{RV}/{k}.json','w'),indent=1) +open(RV+'/REVIEW.md','w').write('# State rules rerun + resume (NE, DE, KS) review\nStage only, not pushed. Licence: see source terms.\n## Dedupe (vs original official run, then internal by sha256)\n'+'\n'.join(f'- {k}: {v}' for k,v in dd.items())+f'\n## Schema: {"OK" if not miss else "MISSING "+str(dict(miss))}\n## Skips\n'+'\n'.join(f"- {s.get('state')}: {s.get('reason')}" for s in sk)+'\nMerge candidates: *_new_unique.jsonl\n') diff --git a/scrapers_and_normalizers/courts/collector/review_sr.py b/scrapers_and_normalizers/courts/collector/review_sr.py new file mode 100644 index 0000000000000000000000000000000000000000..a0af356cbabc99afbac7908be2871657c6b74bfb --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/review_sr.py @@ -0,0 +1,22 @@ +import json,glob,os,hashlib,csv,collections +O=os.environ.get('SR_OUT','/workspace/courts/staging/state_rules/official');RV=os.environ.get('SR_RV','/workspace/courts/review_state_rules');os.makedirs(RV,exist_ok=True) +S=[k for k in json.load(open('/workspace/courts/schema.json'))['tables']['rules'] if not k.startswith('_')] +cnt={};miss=collections.Counter();samp={} +for f in sorted(glob.glob(O+'/[A-Z][A-Z].jsonl')): + st=os.path.basename(f)[:2];n=0 + for l in open(f): + r=json.loads(l);n+=1;miss.update(k for k in S if k not in r) + if n<=2:samp.setdefault(st,[]).append(r) + cnt[st]=n +w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256']) +for p in sorted(glob.glob(O+'/**/*',recursive=True)): + if os.path.isfile(p): + h=hashlib.sha256() + with open(p,'rb') as fh: + for c in iter(lambda:fh.read(1<<20),b''):h.update(c) + w.writerow([p,os.path.getsize(p),h.hexdigest()]) +sk=[json.loads(l) for l in open(O+'/skips.jsonl')] if os.path.exists(O+'/skips.jsonl') else [] +errs=[l for lf in glob.glob('/workspace/courts/logs/'+os.environ.get('SR_LOG','state_rules2_')+'*.log') for l in open(lf,errors='ignore') if any(k in l for k in('ERR','FAIL','DISALLOW','MEMGUARD'))] +for k,v in [('row_counts',cnt),('samples',samp),('schema_validation',dict(required=S,missing=dict(miss),ok=not miss)),('skips',sk)]:json.dump(v,open(f'{RV}/{k}.json','w'),indent=1) +open(RV+'/errors.txt','w').writelines(errs) +open(RV+'/REVIEW.md','w').write('# State court rules (official sites) review\nStage only, not pushed. Licence: see source terms (per state).\n## Rows per state\n'+'\n'.join(f'- {k}: {v}' for k,v in cnt.items())+f'\n## Schema: {"OK" if not miss else "MISSING "+str(dict(miss))}\n## Skipped\n'+'\n'.join(f"- {s.get('state')}: {s.get('reason')}" for s in sk)+f'\n## Errors: {len(errs)} lines (errors.txt)\nTransport: https only; robots.txt + Crawl-delay honored; TX at 720s/request capped at 60 docs.\n') diff --git a/scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.sh b/scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b39d926d94249a4fadb9601dc01158838a30757 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.sh @@ -0,0 +1,25 @@ +#!/bin/bash +cd /workspace/courts/collector; PY=/workspace/venv/bin/python; R=/workspace/courts +L=$R/logs/archive_resume_waiter.log; LAUNCH=$R/logs/archive_resume_launches.log +rm -f $R/STOPPED_ARCHIVE_RESUME $R/CAP_HIT_ARCHIVE_RESUME +echo "$(date -Is) waiter START pid $$" >> $L; echo $$ > $R/ARCHIVE_RESUME_WAITER.pid +while :; do + ok=0 + while [ $ok -lt 10 ]; do + n=$(ps aux | grep -E "nlm2_collect|add_collect|IT_MFR|IT_PR|NL-M|_collect\.py|state_rules[0-9]|archive_rules|archive_resume\.py" | grep -v grep | wc -l) + m=$(awk '/MemAvailable/{print $2}' /proc/meminfo) + if [ $m -ge 4404019 ] && [ $n -lt 3 ]; then ok=$((ok+1)); else ok=0; fi + echo "$(date -Is) check collectors=$n MemAvailable_kB=$m held_min=$ok" >> $L + [ $ok -ge 10 ] && break; sleep 60 + done + cut=$(( $(date +%s) - 21600 )); c=$(awk -v t=$cut '$1>=t' $LAUNCH 2>/dev/null | wc -l) + if [ $c -ge 6 ]; then echo "$(date -Is) 6 launches in 6h" > $R/CAP_HIT_ARCHIVE_RESUME; echo "$(date -Is) CAP HIT" >> $L; exit 4; fi + echo "$(date +%s) $(date -Is) launch collectors=$n MemAvailable_kB=$m" >> $LAUNCH + printf "timestamp=$(date -Iseconds)\nwaiter_pid=$$\nlaunch_no_in_6h=$((c+1))\ncollectors_running_before=$n\nMemAvailable_kB=$m (held>=4.2G 10 min)\nscope=CC archive resume DE (cached CDX) then WY; TN/LA/MI/SD kept, OK skipped. Stage only, no push.\n" > $R/COS_GO_COURTS_STATE_RULES_ARCHIVE_RESUME + $PY -u archive_resume.py >> $L 2>&1; rc=$? + echo "$(date -Is) archive_resume rc=$rc" >> $L + if [ $rc -eq 0 ]; then break; fi + echo "$(date -Is) rc=$rc (3=memguard)" > $R/STOPPED_ARCHIVE_RESUME +done +rm -f $R/STOPPED_ARCHIVE_RESUME; date -Is > $R/ARCHIVE_RESUME_DONE +$PY -u review_archive.py >> $L 2>&1 && echo "$(date -Is) review built" >> $L && date -Is > $R/review_state_rules_archive/REVIEW_READY diff --git a/scrapers_and_normalizers/courts/collector/run_archive_waiter.sh b/scrapers_and_normalizers/courts/collector/run_archive_waiter.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5b52f8e9d675215f5d6e5b7102a413a8af8f187 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_archive_waiter.sh @@ -0,0 +1,17 @@ +#!/bin/bash +cd /workspace/courts/collector; PY=/workspace/venv/bin/python +echo "$(date -Is) waiter START pid $$; waiting for 4160340" +while kill -0 4160340 2>/dev/null; do sleep 60; done +echo "$(date -Is) 4160340 exited" +while :; do + n=$(ps aux | grep -E "nlm2_collect|add_collect|IT_MFR|IT_PR|NL-M|_collect\.py|state_rules[0-9]|archive_rules" | grep -v grep | wc -l) + m=$(awk '/MemAvailable/{print $2}' /proc/meminfo) + echo "$(date -Is) check collectors=$n MemAvailable_kB=$m" + if [ $n -lt 3 ] && [ $m -ge 4404019 ]; then break; fi + sleep 600 +done +printf "timestamp=$(date -Iseconds)\npid=$$ (waiter/driver; child archive_rules.py)\ncollectors_running_before=$n\nMemAvailable_kB=$m\nscope=Common Crawl archive recovery TN OK LA MI SD DE WY (CDX + WARC range, >=6s/req, backoff on 429/5xx). Wayback content host unreachable -> not used. Stage only to staging/state_rules_archive/, no push.\n" > /workspace/courts/COS_GO_COURTS_STATE_RULES_ARCHIVE +$PY -u archive_rules.py; rc=$? +if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_ARCHIVE_RULES; exit 3; fi +date -Is > /workspace/courts/ARCHIVE_RULES_DONE +$PY -u review_archive.py && echo "$(date -Is) review built" diff --git a/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.sh b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.sh new file mode 100644 index 0000000000000000000000000000000000000000..293d745902e1581e0ea4b39caf7ef596352a8a9a --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# CoS GO 2026-10-29: single CC gap-fill launch, no relaunch. Stage only. +R=/workspace/courts; cd $R/collector; PY=/workspace/venv/bin/python; L=$R/logs/cc_gapfill_waiter.log +export SC_MEMFLOOR=3.0 SC_MAXSTRIKES=5 +echo "$(date -Is) GO launch pid $$" >> $L +nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$? +echo "$(date -Is) cc_gapfill rc=$rc" >> $L +if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE + $PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY +else echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL; fi diff --git a/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.sh b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.sh new file mode 100644 index 0000000000000000000000000000000000000000..258807ded5844d7b68f75d57e48149c5ba174d6c --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# CoS GO 2026-11-03 12:26 PT: single CC gap-fill resume, no relaunch. Stage only. +R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill_waiter.log +export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20 +ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo) +if [ $ma -lt 5242880 ]; then echo "$(date -Is) MemAvail<5G, not launching" >> $L; echo "launch gate fail" > $R/STOPPED_CC_GAPFILL_20261103; exit 1; fi +echo "$(date -Is) GO launch pid $$ (20261103)" >> $L +nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$? +echo "$(date -Is) cc_gapfill rc=$rc" >> $L +if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE + $PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY +else echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261103; fi diff --git a/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.sh b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.sh new file mode 100644 index 0000000000000000000000000000000000000000..16f20d0c308e85abc9fae7e68c606b54e88ea260 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# CoS GO 2026-11-04 09:32 PT: single CC gap-fill resume, no relaunch. Stage only. +R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill_waiter.log +export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20 +ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo) +if [ $ma -lt 5242880 ]; then echo "$(date -Is) MemAvail<5G, not launching" >> $L; echo "launch gate fail" > $R/STOPPED_CC_GAPFILL_20261104; exit 1; fi +echo "$(date -Is) GO launch pid $$ (20261104)" >> $L +nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$? +echo "$(date -Is) cc_gapfill rc=$rc" >> $L +if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE + $PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY +else echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261104; fi diff --git a/scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.sh b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9fe72dc459855f869dce3533d9c43a11328116a --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# CoS GO 2026-11-02 21:29 PT: resume CC gap-fill from checkpoints, one run, no relaunch. Stage only, NO push. +R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill.log +export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 +echo "$(date -Is) RESUME launch pid $$" >> $L +nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $R/logs/cc_gapfill_resume.log 2>&1; rc=$? +echo "$(date -Is) cc_gapfill rc=$rc" >> $R/logs/cc_gapfill_resume.log +if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE + $PY -u cc_gapfill_review.py >> $R/logs/cc_gapfill_resume.log 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY +else echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL_20261102; fi diff --git a/scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.sh b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.sh new file mode 100644 index 0000000000000000000000000000000000000000..94d4cced3cdfd36d1ea0c362619df2d9f1b5f435 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Waiter: launch CC gap-fill once (no relaunch loop). Gate: (PHASE2_DONE|STATE_COUNTY_DONE) OR other collectors<=2, AND always other collectors<=2 (we'd be <=3rd), AND MemAvail>=4.2G held 10 consecutive min. +R=/workspace/courts; cd $R/collector; PY=/workspace/venv/bin/python; L=$R/logs/cc_gapfill_waiter.log +echo $$ > $R/CC_GAPFILL_WAITER.pid; echo "$(date -Is) waiter START pid $$" >> $L +PAT='nlm2_collect|add_collect|IT_MFR|IT_PR|NL-M|_collect\.py|state_rules[0-9]|archive_rules|archive_resume\.py|state_county\.py|cc_gapfill\.py|ocr' +ok=0 +while [ $ok -lt 10 ]; do + n=$(ps -eo args | grep -E "python.*($PAT)" | grep -v grep | wc -l) + m=$(awk '/MemAvailable/{print $2}' /proc/meminfo) + p2=0; { [ -e $R/PHASE2_DONE ] || [ -e $R/STATE_COUNTY_DONE ]; } && p2=1 + if [ $m -ge 4404019 ] && [ $n -le 2 ]; then ok=$((ok+1)); else ok=0; fi + echo "$(date -Is) check other_collectors=$n phase2_done=$p2 MemAvailable_kB=$m held_min=$ok" >> $L + [ $ok -ge 10 ] && break; sleep 60 +done +printf "timestamp=$(date -Iseconds)\nwaiter_pid=$$\nother_collectors_before=$n\nphase2_done=$p2\nMemAvailable_kB=$m (>=4.2G held 10 min)\nscope=CC gap-fill AL ND WV PA (courts, courthouses, judges, forms url+sha256). Stage only, no push. Single launch, no relaunch.\n" > $R/COS_GO_COURTS_CC_GAPFILL +nice -n 10 ionice -c3 $PY -u cc_gapfill.py >> $L 2>&1; rc=$? +echo "$(date -Is) cc_gapfill rc=$rc" >> $L +if [ $rc -eq 0 ]; then + date -Is > $R/CC_GAPFILL_DONE + $PY -u cc_gapfill_review.py >> $L 2>&1 && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY && echo "$(date -Is) review built" >> $L +else + echo "$(date -Is) rc=$rc (3=memguard,4=disk,other=crash; see logs/cc_gapfill.log). No relaunch." > $R/STOPPED_CC_GAPFILL +fi +rm -f $R/CC_GAPFILL_WAITER.pid diff --git a/scrapers_and_normalizers/courts/collector/run_phase3gap.sh b/scrapers_and_normalizers/courts/collector/run_phase3gap.sh new file mode 100644 index 0000000000000000000000000000000000000000..43e2991a0f2d3d978aa73034635b43497de84851 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_phase3gap.sh @@ -0,0 +1,5 @@ +#!/bin/bash +B=/workspace/courts; cd $B/collector +echo $$ > $B/PHASE3GAP.pid +/usr/bin/python3 -u phase3gap.py >> $B/logs/phase3gap_driver.log 2>&1; rc=$? +case $rc in 0) date -Is > $B/PHASE3GAP_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,5=top_rss,1=crash). No relaunch." > $B/STOPPED_PHASE3GAP;; esac diff --git a/scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.sh b/scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.sh new file mode 100644 index 0000000000000000000000000000000000000000..81dace82328048e3abb102255d37317c610b7278 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# CoS GO 2026-11-04 09:32 PT resume (IN remaining), no relaunch, stage only +B=/workspace/courts; cd $B/collector +export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20 +ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo) +[ $ma -lt 5242880 ] && { echo "$(date -Is) launch gate fail" > $B/STOPPED_PHASE3GAP_20261104; exit 1; } +echo $$ > $B/PHASE3GAP.pid +nice -n 10 ionice -c3 /usr/bin/python3 -u phase3gap.py >> $B/logs/phase3gap_driver.log 2>&1; rc=$? +case $rc in 0) date -Is > $B/PHASE3GAP_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,5=top_rss,1=crash). No relaunch." > $B/STOPPED_PHASE3GAP_20261104;; esac diff --git a/scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.sh b/scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.sh new file mode 100644 index 0000000000000000000000000000000000000000..50f9c6507b760c9d380c015a8126bbd9c606e5ca --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# CoS GO 2026-11-04 ~09:38 PT: procedure rules wrapper, single run, NO relaunch, stage only +B=/workspace/courts; cd $B/collector +export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20 +ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo) +[ $ma -lt 5242880 ] && { echo "$(date -Is) launch gate fail" > $B/STOPPED_PROCEDURE_RULES_20261104; exit 1; } +echo $$ > $B/PROCEDURE_RULES.pid +nice -n 10 ionice -c3 /usr/bin/python3 -u procedure_rules_collect.py >> $B/logs/procedure_rules_driver.log 2>&1; rc=$? +case $rc in 0) date -Is > $B/PROCEDURE_RULES_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,1=crash). No relaunch." > $B/STOPPED_PROCEDURE_RULES_20261104;; esac diff --git a/scrapers_and_normalizers/courts/collector/run_remaining.sh b/scrapers_and_normalizers/courts/collector/run_remaining.sh new file mode 100644 index 0000000000000000000000000000000000000000..3195fcb30b47466258c384cd4585ae57d418db27 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_remaining.sh @@ -0,0 +1,11 @@ +#!/bin/bash +cd /workspace/courts/collector +PY=/workspace/venv/bin/python +echo "$(date -Is) run_remaining START pid $$" +for s in courthouses ncsc state_rules review; do + echo "$(date -Is) stage $s" + $PY -u resume.py $s; rc=$? + if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes during $s" > /workspace/courts/STOPPED; echo STOPPED; exit 3; fi + [ $rc -ne 0 ] && echo "$(date -Is) stage $s exit $rc (continuing)" +done +date -Is > /workspace/courts/DONE; echo "$(date -Is) DONE" diff --git a/scrapers_and_normalizers/courts/collector/run_state_county.sh b/scrapers_and_normalizers/courts/collector/run_state_county.sh new file mode 100644 index 0000000000000000000000000000000000000000..18fa315a64f5bd763ed00abf347b057f5c8f13b1 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_state_county.sh @@ -0,0 +1,13 @@ +#!/bin/bash +B=/workspace/courts; cd $B/collector; PY=/workspace/venv/bin/python +echo "$(date -Is) driver START pid $$ memfloor=${SC_MEMFLOOR:-4.2} maxstrikes=${SC_MAXSTRIKES:-3} gap=${SC_STRIKEGAP_S:-0}" >> $B/logs/state_county_driver.log +echo $$ > $B/STATE_COUNTY_DRIVER.pid +$PY -u state_county.py >> $B/logs/state_county_driver.log 2>&1; rc=$? +echo "$(date -Is) collector exit rc=$rc" >> $B/logs/state_county_driver.log +case $rc in + 0) date -Is > $B/STATE_COUNTY_DONE;; + 3) echo "$(date -Is) memguard ${SC_MAXSTRIKES:-3} strikes (floor ${SC_MEMFLOOR:-4.2}G)" > $B/STOPPED_STATE_COUNTY;; + 4) echo "$(date -Is) diskguard (free<12G or staging>2G)" > $B/STOPPED_STATE_COUNTY;; + 5) echo "$(date -Is) reason=courts_top_rss" > $B/STOPPED_STATE_COUNTY;; + *) echo "$(date -Is) crash rc=$rc see logs/state_county.log CRASH" > $B/STOPPED_STATE_COUNTY;; +esac diff --git a/scrapers_and_normalizers/courts/collector/run_state_rules.sh b/scrapers_and_normalizers/courts/collector/run_state_rules.sh new file mode 100644 index 0000000000000000000000000000000000000000..354d893e28b3d6cd42326fb3bbb4b901dedf15ff --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_state_rules.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /workspace/courts/collector; PY=/workspace/venv/bin/python +echo "$(date -Is) run_state_rules START pid $$" +$PY -u state_rules2.py; rc=$? +if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES; exit 3; fi +date -Is > /workspace/courts/STATE_RULES_DONE +$PY -u review_sr.py && echo "$(date -Is) review built" diff --git a/scrapers_and_normalizers/courts/collector/run_state_rules_rerun.sh b/scrapers_and_normalizers/courts/collector/run_state_rules_rerun.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f1c7c8b1f332fe98338aacd2d6f9ec7765f39ef --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_state_rules_rerun.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /workspace/courts/collector; PY=/workspace/venv/bin/python +echo "$(date -Is) rerun START pid $$" +$PY -u state_rules3.py; rc=$? +if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES_RERUN; exit 3; fi +date -Is > /workspace/courts/STATE_RULES_RERUN_DONE +SR_OUT=/workspace/courts/staging/state_rules_rerun SR_RV=/workspace/courts/review_state_rules_rerun SR_LOG=state_rules_rerun_ $PY -u review_sr.py && echo "$(date -Is) review built" diff --git a/scrapers_and_normalizers/courts/collector/run_state_rules_resume.sh b/scrapers_and_normalizers/courts/collector/run_state_rules_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..511b7c30832c9b2bc4b29cc87474bb4aa59a55ea --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/run_state_rules_resume.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /workspace/courts/collector; PY=/workspace/venv/bin/python +echo "$(date -Is) resume START pid $$" +$PY -u state_rules4.py; rc=$? +if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES_RESUME; exit 3; fi +date -Is > /workspace/courts/STATE_RULES_RESUME_DONE +$PY -u review_resume.py && echo "$(date -Is) review built" diff --git a/scrapers_and_normalizers/courts/collector/stage2.py b/scrapers_and_normalizers/courts/collector/stage2.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd161054e090cec66aaac29eeea47625a8b3a52 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/stage2.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Chained after us_fed.py (same slot): courts retry, courthouses, state rules, review package.""" +import os,sys,time,json,re,glob,hashlib,collections,asyncio,urllib.parse +sys.path.insert(0,'/workspace/courts/collector') +import us_fed as U +from us_fed import log,fetch,links,prov,sid,ST,memguard +WAIT=int(sys.argv[1]) if __name__=="__main__" and len(sys.argv)>1 else 0 +def wait(): + while WAIT and os.path.exists(f'/proc/{WAIT}'):time.sleep(30) + log('predecessor done',WAIT) +def courts_retry(): + u='https://www.uscourts.gov/about-federal-courts/court-role-and-structure/court-website-links' + r=fetch(u,timeout=180) + if not r:log('COURTS_RETRY_FAIL');return [] + out=open(f'{ST}/courts.jsonl','w');rows=[];seen=set() + for h,t in links(r[0],r[1]): + if not re.search(r'\.uscourts\.gov',h) or 'www.uscourts.gov' in h or not t:continue + root=urllib.parse.urlsplit(h);root=f'{root.scheme}://{root.netloc}/' + if root in seen:continue + seen.add(root);rec=dict(court_id=sid('url',root),name=t,name_local=t,country='US',subdivision_iso=None,level='federal',court_type='',parent_court_id=None,url=root,**prov(r[0])) + if root.startswith('http://'):rec['transport']='http_unreachable' + out.write(json.dumps(rec)+'\n');rows.append(rec) + out.close();log('courts rows',len(rows));return rows +ADDR=re.compile(r'(\d{1,6}\s+[A-Z0-9][\w .\'-]{2,60}?(?:Street|St\.?|Avenue|Ave\.?|Boulevard|Blvd\.?|Road|Rd\.?|Drive|Dr\.?|Way|Place|Pl\.?|Square|Plaza|Lane|Ln\.?|Court|Ct\.?|Parkway|Pkwy\.?|Mall|Center)\b[\w .,#-]{0,40}?),?\s+([A-Z][A-Za-z .\'-]{1,40}),\s+([A-Z]{2}|[A-Z][a-z]+(?: [A-Z][a-z]+)?)\.?\s+(\d{5}(?:-\d{4})?)') +ST2=json.load(open('/workspace/courts/collector/us_iso.json')) +AB={k.split('-')[1]:k for k in ST2};NM={v.lower():k for k,v in ST2.items()} +def text(b): + s=re.sub(r'(?is)<(script|style).*?',' ',b.decode('utf-8','ignore'));s=re.sub(r'',', ',s);s=re.sub(r'<[^>]+>',' ',s);import html;return ' '.join(html.unescape(s).split()) +def courthouses(courts): + out=open(f'{ST}/courthouses.jsonl','a');sk=open(f'{ST}/skips.jsonl','a');n=0 + for c in courts: + if c['url'].startswith('http://'):sk.write(json.dumps(dict(url=c['url'],reason='transport=http_unreachable'))+'\n');continue + r=fetch(c['url'],delay=5) + if not r:sk.write(json.dumps(dict(url=c['url'],reason='fetch_fail_or_robots'))+'\n');continue + pages=[r]+[None]*0;cand=[h for h,t in links(r[0],r[1]) if re.search(r'locat|contact|courthouse|address|divisions|offices',h+' '+t,re.I) and urllib.parse.urlsplit(h).netloc==urllib.parse.urlsplit(r[0]).netloc][:3] + for h in dict.fromkeys(cand): + if not h.startswith('https://'):continue + x=fetch(h,delay=5) + if x:pages.append(x) + seen=set() + for pu,b in pages: + for m in ADDR.finditer(text(b)): + st=m.group(3);iso=AB.get(st) or NM.get(st.lower()) + if not iso:continue + key=(m.group(1).lower()[:30],m.group(4)) + if key in seen:continue + seen.add(key) + out.write(json.dumps(dict(courthouse_id=sid(c['court_id'],*key),court_id=c['court_id'],name=c['name'],address_line=m.group(1).strip(' ,'),locality=m.group(2).strip(),postal_code=m.group(4),country='US',subdivision_iso=iso,lat=None,lon=None,content_sha256=hashlib.sha256(b).hexdigest(),**prov(pu)))+'\n');n+=1 + out.flush();sk.flush() + out.close();log('courthouses rows',n) +SUPP=['AL','AR','GA','IA','IL','IN','LA','MA','MS','NC','PA','TN','TX','VA','WY'] +def state_rules(): + d='/workspace/courts/staging/state_rules';os.makedirs(d,exist_ok=True) + os.environ['HOME']=d+'/_home' + sys.path[:0]=['/workspace/courts/pydeps','/workspace/ipfs_datasets_py_latest'] + from ipfs_datasets_py.processors.legal_scrapers.state_procedure_rules_scraper import scrape_state_procedure_rules as S + memguard() + res=asyncio.run(S(states=SUPP,max_rules=100000,include_metadata=True,rate_limit_delay=10.0,output_dir=d,write_jsonld=True,hydrate_rule_text=True,parallel_workers=1,per_state_retry_attempts=1,retry_zero_rule_states=False,per_state_timeout_seconds=7200.0)) + json.dump(res.get('metadata',{}) if isinstance(res,dict) else {},open(d+'/_run_metadata.json','w'),indent=1,default=str) + log('state_rules done',str((res or {}).get('status'))[:100]) +if __name__=='__main__': + log('STAGE2 START pid',os.getpid());wait() + for f in [lambda:courthouses(courts_retry()),state_rules]: + try:f() + except SystemExit:raise + except Exception as e:log('STAGE_ERR',repr(e)[:300]) + import review;review.build();log('STAGE2 DONE') diff --git a/scrapers_and_normalizers/courts/collector/stage_phase1.py b/scrapers_and_normalizers/courts/collector/stage_phase1.py new file mode 100644 index 0000000000000000000000000000000000000000..132e1f2572218128d7320eb2bcd3fbac3b851d87 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/stage_phase1.py @@ -0,0 +1,92 @@ +import json,glob,os,re,hashlib,collections,unicodedata +B='/workspace/courts';S=B+'/staging/state_county/phase1';H=B+'/hf_stage';O=B+'/review_state_county/phase1_push' +GAPS={'DE':'phase1 ran; official pages yielded no usable static rows','MT':'no candidate directory/judges/forms page in static landing HTML (site errors)', + 'CT':'blocked in phase0: HTTP 403 (jud.ct.gov)','VA':'blocked in phase0: HTTP 403 (vacourts.gov)','KS':'blocked in phase0: challenge page (challenge-platform)', + 'WA':'host stopped on first request: HTTP 403 (courts.wa.gov)','WI':'host stopped: hCaptcha challenge (wicourts.gov)','ND':'host stopped: HTTP 403 (ndcourts.gov), no rows'} +def cov(st): + s=st['status'] + if s=='ok':return 'complete' + if 'guard stop' in s:return 'partial_guard_stop' + if 'phase0' in s or sum(st['counts'].values())==0:return 'blocked' + return 'partial_host_stopped' +def nz(x): + x=unicodedata.normalize('NFKD',x or '').encode('ascii','ignore').decode().lower() + return re.sub(r'\s+',' ',re.sub(r'[^a-z0-9]+',' ',x)).strip() +T=['courts','courthouses','judges','forms'] +hub={t:[json.loads(l) for l in open(f'{H}/data/{t}.jsonl')] for t in T} +URL={'courts':'url','courthouses':None,'judges':None,'forms':'file_url'} +def nkey(t,r): + st=r.get('subdivision_iso') + if t=='judges':return (nz(r.get('full_name')),nz(r.get('court_name')),st) + if t=='forms':return (nz(r.get('title')),st,r.get('file_sha256')) + if t=='courthouses':return (nz(r.get('name')),st,nz(r.get('address_line'))) + return (nz(r.get('name')),st) +states={};flags={'forms_cap250':{},'transport_http_rows':collections.Counter(),'transport_http_skipped_links':collections.Counter()} +for d in sorted(glob.glob(S+'/*/status.json')): + st=json.load(open(d));states[st['state']]=st + for n in st.get('notes',[]): + if 'capped at 250' in n:flags['forms_cap250'][st['state']]=n + flags['transport_http_skipped_links'][st['state']]=sum(1 for k in st.get('skips',[]) if k.get('transport')=='http') +covmap={s:cov(v) for s,v in states.items()} +rep={'tables':{},'coverage':covmap,'gaps':GAPS,'heuristic':{'url_key':URL,'name_key':'courts: norm(name)+state; courthouses: norm(name)+state+norm(address_line); judges: norm(full_name)+norm(court_name)+state; forms: norm(title)+state+file_sha256 (title alone collides across distinct files)'}} +idremap={};out={};keptU={};keptN={} +for t in T: + seenU={r[URL[t]] for r in hub[t] if URL[t] and r.get(URL[t])};seenN={nkey(t,r) for r in hub[t]} + hubN={nkey(t,r):r for r in hub[t]};hubU={r.get(URL[t]):r for r in hub[t]} if URL[t] else {} + c=collections.Counter();new=[] + for s in sorted(states): + if s in GAPS: + c['excluded_gap_state']+=sum(1 for _ in open(f'{S}/{s}/{t}.jsonl')) if os.path.exists(f'{S}/{s}/{t}.jsonl') else 0;continue + f=f'{S}/{s}/{t}.jsonl' + if not os.path.exists(f):continue + for l in open(f): + r=json.loads(l);c['staged']+=1 + if r.get('court_id') in idremap:r['court_id']=idremap[r['court_id']] + u=r.get(URL[t]) if URL[t] else None;k=nkey(t,r) + if u and u in hubU or k in hubN: + c['dupe_hub']+=1 + if t=='courts':idremap[r['court_id']]=(hubU.get(u) or hubN[k])['court_id'] + continue + if (u and u in seenU) or k in seenN: + c['dupe_within_phase1']+=1 + if t=='courts':idremap[r['court_id']]=keptU.get(u) or keptN[k] + continue + if t=='courts': + keptN[k]=r['court_id'] + if u:keptU[u]=r['court_id'] + if u:seenU.add(u) + seenN.add(k) + if t=='judges': + if r.get('court_id') not in ({x['court_id'] for x in hub['courts']}|{x['court_id'] for x in out['courts']}): + r['court_id']=None;c['court_id_nulled_unmatched']+=1 + for x in list(r): + if x not in {'judge_id','full_name','title','court_id','court_name','roster_url','subdivision_iso','as_of','_privacy','source_url','fetched_at','archive_source','archive_timestamp','license','terms_note','robots_note','transport','content_sha256'}:r.pop(x) + r['coverage']=covmap[s];r['source_collection']='official_state_judiciary_sites_phase1_20261028' + if r.get('transport')=='http':flags['transport_http_rows'][f'{t}:{s}']+=1 + new.append(r) + out[t]=new;c['added']=len(new);c['before']=len(hub[t]);c['final']=len(hub[t])+len(new);rep['tables'][t]=dict(c) +# validate +iso=json.load(open(B+'/collector/us_iso.json'));isos=set(iso) +cids={r['court_id'] for r in hub['courts']+out['courts']};err=collections.Counter() +for t in T: + pk={'courts':'court_id','courthouses':'courthouse_id','judges':'judge_id','forms':'form_id'}[t] + ids=[r[pk] for r in hub[t]+out[t]] + if len(ids)!=len(set(ids)):err[t+':dup_pk']+=len(ids)-len(set(ids)) + for r in out[t]: + if not (r.get('subdivision_iso') or '').startswith('US-'):err[t+':bad_iso']+=1 + if r['subdivision_iso'] not in isos:err[t+':iso_not_in_fk']+=1 + for x in ['source_url','fetched_at','archive_source','license','robots_note','transport']: + if r.get(x) in (None,''):err[t+':missing_'+x]+=1 + if t in('courthouses','judges') and r.get('court_id') and r['court_id'] not in cids:err[t+':dangling_court_id']+=1 + if t=='forms' and (not r.get('file_sha256') or r.get('file_stored')):err['forms:sha_or_stored']+=1 + if r['coverage'] not in('complete','partial_host_stopped','partial_guard_stop','blocked'):err['bad_cov']+=1 +rep['validation_errors']=dict(err);rep['flags']={k:dict(v) for k,v in flags.items()} +# unify keys +for t in T: + rows=hub[t]+out[t];keys=[] + for r in rows: + for k in r: + if k not in keys:keys.append(k) + with open(f'{H}/data/{t}.jsonl','w') as fh: + for r in rows:fh.write(json.dumps({k:r.get(k) for k in keys},ensure_ascii=False)+'\n') +json.dump(rep,open(O+'/report.json','w'),indent=1);print(json.dumps(rep,indent=1)) diff --git a/scrapers_and_normalizers/courts/collector/stage_phase2.py b/scrapers_and_normalizers/courts/collector/stage_phase2.py new file mode 100644 index 0000000000000000000000000000000000000000..b0dbac3d52ace676156880bfd4740b4368a26bae --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/stage_phase2.py @@ -0,0 +1,71 @@ +import json,os,glob,shutil,hashlib,sys,datetime +B='/workspace/courts';P2=B+'/staging/state_county/phase2';RV=B+'/review_state_county/phase2' +SRC=B+'/hf_stage_fixup';OUT=B+'/hf_stage_phase2';SC='official_state_judiciary_sites_phase2_20261028' +COV={'KY':'complete','WY':'complete','ID':'complete','NV':'partial_host_stopped','MN':'partial_host_stopped','IA':'partial_rows_dropped'} +now=datetime.datetime.now().astimezone().isoformat() +hub={c:[json.loads(l) for l in open(f'{SRC}/data/{c}.jsonl')] for c in ['courts','courthouses','judges','forms']} +keys={c:list(hub[c][0]) for c in hub} +PK={'courts':'court_id','courthouses':'courthouse_id','judges':'judge_id','forms':'form_id'} +new={c:[] for c in hub} +for st in sorted(COV): + for c in hub: + f=f'{P2}/{st}/{c}.jsonl' + for l in open(f): + if l.strip(): new[c].append(json.loads(l)) +# 1) drop IA judges +ia=[r for r in new['judges'] if r['subdivision_iso']=='US-IA'] +with open(RV+'/removed_ia_judges.jsonl','w') as fh: + for r in ia: fh.write(json.dumps(dict(r,_removed_reason='CoS 2026-10-29: IA roster parse garbage (court_name from In Memoriam/staff pages), no IA courts row to link; dropped',_removed_at=now))+'\n') +new['judges']=[r for r in new['judges'] if r['subdivision_iso']!='US-IA'] +# merge IA courthouses +iac=[r for r in new['courthouses'] if r['subdivision_iso']=='US-IA'] +assert len(iac)==3 and len({r['postal_code'] for r in iac})==1 +keep=iac[0];keep['name']='Iowa Judicial Branch Building' +with open(RV+'/merged_ia_courthouses.jsonl','w') as fh: + fh.write(json.dumps({'kept_courthouse_id':keep['courthouse_id'],'merged_ids':[r['courthouse_id'] for r in iac[1:]],'reason':'same building, 1111 East Court Avenue, Des Moines 50319 (name/abbrev variants)','variants':iac,'merged_at':now})+'\n') +drop={r['courthouse_id'] for r in iac[1:]} +new['courthouses']=[r for r in new['courthouses'] if r['courthouse_id'] not in drop] +# normalize fields +for c in new: + for r in new[c]: + r['coverage']=COV[r['subdivision_iso'][3:]];r['source_collection']=SC + if c=='courts': r.setdefault('content_sha256_note',None) + new[c]=[{k:r.get(k) for k in keys[c]} for r in new[c]] +# validate strict +iso=set();m=json.load(open('/workspace/coverage/subnational_state_matrix_20261025.json')) +for r in m['rows']: iso.add(r.get('iso_3166_2') or r.get('iso')) +courtids={r['court_id'] for r in hub['courts']+new['courts']} +REQ={'courts':['court_id','name','country','source_url'],'courthouses':['courthouse_id','name','source_url'],'judges':['judge_id','full_name','source_url'],'forms':['form_id','title','file_url','file_sha256']} +val={} +for c in new: + ids=[r[PK[c]] for r in new[c]];hids={r[PK[c]] for r in hub[c]} + v={'rows':len(new[c]),'dup_ids':len(ids)-len(set(ids)),'dup_vs_hub':sum(i in hids for i in ids), + 'fk_court_missing':sum(1 for r in new[c] if r.get('court_id') and r['court_id'] not in courtids)+(sum(1 for r in new[c] if r.get('parent_court_id') and r['parent_court_id'] not in courtids) if c=='courts' else 0), + 'fk_iso_bad':sum(1 for r in new[c] if r.get('subdivision_iso') not in iso), + 'missing_required':sum(1 for r in new[c] for k in REQ[c] if not r.get(k)), + 'non_https':sum(1 for r in new[c] for k in ('source_url','url','file_url','roster_url') if r.get(k) and not r[k].startswith('https://'))+sum(r.get('transport')!='https' for r in new[c])} + if c=='judges': v['fk_court_null']=sum(1 for r in new[c] if not r.get('court_id')) + val[c]=v +bad=sum(v['dup_ids']+v['dup_vs_hub']+v['fk_court_missing']+v['fk_iso_bad']+v['missing_required']+v['non_https'] for v in val.values()) +json.dump({'generated':now,'strict_fk':True,'iso_matrix_size':len(iso),'validation':val,'total_problems':bad},open(RV+'/validation_final.json','w'),indent=1) +print(json.dumps(val,indent=1),'TOTAL_PROBLEMS',bad) +if bad or '--build' not in sys.argv: sys.exit(1 if bad else 0) +bak=B+'/hf_stage_fixup_bak_20261029_pre_phase2' +if not os.path.exists(bak): shutil.copytree(SRC,bak) +if os.path.exists(OUT): shutil.rmtree(OUT) +shutil.copytree(SRC,OUT) +for c in new: + with open(f'{OUT}/data/{c}.jsonl','a') as fh: + for r in new[c]: fh.write(json.dumps(r,ensure_ascii=False)+'\n') +s=json.load(open(OUT+'/schema.json')) +for t in s['tables'].values(): + if 'coverage' in t: t['coverage']=t['coverage'].replace('partial_guard_stop,blocked','partial_guard_stop,partial_rows_dropped,blocked') +json.dump(s,open(OUT+'/schema.json','w'),indent=1) +with open(OUT+'/README.md','a') as fh: fh.write(open(RV+'/CARD_PHASE2.md').read()) +rc={c:sum(1 for _ in open(f'{OUT}/data/{c}.jsonl')) for c in ['courthouses','courts','forms','judges','rules','state_rules']} +open(OUT+'/ROWCOUNTS.txt','w').write(''.join(f'data/{c}.jsonl {n}\n' for c,n in rc.items())) +def sh(p): + h=hashlib.sha256();h.update(open(p,'rb').read());return h.hexdigest() +fs=['README.md','ROWCOUNTS.txt','schema.json']+[f'data/{c}.jsonl' for c in rc] +open(OUT+'/MANIFEST.sha256','w').write(''.join(f'{sh(OUT+"/"+f)} {f}\n' for f in fs)) +print('BUILT',rc,{c:len(new[c]) for c in new}) diff --git a/scrapers_and_normalizers/courts/collector/state_county.py b/scrapers_and_normalizers/courts/collector/state_county.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a3136698b33bf49d3066ca2379cbe495c5a1c9 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/state_county.py @@ -0,0 +1,465 @@ +#!/usr/bin/env python3 +"""State+county courthouses/courts/judges/forms collector. Phases 0,1,2 (+FL in 2; SC deferred). +Locked limits: HTTPS only, TLS verify, keyless, max(10s,crawl-delay)/host, stop host on first 403/429/challenge, +memguard <4.2G pause / 3 strikes stop (exit 3), disk free<12G or staging>2G stop (exit 4). PDFs: url+sha256 only.""" +import os, sys, re, json, time, csv, hashlib, threading, shutil, datetime, urllib.parse as up +import requests +from bs4 import BeautifulSoup +from concurrent.futures import ThreadPoolExecutor +BASE='/workspace/courts'; ST_DIR=f'{BASE}/staging/state_county'; RV=f'{BASE}/review_state_county' +LOG=open(f'{BASE}/logs/state_county.log','a',buffering=1) +UA='Mozilla/5.0 (compatible; justicedao-court-research/0.2; +https://huggingface.co/justicedao)' +PH1='AK AZ CA CT GA HI IL IN MD ME MT NE OH OR PA RI TX UT VA WA WI WV DE AR AL KS ND'.split() +PH2='CO KY WY NM ID NV MN MS IA FL'.split() +DEFERRED={'SC':'deferred-by-crawl-delay: robots Crawl-delay 120000s (~33.3h/request); not fetched'} +NEVER=set('CA IL OR WA WI CT VA KS'.split()) +LIC='see source terms (US state government judiciary website)' +MAXP={'courthouses':40,'judges':40,'forms':30}; MAXFILES=250; MAXFILEBYTES=40*2**20; MAXHTMLBYTES=5*2**20; TIMEOUT=(15,30) +CHALL=['cf-chl','challenge-platform','just a moment...','g-recaptcha','hcaptcha','cf-turnstile','leastfactor','_incapsula_','access denied','attention required','px-captcha'] +STOP=threading.Event(); STOPRC=[0]; strikes=[0]; mlock=threading.Lock() +def now(): return datetime.datetime.now().astimezone().isoformat(timespec='seconds') +def log(*a): LOG.write(now()+' '+' '.join(map(str,a))+'\n') +def memavail(): + for l in open('/proc/meminfo'): + if l.startswith('MemAvailable'): return int(l.split()[1])/2**20 +def du(p): + t=0 + for r,_,fs in os.walk(p): + for f in fs: + try: t+=os.path.getsize(os.path.join(r,f)) + except OSError: pass + return t +def memstrike_top5(): + try: + rows=[] + for d in os.listdir('/proc'): + if not d.isdigit(): continue + try: + rss=0 + for l in open(f'/proc/{d}/status'): + if l.startswith('VmRSS'): rss=int(l.split()[1]); break + cmd=open(f'/proc/{d}/cmdline','rb').read().replace(b'\0',b' ').decode('utf-8','replace').strip() + rows.append((rss,d,cmd)) + except OSError: pass + rows.sort(reverse=True) + for rss,pid,cmd in rows[:5]: log(f'MEMSTRIKE strike={strikes[0]} pid={pid} rss={rss/1024:.0f}MB cmd={cmd[:160]}') + except Exception as e: log('MEMSTRIKE err',repr(e)[:200]) +MEMFLOOR=float(os.environ.get('SC_MEMFLOOR','4.2')); MAXSTRIKES=int(os.environ.get('SC_MAXSTRIKES','3')); STRIKEGAP=float(os.environ.get('SC_STRIKEGAP_S','0')) +lastcounted=[0.0]; MYPID=os.getpid() +def ours(pid,cmd): + if '/workspace/courts' in cmd: return True + try: + p=int(pid) + while p>1: + if p==MYPID: return True + p=int(open(f'/proc/{p}/stat').read().rsplit(')',1)[1].split()[1]) + except Exception: pass + return False +def memstrike_top5(): + try: + rows=[] + for d in os.listdir('/proc'): + if not d.isdigit(): continue + try: + rss=0 + for l in open(f'/proc/{d}/status'): + if l.startswith('VmRSS'): rss=int(l.split()[1]); break + cmd=open(f'/proc/{d}/cmdline','rb').read().replace(b'\0',b' ').decode('utf-8','replace').strip() + rows.append((rss,d,cmd)) + except OSError: pass + rows.sort(reverse=True) + for rss,pid,cmd in rows[:5]: log(f'MEMSTRIKE strike={strikes[0]} pid={pid} rss={rss/1024:.0f}MB cmd={cmd[:160]}') + if rows and ours(rows[0][1],rows[0][2]): return 'courts_top_rss' + except Exception as e: log('MEMSTRIKE err',repr(e)[:200]) + return None +def guards(): + if STOP.is_set(): return False + with mlock: + if shutil.disk_usage('/workspace').free/2**30<12 or du(ST_DIR)>2*2**30: + log('DISKGUARD stop'); STOPRC[0]=4; STOP.set(); return False + m=memavail() + if m=STRIKEGAP) + if counted: strikes[0]+=1; lastcounted[0]=t + log(f'MEMGUARD strike {strikes[0]} memavail={m:.2f}G counted={counted} floor={MEMFLOOR} max={MAXSTRIKES} gap={STRIKEGAP}s') + if memstrike_top5()=='courts_top_rss': + log('MEMGUARD courts_top_rss stop'); STOPRC[0]=5; STOP.set(); return False + if strikes[0]>=MAXSTRIKES: STOPRC[0]=3; STOP.set(); return False + for _ in range(60): + time.sleep(10) + if memavail()>=MEMFLOOR: break + else: STOPRC[0]=3; STOP.set(); return False + return True +class HostBlocked(Exception): pass +class Host: + def __init__(s,host): s.host=host; s.delay=10; s.last=0; s.blocked=None; s.n=0; s.robots=None; s.lock=threading.Lock() +HOSTS={}; HL=threading.Lock() +SESS=requests.Session(); SESS.headers['User-Agent']=UA +BLF=f'{ST_DIR}/blocked_hosts.json' +def save_block(h,why): + with HL: + d=json.load(open(BLF)) if os.path.exists(BLF) else {} + d[h]={'reason':why,'at':now()}; json.dump(d,open(BLF,'w'),indent=1) +def load_blocks(): + if os.path.exists(BLF): + for h,v in json.load(open(BLF)).items(): gethost(h).blocked=v['reason']+' (persisted)' +def gethost(h): + with HL: + if h not in HOSTS: HOSTS[h]=Host(h) + return HOSTS[h] +def is_chall(r,body): + if r.status_code in (403,429): return f'http {r.status_code}' + b=body[:30000].lower() + for m in CHALL: + if m in b: return f'challenge marker {m!r} (http {r.status_code})' + return None +def fetch(url,stream=False): + """returns (resp, body_bytes or None, sha256, nbytes). Raises HostBlocked.""" + p=up.urlparse(url) + if p.scheme!='https': return None + H=gethost(p.netloc) + with H.lock: + if H.blocked: raise HostBlocked(H.blocked) + if H.robots is None: _robots(H) + if not guards(): raise HostBlocked('guard stop') + w=H.last+H.delay-time.time() + if w>0: time.sleep(w) + H.last=time.time(); H.n+=1 + try: + r=SESS.get(url,timeout=TIMEOUT,stream=True,allow_redirects=True) + except requests.RequestException as e: + log('ERR',url,repr(e)[:200]); return None + if up.urlparse(r.url).scheme!='https': r.close(); return None + ct=r.headers.get('content-type','') + keep=(not stream) and ('html' in ct.lower() or 'xml' in ct.lower() or r.status_code in (403,429)) # buffer HTML only; forms/PDFs hashed on the fly + h=hashlib.sha256(); n=0; chunks=[] + try: + for c in r.iter_content(65536): + h.update(c); n+=len(c) + if keep: + if n>MAXHTMLBYTES: log('HTMLCAP',url); keep=False; chunks=[]; break + chunks.append(c) + if n>MAXFILEBYTES: log('TOOBIG',url); break + except requests.RequestException as e: log('ERR read',url,repr(e)[:200]) + finally: r.close() + H.last=time.time() + body=b''.join(chunks) if (not stream and chunks) else (b'' if not stream else None) + if r.status_code in (403,429) or ('html' in ct and body is not None): + c=is_chall(r,(body or b'').decode('utf-8','replace')) + if c: + H.blocked=f'{c} at {url}'; log('BLOCK',p.netloc,H.blocked); save_block(p.netloc,H.blocked); raise HostBlocked(H.blocked) + log('GET',r.status_code,n,url) + return r,body,h.hexdigest(),n +def _robots(H): + H.robots='' + try: + w=H.last+H.delay-time.time() + if w>0: time.sleep(w) + r=SESS.get(f'https://{H.host}/robots.txt',timeout=TIMEOUT); H.last=time.time(); H.n+=1 + if r.status_code==200 and 'html' not in r.headers.get('content-type',''): + H.robots=r.text[:200000] + ua=None + for l in H.robots.splitlines(): + l=l.split('#')[0].strip(); k,_,v=l.partition(':'); k=k.strip().lower(); v=v.strip() + if k=='user-agent': ua=v + elif k=='crawl-delay' and ua=='*': + try: H.delay=max(H.delay,float(v)) + except ValueError: pass + log('ROBOTS',H.host,r.status_code,'delay',H.delay) + except requests.RequestException as e: log('ERR robots',H.host,repr(e)[:200]) +KW={'courthouses':['court directory','court locations','find a court','find your court','courts by county','courthouse','court location','directory','locations','county court','district court','circuit court','courts'], + 'judges':['judicial directory','judge directory','judicial officers','judges','justices','meet the','magistrates','judicial officer','bench'], + 'forms':['forms','self-help forms','court forms','form','self help','self-represented','pro se']} +NEG=['opinion','calendar','docket','job','career','employ','news','press','rule','fee','pay','efil','e-fil','login','sign in','search case','case search','jury','media','event','bid','procure','budget','report','vacanc','select','elect','retention','insurance','liability','notice','petition','evaluation','discipline','conduct','closure','emergency','federal','tribal','translated','contact'] +def links(base,soup): + out=[] + for a in soup.find_all('a',href=True): + try: u=up.urljoin(base,a['href'].strip()).split('#')[0] + except ValueError: continue + if not u.startswith(('http://','https://')): continue + out.append((u,' '.join(a.get_text(' ').split())[:200])) + return out +def score(cat,u,t): + s=(t+' '+up.unquote(u)).lower(); sc=0 + for i,k in enumerate(KW[cat]): + if k in s: sc+=10-min(i,8) + if any(n in s for n in NEG): sc-=6 + return sc +def samesite(u,root): + a=up.urlparse(u).netloc.lower(); b=root.lower() + reg=lambda h:'.'.join(h.split('.')[-2:]) + return a==b or reg(a)==reg(b) +def landing_urls(): + d={} + for r in csv.DictReader(open(f'{BASE}/state_county_source_inventory.csv')): d.setdefault(r['state'],r['url']) + return d +ISO=json.load(open(f'{BASE}/collector/us_iso.json')) +NAMES={v:k[3:] for k,v in ISO.items()} +def prov(url,sha,extra=None): + d={'source_url':url,'fetched_at':now(),'archive_source':'live','archive_timestamp':None,'license':LIC, + 'terms_note':'official state judiciary site; public record; cite source','robots_note':'robots advisory (official gov host); crawl-delay honored', + 'transport':'https','content_sha256':sha} + if extra: d.update(extra) + return d +def sid(*a): return hashlib.sha1('|'.join(map(str,a)).encode()).hexdigest()[:16] +# ---------------- Phase 0 ---------------- +def phase0_state(st): + out=f'{ST_DIR}/phase0/{st}.json' + if os.path.exists(out): return + res={'state':st,'subdivision_iso':f'US-{st}','landing':None,'candidates':{},'chosen':{},'status':'ok','notes':[]} + if st in DEFERRED: + res['status']='deferred'; res['notes'].append(DEFERRED[st]); json.dump(res,open(out,'w'),indent=1); return + url=landing_urls()[st]; res['landing']=url + try: + f=fetch(url) + if not f or f[0].status_code!=200: res['status']=f'landing fail {f[0].status_code if f else "neterr/http"}' + else: + r,b,sha,n=f; base=r.url; soup=BeautifulSoup(b,'lxml'); L=links(base,soup) + if len(L)<8: res['notes'].append(f'only {len(L)} links in static HTML (JS-rendered?)') + for cat in KW: + c=sorted({(score(cat,u,t),u,t) for u,t in L if samesite(u,up.urlparse(base).netloc) and score(cat,u,t)>0 and not up.urlparse(u).path.lower().endswith(FILEEXT)},reverse=True)[:5] + res['candidates'][cat]=[{'score':s,'url':u,'text':t} for s,u,t in c] + for cat in KW: # verify top https candidate (1 req per category) + for cand in res['candidates'][cat]: + if not cand['url'].startswith('https://'): res['notes'].append(f'{cat}: http-only {cand["url"]} (transport=http, not fetched)'); continue + if cand['url'] in res['chosen'].values(): + res['chosen'][cat]=cand['url']; break + g=fetch(cand['url']) + if g and g[0].status_code==200: res['chosen'][cat]=g[0].url; break + res['notes'].append(f'{cat}: {cand["url"]} -> {g[0].status_code if g else "err"}') + if len([x for x in res['notes'] if x.startswith(cat+':')])>=2: break + except HostBlocked as e: res['status']=f'blocked: {e}' + json.dump(res,open(out,'w'),indent=1); log('P0',st,res['status'],res['chosen']) +# ---------------- extraction ---------------- +TITLES=r'(Chief Justice|Associate Justice|Justice|Chief Judge|Presiding Judge|Senior Judge|Associate Judge|District Judge|Circuit Judge|Superior Court Judge|County Judge|Probate Judge|Family Court Judge|Judge|Magistrate Judge|Chief Magistrate|Magistrate|Commissioner|Associate Circuit Judge)' +NM=r"([A-Z][a-zA-Z\.'\-]+(?:\s+[A-Z][a-zA-Z\.'\-]*\.?){1,4}(?:,?\s+(?:Jr\.|Sr\.|II|III|IV))?)" +J1=re.compile(r'^(?:The\s+)?(?:Hon(?:orable|\.)\s+)?'+TITLES+r'\s+'+NM+r'$') +J2=re.compile(r'^(?:The\s+)?(?:Hon(?:orable|\.)\s+)?'+NM+r',?\s+[-–]?\s*'+TITLES+r'$') +J3=re.compile(r'^(?:The\s+)?Hon(?:orable|\.)\s+'+NM+r'$') +BADW=re.compile(r'\b(Court|County|Rules?|Office|Clerk|Division|District|Department|Circuit|Judicial|Contact|Directory|Search|Forms?|Home|Menu|Program|Services?|Center|Information|Opinions?|Calendar|Online|Click|More|View|Page|Map|Phone|Fax|Email)\b') +def lines_with_ctx(soup): + for t in soup(['script','style','noscript','nav','footer','header']): t.decompose() + out=[]; head=None + title=(soup.title.get_text(' ').strip() if soup.title else '') + for el in soup.find_all(['h1','h2','h3','h4','h5','p','li','td','th','div','span','strong','b','address','dt','dd','a']): + if el.name in('h1','h2','h3','h4','h5'): + head=' '.join(el.get_text(' ').split())[:200] + text=soup.get_text('\n') + cur=title; res=[] + hs={' '.join(h.get_text(' ').split()) for h in soup.find_all(['h1','h2','h3','h4','h5'])} + for l in text.split('\n'): + l=' '.join(l.split()) + if not l: continue + if l in hs: cur=l + res.append((l,cur)) + return res,title +def ext_judges(st,url,sha,soup): + rows=[]; L,title=lines_with_ctx(soup); seen=set() + for l,ctx in L: + if len(l)>90: continue + m=J1.match(l); name=title_=None + if m: title_,name=m.group(1),m.group(2) + else: + m=J2.match(l) + if m: name,title_=m.group(1),m.group(2) + else: + m=J3.match(l) + if m: name,title_=m.group(1),'Judge (Honorable)' + if not name: continue + name=name.strip(' ,'); + if BADW.search(name) or len(name.split())<2 or len(name)>60: continue + court=ctx if ctx and 'court' in ctx.lower() else (title if 'court' in title.lower() else ctx or title) + k=(name,title_,court) + if k in seen: continue + seen.add(k) + rows.append(dict(judge_id=sid(st,name,court),full_name=name,court_id=sid(st,'court',court) if court else None,court_name=court, + title=title_,subdivision_iso=f'US-{st}',as_of=datetime.date.today().isoformat(),roster_url=url, + _privacy='official public roster only: name, court, title',**prov(url,sha))) + return rows +CITY=lambda st: re.compile(r"^([A-Z][A-Za-z\.'\- ]{1,40}),?\s+(?:"+st+'|'+re.escape(ISO[f'US-{st}'])+r")\.?,?\s+(\d{5})(?:-\d{4})?$") +STREET=re.compile(r'^(\d{1,6}\s+\S.{2,80}|P\.?\s?O\.?\s+Box\s+\d+.*)$',re.I) +NAMEOK=re.compile(r'(Court|Courthouse|Justice Center|Judicial|Clerk|Hall of Justice|Building|Magistrate|Center|Complex)',re.I) +def ext_courthouses(st,url,sha,soup): + rows=[]; L,title=lines_with_ctx(soup); cre=CITY(st); seen=set() + for i,(l,ctx) in enumerate(L): + m=cre.match(l) + if not m or i==0: continue + street=L[i-1][0] + if not STREET.match(street): + # street and city on one line? + continue + name=None + for j in range(i-2,max(-1,i-5),-1): + c=L[j][0] + if NAMEOK.search(c) and len(c)<120 and not STREET.match(c): name=c; break + name=name or (ctx if ctx and NAMEOK.search(ctx) else None) + if not name: continue + k=(name,street) + if k in seen: continue + seen.add(k) + rows.append(dict(courthouse_id=sid(st,name,street),court_id=sid(st,'court',name) if 'court' in name.lower() else None,name=name, + address_line=street,locality=m.group(1).strip(),postal_code=m.group(2),country='US',subdivision_iso=f'US-{st}', + lat=None,lon=None,**prov(url,sha))) + return rows +FILEEXT=('.pdf','.doc','.docx','.rtf','.dot','.dotx','.xls','.xlsx','.odt') +FNUM=re.compile(r'\b([A-Z]{1,6}[- ]?\d{1,5}(?:[-.]\d{1,4})?[A-Z]?)\b') +def ext_formlinks(base,soup): + out=[] + for u,t in links(base,soup): + path=up.urlparse(u).path.lower() + if path.endswith(FILEEXT): out.append((u,t)) + return out +def classify_level(name): + n=name.lower() + for k,v in [('supreme','state'),('appeal','state'),('appellate','state'),('county','county'),('municipal','municipal'),('city','municipal'),('district','district'),('circuit','district'),('superior','county'),('probate','county'),('magistrate','county'),('justice','municipal'),('family','county')]: + if k in n: return v + return 'state' +# ---------------- Phase 1/2 per state ---------------- +def collect_state(ph,st): + d=f'{ST_DIR}/phase{ph}/{st}'; os.makedirs(d,exist_ok=True) + if os.path.exists(f'{d}/DONE'): return + if st in NEVER: log('SKIP never-retry state',st); return + disc=json.load(open(f'{ST_DIR}/phase0/{st}.json')) if os.path.exists(f'{ST_DIR}/phase0/{st}.json') else {} + status={'state':st,'status':'ok','notes':[],'pages':{},'skips':[]} + if st in DEFERRED: status['status']='deferred'; status['notes'].append(DEFERRED[st]) + elif str(disc.get('status','')).startswith('blocked'): status['status']='host stopped in phase0: '+disc['status'] + elif not disc.get('chosen') and not disc.get('landing'): status['status']='no discovery' + tables={k:[] for k in ('judges','courthouses','forms')} + ck=f'{d}/ckpt.json'; ckd=json.load(open(ck)) if os.path.exists(ck) else {} + if status['status']=='ok': + try: + for cat in ('courthouses','judges','forms'): + if cat in ckd: tables[cat]=[json.loads(l) for l in open(f'{d}/{cat}.jsonl')]; continue + start=disc.get('chosen',{}).get(cat) + if not start: status['skips'].append({'table':cat,'reason':'no candidate page found in static landing HTML'}); ckd[cat]=0; continue + root=up.urlparse(start).netloc; q=[start]; seen={start}; npg=0; files=[] + while q and npg0 or (cat!='forms' and re.search(r'county|district|circuit|court',lt,re.I) and up.urlparse(lu).path.startswith(up.urlparse(start).path.rsplit('/',1)[0])): + seen.add(lu) + if lu.startswith('https://'): q.append(lu) + else: status['skips'].append({'url':lu,'reason':'http-only link not fetched','transport':'http'}) + if cat=='judges': tables['judges']+=ext_judges(st,r.url,sha,soup) + if cat=='courthouses': tables['courthouses']+=ext_courthouses(st,r.url,sha,soup) + # courthouse/judge info often co-located + if cat=='courthouses': tables['judges']+=[] + status['pages'][cat]=npg + if cat=='forms': + for fu,ft,src in files[:MAXFILES]: + if STOP.is_set(): break + if not fu.startswith('https://'): status['skips'].append({'url':fu,'reason':'http-only form not fetched','transport':'http'}); continue + g=fetch(fu,stream=True) + if not g or g[0].status_code!=200: status['skips'].append({'url':fu,'reason':f'form fetch {g[0].status_code if g else "err"}'}); continue + r,_,sha,n=g; fn=up.unquote(up.urlparse(fu).path.rsplit('/',1)[-1]) + m=FNUM.search(ft) or FNUM.search(fn.rsplit('.',1)[0].upper()) + lang='es' if re.search(r'spanish|espa[nñ]ol',ft+fn,re.I) else 'en' + tables['forms'].append(dict(form_id=sid(st,fu),form_number=m.group(1) if m else None,title=ft or fn,court_id=None, + subdivision_iso=f'US-{st}',language=lang,file_url=r.url,file_format=fn.rsplit('.',1)[-1].lower() if '.' in fn else None, + file_sha256=sha,file_cid=None,file_bytes=n,effective_date=None,last_modified=r.headers.get('last-modified'),**prov(src,sha,{'file_stored':False}))) + if len(files)>MAXFILES: status['notes'].append(f'forms capped at {MAXFILES} of {len(files)} file links') + if STOP.is_set(): break + # dedupe + checkpoint + k={'judges':'judge_id','courthouses':'courthouse_id','forms':'form_id'}[cat] + u={}; [u.setdefault(x[k],x) for x in tables[cat]]; tables[cat]=list(u.values()) + with open(f'{d}/{cat}.jsonl','w') as fo: + for x in tables[cat]: fo.write(json.dumps(x)+'\n') + ckd[cat]=len(tables[cat]); json.dump(ckd,open(ck,'w')) + except HostBlocked as e: + status['status']=f'host stopped: {e}'; status['skips'].append({'reason':str(e)}) + if STOP.is_set() and status['status']=='ok': return # leave for resume + # judges also: dedupe; write partials if blocked + for cat in ('courthouses','judges','forms'): + if not os.path.exists(f'{d}/{cat}.jsonl') or cat not in ckd: + with open(f'{d}/{cat}.jsonl','w') as fo: + for x in tables[cat]: fo.write(json.dumps(x)+'\n') + # courts derived from courthouse + judge court names + courts={} + for x in tables['courthouses']+tables['judges']: + nm=x.get('name') if 'courthouse_id' in x else x.get('court_name') + cid=x.get('court_id') + if not cid or not nm or 'court' not in nm.lower(): continue + courts.setdefault(cid,dict(court_id=cid,name=nm,name_local=nm,country='US',subdivision_iso=f'US-{st}',level=classify_level(nm), + court_type=None,parent_court_id=None,url=x['source_url'],**{k:x[k] for k in ('source_url','fetched_at','archive_source','archive_timestamp','license','terms_note','robots_note','transport','content_sha256')})) + with open(f'{d}/courts.jsonl','w') as fo: + for x in courts.values(): fo.write(json.dumps(x)+'\n') + status['counts']={'courts':len(courts),**{k:len(v) for k,v in tables.items()}} + json.dump(status,open(f'{d}/status.json','w'),indent=1) + if 'guard stop' not in str(status['status']) and not STOP.is_set(): open(f'{d}/DONE','w').write(now()) + log('STATE DONE',ph,st,status['status'],status.get('counts')) +def review(ph,states): + out=f'{RV}/phase{ph}'; os.makedirs(out,exist_ok=True) + mat=json.load(open('/workspace/coverage/subnational_state_matrix_20261025.json'))['rows'] + fk={r.get('iso_3166_2') for r in mat}|{r.get('iso') for r in mat if r.get('iso')} + rep={'phase':ph,'generated':now(),'states':{},'validation':{},'skips':{}} + man=[] + if ph==0: + for st in states: + p=f'{ST_DIR}/phase0/{st}.json' + if os.path.exists(p): j=json.load(open(p)); rep['states'][st]={'status':j['status'],'chosen':j['chosen'],'notes':j['notes']}; man.append(p) + else: + req={'courts':['court_id','name','subdivision_iso','source_url','content_sha256'],'courthouses':['courthouse_id','name','address_line','locality','postal_code','subdivision_iso','source_url','content_sha256'], + 'judges':['judge_id','full_name','title','roster_url','subdivision_iso','source_url','content_sha256'],'forms':['form_id','title','file_url','file_sha256','subdivision_iso','source_url']} + val={t:{'rows':0,'missing_required':0,'bad_fk':0,'dup_ids':0,'non_https':0} for t in req} + samples={t:[] for t in req} + for st in states: + d=f'{ST_DIR}/phase{ph}/{st}' + if not os.path.exists(f'{d}/status.json'): rep['states'][st]={'status':'not finished'}; continue + s=json.load(open(f'{d}/status.json')); rep['states'][st]={'status':s['status'],'counts':s.get('counts'),'pages':s.get('pages'),'notes':s['notes']} + rep['skips'][st]=s['skips'][:50] + for t in req: + p=f'{d}/{t}.jsonl' + if not os.path.exists(p): continue + man.append(p); ids=set(); pk=req[t][0] + for l in open(p): + x=json.loads(l); v=val[t]; v['rows']+=1 + if any(x.get(k) in (None,'') for k in req[t]): v['missing_required']+=1 + if x.get('subdivision_iso') not in fk: v['bad_fk']+=1 + if x[pk] in ids: v['dup_ids']+=1 + ids.add(x[pk]) + if x.get('transport')!='https': v['non_https']+=1 + if len(samples[t])<15 and (len(samples[t])<3 or hash(x[pk])%7==0): samples[t].append(x) + rep['validation']=val + json.dump(samples,open(f'{out}/samples.json','w'),indent=1) + rep['hosts']={h:{'requests':H.n,'delay_s':H.delay,'blocked':H.blocked} for h,H in HOSTS.items()} + json.dump(rep,open(f'{out}/report.json','w'),indent=1) + with open(f'{out}/MANIFEST.sha256','w') as fo: + for p in man: fo.write(hashlib.sha256(open(p,'rb').read()).hexdigest()+' '+os.path.relpath(p,BASE)+'\n') + open(f'{out}/REVIEW_READY','w').write(now()); log('REVIEW_READY',ph) +def run_pool(fn,states,ph=None): + with ThreadPoolExecutor(1) as ex: + list(ex.map(lambda s:(fn(ph,s) if ph is not None else fn(s)),states)) +def main(): + os.makedirs(f'{ST_DIR}/phase0',exist_ok=True) + allst=PH1+PH2+list(DEFERRED) + log('START pid',os.getpid(),f'memfloor={MEMFLOOR} maxstrikes={MAXSTRIKES} strikegap={STRIKEGAP}s') + if not os.path.exists(BLF): + for st in allst: + p=f'{ST_DIR}/phase0/{st}.json' + if os.path.exists(p): + m=re.search(r'blocked: (.*) at (https://[^/]+)/',json.load(open(p))['status']) + if m: save_block(up.urlparse(m.group(2)).netloc,m.group(0)) + load_blocks() + if not os.path.exists(f'{BASE}/PHASE0_DONE'): + run_pool(phase0_state,allst) + if STOP.is_set(): return STOPRC[0] + review(0,allst); open(f'{BASE}/PHASE0_DONE','w').write(now()) + for ph,sts in ((1,PH1),(2,PH2)): + if os.path.exists(f'{BASE}/PHASE{ph}_DONE'): continue + run_pool(collect_state,sts,ph) + if STOP.is_set(): return STOPRC[0] + review(ph,sts); open(f'{BASE}/PHASE{ph}_DONE','w').write(now()) + return 0 +if __name__=='__main__': + try: rc=main() + except Exception as e: + import traceback; log('CRASH',traceback.format_exc()); rc=1 + log('EXIT rc',rc); sys.exit(rc) diff --git a/scrapers_and_normalizers/courts/collector/state_rules2.py b/scrapers_and_normalizers/courts/collector/state_rules2.py new file mode 100644 index 0000000000000000000000000000000000000000..52981f965a4467ce676b1c1773b5e00c270cca31 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/state_rules2.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Official state court rules index collector (stage only). Sequential, 1 req/10s+, robots/Crawl-delay honored, HTTPS only.""" +import sys,os,json,re,urllib.parse,hashlib +sys.path.insert(0,'/workspace/courts/collector') +import us_fed as U +from us_fed import log,fetch,links,sid,now +OUT='/workspace/courts/staging/state_rules/official';os.makedirs(OUT+'/files',exist_ok=True) +S=[('AK','https://courts.alaska.gov/rules/index.htm'),('AZ','https://www.azcourts.gov/rules'),('CT','https://www.jud.ct.gov/pb.htm'),('DE','https://courts.delaware.gov/rules/'),('HI','https://www.courts.state.hi.us/legal_references/rules/rulesOfCourt'),('KS','https://www.kscourts.gov/Rules-Orders/Rules'),('MI','https://www.courts.michigan.gov/rules-administrative-orders-and-jury-instructions/'),('MN','https://www.revisor.mn.gov/court_rules/'),('NV','https://www.leg.state.nv.us/CourtRules/'),('ND','https://www.ndcourts.gov/legal-resources/rules'),('OH','https://www.supremecourt.ohio.gov/laws-rules/ohio-rules-of-court/'),('OK','https://www.oscn.net/applications/oscn/index.asp?ftdb=STOKRU'),('OR','https://www.courts.oregon.gov/rules/Pages/default.aspx'),('SD','https://sdlegislature.gov/Statutes/15'),('UT','https://legacy.utcourts.gov/rules/'),('WA','https://www.courts.wa.gov/court_rules/'),('WV','https://www.courtswv.gov/legal-community/court-rules'),('LA','https://www.lasc.org/Rules'),('TN','https://www.tncourts.gov/rules'), + ('CA','https://courts.ca.gov/forms-rules/rules-court'),('MD','https://www.mdcourts.gov/rules'),('NE','https://nebraskajudicial.gov/supreme-court-rules'),('VT','https://www.vtcourts.gov/attorneys/rules'),('MT','https://courts.mt.gov/Courts/rules/'),('RI','https://www.courts.ri.gov/Legal-Resources/Pages/court-rules.aspx'),('ME','https://www.courts.maine.gov/rules/index.html'), + ('TX','https://www.txcourts.gov/rules-forms/rules-standards/')] +SKIP={'SC':'crawl-delay-limited: robots Disallow / + Crawl-delay 120000s; not fetched','NM':'nmonesource.com (NM Compilation Commission, official) but page 403 + robots Disallow /; skipped, no bypass','ID':'URL unresolved (rules page 404)','NY':'nycourts.gov rules page 403 on URL fix; skipped',**{s:'403 at probe; skipped per CoS' for s in 'CO DC FL KY MO NH NJ WY'.split()}} +RULE=re.compile(r'rule|court-rules|courtrules|procedure|\.pdf',re.I) +def run(st,idx,cap=None): + done_f=f'{OUT}/{st}.jsonl' + if os.path.exists(done_f+'.done'):return + cap=cap or (60 if st=="TX" else 300);delay=720 if st=="TX" else 10 + r=fetch(idx,delay=delay) + if not r:log('STATE_FAIL',st,idx);open(f'{OUT}/skips.jsonl','a').write(json.dumps(dict(state=st,url=idx,reason='index fetch fail/robots'))+'\n');return + host=urllib.parse.urlsplit(r[0]).netloc;seen=set();n=0 + cand=[(h,t) for h,t in links(r[0],r[1]) if h.startswith('https://') and urllib.parse.urlsplit(h).netloc==host and RULE.search(h+' '+t) and h.split('#')[0]!=r[0]] + with open(done_f,'w') as o: + for h,t in cand: + h=h.split('#')[0] + if h in seen or n>=cap:continue + seen.add(h);fn=f'{OUT}/files/{st}_{sid(h)}';g=fetch(h,delay=delay,stream_to=fn) + if not g:continue + fu,sha,nb=g + o.write(json.dumps(dict(rule_id=sid(st,h),rule_set=f'{st} court rules',citation='',title=t,text=None,court_id=None,subdivision_iso='US-'+st,effective_date=None,version='',file_url=fu,file_sha256=sha,file_bytes=nb,local_path=fn,content_sha256=sha,source_url=r[0],fetched_at=now(),archive_source='live',archive_timestamp=None,license='see source terms (state-specific)',terms_note='',robots_note='robots.txt honored',transport='https'))+'\n');o.flush();n+=1 + open(done_f+'.done','w').write(now());log('STATE',st,'rows',n,'of',len(cand),'candidates') +if __name__=='__main__': + log('STATE_RULES2 START pid',os.getpid()) + with open(f'{OUT}/skips.jsonl','a') as f: + for k,v in SKIP.items():f.write(json.dumps(dict(state=k,reason=v))+'\n') + for st,u in S: + try:run(st,u) + except SystemExit:raise + except Exception as e:log('STATE_ERR',st,repr(e)[:200]) + log('STATE_RULES2 DONE') diff --git a/scrapers_and_normalizers/courts/collector/state_rules3.py b/scrapers_and_normalizers/courts/collector/state_rules3.py new file mode 100644 index 0000000000000000000000000000000000000000..023a43b102b89bc62dc045923c31b71cb514d0f3 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/state_rules3.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Rerun: NE (malformed-link fix), DE (parser fix), KS (cap lifted). Stage only.""" +import sys,os,json,re,urllib.parse,html +sys.path.insert(0,'/workspace/courts/collector') +import us_fed as U, state_rules2 as S2 +from us_fed import log +HREF=re.compile(r']*?href\s*=\s*["\']([^"\']+)["\'][^>]*>(.*?)',re.I|re.S) +def safe_links(base,b): + out=[] + for h,t in HREF.findall(b.decode('utf-8','ignore')): + h=html.unescape(h.strip()) + if h.startswith(('javascript:','mailto:','tel:','#')):continue + try:u=urllib.parse.urljoin(base,h);urllib.parse.urlsplit(u).hostname + except ValueError:log('BAD_LINK skipped',h[:80]);continue + out.append((u,' '.join(re.sub(r'<[^>]+>',' ',t).split()))) + return out +S2.links=safe_links +S2.OUT='/workspace/courts/staging/state_rules_rerun';os.makedirs(S2.OUT+'/files',exist_ok=True) +JOBS=[('NE','https://nebraskajudicial.gov/supreme-court-rules',300),('DE','https://courts.delaware.gov/rules/',300),('KS','https://www.kscourts.gov/Rules-Orders/Rules',100000)] +SKIP={'TN':'JS bot challenge (leastFactor) on index; no bypass','OK':'Cloudflare Turnstile captcha (oscn.net); no bypass','LA':'Blazor SPA, links JS-rendered; no static index','MI':'SPA, no links in static HTML','SD':'Vue SPA (sdlegislature.gov), no static links; public API path unresolved'} +_orig=S2.run +def run(st,u,cap): + import builtins + S2.re_cap=cap + src=open('/workspace/courts/collector/state_rules2.py').read() + return _orig(st,u) +if __name__=='__main__': + log('STATE_RULES3 START pid',os.getpid()) + with open(S2.OUT+'/skips.jsonl','a') as f: + for k,v in SKIP.items():f.write(json.dumps(dict(state=k,reason=v))+'\n') + for st,u,cap in JOBS: + try:S2.run(st,u,cap) + except SystemExit:raise + except Exception as e:log('STATE_ERR',st,repr(e)[:200]) + log('STATE_RULES3 DONE') diff --git a/scrapers_and_normalizers/courts/collector/state_rules4.py b/scrapers_and_normalizers/courts/collector/state_rules4.py new file mode 100644 index 0000000000000000000000000000000000000000..68409dfb17cf0e0eefdb2e6a6d8c23de408419c3 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/state_rules4.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Resume: KS (skip done URLs), NE (remaining candidates), DE (one more parser look). Stage only.""" +import sys,os,json,re,urllib.parse +sys.path.insert(0,'/workspace/courts/collector') +import us_fed as U, state_rules3 as S3 +from us_fed import log,fetch,sid,now +O='/workspace/courts/staging/state_rules_rerun';OFF='/workspace/courts/staging/state_rules/official' +RULE=re.compile(r'rule|court-rules|courtrules|procedure|\.pdf',re.I) +def ids(*fs): + s=set() + for f in fs: + if os.path.exists(f): + for l in open(f): + r=json.loads(l);s.add(r['rule_id']);s.add(r.get('file_url','')) + return s +def run(st,idx,skip): + r=fetch(idx,delay=10) + if not r:log('STATE_FAIL',st);open(O+'/skips.jsonl','a').write(json.dumps(dict(state=st,url=idx,reason='index fetch fail/robots (resume)'))+'\n');return + host=urllib.parse.urlsplit(r[0]).netloc + cand=list(dict.fromkeys(h.split('#')[0] for h,t in S3.safe_links(r[0],r[1]) if h.startswith('https://') and urllib.parse.urlsplit(h).netloc==host and RULE.search(h+' '+t) and h.split('#')[0]!=r[0])) + tmap={h.split('#')[0]:t for h,t in S3.safe_links(r[0],r[1])} + todo=[h for h in cand if sid(st,h) not in skip and h not in skip] + log('STATE',st,'candidates',len(cand),'already_done',len(cand)-len(todo),'todo',len(todo)) + if st=='DE' and not cand: + open(O+'/skips.jsonl','a').write(json.dumps(dict(state='DE',url=idx,reason='no_static_links'))+'\n');return + n=0 + with open(f'{O}/{st}_resume.jsonl','a') as o: + for h in todo: + fn=f'{O}/files/{st}_{sid(h)}';g=fetch(h,delay=10,stream_to=fn) + if not g:continue + fu,sha,nb=g + o.write(json.dumps(dict(rule_id=sid(st,h),rule_set=f'{st} court rules',citation='',title=tmap.get(h,''),text=None,court_id=None,subdivision_iso='US-'+st,effective_date=None,version='',file_url=fu,file_sha256=sha,file_bytes=nb,local_path=fn,content_sha256=sha,source_url=r[0],fetched_at=now(),archive_source='live',archive_timestamp=None,license='see source terms (state-specific)',terms_note='',robots_note='robots.txt honored',transport='https'))+'\n');o.flush();n+=1 + log('STATE',st,'resume rows',n) +if __name__=='__main__': + log('STATE_RULES4 START pid',os.getpid()) + for st,u in [('NE','https://nebraskajudicial.gov/supreme-court-rules'),('DE','https://courts.delaware.gov/rules/'),('KS','https://www.kscourts.gov/Rules-Orders/Rules')]: + try:run(st,u,ids(f'{OFF}/{st}.jsonl',f'{O}/{st}.jsonl',f'{O}/{st}_resume.jsonl')) + except SystemExit:raise + except Exception as e:log('STATE_ERR',st,repr(e)[:200]) + log('STATE_RULES4 DONE') diff --git a/scrapers_and_normalizers/courts/collector/us_fed.py b/scrapers_and_normalizers/courts/collector/us_fed.py new file mode 100644 index 0000000000000000000000000000000000000000..e7133ceaee0a41fb264f0a1dad6990cde08d14c4 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/us_fed.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""US federal court collector: stage only (no HF push). Keyless, TLS verified, robots honored.""" +import csv,io,json,hashlib,re,sys,time,os,urllib.request,urllib.robotparser,urllib.parse,datetime +from html.parser import HTMLParser +ST='/workspace/courts/staging'; UA='Mozilla/5.0 (compatible; court-research-collector/0.1)' +US=json.load(open('/workspace/courts/collector/us_iso.json')) if os.path.exists('/workspace/courts/collector/us_iso.json') else {} +NAME2ISO={v.lower():k for k,v in US.items()} +def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() +def log(*a):print(now(),*a,flush=True) +strikes=0 +def memguard(): + global strikes + while True: + ma=int(re.search(r'MemAvailable:\s+(\d+)',open('/proc/meminfo').read()).group(1))*1024 + if ma>=2.5*2**30:return + strikes+=1;log(f'MEMGUARD strike {strikes} MemAvailable={ma/2**30:.2f}G') + if strikes>=3:log('MEMGUARD 3 strikes: clean stop');sys.exit(3) + time.sleep(60) +RP={};LAST={} +def allowed(u): + h=urllib.parse.urlsplit(u);base=f'{h.scheme}://{h.netloc}' + if base not in RP: + rp=urllib.robotparser.RobotFileParser(); + try: + rq=urllib.request.Request(base+'/robots.txt',headers={'User-Agent':UA});rp.parse(urllib.request.urlopen(rq,timeout=30).read().decode('utf-8','ignore').splitlines()) + except Exception as e:log('robots fail',base,e);rp.parse([]) + RP[base]=rp + return RP[base] +def fetch(u,delay=2,stream_to=None,timeout=60): + memguard();rp=allowed(u) + if not rp.can_fetch(UA,u):log('ROBOTS_DISALLOW',u);return None + base=urllib.parse.urlsplit(u).netloc;d=max(delay,rp.crawl_delay(UA) or 0) + w=LAST.get(base,0)+d-time.time() + if w>0:time.sleep(w) + LAST[base]=time.time() + try: + r=urllib.request.urlopen(urllib.request.Request(u,headers={'User-Agent':UA}),timeout=timeout) + if stream_to: + h=hashlib.sha256();n=0 + with open(stream_to,'wb') as f: + while (c:=r.read(65536)):h.update(c);f.write(c);n+=len(c) + return r.geturl(),h.hexdigest(),n + b=r.read();return r.geturl(),b + except Exception as e:log('FETCH_ERR',u,e);return None +class L(HTMLParser): + def __init__(s):super().__init__();s.links=[];s.h=None;s.t='' + def handle_starttag(s,t,a): + if t=='a':s.h=dict(a).get('href');s.t='' + def handle_data(s,d): + if s.h is not None:s.t+=d + def handle_endtag(s,t): + if t=='a' and s.h:s.links.append((s.h,' '.join(s.t.split())));s.h=None +def links(base,b): + p=L();p.feed(b.decode('utf-8','ignore'));return [(urllib.parse.urljoin(base,h),t) for h,t in p.links] +def prov(u,lic='public domain (US gov work)'):return dict(source_url=u,fetched_at=now(),archive_source='live',archive_timestamp=None,license=lic,terms_note='',robots_note='robots.txt honored',transport=urllib.parse.urlsplit(u).scheme) +def W(name):return open(f'{ST}/{name}.jsonl','a') +def sid(*a):return hashlib.sha1('|'.join(a).encode()).hexdigest()[:16] +def judges(): + u='https://www.fjc.gov/sites/default/files/history/judges.csv';r=fetch(u) + if not r:return + rd=csv.DictReader(io.StringIO(r[1].decode('utf-8-sig','ignore')));n=0;out=W('judges');P=prov(r[0]) + for row in rd: + name=' '.join(x for x in [row.get('First Name'),row.get('Middle Name'),row.get('Last Name'),row.get('Suffix')] if x) + for k in range(1,7): + c=row.get(f'Court Name ({k})'); + if not c:continue + t=row.get(f'Appointment Title ({k})','');term=row.get(f'Termination ({k})','') + out.write(json.dumps(dict(judge_id=sid(row.get('jid',''),str(k)),full_name=name,court_id=sid('court',c),court_name=c,title=t,subdivision_iso=None,status='active' if not term else 'terminated',as_of=P['fetched_at'][:10],content_sha256=hashlib.sha256(r[1]).hexdigest(),**P))+'\n');n+=1 + if n%500==0:out.flush() + out.close();log('judges rows',n) +def courts(): + u='https://www.uscourts.gov/about-federal-courts/federal-courts-public/court-website-links';r=fetch(u) + if not r:return + out=W('courts');n=0;seen=set() + for h,t in links(r[0],r[1]): + if re.search(r'\.uscourts\.gov',h) and 'www.uscourts.gov' not in h and h not in seen and t: + seen.add(h);out.write(json.dumps(dict(court_id=sid('url',h),name=t,name_local=t,country='US',subdivision_iso=None,level='federal',court_type='',parent_court_id=None,url=h,**prov(r[0])))+'\n');n+=1 + out.close();log('courts rows',n,'(courthouse addresses: court finder is JS app; addresses TODO from per-court pages)') +def docs(index,kind,maxpages=80): + r=fetch(index) + if not r:return + pages=[index]+[h for h,t in links(r[0],r[1]) if h.startswith(index.rstrip('/')+'/') ][:maxpages] + seen=set();n=0;out=W(kind) + for pg in dict.fromkeys(pages): + rr=r if pg==index else fetch(pg) + if not rr:continue + for h,t in links(rr[0],rr[1]): + if not re.search(r'\.pdf($|\?)',h,re.I) or h in seen:continue + seen.add(h);fn=f'{ST}/files/{kind}_{sid(h)}.pdf';g=fetch(h,stream_to=fn) + if not g:continue + _,sha,nb=g;P=prov(pg) + if kind=='forms':rec=dict(form_id=sid(h),form_number=(re.search(r'([A-Z]{1,4}[ -]?\d{1,4}[A-Z]?)',t) or [''])[0],title=t,court_id=None,subdivision_iso=None,language='en',file_url=h,file_format='pdf',file_sha256=sha,file_cid=None,file_bytes=nb,effective_date=None,local_path=fn,content_sha256=sha,**P) + else:rec=dict(rule_id=sid(h),rule_set=pg.rsplit('/',1)[-1],citation='',title=t,text=None,court_id=None,subdivision_iso=None,effective_date=None,version='',file_url=h,file_sha256=sha,file_bytes=nb,local_path=fn,content_sha256=sha,**P) + out.write(json.dumps(rec)+'\n');out.flush();n+=1 + out.close();log(kind,'rows',n) +def ncsc(): + r=fetch('https://www.ncsc.org/information-and-resources/state-court-websites',delay=10) + if not r:return + out=W('ncsc_state_links');n=0 + for h,t in links(r[0],r[1]): + iso=NAME2ISO.get(t.lower().strip()) + if iso and 'ncsc.org' not in h: + out.write(json.dumps(dict(subdivision_iso=iso,state=t,judiciary_url=h,**prov(r[0],'NCSC; link list, cite')))+'\n');n+=1 + out.close();log('ncsc state links',n,'final_url',r[0]) +if __name__=='__main__': + log('START pid',os.getpid()) + for f in [judges,courts,lambda:docs('https://www.uscourts.gov/forms-rules/forms','forms'),lambda:docs('https://www.uscourts.gov/forms-rules/current-rules-practice-procedure','rules'),ncsc]: + try:f() + except SystemExit:raise + except Exception as e:log('STAGE_ERR',e) + log('DONE') diff --git a/scrapers_and_normalizers/courts/collector/us_iso.json b/scrapers_and_normalizers/courts/collector/us_iso.json new file mode 100644 index 0000000000000000000000000000000000000000..67b772534b58226a6276038b33e361d6b1282fa6 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/us_iso.json @@ -0,0 +1 @@ +{"US-AK": "Alaska", "US-AL": "Alabama", "US-AR": "Arkansas", "US-AS": "American Samoa", "US-AZ": "Arizona", "US-CA": "California", "US-CO": "Colorado", "US-CT": "Connecticut", "US-DC": "District of Columbia", "US-DE": "Delaware", "US-FL": "Florida", "US-GA": "Georgia", "US-GU": "Guam", "US-HI": "Hawaii", "US-IA": "Iowa", "US-ID": "Idaho", "US-IL": "Illinois", "US-IN": "Indiana", "US-KS": "Kansas", "US-KY": "Kentucky", "US-LA": "Louisiana", "US-MA": "Massachusetts", "US-MD": "Maryland", "US-ME": "Maine", "US-MI": "Michigan", "US-MN": "Minnesota", "US-MO": "Missouri", "US-MP": "Northern Mariana Islands", "US-MS": "Mississippi", "US-MT": "Montana", "US-NC": "North Carolina", "US-ND": "North Dakota", "US-NE": "Nebraska", "US-NH": "New Hampshire", "US-NJ": "New Jersey", "US-NM": "New Mexico", "US-NV": "Nevada", "US-NY": "New York", "US-OH": "Ohio", "US-OK": "Oklahoma", "US-OR": "Oregon", "US-PA": "Pennsylvania", "US-PR": "Puerto Rico", "US-RI": "Rhode Island", "US-SC": "South Carolina", "US-SD": "South Dakota", "US-TN": "Tennessee", "US-TX": "Texas", "US-UT": "Utah", "US-VA": "Virginia", "US-VI": "Virgin Islands, U.S.", "US-VT": "Vermont", "US-WA": "Washington", "US-WI": "Wisconsin", "US-WV": "West Virginia", "US-WY": "Wyoming"} \ No newline at end of file diff --git a/scrapers_and_normalizers/courts/collector/wait_ocr_then_launch.sh b/scrapers_and_normalizers/courts/collector/wait_ocr_then_launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..e728f48c7394486bca80368419194e583b282e13 --- /dev/null +++ b/scrapers_and_normalizers/courts/collector/wait_ocr_then_launch.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Waits for OCR pid 250690 to exit, preflights, launches state-county driver once. Never kills, never relaunches. +B=/workspace/courts; L=$B/logs/state_county_ocr_waiter.log +log(){ echo "$(date -Is) $*" >> $L; } +echo $$ > $B/STATE_COUNTY_OCR_WAITER.pid; log "waiter start pid $$" +while kill -0 250690 2>/dev/null || pgrep -f 'pr_ogp_ocr|pdftoppm' >/dev/null; do sleep 30; done +log "OCR gone" +# collectors box-wide: long-running collector scripts (excluding supervisors/review builds) +OTHERS=$(pgrep -af 'python' | grep -E '_collect|collector/|state_county\.py|scraper' | grep -vE 'supervise|review|grep|wait_ocr' | wc -l) +MEM=$(awk '/MemAvailable/{print $2}' /proc/meminfo) +TOTAL=$((OTHERS+1)) +log "preflight others=$OTHERS total_with_courts=$TOTAL memavail_kb=$MEM" +if pgrep -f 'state_county\.py' >/dev/null; then echo "$(date -Is) courts state_county already running" > $B/STATE_COUNTY_LAUNCH_HELD; log HELD; exit 0; fi +if [ $TOTAL -gt 2 ]; then echo "$(date -Is) collectors would be $TOTAL (>2)" > $B/STATE_COUNTY_LAUNCH_HELD; log HELD; exit 0; fi +if [ $MEM -lt 4404019 ]; then echo "$(date -Is) MemAvail ${MEM}kB < 4.2G" > $B/STATE_COUNTY_LAUNCH_HELD; log HELD; exit 0; fi +echo "$(date -Is) LAUNCH resume WV,AL,AR,DE,ND then Phase2 (CoS GO 2026-10-28 06:19 PT; OCR 250690 gone; collectors=$TOTAL; memavail_kb=$MEM)" >> $B/COS_GO_COURTS_STATE_COUNTY +rm -f $B/STOPPED_STATE_COUNTY +setsid nohup bash $B/collector/run_state_county.sh >/dev/null 2>&1 < /dev/null & +DP=$! +echo "$(date -Is) driver_pid=$DP" > $B/STATE_COUNTY_LAUNCHED; log "launched driver $DP" diff --git a/scrapers_and_normalizers/courts/intl/SCHEMA_MAPPING.md b/scrapers_and_normalizers/courts/intl/SCHEMA_MAPPING.md new file mode 100644 index 0000000000000000000000000000000000000000..40d2535f1b71ac0594296ad1c637ec8c160e0a7c --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/SCHEMA_MAPPING.md @@ -0,0 +1,7 @@ +# Intl -> justicedao configs (draft) +Common to all rows: country_iso (ISO 3166-1 a2), subdivision_iso (ISO 3166-2, e.g. GB-ENG, CA-ON, IN-DL; null = national), source_url, publisher, official=y, transport, retrieved_at, sha256, source=live, coverage, language. +- courts: court_id = "{country}-{sub|NAT}-{slug}", name, name_en (null unless official), level (supreme/appellate/high/first_instance/specialized/tribunal), jurisdiction_type, parent_court_id. +- courthouses: courthouse_id, court_id FK, name, street/locality/postal_code/region (official public address only), lat/lon if published, phone/email only if official switchboard. +- judges: name, court_id, title (as published), role_type (judge, justice, magistrate, senior_judge, other; e.g. "Ministro" STF->justice, "Richter am BGH"->judge). No private data. +- forms: form_id/number, title, court_id or issuing body, url, sha256 (no file stored), language, format. +- rules: rule_set (e.g. ZPO, CPR 1998, CPC/2015 BR), section, title, url, sha256, effective_date if published; national procedural codes -> rules with subdivision_iso null; provincial (CA-ON Rules of Civil Procedure, AU-NSW UCPR) -> subdivision_iso set. diff --git a/scrapers_and_normalizers/courts/intl/TERMS_REVIEW.md b/scrapers_and_normalizers/courts/intl/TERMS_REVIEW.md new file mode 100644 index 0000000000000000000000000000000000000000..fcbd3d40100ce15d2ffe1db2bb6f9f4bc5609306 --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/TERMS_REVIEW.md @@ -0,0 +1,25 @@ +# Intl terms review — 2026-11-02 (PT), checked live this session +| Site | Notice checked | License / basis | Decision | +|---|---|---|---| +| HMCTS Find a court (find-court-tribunal.service.gov.uk) | site footer | "All content is available under the Open Government Licence v3.0, except where otherwise stated, © Crown copyright" | COLLECT | +| GOV.UK court & tribunal forms (gov.uk + assets) | gov.uk/help/terms-conditions | Crown copyright, published under OGL; reproduction allowed per OGL conditions; robots Crawl-delay 10 | COLLECT (url+sha256) | +| MoJ procedure rules (justice.gov.uk) | footer "© Crown copyright"; copyright page 404 | Crown copyright; MoJ content generally OGL v3 (not restated on site) | COLLECT (index only: url/title/sha256), flag terms_verified=partial | +| SCTS (scotcourts.gov.uk) | no copyright/terms link found; /copyright 404 | unverified | SKIP pending terms | +| gesetze-im-internet.de ZPO | /hinweise.html (no reuse restriction stated) | Statutes are amtliche Werke, not copyright-protected (§5(1) UrhG) | COLLECT (xml.zip, 1 request) | +| Justice Laws (laws-lois.justice.gc.ca) | /eng/Notices 404 | Reproduction of Federal Law Order (SI/97-5): federal law may be reproduced without charge/permission, accuracy + not-official caveat | COLLECT | +| Supreme Court of Canada (scc-csc.ca) | /resources-ressources/terms-avis/ | "may reproduce the material in whole or in part for non-commercial purposes… without charge or further permission" (accuracy, attribution) | COLLECT judges (name/court/title only; facts) | +| Ontario Courts / ontariocourtforms.on.ca | important-notices page: no reuse notice found | unverified | SKIP pending terms | +| FR annuaires.justice.gouv.fr | /mentions-legales fetched; no licence text in served HTML | unverified (Licence Ouverte likely but not confirmed) | SKIP pending terms | +| NG supremecourt.gov.ng, courtofappeal.gov.ng | JS-only SPA, no terms readable without JS | unverified | SKIP | +| NG njc.gov.ng | homepage, no terms/copyright notice | unverified | SKIP pending terms | +Dead targets skipped per CoS: Légifrance 403, judiciary.uk 202 list, UKSC justices 404, justiz.de forms 404, bccourts. +No site reviewed explicitly forbids automated collection. Attribution strings must go on the HF card (OGL, SCC, Justice Laws caveat). + +## 2026-11-03 (PT) additions — collector 2 (intl2) +| Site | Notice checked | License / basis | Decision | +|---|---|---|---| +| courts.ie (Courts Service of Ireland) | /organisation-information/re-use-of-information; robots Crawl-delay 10, /docs/ disallowed | Re-use permitted under PSI Regulations + latest PSI licence (CC BY 4.0-compatible): acknowledge source & copyright, accurate, not misleading/advertising | COLLECT offices (addresses, official office phone/email), court rules pages, form landing pages (cap 250; /docs files not fetched per robots) | +| curia.europa.eu (CJEU) | /site/jcms/qua1_6625/en/copyright | "Editorial content and the case-law can be reproduced provided the source is acknowledged" (cite "Court of Justice of the European Union", don't distort, mark changes) | COLLECT members (name/court/title), registry address, procedural texts (url+sha256) | +| courtsofnz.govt.nz (NZ) | /copyright | Crown copyright; copying only for personal/in-house use, other uses need permission | SKIP | +| judiciary.gov.sg (SG) | /terms-of-use §6 | All rights reserved; no reproduction for commercial purposes without written permission | SKIP | +| judiciary.go.ke (KE), ecourts.gov.in (IN), US territories | not yet verified this session | unverified | SKIP pending terms | diff --git a/scrapers_and_normalizers/courts/intl/collector/gb_fix.py b/scrapers_and_normalizers/courts/intl/collector/gb_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..4413ebd09dce283915a161bd09f871b1403e9932 --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/gb_fix.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""GB fix: re-fetch HMCTS court pages (live, polite) -> correct subdivision (postcode) + structured address. Writes *.v2 then swaps with backup. Stage only.""" +import sys,os,json,re,time,shutil +sys.path.insert(0,'/workspace/courts/intl/collector') +import intl_collect as ic +from gb_geo import sub_from,parse_addresses +ic.LOG=ic.ROOT+'/logs/gb_fix.log' +D=ic.ST+'/GB'; RV=ic.ROOT+'/review_intl' +def fin(marker,why): + marker={'STOPPED_INTL':'STOPPED_GB_FIX'}.get(marker,marker) + open(f'{ic.ROOT}/{marker}','w').write(time.strftime('%Y-%m-%dT%H:%M:%S%z')+' '+why+'\n'); ic.log('FINISH',marker,why); sys.exit(0 if 'DONE' in marker else 3) +ic.finish=fin +old=[json.loads(l) for l in open(f'{D}/courts.orig_20261103.jsonl')] +ck=f'{D}/gb_fix_ckpt.jsonl'; done={json.loads(l)['old_id'] for l in open(ck)} if os.path.exists(ck) else set() +ic.log('GB_FIX START pid',os.getpid(),'courts',len(old),'done',len(done)) +for c in old: + if c['court_id'] in done: continue + try: r=ic.fetch(c['source_url']) + except ic.HostStop as h: ic.log('HOSTSTOP',h); break + rec={'old_id':c['court_id'],'ok':False} + if r: + b=r[0].decode('utf-8','ignore'); addrs,ll=parse_addresses(b) + pc=next((a['postal_code'] for a in addrs if a.get('postal_code')),None) + sub,how=sub_from(pc,ic.txt(b)); slug=c['source_url'].rsplit('/',1)[1] + rec.update(ok=True,sub=sub,how=how,court_id=f'GB-{sub[3:]}-{slug}',sha=ic.sha(r[0]),addrs=addrs,ll=ll) + open(ck,'a').write(json.dumps(rec)+'\n') +ic.log('GB_FIX fetch loop end') diff --git a/scrapers_and_normalizers/courts/intl/collector/gb_fix_apply.py b/scrapers_and_normalizers/courts/intl/collector/gb_fix_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..8802594d5cb92ce98d4dcd6386d28f560501a0c4 --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/gb_fix_apply.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Apply GB fix: offline postcode relabel for all rows; refetched structured addresses where available. Validates and writes review.""" +import sys,os,json,time,shutil,collections +sys.path.insert(0,'/workspace/courts/intl/collector') +from gb_geo import sub_from,WTOWN +R='/workspace/courts/intl'; D=R+'/staging/GB'; RV=R+'/review_intl' +src=D+'/courts.orig_20261103.jsonl' +if not os.path.exists(src): shutil.copy(D+'/courts.jsonl',src); shutil.copy(D+'/courthouses.jsonl',D+'/courthouses.orig_20261103.jsonl') +courts=[json.loads(l) for l in open(src)]; chs=[json.loads(l) for l in open(D+'/courthouses.orig_20261103.jsonl')] +fx={} +if os.path.exists(D+'/gb_fix_ckpt.jsonl'): + for l in open(D+'/gb_fix_ckpt.jsonl'): + x=json.loads(l) + if x.get('ok'): fx[x['old_id']]=x +oldpc={h['court_id']:h.get('postal_code') for h in chs} +outc=[];outh=[];stats=collections.Counter() +for c in courts: + oid=c['court_id']; slug=c['source_url'].rsplit('/',1)[1]; f=fx.get(oid) + if f: sub,how=f['sub'],f['how'] + else: sub,how=sub_from(oldpc.get(oid),c['name']+' '+slug.replace('-',' ').title()) + if how=='default_no_postcode' and not f: how='unverified_no_postcode' + nid=f'GB-{sub[3:]}-{slug}'; stats[f'{c["subdivision_iso"]}->{sub}']+=1; stats['sub_method:'+how]+=1 + c2={**c,'subdivision_iso':sub,'court_id':nid,'subdivision_method':how} + if f: c2['sha256']=f['sha'] + outc.append(c2) + if f: + for i,a in enumerate(f['addrs']): + outh.append({**c2,'courthouse_id':nid+('-visit' if i==0 else f'-addr{i+1}'),'court_id':nid,'street':a['street'],'locality':a['locality'],'postal_code':a['postal_code'], + 'region':sub,'lat':f['ll'][0] if i==0 else None,'lon':f['ll'][1] if i==0 else None,'phone':None,'email':None,'address_source':a['kind']}) + for k in ('level','jurisdiction_type','parent_court_id','name_en','subdivision_method'): outh[-1].pop(k,None) + else: + for h in chs: + if h['court_id']==oid: outh.append({**h,'court_id':nid,'courthouse_id':nid+'-visit','subdivision_iso':sub,'region':sub,'address_source':'legacy_text_unverified'}) +ids=collections.Counter(x['court_id'] for x in outc); hids=collections.Counter(x['courthouse_id'] for x in outh); cset=set(ids) +val=dict(courts=len(outc),courthouses=len(outh),dup_court_ids=sum(v-1 for v in ids.values() if v>1),dup_courthouse_ids=sum(v-1 for v in hids.values() if v>1), + bad_fk=sum(1 for h in outh if h['court_id'] not in cset),courthouses_missing_postcode=sum(1 for h in outh if not h.get('postal_code')), + sct_with_nonsct_postcode=sum(1 for h in outh if h['subdivision_iso']!='GB-SCT' and sub_from(h.get('postal_code'))[0]=='GB-SCT' and h.get('postal_code')), + refetched=len(fx),courts_without_address=len(cset-{h['court_id'] for h in outh})) +for n,rows in (('courts',outc),('courthouses',outh)): + with open(f'{D}/{n}.jsonl','w') as fo: + for x in rows: fo.write(json.dumps(x,ensure_ascii=False)+'\n') +rep={'generated':time.strftime('%Y-%m-%d %H:%M %Z'),'validation':val,'relabel':dict(stats),'backups':['GB/courts.orig_20261103.jsonl','GB/courthouses.orig_20261103.jsonl']} +json.dump(rep,open(RV+'/gb_fix_report.json','w'),indent=1); print(json.dumps(rep,indent=1)) diff --git a/scrapers_and_normalizers/courts/intl/collector/gb_geo.py b/scrapers_and_normalizers/courts/intl/collector/gb_geo.py new file mode 100644 index 0000000000000000000000000000000000000000..ef66c1a2c3c3072d302dbf71ba98832806d404ee --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/gb_geo.py @@ -0,0 +1,36 @@ +"""GB subdivision from postcode + HMCTS page address parsing (JSON-LD first, then address block).""" +import re,json,html +SCT={'AB','DD','DG','EH','FK','G','HS','IV','KA','KW','KY','ML','PA','PH','TD','ZE'} +WLS_AREA={'CF','LL','NP','SA','LD'} +WTOWN=re.compile(r'\b(Cardiff|Swansea|Newport|Wrexham|Aberystwyth|Caernarfon|Mold|Llandudno|Merthyr|Haverfordwest|Carmarthen|Llanelli|Welshpool|Prestatyn|Port Talbot|Pontypridd|Cwmbran)\b') +PC=re.compile(r'\b([A-Z]{1,2})(\d[A-Z\d]?) ?(\d[A-Z]{2})\b') +def sub_from(postcode=None,text=''): + m=PC.search((postcode or '').upper()) + if m: + a,d=m.group(1),m.group(2); dn=int(re.match(r'\d+',d).group()) + if a=='BT': return 'GB-NIR','postcode' + if a in SCT: return 'GB-SCT','postcode' + if a in WLS_AREA or (a=='SY' and 15<=dn<=25) or (a=='CH' and 5<=dn<=8): return 'GB-WLS','postcode' + return 'GB-ENG','postcode' + if WTOWN.search(text or ''): return 'GB-WLS','town' + return 'GB-ENG','default_no_postcode' +def parse_addresses(b): + out=[] + for blk in re.findall(r'(?s)]*ld\+json[^>]*>(.*?)',b): + try: j=json.loads(blk) + except Exception: continue + for o in (j if isinstance(j,list) else [j]): + a=o.get('address') if isinstance(o,dict) else None + for x in (a if isinstance(a,list) else [a] if a else []): + out.append(dict(street=x.get('streetAddress'),locality=x.get('addressLocality'),postal_code=x.get('postalCode'),kind='jsonld')) + if not out: + for p in re.findall(r'(?s)

(.*?)

',b): + parts=[html.unescape(re.sub(r'<[^>]+>','',x)).strip() for x in re.split(r'',p)] + parts=[x for x in parts if x] + if not parts: continue + pc=parts[-1] if PC.search(parts[-1].upper()) else None + body=parts[:-1] if pc else parts + out.append(dict(street=', '.join(body[:-1]) or None,locality=body[-1] if body else None,postal_code=pc,kind='address_block')) + m=re.search(r'maps\?q=(-?\d+\.\d+),(-?\d+\.\d+)',b) + ll=(float(m.group(1)),float(m.group(2))) if m else (None,None) + return out,ll diff --git a/scrapers_and_normalizers/courts/intl/collector/intl2_collect.py b/scrapers_and_normalizers/courts/intl/collector/intl2_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ae89179df80ad723c812da22404d39dc721f8c --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/intl2_collect.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Intl collector 2 (IE courts.ie under PSI licence; EU CJEU curia 'reproduce with source acknowledged'). Live official, keyless, polite (>=10s/host, robots Crawl-delay), stop host on 403/429/challenge. Stage only. GO: COS_GO_INTL2_20261103""" +import sys,os,re,json,time,html +sys.path.insert(0,'/workspace/courts/intl/collector') +import intl_collect as ic +ic.LOG=ic.ROOT+'/logs/intl2_collect.log' +def fin(marker,why): + marker={'STOPPED_INTL':'STOPPED_INTL2','INTL_DONE':'INTL2_DONE'}.get(marker,marker) + open(f'{ic.ROOT}/{marker}','w').write(f'{ic.now()} {why}\n'); ic.log('FINISH',marker,why) + import subprocess; subprocess.run([sys.executable,ic.ROOT+'/collector/intl2_review.py']); sys.exit(0 if 'DONE' in marker else 3) +ic.finish=fin +FORMCAP=250 +def locs(u): + r=ic.fetch(u); return re.findall(r'\s*([^<\s]+)\s*',r[0].decode('utf-8','ignore')) if r else [] +def h1(b): + m=re.search(r'(?s)]*>(.*?)',b); return ic.txt(m.group(1)) if m else None +IEB='https://www.courts.ie' +IECOURTS=[('supreme','Supreme Court','supreme'),('court-of-appeal','Court of Appeal','appellate'),('high','High Court','high'),('circuit','Circuit Court','first_instance'),('district','District Court','first_instance')] +def ie_courts(o): + r=ic.fetch(IEB+'/explore/courts') + if not r: return 'partial' + b=r[0] + for s,n,l in IECOURTS: + o.w('courts',{**ic.base('IE',None,IEB+'/explore/courts','Courts Service of Ireland','en',b),'court_id':f'IE-NAT-{s}','name':n,'name_en':n,'level':l,'jurisdiction_type':None,'parent_court_id':None,'license':'Irish PSI Licence (CC BY 4.0-compatible); © Courts Service'}) +def ie_courthouses(o): + for u in locs(IEB+'/sitemaps/sitemap-offices.xml'): + r=ic.fetch(u) + if not r: continue + b=r[0].decode('utf-8','ignore'); t=ic.txt(b); name=h1(b) or u.rsplit('/',1)[1] + a=re.search(r'Address (.*?) (?:Eircode (\S+ ?\S+)|Telephone number|Email|Head of office|Opening)',t) + if not a: ic.log('IE no address',u); continue + ph=re.search(r'Telephone number ([\d +()-]{6,20})',t); em=re.search(r'Email (\S+@courts\.ie)',t) + addr=a.group(1).strip().rstrip(',') + o.w('courthouses',{**ic.base('IE',None,u,'Courts Service of Ireland','en',r[0]),'courthouse_id':'IE-NAT-'+u.rstrip('-').rsplit('/',1)[1][:80],'court_id':None,'name':name, + 'street':addr,'locality':None,'postal_code':a.group(2),'region':None,'lat':None,'lon':None,'phone':ph.group(1).strip() if ph else None,'email':em.group(1) if em else None, + 'license':'Irish PSI Licence; © Courts Service','note':'office/venue page; serves multiple court jurisdictions'}) +def ie_rules(o): + for u in locs(IEB+'/sitemaps/sitemap-court-rules.xml'): + if 'full-court-rule' not in u: continue + r=ic.fetch(u) + if not r: continue + b=r[0].decode('utf-8','ignore'); slug=u.split('url=',1)[-1] + rs='Rules of the Superior Courts' if 'Superior' in slug else 'Circuit Court Rules' if 'Circuit' in slug else 'District Court Rules' if 'District' in slug else 'Court Rules' + o.w('rules',{**ic.base('IE',None,u,'Courts Service of Ireland','en',r[0]),'rule_set':rs,'section':slug,'title':h1(b) or slug.replace('-',' '),'url':u,'effective_date':None,'license':'Irish PSI Licence; © Courts Service'}) +def ie_forms(o): + us=locs(IEB+'/sitemaps/sitemap-forms.xml'); n=0 + for u in us[:FORMCAP]: + r=ic.fetch(u) + if not r: continue + b=r[0].decode('utf-8','ignore'); t=h1(b) or u.rsplit('/',1)[1] + m=re.match(r'(?:No\.\s*)?([0-9]+[A-Z]?\.[0-9]+[A-Z]?)',t) + o.w('forms',{**ic.base('IE',None,u,'Courts Service of Ireland','en',r[0]),'form_id':'IE-'+u.rsplit('/',1)[1][:90],'form_number':m.group(1) if m else None,'title':t,'court_id':None,'url':u,'format':'html', + 'note':'form landing page hashed; files under /docs/ are robots-disallowed and not fetched','license':'Irish PSI Licence; © Courts Service'}); n+=1 + if len(us)>FORMCAP: return f'partial_capped_{FORMCAP}_of_{len(us)}' +CU='https://curia.europa.eu' +def eu_courts(o): + for cid,n,l in (('EU-NAT-court-of-justice','Court of Justice','supreme'),('EU-NAT-general-court','General Court','first_instance')): + o.w('courts',{**ic.base('EU',None,CU,'Court of Justice of the European Union','en'),'court_id':cid,'name':n,'name_en':n,'level':l,'jurisdiction_type':'EU','parent_court_id':None,'sha256':None,'license':'Source: Court of Justice of the European Union'}) + r=ic.fetch(CU+'/jcms/jcms/Jo2_7039/en/') + if r: + t=ic.txt(r[0]); a=re.search(r'Registry of the Court of Justice (.*?L-\d{4} Luxembourg)',t) + if a: o.w('courthouses',{**ic.base('EU',None,r[1],'Court of Justice of the European Union','en',r[0]),'courthouse_id':'EU-NAT-court-of-justice-registry','court_id':'EU-NAT-court-of-justice','name':'Registry of the Court of Justice', + 'street':a.group(1).split(' L-')[0],'locality':'Luxembourg','postal_code':re.search(r'L-\d{4}',a.group(1)).group(),'region':None,'lat':None,'lon':None,'phone':None,'email':None,'license':'Source: Court of Justice of the European Union'}) +def eu_judges(o): + r=ic.fetch(CU+'/jcms/jcms/Jo2_7026/en/') + if not r: return 'partial' + b=r[0].decode('utf-8','ignore') + for m in re.finditer(r'(?s)

(.*?)

(.{0,400})',b): + nm=ic.txt(m.group(1)); tl=re.match(r'\s*(.*?)\s+Biography',ic.txt(m.group(2))) + title=tl.group(1) if tl and len(tl.group(1))<80 else None + rt='advocate_general' if title and 'Advocate' in title else 'judge' + o.w('judges',{**ic.base('EU',None,r[1],'Court of Justice of the European Union','en',r[0]),'name':nm,'court_id':'EU-NAT-court-of-justice','title':title,'role_type':rt,'license':'Source: Court of Justice of the European Union'}) +def eu_rules(o): + r=ic.fetch(CU+'/jcms/d2_5104/en/case-procedure') or ic.fetch(CU+'/site/jcms/d2_5104/en/case-procedure') + if not r: return 'partial' + b=r[0].decode('utf-8','ignore'); seen=set() + for href,tx in re.findall(r'(?s)]+href="([^"]+\.pdf)"[^>]*>(.*?)
',b): + u=href if href.startswith('http') else CU+'/'+href.lstrip('/'); t=ic.txt(tx) + if u in seen or not re.search(r'rule|statute|instruction|practice|recommendation',t+u,re.I) or len(seen)>=30: continue + seen.add(u); g=ic.fetch(u,binary=True) + if g: o.w('rules',{**ic.base('EU',None,u,'Court of Justice of the European Union','en',g[0]),'rule_set':'CJEU procedural texts','section':None,'title':t,'url':g[1],'effective_date':None,'source_page':r[1],'license':'Source: Court of Justice of the European Union'}) +if __name__=='__main__': + ic.log('START pid',os.getpid(),'memavail %.2fG'%ic.memavail()) + plan=[('EU',[('eu_courts',eu_courts),('eu_judges',eu_judges),('eu_rules',eu_rules)]),('IE',[('ie_courts',ie_courts),('ie_courthouses',ie_courthouses),('ie_rules',ie_rules),('ie_forms',ie_forms)])] + for cc,ts in plan: + o=ic.Out(cc) + for n,f in ts: ic.task(o,n,lambda f=f,o=o:f(o)) + open(f'{ic.ST}/{cc}/DONE','w').write(ic.now()) + ic.finish('INTL_DONE','IE+EU planned tasks done; NZ/SG skipped (terms forbid reuse w/o permission); KE/IN/US territories pending terms') diff --git a/scrapers_and_normalizers/courts/intl/collector/intl2_review.py b/scrapers_and_normalizers/courts/intl/collector/intl2_review.py new file mode 100644 index 0000000000000000000000000000000000000000..20e290673b5a84daa76f61e562d8e8216bf07fc6 --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/intl2_review.py @@ -0,0 +1,11 @@ +import json,os,glob,collections,time +R='/workspace/courts/intl'; out={'generated':time.strftime('%Y-%m-%d %H:%M %Z'),'counts':{},'coverage':{},'validation':{}} +for cc in ('IE','EU'): + d=f'{R}/staging/{cc}' + if os.path.exists(d+'/ckpt.json'): out['coverage'][cc]=json.load(open(d+'/ckpt.json')).get('coverage') + for f in glob.glob(d+'/*.jsonl'): + rows=[json.loads(l) for l in open(f)]; k=f'{cc}/{os.path.basename(f)[:-6]}'; out['counts'][k]=len(rows) + pk={'courts':'court_id','courthouses':'courthouse_id','forms':'form_id','rules':'url','judges':'name'}.get(os.path.basename(f)[:-6]) + c=collections.Counter(r.get(pk) for r in rows) + out['validation'][k]={'dup_ids':sum(v-1 for v in c.values() if v>1),'missing_source':sum(1 for r in rows if not r.get('source_url')),'non_https':sum(1 for r in rows if r.get('transport')!='https')} +os.makedirs(R+'/review_intl/intl2',exist_ok=True); json.dump(out,open(R+'/review_intl/intl2/summary.json','w'),indent=1); open(R+'/review_intl/intl2/REVIEW_READY','w').write(out['generated']) diff --git a/scrapers_and_normalizers/courts/intl/collector/intl_collect.py b/scrapers_and_normalizers/courts/intl/collector/intl_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a2106913fa266abf7aa12c687760a760fd0f0a --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/intl_collect.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Intl courts collector (light, live official sites only, stage only). GO: COS_GO_COURTS_INTL_20261102""" +import os,sys,re,json,time,html,hashlib,io,zipfile,shutil,urllib.request,urllib.error,urllib.parse,urllib.robotparser +import xml.etree.ElementTree as ET +ROOT='/workspace/courts/intl'; ST=ROOT+'/staging'; sys.path.insert(0,ROOT+'/collector'); LOG=ROOT+'/logs/intl_collect.log' +UA='ipfs_datasets_py-courts/1.0 (justicedao research; polite 1req/10s)' +MINGAP=10.0; MEMFLOOR=4.2; STRIKES=3; DISKMIN=10.0 +last={}; stopped=set(); robots={}; strikes=0 +def log(*a): + s=time.strftime('%Y-%m-%dT%H:%M:%S%z')+' '+' '.join(str(x) for x in a) + open(LOG,'a').write(s+'\n') +def memavail(): + for l in open('/proc/meminfo'): + if l.startswith('MemAvailable'): return int(l.split()[1])/1048576 +def guard(): + global strikes + if shutil.disk_usage('/workspace').free/1e9=STRIKES: finish('STOPPED_INTL','memguard %.2fG'%m) + time.sleep(60) + else: strikes=0 +class HostStop(Exception): pass +def rp(host,scheme): + if host not in robots: + r=urllib.robotparser.RobotFileParser() + try: + req=urllib.request.Request(f'{scheme}://{host}/robots.txt',headers={'User-Agent':UA}) + body=urllib.request.urlopen(req,timeout=30).read().decode('utf-8','ignore'); r.parse(body.splitlines()) + except Exception: r.parse([]) + last[host]=time.time(); robots[host]=r + return robots[host] +def fetch(url,binary=False): + guard() + u=urllib.parse.urlparse(url); host=u.netloc + if host in stopped: raise HostStop(host) + r=rp(host,u.scheme) + if not r.can_fetch(UA,url): log('ROBOTS_DISALLOW',url); return None + gap=max(MINGAP,float(r.crawl_delay(UA) or 0)) + w=last.get(host,0)+gap-time.time() + if w>0: time.sleep(w) + last[host]=time.time() + try: + resp=urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':UA}),timeout=60) + data=resp.read(); final=resp.geturl() + except urllib.error.HTTPError as e: + if e.code in (403,429): stopped.add(host); log('HOST_STOP',host,e.code,url); raise HostStop(host) + log('HTTP',e.code,url); return None + except Exception as e: log('ERR',type(e).__name__,url); return None + if not binary: + t=data[:20000].decode('utf-8','ignore').lower() + if any(k in t for k in ('captcha','cf-challenge','just a moment...','attention required','are you a robot')): + stopped.add(host); log('HOST_STOP_CHALLENGE',host,url); raise HostStop(host) + return data,final +def txt(b): + t=html.unescape(re.sub(r'(?s)|','',b if isinstance(b,str) else b.decode('utf-8','ignore'))) + return re.sub(r'\s+',' ',re.sub('<[^>]+>',' ',t)).strip() +sha=lambda b:hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest() +now=lambda:time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) +def base(cc,sub,url,pub,lang,b=None): + return dict(country_iso=cc,subdivision_iso=sub,source_url=url,publisher=pub,official='y',transport=urllib.parse.urlparse(url).scheme, + retrieved_at=now(),sha256=sha(b) if b is not None else None,source='live',coverage='complete',language=lang) +class Out: + def __init__(s,cc): + s.d=f'{ST}/{cc}'; os.makedirs(s.d,exist_ok=True); s.ck=s.d+'/ckpt.json' + s.state=json.load(open(s.ck)) if os.path.exists(s.ck) else {'done_tasks':[]} + def w(s,cfg,row): open(f'{s.d}/{cfg}.jsonl','a').write(json.dumps(row,ensure_ascii=False)+'\n') + def done(s,t): return t in s.state['done_tasks'] + def mark(s,t,cov='complete'): + s.state['done_tasks'].append(t); s.state.setdefault('coverage',{})[t]=cov; json.dump(s.state,open(s.ck,'w'),indent=1) +def task(o,name,fn): + if o.done(name): log('SKIP_DONE',name); return + log('TASK_START',name) + try: cov=fn() or 'complete' + except HostStop as h: cov='partial_host_stopped'; log('TASK_HOSTSTOP',name,h) + o.mark(name,cov); log('TASK_END',name,cov) +# ---------------- GB +def gb_courts(o): + B='https://www.find-court-tribunal.service.gov.uk'; slugs=set() + for q in ['court','tribunal','centre','justice','hearing','house','office','law','county','magistrates','crown','family']: + r=fetch(f'{B}/courts?search={q}') + if r: slugs|=set(re.findall(r'href="/courts/([a-z0-9-]+)"',r[0].decode('utf-8','ignore'))) + log('GB slugs',len(slugs)) + for s in sorted(slugs): + r=fetch(f'{B}/courts/{s}') + if not r: continue + b=r[0].decode('utf-8','ignore'); t=txt(b) + m=re.search(r']*>(.*?)',b,re.S); name=txt(m.group(1)) if m else s + from gb_geo import sub_from,parse_addresses + addrs,ll=parse_addresses(b); pc=next((x['postal_code'] for x in addrs if x.get('postal_code')),None) + sub,how=sub_from(pc,t) + cid=f'GB-{sub[3:]}-{s}' + lvl='tribunal' if 'ribunal' in name else ('first_instance') + o.w('courts',{**base('GB',sub,f'{B}/courts/{s}','HMCTS','en',b),'court_id':cid,'name':name,'name_en':name,'level':lvl,'jurisdiction_type':None,'parent_court_id':None,'subdivision_method':how}) + for i,x in enumerate(addrs): + o.w('courthouses',{**base('GB',sub,f'{B}/courts/{s}','HMCTS','en',b),'courthouse_id':cid+('-visit' if i==0 else f'-addr{i+1}'),'court_id':cid,'name':name, + 'street':x['street'],'locality':x['locality'],'postal_code':x['postal_code'],'region':sub,'lat':ll[0] if i==0 else None,'lon':ll[1] if i==0 else None,'phone':None,'email':None,'address_source':x['kind']}) +def gb_forms(o): + r=fetch('https://www.gov.uk/api/content/government/collections/court-and-tribunal-forms') + if not r: return 'blocked' + j=json.loads(r[0]); docs=[] + for k,v in j.get('links',{}).items(): + if k=='documents': docs+= [d['base_path'] for d in v] + log('GB form docs',len(docs)); n=0; cap=250 + for p in docs: + if n>=cap: return 'forms_cap250' + rr=fetch('https://www.gov.uk/api/content'+p) + if not rr: continue + d=json.loads(rr[0]); atts=d.get('details',{}).get('attachments',[]) or [] + for a in atts: + u=a.get('url'); + if not u or n>=cap: continue + if u.startswith('/'): u='https://www.gov.uk'+u + fr=fetch(u,binary=True) + o.w('forms',{**base('GB','GB-ENG',u,'HMCTS','en',fr[0] if fr else None),'form_id':(a.get('title') or '')[:40] if not re.match(r'\w',d.get('title','')) else d.get('title','').split()[0], + 'title':a.get('title') or d.get('title'),'court_id':None,'issuing_body':'HMCTS','url':u,'format':a.get('content_type'),'parent_page':'https://www.gov.uk'+p}) + n+=1 +def gb_rules(o): + for rs,idx,pref in [('CPR','https://www.justice.gov.uk/courts/procedure-rules/civil/rules','/courts/procedure-rules/civil/rules/'), + ('FPR','https://www.justice.gov.uk/courts/procedure-rules/family/rules_pd_menu','/courts/procedure-rules/family/'), + ('CrimPR','https://www.justice.gov.uk/courts/procedure-rules/criminal/rulesmenu','/courts/procedure-rules/criminal/')]: + r=fetch(idx) + if not r: log('GB rules idx miss',idx); continue + links=sorted(set(urllib.parse.urljoin(idx,h) for h in re.findall(r'href="([^"#]+)"',r[0].decode('utf-8','ignore')))) + links=[l for l in links if urllib.parse.urlparse(l).path.startswith(pref) and l.rstrip('/')!=idx.rstrip('/') and urllib.parse.urlparse(l).netloc=='www.justice.gov.uk' and not l.lower().endswith('.pdf')][:150] + for l in links: + rr=fetch(l) + if not rr: continue + b=rr[0].decode('utf-8','ignore'); m=re.search(r']*>(.*?)',b,re.S) + o.w('rules',{**base('GB','GB-ENG',l,'Ministry of Justice','en',rr[0]),'rule_set':rs,'section':l.rstrip('/').rsplit('/',1)[-1],'title':txt(m.group(1)) if m else None,'url':l,'effective_date':None}) +# ---------------- DE +def de_zpo(o): + r=fetch('https://www.gesetze-im-internet.de/zpo/xml.zip',binary=True) + if not r: return 'blocked' + z=zipfile.ZipFile(io.BytesIO(r[0])); x=ET.fromstring(z.read([n for n in z.namelist() if n.endswith('.xml')][0])) + for nm in x.iter('norm'): + md=nm.find('metadaten'); e=md.findtext('enbez') if md is not None else None + if not e or not e.startswith('§'): continue + ti=md.findtext('titel'); body=ET.tostring(nm,encoding='unicode') + num=e.replace('§','').strip() + u=f'https://www.gesetze-im-internet.de/zpo/__{num}.html' + o.w('rules',{**base('DE',None,u,'BMJ / gesetze-im-internet.de','de',body),'rule_set':'ZPO','section':e,'title':ti,'url':u,'effective_date':None,'note':'sha256 of norm XML from zpo/xml.zip'}) +# ---------------- CA +def ca_laws(o): + for code,rs in [('SOR-98-106','Federal Courts Rules'),('SOR-2002-156','Rules of the Supreme Court of Canada'),('SOR-90-688a','Tax Court of Canada Rules (General Procedure)')]: + u=f'https://laws-lois.justice.gc.ca/eng/XML/{code}.xml'; r=fetch(u,binary=True) + if not r: log('CA miss',u); continue + x=ET.fromstring(r[0]) + for s in x.iter('Section'): + lab=s.findtext('Label'); mn=s.findtext('MarginalNote') + if not lab: continue + o.w('rules',{**base('CA',None,f'https://laws-lois.justice.gc.ca/eng/regulations/{code}/',('Department of Justice Canada'),'en',ET.tostring(s)),'rule_set':rs,'section':lab,'title':mn,'url':f'https://laws-lois.justice.gc.ca/eng/regulations/{code}/','effective_date':None}) +def ca_scc(o): + u='https://www.scc-csc.ca/about-apropos/judges-juges/list-liste/'; r=fetch(u) + if not r: return 'blocked' + b=r[0].decode('utf-8','ignore'); seen=set() + for href,inner in re.findall(r'href="(/about-apropos/judges-juges/list-liste/[a-z0-9-]+/)"[^>]*>(.*?)',b,re.S): + nm=txt(inner) + if not nm or href in seen or len(nm)>80: continue + seen.add(href); title='Chief Justice of Canada' if 'Chief' in nm else 'Puisne Justice' + clean=re.sub(r'^(The )?(Right )?Honourable |,? ?(Chief Justice of Canada|P\.C\.)','',nm).strip() + o.w('judges',{**base('CA',None,u,'Supreme Court of Canada','en',b),'name':clean,'court_id':'CA-NAT-supreme-court-of-canada','title':title,'role_type':'justice','profile_url':'https://www.scc-csc.ca'+href}) + if not seen: return 'blocked' +def finish(marker,why): + open(f'{ROOT}/{marker}','w').write(f'{now()} {why}\n'); log('FINISH',marker,why) + import subprocess; subprocess.run([sys.executable,ROOT+'/collector/intl_review.py']); sys.exit(0 if marker=='INTL_DONE' else 5) +if __name__=='__main__': + log('START pid',os.getpid(),'memavail %.2fG'%memavail()) + plan=[('GB',[('gb_courts',gb_courts),('gb_forms',gb_forms),('gb_rules',gb_rules)]),('DE',[('de_zpo',de_zpo)]),('CA',[('ca_laws',ca_laws),('ca_scc',ca_scc)])] + for cc,ts in plan: + o=Out(cc) + for n,f in ts: task(o,n,lambda f=f,o=o:f(o)) + open(f'{ST}/{cc}/DONE','w').write(now()) + finish('INTL_DONE','all planned tasks; FR/NG/SCTS/Ontario skipped per TERMS_REVIEW.md') diff --git a/scrapers_and_normalizers/courts/intl/collector/intl_review.py b/scrapers_and_normalizers/courts/intl/collector/intl_review.py new file mode 100644 index 0000000000000000000000000000000000000000..e43100da61cd093f6de34dd2096e8b36e9bf3018 --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/intl_review.py @@ -0,0 +1,22 @@ +import json,os,glob,collections,time +R='/workspace/courts/intl'; O=R+'/review_intl'; os.makedirs(O,exist_ok=True) +cnt={};bad=collections.Counter();ids=collections.Counter() +req={'courts':['court_id','name'],'courthouses':['courthouse_id','court_id'],'judges':['name','court_id','title'],'forms':['url','sha256'],'rules':['rule_set','section','url']} +cov={} +for d in sorted(glob.glob(R+'/staging/*/')): + cc=d.rstrip('/').rsplit('/',1)[1]; ck=d+'ckpt.json' + cov[cc]=json.load(open(ck)).get('coverage',{}) if os.path.exists(ck) else {} + for f in glob.glob(d+'*.jsonl'): + cfg=os.path.basename(f)[:-6]; n=0 + for l in open(f): + r=json.loads(l); n+=1 + for k in req.get(cfg,[]): + if not r.get(k): bad[f'{cc}/{cfg}/missing_{k}']+=1 + if r.get('source')!='live': bad[f'{cc}/{cfg}/nonlive']+=1 + for pk in ('court_id','courthouse_id'): + if cfg==pk.split('_')[0]+'s': ids[(cfg,r.get(pk))]+=1 + cnt[f'{cc}/{cfg}']=n +dups={f'{k[0]}:{k[1]}':v for k,v in ids.items() if v>1} +json.dump({'generated':time.strftime('%Y-%m-%d %H:%M %Z'),'counts':cnt,'coverage':cov,'validation':{'missing_or_nonlive':dict(bad),'duplicate_ids':dups}, + 'skips':'see TERMS_REVIEW.md + dead targets (Legifrance 403, judiciary.uk 202, UKSC 404, justiz.de forms 404, bccourts)'},open(O+'/summary.json','w'),indent=1) +open(O+'/REVIEW_READY','w').write(time.strftime('%Y-%m-%dT%H:%M:%S%z')+'\n') diff --git a/scrapers_and_normalizers/courts/intl/collector/run_gb_fix.sh b/scrapers_and_normalizers/courts/intl/collector/run_gb_fix.sh new file mode 100644 index 0000000000000000000000000000000000000000..2f98668033e1db3def5cf8f572cad93546062dcc --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/run_gb_fix.sh @@ -0,0 +1,5 @@ +#!/bin/bash +R=/workspace/courts/intl; cd $R/collector; echo $$ > $R/GB_FIX.pid +python3 -u gb_fix.py >> $R/logs/gb_fix_driver.log 2>&1; rc=$? +python3 gb_fix_apply.py > $R/review_intl/gb_fix_apply.out 2>&1 +if [ $rc = 0 ] && [ ! -f $R/STOPPED_GB_FIX ]; then date -Is > $R/GB_FIX_DONE; else [ -f $R/STOPPED_GB_FIX ] || echo "$(date -Is) rc=$rc No relaunch." > $R/STOPPED_GB_FIX; fi diff --git a/scrapers_and_normalizers/courts/intl/collector/run_intl2.sh b/scrapers_and_normalizers/courts/intl/collector/run_intl2.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c5577c6d7226c73cdccfbef1dd5093401324a0f --- /dev/null +++ b/scrapers_and_normalizers/courts/intl/collector/run_intl2.sh @@ -0,0 +1,4 @@ +#!/bin/bash +R=/workspace/courts/intl; cd $R/collector; echo $$ > $R/INTL2.pid +python3 -u intl2_collect.py >> $R/logs/intl2_driver.log 2>&1; rc=$? +[ -f $R/INTL2_DONE ] || [ -f $R/STOPPED_INTL2 ] || echo "$(date -Is) rc=$rc crash, no relaunch" > $R/STOPPED_INTL2 diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/__init__.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c32fa5a2e5ffb9083d925dbc28f32bd2e5d1eb66 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/__init__.py @@ -0,0 +1,15 @@ +"""Checker sub-package: re-exports all check functions for convenient import.""" + +from .geography import check_geography +from .code_type import check_code_type +from .section import check_section +from .date import check_date +from .format import check_format + +__all__ = [ + "check_geography", + "check_code_type", + "check_section", + "check_date", + "check_format", +] diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/code_type.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/code_type.py new file mode 100644 index 0000000000000000000000000000000000000000..cd63011e12594709b88ea70a1581bdd3973b38d8 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/code_type.py @@ -0,0 +1,76 @@ +"""Code-type checker: validates Municipal / County Code type against GNIS class_code.""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ..constants import MUNICIPAL_CLASS_CODES, COUNTY_CLASS_CODES, CONSOLIDATED_CLASS_CODES + +logger = logging.getLogger(__name__) + +# Bug #22 fix: use class_code values (C1-C7, H1/H4-H6, C8), NOT feature_class strings. +# Frozensets are defined in constants.py for shared use across the package. +_MUNICIPAL_CLASS_CODES = MUNICIPAL_CLASS_CODES +_COUNTY_CLASS_CODES = COUNTY_CLASS_CODES +_CONSOLIDATED_CLASS_CODES = CONSOLIDATED_CLASS_CODES + + +def check_code_type(citation: dict, reference_db) -> Optional[str]: + """Validate that the citation's code type (Municipal/County/City Code) matches the GNIS class_code. + + Per the Bluebook PRD: + - ``C1``–``C7`` → Municipal Code + - ``H1``, ``H4``–``H6`` → County Code + - ``C8`` → consolidated city (accepts either Municipal or County Code) + + Args: + citation: Citation dict. Must contain ``gnis`` and ``code_type`` fields. + reference_db: An open database connection whose ``locations`` table has a + ``class_code`` column keyed by ``gnis``. + + Returns: + ``None`` when the code type is valid; an error string otherwise. + """ + gnis = citation.get("gnis") + cited_code_type = citation.get("code_type") or citation.get("bluebook_code_type") + + if gnis is None or not cited_code_type: + return "Missing gnis or code_type in citation" + + try: + result = reference_db.execute( + "SELECT class_code FROM locations WHERE gnis = ?", [int(gnis)] + ).fetchone() + except Exception as exc: + logger.error("Database error during code-type check for gnis %s: %s", gnis, exc) + return f"Database error checking code type for gnis {gnis}: {exc}" + + if result is None: + return f"GNIS {gnis} not found in reference database" + + class_code: str = str(result[0]).strip() + cited_code_type = cited_code_type.strip() + + if class_code in _MUNICIPAL_CLASS_CODES: + expected = "Municipal Code" + elif class_code in _COUNTY_CLASS_CODES: + expected = "County Code" + elif class_code in _CONSOLIDATED_CLASS_CODES: + # Consolidated city-counties are valid as either type. + if cited_code_type in ("Municipal Code", "County Code", "City Code"): + return None + return ( + f"Code type '{cited_code_type}' not valid for consolidated city " + f"(class_code={class_code}); expected 'Municipal Code' or 'County Code'" + ) + else: + return f"Unknown class_code '{class_code}' for gnis {gnis}" + + if cited_code_type != expected: + return ( + f"Code type mismatch for gnis {gnis} (class_code={class_code}): " + f"citation says '{cited_code_type}', should be '{expected}'" + ) + + return None # valid diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/date.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/date.py new file mode 100644 index 0000000000000000000000000000000000000000..b92aab1440b816b7fd7759087dc06ba3a323f8b3 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/date.py @@ -0,0 +1,89 @@ +"""Date checker: validates the citation year is reasonable and consistent. + +Fixes: +- Bug #9: returns ``None`` (not the string ``'Date check passed'``) on success. +- Deferred feature #26: implements document date cross-reference check. +""" + +from __future__ import annotations + +import re +from typing import Optional + +_YEAR_PATTERN = re.compile(r"\b(1[7-9]\d{2}|20[0-2]\d)\b") +_CITATION_YEAR_PATTERN = re.compile(r"\((\d{4})\)$") + +_MIN_YEAR = 1776 +_MAX_YEAR = 2025 + + +def _extract_year_from_string(text: str) -> Optional[int]: + """Return the first plausible 4-digit year found in *text*, or ``None``.""" + m = _YEAR_PATTERN.search(str(text)) + return int(m.group(1)) if m else None + + +def check_date(citation: dict, documents: Optional[list[dict]] = None) -> Optional[str]: + """Validate the citation year. + + Checks (in order): + 1. Range check: year must be in ``[1776, 2025]``. + 2. Metadata cross-reference: year extracted from ``bluebook_citation`` must + match the year from the ``date`` / ``year`` field (if both are present). + 3. Document cross-reference: the year must appear in at least one document + (if documents are provided). This implements the previously deferred + TODO in the original code. + + Args: + citation: Citation dict. Year is read from ``bluebook_citation`` (trailing + ``(YYYY)`` pattern) and/or the ``date`` / ``year`` field. + documents: Optional list of document dicts with ``html_body`` or ``content``. + + Returns: + ``None`` when all checks pass; an error string otherwise. + """ + # --- Extract year from bluebook_citation string --- + citation_year: Optional[int] = None + bluebook = citation.get("bluebook_citation", "") + if bluebook: + m = _CITATION_YEAR_PATTERN.search(bluebook.strip()) + if m: + citation_year = int(m.group(1)) + + # --- Extract year from metadata field --- + metadata_year: Optional[int] = None + raw_date = citation.get("date") or citation.get("year") + if raw_date is not None: + if isinstance(raw_date, int): + metadata_year = raw_date + else: + metadata_year = _extract_year_from_string(str(raw_date)) + + # Decide which year to use for range checking (prefer citation string). + year = citation_year if citation_year is not None else metadata_year + + if year is None: + return "Could not extract a valid year from citation or metadata" + + # 1. Range check. + if not (_MIN_YEAR <= year <= _MAX_YEAR): + return f"Year {year} is outside the valid range ({_MIN_YEAR}–{_MAX_YEAR})" + + # 2. Metadata cross-reference. + if citation_year is not None and metadata_year is not None: + if citation_year != metadata_year: + return ( + f"Year mismatch: bluebook_citation says {citation_year}, " + f"metadata date says {metadata_year}" + ) + + # 3. Document cross-reference (deferred feature now implemented). + if documents: + year_str = str(year) + found_in_doc = any( + year_str in (doc.get("html_body") or doc.get("content") or "") for doc in documents + ) + if not found_in_doc: + return f"Year {year} not found in any source document" + + return None # all checks passed diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/format.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/format.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c800c099dfc547cd170a1830a1423f33fc7722 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/format.py @@ -0,0 +1,67 @@ +"""Format checker: validates the ``bluebook_citation`` string against Bluebook Rule 12.9. + +Deferred feature #27 fix: validates the full citation STRING, not individual +title/url/section fields. +""" + +from __future__ import annotations + +import re +from typing import Optional + +from ..constants import BLUEBOOK_STATE_ABBREVS, MIN_CITATION_YEAR, MAX_CITATION_YEAR + +# --------------------------------------------------------------------------- +# Bluebook Rule 12.9 pattern +# Format: "Place, State Abbrev., Code Type, §Section (Year)" +# Example: "Garland, Ark., County Code, §14-75 (2007)" +# --------------------------------------------------------------------------- +_BLUEBOOK_PATTERN = re.compile( + r"^(?P[^,]+),\s+" + # State abbreviation: handles all Bluebook forms: + # single-word e.g. "Ala." "Alaska" "Ohio" + # all-caps e.g. "N.H." "D.C." "S.C." + # two-word e.g. "W. Va." + r"(?P[A-Z][A-Za-z.]*\.?(?:\s[A-Z][a-z]+\.?)?),\s+" + r"(?P(?:Municipal|County|City)\s+Code),\s+" + r"§(?P
[\d]+(?:[-.][\d]+)*)\s+" + r"\((?P\d{4})\)$" +) + + +def check_format(citation: dict) -> Optional[str]: + """Validate the ``bluebook_citation`` string against Bluebook Rule 12.9 format. + + Args: + citation: Citation dict containing a ``bluebook_citation`` field. + + Returns: + ``None`` when the format is valid; a descriptive error string otherwise. + """ + raw = citation.get("bluebook_citation") + if not raw: + return "Missing bluebook_citation field" + + text = raw.strip() + m = _BLUEBOOK_PATTERN.match(text) + if not m: + return ( + f"bluebook_citation does not match Bluebook Rule 12.9 format " + f"'Place, State, Code Type, §Section (Year)': {text!r}" + ) + + state_abbrev = m.group("state") + if state_abbrev not in BLUEBOOK_STATE_ABBREVS: + return ( + f"Unrecognised Bluebook state abbreviation '{state_abbrev}' " + f"in bluebook_citation: {text!r}" + ) + + year = int(m.group("year")) + if not (MIN_CITATION_YEAR <= year <= MAX_CITATION_YEAR): + return ( + f"Year {year} in bluebook_citation is outside the valid range " + f"({MIN_CITATION_YEAR}–{MAX_CITATION_YEAR}): {text!r}" + ) + + return None # valid diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/geography.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/geography.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8cfbc204a8919e6141c57a17c431ee07a9762b --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/geography.py @@ -0,0 +1,49 @@ +"""Geography checker: validates that a citation's state matches the GNIS record.""" + +from __future__ import annotations + +import logging +from typing import Optional + +logger = logging.getLogger(__name__) + + +def check_geography(citation: dict, reference_db) -> Optional[str]: + """Validate that the place name and state in the citation match the GNIS reference data. + + Args: + citation: Citation dict. Must contain ``gnis`` and + ``bluebook_state_code`` fields. + reference_db: An open database connection whose ``locations`` table + has a ``state_code`` column keyed by ``gnis``. + + Returns: + ``None`` when the geography is valid; an error string otherwise. + """ + gnis = citation.get("gnis") + # Bug #21 fix: use 'bluebook_state_code', NOT 'state' + cited_state = citation.get("bluebook_state_code") + + if gnis is None or cited_state is None: + return "Missing gnis or bluebook_state_code in citation" + + try: + # Parameterized query — never interpolate user data into SQL strings + result = reference_db.execute( + "SELECT state_code FROM locations WHERE gnis = ?", [int(gnis)] + ).fetchone() + except Exception as exc: + logger.error("Database error during geography check for gnis %s: %s", gnis, exc) + return f"Database error checking geography for gnis {gnis}: {exc}" + + if result is None: + return f"GNIS {gnis} not found in reference database" + + actual_state = result[0] + if str(cited_state).strip().lower() != str(actual_state).strip().lower(): + return ( + f"State mismatch for gnis {gnis}: " + f"citation says '{cited_state}', reference says '{actual_state}'" + ) + + return None # valid diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/section.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/section.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2f16696ad739ee3e9321300874d71b5b21cf4a --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/section.py @@ -0,0 +1,74 @@ +"""Section checker: validates that the cited section exists in source HTML documents. + +Bug #23 fix: correct signature is ``(citation: dict, documents: list[dict])``, +**not** ``(citation_section: str, html_body: str)``. +""" + +from __future__ import annotations + +import re +from typing import Optional + + +def _extract_section_number(citation: dict) -> Optional[str]: + """Extract a bare section number from the citation dict. + + Tries (in order): + 1. ``citation['title_num']`` — explicit section field. + 2. The section captured from ``citation['bluebook_citation']`` via the + ``§
`` pattern. + + Returns the number string (e.g. ``"14-75"``) or ``None``. + """ + title_num = citation.get("title_num") or citation.get("section") + if title_num: + # Strip any leading §/S whitespace. + cleaned = re.sub(r"^[§S]\s*", "", str(title_num).strip()) + if cleaned: + return cleaned + + bluebook = citation.get("bluebook_citation", "") + # Pattern: §14-75 or § 14-75 in the citation string + m = re.search(r"§\s*([\d]+(?:[-.][\d]+)*)", bluebook) + if m: + return m.group(1) + + return None + + +def check_section(citation: dict, documents: list[dict]) -> Optional[str]: + """Validate that the section referenced in the citation exists in the source HTML. + + Args: + citation: Citation dict. Section is extracted from ``title_num`` or + ``bluebook_citation``. + documents: List of document dicts, each containing ``html_body`` or + ``content`` text. + + Returns: + ``None`` when the section is found; an error string otherwise. + """ + section_number = _extract_section_number(citation) + if not section_number: + return "Could not extract section number from citation" + + if not documents: + return f"No documents provided; cannot verify section {section_number}" + + escaped = re.escape(section_number) + patterns = [ + re.compile(rf"§\s*{escaped}\b", re.IGNORECASE), + re.compile(rf"\bsection\s+{escaped}\b", re.IGNORECASE), + re.compile(rf"\bsec\.\s*{escaped}\b", re.IGNORECASE), + re.compile(rf"\bs\s+{escaped}\b", re.IGNORECASE), + ] + + for doc in documents: + body = doc.get("html_body") or doc.get("content") or "" + if not body: + continue + for pattern in patterns: + if pattern.search(body): + return None # found — valid + + return f"Section {section_number} not found in any source document" diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/legal_corpus/docs/JURISDICTION_IMPLEMENTATION.md b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/legal_corpus/docs/JURISDICTION_IMPLEMENTATION.md new file mode 100644 index 0000000000000000000000000000000000000000..8bc4d122b8a59eed6cc330142e87dfd4fa8744de --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/legal_corpus/docs/JURISDICTION_IMPLEMENTATION.md @@ -0,0 +1,100 @@ +# Legal Corpus Jurisdiction Implementation Guide + +This framework defines the reusable legal corpus pipeline contracts used by the +Netherlands BWBR implementation. Future jurisdictions should implement the same +interfaces without weakening Netherlands behavior or reusing unofficial source +logic. + +## Required Spec + +Every jurisdiction must expose a `JurisdictionSpec` with: + +- stable `jurisdiction_id`, `slug`, display name, country code, and language codes +- authoritative source descriptions +- default raw/catalog paths, if the jurisdiction supports durable acquisition +- Hugging Face repo ids for each published package variant +- aliases used by the registry and CLI dispatchers + +## Required Components + +Every production jurisdiction must provide concrete implementations for: + +- `DiscoveryProvider`: official-source discovery, catalog import, queuing, and + coverage reporting +- `FetchProvider`: resumable fetching/scraping from official source records +- `Parser`: source-document parsing into law and article records +- `HierarchyExtractor`: normalized hierarchy extraction for books, titles, + chapters, divisions, paragraphs, articles, or local equivalents +- `StatusClassifier`: official metadata based status/version classification +- `CIDGenerator`: deterministic content-address generation for law and article + payloads +- `PackageBuilder`: normalized and CID package builders +- `VectorIndexBuilder`: dense retrieval index builder +- `BM25IndexBuilder`: sparse retrieval index builder +- `JsonLdGraphBuilder`: JSON-LD graph builder +- `HuggingFacePublisher`: upload and remote verification +- `IntegrityValidator`: duplicate, parent/child, status inheritance, CID, and + graph validation + +## Status Semantics + +Jurisdictions must preserve inactive and historical law. They must not delete a +law merely because it is old, repealed, superseded, or no longer current. + +Each law row and article row should carry: + +- `law_status`: one of `current`, `historical`, `repealed`, `superseded`, + `unknown` +- `is_current` +- `valid_from` +- `valid_to` +- `effective_date` +- `retrieved_at` +- `status_source` +- `status_confidence` +- `status_note` +- version fields where available + +Article rows must inherit the parent law status/version fields unless official +article-level metadata proves a different value. If official metadata cannot +determine status, use `unknown`. + +## CID And Packaging Rules + +CID generation must be deterministic for the exact normalized row payload. If +status/version fields are part of that payload, CID values are expected to change +when those fields change. Package manifests and all downstream indexes must be +rebuilt consistently from the same row set. + +## Completeness And Integrity + +Jurisdictions with durable ingestion should converge through explicit states +such as discovered, queued, downloading, downloaded, parsed, packaged, uploaded, +verified, failed, and permanently skipped. Coverage reports must distinguish +processed, remaining, transient failures, permanent failures, and intentionally +skipped identifiers. + +Integrity validation should detect duplicate source identifiers, duplicate CIDs, +orphan article rows, missing parent law rows, status inheritance drift, and +broken graph edges. + +## Publication + +Dataset cards must state corpus scope, scrape date, exact row counts, +status-labeling semantics, limitations, and that the dataset is not legal advice. +Do not claim full jurisdiction coverage unless every discovered official +identifier has been parsed, intentionally skipped, or permanently failed with an +explanation. + +## First Implementation + +The Netherlands implementation lives in +`ipfs_datasets_py.processors.legal_scrapers.netherlands_laws.jurisdiction` and +adapts the existing BWBR catalog-backed pipeline behind these interfaces. Its +existing CLI commands remain backward compatible. + +Harvested Hugging Face gazette collectors are wrapped by +`ipfs_datasets_py.processors.legal_scrapers.international` behind the same +interfaces. Use `scrape_legal_data(jurisdiction, mode="snapshot"|"collect"|"native")` +as the unified API. Snapshot corpora are research snapshots, not official +consolidations, and are not legal advice. diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/common.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/common.py new file mode 100644 index 0000000000000000000000000000000000000000..cd73fd1ad1a229dcea0de88f9823c06c3633166b --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/common.py @@ -0,0 +1,159 @@ +"""Shared helpers for Netherlands laws packaging builders.""" + +from __future__ import annotations + +import hashlib +import json +import re +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq + +from ipfs_datasets_py.utils.cid_utils import cid_for_bytes + + +PARSER_NOISE_PHRASES = [ + "Toon relaties in LiDO", + "Maak een permanente link", + "Toon wetstechnische informatie", + "Geen andere versie om mee te vergelijken", + "Druk de regeling af", + "Druk het regelingonderdeel af", + "Sla de regeling op", + "Sla het regelingonderdeel op", +] + +PARSER_NOISE_PATTERNS = [ + re.compile(rf"\b{re.escape(phrase)}\b", re.IGNORECASE) for phrase in PARSER_NOISE_PHRASES +] +_WHITESPACE_RE = re.compile(r"\s+") + + +def iter_jsonl(path: Path): + with path.open("r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line: + yield json.loads(line) + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + for row in iter_jsonl(path): + rows.append(row) + return rows + + +def count_jsonl(path: Path) -> int: + count = 0 + with path.open("r", encoding="utf-8") as handle: + for line in handle: + if line.strip(): + count += 1 + return count + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def clean_legal_text(text: Any) -> str: + """Remove official website UI chrome from scraped legal text.""" + if text is None: + return "" + cleaned = str(text) + for pattern in PARSER_NOISE_PATTERNS: + cleaned = pattern.sub(" ", cleaned) + return _WHITESPACE_RE.sub(" ", cleaned).strip() + + +def stable_row_key(row: dict[str, Any]) -> str: + return json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str) + + +def disambiguate_duplicate_article_identifiers(rows: list[dict[str, Any]]) -> int: + """Make repeated scraper article IDs unique by appending a hierarchy-derived suffix.""" + groups: dict[str, list[dict[str, Any]]] = {} + for row in rows: + identifier = str(row.get("article_identifier") or "") + if not identifier: + continue + groups.setdefault(identifier, []).append(row) + + changed = 0 + for identifier, group in groups.items(): + if len(group) < 2: + continue + for row in group: + basis = { + "citation": row.get("citation"), + "hierarchy_path": row.get("hierarchy_path"), + "hierarchy_path_text": row.get("hierarchy_path_text"), + "article_number": row.get("article_number"), + "text": row.get("text"), + } + suffix = hashlib.sha256(stable_row_key(basis).encode("utf-8")).hexdigest()[:12] + row["article_identifier"] = f"{identifier}:path:{suffix}" + changed += 1 + return changed + + +def _parquet_safe(value: Any) -> Any: + if value == {}: + return None + if isinstance(value, dict): + return {key: _parquet_safe(item) for key, item in value.items()} + if isinstance(value, list): + return [_parquet_safe(item) for item in value] + return value + + +def _jsonify_complex(value: Any) -> Any: + if isinstance(value, (dict, list)): + return json.dumps(value, ensure_ascii=False, sort_keys=True) + return value + + +def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + safe_rows = [{key: _parquet_safe(value) for key, value in row.items()} for row in rows] + try: + table = pa.Table.from_pylist(safe_rows) + except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError): + table = pa.Table.from_pylist( + [{key: _jsonify_complex(value) for key, value in row.items()} for row in safe_rows] + ) + pq.write_table(table, path, compression="zstd") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def file_cid(path: Path) -> str: + return cid_for_bytes(path.read_bytes()) + + +def file_manifest_entry(path: Path, records: int | None = None) -> dict[str, Any]: + entry: dict[str, Any] = { + "bytes": path.stat().st_size, + "sha256": sha256(path), + "file_cid": file_cid(path), + } + if records is not None: + entry["records"] = records + return entry + + +def write_json(path: Path, obj: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(obj, indent=2, ensure_ascii=False), encoding="utf-8") diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_indexes.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..992fb359856b59d9d8f772a54a43be161a243b29 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_indexes.py @@ -0,0 +1,663 @@ +"""Build CID-keyed vector, BM25, and JSON-LD indexes for Netherlands laws.""" + +from __future__ import annotations + +import json +import math +import pickle +import re +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +from ipfs_datasets_py.utils.cid_utils import cid_for_obj + +from .common import ( + file_cid, + file_manifest_entry, + read_jsonl, + write_json, + write_jsonl, + write_parquet, +) +from ..paths import ( + BM25_INDEX_DATASET_NAME, + DEFAULT_HF_REPO_IDS, + HF_DATA_DIR, + IPFS_DATASET_NAME, + KNOWLEDGE_GRAPH_DATASET_NAME, + VECTOR_INDEX_DATASET_NAME, +) + + +DEFAULT_SOURCE_DIR = HF_DATA_DIR / IPFS_DATASET_NAME +DEFAULT_VECTOR_OUT_DIR = HF_DATA_DIR / VECTOR_INDEX_DATASET_NAME +DEFAULT_BM25_OUT_DIR = HF_DATA_DIR / BM25_INDEX_DATASET_NAME +DEFAULT_KG_OUT_DIR = HF_DATA_DIR / KNOWLEDGE_GRAPH_DATASET_NAME +TOKENIZER_RE = re.compile(r"[0-9A-Za-zÀ-ÿ_]+", re.UNICODE) + + +def tokenise(text: str) -> list[str]: + return [match.group(0).lower() for match in TOKENIZER_RE.finditer(text or "")] + + +def load_source_rows(source_dir: Path | None = None) -> list[dict[str, Any]]: + source_dir = source_dir or DEFAULT_SOURCE_DIR + laws = read_jsonl(source_dir / "data/laws/ipfs_netherlands_laws.jsonl") + articles = read_jsonl(source_dir / "data/articles/ipfs_netherlands_laws_articles.jsonl") + corpus: list[dict[str, Any]] = [] + for row in laws: + corpus.append( + { + "record_type": "law", + "source_cid": row["cid"], + "law_cid": row["cid"], + "law_identifier": row.get("law_identifier"), + "article_identifier": None, + "title": row.get("title") or row.get("citation") or row.get("law_identifier"), + "citation": row.get("citation"), + "content_address": row.get("content_address"), + "source_url": row.get("source_url"), + "law_status": row.get("law_status"), + "is_current": row.get("is_current"), + "valid_from": row.get("valid_from"), + "valid_to": row.get("valid_to"), + "effective_date": row.get("effective_date"), + "retrieved_at": row.get("retrieved_at"), + "status_source": row.get("status_source"), + "status_confidence": row.get("status_confidence"), + "status_note": row.get("status_note"), + "text": row.get("text") or "", + } + ) + for row in articles: + corpus.append( + { + "record_type": "article", + "source_cid": row["cid"], + "law_cid": row.get("law_cid"), + "law_identifier": row.get("law_identifier"), + "article_identifier": row.get("article_identifier"), + "title": row.get("citation") or row.get("article_identifier"), + "citation": row.get("citation"), + "content_address": row.get("content_address"), + "source_url": None, + "law_status": row.get("law_status"), + "is_current": row.get("is_current"), + "valid_from": row.get("valid_from"), + "valid_to": row.get("valid_to"), + "effective_date": row.get("effective_date"), + "retrieved_at": row.get("retrieved_at"), + "status_source": row.get("status_source"), + "status_confidence": row.get("status_confidence"), + "status_note": row.get("status_note"), + "text": row.get("text") or "", + } + ) + return corpus + + +def load_source_run_metadata(source_dir: Path | None = None) -> dict[str, Any]: + source_dir = source_dir or DEFAULT_SOURCE_DIR + metadata_path = source_dir / "data/metadata/netherlands_laws_run_metadata_latest.json" + if not metadata_path.exists(): + return {} + try: + return json.loads(metadata_path.read_text(encoding="utf-8")) + except Exception: + return {} + + +def _write_dataset_card( + out_dir: Path, title: str, repo_id: str, configs: list[str], body: str +) -> None: + config_yaml = "\n".join( + [ + f"- config_name: {config}\n data_files:\n - split: train\n path: parquet/{config}/*.parquet" + for config in configs + ] + ) + readme = f"""--- +pretty_name: {title} +language: +- nl +tags: +- ipfs +- cid +- legal +license: other +configs: +{config_yaml} +--- + +# {title} + +Hugging Face target: `{repo_id}`. + +{body} +""" + (out_dir / "README.md").write_text(readme, encoding="utf-8") + + +def _write_gitattributes(out_dir: Path) -> None: + (out_dir / ".gitattributes").write_text( + "parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text\n" + "artifacts/* filter=lfs diff=lfs merge=lfs -text\n" + "data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text\n" + "data/**/*.jsonld filter=lfs diff=lfs merge=lfs -text\n", + encoding="utf-8", + ) + + +def _catalog_summary_text(run_metadata: dict[str, Any]) -> str: + if not run_metadata.get("catalog_backed_run"): + return "" + counts = run_metadata.get("catalog_coverage_counts") or {} + return ( + f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). " + f"Catalog coverage after this run: {counts.get('complete', 'unknown')} complete of " + f"{counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) " + f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: " + f"{counts.get('remaining', 'unknown')}. Integrity validation ok: " + f"{run_metadata.get('catalog_integrity_ok', 'unknown')}. " + "This is not full Dutch corpus coverage until every discovered identifier is parsed, intentionally skipped, " + "or permanently failed with explanation. " + ) + + +def _write_manifest( + out_dir: Path, + dataset_name: str, + repo_id: str, + record_counts: dict[str, int], + source_dataset: str = DEFAULT_HF_REPO_IDS["base"], + extra: dict[str, Any] | None = None, +) -> dict[str, Any]: + manifest: dict[str, Any] = { + "dataset_name": dataset_name, + "source_dataset": source_dataset, + "repo_target": repo_id, + "upload_target": repo_id, + "records": record_counts, + "files": {}, + } + if extra: + manifest["index_metadata"] = extra + for path in sorted( + p for p in out_dir.rglob("*") if p.is_file() and p.name != "dataset_manifest.json" + ): + rel = path.relative_to(out_dir).as_posix() + records = None + for key, count in record_counts.items(): + if ( + f"/{key}/" in f"/{rel}/" + or rel.startswith(f"parquet/{key}/") + or rel.startswith(f"data/{key}/") + ): + records = count + break + manifest["files"][rel] = file_manifest_entry(path, records) + write_json(out_dir / "dataset_manifest.json", manifest) + return manifest + + +def build_vector_index( + corpus: list[dict[str, Any]] | None = None, + source_dir: Path | None = None, + out_dir: Path | None = None, + repo_id: str = DEFAULT_HF_REPO_IDS["vector"], +) -> Path: + import faiss + from sklearn.decomposition import TruncatedSVD + from sklearn.feature_extraction.text import TfidfVectorizer + from sklearn.preprocessing import normalize + + corpus = corpus or load_source_rows(source_dir) + run_metadata = load_source_run_metadata(source_dir) + out_dir = out_dir or DEFAULT_VECTOR_OUT_DIR + docs: list[dict[str, Any]] = [] + texts: list[str] = [] + for row in corpus: + search_text = f"{row.get('title') or ''}\n{row.get('citation') or ''}\n{row.get('text') or ''}".strip() + docs.append({**row, "search_text": search_text}) + texts.append(search_text) + + vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1, max_features=8192) + tfidf = vectorizer.fit_transform(texts) + max_components = min(256, max(2, tfidf.shape[0] - 1), max(2, tfidf.shape[1] - 1)) + svd = TruncatedSVD(n_components=max_components, random_state=42) + dense = normalize(svd.fit_transform(tfidf), norm="l2").astype("float32") + + index = faiss.IndexFlatIP(dense.shape[1]) + index.add(dense) + + mapping_rows: list[dict[str, Any]] = [] + for idx, row in enumerate(docs): + payload = { + "cid": row["source_cid"], + "source_cid": row["source_cid"], + "law_cid": row.get("law_cid"), + "record_type": row["record_type"], + "law_identifier": row.get("law_identifier"), + "article_identifier": row.get("article_identifier"), + "title": row.get("title"), + "citation": row.get("citation"), + "content_address": row.get("content_address"), + "law_status": row.get("law_status"), + "is_current": row.get("is_current"), + "valid_from": row.get("valid_from"), + "valid_to": row.get("valid_to"), + "effective_date": row.get("effective_date"), + "retrieved_at": row.get("retrieved_at"), + "status_source": row.get("status_source"), + "status_confidence": row.get("status_confidence"), + "status_note": row.get("status_note"), + "embedding": dense[idx].tolist(), + "embedding_dim": int(dense.shape[1]), + "search_text_preview": row["search_text"][:500], + } + payload["index_row_cid"] = cid_for_obj(payload) + mapping_rows.append(payload) + + write_parquet(out_dir / "parquet/mapping/train-00000-of-00001.parquet", mapping_rows) + write_jsonl(out_dir / "data/mapping/ipfs_netherlands_laws_vector_mapping.jsonl", mapping_rows) + (out_dir / "artifacts").mkdir(parents=True, exist_ok=True) + (out_dir / "artifacts/faiss.index").write_bytes(faiss.serialize_index(index).tobytes()) + (out_dir / "artifacts/vectorizer.pkl").write_bytes(pickle.dumps(vectorizer)) + (out_dir / "artifacts/svd.pkl").write_bytes(pickle.dumps(svd)) + metadata = { + "dataset_name": VECTOR_INDEX_DATASET_NAME, + "source_dataset": DEFAULT_HF_REPO_IDS["base"], + "records": len(mapping_rows), + "embedding_method": "tfidf_plus_truncated_svd", + "embedding_dim": int(dense.shape[1]), + "faiss_metric": "inner_product_on_l2_normalized_vectors", + "index_key": "source_cid", + } + write_json(out_dir / "artifacts/metadata.json", metadata) + scrape_date = str(run_metadata.get("scraped_at") or "unknown") + full_bwb = run_metadata.get("full_bwb_discovery") or {} + catalog_summary = _catalog_summary_text(run_metadata) + _write_dataset_card( + out_dir, + "IPFS Netherlands Laws Vector Index", + repo_id, + ["mapping"], + ( + "Dense vector mapping keyed by source CID, with FAISS and TF-IDF/SVD artifacts.\n\n" + f"This index covers {len(mapping_rows)} rows from the paired CID dataset. " + f"Source scrape date: {scrape_date}. " + f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers " + f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). " + f"{catalog_summary}" + "The current source dataset may be capped; do not describe it as the full Dutch corpus unless " + "the paired base dataset manifest/run metadata proves full discovery coverage. " + "The paired base dataset includes article extraction diagnostics and parser coverage improvements " + "for older/French heading styles. The paired source package was quality-audited after parser-noise " + "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean " + "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with " + "`law_status`, `is_current`, validity dates, status source, confidence, and notes; these fields " + "are also present in the vector mapping rows for filtering. This index is not legal advice." + ), + ) + _write_gitattributes(out_dir) + _write_manifest( + out_dir, VECTOR_INDEX_DATASET_NAME, repo_id, {"mapping": len(mapping_rows)}, extra=metadata + ) + return out_dir + + +def build_bm25_index( + corpus: list[dict[str, Any]] | None = None, + source_dir: Path | None = None, + out_dir: Path | None = None, + repo_id: str = DEFAULT_HF_REPO_IDS["bm25"], +) -> Path: + corpus = corpus or load_source_rows(source_dir) + run_metadata = load_source_run_metadata(source_dir) + out_dir = out_dir or DEFAULT_BM25_OUT_DIR + doc_lengths: dict[str, int] = {} + tf_by_doc: dict[str, Counter[str]] = {} + postings_by_term: dict[str, list[tuple[str, int]]] = defaultdict(list) + doc_rows: list[dict[str, Any]] = [] + row_by_cid: dict[str, dict[str, Any]] = {} + + for row in corpus: + text = ( + f"{row.get('title') or ''} {row.get('citation') or ''} {row.get('text') or ''}".strip() + ) + source_cid = row["source_cid"] + tokens = tokenise(text) + term_counts = Counter(tokens) + doc_lengths[source_cid] = len(tokens) + tf_by_doc[source_cid] = term_counts + for term, tf in term_counts.items(): + postings_by_term[term].append((source_cid, tf)) + payload = { + "cid": source_cid, + "source_cid": source_cid, + "law_cid": row.get("law_cid"), + "record_type": row["record_type"], + "law_identifier": row.get("law_identifier"), + "article_identifier": row.get("article_identifier"), + "title": row.get("title"), + "citation": row.get("citation"), + "content_address": row.get("content_address"), + "law_status": row.get("law_status"), + "is_current": row.get("is_current"), + "valid_from": row.get("valid_from"), + "valid_to": row.get("valid_to"), + "effective_date": row.get("effective_date"), + "retrieved_at": row.get("retrieved_at"), + "status_source": row.get("status_source"), + "status_confidence": row.get("status_confidence"), + "status_note": row.get("status_note"), + "doc_length": len(tokens), + "token_count_unique": len(tf_by_doc[source_cid]), + "text_preview": text[:500], + } + payload["doc_row_cid"] = cid_for_obj(payload) + doc_rows.append(payload) + row_by_cid[source_cid] = payload + + n_docs = len(doc_lengths) + avgdl = sum(doc_lengths.values()) / max(1, n_docs) + doc_freq: Counter[str] = Counter() + for tf_counter in tf_by_doc.values(): + doc_freq.update(tf_counter.keys()) + + k1 = 1.5 + b = 0.75 + term_rows: list[dict[str, Any]] = [] + for term in sorted(doc_freq): + df = doc_freq[term] + idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5)) + postings = [] + for source_cid, tf in postings_by_term.get(term, []): + dl = doc_lengths[source_cid] + score = idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (dl / avgdl)))) + postings.append( + { + "source_cid": source_cid, + "law_cid": row_by_cid[source_cid]["law_cid"], + "tf": tf, + "doc_length": dl, + "bm25_term_score": score, + } + ) + row = { + "term": term, + "doc_freq": df, + "idf": idf, + "postings_count": len(postings), + "postings": postings, + } + row["term_row_cid"] = cid_for_obj(row) + term_rows.append(row) + + write_parquet(out_dir / "parquet/documents/train-00000-of-00001.parquet", doc_rows) + write_parquet(out_dir / "parquet/terms/train-00000-of-00001.parquet", term_rows) + write_jsonl(out_dir / "data/documents/ipfs_netherlands_laws_bm25_documents.jsonl", doc_rows) + write_jsonl(out_dir / "data/terms/ipfs_netherlands_laws_bm25_terms.jsonl", term_rows) + metadata = { + "dataset_name": BM25_INDEX_DATASET_NAME, + "source_dataset": DEFAULT_HF_REPO_IDS["base"], + "records": {"documents": len(doc_rows), "terms": len(term_rows)}, + "bm25": {"k1": k1, "b": b, "avgdl": avgdl}, + "index_key": "source_cid", + } + write_json(out_dir / "artifacts/metadata.json", metadata) + scrape_date = str(run_metadata.get("scraped_at") or "unknown") + full_bwb = run_metadata.get("full_bwb_discovery") or {} + catalog_summary = _catalog_summary_text(run_metadata) + _write_dataset_card( + out_dir, + "IPFS Netherlands Laws BM25 Index", + repo_id, + ["documents", "terms"], + ( + "Sparse BM25 document and postings tables keyed by source CID.\n\n" + f"This index covers {len(doc_rows)} documents and {len(term_rows)} terms from the paired CID dataset. " + f"Source scrape date: {scrape_date}. " + f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers " + f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). " + f"{catalog_summary}" + "The current source dataset may be capped; do not describe it as the full Dutch corpus unless " + "the paired base dataset manifest/run metadata proves full discovery coverage. " + "The paired base dataset includes article extraction diagnostics and parser coverage improvements " + "for older/French heading styles. The paired source package was quality-audited after parser-noise " + "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean " + "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with " + "`law_status`, `is_current`, validity dates, status source, confidence, and notes; these fields " + "are also present in BM25 document rows for filtering. This index is not legal advice." + ), + ) + _write_gitattributes(out_dir) + _write_manifest( + out_dir, + BM25_INDEX_DATASET_NAME, + repo_id, + {"documents": len(doc_rows), "terms": len(term_rows)}, + extra=metadata, + ) + return out_dir + + +def build_knowledge_graph( + corpus: list[dict[str, Any]] | None = None, + source_dir: Path | None = None, + out_dir: Path | None = None, + repo_id: str = DEFAULT_HF_REPO_IDS["knowledge-graph"], +) -> Path: + corpus = corpus or load_source_rows(source_dir) + run_metadata = load_source_run_metadata(source_dir) + out_dir = out_dir or DEFAULT_KG_OUT_DIR + laws = [row for row in corpus if row["record_type"] == "law"] + articles = [row for row in corpus if row["record_type"] == "article"] + graph_nodes: list[dict[str, Any]] = [] + graph_edges: list[dict[str, Any]] = [] + jsonld_graph: list[dict[str, Any]] = [] + + context = { + "@vocab": "https://schema.org/", + "source_cid": "https://schema.org/identifier", + "law_cid": "https://schema.org/isPartOf", + "article_identifier": "https://schema.org/identifier", + "law_identifier": "https://schema.org/identifier", + "content_address": "https://schema.org/url", + "law_status": "https://schema.org/legislationLegalForce", + "valid_from": "https://schema.org/validFrom", + "valid_to": "https://schema.org/validThrough", + "hasPart": {"@id": "https://schema.org/hasPart", "@type": "@id"}, + "isPartOf": {"@id": "https://schema.org/isPartOf", "@type": "@id"}, + } + + for law in laws: + node = { + "@id": law["content_address"], + "@type": "Legislation", + "source_cid": law["source_cid"], + "law_identifier": law["law_identifier"], + "name": law["title"], + "law_status": law.get("law_status") or "unknown", + "is_current": law.get("is_current"), + "valid_from": law.get("valid_from"), + "valid_to": law.get("valid_to"), + "effective_date": law.get("effective_date"), + "retrieved_at": law.get("retrieved_at"), + "status_source": law.get("status_source"), + "status_confidence": law.get("status_confidence"), + "status_note": law.get("status_note"), + } + jsonld_graph.append(node) + graph_nodes.append( + { + "cid": law["source_cid"], + "node_cid": cid_for_obj(node), + "source_cid": law["source_cid"], + "record_type": "law", + "label": law["title"], + "jsonld_id": law["content_address"], + "law_identifier": law["law_identifier"], + "article_identifier": None, + "law_status": law.get("law_status"), + "is_current": law.get("is_current"), + "valid_from": law.get("valid_from"), + "valid_to": law.get("valid_to"), + "effective_date": law.get("effective_date"), + "retrieved_at": law.get("retrieved_at"), + "status_source": law.get("status_source"), + "status_confidence": law.get("status_confidence"), + } + ) + + law_map = {law["law_identifier"]: law for law in laws} + for article in articles: + law = law_map.get(article["law_identifier"]) + node = { + "@id": article["content_address"], + "@type": "LegislationObject", + "source_cid": article["source_cid"], + "article_identifier": article["article_identifier"], + "law_identifier": article["law_identifier"], + "name": article["title"], + "law_status": article.get("law_status") or "unknown", + "is_current": article.get("is_current"), + "valid_from": article.get("valid_from"), + "valid_to": article.get("valid_to"), + "effective_date": article.get("effective_date"), + "retrieved_at": article.get("retrieved_at"), + "status_source": article.get("status_source"), + "status_confidence": article.get("status_confidence"), + "status_note": article.get("status_note"), + } + if law: + node["isPartOf"] = {"@id": law["content_address"]} + jsonld_graph.append(node) + graph_nodes.append( + { + "cid": article["source_cid"], + "node_cid": cid_for_obj(node), + "source_cid": article["source_cid"], + "record_type": "article", + "label": article["title"], + "jsonld_id": article["content_address"], + "law_identifier": article["law_identifier"], + "article_identifier": article["article_identifier"], + "law_status": article.get("law_status"), + "is_current": article.get("is_current"), + "valid_from": article.get("valid_from"), + "valid_to": article.get("valid_to"), + "effective_date": article.get("effective_date"), + "retrieved_at": article.get("retrieved_at"), + "status_source": article.get("status_source"), + "status_confidence": article.get("status_confidence"), + } + ) + if law: + edge = { + "cid": article["source_cid"], + "edge_type": "isPartOf", + "source_cid": article["source_cid"], + "target_cid": law["source_cid"], + "source_id": article["content_address"], + "target_id": law["content_address"], + "law_identifier": article["law_identifier"], + "article_identifier": article["article_identifier"], + } + edge["edge_cid"] = cid_for_obj(edge) + graph_edges.append(edge) + + for law in laws: + children = [ + {"@id": article["content_address"]} + for article in articles + if article["law_identifier"] == law["law_identifier"] + ] + if children: + for obj in jsonld_graph: + if obj["@id"] == law["content_address"]: + obj["hasPart"] = children + break + + jsonld_doc = {"@context": context, "@graph": jsonld_graph} + write_jsonl(out_dir / "data/nodes/ipfs_netherlands_laws_kg_nodes.jsonl", graph_nodes) + write_jsonl(out_dir / "data/edges/ipfs_netherlands_laws_kg_edges.jsonl", graph_edges) + (out_dir / "data/graph").mkdir(parents=True, exist_ok=True) + (out_dir / "data/graph/ipfs_netherlands_laws_kg.jsonld").write_text( + json.dumps(jsonld_doc, ensure_ascii=False, indent=2), encoding="utf-8" + ) + write_parquet(out_dir / "parquet/nodes/train-00000-of-00001.parquet", graph_nodes) + write_parquet(out_dir / "parquet/edges/train-00000-of-00001.parquet", graph_edges) + metadata = { + "dataset_name": KNOWLEDGE_GRAPH_DATASET_NAME, + "source_dataset": DEFAULT_HF_REPO_IDS["base"], + "records": {"nodes": len(graph_nodes), "edges": len(graph_edges)}, + "graph_root_cid": cid_for_obj(jsonld_doc), + "index_key": "source_cid", + } + write_json(out_dir / "artifacts/metadata.json", metadata) + scrape_date = str(run_metadata.get("scraped_at") or "unknown") + full_bwb = run_metadata.get("full_bwb_discovery") or {} + catalog_summary = _catalog_summary_text(run_metadata) + _write_dataset_card( + out_dir, + "IPFS Netherlands Laws Knowledge Graph", + repo_id, + ["nodes", "edges"], + ( + "JSON-LD graph and node/edge tables whose identities are IPFS content addresses.\n\n" + f"This graph currently has {len(graph_nodes)} nodes and {len(graph_edges)} edges from the paired CID dataset. " + f"Source scrape date: {scrape_date}. " + f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers " + f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). " + f"{catalog_summary}" + "The current source dataset may be capped; do not describe it as the full Dutch corpus unless " + "the paired base dataset manifest/run metadata proves full discovery coverage. " + "The paired base dataset includes article extraction diagnostics and parser coverage improvements " + "for older/French heading styles. The paired source package was quality-audited after parser-noise " + "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean " + "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with " + "`law_status`, `is_current`, validity dates, status source, confidence, and notes in graph nodes " + "and JSON-LD objects. This graph is not legal advice." + ), + ) + _write_gitattributes(out_dir) + _write_manifest( + out_dir, + KNOWLEDGE_GRAPH_DATASET_NAME, + repo_id, + {"nodes": len(graph_nodes), "edges": len(graph_edges)}, + extra=metadata, + ) + return out_dir + + +def build_vector_package(*args: Any, **kwargs: Any) -> Path: + return build_vector_index(*args, **kwargs) + + +def build_bm25_package(*args: Any, **kwargs: Any) -> Path: + return build_bm25_index(*args, **kwargs) + + +def build_knowledge_graph_package(*args: Any, **kwargs: Any) -> Path: + return build_knowledge_graph(*args, **kwargs) + + +def build_all_indexes(source_dir: Path | None = None) -> list[Path]: + corpus = load_source_rows(source_dir) + return [ + build_vector_index(corpus=corpus, source_dir=source_dir), + build_bm25_index(corpus=corpus, source_dir=source_dir), + build_knowledge_graph(corpus=corpus, source_dir=source_dir), + ] + + +def main() -> None: + built = build_all_indexes() + print(json.dumps([str(path) for path in built], indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_package.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_package.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff8ba6f6a75fad79389138cc019470ab90a115c --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_package.py @@ -0,0 +1,447 @@ +"""Build the CID-addressed Hugging Face package for Netherlands laws.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from ipfs_datasets_py.utils.cid_utils import cid_for_obj + +from .common import ( + clean_legal_text, + disambiguate_duplicate_article_identifiers, + file_manifest_entry, + read_jsonl, + stable_row_key, + write_json, + write_jsonl, + write_parquet, +) +from ..paths import ( + DEFAULT_HF_REPO_IDS, + HF_DATA_DIR, + IPFS_DATASET_NAME, + PACKAGE_RAW_OUTPUT_DIR, +) + + +DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["base"] +DEFAULT_RAW_DIR = PACKAGE_RAW_OUTPUT_DIR +DEFAULT_OUT_DIR = HF_DATA_DIR / IPFS_DATASET_NAME + + +def coverage_note(run_metadata: dict[str, Any], record_counts: dict[str, int]) -> str: + max_documents = run_metadata.get("max_documents") + parsed = ( + run_metadata.get("output_records_count") + or run_metadata.get("documents_parsed") + or record_counts.get("laws", 0) + ) + discovered = ( + run_metadata.get("total_unique_laws_discovered") + or run_metadata.get("unique_laws_discovered") + or "unknown" + ) + failed = run_metadata.get("documents_failed", "unknown") + if max_documents: + return ( + f"This is a capped Netherlands scrape, not the full Dutch corpus. " + f"The scrape used max_documents={max_documents}, parsed {parsed} law record(s), " + f"and discovered {discovered} unique official BWBR law document(s) before applying the cap. " + f"Documents failed: {failed}." + ) + return ( + "This is an uncapped discovered-corpus Netherlands scrape from the configured official discovery sources, " + "but it should not be described as the full Dutch corpus unless the run metadata confirms discovery covered " + f"the complete intended BWBR population. Parsed law records: {parsed}; discovered: {discovered}; " + f"documents failed: {failed}." + ) + + +def law_payload(row: dict[str, Any]) -> dict[str, Any]: + keep = [ + "record_type", + "jurisdiction", + "jurisdiction_name", + "country", + "language", + "identifier", + "law_identifier", + "official_identifier", + "law_version_identifier", + "version_specific_identifier", + "title", + "canonical_title", + "aliases", + "text", + "source_url", + "canonical_law_url", + "canonical_document_url", + "versioned_law_url", + "information_url", + "document_type", + "citation", + "official_metadata", + "law_status", + "is_current", + "valid_from", + "valid_to", + "effective_date", + "retrieved_at", + "status_source", + "status_confidence", + "status_note", + "version_start_date", + "version_end_date", + "publication_date", + "last_modified_date", + "historical_versions", + "article_count", + "article_rows_count", + "article_extraction_status", + "article_extraction_note", + "article_extraction_diagnostics", + "chapter_count", + "scraped_at", + "metadata", + ] + payload = {key: row.get(key) for key in keep} + payload["text"] = clean_legal_text(payload.get("text")) + return payload + + +def article_payload(row: dict[str, Any]) -> dict[str, Any]: + keep = [ + "record_type", + "law_identifier", + "law_version_identifier", + "version_specific_identifier", + "document_identifier", + "document_version_identifier", + "article_identifier", + "article_number", + "article_heading", + "citation", + "document_citation", + "hierarchy_path", + "hierarchy_path_text", + "hierarchy_labels", + "book_label", + "title_label", + "chapter_label", + "division_label", + "paragraph_label", + "article_label", + "book_number", + "title_number", + "chapter_number", + "division_number", + "paragraph_number", + "text", + "law_status", + "is_current", + "valid_from", + "valid_to", + "effective_date", + "retrieved_at", + "status_source", + "status_confidence", + "status_note", + "version_start_date", + "version_end_date", + "scraped_at", + ] + payload = {key: row.get(key) for key in keep} + payload["text"] = clean_legal_text(payload.get("text")) + return payload + + +def build_rows( + raw_dir: Path | None = None, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: + raw_dir = raw_dir or DEFAULT_RAW_DIR + raw_laws = read_jsonl(raw_dir / "netherlands_laws_index_latest.jsonl") + raw_articles = read_jsonl(raw_dir / "netherlands_laws_articles_index_latest.jsonl") + + laws: list[dict[str, Any]] = [] + law_cid_by_id: dict[str, str] = {} + cid_index: list[dict[str, Any]] = [] + for raw_row in raw_laws: + payload = law_payload(raw_row) + cid = cid_for_obj(payload) + payload["cid"] = cid + payload["content_address"] = f"ipfs://{cid}" + laws.append(payload) + law_id = str(payload.get("law_identifier") or payload.get("identifier") or "") + law_cid_by_id[law_id] = cid + cid_index.append( + { + "record_type": "law", + "law_identifier": law_id, + "article_identifier": None, + "cid": cid, + "content_address": f"ipfs://{cid}", + "source_url": payload.get("source_url"), + "title": payload.get("title"), + "law_status": payload.get("law_status"), + "is_current": payload.get("is_current"), + "valid_from": payload.get("valid_from"), + "valid_to": payload.get("valid_to"), + "effective_date": payload.get("effective_date"), + "retrieved_at": payload.get("retrieved_at"), + "status_source": payload.get("status_source"), + "status_confidence": payload.get("status_confidence"), + } + ) + + article_payloads = [article_payload(raw_row) for raw_row in raw_articles] + disambiguate_duplicate_article_identifiers(article_payloads) + + articles: list[dict[str, Any]] = [] + seen_article_payloads: set[str] = set() + for payload in article_payloads: + payload["law_cid"] = law_cid_by_id.get(str(payload.get("law_identifier") or ""), "") + dedupe_key = stable_row_key(payload) + if dedupe_key in seen_article_payloads: + continue + seen_article_payloads.add(dedupe_key) + cid = cid_for_obj(payload) + payload["cid"] = cid + payload["content_address"] = f"ipfs://{cid}" + articles.append(payload) + cid_index.append( + { + "record_type": "article", + "law_identifier": payload.get("law_identifier"), + "article_identifier": payload.get("article_identifier"), + "cid": cid, + "content_address": f"ipfs://{cid}", + "source_url": None, + "title": payload.get("citation"), + "law_status": payload.get("law_status"), + "is_current": payload.get("is_current"), + "valid_from": payload.get("valid_from"), + "valid_to": payload.get("valid_to"), + "effective_date": payload.get("effective_date"), + "retrieved_at": payload.get("retrieved_at"), + "status_source": payload.get("status_source"), + "status_confidence": payload.get("status_confidence"), + } + ) + return laws, articles, cid_index + + +def write_readme( + out_dir: Path, + repo_id: str = DEFAULT_REPO_ID, + *, + run_metadata: dict[str, Any] | None = None, + record_counts: dict[str, int] | None = None, +) -> None: + run_metadata = run_metadata or {} + record_counts = record_counts or {} + scrape_command = run_metadata.get("scrape_command") or ( + "python -m ipfs_datasets_py.processors.legal_scrapers.netherlands_laws scrape " + "--use_default_seeds true --max_seed_pages --crawl_depth 1 " + "--max_documents --rate_limit_delay --resume" + ) + coverage = coverage_note(run_metadata, record_counts) + scrape_date = str(run_metadata.get("scraped_at") or "unknown") + scope_note = str(run_metadata.get("corpus_scope_note") or "") + full_bwb = run_metadata.get("full_bwb_discovery") or {} + catalog_counts = run_metadata.get("catalog_coverage_counts") or {} + catalog_note = "" + if run_metadata.get("catalog_backed_run"): + catalog_note = ( + f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). " + f"Catalog coverage after this run: {catalog_counts.get('complete', 'unknown')} complete of " + f"{catalog_counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) " + f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: " + f"{catalog_counts.get('remaining', 'unknown')}. Integrity validation ok: " + f"{run_metadata.get('catalog_integrity_ok', 'unknown')}." + ) + readme = f"""--- +pretty_name: IPFS Netherlands Laws +language: +- nl +task_categories: +- text-retrieval +- question-answering +- text-classification +tags: +- law +- legal +- legislation +- netherlands +- dutch +- ipfs +- cid +license: other +configs: +- config_name: laws + data_files: + - split: train + path: parquet/laws/*.parquet +- config_name: articles + data_files: + - split: train + path: parquet/articles/*.parquet +- config_name: cid_index + data_files: + - split: train + path: parquet/cid_index/*.parquet +--- + +# IPFS Netherlands Laws + +Hugging Face target: `{repo_id}`. + +This dataset packages Netherlands law records with deterministic IPFS Content IDs. Each row includes a `cid` and `content_address`; article rows also include the parent `law_cid`. + +{coverage} + +Scrape date: {scrape_date} + +Exact corpus size in this package: {record_counts.get("laws", 0)} law records, {record_counts.get("articles", 0)} article records, and {record_counts.get("cid_index", 0)} CID index rows. + +Full BWB discovery inventory: {full_bwb.get("unique_laws_discovered", "unknown")} unique BWBR identifiers from {full_bwb.get("number_of_records_reported", "unknown")} official SRU record(s), with {full_bwb.get("failed_pages_count", "unknown")} failed discovery page(s). + +{catalog_note} + +{scope_note} + +This refresh includes parser coverage improvements for older/French heading styles such as `Article I.er`, +plus run metadata diagnostics that distinguish article-producing laws, parser-missing article cases, +and genuinely unnumbered/non-article documents. + +Quality audit note: this snapshot was rebuilt after parser-noise cleanup for official website UI chrome +such as relation, permanent-link, print, save, and wetstechnical-information controls. Duplicate article +identifiers caused by repeated article numbers in different hierarchy branches are disambiguated with +deterministic hierarchy/text-derived suffixes. The quality audit reports duplicate IDs/CIDs as zero, +clean status inheritance, clean hierarchy/citation reconstruction, and passing sampled CID/vector/BM25/KG +retrieval validation. + +Historical/former laws are preserved. Consumers should use `law_status`, `is_current`, `valid_from`, +`valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note` +to distinguish current law from historical, repealed, superseded, or unknown-status records. These fields +are part of the content-addressed payload, so CIDs change when official status/version metadata changes. +This dataset is not legal advice and does not validate legal force beyond the official metadata parsed. + +Scrape command: + +```bash +{scrape_command} +``` + +Current package counts: + +- Laws: {record_counts.get("laws", 0)} +- Articles: {record_counts.get("articles", 0)} +- CID index rows: {record_counts.get("cid_index", 0)} +- Unique laws discovered before any document cap: {run_metadata.get("unique_laws_discovered", "unknown")} +- Documents failed: {run_metadata.get("documents_failed", "unknown")} +- Article-producing laws: {run_metadata.get("article_producing_laws_count", "unknown")} +- Non-article-producing laws: {run_metadata.get("non_article_producing_laws_count", "unknown")} +- Current laws: {run_metadata.get("current_laws_count", "unknown")} +- Historical/repealed/superseded laws: {run_metadata.get("historical_repealed_superseded_laws_count", "unknown")} +- Unknown-status laws: {run_metadata.get("unknown_status_laws_count", "unknown")} +- Ambiguous-status laws: {run_metadata.get("ambiguous_status_laws_count", "unknown")} + +Remaining limitations: this package should only be described as the full Dutch corpus when the run metadata shows uncapped official discovery and every discovered official BWBR document was parsed or explicitly logged as failed/skipped. Otherwise it is a verified shard or discovered-corpus subset. +""" + (out_dir / "README.md").write_text(readme, encoding="utf-8") + + +def write_gitattributes(out_dir: Path) -> None: + (out_dir / ".gitattributes").write_text( + "data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text\n" + "data/**/*.json filter=lfs diff=lfs merge=lfs -text\n" + "parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text\n", + encoding="utf-8", + ) + + +def build_manifest( + laws: list[dict[str, Any]], + articles: list[dict[str, Any]], + cid_index: list[dict[str, Any]], + out_dir: Path, + repo_id: str = DEFAULT_REPO_ID, +) -> dict[str, Any]: + manifest: dict[str, Any] = { + "dataset_name": IPFS_DATASET_NAME, + "snapshot_date": "2026-04-11", + "repo_target": repo_id, + "upload_target": repo_id, + "jurisdiction": "Netherlands", + "language": "nl", + "cid_format": {"version": 1, "codec": "raw", "multihash": "sha2-256", "base": "base32"}, + "records": {"laws": len(laws), "articles": len(articles), "cid_index": len(cid_index)}, + "files": {}, + } + files: list[tuple[str, int | None]] = [ + ("data/laws/ipfs_netherlands_laws.jsonl", len(laws)), + ("data/articles/ipfs_netherlands_laws_articles.jsonl", len(articles)), + ("data/cid_index/ipfs_netherlands_laws_cid_index.jsonl", len(cid_index)), + ("data/metadata/netherlands_laws_run_metadata_latest.json", None), + ("parquet/laws/train-00000-of-00001.parquet", len(laws)), + ("parquet/articles/train-00000-of-00001.parquet", len(articles)), + ("parquet/cid_index/train-00000-of-00001.parquet", len(cid_index)), + ] + for rel, records in files: + manifest["files"][rel] = file_manifest_entry(out_dir / rel, records) + write_json(out_dir / "dataset_manifest.json", manifest) + return manifest + + +def build_ipfs_cid_package( + raw_dir: Path | None = None, + out_dir: Path | None = None, + repo_id: str = DEFAULT_REPO_ID, +) -> Path: + raw_dir = raw_dir or DEFAULT_RAW_DIR + out_dir = out_dir or DEFAULT_OUT_DIR + laws, articles, cid_index = build_rows(raw_dir) + run_metadata = json.loads( + (raw_dir / "netherlands_laws_run_metadata_latest.json").read_text(encoding="utf-8") + ) + + for rel in [ + "data/laws", + "data/articles", + "data/cid_index", + "data/metadata", + "parquet/laws", + "parquet/articles", + "parquet/cid_index", + ]: + (out_dir / rel).mkdir(parents=True, exist_ok=True) + + write_jsonl(out_dir / "data/laws/ipfs_netherlands_laws.jsonl", laws) + write_jsonl(out_dir / "data/articles/ipfs_netherlands_laws_articles.jsonl", articles) + write_jsonl(out_dir / "data/cid_index/ipfs_netherlands_laws_cid_index.jsonl", cid_index) + write_json(out_dir / "data/metadata/netherlands_laws_run_metadata_latest.json", run_metadata) + write_parquet(out_dir / "parquet/laws/train-00000-of-00001.parquet", laws) + write_parquet(out_dir / "parquet/articles/train-00000-of-00001.parquet", articles) + write_parquet(out_dir / "parquet/cid_index/train-00000-of-00001.parquet", cid_index) + + write_readme( + out_dir, + repo_id, + run_metadata=run_metadata, + record_counts={"laws": len(laws), "articles": len(articles), "cid_index": len(cid_index)}, + ) + write_gitattributes(out_dir) + build_manifest(laws, articles, cid_index, out_dir, repo_id) + return out_dir + + +def main() -> None: + out_dir = build_ipfs_cid_package() + manifest = json.loads((out_dir / "dataset_manifest.json").read_text(encoding="utf-8")) + print(json.dumps({"out_dir": str(out_dir), "records": manifest["records"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/normalized_package.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/normalized_package.py new file mode 100644 index 0000000000000000000000000000000000000000..cac1e32f9377dbcd3d60de305a9e8fd892d50bd7 --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/normalized_package.py @@ -0,0 +1,483 @@ +"""Build a normalized Hugging Face package for Netherlands laws.""" + +from __future__ import annotations + +import json +from collections import Counter +from pathlib import Path +from typing import Any + +from .common import ( + clean_legal_text, + count_jsonl, + disambiguate_duplicate_article_identifiers, + file_manifest_entry, + read_jsonl, + stable_row_key, + write_json, + write_jsonl, + write_parquet, +) +from ..paths import ( + DEFAULT_HF_REPO_IDS, + HF_DATA_DIR, + NORMALIZED_DATASET_NAME, + PACKAGE_RAW_OUTPUT_DIR, +) + + +DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["normalized"] +DEFAULT_RAW_DIR = PACKAGE_RAW_OUTPUT_DIR +DEFAULT_OUT_DIR = HF_DATA_DIR / NORMALIZED_DATASET_NAME + + +def coverage_note(run_metadata: dict[str, Any], record_counts: dict[str, int]) -> str: + max_documents = run_metadata.get("max_documents") + parsed = ( + run_metadata.get("output_records_count") + or run_metadata.get("documents_parsed") + or record_counts.get("laws", 0) + ) + discovered = ( + run_metadata.get("total_unique_laws_discovered") + or run_metadata.get("unique_laws_discovered") + or "unknown" + ) + failed = run_metadata.get("documents_failed", "unknown") + if max_documents: + return ( + f"This is a capped Netherlands scrape, not the full Dutch corpus. " + f"The scrape used max_documents={max_documents}, parsed {parsed} law record(s), " + f"and discovered {discovered} unique official BWBR law document(s) before applying the cap. " + f"Documents failed: {failed}." + ) + return ( + "This is an uncapped discovered-corpus Netherlands scrape from the configured official discovery sources, " + "but it should not be described as the full Dutch corpus unless the run metadata confirms discovery covered " + f"the complete intended BWBR population. Parsed law records: {parsed}; discovered: {discovered}; " + f"documents failed: {failed}." + ) + + +def measured_size(value: Any) -> int: + return len(json.dumps(value, ensure_ascii=False, separators=(",", ":"))) + + +def top_field_report(rows: list[dict[str, Any]], limit: int = 15) -> list[dict[str, Any]]: + field_sizes: Counter[str] = Counter() + nonnull: Counter[str] = Counter() + for row in rows: + for key, value in row.items(): + if value not in (None, "", [], {}): + field_sizes[key] += measured_size(value) + nonnull[key] += 1 + total = sum(field_sizes.values()) + report: list[dict[str, Any]] = [] + for key, size in sorted(field_sizes.items(), key=lambda kv: kv[1], reverse=True)[:limit]: + report.append( + { + "field": key, + "total_bytes": size, + "pct_of_measured_fields": round((100 * size / total), 2) if total else 0.0, + "nonnull_rows": nonnull[key], + "avg_bytes_when_present": round(size / nonnull[key], 1) if nonnull[key] else 0.0, + } + ) + return report + + +def normalize_laws(raw_laws: list[dict[str, Any]]) -> list[dict[str, Any]]: + keep = [ + "record_type", + "jurisdiction", + "jurisdiction_name", + "country", + "language", + "identifier", + "law_identifier", + "official_identifier", + "law_version_identifier", + "version_specific_identifier", + "title", + "canonical_title", + "aliases", + "text", + "source_url", + "canonical_law_url", + "canonical_document_url", + "versioned_law_url", + "information_url", + "document_type", + "citation", + "official_metadata", + "law_status", + "is_current", + "valid_from", + "valid_to", + "effective_date", + "retrieved_at", + "status_source", + "status_confidence", + "status_note", + "version_start_date", + "version_end_date", + "publication_date", + "last_modified_date", + "historical_versions", + "article_count", + "article_rows_count", + "article_extraction_status", + "article_extraction_note", + "article_extraction_diagnostics", + "chapter_count", + "scraped_at", + "metadata", + ] + rows = [{key: row.get(key) for key in keep} for row in raw_laws] + for row in rows: + row["text"] = clean_legal_text(row.get("text")) + return rows + + +def normalize_articles(raw_articles: list[dict[str, Any]]) -> list[dict[str, Any]]: + keep = [ + "record_type", + "law_identifier", + "law_version_identifier", + "version_specific_identifier", + "document_identifier", + "document_version_identifier", + "article_identifier", + "article_number", + "article_heading", + "citation", + "document_citation", + "hierarchy_path", + "hierarchy_path_text", + "hierarchy_labels", + "book_label", + "title_label", + "chapter_label", + "division_label", + "paragraph_label", + "article_label", + "book_number", + "title_number", + "chapter_number", + "division_number", + "paragraph_number", + "text", + "law_status", + "is_current", + "valid_from", + "valid_to", + "effective_date", + "retrieved_at", + "status_source", + "status_confidence", + "status_note", + "version_start_date", + "version_end_date", + "scraped_at", + ] + rows: list[dict[str, Any]] = [] + for row in raw_articles: + out = {key: row.get(key) for key in keep} + out["text"] = clean_legal_text(out.get("text")) + out["law_row_id"] = row.get("law_identifier") + rows.append(out) + disambiguate_duplicate_article_identifiers(rows) + deduplicated: list[dict[str, Any]] = [] + seen: set[str] = set() + for row in rows: + key = stable_row_key(row) + if key in seen: + continue + seen.add(key) + deduplicated.append(row) + return deduplicated + + +def write_dataset_card( + out_dir: Path, + repo_id: str = DEFAULT_REPO_ID, + *, + run_metadata: dict[str, Any] | None = None, + record_counts: dict[str, int] | None = None, +) -> None: + run_metadata = run_metadata or {} + record_counts = record_counts or {} + coverage = coverage_note(run_metadata, record_counts) + scrape_command = run_metadata.get("scrape_command") or ( + "python -m ipfs_datasets_py.processors.legal_scrapers.netherlands_laws scrape " + "--use_default_seeds true --max_seed_pages --crawl_depth 1 " + "--max_documents --rate_limit_delay --resume" + ) + scrape_date = str(run_metadata.get("scraped_at") or "unknown") + scope_note = str(run_metadata.get("corpus_scope_note") or "") + full_bwb = run_metadata.get("full_bwb_discovery") or {} + catalog_counts = run_metadata.get("catalog_coverage_counts") or {} + catalog_note = "" + if run_metadata.get("catalog_backed_run"): + catalog_note = ( + f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). " + f"Catalog coverage after this run: {catalog_counts.get('complete', 'unknown')} complete of " + f"{catalog_counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) " + f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: " + f"{catalog_counts.get('remaining', 'unknown')}. Integrity validation ok: " + f"{run_metadata.get('catalog_integrity_ok', 'unknown')}." + ) + readme = f"""--- +pretty_name: Netherlands Laws (Dutch, Normalized) +language: +- nl +task_categories: +- text-retrieval +- question-answering +- text-classification +tags: +- law +- legal +- legislation +- netherlands +- dutch +license: other +configs: +- config_name: laws + data_files: + - split: train + path: parquet/laws/*.parquet +- config_name: articles + data_files: + - split: train + path: parquet/articles/*.parquet +--- + +# Netherlands Laws (Dutch, Normalized) + +Hugging Face target: `{repo_id}`. + +This package is a normalized version of the Netherlands laws scrape output. + +{coverage} + +Scrape date: {scrape_date} + +Exact corpus size in this package: {record_counts.get("laws", 0)} law records and {record_counts.get("articles", 0)} article records. + +Full BWB discovery inventory: {full_bwb.get("unique_laws_discovered", "unknown")} unique BWBR identifiers from {full_bwb.get("number_of_records_reported", "unknown")} official SRU record(s), with {full_bwb.get("failed_pages_count", "unknown")} failed discovery page(s). + +{catalog_note} + +{scope_note} + +This refresh includes parser coverage improvements for older/French heading styles such as `Article I.er`, +plus run metadata diagnostics that distinguish article-producing laws, parser-missing article cases, +and genuinely unnumbered/non-article documents. + +Historical/former laws are preserved. Consumers should use `law_status`, `is_current`, `valid_from`, +`valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note` +to distinguish current law from historical, repealed, superseded, or unknown-status records. These fields +are parsed only from official Dutch government metadata/pages; `unknown` means the scraper did not find +enough official metadata to classify the status. + +This dataset is not legal advice and does not validate legal force beyond the official metadata parsed. + +Scrape command: + +```bash +{scrape_command} +``` + +Current package counts: + +- Laws: {record_counts.get("laws", 0)} +- Articles: {record_counts.get("articles", 0)} +- Search records in raw run: {run_metadata.get("search_records_count", "unknown")} +- Unique laws discovered before any document cap: {run_metadata.get("unique_laws_discovered", "unknown")} +- Documents failed: {run_metadata.get("documents_failed", "unknown")} +- Article-producing laws: {run_metadata.get("article_producing_laws_count", "unknown")} +- Non-article-producing laws: {run_metadata.get("non_article_producing_laws_count", "unknown")} +- Current laws: {run_metadata.get("current_laws_count", "unknown")} +- Historical/repealed/superseded laws: {run_metadata.get("historical_repealed_superseded_laws_count", "unknown")} +- Unknown-status laws: {run_metadata.get("unknown_status_laws_count", "unknown")} +- Ambiguous-status laws: {run_metadata.get("ambiguous_status_laws_count", "unknown")} + +Remaining limitations: this package should only be described as the full Dutch corpus when the run metadata shows uncapped official discovery and every discovered official BWBR document was parsed or explicitly logged as failed/skipped. Otherwise it is a verified shard or discovered-corpus subset. +""" + (out_dir / "README.md").write_text(readme, encoding="utf-8") + + +def write_gitattributes(out_dir: Path) -> None: + text = """data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text +data/**/*.json filter=lfs diff=lfs merge=lfs -text +parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text +analysis/**/*.json filter=lfs diff=lfs merge=lfs -text +""" + (out_dir / ".gitattributes").write_text(text, encoding="utf-8") + + +def write_upload_script(out_dir: Path) -> None: + text = """#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -lt 1 ]]; then + echo "Usage: $0 " + exit 1 +fi + +REPO_ID="$1" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +cat < Path: + raw_dir = raw_dir or DEFAULT_RAW_DIR + out_dir = out_dir or DEFAULT_OUT_DIR + raw_laws = read_jsonl(raw_dir / "netherlands_laws_index_latest.jsonl") + raw_articles = read_jsonl(raw_dir / "netherlands_laws_articles_index_latest.jsonl") + raw_search_rows = count_jsonl(raw_dir / "netherlands_laws_search_index_latest.jsonl") + run_metadata = json.loads( + (raw_dir / "netherlands_laws_run_metadata_latest.json").read_text(encoding="utf-8") + ) + + laws = normalize_laws(raw_laws) + articles = normalize_articles(raw_articles) + + (out_dir / "data" / "laws").mkdir(parents=True, exist_ok=True) + (out_dir / "data" / "articles").mkdir(parents=True, exist_ok=True) + (out_dir / "data" / "metadata").mkdir(parents=True, exist_ok=True) + (out_dir / "analysis").mkdir(parents=True, exist_ok=True) + (out_dir / "parquet" / "laws").mkdir(parents=True, exist_ok=True) + (out_dir / "parquet" / "articles").mkdir(parents=True, exist_ok=True) + + laws_jsonl = out_dir / "data" / "laws" / "netherlands_laws_normalized.jsonl" + articles_jsonl = out_dir / "data" / "articles" / "netherlands_laws_articles_normalized.jsonl" + + write_jsonl(laws_jsonl, laws) + write_jsonl(articles_jsonl, articles) + write_parquet(out_dir / "parquet" / "laws" / "train-00000-of-00001.parquet", laws) + write_parquet(out_dir / "parquet" / "articles" / "train-00000-of-00001.parquet", articles) + + raw_article_bytes = (raw_dir / "netherlands_laws_articles_index_latest.jsonl").stat().st_size + normalized_article_bytes = articles_jsonl.stat().st_size + report = { + "raw": { + "laws_rows": len(raw_laws), + "articles_rows": len(raw_articles), + "search_rows": raw_search_rows, + "article_jsonl_bytes": raw_article_bytes, + "article_top_fields": top_field_report(raw_articles), + }, + "normalized": { + "laws_rows": len(laws), + "articles_rows": len(articles), + "article_jsonl_bytes": normalized_article_bytes, + "article_reduction_bytes": raw_article_bytes - normalized_article_bytes, + "article_reduction_pct": round( + 100 * (raw_article_bytes - normalized_article_bytes) / raw_article_bytes, 2 + ) + if raw_article_bytes + else 0.0, + }, + "scrape_trace": { + "max_documents": run_metadata.get("max_documents"), + "seed_url_count": run_metadata.get("seed_url_count"), + "seed_pages_visited": run_metadata.get("seed_pages_visited"), + "explicit_document_urls": run_metadata.get("explicit_document_urls"), + "official_law_documents_accepted": run_metadata.get("official_law_documents_accepted"), + "documents_parsed": run_metadata.get("documents_parsed"), + "records_count": run_metadata.get("records_count"), + "article_records_count": run_metadata.get("article_records_count"), + "search_records_count": run_metadata.get("search_records_count"), + "law_status_counts": run_metadata.get("law_status_counts"), + "current_laws_count": run_metadata.get("current_laws_count"), + "historical_repealed_superseded_laws_count": run_metadata.get( + "historical_repealed_superseded_laws_count" + ), + "unknown_status_laws_count": run_metadata.get("unknown_status_laws_count"), + "ambiguous_status_laws_count": run_metadata.get("ambiguous_status_laws_count"), + }, + } + + write_json(out_dir / "analysis" / "size_inflation_report.json", report) + write_json( + out_dir / "data" / "metadata" / "netherlands_laws_run_metadata_latest.json", run_metadata + ) + + manifest = { + "dataset_name": NORMALIZED_DATASET_NAME, + "snapshot_date": "2026-04-11", + "package_variant": "normalized", + "source_directory": str(raw_dir), + "source_url": "https://wetten.overheid.nl/", + "repo_target": repo_id, + "upload_target": repo_id, + "language": "nl", + "jurisdiction": "Netherlands", + "join_key": {"articles": "law_identifier", "laws": "law_identifier"}, + "records": {"laws": len(laws), "articles": len(articles)}, + "notes": [ + "Law-level metadata is stored in the laws table.", + "Repeated law-level fields were removed from article rows.", + "Historical/former laws are preserved and labeled; they are not filtered out.", + "This dataset is not legal advice and does not validate legal force beyond parsed official metadata.", + ], + "files": {}, + } + for rel in [ + "data/laws/netherlands_laws_normalized.jsonl", + "data/articles/netherlands_laws_articles_normalized.jsonl", + "data/metadata/netherlands_laws_run_metadata_latest.json", + "analysis/size_inflation_report.json", + "parquet/laws/train-00000-of-00001.parquet", + "parquet/articles/train-00000-of-00001.parquet", + ]: + path = out_dir / rel + records: int | None = None + if rel.startswith("data/laws") or rel.startswith("parquet/laws"): + records = len(laws) + elif rel.startswith("data/articles") or rel.startswith("parquet/articles"): + records = len(articles) + manifest["files"][rel] = file_manifest_entry(path, records) + write_json(out_dir / "dataset_manifest.json", manifest) + + write_dataset_card( + out_dir, + repo_id, + run_metadata=run_metadata, + record_counts={"laws": len(laws), "articles": len(articles)}, + ) + write_gitattributes(out_dir) + write_upload_script(out_dir) + return out_dir + + +def main() -> None: + out_dir = build_normalized_package() + report = json.loads( + (out_dir / "analysis" / "size_inflation_report.json").read_text(encoding="utf-8") + ) + print(json.dumps(report, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/unified_package.py b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/unified_package.py new file mode 100644 index 0000000000000000000000000000000000000000..24454076f6f6b9a7cce789fb779f0b2c930bb71d --- /dev/null +++ b/scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/unified_package.py @@ -0,0 +1,824 @@ +"""Build the unified WetWijzer Netherlands legal corpus bundle.""" + +from __future__ import annotations + +import json +import re +import shutil +import tempfile +from collections import defaultdict +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pyarrow.parquet as pq + +from ipfs_datasets_py.utils.cid_utils import cid_for_obj + +from .common import file_manifest_entry, write_json, write_jsonl, write_parquet +from ..paths import ( + BM25_INDEX_DATASET_NAME, + DEFAULT_HF_REPO_IDS, + DATASETS_DIR, + HF_DATA_DIR, + IPFS_DATASET_NAME, + KNOWLEDGE_GRAPH_DATASET_NAME, + OPERATIONS_DATA_DIR, + UNIFIED_WETWIJZER_DATASET_NAME, + VECTOR_INDEX_DATASET_NAME, +) + + +DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["unified"] +DEFAULT_BASE_DIR = HF_DATA_DIR / IPFS_DATASET_NAME +DEFAULT_VECTOR_DIR = HF_DATA_DIR / VECTOR_INDEX_DATASET_NAME +DEFAULT_BM25_DIR = HF_DATA_DIR / BM25_INDEX_DATASET_NAME +DEFAULT_KG_DIR = HF_DATA_DIR / KNOWLEDGE_GRAPH_DATASET_NAME +DEFAULT_REPORTS_DIR = OPERATIONS_DATA_DIR +DEFAULT_OUT_DIR = HF_DATA_DIR / UNIFIED_WETWIJZER_DATASET_NAME +DATASET_VIEWER_ROW_GROUP_SIZE = 10_000 + +ARTICLE_REFERENCE_RE = re.compile(r"\b(?:Artikel|Article)\s+([0-9]+[a-zA-Z]?)\b") + + +def build_unified_wetwijzer_package( + *, + base_dir: Path | None = None, + vector_dir: Path | None = None, + bm25_dir: Path | None = None, + kg_dir: Path | None = None, + reports_dir: Path | None = None, + out_dir: Path | None = None, + repo_id: str = DEFAULT_REPO_ID, + include_relationship_summaries: bool = True, +) -> Path: + """Create a single HF-ready bundle from the existing quality-audited outputs.""" + + base_dir = base_dir or DEFAULT_BASE_DIR + vector_dir = vector_dir or DEFAULT_VECTOR_DIR + bm25_dir = bm25_dir or DEFAULT_BM25_DIR + kg_dir = kg_dir or DEFAULT_KG_DIR + reports_dir = reports_dir or DEFAULT_REPORTS_DIR + out_dir = out_dir or DEFAULT_OUT_DIR + + _reset_output_dir(out_dir) + + copied = _copy_package_layers( + out_dir=out_dir, + base_dir=base_dir, + vector_dir=vector_dir, + bm25_dir=bm25_dir, + kg_dir=kg_dir, + reports_dir=reports_dir, + ) + if include_relationship_summaries: + _write_logic_relationship_summaries(out_dir) + + _write_source_manifests(out_dir, base_dir, vector_dir, bm25_dir, kg_dir) + manifest = _write_unified_manifest(out_dir, repo_id, copied) + _write_readme(out_dir, repo_id, manifest) + _write_gitattributes(out_dir) + return out_dir + + +def _reset_output_dir(out_dir: Path) -> None: + _ensure_safe_output_dir(out_dir) + if out_dir.exists(): + shutil.rmtree(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + +def _ensure_safe_output_dir(out_dir: Path) -> None: + resolved = out_dir.resolve() + safe_roots = [DATASETS_DIR.resolve(), Path(tempfile.gettempdir()).resolve()] + if resolved in safe_roots or not any(resolved.is_relative_to(root) for root in safe_roots): + roots = ", ".join(str(root) for root in safe_roots) + raise ValueError( + f"Refusing to reset unsafe unified package output directory: {resolved}. " + f"Use a child directory under one of: {roots}" + ) + + +def _copy_package_layers( + *, + out_dir: Path, + base_dir: Path, + vector_dir: Path, + bm25_dir: Path, + kg_dir: Path, + reports_dir: Path, +) -> dict[str, str]: + copies = { + "data/laws.parquet": base_dir / "parquet/laws/train-00000-of-00001.parquet", + "data/articles.parquet": base_dir / "parquet/articles/train-00000-of-00001.parquet", + "data/cid_index.parquet": base_dir / "parquet/cid_index/train-00000-of-00001.parquet", + "indexes/vector/vector_mapping.parquet": vector_dir + / "parquet/mapping/train-00000-of-00001.parquet", + "indexes/vector/faiss.index": vector_dir / "artifacts/faiss.index", + "indexes/vector/vectorizer.pkl": vector_dir / "artifacts/vectorizer.pkl", + "indexes/vector/svd.pkl": vector_dir / "artifacts/svd.pkl", + "indexes/vector/metadata.json": vector_dir / "artifacts/metadata.json", + "indexes/bm25/bm25_documents.parquet": bm25_dir + / "parquet/documents/train-00000-of-00001.parquet", + "indexes/bm25/bm25_terms.parquet": bm25_dir / "parquet/terms/train-00000-of-00001.parquet", + "indexes/bm25/metadata.json": bm25_dir / "artifacts/metadata.json", + "graph/kg_nodes.parquet": kg_dir / "parquet/nodes/train-00000-of-00001.parquet", + "graph/kg_edges.parquet": kg_dir / "parquet/edges/train-00000-of-00001.parquet", + "graph/graph.jsonld": kg_dir / "data/graph/ipfs_netherlands_laws_kg.jsonld", + "graph/metadata.json": kg_dir / "artifacts/metadata.json", + "reports/run_metadata.json": base_dir + / "data/metadata/netherlands_laws_run_metadata_latest.json", + } + + report_paths = _select_reports(reports_dir) + copies.update(report_paths) + + copied: dict[str, str] = {} + for rel, source in copies.items(): + if not source.exists(): + raise FileNotFoundError( + f"Cannot build unified package; missing source file for {rel}: {source}" + ) + destination = out_dir / rel + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + copied[rel] = str(source) + _rewrite_viewer_friendly_parquet(out_dir / "indexes/bm25/bm25_terms.parquet") + return copied + + +def _rewrite_viewer_friendly_parquet(path: Path) -> None: + """Rewrite large copied parquet files with row groups small enough for Dataset Viewer.""" + + table = pq.read_table(path) + pq.write_table( + table, + path, + compression="zstd", + row_group_size=DATASET_VIEWER_ROW_GROUP_SIZE, + write_page_index=True, + ) + + +def _select_reports(reports_dir: Path) -> dict[str, Path]: + quality_dir = reports_dir / "quality_audit" + return { + "reports/coverage_report.json": _first_existing_or_latest( + reports_dir, + [ + "coverage_report_quality_audit_after_verify_*.json", + "coverage_report_catalog_batch_5000_after_verify_*.json", + "coverage_report_latest.json", + "coverage_report*.json", + ], + ), + "reports/integrity_report.json": _first_existing_or_latest( + reports_dir, + [ + "integrity_report_quality_audit_final_*.json", + "integrity_report_catalog_batch_5000_after_verify_*.json", + "integrity_report*.json", + ], + ), + "reports/quality_report.json": quality_dir / "quality_report.json", + "reports/duplicate_report.json": quality_dir / "duplicate_report.json", + "reports/parser_noise_report.json": quality_dir / "parser_noise_report.json", + "reports/hierarchy_report.json": quality_dir / "hierarchy_report.json", + "reports/retrieval_validation_report.json": quality_dir + / "retrieval_validation_report.json", + } + + +def _first_existing_or_latest(directory: Path, patterns: list[str]) -> Path: + for pattern in patterns: + matches = sorted( + directory.glob(pattern), key=lambda path: path.stat().st_mtime, reverse=True + ) + if matches: + return matches[0] + raise FileNotFoundError(f"No report matched any of {patterns} in {directory}") + + +def _write_source_manifests( + out_dir: Path, base_dir: Path, vector_dir: Path, bm25_dir: Path, kg_dir: Path +) -> None: + sources = { + "ipfs_netherlands_laws_manifest.json": base_dir / "dataset_manifest.json", + "ipfs_netherlands_laws_vector_index_manifest.json": vector_dir / "dataset_manifest.json", + "ipfs_netherlands_laws_bm25_index_manifest.json": bm25_dir / "dataset_manifest.json", + "ipfs_netherlands_laws_knowledge_graph_manifest.json": kg_dir / "dataset_manifest.json", + } + for filename, source in sources.items(): + if not source.exists(): + raise FileNotFoundError(f"Missing source manifest: {source}") + destination = out_dir / "manifests" / filename + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + + +def _write_logic_relationship_summaries(out_dir: Path) -> list[dict[str, Any]]: + articles_path = out_dir / "data/articles.parquet" + laws_path = out_dir / "data/laws.parquet" + + law_rows = _read_parquet_rows( + laws_path, + ["cid", "law_identifier", "title", "citation", "source_url", "law_status", "is_current"], + ) + law_by_id = {str(row.get("law_identifier") or ""): row for row in law_rows} + + article_rows = _read_parquet_rows( + articles_path, + [ + "cid", + "law_cid", + "law_identifier", + "article_identifier", + "article_number", + "citation", + "document_citation", + "text", + "law_status", + "is_current", + "valid_from", + "valid_to", + "source_url", + ], + ) + + by_law: dict[str, list[dict[str, Any]]] = defaultdict(list) + article_by_number: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) + for row in article_rows: + law_identifier = str(row.get("law_identifier") or "") + by_law[law_identifier].append(row) + article_number = _normalize_article_number(row.get("article_number")) + if article_number and article_number not in article_by_number[law_identifier]: + article_by_number[law_identifier][article_number] = row + + relationships: list[dict[str, Any]] = [] + seen: set[tuple[str, str, str]] = set() + + for law_identifier, articles in by_law.items(): + law = law_by_id.get(law_identifier) or {} + law_cid = str(law.get("cid") or articles[0].get("law_cid") or "") + for index, article in enumerate(articles): + _append_relationship( + relationships, + seen, + relationship_type="parent_law", + source=article, + target_cid=law_cid, + target_record_type="law", + target_label=str(law.get("title") or law.get("citation") or law_identifier), + target_identifier=law_identifier, + note="Parent law relationship derived from article law_cid.", + ) + if index > 0: + previous = articles[index - 1] + _append_relationship( + relationships, + seen, + relationship_type="previous_article", + source=article, + target_cid=str(previous.get("cid") or ""), + target_record_type="article", + target_label=str( + previous.get("citation") or previous.get("article_identifier") or "" + ), + target_identifier=str(previous.get("article_identifier") or ""), + note="Previous article relationship derived from source article ordering within the same law.", + ) + if index + 1 < len(articles): + following = articles[index + 1] + _append_relationship( + relationships, + seen, + relationship_type="next_article", + source=article, + target_cid=str(following.get("cid") or ""), + target_record_type="article", + target_label=str( + following.get("citation") or following.get("article_identifier") or "" + ), + target_identifier=str(following.get("article_identifier") or ""), + note="Next article relationship derived from source article ordering within the same law.", + ) + + for target in _referenced_article_targets(article, article_by_number[law_identifier]): + _append_relationship( + relationships, + seen, + relationship_type="referenced_article_candidate", + source=article, + target_cid=str(target.get("cid") or ""), + target_record_type="article", + target_label=str( + target.get("citation") or target.get("article_identifier") or "" + ), + target_identifier=str(target.get("article_identifier") or ""), + confidence="low", + note="Candidate same-law article reference derived from article text mention.", + ) + + write_parquet(out_dir / "logic/logic_relationships.parquet", relationships) + write_jsonl(out_dir / "logic/logic_relationships.jsonl", relationships) + return relationships + + +def _read_parquet_rows(path: Path, columns: list[str]) -> list[dict[str, Any]]: + parquet = pq.ParquetFile(path) + available = [column for column in columns if column in parquet.schema_arrow.names] + if not available: + return [] + return parquet.read(columns=available).to_pylist() + + +def _normalize_article_number(value: Any) -> str: + return str(value or "").strip().lower().rstrip(".") + + +def _referenced_article_targets( + source: dict[str, Any], + article_by_number: dict[str, dict[str, Any]], + *, + limit: int = 20, +) -> list[dict[str, Any]]: + text = str(source.get("text") or "") + if not text: + return [] + source_cid = str(source.get("cid") or "") + targets: list[dict[str, Any]] = [] + seen: set[str] = set() + for match in ARTICLE_REFERENCE_RE.finditer(text): + target = article_by_number.get(_normalize_article_number(match.group(1))) + target_cid = str((target or {}).get("cid") or "") + if not target or not target_cid or target_cid == source_cid or target_cid in seen: + continue + seen.add(target_cid) + targets.append(target) + if len(targets) >= limit: + break + return targets + + +def _append_relationship( + rows: list[dict[str, Any]], + seen: set[tuple[str, str, str]], + *, + relationship_type: str, + source: dict[str, Any], + target_cid: str, + target_record_type: str, + target_label: str, + target_identifier: str, + confidence: str = "high", + note: str, +) -> None: + source_cid = str(source.get("cid") or "") + target_cid = str(target_cid or "") + if not source_cid or not target_cid: + return + key = (relationship_type, source_cid, target_cid) + if key in seen: + return + seen.add(key) + row = { + "relationship_type": relationship_type, + "source_cid": source_cid, + "target_cid": target_cid, + "source_record_type": "article", + "target_record_type": target_record_type, + "law_cid": source.get("law_cid"), + "law_identifier": source.get("law_identifier"), + "source_identifier": source.get("article_identifier"), + "target_identifier": target_identifier, + "source_label": source.get("citation") or source.get("article_identifier"), + "target_label": target_label, + "source_law_status": source.get("law_status"), + "source_is_current": source.get("is_current"), + "source_valid_from": source.get("valid_from"), + "source_valid_to": source.get("valid_to"), + "source_url": source.get("source_url"), + "status": "derived", + "confidence": confidence, + "derivation_note": note, + } + row["relationship_cid"] = cid_for_obj(row) + rows.append(row) + + +def _write_unified_manifest( + out_dir: Path, repo_id: str, copied_sources: dict[str, str] +) -> dict[str, Any]: + records = _record_counts(out_dir) + source_manifests = _load_source_manifests(out_dir) + coverage = _read_json(out_dir / "reports/coverage_report.json") + quality = _read_json(out_dir / "reports/quality_report.json") + integrity = _read_json(out_dir / "reports/integrity_report.json") + run_metadata = _read_json(out_dir / "reports/run_metadata.json") + + manifest: dict[str, Any] = { + "dataset_name": UNIFIED_WETWIJZER_DATASET_NAME, + "repo_target": repo_id, + "upload_target": repo_id, + "jurisdiction": "Netherlands", + "language": "nl", + "build_date": datetime.now(UTC).isoformat(), + "source_repos": { + "base": DEFAULT_HF_REPO_IDS["base"], + "vector": DEFAULT_HF_REPO_IDS["vector"], + "bm25": DEFAULT_HF_REPO_IDS["bm25"], + "knowledge_graph": DEFAULT_HF_REPO_IDS["knowledge-graph"], + }, + "records": records, + "coverage": { + "counts": coverage.get("counts"), + "percent_complete": coverage.get("percent_complete"), + "completion_semantics": coverage.get("completion_semantics"), + "law_status_counts": coverage.get("law_status_counts") + or run_metadata.get("law_status_counts"), + "article_extraction_status_counts": coverage.get("article_extraction_status_counts"), + }, + "quality_audit": { + "generated_at": quality.get("generated_at"), + "records": quality.get("records"), + "issue_summary": quality.get("issue_summary"), + "current_gate_pass": (quality.get("quality_gate_recommendation") or {}).get( + "current_gate_pass" + ), + }, + "integrity": { + "generated_at": integrity.get("generated_at"), + "ok": integrity.get("ok"), + "issue_counts": integrity.get("issue_counts"), + }, + "not_full_corpus_warning": ( + "This is a quality-audited partial Dutch corpus package. Do not claim full Dutch corpus coverage " + "until every discovered BWBR identifier is parsed, intentionally skipped, or permanently failed " + "with explanation." + ), + "source_local_files": copied_sources, + "source_manifest_records": { + name: manifest_data.get("records", {}) + for name, manifest_data in source_manifests.items() + }, + "sample_cids": _sample_cids(out_dir), + "files": {}, + } + + for path in sorted( + p for p in out_dir.rglob("*") if p.is_file() and p.name != "dataset_manifest.json" + ): + rel = path.relative_to(out_dir).as_posix() + manifest["files"][rel] = file_manifest_entry(path, _records_for_file(rel, records)) + + write_json(out_dir / "dataset_manifest.json", manifest) + return manifest + + +def _record_counts(out_dir: Path) -> dict[str, int]: + counts = { + "laws": _parquet_count(out_dir / "data/laws.parquet"), + "articles": _parquet_count(out_dir / "data/articles.parquet"), + "cid_index": _parquet_count(out_dir / "data/cid_index.parquet"), + "vector_index": _parquet_count(out_dir / "indexes/vector/vector_mapping.parquet"), + "bm25_documents": _parquet_count(out_dir / "indexes/bm25/bm25_documents.parquet"), + "bm25_terms": _parquet_count(out_dir / "indexes/bm25/bm25_terms.parquet"), + "knowledge_graph_nodes": _parquet_count(out_dir / "graph/kg_nodes.parquet"), + "knowledge_graph_edges": _parquet_count(out_dir / "graph/kg_edges.parquet"), + } + logic_path = out_dir / "logic/logic_relationships.parquet" + if logic_path.exists(): + counts["logic_relationships"] = _parquet_count(logic_path) + return counts + + +def _parquet_count(path: Path) -> int: + return int(pq.ParquetFile(path).metadata.num_rows) + + +def _records_for_file(rel: str, records: dict[str, int]) -> int | None: + mapping = { + "data/laws.parquet": "laws", + "data/articles.parquet": "articles", + "data/cid_index.parquet": "cid_index", + "indexes/vector/vector_mapping.parquet": "vector_index", + "indexes/bm25/bm25_documents.parquet": "bm25_documents", + "indexes/bm25/bm25_terms.parquet": "bm25_terms", + "graph/kg_nodes.parquet": "knowledge_graph_nodes", + "graph/kg_edges.parquet": "knowledge_graph_edges", + "logic/logic_relationships.parquet": "logic_relationships", + "logic/logic_relationships.jsonl": "logic_relationships", + } + key = mapping.get(rel) + return records.get(key) if key else None + + +def _load_source_manifests(out_dir: Path) -> dict[str, dict[str, Any]]: + manifests: dict[str, dict[str, Any]] = {} + for path in sorted((out_dir / "manifests").glob("*.json")): + manifests[path.stem] = _read_json(path) + return manifests + + +def _read_json(path: Path) -> dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) + + +def _sample_cids(out_dir: Path) -> dict[str, str | None]: + samples: dict[str, str | None] = {} + for name, path, column in [ + ("law", out_dir / "data/laws.parquet", "cid"), + ("article", out_dir / "data/articles.parquet", "cid"), + ("cid_index", out_dir / "data/cid_index.parquet", "cid"), + ("vector", out_dir / "indexes/vector/vector_mapping.parquet", "source_cid"), + ("bm25_document", out_dir / "indexes/bm25/bm25_documents.parquet", "source_cid"), + ("knowledge_graph_node", out_dir / "graph/kg_nodes.parquet", "cid"), + ("knowledge_graph_edge_source", out_dir / "graph/kg_edges.parquet", "source_cid"), + ("logic_relationship_source", out_dir / "logic/logic_relationships.parquet", "source_cid"), + ]: + if not path.exists(): + samples[name] = None + continue + parquet = pq.ParquetFile(path) + if parquet.metadata.num_rows == 0 or column not in parquet.schema_arrow.names: + samples[name] = None + continue + samples[name] = str(parquet.read_row_group(0, columns=[column]).column(0)[0].as_py() or "") + return samples + + +def _write_readme(out_dir: Path, repo_id: str, manifest: dict[str, Any]) -> None: + records = manifest["records"] + coverage_counts = (manifest.get("coverage") or {}).get("counts") or {} + integrity = manifest.get("integrity") or {} + quality = manifest.get("quality_audit") or {} + readme = f"""--- +pretty_name: WetWijzer Netherlands Legal Corpus +language: +- nl +task_categories: +- text-retrieval +- question-answering +- text-classification +tags: +- law +- legal +- legislation +- netherlands +- dutch +- ipfs +- cid +- bm25 +- vector-search +- knowledge-graph +license: other +configs: +- config_name: laws + data_files: + - split: train + path: data/laws.parquet +- config_name: articles + data_files: + - split: train + path: data/articles.parquet +- config_name: cid_index + data_files: + - split: train + path: data/cid_index.parquet +- config_name: vector_index + data_files: + - split: train + path: indexes/vector/vector_mapping.parquet +- config_name: bm25_documents + data_files: + - split: train + path: indexes/bm25/bm25_documents.parquet +- config_name: bm25_terms + data_files: + - split: train + path: indexes/bm25/bm25_terms.parquet +- config_name: knowledge_graph_nodes + data_files: + - split: train + path: graph/kg_nodes.parquet +- config_name: knowledge_graph_edges + data_files: + - split: train + path: graph/kg_edges.parquet +- config_name: logic_relationships + data_files: + - split: train + path: logic/logic_relationships.parquet +--- + +# WetWijzer Netherlands Legal Corpus + +Hugging Face target: `{repo_id}`. + +This unified dataset bundles the quality-audited WetWijzer Netherlands legal corpus stack in one repository for frontend retrieval. It preserves the existing compatibility repositories and does not replace or delete them. + +## Contents + +- Laws: {records.get("laws", 0):,} +- Articles: {records.get("articles", 0):,} +- CID index rows: {records.get("cid_index", 0):,} +- Vector mapping rows: {records.get("vector_index", 0):,} +- BM25 document rows: {records.get("bm25_documents", 0):,} +- BM25 term rows: {records.get("bm25_terms", 0):,} +- Knowledge graph nodes: {records.get("knowledge_graph_nodes", 0):,} +- Knowledge graph edges: {records.get("knowledge_graph_edges", 0):,} +- Logic/relationship summary rows: {records.get("logic_relationships", 0):,} + +## Layout + +- `data/laws.parquet` +- `data/articles.parquet` +- `data/cid_index.parquet` +- `indexes/vector/vector_mapping.parquet` +- `indexes/vector/faiss.index` +- `indexes/bm25/bm25_documents.parquet` +- `indexes/bm25/bm25_terms.parquet` +- `graph/kg_nodes.parquet` +- `graph/kg_edges.parquet` +- `graph/graph.jsonld` +- `logic/logic_relationships.parquet` +- `reports/*.json` +- `manifests/*.json` +- `dataset_manifest.json` + +Every retrieval layer is joinable by CID. Law rows have `cid`; article rows have `cid` and `law_cid`; vector and BM25 rows use `source_cid`; graph nodes use `cid`; graph edges and relationship summaries use `source_cid`, `target_cid`, and a relationship type. + +## Source Repositories + +- `{DEFAULT_HF_REPO_IDS["base"]}` +- `{DEFAULT_HF_REPO_IDS["vector"]}` +- `{DEFAULT_HF_REPO_IDS["bm25"]}` +- `{DEFAULT_HF_REPO_IDS["knowledge-graph"]}` + +## Coverage And Quality + +This is a quality-audited partial Dutch corpus package, not a full Dutch corpus claim. + +Completed catalog coverage: {coverage_counts.get("complete", "unknown")} of {coverage_counts.get("total_discovered_identifiers", "unknown")} discovered BWBR identifiers ({(manifest.get("coverage") or {}).get("percent_complete", "unknown")}%). Remaining identifiers: {coverage_counts.get("remaining", "unknown")}. + +Integrity validation ok: {integrity.get("ok", "unknown")}. Quality gate passed: {quality.get("current_gate_pass", "unknown")}. + +Historical and inactive laws are preserved. Use `law_status`, `is_current`, `valid_from`, `valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note` to distinguish current, historical, repealed, superseded, and unknown-status records. + +This dataset is not legal advice. Users should verify official text and legal effect on `wetten.overheid.nl`. +""" + (out_dir / "README.md").write_text(readme, encoding="utf-8") + + +def _write_gitattributes(out_dir: Path) -> None: + (out_dir / ".gitattributes").write_text( + "*.parquet filter=lfs diff=lfs merge=lfs -text\n" + "*.index filter=lfs diff=lfs merge=lfs -text\n" + "*.pkl filter=lfs diff=lfs merge=lfs -text\n" + "*.jsonld filter=lfs diff=lfs merge=lfs -text\n" + "logic/*.jsonl filter=lfs diff=lfs merge=lfs -text\n", + encoding="utf-8", + ) + + +def load_parquet_head( + path: Path, *, columns: list[str] | None = None, limit: int = 5 +) -> list[dict[str, Any]]: + """Small verification helper for local/remote downloaded Parquet files.""" + + parquet = pq.ParquetFile(path) + read_columns = columns or parquet.schema_arrow.names + if parquet.metadata.num_rows == 0: + return [] + table = parquet.read_row_group( + 0, columns=[column for column in read_columns if column in parquet.schema_arrow.names] + ) + return table.slice(0, limit).to_pylist() + + +def validate_unified_package(out_dir: Path | None = None) -> dict[str, Any]: + """Validate local unified bundle joins without downloading or scraping anything.""" + + out_dir = out_dir or DEFAULT_OUT_DIR + required = [ + "dataset_manifest.json", + "data/laws.parquet", + "data/articles.parquet", + "data/cid_index.parquet", + "indexes/vector/vector_mapping.parquet", + "indexes/bm25/bm25_documents.parquet", + "indexes/bm25/bm25_terms.parquet", + "graph/kg_nodes.parquet", + "graph/kg_edges.parquet", + "logic/logic_relationships.parquet", + ] + missing = [rel for rel in required if not (out_dir / rel).exists()] + sample = _sample_cids(out_dir) + messages = [f"Missing required file: {rel}" for rel in missing] + if "logic/logic_relationships.parquet" in missing: + messages.append( + "Relationship summaries are required for unified package validation; " + "rebuild with include_relationship_summaries=True before upload." + ) + + manifest = ( + _read_json(out_dir / "dataset_manifest.json") + if "dataset_manifest.json" not in missing + else {} + ) + article_rows = ( + [] + if "data/articles.parquet" in missing + else load_parquet_head( + out_dir / "data/articles.parquet", + columns=["cid", "law_cid"], + limit=1, + ) + ) + if not article_rows and "data/articles.parquet" not in missing: + messages.append("Required parquet has no article rows: data/articles.parquet") + + article = article_rows[0] if article_rows else {} + article_cid = article.get("cid") + law_cid = article.get("law_cid") + if article_rows and (not article_cid or not law_cid): + messages.append("Sample article row must include cid and law_cid.") + + vector_match = _parquet_contains_if_present( + out_dir, + missing, + "indexes/vector/vector_mapping.parquet", + "source_cid", + article_cid, + ) + bm25_match = _parquet_contains_if_present( + out_dir, + missing, + "indexes/bm25/bm25_documents.parquet", + "source_cid", + article_cid, + ) + node_match = _parquet_contains_if_present( + out_dir, missing, "graph/kg_nodes.parquet", "cid", article_cid + ) + edge_match = _parquet_contains_if_present( + out_dir, missing, "graph/kg_edges.parquet", "source_cid", article_cid + ) + relationship_match = _parquet_contains_if_present( + out_dir, + missing, + "logic/logic_relationships.parquet", + "source_cid", + article_cid, + ) + parent_match = _parquet_contains_if_present( + out_dir, missing, "data/laws.parquet", "cid", law_cid + ) + + checks = { + "missing_required_files": missing, + "sample_article_cid": article_cid, + "sample_parent_law_cid": law_cid, + "parent_law_found": parent_match, + "vector_row_found": vector_match, + "bm25_row_found": bm25_match, + "graph_node_found": node_match, + "graph_edge_found": edge_match, + "logic_relationship_found": relationship_match, + } + ok = not messages and all(value for key, value in checks.items() if key.endswith("_found")) + return { + "ok": ok, + "records": manifest.get("records", {}), + "sample_cids": sample, + "checks": checks, + "messages": messages, + } + + +def _parquet_contains_if_present( + out_dir: Path, missing: list[str], rel: str, column: str, value: Any +) -> bool: + if value is None or rel in missing: + return False + return _parquet_contains(out_dir / rel, column, value) + + +def _parquet_contains(path: Path, column: str, value: Any) -> bool: + parquet = pq.ParquetFile(path) + if column not in parquet.schema_arrow.names: + return False + for batch in parquet.iter_batches(columns=[column], batch_size=8192): + values = batch.column(0).to_pylist() + if value in values: + return True + return False + + +def main() -> None: + out_dir = build_unified_wetwijzer_package() + print(json.dumps({"out_dir": str(out_dir), **validate_unified_package(out_dir)}, indent=2)) + + +if __name__ == "__main__": + main()