Add scrapers_and_normalizers overlay (courts+caselaw/courts_caselaw, data/* untouched) [3/3]
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.pyAdded+64
- scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.pyAdded+74
- scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.pyAdded+45
- scrapers_and_normalizers/caselaw/scrapers/common/guard.pyAdded+39
- scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.pyAdded+99
- scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.pyAdded+67
- scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.pyAdded+159
- scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.pyAdded+54
- scrapers_and_normalizers/courts/collector/archive_resume.pyAdded+46
- scrapers_and_normalizers/courts/collector/archive_rules.pyAdded+75
- scrapers_and_normalizers/courts/collector/cc_gapfill.pyAdded+141
- scrapers_and_normalizers/courts/collector/cc_gapfill_review.pyAdded+19
- scrapers_and_normalizers/courts/collector/dedupe_stage_archive.pyAdded+30
- scrapers_and_normalizers/courts/collector/filter_archive.pyAdded+48
- scrapers_and_normalizers/courts/collector/fixup_phase1.pyAdded+81
- scrapers_and_normalizers/courts/collector/hf_push.pyAdded+6
- scrapers_and_normalizers/courts/collector/hf_push2.pyAdded+12
- scrapers_and_normalizers/courts/collector/hf_push3.pyAdded+15
- scrapers_and_normalizers/courts/collector/hf_push_phase1.pyAdded+18
- scrapers_and_normalizers/courts/collector/hf_push_phase2.pyAdded+17
- scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.pyAdded+17
- scrapers_and_normalizers/courts/collector/phase3gap.pyAdded+58
- scrapers_and_normalizers/courts/collector/procedure_rules_collect.pyAdded+111
- scrapers_and_normalizers/courts/collector/resume.pyAdded+18
- scrapers_and_normalizers/courts/collector/review.pyAdded+29
- scrapers_and_normalizers/courts/collector/review_archive.pyAdded+22
- scrapers_and_normalizers/courts/collector/review_resume.pyAdded+26
- scrapers_and_normalizers/courts/collector/review_sr.pyAdded+22
- scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.shAdded+25
- scrapers_and_normalizers/courts/collector/run_archive_waiter.shAdded+17
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.shAdded+10
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.shAdded+12
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.shAdded+12
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.shAdded+10
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.shAdded+24
- scrapers_and_normalizers/courts/collector/run_phase3gap.shAdded+5
- scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.shAdded+9
- scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.shAdded+9
- scrapers_and_normalizers/courts/collector/run_remaining.shAdded+11
- scrapers_and_normalizers/courts/collector/run_state_county.shAdded+13
- scrapers_and_normalizers/courts/collector/run_state_rules.shAdded+7
- scrapers_and_normalizers/courts/collector/run_state_rules_rerun.shAdded+7
- scrapers_and_normalizers/courts/collector/run_state_rules_resume.shAdded+7
- scrapers_and_normalizers/courts/collector/stage2.pyAdded+67
- scrapers_and_normalizers/courts/collector/stage_phase1.pyAdded+92
- scrapers_and_normalizers/courts/collector/stage_phase2.pyAdded+71
- scrapers_and_normalizers/courts/collector/state_county.pyAdded+465
- scrapers_and_normalizers/courts/collector/state_rules2.pyAdded+38
- scrapers_and_normalizers/courts/collector/state_rules3.pyAdded+35
- scrapers_and_normalizers/courts/collector/state_rules4.pyAdded+40
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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<21def 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 Nonedef 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'])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""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 pqREV='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=2000MAP={'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<DISK: logging.info('DISK GUARD %.2fG stop',free/1e9); sys.exit(2) if m<MEM: logging.info('MEM GUARD %.2fG stop',m/1e9); sys.exit(2)st=json.load(open(ST)) if os.path.exists(ST) else dict(offset=0,parts={},rows={},skipped={},done=False)if st.get('done'): logging.info('already done'); sys.exit(0)def save(): tmp=ST+'.tmp'; json.dump(st,open(tmp,'w')); os.replace(tmp,ST)buf={c:[] for c in MAP.values()}; pend_skip={}def flush_all(off): for c,rows in buf.items(): if not rows: continue os.makedirs(f'{BASE}/{c}',exist_ok=True); n=st['parts'].get(c,0) p=f'{BASE}/{c}/{c}.part{n:05d}.parquet' pq.write_table(pa.Table.from_pylist(rows),p+'.tmp',compression='zstd'); os.replace(p+'.tmp',p) st['parts'][c]=n+1; st['rows'][c]=st['rows'].get(c,0)+len(rows); logging.info('wrote %s rows=%d total=%d',p,len(rows),st['rows'][c]); buf[c]=[] for k,v in pend_skip.items(): st['skipped'][k]=st['skipped'].get(k,0)+v pend_skip.clear(); st['offset']=off; save(); guard()def row(d,c): return dict(ecli=None,jurisdiction='au',court=d.get('source'),chamber=None,date=d.get('date'),number=None,title=d.get('citation'),text=d.get('text'), source_url=d.get('url'),archive_name='isaacus/open-australian-legal-corpus@'+REV[:7],is_archive=False,licence=LIC[c], retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),court_id=None,version_id=d.get('version_id'), au_jurisdiction=d.get('jurisdiction'),mime=d.get('mime'),when_scraped=d.get('when_scraped'), licence_flag='non_commercial' if c=='au_hca' else 'commercial_ok_unaltered_with_attribution',config=c)guard(); logging.info('start offset=%d',st['offset'])off=st['offset']; tries=0; S=requests.Session(); S.headers['User-Agent']='justicedao-caselaw-research/0.1'while True: pos=off try: r=S.get(URL,headers={'Range':f'bytes={off}-'},stream=True,timeout=120) if r.status_code==416: break if r.status_code not in (200,206): raise Exception(f'HTTP {r.status_code}') if off and r.status_code==200: raise Exception('range not honoured') rest=b'' for chunk in r.iter_content(1<<20): rest+=chunk; lines=rest.split(b'\n'); rest=lines.pop() for l in lines: pos+=len(l)+1 if b'"decision"' not in l[:600]: continue d=json.loads(l) if d.get('type')!='decision': continue s=d.get('source') if s in SKIP: pend_skip[s]=pend_skip.get(s,0)+1; continue c=MAP.get(s) if not c: k='unknown:'+str(s); pend_skip[k]=pend_skip.get(k,0)+1; continue buf[c].append(row(d,c)) if len(buf[c])>=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'])123456789101112131415161718192021222324252627282930313233343536373839404142434445# 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 freeimport pyarrow.parquet as pqfrom huggingface_hub import HfApi,hf_hub_downloadB='/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'])123456789101112131415161718192021222324252627282930313233343536373839import osos.environ.setdefault("MALLOC_ARENA_MAX","2") # memsafe default for all caselaw collectorsimport json,shutil,time,datetime,pyarrow as pa,pyarrow.parquet as pqdef _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 MemAvailableDISK_STOP=_gb(os.environ.get("CASELAW_DISK_STOP","20.0")) # stop below 20G free diskdef mem_avail(): for l in open('/proc/meminfo'): if l.startswith('MemAvailable:'): return int(l.split()[1])*1024def guard_ok(): m=mem_avail(); d=shutil.disk_usage('/workspace').free return (m>=MEM_STOP and d>=DISK_STOP), m, ddef 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""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 legalbranch and to refuse targets that are Caselaw Access Project corpora (CAP exclusion).No network access, no secrets."""import os, sys, hashlibimport pyarrow as paIPFS_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 _clcexcept 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())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""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,loggingimport requests,lxml.etree as ET,lxml.html as LH,pyarrow as pa,pyarrow.parquet as pqOUT='/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.0logging.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 Nonedef guards(): while True: free=shutil.disk_usage('/workspace').free if free<DISK: logging.info('DISK GUARD %.2fG stop',free/1e9); sys.exit(2) m=int([l for l in open('/proc/meminfo') if l.startswith('MemAvailable')][0].split()[1])*1024 if m>=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('<div>'+s+'</div>').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'<link>([^<]+)</link>',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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""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 <name> --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, timeimport requestsfrom 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.0S = 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)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# 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 pqB='/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'])12345678910111213141516171819202122232425262728293031323334353637383940414243444546#!/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,datetimesys.path.insert(0,'/workspace/courts/collector')import archive_rules as Afrom us_fed import log,sid,nowO=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')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#!/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,datetimesys.path.insert(0,'/workspace/courts/collector')import us_fed as Ufrom us_fed import log,memguard,sid,nowO='/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=0def 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 Nonedef 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:passdef 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(),nif __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')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141#!/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,collectionssys.path.insert(0,'/workspace/courts/collector')import requestsfrom bs4 import BeautifulSoupimport state_county as SB='/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.logHL=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_frsize<float(os.environ.get('CC_DISKFLOOR_G','12'))*2**30: log('DISKGUARD free<floor stop');sys.exit(4)def get(u,rng=None,stream=False): for i in range(6): guard();w=last[0]+DELAY-time.time() if w>0: 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 NoneFORM_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 bestdef 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,ldSTF=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)12345678910111213141516171819import json,glob,collections,os,hashlib,randomB='/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'])]+=1md=['# 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])123456789101112131415161718192021222324252627282930import json,hashlib,collections,globB='/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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import json,glob,re,subprocess,hashlib,collections,os,zipfilefrom bs4 import BeautifulSoupB='/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,lddef 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',mout=[];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})})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import json,re,collections,shutil,os,hashlib,randomSRC='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 coverageal=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) judgesp=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)]+=1REMOVE={'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 stateseat={(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}# cardcard=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))123456import sys;sys.path.insert(0,'/workspace/scripts');import _hf_env # sets HF_TOKEN env from existing connector secret; never printedfrom huggingface_hub import HfApiapi=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)123456789101112import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_envfrom huggingface_hub import HfApi,snapshot_downloadapi=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=Truefor 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')123456789101112131415import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_envfrom huggingface_hub import HfApi,snapshot_downloadapi=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=Truefor 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')123456789101112131415161718import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_envfrom huggingface_hub import HfApi,snapshot_downloadapi=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=Truefor 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_datasetfor 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)1234567891011121314151617import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_envfrom huggingface_hub import HfApi,snapshot_downloadapi=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=Truefor 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')1234567891011121314151617import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_envfrom huggingface_hub import HfApi,snapshot_downloadapi=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=Truefor 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')12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/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 upsys.path.insert(0,'/workspace/courts/collector')import state_county as mfrom bs4 import BeautifulSoupB=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'<loc>\s*([^<\s]+)\s*</loc>',body) if '<sitemapindex' in body: sms+=[x for x in locs if re.search(r'page|post|content|court',x,re.I)][:3]; continue L+=[(x,up.unquote(up.urlparse(x).path).replace('-',' ').replace('/',' ')) for x in locs] res['notes'].append(f'{len(L)} candidate links') for cat in m.KW: c=sorted({(m.score(cat,u,t),u,t) for u,t in L if m.samesite(u,host) and m.score(cat,u,t)>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 0if __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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#!/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 rpfrom datetime import datetimeimport requestsSRC='/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])/1048576def guard(): s=0 while not STOP.is_set(): m=memavail(); d=shutil.disk_usage('/workspace').free/2**30 if d<DISKFLOOR: log('DISKGUARD',f'{d:.1f}G'); RC[0]=4; STOP.set(); return if m<MEMFLOOR: s+=1; log('MEMGUARD strike',s,f'{m:.2f}G') else: s=0 if s>=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 resHOSTS={}; 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 Hdef 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'<html' in head[:2000].lower() and CHAL.search(head) and n<30000): block(h,f'{r.status_code} at {url}'); return None,f'blocked_{r.status_code}' if r.status_code!=200: return None,f'http_{r.status_code}' return {'final_url':r.url,'sha256':sha.hexdigest(),'bytes':n,'content_type':r.headers.get('content-type','').split(';')[0],'last_modified':r.headers.get('last-modified')},'ok'def fam(it): s=(it.get('name','')+' '+it.get('_var','')+' '+it['url']).lower() return 'criminal' if re.search(r'crim|crr|crp',s) else 'civil' if re.search(r'civ|\bcr\b|rcp|cp-',s) else 'court_rules'def main(states): srcs=sources(); ck=f'{OUT}/ckpt.json'; C=json.load(open(ck)) if os.path.exists(ck) else {'done':[]} allst=sorted(srcs); inc=[s for s in allst if s not in EXCL]; exc=[s for s in allst if s in EXCL] if states: inc=[s for s in states if s in inc] json.dump({'included':inc,'excluded_policy':exc,'private_skipped':PRIVATE},open(f'{OUT}/plan.json','w'),indent=1) log('PR START pid',os.getpid(),'states',inc,'excluded',exc) threading.Thread(target=guard,daemon=True).start() for st in inc: if STOP.is_set(): break if st in C['done']: continue rows=[];cnt={} for it in srcs[st]: if STOP.is_set(): break meta,status=fetch(it['url']); cnt[status]=cnt.get(status,0)+1 if meta: rows.append({'state':st,'jurisdiction':f'US-{st}','rule_set':it.get('name') or it.get('title') or it['_var'],'family':fam(it),'source_url':it['url'],**meta,'source':'official','transport':'https','fetched_at':now(),'registry':'state_procedure_rules_scraper.'+it.get('_var','')}) if STOP.is_set(): log('STATE',st,'interrupted',cnt); break with open(f'{OUT}/{st}.jsonl','w') as f: for r in rows: f.write(json.dumps(r,sort_keys=True)+'\n') C['done'].append(st); C[st]=cnt; json.dump(C,open(ck,'w'),indent=1); log('STATE',st,'DONE',cnt) STOP.set(); return RC[0]if __name__=='__main__': sys.exit(main(sys.argv[1:]))123456789101112131415161718import sys,json,ossys.path.insert(0,'/workspace/courts/collector')import stage2 as S, us_fed as Ust=sys.argv[1];ST='/workspace/courts/staging'def rd(f):return [json.loads(l) for l in open(f) if l.strip()] if os.path.exists(f) else []if st=='courthouses': courts=rd(ST+'/courts.jsonl') or S.courts_retry() done={r['court_id'] for r in rd(ST+'/courthouses.jsonl')}|{S.sid('url',r['url']) for r in rd(ST+'/skips.jsonl')} # resume after last court with rows (courts processed in order) last=max([i for i,c in enumerate(courts) if c['court_id'] in done],default=-1) U.log('resume courthouses from index',last+1,'of',len(courts)) S.courthouses(courts[last+1:])elif st=='ncsc': U.ncsc() if not rd(ST+'/ncsc_state_links.jsonl'):U.log('NCSC_EMPTY: page 301 -> /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()1234567891011121314151617181920212223242526272829import json,glob,os,hashlib,collections,csv,randomC='/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()12345678910111213141516171819202122import json,glob,os,hashlib,csv,collectionsO='/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 Nonew=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 badfor 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')1234567891011121314151617181920212223242526import json,glob,os,hashlib,csv,collectionsO='/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')12345678910111213141516171819202122import json,glob,os,hashlib,csv,collectionsO=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]=nw=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')12345678910111213141516171819202122232425#!/bin/bashcd /workspace/courts/collector; PY=/workspace/venv/bin/python; R=/workspace/courtsL=$R/logs/archive_resume_waiter.log; LAUNCH=$R/logs/archive_resume_launches.logrm -f $R/STOPPED_ARCHIVE_RESUME $R/CAP_HIT_ARCHIVE_RESUMEecho "$(date -Is) waiter START pid $$" >> $L; echo $$ > $R/ARCHIVE_RESUME_WAITER.pidwhile :; 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_RESUMEdonerm -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_READY1234567891011121314151617#!/bin/bashcd /workspace/courts/collector; PY=/workspace/venv/bin/pythonecho "$(date -Is) waiter START pid $$; waiting for 4160340"while kill -0 4160340 2>/dev/null; do sleep 60; doneecho "$(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 600doneprintf "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; fidate -Is > /workspace/courts/ARCHIVE_RULES_DONE$PY -u review_archive.py && echo "$(date -Is) review built"12345678910#!/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.logexport SC_MEMFLOOR=3.0 SC_MAXSTRIKES=5echo "$(date -Is) GO launch pid $$" >> $Lnice -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" >> $Lif [ $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_READYelse echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL; fi123456789101112#!/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.logexport SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20ma=$(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; fiecho "$(date -Is) GO launch pid $$ (20261103)" >> $Lnice -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" >> $Lif [ $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_READYelse echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261103; fi123456789101112#!/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.logexport SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20ma=$(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; fiecho "$(date -Is) GO launch pid $$ (20261104)" >> $Lnice -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" >> $Lif [ $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_READYelse echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261104; fi12345678910#!/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.logexport SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3echo "$(date -Is) RESUME launch pid $$" >> $Lnice -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.logif [ $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_READYelse echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL_20261102; fi123456789101112131415161718192021222324#!/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.logecho $$ > $R/CC_GAPFILL_WAITER.pid; echo "$(date -Is) waiter START pid $$" >> $LPAT='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=0while [ $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 60doneprintf "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_GAPFILLnice -n 10 ionice -c3 $PY -u cc_gapfill.py >> $L 2>&1; rc=$?echo "$(date -Is) cc_gapfill rc=$rc" >> $Lif [ $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" >> $Lelse echo "$(date -Is) rc=$rc (3=memguard,4=disk,other=crash; see logs/cc_gapfill.log). No relaunch." > $R/STOPPED_CC_GAPFILLfirm -f $R/CC_GAPFILL_WAITER.pid12345#!/bin/bashB=/workspace/courts; cd $B/collectorecho $$ > $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;; esac123456789#!/bin/bash# CoS GO 2026-11-04 09:32 PT resume (IN remaining), no relaunch, stage onlyB=/workspace/courts; cd $B/collectorexport SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)[ $ma -lt 5242880 ] && { echo "$(date -Is) launch gate fail" > $B/STOPPED_PHASE3GAP_20261104; exit 1; }echo $$ > $B/PHASE3GAP.pidnice -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;; esac123456789#!/bin/bash# CoS GO 2026-11-04 ~09:38 PT: procedure rules wrapper, single run, NO relaunch, stage onlyB=/workspace/courts; cd $B/collectorexport SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20ma=$(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.pidnice -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;; esac1234567891011#!/bin/bashcd /workspace/courts/collectorPY=/workspace/venv/bin/pythonecho "$(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)"donedate -Is > /workspace/courts/DONE; echo "$(date -Is) DONE"12345678910111213#!/bin/bashB=/workspace/courts; cd $B/collector; PY=/workspace/venv/bin/pythonecho "$(date -Is) driver START pid $$ memfloor=${SC_MEMFLOOR:-4.2} maxstrikes=${SC_MAXSTRIKES:-3} gap=${SC_STRIKEGAP_S:-0}" >> $B/logs/state_county_driver.logecho $$ > $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.logcase $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;;esac1234567#!/bin/bashcd /workspace/courts/collector; PY=/workspace/venv/bin/pythonecho "$(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; fidate -Is > /workspace/courts/STATE_RULES_DONE$PY -u review_sr.py && echo "$(date -Is) review built"1234567#!/bin/bashcd /workspace/courts/collector; PY=/workspace/venv/bin/pythonecho "$(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; fidate -Is > /workspace/courts/STATE_RULES_RERUN_DONESR_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"1234567#!/bin/bashcd /workspace/courts/collector; PY=/workspace/venv/bin/pythonecho "$(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; fidate -Is > /workspace/courts/STATE_RULES_RESUME_DONE$PY -u review_resume.py && echo "$(date -Is) review built"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/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.parsesys.path.insert(0,'/workspace/courts/collector')import us_fed as Ufrom us_fed import log,fetch,links,prov,sid,ST,memguardWAIT=int(sys.argv[1]) if __name__=="__main__" and len(sys.argv)>1 else 0def 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 rowsADDR=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).*?</\1>',' ',b.decode('utf-8','ignore'));s=re.sub(r'<br\s*/?>',', ',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')1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import json,glob,os,re,hashlib,collections,unicodedataB='/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)# validateiso=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']+=1rep['validation_errors']=dict(err);rep['flags']={k:dict(v) for k,v in flags.items()}# unify keysfor 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))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import json,os,glob,shutil,hashlib,sys,datetimeB='/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 judgesia=[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 courthousesiac=[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})==1keep=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 fieldsfor 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 strictiso=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]=vbad=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})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465#!/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 upimport requestsfrom bs4 import BeautifulSoupfrom concurrent.futures import ThreadPoolExecutorBASE='/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**20def 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 tdef 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 Falsedef 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 Nonedef 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<MEMFLOOR: t=time.time(); counted=(strikes[0]==0 or t-lastcounted[0]>=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 Trueclass HostBlocked(Exception): passclass 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']=UABLF=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 Nonedef 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(),ndef _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 outdef 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 scdef 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 dISO=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 ddef 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,titledef 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 rowsCITY=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 rowsFILEEXT=('.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 outdef 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 npg<MAXP[cat] and not STOP.is_set(): u=q.pop(0); f=fetch(u) if not f: status['skips'].append({'url':u,'reason':'http-only or network error','transport':'http' if u.startswith('http:') else 'https'}); continue r,b,sha,n=f; npg+=1 if r.status_code!=200 or 'html' not in r.headers.get('content-type',''): continue soup=BeautifulSoup(b,'lxml'); L=links(r.url,soup) if cat=='forms': for fu,ft in ext_formlinks(r.url,soup): if fu not in {x[0] for x in files}: files.append((fu,ft,r.url)) for lu,lt in L: if lu in seen or not samesite(lu,root) or up.urlparse(lu).path.lower().endswith(FILEEXT): continue if score(cat,lu,lt)>0 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 0if __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)1234567891011121314151617181920212223242526272829303132333435363738#!/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,hashlibsys.path.insert(0,'/workspace/courts/collector')import us_fed as Ufrom us_fed import log,fetch,links,sid,nowOUT='/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')1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env python3"""Rerun: NE (malformed-link fix), DE (parser fix), KS (cap lifted). Stage only."""import sys,os,json,re,urllib.parse,htmlsys.path.insert(0,'/workspace/courts/collector')import us_fed as U, state_rules2 as S2from us_fed import logHREF=re.compile(r'<a\b[^>]*?href\s*=\s*["\']([^"\']+)["\'][^>]*>(.*?)</a>',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 outS2.links=safe_linksS2.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 <a> links in static HTML','SD':'Vue SPA (sdlegislature.gov), no static links; public API path unresolved'}_orig=S2.rundef 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')12345678910111213141516171819202122232425262728293031323334353637383940#!/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.parsesys.path.insert(0,'/workspace/courts/collector')import us_fed as U, state_rules3 as S3from us_fed import log,fetch,sid,nowO='/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 sdef 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')scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.pyAdded+64
scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.pyAdded+74
scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.pyAdded+45
scrapers_and_normalizers/caselaw/scrapers/common/guard.pyAdded+39
scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.pyAdded+99
scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.pyAdded+67
scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.pyAdded+159
scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.pyAdded+54
scrapers_and_normalizers/courts/collector/archive_resume.pyAdded+46
scrapers_and_normalizers/courts/collector/archive_rules.pyAdded+75
scrapers_and_normalizers/courts/collector/cc_gapfill.pyAdded+141
scrapers_and_normalizers/courts/collector/cc_gapfill_review.pyAdded+19
scrapers_and_normalizers/courts/collector/dedupe_stage_archive.pyAdded+30
scrapers_and_normalizers/courts/collector/filter_archive.pyAdded+48
scrapers_and_normalizers/courts/collector/fixup_phase1.pyAdded+81
scrapers_and_normalizers/courts/collector/hf_push.pyAdded+6
scrapers_and_normalizers/courts/collector/hf_push2.pyAdded+12
scrapers_and_normalizers/courts/collector/hf_push3.pyAdded+15
scrapers_and_normalizers/courts/collector/hf_push_phase1.pyAdded+18
scrapers_and_normalizers/courts/collector/hf_push_phase2.pyAdded+17
scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.pyAdded+17
scrapers_and_normalizers/courts/collector/phase3gap.pyAdded+58
scrapers_and_normalizers/courts/collector/procedure_rules_collect.pyAdded+111
scrapers_and_normalizers/courts/collector/resume.pyAdded+18
scrapers_and_normalizers/courts/collector/review.pyAdded+29
scrapers_and_normalizers/courts/collector/review_archive.pyAdded+22
scrapers_and_normalizers/courts/collector/review_resume.pyAdded+26
scrapers_and_normalizers/courts/collector/review_sr.pyAdded+22
scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.shAdded+25
scrapers_and_normalizers/courts/collector/run_archive_waiter.shAdded+17
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.shAdded+10
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.shAdded+12
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.shAdded+12
scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.shAdded+10
scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.shAdded+24
scrapers_and_normalizers/courts/collector/run_phase3gap.shAdded+5
scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.shAdded+9
scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.shAdded+9
scrapers_and_normalizers/courts/collector/run_remaining.shAdded+11
scrapers_and_normalizers/courts/collector/run_state_county.shAdded+13
scrapers_and_normalizers/courts/collector/run_state_rules.shAdded+7
scrapers_and_normalizers/courts/collector/run_state_rules_rerun.shAdded+7
scrapers_and_normalizers/courts/collector/run_state_rules_resume.shAdded+7
scrapers_and_normalizers/courts/collector/stage2.pyAdded+67
scrapers_and_normalizers/courts/collector/stage_phase1.pyAdded+92
scrapers_and_normalizers/courts/collector/stage_phase2.pyAdded+71
scrapers_and_normalizers/courts/collector/state_county.pyAdded+465
scrapers_and_normalizers/courts/collector/state_rules2.pyAdded+38
scrapers_and_normalizers/courts/collector/state_rules3.pyAdded+35
scrapers_and_normalizers/courts/collector/state_rules4.pyAdded+40