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
- scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.py +64 -0
- scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.py +74 -0
- scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.py +45 -0
- scrapers_and_normalizers/caselaw/scrapers/common/guard.py +39 -0
- scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.py +99 -0
- scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.py +67 -0
- scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.py +159 -0
- scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.py +54 -0
- scrapers_and_normalizers/courts/collector/archive_resume.py +46 -0
- scrapers_and_normalizers/courts/collector/archive_rules.py +75 -0
- scrapers_and_normalizers/courts/collector/cc_gapfill.py +141 -0
- scrapers_and_normalizers/courts/collector/cc_gapfill_review.py +19 -0
- scrapers_and_normalizers/courts/collector/dedupe_stage_archive.py +30 -0
- scrapers_and_normalizers/courts/collector/filter_archive.py +48 -0
- scrapers_and_normalizers/courts/collector/fixup_phase1.py +81 -0
- scrapers_and_normalizers/courts/collector/hf_push.py +6 -0
- scrapers_and_normalizers/courts/collector/hf_push2.py +12 -0
- scrapers_and_normalizers/courts/collector/hf_push3.py +15 -0
- scrapers_and_normalizers/courts/collector/hf_push_phase1.py +18 -0
- scrapers_and_normalizers/courts/collector/hf_push_phase2.py +17 -0
- scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.py +17 -0
- scrapers_and_normalizers/courts/collector/phase3gap.py +58 -0
- scrapers_and_normalizers/courts/collector/procedure_rules_collect.py +111 -0
- scrapers_and_normalizers/courts/collector/resume.py +18 -0
- scrapers_and_normalizers/courts/collector/review.py +29 -0
- scrapers_and_normalizers/courts/collector/review_archive.py +22 -0
- scrapers_and_normalizers/courts/collector/review_resume.py +26 -0
- scrapers_and_normalizers/courts/collector/review_sr.py +22 -0
- scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.sh +25 -0
- scrapers_and_normalizers/courts/collector/run_archive_waiter.sh +17 -0
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.sh +10 -0
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.sh +12 -0
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.sh +12 -0
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.sh +10 -0
- scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.sh +24 -0
- scrapers_and_normalizers/courts/collector/run_phase3gap.sh +5 -0
- scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.sh +9 -0
- scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.sh +9 -0
- scrapers_and_normalizers/courts/collector/run_remaining.sh +11 -0
- scrapers_and_normalizers/courts/collector/run_state_county.sh +13 -0
- scrapers_and_normalizers/courts/collector/run_state_rules.sh +7 -0
- scrapers_and_normalizers/courts/collector/run_state_rules_rerun.sh +7 -0
- scrapers_and_normalizers/courts/collector/run_state_rules_resume.sh +7 -0
- scrapers_and_normalizers/courts/collector/stage2.py +67 -0
- scrapers_and_normalizers/courts/collector/stage_phase1.py +92 -0
- scrapers_and_normalizers/courts/collector/stage_phase2.py +71 -0
- scrapers_and_normalizers/courts/collector/state_county.py +465 -0
- scrapers_and_normalizers/courts/collector/state_rules2.py +38 -0
- scrapers_and_normalizers/courts/collector/state_rules3.py +35 -0
- scrapers_and_normalizers/courts/collector/state_rules4.py +40 -0
scrapers_and_normalizers/caselaw/scrapers/at_ris/collect.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 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.
|
| 2 |
+
import sys,os,time,datetime,requests,lxml.html;sys.path.insert(0,'/workspace/caselaw/scrapers/common')
|
| 3 |
+
from guard import *
|
| 4 |
+
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'
|
| 5 |
+
LIC='CC BY 4.0 (RIS OGD, Bundeskanzleramt Österreich, data.gv.at)'
|
| 6 |
+
APPS=['Vfgh','Vwgh','Justiz','Bvwg','Lvwg','Dsk','Gbk','Pvak','Umse','Bks','Verg','Ubas','Dok']
|
| 7 |
+
os.makedirs(OUT,exist_ok=True); st=State(OUT+'/state.json',{'page':{},'done_apps':[]})
|
| 8 |
+
H={'User-Agent':'justicedao-caselaw-research/1.0 (polite 0.5 req/s)'}; last=[0.0]
|
| 9 |
+
def in_window():
|
| 10 |
+
n=datetime.datetime.now(); return n.weekday()<5 and 12<=n.hour<21
|
| 11 |
+
def wait_window():
|
| 12 |
+
while not in_window():
|
| 13 |
+
log(LOG,'outside window, paused'); time.sleep(600)
|
| 14 |
+
def get(u,params=None):
|
| 15 |
+
for a in range(6):
|
| 16 |
+
wait_window(); dt=time.time()-last[0]
|
| 17 |
+
if dt<2.0: time.sleep(2.0-dt)
|
| 18 |
+
last[0]=time.time()
|
| 19 |
+
try:
|
| 20 |
+
r=requests.get(u,params=params,headers=H,timeout=60)
|
| 21 |
+
if 'Security Check' in r.text[:3000]: log(LOG,'WAF page, stopping (no bypass)',u); sys.exit(4)
|
| 22 |
+
if r.status_code in(429,503): time.sleep(60*(a+1)); continue
|
| 23 |
+
r.raise_for_status(); return r
|
| 24 |
+
except requests.RequestException as e: log(LOG,'retry',a,u,e); time.sleep(20*(a+1))
|
| 25 |
+
return None
|
| 26 |
+
def L(x): return x if isinstance(x,list) else ([] if x is None else [x])
|
| 27 |
+
def items(x): return [i for i in L(x.get('item') if isinstance(x,dict) else x)] if x else []
|
| 28 |
+
for app in APPS:
|
| 29 |
+
if app in st.d['done_apps']: continue
|
| 30 |
+
cfg='at_'+app.lower(); w=PartWriter(f'{OUT}/{cfg}',cfg,st,cfg); page=st.d['page'].get(app,0)
|
| 31 |
+
while True:
|
| 32 |
+
ok,m,d=guard_ok()
|
| 33 |
+
if not ok: log(LOG,'GUARD STOP',app,page,m,d); sys.exit(3)
|
| 34 |
+
r=get(API,{'Applikation':app,'DokumenteProSeite':'OneHundred','Seitennummer':page+1})
|
| 35 |
+
if r is None: log(LOG,'list failed',app,page); sys.exit(5)
|
| 36 |
+
res=r.json()['OgdSearchResult']
|
| 37 |
+
refs=L(res.get('OgdDocumentResults',{}).get('OgdDocumentReference'))
|
| 38 |
+
if not refs: break
|
| 39 |
+
for ref in refs:
|
| 40 |
+
D=ref['Data']; M=D['Metadaten']; T=M['Technisch']; A=M.get('Allgemein',{}); J=M.get('Judikatur',{})
|
| 41 |
+
urls=L(D.get('Dokumentliste',{}).get('ContentReference')); hu=None
|
| 42 |
+
for cr in urls:
|
| 43 |
+
if cr.get('ContentType')=='MainDocument':
|
| 44 |
+
for cu in L(cr['Urls']['ContentUrl']):
|
| 45 |
+
if cu['DataType']=='Html': hu=cu['Url']
|
| 46 |
+
txt=None
|
| 47 |
+
if hu:
|
| 48 |
+
hr=get(hu)
|
| 49 |
+
if hr is not None:
|
| 50 |
+
try: txt=lxml.html.fromstring(hr.content).text_content()
|
| 51 |
+
except Exception: txt=None
|
| 52 |
+
gz=J.get('Geschaeftszahl'); gz='; '.join(map(str,items(gz))) if isinstance(gz,dict) else gz
|
| 53 |
+
row=dict(jurisdiction='AT',court=T.get('Organ') or app,config=cfg,ecli=J.get('EuropeanCaseLawIdentifier'),court_id=None,chamber=None,
|
| 54 |
+
date=J.get('Entscheidungsdatum'),number=gz,title=None,text=txt,source_url=hu or A.get('DokumentUrl'),licence=LIC,licence_flag='attribution_required',
|
| 55 |
+
is_archive=False,archive_name=None,retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
| 56 |
+
ris_id=T.get('ID'),ris_app=app,doc_type=J.get('Dokumenttyp'),published=A.get('Veroeffentlicht'),changed=A.get('Geaendert'),
|
| 57 |
+
normen='; '.join(map(str,items(J.get('Normen')))),schlagworte=J.get('Schlagworte'))
|
| 58 |
+
if w.add(row): w.flush(); log(LOG,app,'page',page,'rows',st.d['rows'][cfg])
|
| 59 |
+
page+=1; st.d['page'][app]=page
|
| 60 |
+
if page%5==0: log(LOG,app,'page',page)
|
| 61 |
+
# state page only advances with flushed rows: flush on page boundary when buffer big enough handled above; persist page after flush
|
| 62 |
+
if not w.buf: st.save()
|
| 63 |
+
w.flush(); st.d['done_apps'].append(app); st.save(); log(LOG,'app done',app,st.d['rows'][cfg])
|
| 64 |
+
st.d['done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows'])
|
scrapers_and_normalizers/caselaw/scrapers/au_oalc/collect.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AU decisions from isaacus/open-australian-legal-corpus@ef45e3f (keyless). Streams corpus.jsonl with HTTP Range resume.
|
| 2 |
+
Decisions only. HCA -> au_hca (non-commercial, kept separate). FCA -> au_fca. NSW skipped (blocked_needs_benjamin). zstd parquet, 2000-row parts."""
|
| 3 |
+
import os,sys,json,time,shutil,logging,datetime,requests,pyarrow as pa,pyarrow.parquet as pq
|
| 4 |
+
REV='ef45e3fec41a960919a31149eee6dab9aa39f725'
|
| 5 |
+
URL=f'https://huggingface.co/datasets/isaacus/open-australian-legal-corpus/resolve/{REV}/corpus.jsonl'
|
| 6 |
+
BASE='/workspace/caselaw/staging/ipfs_australia_caselaw'; ST=BASE+'/state.json'
|
| 7 |
+
DISK=10.5e9; MEM=4.2e9; BATCH=2000
|
| 8 |
+
MAP={'federal_court_of_australia':'au_fca','high_court_of_australia':'au_hca'}
|
| 9 |
+
SKIP={'nsw_caselaw':'blocked_needs_benjamin'}
|
| 10 |
+
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)',
|
| 11 |
+
'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)'}
|
| 12 |
+
os.makedirs(BASE,exist_ok=True)
|
| 13 |
+
logging.basicConfig(filename='/workspace/caselaw/logs/au_oalc.log',level=logging.INFO,format='%(asctime)s %(message)s')
|
| 14 |
+
def guard():
|
| 15 |
+
free=shutil.disk_usage('/workspace').free
|
| 16 |
+
m=int([l for l in open('/proc/meminfo') if l.startswith('MemAvailable')][0].split()[1])*1024
|
| 17 |
+
if free<DISK: logging.info('DISK GUARD %.2fG stop',free/1e9); sys.exit(2)
|
| 18 |
+
if m<MEM: logging.info('MEM GUARD %.2fG stop',m/1e9); sys.exit(2)
|
| 19 |
+
st=json.load(open(ST)) if os.path.exists(ST) else dict(offset=0,parts={},rows={},skipped={},done=False)
|
| 20 |
+
if st.get('done'): logging.info('already done'); sys.exit(0)
|
| 21 |
+
def save():
|
| 22 |
+
tmp=ST+'.tmp'; json.dump(st,open(tmp,'w')); os.replace(tmp,ST)
|
| 23 |
+
buf={c:[] for c in MAP.values()}; pend_skip={}
|
| 24 |
+
def flush_all(off):
|
| 25 |
+
for c,rows in buf.items():
|
| 26 |
+
if not rows: continue
|
| 27 |
+
os.makedirs(f'{BASE}/{c}',exist_ok=True); n=st['parts'].get(c,0)
|
| 28 |
+
p=f'{BASE}/{c}/{c}.part{n:05d}.parquet'
|
| 29 |
+
pq.write_table(pa.Table.from_pylist(rows),p+'.tmp',compression='zstd'); os.replace(p+'.tmp',p)
|
| 30 |
+
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]=[]
|
| 31 |
+
for k,v in pend_skip.items(): st['skipped'][k]=st['skipped'].get(k,0)+v
|
| 32 |
+
pend_skip.clear(); st['offset']=off; save(); guard()
|
| 33 |
+
def row(d,c):
|
| 34 |
+
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'),
|
| 35 |
+
source_url=d.get('url'),archive_name='isaacus/open-australian-legal-corpus@'+REV[:7],is_archive=False,licence=LIC[c],
|
| 36 |
+
retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),court_id=None,version_id=d.get('version_id'),
|
| 37 |
+
au_jurisdiction=d.get('jurisdiction'),mime=d.get('mime'),when_scraped=d.get('when_scraped'),
|
| 38 |
+
licence_flag='non_commercial' if c=='au_hca' else 'commercial_ok_unaltered_with_attribution',config=c)
|
| 39 |
+
guard(); logging.info('start offset=%d',st['offset'])
|
| 40 |
+
off=st['offset']; tries=0; S=requests.Session(); S.headers['User-Agent']='justicedao-caselaw-research/0.1'
|
| 41 |
+
while True:
|
| 42 |
+
pos=off
|
| 43 |
+
try:
|
| 44 |
+
r=S.get(URL,headers={'Range':f'bytes={off}-'},stream=True,timeout=120)
|
| 45 |
+
if r.status_code==416: break
|
| 46 |
+
if r.status_code not in (200,206): raise Exception(f'HTTP {r.status_code}')
|
| 47 |
+
if off and r.status_code==200: raise Exception('range not honoured')
|
| 48 |
+
rest=b''
|
| 49 |
+
for chunk in r.iter_content(1<<20):
|
| 50 |
+
rest+=chunk; lines=rest.split(b'\n'); rest=lines.pop()
|
| 51 |
+
for l in lines:
|
| 52 |
+
pos+=len(l)+1
|
| 53 |
+
if b'"decision"' not in l[:600]: continue
|
| 54 |
+
d=json.loads(l)
|
| 55 |
+
if d.get('type')!='decision': continue
|
| 56 |
+
s=d.get('source')
|
| 57 |
+
if s in SKIP: pend_skip[s]=pend_skip.get(s,0)+1; continue
|
| 58 |
+
c=MAP.get(s)
|
| 59 |
+
if not c: k='unknown:'+str(s); pend_skip[k]=pend_skip.get(k,0)+1; continue
|
| 60 |
+
buf[c].append(row(d,c))
|
| 61 |
+
if len(buf[c])>=BATCH: flush_all(pos)
|
| 62 |
+
tries=0
|
| 63 |
+
if rest.strip(): pos+=len(rest) # last line without newline
|
| 64 |
+
if rest.strip():
|
| 65 |
+
d=json.loads(rest)
|
| 66 |
+
if d.get('type')=='decision' and d.get('source') in MAP: c=MAP[d['source']]; buf[c].append(row(d,c))
|
| 67 |
+
off=pos; break
|
| 68 |
+
except SystemExit: raise
|
| 69 |
+
except Exception as e:
|
| 70 |
+
tries+=1; logging.info('ERR %s retry %d from committed offset %d',e,tries,st['offset'])
|
| 71 |
+
buf={c:[] for c in MAP.values()}; pend_skip.clear(); off=st['offset']
|
| 72 |
+
if tries>10: logging.info('giving up'); sys.exit(1)
|
| 73 |
+
time.sleep(min(600,10*2**tries))
|
| 74 |
+
flush_all(off); st['done']=True; save(); logging.info('DONE rows=%s skipped=%s',st['rows'],st['skipped'])
|
scrapers_and_normalizers/caselaw/scrapers/ca_a2aj/collect.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CA: a2aj/canadian-case-law (public HF, keyless). Stage-only. Resumable.
|
| 2 |
+
import sys,os,time,datetime;sys.path.insert(0,'/workspace/caselaw/scrapers/common')
|
| 3 |
+
from guard import *
|
| 4 |
+
import guard; guard.DISK_STOP=20e9 # CoS: CA pauses (resumable) below 20G free
|
| 5 |
+
import pyarrow.parquet as pq
|
| 6 |
+
from huggingface_hub import HfApi,hf_hub_download
|
| 7 |
+
B='/workspace/caselaw'; REPO='a2aj/canadian-case-law'; OUT=B+'/staging/ipfs_canada_caselaw'; LOG=B+'/logs/ca_a2aj.log'
|
| 8 |
+
st=State(OUT+'/state.json',{'done_courts':[],'offset':{}}); os.makedirs(OUT,exist_ok=True)
|
| 9 |
+
api=HfApi(token=False); rev=st.d.setdefault('revision',api.dataset_info(REPO).sha); st.save()
|
| 10 |
+
courts=sorted({f.split('/')[0] for f in api.list_repo_files(REPO,repo_type='dataset',revision=rev) if f.endswith('train.parquet')})
|
| 11 |
+
log(LOG,'start rev',rev,'courts',len(courts),'done',len(st.d['done_courts']))
|
| 12 |
+
def lic_flag(l):
|
| 13 |
+
l=(l or '').lower(); f=[]
|
| 14 |
+
if 'non-commercial' in l or 'noncommercial' in l or 'non commercial' in l: f.append('non_commercial')
|
| 15 |
+
if 'artificial intelligence' in l or ' ai ' in l or 'machine learning' in l: f.append('ai_terms_check')
|
| 16 |
+
return ';'.join(f) or 'see_upstream_license'
|
| 17 |
+
for c in courts:
|
| 18 |
+
if c in st.d['done_courts']: continue
|
| 19 |
+
ok,m,d=guard_ok()
|
| 20 |
+
if not ok: log(LOG,'GUARD STOP before',c,m,d); sys.exit(3)
|
| 21 |
+
p=hf_hub_download(REPO,f'{c}/train.parquet',repo_type='dataset',revision=rev,token=False,cache_dir=B+'/work/ca_hfcache')
|
| 22 |
+
cfg='ca_'+c.lower(); w=PartWriter(f'{OUT}/{cfg}',cfg,st,cfg); off=st.d['offset'].get(c,0); i=0
|
| 23 |
+
pf=pq.ParquetFile(p,buffer_size=1<<20,pre_buffer=False)
|
| 24 |
+
now=datetime.datetime.now(datetime.timezone.utc).isoformat()
|
| 25 |
+
for b in pf.iter_batches(batch_size=200):
|
| 26 |
+
for r in b.to_pylist():
|
| 27 |
+
i+=1
|
| 28 |
+
if i<=off: continue
|
| 29 |
+
lic=r.get('upstream_license')
|
| 30 |
+
row=dict(jurisdiction='CA',court=c,config=cfg,ecli=None,court_id=None,chamber=None,
|
| 31 |
+
date=str(r.get('document_date_en') or r.get('document_date_fr') or '')[:10] or None,
|
| 32 |
+
number=r.get('citation_en') or r.get('citation_fr'),title=r.get('name_en') or r.get('name_fr'),
|
| 33 |
+
text=r.get('unofficial_text_en') or r.get('unofficial_text_fr'),
|
| 34 |
+
source_url=r.get('url_en') or r.get('url_fr'),licence=('A2AJ compilation MIT; upstream: '+(lic or '')),licence_flag=lic_flag(lic),
|
| 35 |
+
is_archive=False,archive_name=None,retrieved_at=now,source_dataset=f'{REPO}@{rev}')
|
| 36 |
+
for k,v in r.items():
|
| 37 |
+
if k.startswith(('citation','name_','url_','unofficial_text','document_date','scraped')): row['a2aj_'+k]=v
|
| 38 |
+
row['a2aj_cases_cited_en']=r.get('cases_cited_en'); row['a2aj_citing_cases_count']=r.get('citing_cases_count')
|
| 39 |
+
if w.add(row):
|
| 40 |
+
w.flush(lambda: st.d['offset'].__setitem__(c,i)); log(LOG,c,'rows',i,'total',sum(st.d['rows'].values()))
|
| 41 |
+
ok,m,d=guard_ok()
|
| 42 |
+
if not ok: log(LOG,'GUARD STOP',c,i,m,d); sys.exit(3)
|
| 43 |
+
w.flush(lambda: st.d['offset'].__setitem__(c,i)); st.d['done_courts'].append(c); st.save()
|
| 44 |
+
os.remove(os.path.realpath(p)); log(LOG,'done',c,i)
|
| 45 |
+
st.d['done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows'])
|
scrapers_and_normalizers/caselaw/scrapers/common/guard.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ.setdefault("MALLOC_ARENA_MAX","2") # memsafe default for all caselaw collectors
|
| 3 |
+
import json,shutil,time,datetime,pyarrow as pa,pyarrow.parquet as pq
|
| 4 |
+
def _gb(v):
|
| 5 |
+
v=float(v); return v*1e9 if v<1e6 else v # accept GB (3.2) or bytes (3.2e9)
|
| 6 |
+
MEM_STOP=_gb(os.environ.get("CASELAW_MEM_STOP","3.2")) # stop below 3.2G MemAvailable
|
| 7 |
+
DISK_STOP=_gb(os.environ.get("CASELAW_DISK_STOP","20.0")) # stop below 20G free disk
|
| 8 |
+
def mem_avail():
|
| 9 |
+
for l in open('/proc/meminfo'):
|
| 10 |
+
if l.startswith('MemAvailable:'): return int(l.split()[1])*1024
|
| 11 |
+
def guard_ok():
|
| 12 |
+
m=mem_avail(); d=shutil.disk_usage('/workspace').free
|
| 13 |
+
return (m>=MEM_STOP and d>=DISK_STOP), m, d
|
| 14 |
+
def log(path,*a):
|
| 15 |
+
with open(path,'a') as f: f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S ')+' '.join(map(str,a))+'\n')
|
| 16 |
+
class State:
|
| 17 |
+
def __init__(s,path,default):
|
| 18 |
+
s.path=path; s.d=json.load(open(path)) if os.path.exists(path) else default
|
| 19 |
+
def save(s):
|
| 20 |
+
t=s.path+'.tmp'; json.dump(s.d,open(t,'w'),indent=1); os.replace(t,s.path)
|
| 21 |
+
class PartWriter:
|
| 22 |
+
"""2000-row zstd parquet parts; all columns string except bools."""
|
| 23 |
+
def __init__(s,outdir,prefix,state,key):
|
| 24 |
+
os.makedirs(outdir,exist_ok=True); s.outdir=outdir; s.prefix=prefix; s.st=state; s.key=key; s.buf=[]
|
| 25 |
+
s.st.d.setdefault('parts',{}).setdefault(key,0); s.st.d.setdefault('rows',{}).setdefault(key,0)
|
| 26 |
+
def add(s,row):
|
| 27 |
+
s.buf.append(row)
|
| 28 |
+
return len(s.buf)>=2000
|
| 29 |
+
def flush(s,extra_state=None):
|
| 30 |
+
if not s.buf:
|
| 31 |
+
if extra_state: extra_state(); s.st.save()
|
| 32 |
+
return
|
| 33 |
+
n=s.st.d['parts'][s.key]; p=f'{s.outdir}/{s.prefix}.part{n:05d}.parquet'
|
| 34 |
+
cols=sorted({k for r in s.buf for k in r})
|
| 35 |
+
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})
|
| 36 |
+
pq.write_table(t,p+'.tmp',compression='zstd'); os.replace(p+'.tmp',p)
|
| 37 |
+
s.st.d['parts'][s.key]=n+1; s.st.d['rows'][s.key]+=len(s.buf); s.buf=[]
|
| 38 |
+
if extra_state: extra_state()
|
| 39 |
+
s.st.save()
|
scrapers_and_normalizers/caselaw/scrapers/common/normalize_caselaw.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ipfs_datasets_py-backed case-law normalizer (JusticeDAO world_law caselaw scrapers).
|
| 2 |
+
|
| 3 |
+
Normalizes staged case-law parquet rows into the shared world_law caselaw schema:
|
| 4 |
+
* standard core fields always present (string-typed, nullable) so HF `load_dataset`
|
| 5 |
+
streaming never hits null-type/schema-cast failures across parts;
|
| 6 |
+
* `licence`, `licence_flag`, `flag` columns; source provenance (`source_host`,
|
| 7 |
+
`source_dataset`, `normalizer`), `country`, `legal_branch`;
|
| 8 |
+
* `court_id` linkage (Courthouse-scraper ids where a mapping is supplied);
|
| 9 |
+
* a deterministic `doc_id` (sha256 of config+source_url/number+text prefix).
|
| 10 |
+
Uses ipfs_datasets_py.processors.legal_data.canonical_legal_corpora (from
|
| 11 |
+
/workspace/ipfs_datasets_py_latest or an installed ipfs_datasets_py) to tag the legal
|
| 12 |
+
branch and to refuse targets that are Caselaw Access Project corpora (CAP exclusion).
|
| 13 |
+
No network access, no secrets.
|
| 14 |
+
"""
|
| 15 |
+
import os, sys, hashlib
|
| 16 |
+
import pyarrow as pa
|
| 17 |
+
IPFS_DATASETS_PATH = os.environ.get("IPFS_DATASETS_PY_PATH", "/workspace/ipfs_datasets_py_latest")
|
| 18 |
+
if os.path.isdir(IPFS_DATASETS_PATH) and IPFS_DATASETS_PATH not in sys.path:
|
| 19 |
+
sys.path.insert(0, IPFS_DATASETS_PATH)
|
| 20 |
+
try:
|
| 21 |
+
from ipfs_datasets_py.processors.legal_data import canonical_legal_corpora as _clc
|
| 22 |
+
except Exception: # pragma: no cover - library optional at read time
|
| 23 |
+
_clc = None
|
| 24 |
+
|
| 25 |
+
NORMALIZER_VERSION = "caselaw-normalize/1.0"
|
| 26 |
+
CORE = ["doc_id", "country", "jurisdiction", "config", "court", "court_id", "chamber", "date",
|
| 27 |
+
"number", "ecli", "title", "text", "source_url", "source_host", "source_dataset",
|
| 28 |
+
"licence", "licence_flag", "flag", "retrieved_at", "legal_branch", "normalizer"]
|
| 29 |
+
BOOL = {"is_archive"}
|
| 30 |
+
|
| 31 |
+
def ipfs_datasets_available():
|
| 32 |
+
return _clc is not None
|
| 33 |
+
|
| 34 |
+
def assert_not_cap(dataset_id):
|
| 35 |
+
"""Refuse to (re)publish anything ipfs_datasets_py maps to the Caselaw Access Project."""
|
| 36 |
+
if _clc is None:
|
| 37 |
+
return
|
| 38 |
+
try:
|
| 39 |
+
c = _clc.infer_canonical_legal_corpus_for_dataset_id(dataset_id)
|
| 40 |
+
if c and c.key == "caselaw_access_project":
|
| 41 |
+
raise ValueError(f"{dataset_id} maps to CAP; excluded by policy")
|
| 42 |
+
except KeyError:
|
| 43 |
+
pass
|
| 44 |
+
except ValueError as e:
|
| 45 |
+
if "CAP" in str(e): raise
|
| 46 |
+
|
| 47 |
+
def legal_branch(dataset_id):
|
| 48 |
+
if _clc is not None:
|
| 49 |
+
try:
|
| 50 |
+
return _clc.infer_canonical_legal_corpus_for_dataset_id(dataset_id).normalized_branch() or "caselaw"
|
| 51 |
+
except Exception:
|
| 52 |
+
pass
|
| 53 |
+
return "caselaw"
|
| 54 |
+
|
| 55 |
+
def _doc_id(cfg, r):
|
| 56 |
+
key = "|".join(str(r.get(k) or "") for k in ("source_url", "number", "ris_id", "date")) + "|" + str(r.get("text") or "")[:2000]
|
| 57 |
+
return hashlib.sha256(f"{cfg}|{key}".encode("utf-8", "replace")).hexdigest()
|
| 58 |
+
|
| 59 |
+
def normalize_table(t, *, dataset_id, config, country, source_host, source_dataset,
|
| 60 |
+
licence=None, licence_flag=None, flags=None, court_ids=None):
|
| 61 |
+
"""Return a normalized pyarrow Table. `flags`: list (aligned to rows) of flag str/None.
|
| 62 |
+
`court_ids`: dict court-name -> Courthouse court_id (optional linkage)."""
|
| 63 |
+
assert_not_cap(dataset_id)
|
| 64 |
+
branch = legal_branch(dataset_id)
|
| 65 |
+
rows = t.to_pylist()
|
| 66 |
+
if flags is not None and len(flags) != len(rows):
|
| 67 |
+
raise ValueError("flags length mismatch")
|
| 68 |
+
out = []
|
| 69 |
+
for i, r in enumerate(rows):
|
| 70 |
+
r = dict(r)
|
| 71 |
+
r.setdefault("config", config); r["config"] = r.get("config") or config
|
| 72 |
+
r["country"] = country
|
| 73 |
+
r["source_host"] = r.get("source_host") or source_host
|
| 74 |
+
r["source_dataset"] = r.get("source_dataset") or source_dataset
|
| 75 |
+
if licence and not r.get("licence"): r["licence"] = licence
|
| 76 |
+
if licence_flag and not r.get("licence_flag"): r["licence_flag"] = licence_flag
|
| 77 |
+
if flags is not None: r["flag"] = flags[i]
|
| 78 |
+
if court_ids and not r.get("court_id"): r["court_id"] = court_ids.get(r.get("court"))
|
| 79 |
+
r["legal_branch"] = branch; r["normalizer"] = NORMALIZER_VERSION
|
| 80 |
+
r["doc_id"] = _doc_id(config, r)
|
| 81 |
+
out.append(r)
|
| 82 |
+
cols = CORE + sorted({k for r in out for k in r} - set(CORE))
|
| 83 |
+
arrs = {}
|
| 84 |
+
for c in cols:
|
| 85 |
+
if c in BOOL:
|
| 86 |
+
arrs[c] = pa.array([r.get(c) for r in out], pa.bool_())
|
| 87 |
+
else:
|
| 88 |
+
arrs[c] = pa.array([None if r.get(c) is None else str(r.get(c)) for r in out], pa.string())
|
| 89 |
+
return pa.table(arrs)
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
import argparse, pyarrow.parquet as pq
|
| 93 |
+
ap = argparse.ArgumentParser(description="Normalize one staged caselaw parquet file")
|
| 94 |
+
for a in ("src", "dst", "--dataset-id", "--config", "--country", "--source-host", "--source-dataset", "--licence", "--licence-flag"):
|
| 95 |
+
ap.add_argument(a)
|
| 96 |
+
x = ap.parse_args()
|
| 97 |
+
tb = normalize_table(pq.read_table(x.src), dataset_id=x.dataset_id, config=x.config, country=x.country,
|
| 98 |
+
source_host=x.source_host, source_dataset=x.source_dataset, licence=x.licence, licence_flag=x.licence_flag)
|
| 99 |
+
pq.write_table(tb, x.dst, compression="zstd"); print(x.dst, tb.num_rows, "ipfs_datasets_py:", ipfs_datasets_available())
|
scrapers_and_normalizers/caselaw/scrapers/de_rii/collect.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DE Rechtsprechung im Internet collector -> zstd parquet staging. Text only, 0.5 req/s, resumable."""
|
| 2 |
+
import os,io,re,sys,json,time,zipfile,shutil,datetime,logging
|
| 3 |
+
import requests,lxml.etree as ET,lxml.html as LH,pyarrow as pa,pyarrow.parquet as pq
|
| 4 |
+
OUT='/workspace/caselaw/staging/ipfs_germany_caselaw/de_bund'; ST='/workspace/caselaw/staging/ipfs_germany_caselaw/state.json'
|
| 5 |
+
TOC='https://www.rechtsprechung-im-internet.de/rii-toc.xml'; UA='justicedao-caselaw-research/0.1 (Benjamin Barber; 0.5 req/s)'
|
| 6 |
+
LIC='Free use and re-use (rechtsprechung-im-internet.de, BMJ/BfJ); attribution: Rechtsprechung im Internet'
|
| 7 |
+
DISK=10.5e9; MEM=4.2e9; BATCH=2000; GAP=2.0
|
| 8 |
+
logging.basicConfig(filename='/workspace/caselaw/logs/de_rii.log',level=logging.INFO,format='%(asctime)s %(message)s')
|
| 9 |
+
os.makedirs(OUT,exist_ok=True); S=requests.Session(); S.headers['User-Agent']=UA; last=[0.0]
|
| 10 |
+
def get(u):
|
| 11 |
+
for a in range(8):
|
| 12 |
+
w=GAP-(time.time()-last[0]); time.sleep(max(0,w)); last[0]=time.time()
|
| 13 |
+
try:
|
| 14 |
+
r=S.get(u,timeout=120)
|
| 15 |
+
if r.status_code==200: return r.content
|
| 16 |
+
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)
|
| 17 |
+
logging.info('HTTP %s %s',r.status_code,u)
|
| 18 |
+
if r.status_code==404: return None
|
| 19 |
+
except Exception as e: logging.info('ERR %s %s',u,e)
|
| 20 |
+
time.sleep(min(600,5*2**a))
|
| 21 |
+
return None
|
| 22 |
+
def guards():
|
| 23 |
+
while True:
|
| 24 |
+
free=shutil.disk_usage('/workspace').free
|
| 25 |
+
if free<DISK: logging.info('DISK GUARD %.2fG stop',free/1e9); sys.exit(2)
|
| 26 |
+
m=int([l for l in open('/proc/meminfo') if l.startswith('MemAvailable')][0].split()[1])*1024
|
| 27 |
+
if m>=MEM: return
|
| 28 |
+
logging.info('MEM GUARD %.2fG wait',m/1e9); time.sleep(60)
|
| 29 |
+
def txt(el):
|
| 30 |
+
if el is None: return ''
|
| 31 |
+
s=ET.tostring(el,encoding='unicode',method='html')
|
| 32 |
+
try: return LH.fromstring('<div>'+s+'</div>').text_content().strip()
|
| 33 |
+
except Exception: return ''
|
| 34 |
+
def parse(b,link):
|
| 35 |
+
z=zipfile.ZipFile(io.BytesIO(b)); x=[n for n in z.namelist() if n.endswith('.xml')][0]
|
| 36 |
+
d=ET.fromstring(z.read(x),ET.XMLParser(load_dtd=False,no_network=True,resolve_entities=False))
|
| 37 |
+
g=lambda t:(d.findtext(t) or '').strip()
|
| 38 |
+
parts=[]
|
| 39 |
+
for t,h in [('leitsatz','Leitsatz'),('sonstosatz','Orientierungssatz'),('tenor','Tenor'),('tatbestand','Tatbestand'),('entscheidungsgruende','Entscheidungsgründe'),('gruende','Gründe'),('abwmeinung','Abweichende Meinung'),('sonstlt','Sonstiger Langtext')]:
|
| 40 |
+
v=txt(d.find(t))
|
| 41 |
+
if v: parts.append(h+'\n'+v)
|
| 42 |
+
dt=g('entsch-datum'); dt=f'{dt[:4]}-{dt[4:6]}-{dt[6:8]}' if len(dt)==8 else dt
|
| 43 |
+
court=(g('gertyp')+' '+g('spruchkoerper')).strip()
|
| 44 |
+
return dict(ecli=g('ecli') or None,jurisdiction='de',court=court,chamber=g('spruchkoerper') or None,date=dt,number=g('aktenzeichen'),
|
| 45 |
+
title=txt(d.find('titelzeile')) or (g('doktyp')+' '+g('aktenzeichen')).strip(),text='\n\n'.join(parts),source_url=link,
|
| 46 |
+
archive_name=None,is_archive=False,licence=LIC,retrieved_at=datetime.datetime.utcnow().isoformat()+'Z',court_id=None,
|
| 47 |
+
rii_doknr=g('doknr'),doctype=g('doktyp'),norm=g('norm'),config='de_bund')
|
| 48 |
+
def save(st):
|
| 49 |
+
t=ST+'.tmp'; json.dump(st,open(t,'w')); os.replace(t,ST)
|
| 50 |
+
def flush(rows,st):
|
| 51 |
+
if not rows: return
|
| 52 |
+
fn=f'{OUT}/de_bund.part{st["part"]:05d}.parquet'; tmp=fn+'.tmp'
|
| 53 |
+
pq.write_table(pa.Table.from_pylist(rows),tmp,compression='zstd'); os.replace(tmp,fn)
|
| 54 |
+
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'])
|
| 55 |
+
def main():
|
| 56 |
+
st=json.load(open(ST)) if os.path.exists(ST) else {'part':0,'rows':0,'done':0}
|
| 57 |
+
toc=get(TOC); links=[re.sub('^http:','https:',l.decode()) for l in re.findall(rb'<link>([^<]+)</link>',toc)]
|
| 58 |
+
logging.info('toc %d items, resume at %d',len(links),st['done']); rows=[]
|
| 59 |
+
for i in range(st['done'],len(links)):
|
| 60 |
+
guards(); b=get(links[i])
|
| 61 |
+
if b:
|
| 62 |
+
try: rows.append(parse(b,links[i]))
|
| 63 |
+
except Exception as e: logging.info('PARSE %s %s',links[i],e)
|
| 64 |
+
st['pending']=i+1
|
| 65 |
+
if len(rows)>=BATCH: flush(rows,st); rows=[]
|
| 66 |
+
st['pending']=len(links); flush(rows,st); st['done']=len(links); save(st); logging.info('DONE rows=%d',st['rows'])
|
| 67 |
+
main()
|
scrapers_and_normalizers/caselaw/scrapers/fr_dila/adapter.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming adapter for DILA open-data case-law dumps (CASS, CAPP, JADE, CONSTIT, INCA).
|
| 2 |
+
Streams .tar.gz over HTTPS (verify on), parses XML members on the fly; never writes archives.
|
| 3 |
+
Usage: python adapter.py --fond CASS --archive <name> --out DIR [--limit N]
|
| 4 |
+
python adapter.py --full --out DIR --state state.json (resumable, guarded)
|
| 5 |
+
"""
|
| 6 |
+
import argparse, datetime as dt, json, os, re, shutil, sys, tarfile, time
|
| 7 |
+
import requests
|
| 8 |
+
from lxml import etree
|
| 9 |
+
|
| 10 |
+
BASE = "https://echanges.dila.gouv.fr/OPENDATA/"
|
| 11 |
+
UA = "JusticeDAO-caselaw-collector/0.1 (open-data research; ipfs_datasets_py)"
|
| 12 |
+
FONDS = {"CASS": "fr_cass", "CAPP": "fr_capp", "JADE": "fr_jade", "CONSTIT": "fr_constit", "INCA": "fr_inca"}
|
| 13 |
+
PAUSE = 2.0
|
| 14 |
+
S = requests.Session(); S.headers["User-Agent"] = UA
|
| 15 |
+
|
| 16 |
+
def guard(min_mem_gb=4.2, min_disk_gb=10.5, path="/workspace"):
|
| 17 |
+
mem = int(re.search(r"MemAvailable:\s+(\d+)", open("/proc/meminfo").read()).group(1)) / 1024**2
|
| 18 |
+
disk = shutil.disk_usage(path).free / 1024**3
|
| 19 |
+
return mem >= min_mem_gb and disk >= min_disk_gb, mem, disk
|
| 20 |
+
|
| 21 |
+
def list_archives(fond):
|
| 22 |
+
time.sleep(PAUSE)
|
| 23 |
+
r = S.get(f"{BASE}{fond}/", timeout=60, verify=True); r.raise_for_status()
|
| 24 |
+
return sorted(set(re.findall(r'href="([^"]+\.tar\.gz)"', r.text)))
|
| 25 |
+
|
| 26 |
+
def _t(root, *paths):
|
| 27 |
+
for p in paths:
|
| 28 |
+
v = root.findtext(p)
|
| 29 |
+
if v: return v.strip()
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
def parse(xml_bytes, fond, url, archive):
|
| 33 |
+
root = etree.fromstring(xml_bytes)
|
| 34 |
+
meta = ".//META_JURI"
|
| 35 |
+
text_el = root.find(".//CONTENU")
|
| 36 |
+
text = " ".join(text_el.itertext()).strip() if text_el is not None else None
|
| 37 |
+
return {
|
| 38 |
+
"ecli": _t(root, ".//ECLI"),
|
| 39 |
+
"jurisdiction": "FR",
|
| 40 |
+
"court": _t(root, f"{meta}/JURIDICTION"),
|
| 41 |
+
"chamber": _t(root, ".//FORMATION"),
|
| 42 |
+
"date": _t(root, f"{meta}/DATE_DEC"),
|
| 43 |
+
"number": _t(root, f"{meta}/NUMERO", ".//NUMEROS_AFFAIRES/NUMERO_AFFAIRE"),
|
| 44 |
+
"title": _t(root, f"{meta}/TITRE"),
|
| 45 |
+
"text": text,
|
| 46 |
+
"source_url": url, "archive_name": archive, "is_archive": False,
|
| 47 |
+
"licence": "Licence Ouverte 2.0",
|
| 48 |
+
"retrieved_at": dt.datetime.now(dt.timezone.utc).isoformat(),
|
| 49 |
+
"court_id": None, "dila_id": _t(root, ".//META_COMMUN/ID"), "config": FONDS[fond],
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
class ResumableRaw:
|
| 53 |
+
"""File-like over an HTTP body; on IncompleteRead/reset reopens with Range from the current
|
| 54 |
+
byte offset (server sends Accept-Ranges: bytes), up to `retries` times with backoff."""
|
| 55 |
+
def __init__(self, url, retries=5):
|
| 56 |
+
self.url, self.retries, self.pos, self.r = url, retries, 0, None
|
| 57 |
+
self._open()
|
| 58 |
+
def _open(self):
|
| 59 |
+
h = {"Range": f"bytes={self.pos}-"} if self.pos else {}
|
| 60 |
+
time.sleep(PAUSE)
|
| 61 |
+
self.r = S.get(self.url, stream=True, timeout=120, verify=True, headers=h)
|
| 62 |
+
self.r.raise_for_status()
|
| 63 |
+
if self.pos and self.r.status_code != 206:
|
| 64 |
+
self.r.close(); raise IOError(f"server ignored Range at {self.pos}")
|
| 65 |
+
self.r.raw.decode_content = False
|
| 66 |
+
def read(self, n=-1):
|
| 67 |
+
for attempt in range(self.retries + 1):
|
| 68 |
+
try:
|
| 69 |
+
b = self.r.raw.read(n); self.pos += len(b); return b
|
| 70 |
+
except Exception as e:
|
| 71 |
+
if attempt >= self.retries: raise
|
| 72 |
+
wait = min(300, 10 * 2 ** attempt)
|
| 73 |
+
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)
|
| 74 |
+
try: self.r.close()
|
| 75 |
+
except Exception: pass
|
| 76 |
+
time.sleep(wait)
|
| 77 |
+
try: self._open()
|
| 78 |
+
except Exception as e2: print(f"reopen failed: {e2}", flush=True)
|
| 79 |
+
def close(self):
|
| 80 |
+
try: self.r.close()
|
| 81 |
+
except Exception: pass
|
| 82 |
+
|
| 83 |
+
def stream(fond, archive):
|
| 84 |
+
url = f"{BASE}{fond}/{archive}"
|
| 85 |
+
raw = ResumableRaw(url)
|
| 86 |
+
try:
|
| 87 |
+
with tarfile.open(fileobj=raw, mode="r|gz") as tf:
|
| 88 |
+
for m in tf:
|
| 89 |
+
if m.isfile() and m.name.endswith(".xml"):
|
| 90 |
+
try: yield parse(tf.extractfile(m).read(), fond, url, archive)
|
| 91 |
+
except etree.XMLSyntaxError: continue
|
| 92 |
+
finally: raw.close()
|
| 93 |
+
|
| 94 |
+
def write_parquet(rows, path):
|
| 95 |
+
import pyarrow as pa, pyarrow.parquet as pq
|
| 96 |
+
pq.write_table(pa.Table.from_pylist(rows), path, compression="zstd")
|
| 97 |
+
|
| 98 |
+
def existing_ids(base):
|
| 99 |
+
import glob, pyarrow.parquet as pq
|
| 100 |
+
ids = set()
|
| 101 |
+
for f in glob.glob(f"{base}.*parquet"):
|
| 102 |
+
ids.update(x for x in pq.read_table(f, columns=["dila_id"]).column(0).to_pylist() if x)
|
| 103 |
+
return ids
|
| 104 |
+
|
| 105 |
+
def save_state(st, path):
|
| 106 |
+
tmp = path + ".tmp"; json.dump(st, open(tmp, "w")); os.replace(tmp, path)
|
| 107 |
+
|
| 108 |
+
def full(out, state_path, check_every=180, batch=2000):
|
| 109 |
+
st = json.load(open(state_path)) if os.path.exists(state_path) else {"done": []}
|
| 110 |
+
st.setdefault("failed", {}); run = dt.datetime.now().strftime("r%Y%m%d%H%M")
|
| 111 |
+
print(f"run {run} start; done={len(st['done'])} failed={len(st['failed'])}", flush=True)
|
| 112 |
+
last = 0
|
| 113 |
+
for fond, cfg in FONDS.items():
|
| 114 |
+
os.makedirs(f"{out}/{cfg}", exist_ok=True)
|
| 115 |
+
for a in list_archives(fond):
|
| 116 |
+
key = f"{fond}/{a}"
|
| 117 |
+
if key in st["done"]: continue
|
| 118 |
+
rows, part, total, skipped = [], 0, 0, 0
|
| 119 |
+
base = f"{out}/{cfg}/{a.replace('.tar.gz','')}"
|
| 120 |
+
seen = existing_ids(base) # partial output from an interrupted run: skip by dila_id
|
| 121 |
+
if seen: print(f"{key}: {len(seen)} ids already staged; new parts tagged .{run}.", flush=True)
|
| 122 |
+
pfx = f"{base}.{run}.part" # run id in name: never overwrites earlier parts
|
| 123 |
+
try:
|
| 124 |
+
for rec in stream(fond, a):
|
| 125 |
+
if rec["dila_id"] and rec["dila_id"] in seen: skipped += 1; continue
|
| 126 |
+
rows.append(rec)
|
| 127 |
+
if len(rows) >= batch:
|
| 128 |
+
write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows); part += 1; rows = []
|
| 129 |
+
if time.time() - last > check_every:
|
| 130 |
+
ok, mem, disk = guard(); last = time.time()
|
| 131 |
+
print(f"guard mem={mem:.1f}G disk={disk:.1f}G", flush=True)
|
| 132 |
+
if not ok:
|
| 133 |
+
if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet")
|
| 134 |
+
print("GUARD STOP", flush=True); sys.exit(3)
|
| 135 |
+
if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows)
|
| 136 |
+
except Exception as e:
|
| 137 |
+
if rows: write_parquet(rows, f"{pfx}{part:05d}.parquet"); total += len(rows)
|
| 138 |
+
st["failed"][key] = {"error": f"{type(e).__name__}: {str(e)[:300]}", "run": run, "rows_written": total}
|
| 139 |
+
save_state(st, state_path)
|
| 140 |
+
print(f"FAILED {key} rows={total}: {type(e).__name__}: {str(e)[:200]}; continuing", flush=True)
|
| 141 |
+
continue
|
| 142 |
+
st["done"].append(key); st["failed"].pop(key, None); save_state(st, state_path)
|
| 143 |
+
print(f"done {key} rows={total} skipped_existing={skipped} parts={part + (1 if rows else 0)}", flush=True)
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
ap = argparse.ArgumentParser()
|
| 147 |
+
ap.add_argument("--fond"); ap.add_argument("--archive"); ap.add_argument("--out", required=True)
|
| 148 |
+
ap.add_argument("--limit", type=int, default=20); ap.add_argument("--full", action="store_true")
|
| 149 |
+
ap.add_argument("--state")
|
| 150 |
+
a = ap.parse_args()
|
| 151 |
+
ok, mem, disk = guard()
|
| 152 |
+
if not ok: sys.exit(f"ABORT: MemAvailable={mem:.2f}G disk={disk:.1f}G below thresholds")
|
| 153 |
+
if a.full: full(a.out, a.state)
|
| 154 |
+
else:
|
| 155 |
+
rows = list(stream(a.fond, a.archive))
|
| 156 |
+
write_parquet(rows, f"{a.out}/sample.parquet")
|
| 157 |
+
with open(f"{a.out}/preview.jsonl", "w") as f:
|
| 158 |
+
for r in rows[:a.limit]: f.write(json.dumps({**r, "text": (r["text"] or "")[:500]}, ensure_ascii=False) + "\n")
|
| 159 |
+
print(f"records={len(rows)}")
|
scrapers_and_normalizers/caselaw/scrapers/in_aws/collect.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# IN: AWS Open Data indian-supreme-court-judgments (CC-BY-4.0), keyless S3 HTTPS. PDFs streamed, text extracted in-memory, never stored.
|
| 2 |
+
import sys,os,io,re,json,time,tarfile,subprocess,datetime,requests;sys.path.insert(0,'/workspace/caselaw/scrapers/common')
|
| 3 |
+
from guard import *
|
| 4 |
+
import pyarrow.parquet as pq
|
| 5 |
+
B='/workspace/caselaw'; S3='https://indian-supreme-court-judgments.s3.amazonaws.com'; OUT=B+'/staging/ipfs_india_caselaw'; LOG=B+'/logs/in_aws.log'
|
| 6 |
+
LIC='CC-BY-4.0 (AWS Open Data: indian-supreme-court-judgments, from ecourts/SCI)'
|
| 7 |
+
os.makedirs(OUT,exist_ok=True); st=State(OUT+'/state.json',{'done':[],'members_done':{}})
|
| 8 |
+
H={'User-Agent':'justicedao-caselaw-research/1.0'}
|
| 9 |
+
def get(u,**k):
|
| 10 |
+
for a in range(6):
|
| 11 |
+
try:
|
| 12 |
+
r=requests.get(u,headers=H,timeout=120,**k); r.raise_for_status(); return r
|
| 13 |
+
except Exception as e: log(LOG,'retry',a,u,e); time.sleep(10*(a+1))
|
| 14 |
+
raise RuntimeError(u)
|
| 15 |
+
years=list(range(1950,datetime.date.today().year+1))
|
| 16 |
+
w=PartWriter(OUT+'/in_sc','in_sc',st,'in_sc')
|
| 17 |
+
for y in years:
|
| 18 |
+
key=f'{y}/english'
|
| 19 |
+
if key in st.d['done']: continue
|
| 20 |
+
ok,m,d=guard_ok()
|
| 21 |
+
if not ok: log(LOG,'GUARD STOP',y,m,d); sys.exit(3)
|
| 22 |
+
try: idx=get(f'{S3}/data/tar/year={y}/english/english.index.json').json()
|
| 23 |
+
except Exception: log(LOG,'no index',y); st.d['done'].append(key); st.save(); continue
|
| 24 |
+
meta={}
|
| 25 |
+
try:
|
| 26 |
+
t=pq.read_table(io.BytesIO(get(f'{S3}/metadata/parquet/year={y}/metadata.parquet').content))
|
| 27 |
+
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
|
| 28 |
+
except Exception as e: log(LOG,'no meta',y,e)
|
| 29 |
+
done=set(st.d['members_done'].get(key,[]))
|
| 30 |
+
for part in idx.get('parts',[{'name':'english.tar'}]):
|
| 31 |
+
u=f"{S3}/data/tar/year={y}/english/{part['name']}"
|
| 32 |
+
r=get(u,stream=True); tf=tarfile.open(fileobj=r.raw,mode='r|')
|
| 33 |
+
for mem in tf:
|
| 34 |
+
if not mem.isfile() or not mem.name.lower().endswith('.pdf'): continue
|
| 35 |
+
nm=os.path.basename(mem.name)
|
| 36 |
+
if nm in done: continue
|
| 37 |
+
data=tf.extractfile(mem).read()
|
| 38 |
+
try: txt=subprocess.run(['pdftotext','-enc','UTF-8','-layout','-','-'],input=data,capture_output=True,timeout=120).stdout.decode('utf-8','replace')
|
| 39 |
+
except Exception as e: txt=None; log(LOG,'pdftotext fail',nm,e)
|
| 40 |
+
del data
|
| 41 |
+
pth=re.sub(r'_EN\.pdf$','',nm,flags=re.I); md=meta.get(pth,{})
|
| 42 |
+
row=dict(jurisdiction='IN',court='Supreme Court of India',config='in_sc',ecli=None,court_id=None,chamber=None,
|
| 43 |
+
date=md.get('decision_date'),number=md.get('case_id') or md.get('citation'),title=md.get('title'),text=txt,
|
| 44 |
+
source_url=f'{u}#{nm}',licence=LIC,licence_flag='attribution_required',is_archive=False,archive_name=part['name'],
|
| 45 |
+
retrieved_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),pdf_member=nm,text_extraction='pdftotext',
|
| 46 |
+
**{'in_'+k:v for k,v in md.items() if k not in('title','year')})
|
| 47 |
+
done.add(nm)
|
| 48 |
+
if w.add(row):
|
| 49 |
+
w.flush(lambda: st.d['members_done'].__setitem__(key,sorted(done))); log(LOG,y,'rows total',st.d['rows']['in_sc'])
|
| 50 |
+
ok,m,d=guard_ok()
|
| 51 |
+
if not ok: log(LOG,'GUARD STOP',y,m,d); sys.exit(3)
|
| 52 |
+
r.close()
|
| 53 |
+
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))
|
| 54 |
+
st.d['all_done']=True; st.save(); log(LOG,'ALL DONE',st.d['rows'])
|
scrapers_and_normalizers/courts/collector/archive_resume.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Resume CC archive recovery from state: cached CDX per state, skip URLs already staged. Stage only."""
|
| 3 |
+
import sys,os,json,re,datetime
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import archive_rules as A
|
| 6 |
+
from us_fed import log,sid,now
|
| 7 |
+
O=A.O;ST=O+'/resume_state.json';C=O+'/cdx_cache'
|
| 8 |
+
os.makedirs(C,exist_ok=True)
|
| 9 |
+
def save(s):json.dump(s,open(ST+'.tmp','w'),indent=1);os.replace(ST+'.tmp',ST)
|
| 10 |
+
s=json.load(open(ST)) if os.path.exists(ST) else dict(done=['TN','LA','MI','SD','OK'],todo=['DE','WY'])
|
| 11 |
+
save(s)
|
| 12 |
+
log('RESUME START pid',os.getpid(),s)
|
| 13 |
+
for st in list(s['todo']):
|
| 14 |
+
cf=f'{C}/{st}.json'
|
| 15 |
+
if os.path.exists(cf):best=json.load(open(cf));log('STATE',st,'cdx from cache',len(best))
|
| 16 |
+
else:
|
| 17 |
+
best={};complete=True
|
| 18 |
+
for idx in A.IDX:
|
| 19 |
+
for pat in A.STATES[st]:
|
| 20 |
+
got=False
|
| 21 |
+
for c in A.cdx(idx,pat):
|
| 22 |
+
got=True;u=c['url']
|
| 23 |
+
if not u.startswith('https://'):continue
|
| 24 |
+
if not re.search(r'rule|pdf|download|Statutes|STOKRU|DocumentID',u,re.I):continue
|
| 25 |
+
k=u.split('#')[0]
|
| 26 |
+
if k not in best or c['timestamp']>best[k]['timestamp']:best[k]=dict(c,_idx=idx)
|
| 27 |
+
if best:json.dump(best,open(cf,'w'))
|
| 28 |
+
log('STATE',st,'cdx unique urls',len(best),'cached')
|
| 29 |
+
if not best:
|
| 30 |
+
open(O+'/skips.jsonl','a').write(json.dumps(dict(state=st,reason='no Common Crawl captures matched'))+'\n')
|
| 31 |
+
have=set()
|
| 32 |
+
if os.path.exists(f'{O}/{st}.jsonl'):
|
| 33 |
+
for l in open(f'{O}/{st}.jsonl'):
|
| 34 |
+
try:have.add(json.loads(l)['original_url'])
|
| 35 |
+
except Exception:pass
|
| 36 |
+
n=0
|
| 37 |
+
with open(f'{O}/{st}.jsonl','a') as o:
|
| 38 |
+
for k,c in sorted(best.items())[:A.CAP]:
|
| 39 |
+
if k in have:continue
|
| 40 |
+
fn=f'{O}/files/{st}_{sid(k)}';g=A.fetch_warc(c,fn)
|
| 41 |
+
if not g:continue
|
| 42 |
+
sha,nb=g;cap=datetime.datetime.strptime(c['timestamp'],'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat()
|
| 43 |
+
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)
|
| 44 |
+
log('STATE',st,'new rows',n,'total',len(have))
|
| 45 |
+
s['todo'].remove(st);s['done'].append(st);save(s)
|
| 46 |
+
log('ARCHIVE RESUME DONE')
|
scrapers_and_normalizers/courts/collector/archive_rules.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Archive recovery of state court rules via Common Crawl (CDX + WARC range). Stage only. Wayback content host unreachable (probe 2026-10-27)."""
|
| 3 |
+
import sys,os,json,re,time,zlib,hashlib,urllib.request,urllib.parse,datetime
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import us_fed as U
|
| 6 |
+
from us_fed import log,memguard,sid,now
|
| 7 |
+
O='/workspace/courts/staging/state_rules_archive';os.makedirs(O+'/files',exist_ok=True)
|
| 8 |
+
UA='Mozilla/5.0 (compatible; court-research-collector/0.1)'
|
| 9 |
+
IDX=['CC-MAIN-2026-43','CC-MAIN-2026-30','CC-MAIN-2025-51']
|
| 10 |
+
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']}
|
| 11 |
+
OKSEL={'OK':re.compile(r'STOKRU|ftdb=STOKRU|DocumentID',re.I)}
|
| 12 |
+
CAP=int(os.environ.get('ARCH_CAP','300'));DELAY=6;last=0
|
| 13 |
+
def get(u,rng=None,tries=5):
|
| 14 |
+
global last
|
| 15 |
+
for i in range(tries):
|
| 16 |
+
memguard();w=last+DELAY-time.time()
|
| 17 |
+
if w>0:time.sleep(w)
|
| 18 |
+
last=time.time();h={'User-Agent':UA}
|
| 19 |
+
if rng:h['Range']=rng
|
| 20 |
+
try:return urllib.request.urlopen(urllib.request.Request(u,headers=h),timeout=120)
|
| 21 |
+
except urllib.error.HTTPError as e:
|
| 22 |
+
if e.code in(429,500,502,503,504):b=60*(2**i);log('BACKOFF',e.code,b,u[:100]);time.sleep(b);continue
|
| 23 |
+
if e.code==404:return None
|
| 24 |
+
log('HTTP_ERR',e.code,u[:120]);return None
|
| 25 |
+
except Exception as e:log('NET_ERR',repr(e)[:120],u[:100]);time.sleep(30)
|
| 26 |
+
return None
|
| 27 |
+
def cdx(idx,pat):
|
| 28 |
+
u=f'https://index.commoncrawl.org/{idx}-index?'+urllib.parse.urlencode(dict(url=pat+'*',output='json',filter='status:200'))
|
| 29 |
+
r=get(u)
|
| 30 |
+
if not r:return
|
| 31 |
+
for l in r:
|
| 32 |
+
try:yield json.loads(l)
|
| 33 |
+
except Exception:pass
|
| 34 |
+
def fetch_warc(c,fn):
|
| 35 |
+
off,ln=int(c['offset']),int(c['length'])
|
| 36 |
+
r=get('https://data.commoncrawl.org/'+c['filename'],rng=f'bytes={off}-{off+ln-1}')
|
| 37 |
+
if not r:return None
|
| 38 |
+
d=zlib.decompressobj(16+zlib.MAX_WBITS);buf=b'';hdr_done=False;h=hashlib.sha256();n=0;out=open(fn,'wb')
|
| 39 |
+
while True:
|
| 40 |
+
ch=r.read(65536)
|
| 41 |
+
if not ch:break
|
| 42 |
+
x=d.decompress(ch)
|
| 43 |
+
if not hdr_done:
|
| 44 |
+
buf+=x;p=buf.find(b'\r\n\r\n')
|
| 45 |
+
q=buf.find(b'\r\n\r\n',p+4) if p>=0 else -1
|
| 46 |
+
if q<0:continue
|
| 47 |
+
x=buf[q+4:];hdr_done=True;buf=b''
|
| 48 |
+
h.update(x);out.write(x);n+=len(x)
|
| 49 |
+
out.close();return h.hexdigest(),n
|
| 50 |
+
if __name__=='__main__':
|
| 51 |
+
only=sys.argv[1:] or list(STATES)
|
| 52 |
+
log('ARCHIVE START pid',os.getpid(),only,'cap',CAP)
|
| 53 |
+
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()
|
| 54 |
+
for st in only:
|
| 55 |
+
best={}
|
| 56 |
+
for idx in IDX:
|
| 57 |
+
for pat in STATES[st]:
|
| 58 |
+
for c in cdx(idx,pat):
|
| 59 |
+
u=c['url']
|
| 60 |
+
if not u.startswith('https://'):continue
|
| 61 |
+
if st in OKSEL and not OKSEL[st].search(u):continue
|
| 62 |
+
if not re.search(r'rule|pdf|download|Statutes|STOKRU|DocumentID',u,re.I):continue
|
| 63 |
+
k=u.split('#')[0]
|
| 64 |
+
if k not in best or c['timestamp']>best[k]['timestamp']:best[k]=dict(c,_idx=idx)
|
| 65 |
+
log('STATE',st,'cdx unique urls',len(best))
|
| 66 |
+
if not best:sk.write(json.dumps(dict(state=st,reason='no Common Crawl captures matched'))+'\n');sk.flush();continue
|
| 67 |
+
n=0
|
| 68 |
+
with open(f'{O}/{st}.jsonl','a') as o:
|
| 69 |
+
for k,c in sorted(best.items(),key=lambda kv:kv[0])[:CAP]:
|
| 70 |
+
fn=f'{O}/files/{st}_{sid(k)}';g=fetch_warc(c,fn)
|
| 71 |
+
if not g:continue
|
| 72 |
+
sha,nb=g;ts=c['timestamp'];cap=datetime.datetime.strptime(ts,'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat()
|
| 73 |
+
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
|
| 74 |
+
log('STATE',st,'rows',n)
|
| 75 |
+
log('ARCHIVE DONE')
|
scrapers_and_normalizers/courts/collector/cc_gapfill.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CC gap-fill for state/county courthouse data: AL ND WV PA. CDX + WARC range fetch only (index.commoncrawl.org, data.commoncrawl.org).
|
| 3 |
+
Stage only, no push. memguard 4.2G/3 strikes -> exit 3. disk free<12G -> exit 4. Every row: source=archive, archive_source=commoncrawl."""
|
| 4 |
+
import sys,os,json,re,time,zlib,hashlib,datetime,urllib.parse as up,collections
|
| 5 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 6 |
+
import requests
|
| 7 |
+
from bs4 import BeautifulSoup
|
| 8 |
+
import state_county as S
|
| 9 |
+
B='/workspace/courts';O=f'{B}/staging/state_county_cc';os.makedirs(O,exist_ok=True)
|
| 10 |
+
S.LOG=open(f'{B}/logs/cc_gapfill.log','a',buffering=1);log=S.log
|
| 11 |
+
HL=open(f'{O}/page_filter_log.jsonl','a',buffering=1)
|
| 12 |
+
IDX=['CC-MAIN-2026-43','CC-MAIN-2026-30','CC-MAIN-2025-51']
|
| 13 |
+
HOSTS={'AL':['judicial.alabama.gov','www.alacourt.gov','alacourt.gov'],'ND':['www.ndcourts.gov','ndcourts.gov'],
|
| 14 |
+
'WV':['www.courtswv.gov','courtswv.gov'],'PA':['www.pacourts.us','pacourts.us'],
|
| 15 |
+
'CO':['www.coloradojudicial.gov','coloradojudicial.gov'],'MS':['courts.ms.gov','www.courts.ms.gov'],'MN':['mncourts.gov','www.mncourts.gov'],
|
| 16 |
+
'NM':['nmcourts.gov','www.nmcourts.gov'],'FL':['www.flcourts.gov','flcourts.gov']}
|
| 17 |
+
STATES=sys.argv[1:] or ['AL','ND','WV','PA']
|
| 18 |
+
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]
|
| 19 |
+
sess=requests.Session();sess.headers['User-Agent']='Mozilla/5.0 (compatible; justicedao-court-research/0.2; archive gap-fill)'
|
| 20 |
+
def guard():
|
| 21 |
+
while True:
|
| 22 |
+
ma=S.memavail()
|
| 23 |
+
if ma>=MEMFLOOR: break
|
| 24 |
+
strikes[0]+=1;S.strikes[0]=strikes[0];log(f'MEMGUARD strike {strikes[0]} MemAvailable={ma:.2f}G');S.memstrike_top5()
|
| 25 |
+
if strikes[0]>=MAXSTRIKES: log(f'MEMGUARD {MAXSTRIKES} strikes: clean stop');sys.exit(3)
|
| 26 |
+
time.sleep(60)
|
| 27 |
+
st=os.statvfs(B)
|
| 28 |
+
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)
|
| 29 |
+
def get(u,rng=None,stream=False):
|
| 30 |
+
for i in range(6):
|
| 31 |
+
guard();w=last[0]+DELAY-time.time()
|
| 32 |
+
if w>0: time.sleep(w)
|
| 33 |
+
last[0]=time.time();h={'Range':rng} if rng else {}
|
| 34 |
+
try:
|
| 35 |
+
r=sess.get(u,headers=h,stream=stream,timeout=(15,60))
|
| 36 |
+
if r.status_code in (429,500,502,503,504):
|
| 37 |
+
b=min(60*2**i,1800);log('BACKOFF',r.status_code,b,u[:110]);r.close();time.sleep(b);continue
|
| 38 |
+
if r.status_code not in (200,206): log('HTTP',r.status_code,u[:110]);r.close();return None
|
| 39 |
+
return r
|
| 40 |
+
except requests.RequestException as e:
|
| 41 |
+
b=min(30*2**i,900);log('NETERR',repr(e)[:100],'sleep',b);time.sleep(b)
|
| 42 |
+
log('GIVEUP',u[:110]);return None
|
| 43 |
+
FORM_RX=re.compile(r'\.(pdf|docx?|rtf|xlsx?|odt)$',re.I)
|
| 44 |
+
FORM_HINT=re.compile(r'form',re.I)
|
| 45 |
+
TAB_RX={'judges':re.compile(r'judge|justice|magistrate|roster|bench|biograph',re.I),
|
| 46 |
+
'courthouses':re.compile(r'courthouse|location|directory|county|contact|address|find-?a-?court|district|circuit|magisterial',re.I)}
|
| 47 |
+
NEG=re.compile(r'opinion|calendar|docket|news|press|career|job|employ|search|login|event|rule|order|\?.*page=',re.I)
|
| 48 |
+
def cdx(host):
|
| 49 |
+
best={}
|
| 50 |
+
for idx in IDX:
|
| 51 |
+
u=f'https://index.commoncrawl.org/{idx}-index?'+up.urlencode(dict(url=host+'/*',output='json',filter='status:200',limit='20000'))
|
| 52 |
+
r=get(u,stream=True)
|
| 53 |
+
if not r: continue
|
| 54 |
+
try:
|
| 55 |
+
for l in r.iter_lines():
|
| 56 |
+
try:c=json.loads(l)
|
| 57 |
+
except Exception:continue
|
| 58 |
+
k=c['url'].split('#')[0]
|
| 59 |
+
if not k.startswith('https://'): continue
|
| 60 |
+
if k not in best or c['timestamp']>best[k]['timestamp']: best[k]=dict(c,_idx=idx)
|
| 61 |
+
except Exception as e: log('CDXSTREAMERR',idx,host,repr(e)[:120],'kept partial',len(best))
|
| 62 |
+
r.close()
|
| 63 |
+
return best
|
| 64 |
+
def warc_body(c,limit=None,sink=None):
|
| 65 |
+
off,ln=int(c['offset']),int(c['length'])
|
| 66 |
+
r=get('https://data.commoncrawl.org/'+c['filename'],rng=f'bytes={off}-{off+ln-1}',stream=True)
|
| 67 |
+
if not r: return None
|
| 68 |
+
d=zlib.decompressobj(16+zlib.MAX_WBITS);buf=b'';hd=False;h=hashlib.sha256();n=0;keep=[]
|
| 69 |
+
for ch in r.iter_content(65536):
|
| 70 |
+
x=d.decompress(ch)
|
| 71 |
+
if not hd:
|
| 72 |
+
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
|
| 73 |
+
if q<0: continue
|
| 74 |
+
x=buf[q+4:];hd=True;buf=b''
|
| 75 |
+
h.update(x);n+=len(x)
|
| 76 |
+
if limit is not None and n<=limit: keep.append(x)
|
| 77 |
+
r.close();return h.hexdigest(),n,b''.join(keep)
|
| 78 |
+
def arch(c,sha):
|
| 79 |
+
ts=datetime.datetime.strptime(c['timestamp'],'%Y%m%d%H%M%S').replace(tzinfo=datetime.timezone.utc).isoformat()
|
| 80 |
+
u=c['url'].split('#')[0]
|
| 81 |
+
return dict(source='archive',source_url=u,original_url=u,fetched_at=S.now(),archive_source='commoncrawl',archive_timestamp=ts,
|
| 82 |
+
archive_index=c['_idx'],warc_filename=c['filename'],warc_offset=int(c['offset']),warc_length=int(c['length']),cc_digest=c.get('digest'),
|
| 83 |
+
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',
|
| 84 |
+
transport='https',content_sha256=sha,sha256=sha,coverage='archive_gapfill')
|
| 85 |
+
def page_decision(soup,nrows):
|
| 86 |
+
for x in soup(['script','style','noscript','nav','header','footer']): x.decompose()
|
| 87 |
+
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
|
| 88 |
+
if tw<80: return False,'too_short(<80 words)',tw,ld
|
| 89 |
+
if nrows==0: return False,'no_extractable_rows',tw,ld
|
| 90 |
+
if ld>0.5 and nrows<3: return False,'navigation(link_density>0.5 and <3 rows)',tw,ld
|
| 91 |
+
return True,'kept(rows>0, not nav)',tw,ld
|
| 92 |
+
STF=f'{O}/state.json'
|
| 93 |
+
state=json.load(open(STF)) if os.path.exists(STF) else {'done':[]}
|
| 94 |
+
log('CC GAPFILL START pid',os.getpid(),STATES,'done',state['done'])
|
| 95 |
+
for st in STATES:
|
| 96 |
+
if st in state['done']: continue
|
| 97 |
+
cf=f'{O}/cdx_{st}.json'
|
| 98 |
+
if os.path.exists(cf): best=json.load(open(cf))
|
| 99 |
+
else:
|
| 100 |
+
best={}
|
| 101 |
+
for h in HOSTS[st]: best.update(cdx(h))
|
| 102 |
+
json.dump(best,open(cf,'w'))
|
| 103 |
+
log('STATE',st,'cdx unique https urls',len(best))
|
| 104 |
+
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]
|
| 105 |
+
html=[]
|
| 106 |
+
for k,c in sorted(best.items()):
|
| 107 |
+
if 'html' not in (c.get('mime') or '') or NEG.search(k): continue
|
| 108 |
+
if TAB_RX['judges'].search(k) or TAB_RX['courthouses'].search(k): html.append((k,c))
|
| 109 |
+
html=html[:CAP_HTML]
|
| 110 |
+
out={t:open(f'{O}/{st}_{t}.jsonl','w') for t in ('courts','courthouses','judges','forms')}
|
| 111 |
+
cnt=collections.Counter();courts={}
|
| 112 |
+
for k,c in html:
|
| 113 |
+
g=warc_body(c,limit=MAXB)
|
| 114 |
+
if not g: continue
|
| 115 |
+
sha,n,body=g
|
| 116 |
+
if n>MAXB: HL.write(json.dumps(dict(state=st,url=k,keep=False,reason='too_large(>5MB)'))+'\n');continue
|
| 117 |
+
soup=BeautifulSoup(body,'html.parser');A=arch(c,sha)
|
| 118 |
+
js=S.ext_judges(st,k,sha,soup);ch=S.ext_courthouses(st,k,sha,soup)
|
| 119 |
+
keep,why,tw,ld=page_decision(BeautifulSoup(body,'html.parser'),len(js)+len(ch))
|
| 120 |
+
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')
|
| 121 |
+
if not keep: cnt['pages_dropped']+=1;continue
|
| 122 |
+
cnt['pages_kept']+=1
|
| 123 |
+
for t,rs in (('judges',js),('courthouses',ch)):
|
| 124 |
+
for r in rs:
|
| 125 |
+
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))
|
| 126 |
+
if t!='judges': r.pop('role_type')
|
| 127 |
+
out[t].write(json.dumps(r,ensure_ascii=False)+'\n');cnt[t]+=1
|
| 128 |
+
nm=r.get('court_name') if t=='judges' else r.get('name')
|
| 129 |
+
if r.get('court_id') and nm and r['court_id'] not in courts:
|
| 130 |
+
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)
|
| 131 |
+
for r in courts.values(): out['courts'].write(json.dumps(r,ensure_ascii=False)+'\n');cnt['courts']+=1
|
| 132 |
+
for k,c in forms:
|
| 133 |
+
g=warc_body(c,limit=0)
|
| 134 |
+
if not g: continue
|
| 135 |
+
sha,n,_=g;A=arch(c,sha);fn=up.unquote(up.urlparse(k).path.rsplit('/',1)[-1]);m=S.FNUM.search(fn)
|
| 136 |
+
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',
|
| 137 |
+
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
|
| 138 |
+
for f in out.values(): f.close()
|
| 139 |
+
log('STATE',st,'DONE',dict(cnt));state['done'].append(st);state[st]=dict(cnt)
|
| 140 |
+
json.dump(state,open(STF+'.tmp','w'));os.replace(STF+'.tmp',STF)
|
| 141 |
+
log('CC GAPFILL DONE',state)
|
scrapers_and_normalizers/courts/collector/cc_gapfill_review.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,collections,os,hashlib,random
|
| 2 |
+
B='/workspace/courts';O=f'{B}/staging/state_county_cc';R=f'{B}/review_state_county/cc_gapfill';os.makedirs(R,exist_ok=True)
|
| 3 |
+
c=collections.Counter();bad=collections.Counter();samp={}
|
| 4 |
+
REQ=['source','archive_source','archive_timestamp','original_url','sha256','warc_filename','warc_offset','warc_length']
|
| 5 |
+
for f in sorted(glob.glob(f'{O}/[A-Z][A-Z]_*.jsonl')):
|
| 6 |
+
st,t=os.path.basename(f)[:-6].split('_',1);rows=[json.loads(l) for l in open(f)];c[(st,t)]=len(rows)
|
| 7 |
+
for r in rows:
|
| 8 |
+
for k in REQ:
|
| 9 |
+
if r.get(k) in (None,''): bad[(st,t,k)]+=1
|
| 10 |
+
if r.get('source')!='archive' or r.get('archive_source')!='commoncrawl': bad[(st,t,'flag')]+=1
|
| 11 |
+
if rows: samp[f'{st}_{t}']=random.sample(rows,min(2,len(rows)))
|
| 12 |
+
pf=collections.Counter()
|
| 13 |
+
if os.path.exists(f'{O}/page_filter_log.jsonl'):
|
| 14 |
+
for l in open(f'{O}/page_filter_log.jsonl'): d=json.loads(l);pf[(d['state'],d['reason'])]+=1
|
| 15 |
+
md=['# CC gap-fill review (AL ND WV PA CO MS MN NM FL — 9 states) — STAGED, NOT PUSHED','','## Rows by state x table']+[f'- {s} {t}: {n}' for (s,t),n in sorted(c.items())]+['','## Page filter (index/nav heuristic) by state x reason']+[f'- {s} {r}: {n}' for (s,r),n in sorted(pf.items())]+['','Heuristic: drop HTML page if <80 words (scripts/nav/header/footer stripped), or no judge/courthouse rows extracted, or link_density>0.5 with <3 rows. Forms: archived file URLs with form in path and doc extension, sha256 of WARC payload only, not stored.','','## Validation (missing required archive fields)',str(dict(bad)) or 'none','','## Samples']+[f'- {k}: '+json.dumps(v,ensure_ascii=False)[:1500] for k,v in samp.items()]
|
| 16 |
+
open(f'{R}/REVIEW.md','w').write('\n'.join(md)+'\n')
|
| 17 |
+
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)
|
| 18 |
+
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']))
|
| 19 |
+
print(md[:20])
|
scrapers_and_normalizers/courts/collector/dedupe_stage_archive.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,hashlib,collections,glob
|
| 2 |
+
B='/workspace/courts';RV=f'{B}/review_state_rules_archive';H=f'{B}/hf_stage/data/state_rules.jsonl'
|
| 3 |
+
nu=lambda u:(u or '').strip().lower().split('#')[0].rstrip('/').replace('http://','https://')
|
| 4 |
+
sh=set();urls=set();th=set()
|
| 5 |
+
for l in open(H):
|
| 6 |
+
r=json.loads(l);rec=r['record']
|
| 7 |
+
for k in('content_sha256','file_sha256'):
|
| 8 |
+
if rec.get(k):sh.add(rec[k])
|
| 9 |
+
for k in('file_url','original_url'):
|
| 10 |
+
if rec.get(k):urls.add(nu(rec[k]))
|
| 11 |
+
if rec.get('file_url') is None and rec.get('source_url'):urls.add(nu(rec['source_url'])) # page-level rows
|
| 12 |
+
t=rec.get('full_text') or rec.get('text')
|
| 13 |
+
if t:th.add(hashlib.sha256(t.encode()).hexdigest())
|
| 14 |
+
seen=set();out=[];log=[];c=collections.Counter()
|
| 15 |
+
for l in open(f'{RV}/filter_survivors.jsonl'):
|
| 16 |
+
r=json.loads(l);st=r['subdivision_iso'][3:];u=nu(r['original_url'])
|
| 17 |
+
why=('dup_hf_sha256' if r['content_sha256'] in sh or r['file_sha256'] in sh else
|
| 18 |
+
'dup_hf_url' if u in urls or nu(r['source_url']) in urls else
|
| 19 |
+
'dup_hf_text_sha256' if r['text_sha256'] in th else
|
| 20 |
+
'dup_within_batch' if r['content_sha256'] in seen or r['text_sha256'] in seen else None)
|
| 21 |
+
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'))
|
| 22 |
+
if why:continue
|
| 23 |
+
seen|={r['content_sha256'],r['text_sha256']}
|
| 24 |
+
rec={k:v for k,v in r.items() if k!='local_path'}
|
| 25 |
+
out.append(dict(subdivision_iso=r['subdivision_iso'],license='see source terms',archive_source='commoncrawl',source_collection='commoncrawl_archive_20261028',record=rec))
|
| 26 |
+
with open(f'{RV}/dedupe_log.jsonl','w') as f:
|
| 27 |
+
for x in log:f.write(json.dumps(x)+'\n')
|
| 28 |
+
with open(f'{RV}/archive_new_unique.jsonl','w') as f:
|
| 29 |
+
for x in out:f.write(json.dumps(x)+'\n')
|
| 30 |
+
print(dict(c),len(out))
|
scrapers_and_normalizers/courts/collector/filter_archive.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,re,subprocess,hashlib,collections,os,zipfile
|
| 2 |
+
from bs4 import BeautifulSoup
|
| 3 |
+
B='/workspace/courts'; A=f'{B}/staging/state_rules_archive'; RV=f'{B}/review_state_rules_archive'
|
| 4 |
+
CUE=re.compile(r'\b(?:Rule|RULE|Rules|§|Section|SECTION|Sec\.)\s*\d+[A-Za-z]?(?:[.\-:]\d+)*')
|
| 5 |
+
SUB=re.compile(r'(?m)^\s*\((?:[a-z]|\d{1,2}|[ivx]{1,4})\)\s')
|
| 6 |
+
TITLE=re.compile(r'(?i)\b(rules? of|court rules?|procedure|order amending|amend(?:ment|ing)|administrative (?:order|directive)|standing order|rule \d)')
|
| 7 |
+
def ext(r):
|
| 8 |
+
p=r['local_path'];b=open(p,'rb').read();ld=None
|
| 9 |
+
if b[:5]==b'%PDF-':
|
| 10 |
+
t=subprocess.run(['pdftotext','-layout',p,'-'],capture_output=True,timeout=120).stdout.decode('utf-8','replace');k='pdf'
|
| 11 |
+
elif b[:2]==b'PK':
|
| 12 |
+
try:
|
| 13 |
+
import docx; t='\n'.join(x.text for x in docx.Document(p).paragraphs);k='docx'
|
| 14 |
+
except Exception: t='';k='zip_unparsed'
|
| 15 |
+
elif b.lstrip()[:1]==b'<' or 'html' in r['mime']:
|
| 16 |
+
s=BeautifulSoup(b,'html.parser')
|
| 17 |
+
for x in s(['script','style','noscript','nav','header','footer','form']):x.decompose()
|
| 18 |
+
t=s.get_text('\n');k='html'
|
| 19 |
+
aw=sum(len(a.get_text().split()) for a in s.find_all('a'));tw=len(t.split()) or 1;ld=aw/tw
|
| 20 |
+
else:
|
| 21 |
+
t='';k='binary_unparsed' # .doc/.ppt OLE: no extractor on box
|
| 22 |
+
t=re.sub(r'[ \t]+',' ',re.sub(r'\n\s*\n+','\n\n',t)).strip()
|
| 23 |
+
return k,t,ld
|
| 24 |
+
def decide(r,k,t,ld):
|
| 25 |
+
w=len(t.split());cues=len(CUE.findall(t));subs=len(SUB.findall(t))
|
| 26 |
+
tc=bool(TITLE.search(t[:600]+' '+r['original_url']))
|
| 27 |
+
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)
|
| 28 |
+
if not t: return False,'no_text_extracted',m
|
| 29 |
+
if w<150: return False,'too_short(<150 words)',m
|
| 30 |
+
if ld is not None and ld>0.4: return False,'navigation(link_density>0.4)',m
|
| 31 |
+
blanks=len(re.findall(r'_{5,}',t));m['form_blanks']=blanks
|
| 32 |
+
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
|
| 33 |
+
h=t[:700]
|
| 34 |
+
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
|
| 35 |
+
if re.match(r'(?i)\s*memorandum\b',t): return False,'memorandum_not_rule',m
|
| 36 |
+
if cues+subs>=5: return True,'rule_structure(cues+subsections>=5)',m
|
| 37 |
+
if tc and w>=300 and (ld is None or ld<=0.25): return True,'title_cue+>=300 words+low link density',m
|
| 38 |
+
return False,'no_rule_structure',m
|
| 39 |
+
out=[];log=open(f'{RV}/filter_log.jsonl','w');cnt=collections.Counter()
|
| 40 |
+
for f in sorted(glob.glob(f'{A}/[A-Z][A-Z].jsonl')):
|
| 41 |
+
for l in open(f):
|
| 42 |
+
r=json.loads(l);k,t,ld=ext(r);keep,why,m=decide(r,k,t,ld);st=r['subdivision_iso'][3:]
|
| 43 |
+
cnt[(st,keep)]+=1
|
| 44 |
+
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')
|
| 45 |
+
if keep: r['text']=t;r['text_extraction']=k;r['text_sha256']=hashlib.sha256(t.encode()).hexdigest();out.append(r)
|
| 46 |
+
with open(f'{RV}/filter_survivors.jsonl','w') as o:
|
| 47 |
+
for r in out:o.write(json.dumps(r)+'\n')
|
| 48 |
+
print({f'{s}':(cnt[(s,True)],cnt[(s,False)]) for s in sorted({s for s,_ in cnt})})
|
scrapers_and_normalizers/courts/collector/fixup_phase1.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,re,collections,shutil,os,hashlib,random
|
| 2 |
+
SRC='hf_stage';DST='hf_stage_fixup';REV='review_state_county/phase1_fixup'
|
| 3 |
+
if os.path.exists(DST): shutil.rmtree(DST)
|
| 4 |
+
shutil.copytree(SRC,DST)
|
| 5 |
+
log=open(f'{REV}/rules_applied.log','w')
|
| 6 |
+
RULES=[ # (name, field, regex, role_type) first match wins; applied to court_id-null rows
|
| 7 |
+
('R0_ut_senior_board','court_name',r'^board of senior judges$','senior_judge'),
|
| 8 |
+
('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'),
|
| 9 |
+
('R2_nav_heading','court_name',r'responsibilities of','other'),
|
| 10 |
+
('R3_justice','title',r'justice','justice'),
|
| 11 |
+
('R4_magistrate','title',r'magistrate|commissioner|referee','magistrate'),
|
| 12 |
+
('R5_staff','title',r'clerk|administrator|staff|secretary|director','staff'),
|
| 13 |
+
('R6_judge_seat','court_name',r'^district \d+$|circuit judges|presiding judges','judge'),
|
| 14 |
+
]
|
| 15 |
+
def classify_null(x):
|
| 16 |
+
for n,f,rx,rt in RULES:
|
| 17 |
+
if re.search(rx,(x.get(f) or ''),re.I): return rt,n
|
| 18 |
+
return 'other','R9_default'
|
| 19 |
+
def classify_linked(x):
|
| 20 |
+
t=(x.get('title') or '').lower()
|
| 21 |
+
if 'justice' in t: return 'justice','L1_title_justice'
|
| 22 |
+
if re.search('magistrate|commissioner|referee',t): return 'magistrate','L2_title_magistrate'
|
| 23 |
+
return 'judge','L3_linked_seat'
|
| 24 |
+
before={}
|
| 25 |
+
# (1) AL coverage
|
| 26 |
+
al=collections.Counter()
|
| 27 |
+
for f in ['courts','courthouses','forms','judges']:
|
| 28 |
+
p=f'{DST}/data/{f}.jsonl';rows=[json.loads(l) for l in open(p)];before[f]=len(rows)
|
| 29 |
+
for r in rows:
|
| 30 |
+
if r.get('subdivision_iso')=='US-AL':
|
| 31 |
+
if r.get('coverage')=='complete': r['coverage']='partial_guard_stop';al[f]+=1
|
| 32 |
+
else: al[f+'_untouched_cov_'+str(r.get('coverage'))]+=1
|
| 33 |
+
if f!='judges': open(p,'w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in rows))
|
| 34 |
+
# (2) judges
|
| 35 |
+
p=f'{DST}/data/judges.jsonl';rows=[json.loads(l) for l in open(p)]
|
| 36 |
+
cnt=collections.Counter();bystate=collections.Counter();rulec=collections.Counter()
|
| 37 |
+
for r in rows:
|
| 38 |
+
if r.get('court_id'): rt,n=classify_linked(r)
|
| 39 |
+
else:
|
| 40 |
+
rt,n=classify_null(r);bystate[(r['subdivision_iso'],rt)]+=1
|
| 41 |
+
log.write(f"{r['judge_id']}\t{r['subdivision_iso']}\t{r['court_name']!r}\t{r['title']!r}\t{n}\t{rt}\n")
|
| 42 |
+
r['role_type']=rt;rulec[n]+=1;cnt[(bool(r.get('court_id')),rt)]+=1
|
| 43 |
+
REMOVE={'committee_member','staff','other'}
|
| 44 |
+
keep=[r for r in rows if not (not r.get('court_id') and r['role_type'] in REMOVE)]
|
| 45 |
+
removed=[r for r in rows if r not in keep]
|
| 46 |
+
# names removed that also survive as a seat in same state
|
| 47 |
+
seat={(r['subdivision_iso'],' '.join(r['full_name'].split()).lower()) for r in keep}
|
| 48 |
+
dup=sum(((r['subdivision_iso'],' '.join(r['full_name'].split()).lower()) in seat) for r in removed)
|
| 49 |
+
open(p,'w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in keep))
|
| 50 |
+
open(f'{REV}/removed_judges.jsonl','w').write(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in removed))
|
| 51 |
+
after={f:sum(1 for _ in open(f'{DST}/data/{f}.jsonl')) for f in before}
|
| 52 |
+
# card
|
| 53 |
+
card=open(f'{DST}/README.md').read()
|
| 54 |
+
card+=f"""
|
| 55 |
+
|
| 56 |
+
## Fix-up (staged 2026-10-28, on top of f12c757)
|
| 57 |
+
- Alabama state/county rows: coverage changed `complete` -> `partial_guard_stop` (the AL collection was cut by the memory guard).
|
| 58 |
+
- `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.
|
| 59 |
+
- **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.
|
| 60 |
+
"""
|
| 61 |
+
open(f'{DST}/README.md','w').write(card)
|
| 62 |
+
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]]))
|
| 63 |
+
man=''
|
| 64 |
+
for root,_,fs in os.walk(DST):
|
| 65 |
+
for f in sorted(fs):
|
| 66 |
+
if f=='MANIFEST.sha256':continue
|
| 67 |
+
q=os.path.join(root,f);man+=hashlib.sha256(open(q,'rb').read()).hexdigest()+' '+os.path.relpath(q,DST)+'\n'
|
| 68 |
+
open(f'{DST}/MANIFEST.sha256','w').write(man)
|
| 69 |
+
random.seed(7)
|
| 70 |
+
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'))}
|
| 71 |
+
nl=collections.Counter(r['role_type'] for r in rows if not r.get('court_id'))
|
| 72 |
+
md=["# Phase 1 fix-up review (STAGED, NOT PUSHED)","Base: justicedao/ipfs_us_courts f12c75717a852dc2d81f1f293a7005251c52dd5f. Staged copy: hf_stage_fixup/","",
|
| 73 |
+
"## (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.","",
|
| 74 |
+
"## (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.","",
|
| 75 |
+
"## 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())]+["",
|
| 76 |
+
"## 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)),"",
|
| 77 |
+
"## 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."]
|
| 78 |
+
open(f'{REV}/REVIEW.md','w').write('\n'.join(md)+'\n')
|
| 79 |
+
m=''.join(hashlib.sha256(open(f'{REV}/{f}','rb').read()).hexdigest()+' '+f+'\n' for f in sorted(os.listdir(REV)) if f!='MANIFEST.sha256')
|
| 80 |
+
open(f'{REV}/MANIFEST.sha256','w').write(m)
|
| 81 |
+
print('\n'.join(md))
|
scrapers_and_normalizers/courts/collector/hf_push.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys;sys.path.insert(0,'/workspace/scripts');import _hf_env # sets HF_TOKEN env from existing connector secret; never printed
|
| 2 |
+
from huggingface_hub import HfApi
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts'
|
| 4 |
+
api.create_repo(R,repo_type='dataset',exist_ok=True)
|
| 5 |
+
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)')
|
| 6 |
+
print('COMMIT',c.oid);print('URL',c.commit_url)
|
scrapers_and_normalizers/courts/collector/hf_push2.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env
|
| 2 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts'
|
| 4 |
+
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')
|
| 5 |
+
print('COMMIT',c.oid)
|
| 6 |
+
p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv3');ok=True
|
| 7 |
+
for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'):
|
| 8 |
+
h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256()
|
| 9 |
+
with open(os.path.join(p,f),'rb') as fh:
|
| 10 |
+
for b in iter(lambda:fh.read(1<<20),b''):h2.update(b)
|
| 11 |
+
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 '')
|
| 12 |
+
print('ALL_OK',ok);shutil.rmtree('/tmp/hfv3')
|
scrapers_and_normalizers/courts/collector/hf_push3.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_env
|
| 2 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts'
|
| 4 |
+
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')
|
| 5 |
+
print('COMMIT',c.oid)
|
| 6 |
+
p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv4');ok=True
|
| 7 |
+
for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'):
|
| 8 |
+
h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256()
|
| 9 |
+
with open(os.path.join(p,f),'rb') as fh:
|
| 10 |
+
for b in iter(lambda:fh.read(1<<20),b''):h2.update(b)
|
| 11 |
+
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 '')
|
| 12 |
+
rows=[json.loads(l) for l in open(os.path.join(p,'data/state_rules.jsonl'))]
|
| 13 |
+
a=[r for r in rows if r.get('source_collection')=='commoncrawl_archive_20261028']
|
| 14 |
+
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))
|
| 15 |
+
print('ALL_OK',ok);shutil.rmtree('/tmp/hfv4')
|
scrapers_and_normalizers/courts/collector/hf_push_phase1.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os,hashlib,shutil,json;sys.path.insert(0,'/workspace/scripts');import _hf_env
|
| 2 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts'
|
| 4 |
+
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)')
|
| 5 |
+
print('COMMIT',c.oid,flush=True)
|
| 6 |
+
p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv5');ok=True
|
| 7 |
+
for l in open('/workspace/courts/hf_stage/MANIFEST.sha256'):
|
| 8 |
+
h,f=l.split(None,1);f=f.strip()[2:];h2=hashlib.sha256()
|
| 9 |
+
with open(os.path.join(p,f),'rb') as fh:
|
| 10 |
+
for b in iter(lambda:fh.read(1<<20),b''):h2.update(b)
|
| 11 |
+
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 '')
|
| 12 |
+
print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv5')
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
+
for cfg in ['courts','courthouses','judges','forms']:
|
| 15 |
+
d=load_dataset(R,cfg,split='train',revision=c.oid,cache_dir='/tmp/hfds5')
|
| 16 |
+
n=[r for r in d if r.get('coverage')][:2]
|
| 17 |
+
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])
|
| 18 |
+
shutil.rmtree('/tmp/hfds5',ignore_errors=True)
|
scrapers_and_normalizers/courts/collector/hf_push_phase2.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env
|
| 2 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts';S='/workspace/courts/hf_stage_phase2';PARENT='587b1e2a7e0e6dc3f95380e1c604df629af080e7'
|
| 4 |
+
head=api.dataset_info(R).sha;print('HEAD',head,flush=True)
|
| 5 |
+
assert head==PARENT,'head moved'
|
| 6 |
+
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)')
|
| 7 |
+
print('COMMIT',c.oid,flush=True)
|
| 8 |
+
p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv6');ok=True
|
| 9 |
+
for l in open(S+'/MANIFEST.sha256'):
|
| 10 |
+
h,f=l.split(None,1);f=f.strip();h2=hashlib.sha256()
|
| 11 |
+
with open(os.path.join(p,f),'rb') as fh:
|
| 12 |
+
for b in iter(lambda:fh.read(1<<20),b''):h2.update(b)
|
| 13 |
+
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 '')
|
| 14 |
+
rc=open(os.path.join(p,'ROWCOUNTS.txt')).read()
|
| 15 |
+
for l in rc.split('\n'):
|
| 16 |
+
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)
|
| 17 |
+
print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv6')
|
scrapers_and_normalizers/courts/collector/hf_push_state_rules_schemafix.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os,hashlib,shutil;sys.path.insert(0,'/workspace/scripts');import _hf_env
|
| 2 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 3 |
+
api=HfApi();R='justicedao/ipfs_us_courts';S='/workspace/courts/hf_stage_phase2';PARENT='dca3bf749a865c39badc4fe186608200f6fc29f4'
|
| 4 |
+
head=api.dataset_info(R).sha;print('HEAD',head,flush=True)
|
| 5 |
+
assert head==PARENT,'head moved'
|
| 6 |
+
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)')
|
| 7 |
+
print('COMMIT',c.oid,flush=True)
|
| 8 |
+
p=snapshot_download(R,repo_type='dataset',revision=c.oid,local_dir='/tmp/hfv7');ok=True
|
| 9 |
+
for l in open(S+'/MANIFEST.sha256'):
|
| 10 |
+
h,f=l.split(None,1);f=f.strip();h2=hashlib.sha256()
|
| 11 |
+
with open(os.path.join(p,f),'rb') as fh:
|
| 12 |
+
for b in iter(lambda:fh.read(1<<20),b''):h2.update(b)
|
| 13 |
+
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 '')
|
| 14 |
+
rc=open(os.path.join(p,'ROWCOUNTS.txt')).read()
|
| 15 |
+
for l in rc.split('\n'):
|
| 16 |
+
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)
|
| 17 |
+
print('ALL_OK',ok,flush=True);shutil.rmtree('/tmp/hfv7')
|
scrapers_and_normalizers/courts/collector/phase3gap.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Phase3 gap collector: reuses state_county.py; sitemap-assisted discovery for JS-rendered/thin states. Stage only. GO: COS_GO_COURTS_PHASE3GAP_20261103"""
|
| 3 |
+
import sys,os,re,json,urllib.parse as up
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import state_county as m
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
B=m.BASE; m.ST_DIR=f'{B}/staging/state_county_phase3gap'; m.RV=f'{B}/review_state_county_phase3gap'
|
| 8 |
+
m.LOG=open(f'{B}/logs/phase3gap.log','a',buffering=1); m.BLF=f'{m.ST_DIR}/blocked_hosts.json'
|
| 9 |
+
m.NEVER|=set('CO MS ND NV MN DC MA NC NH NJ NY LA PR TN MO OK'.split())
|
| 10 |
+
STATES='MI SD VT DE MT FL NM GA IN'.split()
|
| 11 |
+
def phase0(st):
|
| 12 |
+
out=f'{m.ST_DIR}/phase0/{st}.json'
|
| 13 |
+
if os.path.exists(out): return
|
| 14 |
+
url=m.landing_urls()[st]; host=up.urlparse(url).netloc
|
| 15 |
+
res={'state':st,'subdivision_iso':f'US-{st}','landing':url,'candidates':{},'chosen':{},'status':'ok','notes':['sitemap-assisted discovery']}
|
| 16 |
+
try:
|
| 17 |
+
L=[]
|
| 18 |
+
f=m.fetch(url)
|
| 19 |
+
if f and f[0].status_code==200 and f[1]:
|
| 20 |
+
L+=m.links(f[0].url,BeautifulSoup(f[1],'lxml')); host=up.urlparse(f[0].url).netloc
|
| 21 |
+
sms=[f'https://{host}/sitemap.xml']
|
| 22 |
+
H=m.gethost(host)
|
| 23 |
+
sms=[l.split(':',1)[1].strip() for l in (H.robots or '').splitlines() if l.lower().startswith('sitemap:')][:2] or sms
|
| 24 |
+
n=0
|
| 25 |
+
while sms and n<4:
|
| 26 |
+
s=sms.pop(0); n+=1; g=m.fetch(s)
|
| 27 |
+
if not g or g[0].status_code!=200: res['notes'].append(f'sitemap {s} unavailable'); continue
|
| 28 |
+
g2=m.fetch(s) if False else g
|
| 29 |
+
body=(g2[1] or b'').decode('utf-8','ignore')
|
| 30 |
+
if not body:
|
| 31 |
+
continue
|
| 32 |
+
locs=re.findall(r'<loc>\s*([^<\s]+)\s*</loc>',body)
|
| 33 |
+
if '<sitemapindex' in body: sms+=[x for x in locs if re.search(r'page|post|content|court',x,re.I)][:3]; continue
|
| 34 |
+
L+=[(x,up.unquote(up.urlparse(x).path).replace('-',' ').replace('/',' ')) for x in locs]
|
| 35 |
+
res['notes'].append(f'{len(L)} candidate links')
|
| 36 |
+
for cat in m.KW:
|
| 37 |
+
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]
|
| 38 |
+
res['candidates'][cat]=[{'score':s,'url':u,'text':t} for s,u,t in c]
|
| 39 |
+
for cand in res['candidates'][cat][:2]:
|
| 40 |
+
if not cand['url'].startswith('https://'): continue
|
| 41 |
+
g=m.fetch(cand['url'])
|
| 42 |
+
if g and g[0].status_code==200: res['chosen'][cat]=g[0].url; break
|
| 43 |
+
except m.HostBlocked as e: res['status']=f'blocked: {e}'
|
| 44 |
+
json.dump(res,open(out,'w'),indent=1); m.log('P3G P0',st,res['status'],res['chosen'])
|
| 45 |
+
def main():
|
| 46 |
+
m.load_blocks(); m.log('P3G START pid',os.getpid(),STATES)
|
| 47 |
+
for st in STATES:
|
| 48 |
+
if m.STOP.is_set(): return m.STOPRC[0]
|
| 49 |
+
phase0(st)
|
| 50 |
+
if m.STOP.is_set(): return m.STOPRC[0]
|
| 51 |
+
m.collect_state(3,st)
|
| 52 |
+
if m.STOP.is_set(): return m.STOPRC[0]
|
| 53 |
+
m.review(3,STATES); return 0
|
| 54 |
+
if __name__=='__main__':
|
| 55 |
+
try: rc=main()
|
| 56 |
+
except Exception:
|
| 57 |
+
import traceback; m.log('CRASH',traceback.format_exc()); rc=1
|
| 58 |
+
m.log('P3G EXIT rc',rc); sys.exit(rc)
|
scrapers_and_normalizers/courts/collector/procedure_rules_collect.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Memsafe wrapper for state_procedure_rules_scraper source registry (CoS GO 2026-11-04).
|
| 3 |
+
Reads the scraper's per-state source tables via AST (no import: no fallbacks, no scrape_state_laws,
|
| 4 |
+
no IPFS cache, no curl). Single worker, HTTPS only, TLS verify on, robots honored, >=10s/host,
|
| 5 |
+
stop host on first 403/429/challenge, no retries. Stores url+sha256+metadata only."""
|
| 6 |
+
import ast,hashlib,json,os,re,shutil,sys,threading,time,urllib.parse as up,urllib.robotparser as rp
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import requests
|
| 9 |
+
SRC='/workspace/ipfs_datasets_py_latest/ipfs_datasets_py/processors/legal_scrapers/state_procedure_rules_scraper.py'
|
| 10 |
+
OUT=os.environ.get('PR_OUT','/workspace/courts/staging/procedure_rules'); os.makedirs(OUT,exist_ok=True)
|
| 11 |
+
LOG=open(os.environ.get('PR_LOG','/workspace/courts/logs/procedure_rules.log'),'a',buffering=1)
|
| 12 |
+
UA='justicedao-courts-collector/1.0 (public court data; polite 1 req/10s)'
|
| 13 |
+
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())
|
| 14 |
+
PRIVATE=('westlaw.com','lexis','casetext','justia.com','findlaw','fastcase')
|
| 15 |
+
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'))
|
| 16 |
+
MINDELAY=10.0; STOP=threading.Event(); RC=[0]
|
| 17 |
+
def now(): return datetime.now().astimezone().isoformat(timespec='seconds')
|
| 18 |
+
def log(*a): LOG.write(now()+' '+' '.join(map(str,a))+'\n')
|
| 19 |
+
def memavail(): return int(next(l for l in open('/proc/meminfo') if l.startswith('MemAvailable')).split()[1])/1048576
|
| 20 |
+
def guard():
|
| 21 |
+
s=0
|
| 22 |
+
while not STOP.is_set():
|
| 23 |
+
m=memavail(); d=shutil.disk_usage('/workspace').free/2**30
|
| 24 |
+
if d<DISKFLOOR: log('DISKGUARD',f'{d:.1f}G'); RC[0]=4; STOP.set(); return
|
| 25 |
+
if m<MEMFLOOR: s+=1; log('MEMGUARD strike',s,f'{m:.2f}G')
|
| 26 |
+
else: s=0
|
| 27 |
+
if s>=MAXSTRIKES: log('MEMGUARD 3 strikes: clean stop'); RC[0]=3; STOP.set(); return
|
| 28 |
+
time.sleep(20)
|
| 29 |
+
def sources():
|
| 30 |
+
t=ast.parse(open(SRC).read()); res={}
|
| 31 |
+
for n in t.body:
|
| 32 |
+
tg=n.targets[0] if isinstance(n,ast.Assign) else (n.target if isinstance(n,ast.AnnAssign) else None)
|
| 33 |
+
if not isinstance(tg,ast.Name) or n.value is None: continue
|
| 34 |
+
mm=re.match(r'_([A-Z]{2})_',tg.id)
|
| 35 |
+
if not mm: continue
|
| 36 |
+
try: v=ast.literal_eval(n.value)
|
| 37 |
+
except Exception: continue
|
| 38 |
+
st=mm.group(1); items=[]
|
| 39 |
+
if isinstance(v,str) and v.startswith('http'): items=[{'name':tg.id,'url':v}]
|
| 40 |
+
elif isinstance(v,list): items=[dict(x,_var=tg.id) for x in v if isinstance(x,dict) and isinstance(x.get('url'),str)]
|
| 41 |
+
for it in items: res.setdefault(st,[]).append(it)
|
| 42 |
+
return res
|
| 43 |
+
HOSTS={}; BLK=f'{OUT}/blocked_hosts.json'
|
| 44 |
+
blocked=json.load(open(BLK)) if os.path.exists(BLK) else {}
|
| 45 |
+
def hostinfo(h):
|
| 46 |
+
if h in HOSTS: return HOSTS[h]
|
| 47 |
+
H={'last':0,'delay':MINDELAY,'rp':None}; HOSTS[h]=H
|
| 48 |
+
wait(H)
|
| 49 |
+
try:
|
| 50 |
+
r=requests.get(f'https://{h}/robots.txt',headers={'User-Agent':UA},timeout=30); H['last']=time.time()
|
| 51 |
+
log('ROBOTS',h,r.status_code)
|
| 52 |
+
if r.status_code in (403,429): block(h,f'robots {r.status_code}')
|
| 53 |
+
elif r.status_code==200:
|
| 54 |
+
p=rp.RobotFileParser(); p.parse(r.text.splitlines()); H['rp']=p
|
| 55 |
+
cd=p.crawl_delay(UA) or p.crawl_delay('*')
|
| 56 |
+
if cd: H['delay']=max(MINDELAY,float(cd))
|
| 57 |
+
except requests.RequestException as e: H['last']=time.time(); log('ROBOTSERR',h,type(e).__name__)
|
| 58 |
+
return H
|
| 59 |
+
def wait(H):
|
| 60 |
+
dt=H['last']+H['delay']-time.time()
|
| 61 |
+
while dt>0 and not STOP.is_set(): time.sleep(min(dt,5)); dt=H['last']+H['delay']-time.time()
|
| 62 |
+
def block(h,why): blocked[h]=why; json.dump(blocked,open(BLK,'w'),indent=1); log('BLOCK',h,why)
|
| 63 |
+
CHAL=re.compile(rb'captcha|cf-challenge|challenge-platform|Just a moment|Access Denied|Request Rejected|incapsula|px-captcha',re.I)
|
| 64 |
+
def fetch(url):
|
| 65 |
+
p=up.urlparse(url); h=p.netloc.lower()
|
| 66 |
+
if p.scheme!='https': return None,'non_https_skipped'
|
| 67 |
+
if any(x in h for x in PRIVATE): return None,'private_publisher_skipped'
|
| 68 |
+
if h in blocked: return None,'host_blocked'
|
| 69 |
+
H=hostinfo(h)
|
| 70 |
+
if h in blocked: return None,'host_blocked'
|
| 71 |
+
if H['rp'] and not H['rp'].can_fetch(UA,url): return None,'robots_disallow'
|
| 72 |
+
wait(H)
|
| 73 |
+
if STOP.is_set(): return None,'stopped'
|
| 74 |
+
try:
|
| 75 |
+
r=requests.get(url,headers={'User-Agent':UA},timeout=90,stream=True,verify=True); H['last']=time.time()
|
| 76 |
+
sha=hashlib.sha256(); n=0; head=b''
|
| 77 |
+
for c in r.iter_content(65536):
|
| 78 |
+
sha.update(c); n+=len(c)
|
| 79 |
+
if len(head)<20000: head+=c[:20000-len(head)]
|
| 80 |
+
if n>80*2**20: break
|
| 81 |
+
r.close()
|
| 82 |
+
except requests.RequestException as e: H['last']=time.time(); log('NETERR',url,type(e).__name__); return None,'neterr'
|
| 83 |
+
log('GET',r.status_code,n,url)
|
| 84 |
+
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):
|
| 85 |
+
block(h,f'{r.status_code} at {url}'); return None,f'blocked_{r.status_code}'
|
| 86 |
+
if r.status_code!=200: return None,f'http_{r.status_code}'
|
| 87 |
+
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'
|
| 88 |
+
def fam(it):
|
| 89 |
+
s=(it.get('name','')+' '+it.get('_var','')+' '+it['url']).lower()
|
| 90 |
+
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'
|
| 91 |
+
def main(states):
|
| 92 |
+
srcs=sources(); ck=f'{OUT}/ckpt.json'; C=json.load(open(ck)) if os.path.exists(ck) else {'done':[]}
|
| 93 |
+
allst=sorted(srcs); inc=[s for s in allst if s not in EXCL]; exc=[s for s in allst if s in EXCL]
|
| 94 |
+
if states: inc=[s for s in states if s in inc]
|
| 95 |
+
json.dump({'included':inc,'excluded_policy':exc,'private_skipped':PRIVATE},open(f'{OUT}/plan.json','w'),indent=1)
|
| 96 |
+
log('PR START pid',os.getpid(),'states',inc,'excluded',exc)
|
| 97 |
+
threading.Thread(target=guard,daemon=True).start()
|
| 98 |
+
for st in inc:
|
| 99 |
+
if STOP.is_set(): break
|
| 100 |
+
if st in C['done']: continue
|
| 101 |
+
rows=[];cnt={}
|
| 102 |
+
for it in srcs[st]:
|
| 103 |
+
if STOP.is_set(): break
|
| 104 |
+
meta,status=fetch(it['url']); cnt[status]=cnt.get(status,0)+1
|
| 105 |
+
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','')})
|
| 106 |
+
if STOP.is_set(): log('STATE',st,'interrupted',cnt); break
|
| 107 |
+
with open(f'{OUT}/{st}.jsonl','w') as f:
|
| 108 |
+
for r in rows: f.write(json.dumps(r,sort_keys=True)+'\n')
|
| 109 |
+
C['done'].append(st); C[st]=cnt; json.dump(C,open(ck,'w'),indent=1); log('STATE',st,'DONE',cnt)
|
| 110 |
+
STOP.set(); return RC[0]
|
| 111 |
+
if __name__=='__main__': sys.exit(main(sys.argv[1:]))
|
scrapers_and_normalizers/courts/collector/resume.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,json,os
|
| 2 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 3 |
+
import stage2 as S, us_fed as U
|
| 4 |
+
st=sys.argv[1];ST='/workspace/courts/staging'
|
| 5 |
+
def rd(f):return [json.loads(l) for l in open(f) if l.strip()] if os.path.exists(f) else []
|
| 6 |
+
if st=='courthouses':
|
| 7 |
+
courts=rd(ST+'/courts.jsonl') or S.courts_retry()
|
| 8 |
+
done={r['court_id'] for r in rd(ST+'/courthouses.jsonl')}|{S.sid('url',r['url']) for r in rd(ST+'/skips.jsonl')}
|
| 9 |
+
# resume after last court with rows (courts processed in order)
|
| 10 |
+
last=max([i for i,c in enumerate(courts) if c['court_id'] in done],default=-1)
|
| 11 |
+
U.log('resume courthouses from index',last+1,'of',len(courts))
|
| 12 |
+
S.courthouses(courts[last+1:])
|
| 13 |
+
elif st=='ncsc':
|
| 14 |
+
U.ncsc()
|
| 15 |
+
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)')
|
| 16 |
+
elif st=='state_rules':S.state_rules()
|
| 17 |
+
elif st=='review':
|
| 18 |
+
import review;review.build()
|
scrapers_and_normalizers/courts/collector/review.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,os,hashlib,collections,csv,random
|
| 2 |
+
C='/workspace/courts';ST=C+'/staging';RV=C+'/review'
|
| 3 |
+
def build():
|
| 4 |
+
os.makedirs(RV,exist_ok=True);S=json.load(open(C+'/schema.json'))['tables']
|
| 5 |
+
tmap={'judges':'judges','courts':'courts','courthouses':'courthouses','forms':'forms','rules':'rules','ncsc_state_links':None}
|
| 6 |
+
counts={};val={};samp={};tr=collections.Counter();lic=collections.Counter();rob=collections.Counter()
|
| 7 |
+
for f in sorted(glob.glob(ST+'/*.jsonl')):
|
| 8 |
+
n=os.path.basename(f)[:-6];rows=[json.loads(l) for l in open(f) if l.strip()];counts[n]=len(rows)
|
| 9 |
+
samp[n]=random.Random(0).sample(rows,min(5,len(rows)))
|
| 10 |
+
for r in rows:tr[r.get('transport')]+=1;lic[r.get('license')]+=1;rob[r.get('robots_note')]+=1
|
| 11 |
+
t=tmap.get(n)
|
| 12 |
+
if t:
|
| 13 |
+
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)
|
| 14 |
+
val[n]=dict(required_fields=len(req),rows=len(rows),missing_field_counts=dict(miss),ok=not miss)
|
| 15 |
+
sr=glob.glob(ST+'/state_rules/**/*.json*',recursive=True);counts['state_rules_files']=len(sr)
|
| 16 |
+
man=open(RV+'/sha256_manifest.csv','w');w=csv.writer(man);w.writerow(['path','bytes','sha256'])
|
| 17 |
+
for p in sorted(glob.glob(ST+'/**/*',recursive=True)):
|
| 18 |
+
if os.path.isfile(p) and '/_home/' not in p:
|
| 19 |
+
h=hashlib.sha256()
|
| 20 |
+
with open(p,'rb') as fh:
|
| 21 |
+
for c in iter(lambda:fh.read(1<<20),b''):h.update(c)
|
| 22 |
+
w.writerow([p,os.path.getsize(p),h.hexdigest()])
|
| 23 |
+
man.close()
|
| 24 |
+
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'))]
|
| 25 |
+
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)
|
| 26 |
+
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)
|
| 27 |
+
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']
|
| 28 |
+
open(RV+'/REVIEW.md','w').write('\n'.join(md)+'\n')
|
| 29 |
+
if __name__=='__main__':build()
|
scrapers_and_normalizers/courts/collector/review_archive.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,os,hashlib,csv,collections
|
| 2 |
+
O='/workspace/courts/staging/state_rules_archive';RV='/workspace/courts/review_state_rules_archive';os.makedirs(RV,exist_ok=True)
|
| 3 |
+
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']
|
| 4 |
+
cnt={};rng={};miss=collections.Counter();samp={};bad=collections.Counter()
|
| 5 |
+
for f in sorted(glob.glob(O+'/[A-Z][A-Z].jsonl')):
|
| 6 |
+
st=os.path.basename(f)[:2];ts=[];n=0
|
| 7 |
+
for l in open(f):
|
| 8 |
+
r=json.loads(l);n+=1;miss.update(k for k in S if k not in r);ts.append(r['archive_timestamp'])
|
| 9 |
+
if r.get('source')!='archive' or r.get('archive_source')!='commoncrawl':bad[st]+=1
|
| 10 |
+
if n<=2:samp.setdefault(st,[]).append(r)
|
| 11 |
+
cnt[st]=n;rng[st]=[min(ts),max(ts)] if ts else None
|
| 12 |
+
w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256'])
|
| 13 |
+
for p in sorted(glob.glob(O+'/**/*',recursive=True)):
|
| 14 |
+
if os.path.isfile(p):
|
| 15 |
+
h=hashlib.sha256()
|
| 16 |
+
with open(p,'rb') as fh:
|
| 17 |
+
for c in iter(lambda:fh.read(1<<20),b''):h.update(c)
|
| 18 |
+
w.writerow([p,os.path.getsize(p),h.hexdigest()])
|
| 19 |
+
sk=[json.loads(l) for l in open(O+'/skips.jsonl')] if os.path.exists(O+'/skips.jsonl') else []
|
| 20 |
+
ok=not miss and not bad
|
| 21 |
+
for k,v in [('row_counts',cnt),('capture_ranges',rng),('samples',samp),('validation',dict(missing=dict(miss),bad_flags=dict(bad),ok=ok)),('skips',sk)]:json.dump(v,open(f'{RV}/{k}.json','w'),indent=1)
|
| 22 |
+
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')
|
scrapers_and_normalizers/courts/collector/review_resume.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,os,hashlib,csv,collections
|
| 2 |
+
O='/workspace/courts/staging/state_rules_rerun';OFF='/workspace/courts/staging/state_rules/official';RV='/workspace/courts/review_state_rules_rerun';os.makedirs(RV,exist_ok=True)
|
| 3 |
+
S=[k for k in json.load(open('/workspace/courts/schema.json'))['tables']['rules'] if not k.startswith('_')]
|
| 4 |
+
def rows(f):return [json.loads(l) for l in open(f)] if os.path.exists(f) else []
|
| 5 |
+
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']}
|
| 6 |
+
cnt={};dd={};miss=collections.Counter();samp={}
|
| 7 |
+
for st in ['KS','NE','DE']:
|
| 8 |
+
allr=rows(f'{O}/{st}.jsonl')+rows(f'{O}/{st}_resume.jsonl');seen=set();uniq=[];dup_orig=dup_int=0
|
| 9 |
+
for r in allr:
|
| 10 |
+
miss.update(k for k in S if k not in r)
|
| 11 |
+
if r['rule_id'] in orig[st] or r['file_sha256'] in orig[st]:dup_orig+=1;continue
|
| 12 |
+
if r['file_sha256'] in seen:dup_int+=1;continue
|
| 13 |
+
seen.add(r['file_sha256']);uniq.append(r)
|
| 14 |
+
with open(f'{RV}/{st}_new_unique.jsonl','w') as o:
|
| 15 |
+
for r in uniq:o.write(json.dumps(r)+'\n')
|
| 16 |
+
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]
|
| 17 |
+
w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256'])
|
| 18 |
+
for p in sorted(glob.glob(O+'/**/*',recursive=True)+glob.glob(RV+'/*_new_unique.jsonl')):
|
| 19 |
+
if os.path.isfile(p):
|
| 20 |
+
h=hashlib.sha256()
|
| 21 |
+
with open(p,'rb') as fh:
|
| 22 |
+
for c in iter(lambda:fh.read(1<<20),b''):h.update(c)
|
| 23 |
+
w.writerow([p,os.path.getsize(p),h.hexdigest()])
|
| 24 |
+
sk=rows(O+'/skips.jsonl')
|
| 25 |
+
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)
|
| 26 |
+
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')
|
scrapers_and_normalizers/courts/collector/review_sr.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,os,hashlib,csv,collections
|
| 2 |
+
O=os.environ.get('SR_OUT','/workspace/courts/staging/state_rules/official');RV=os.environ.get('SR_RV','/workspace/courts/review_state_rules');os.makedirs(RV,exist_ok=True)
|
| 3 |
+
S=[k for k in json.load(open('/workspace/courts/schema.json'))['tables']['rules'] if not k.startswith('_')]
|
| 4 |
+
cnt={};miss=collections.Counter();samp={}
|
| 5 |
+
for f in sorted(glob.glob(O+'/[A-Z][A-Z].jsonl')):
|
| 6 |
+
st=os.path.basename(f)[:2];n=0
|
| 7 |
+
for l in open(f):
|
| 8 |
+
r=json.loads(l);n+=1;miss.update(k for k in S if k not in r)
|
| 9 |
+
if n<=2:samp.setdefault(st,[]).append(r)
|
| 10 |
+
cnt[st]=n
|
| 11 |
+
w=csv.writer(open(RV+'/sha256_manifest.csv','w'));w.writerow(['path','bytes','sha256'])
|
| 12 |
+
for p in sorted(glob.glob(O+'/**/*',recursive=True)):
|
| 13 |
+
if os.path.isfile(p):
|
| 14 |
+
h=hashlib.sha256()
|
| 15 |
+
with open(p,'rb') as fh:
|
| 16 |
+
for c in iter(lambda:fh.read(1<<20),b''):h.update(c)
|
| 17 |
+
w.writerow([p,os.path.getsize(p),h.hexdigest()])
|
| 18 |
+
sk=[json.loads(l) for l in open(O+'/skips.jsonl')] if os.path.exists(O+'/skips.jsonl') else []
|
| 19 |
+
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'))]
|
| 20 |
+
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)
|
| 21 |
+
open(RV+'/errors.txt','w').writelines(errs)
|
| 22 |
+
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')
|
scrapers_and_normalizers/courts/collector/run_archive_resume_waiter.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector; PY=/workspace/venv/bin/python; R=/workspace/courts
|
| 3 |
+
L=$R/logs/archive_resume_waiter.log; LAUNCH=$R/logs/archive_resume_launches.log
|
| 4 |
+
rm -f $R/STOPPED_ARCHIVE_RESUME $R/CAP_HIT_ARCHIVE_RESUME
|
| 5 |
+
echo "$(date -Is) waiter START pid $$" >> $L; echo $$ > $R/ARCHIVE_RESUME_WAITER.pid
|
| 6 |
+
while :; do
|
| 7 |
+
ok=0
|
| 8 |
+
while [ $ok -lt 10 ]; do
|
| 9 |
+
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)
|
| 10 |
+
m=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 11 |
+
if [ $m -ge 4404019 ] && [ $n -lt 3 ]; then ok=$((ok+1)); else ok=0; fi
|
| 12 |
+
echo "$(date -Is) check collectors=$n MemAvailable_kB=$m held_min=$ok" >> $L
|
| 13 |
+
[ $ok -ge 10 ] && break; sleep 60
|
| 14 |
+
done
|
| 15 |
+
cut=$(( $(date +%s) - 21600 )); c=$(awk -v t=$cut '$1>=t' $LAUNCH 2>/dev/null | wc -l)
|
| 16 |
+
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
|
| 17 |
+
echo "$(date +%s) $(date -Is) launch collectors=$n MemAvailable_kB=$m" >> $LAUNCH
|
| 18 |
+
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
|
| 19 |
+
$PY -u archive_resume.py >> $L 2>&1; rc=$?
|
| 20 |
+
echo "$(date -Is) archive_resume rc=$rc" >> $L
|
| 21 |
+
if [ $rc -eq 0 ]; then break; fi
|
| 22 |
+
echo "$(date -Is) rc=$rc (3=memguard)" > $R/STOPPED_ARCHIVE_RESUME
|
| 23 |
+
done
|
| 24 |
+
rm -f $R/STOPPED_ARCHIVE_RESUME; date -Is > $R/ARCHIVE_RESUME_DONE
|
| 25 |
+
$PY -u review_archive.py >> $L 2>&1 && echo "$(date -Is) review built" >> $L && date -Is > $R/review_state_rules_archive/REVIEW_READY
|
scrapers_and_normalizers/courts/collector/run_archive_waiter.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector; PY=/workspace/venv/bin/python
|
| 3 |
+
echo "$(date -Is) waiter START pid $$; waiting for 4160340"
|
| 4 |
+
while kill -0 4160340 2>/dev/null; do sleep 60; done
|
| 5 |
+
echo "$(date -Is) 4160340 exited"
|
| 6 |
+
while :; do
|
| 7 |
+
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)
|
| 8 |
+
m=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 9 |
+
echo "$(date -Is) check collectors=$n MemAvailable_kB=$m"
|
| 10 |
+
if [ $n -lt 3 ] && [ $m -ge 4404019 ]; then break; fi
|
| 11 |
+
sleep 600
|
| 12 |
+
done
|
| 13 |
+
printf "timestamp=$(date -Iseconds)\npid=$$ (waiter/driver; child archive_rules.py)\ncollectors_running_before=$n\nMemAvailable_kB=$m\nscope=Common Crawl archive recovery TN OK LA MI SD DE WY (CDX + WARC range, >=6s/req, backoff on 429/5xx). Wayback content host unreachable -> not used. Stage only to staging/state_rules_archive/, no push.\n" > /workspace/courts/COS_GO_COURTS_STATE_RULES_ARCHIVE
|
| 14 |
+
$PY -u archive_rules.py; rc=$?
|
| 15 |
+
if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_ARCHIVE_RULES; exit 3; fi
|
| 16 |
+
date -Is > /workspace/courts/ARCHIVE_RULES_DONE
|
| 17 |
+
$PY -u review_archive.py && echo "$(date -Is) review built"
|
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-10-29: single CC gap-fill launch, no relaunch. Stage only.
|
| 3 |
+
R=/workspace/courts; cd $R/collector; PY=/workspace/venv/bin/python; L=$R/logs/cc_gapfill_waiter.log
|
| 4 |
+
export SC_MEMFLOOR=3.0 SC_MAXSTRIKES=5
|
| 5 |
+
echo "$(date -Is) GO launch pid $$" >> $L
|
| 6 |
+
nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$?
|
| 7 |
+
echo "$(date -Is) cc_gapfill rc=$rc" >> $L
|
| 8 |
+
if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE
|
| 9 |
+
$PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY
|
| 10 |
+
else echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL; fi
|
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261103.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-11-03 12:26 PT: single CC gap-fill resume, no relaunch. Stage only.
|
| 3 |
+
R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill_waiter.log
|
| 4 |
+
export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20
|
| 5 |
+
ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 6 |
+
if [ $ma -lt 5242880 ]; then echo "$(date -Is) MemAvail<5G, not launching" >> $L; echo "launch gate fail" > $R/STOPPED_CC_GAPFILL_20261103; exit 1; fi
|
| 7 |
+
echo "$(date -Is) GO launch pid $$ (20261103)" >> $L
|
| 8 |
+
nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$?
|
| 9 |
+
echo "$(date -Is) cc_gapfill rc=$rc" >> $L
|
| 10 |
+
if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE
|
| 11 |
+
$PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY
|
| 12 |
+
else echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261103; fi
|
scrapers_and_normalizers/courts/collector/run_cc_gapfill_go_20261104.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-11-04 09:32 PT: single CC gap-fill resume, no relaunch. Stage only.
|
| 3 |
+
R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill_waiter.log
|
| 4 |
+
export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20
|
| 5 |
+
ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 6 |
+
if [ $ma -lt 5242880 ]; then echo "$(date -Is) MemAvail<5G, not launching" >> $L; echo "launch gate fail" > $R/STOPPED_CC_GAPFILL_20261104; exit 1; fi
|
| 7 |
+
echo "$(date -Is) GO launch pid $$ (20261104)" >> $L
|
| 8 |
+
nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $L 2>&1; rc=$?
|
| 9 |
+
echo "$(date -Is) cc_gapfill rc=$rc" >> $L
|
| 10 |
+
if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE
|
| 11 |
+
$PY -u cc_gapfill_review.py >> $L 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY
|
| 12 |
+
else echo "$(date -Is) rc=$rc (3=memguard,4=disk<20G). No relaunch." > $R/STOPPED_CC_GAPFILL_20261104; fi
|
scrapers_and_normalizers/courts/collector/run_cc_gapfill_resume_20261102.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-11-02 21:29 PT: resume CC gap-fill from checkpoints, one run, no relaunch. Stage only, NO push.
|
| 3 |
+
R=/workspace/courts; cd $R/collector; PY=/usr/bin/python3; L=$R/logs/cc_gapfill.log
|
| 4 |
+
export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3
|
| 5 |
+
echo "$(date -Is) RESUME launch pid $$" >> $L
|
| 6 |
+
nice -n 10 ionice -c3 $PY -u cc_gapfill.py AL ND WV PA CO MS MN NM FL >> $R/logs/cc_gapfill_resume.log 2>&1; rc=$?
|
| 7 |
+
echo "$(date -Is) cc_gapfill rc=$rc" >> $R/logs/cc_gapfill_resume.log
|
| 8 |
+
if [ $rc -eq 0 ]; then date -Is > $R/CC_GAPFILL_DONE
|
| 9 |
+
$PY -u cc_gapfill_review.py >> $R/logs/cc_gapfill_resume.log 2>&1 && mkdir -p $R/review_state_county/cc_gapfill && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY
|
| 10 |
+
else echo "$(date -Is) rc=$rc (3=memguard,4=disk). No relaunch." > $R/STOPPED_CC_GAPFILL_20261102; fi
|
scrapers_and_normalizers/courts/collector/run_cc_gapfill_waiter.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 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.
|
| 3 |
+
R=/workspace/courts; cd $R/collector; PY=/workspace/venv/bin/python; L=$R/logs/cc_gapfill_waiter.log
|
| 4 |
+
echo $$ > $R/CC_GAPFILL_WAITER.pid; echo "$(date -Is) waiter START pid $$" >> $L
|
| 5 |
+
PAT='nlm2_collect|add_collect|IT_MFR|IT_PR|NL-M|_collect\.py|state_rules[0-9]|archive_rules|archive_resume\.py|state_county\.py|cc_gapfill\.py|ocr'
|
| 6 |
+
ok=0
|
| 7 |
+
while [ $ok -lt 10 ]; do
|
| 8 |
+
n=$(ps -eo args | grep -E "python.*($PAT)" | grep -v grep | wc -l)
|
| 9 |
+
m=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 10 |
+
p2=0; { [ -e $R/PHASE2_DONE ] || [ -e $R/STATE_COUNTY_DONE ]; } && p2=1
|
| 11 |
+
if [ $m -ge 4404019 ] && [ $n -le 2 ]; then ok=$((ok+1)); else ok=0; fi
|
| 12 |
+
echo "$(date -Is) check other_collectors=$n phase2_done=$p2 MemAvailable_kB=$m held_min=$ok" >> $L
|
| 13 |
+
[ $ok -ge 10 ] && break; sleep 60
|
| 14 |
+
done
|
| 15 |
+
printf "timestamp=$(date -Iseconds)\nwaiter_pid=$$\nother_collectors_before=$n\nphase2_done=$p2\nMemAvailable_kB=$m (>=4.2G held 10 min)\nscope=CC gap-fill AL ND WV PA (courts, courthouses, judges, forms url+sha256). Stage only, no push. Single launch, no relaunch.\n" > $R/COS_GO_COURTS_CC_GAPFILL
|
| 16 |
+
nice -n 10 ionice -c3 $PY -u cc_gapfill.py >> $L 2>&1; rc=$?
|
| 17 |
+
echo "$(date -Is) cc_gapfill rc=$rc" >> $L
|
| 18 |
+
if [ $rc -eq 0 ]; then
|
| 19 |
+
date -Is > $R/CC_GAPFILL_DONE
|
| 20 |
+
$PY -u cc_gapfill_review.py >> $L 2>&1 && date -Is > $R/review_state_county/cc_gapfill/REVIEW_READY && echo "$(date -Is) review built" >> $L
|
| 21 |
+
else
|
| 22 |
+
echo "$(date -Is) rc=$rc (3=memguard,4=disk,other=crash; see logs/cc_gapfill.log). No relaunch." > $R/STOPPED_CC_GAPFILL
|
| 23 |
+
fi
|
| 24 |
+
rm -f $R/CC_GAPFILL_WAITER.pid
|
scrapers_and_normalizers/courts/collector/run_phase3gap.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
B=/workspace/courts; cd $B/collector
|
| 3 |
+
echo $$ > $B/PHASE3GAP.pid
|
| 4 |
+
/usr/bin/python3 -u phase3gap.py >> $B/logs/phase3gap_driver.log 2>&1; rc=$?
|
| 5 |
+
case $rc in 0) date -Is > $B/PHASE3GAP_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,5=top_rss,1=crash). No relaunch." > $B/STOPPED_PHASE3GAP;; esac
|
scrapers_and_normalizers/courts/collector/run_phase3gap_20261104.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-11-04 09:32 PT resume (IN remaining), no relaunch, stage only
|
| 3 |
+
B=/workspace/courts; cd $B/collector
|
| 4 |
+
export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20
|
| 5 |
+
ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 6 |
+
[ $ma -lt 5242880 ] && { echo "$(date -Is) launch gate fail" > $B/STOPPED_PHASE3GAP_20261104; exit 1; }
|
| 7 |
+
echo $$ > $B/PHASE3GAP.pid
|
| 8 |
+
nice -n 10 ionice -c3 /usr/bin/python3 -u phase3gap.py >> $B/logs/phase3gap_driver.log 2>&1; rc=$?
|
| 9 |
+
case $rc in 0) date -Is > $B/PHASE3GAP_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,5=top_rss,1=crash). No relaunch." > $B/STOPPED_PHASE3GAP_20261104;; esac
|
scrapers_and_normalizers/courts/collector/run_procedure_rules_20261104.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoS GO 2026-11-04 ~09:38 PT: procedure rules wrapper, single run, NO relaunch, stage only
|
| 3 |
+
B=/workspace/courts; cd $B/collector
|
| 4 |
+
export SC_MEMFLOOR=4.2 SC_MAXSTRIKES=3 CC_DISKFLOOR_G=20
|
| 5 |
+
ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
|
| 6 |
+
[ $ma -lt 5242880 ] && { echo "$(date -Is) launch gate fail" > $B/STOPPED_PROCEDURE_RULES_20261104; exit 1; }
|
| 7 |
+
echo $$ > $B/PROCEDURE_RULES.pid
|
| 8 |
+
nice -n 10 ionice -c3 /usr/bin/python3 -u procedure_rules_collect.py >> $B/logs/procedure_rules_driver.log 2>&1; rc=$?
|
| 9 |
+
case $rc in 0) date -Is > $B/PROCEDURE_RULES_DONE;; *) echo "$(date -Is) rc=$rc (3=memguard,4=disk,1=crash). No relaunch." > $B/STOPPED_PROCEDURE_RULES_20261104;; esac
|
scrapers_and_normalizers/courts/collector/run_remaining.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector
|
| 3 |
+
PY=/workspace/venv/bin/python
|
| 4 |
+
echo "$(date -Is) run_remaining START pid $$"
|
| 5 |
+
for s in courthouses ncsc state_rules review; do
|
| 6 |
+
echo "$(date -Is) stage $s"
|
| 7 |
+
$PY -u resume.py $s; rc=$?
|
| 8 |
+
if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes during $s" > /workspace/courts/STOPPED; echo STOPPED; exit 3; fi
|
| 9 |
+
[ $rc -ne 0 ] && echo "$(date -Is) stage $s exit $rc (continuing)"
|
| 10 |
+
done
|
| 11 |
+
date -Is > /workspace/courts/DONE; echo "$(date -Is) DONE"
|
scrapers_and_normalizers/courts/collector/run_state_county.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
B=/workspace/courts; cd $B/collector; PY=/workspace/venv/bin/python
|
| 3 |
+
echo "$(date -Is) driver START pid $$ memfloor=${SC_MEMFLOOR:-4.2} maxstrikes=${SC_MAXSTRIKES:-3} gap=${SC_STRIKEGAP_S:-0}" >> $B/logs/state_county_driver.log
|
| 4 |
+
echo $$ > $B/STATE_COUNTY_DRIVER.pid
|
| 5 |
+
$PY -u state_county.py >> $B/logs/state_county_driver.log 2>&1; rc=$?
|
| 6 |
+
echo "$(date -Is) collector exit rc=$rc" >> $B/logs/state_county_driver.log
|
| 7 |
+
case $rc in
|
| 8 |
+
0) date -Is > $B/STATE_COUNTY_DONE;;
|
| 9 |
+
3) echo "$(date -Is) memguard ${SC_MAXSTRIKES:-3} strikes (floor ${SC_MEMFLOOR:-4.2}G)" > $B/STOPPED_STATE_COUNTY;;
|
| 10 |
+
4) echo "$(date -Is) diskguard (free<12G or staging>2G)" > $B/STOPPED_STATE_COUNTY;;
|
| 11 |
+
5) echo "$(date -Is) reason=courts_top_rss" > $B/STOPPED_STATE_COUNTY;;
|
| 12 |
+
*) echo "$(date -Is) crash rc=$rc see logs/state_county.log CRASH" > $B/STOPPED_STATE_COUNTY;;
|
| 13 |
+
esac
|
scrapers_and_normalizers/courts/collector/run_state_rules.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector; PY=/workspace/venv/bin/python
|
| 3 |
+
echo "$(date -Is) run_state_rules START pid $$"
|
| 4 |
+
$PY -u state_rules2.py; rc=$?
|
| 5 |
+
if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES; exit 3; fi
|
| 6 |
+
date -Is > /workspace/courts/STATE_RULES_DONE
|
| 7 |
+
$PY -u review_sr.py && echo "$(date -Is) review built"
|
scrapers_and_normalizers/courts/collector/run_state_rules_rerun.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector; PY=/workspace/venv/bin/python
|
| 3 |
+
echo "$(date -Is) rerun START pid $$"
|
| 4 |
+
$PY -u state_rules3.py; rc=$?
|
| 5 |
+
if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES_RERUN; exit 3; fi
|
| 6 |
+
date -Is > /workspace/courts/STATE_RULES_RERUN_DONE
|
| 7 |
+
SR_OUT=/workspace/courts/staging/state_rules_rerun SR_RV=/workspace/courts/review_state_rules_rerun SR_LOG=state_rules_rerun_ $PY -u review_sr.py && echo "$(date -Is) review built"
|
scrapers_and_normalizers/courts/collector/run_state_rules_resume.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /workspace/courts/collector; PY=/workspace/venv/bin/python
|
| 3 |
+
echo "$(date -Is) resume START pid $$"
|
| 4 |
+
$PY -u state_rules4.py; rc=$?
|
| 5 |
+
if [ $rc -eq 3 ]; then echo "$(date -Is) memguard 3 strikes" > /workspace/courts/STOPPED_STATE_RULES_RESUME; exit 3; fi
|
| 6 |
+
date -Is > /workspace/courts/STATE_RULES_RESUME_DONE
|
| 7 |
+
$PY -u review_resume.py && echo "$(date -Is) review built"
|
scrapers_and_normalizers/courts/collector/stage2.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Chained after us_fed.py (same slot): courts retry, courthouses, state rules, review package."""
|
| 3 |
+
import os,sys,time,json,re,glob,hashlib,collections,asyncio,urllib.parse
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import us_fed as U
|
| 6 |
+
from us_fed import log,fetch,links,prov,sid,ST,memguard
|
| 7 |
+
WAIT=int(sys.argv[1]) if __name__=="__main__" and len(sys.argv)>1 else 0
|
| 8 |
+
def wait():
|
| 9 |
+
while WAIT and os.path.exists(f'/proc/{WAIT}'):time.sleep(30)
|
| 10 |
+
log('predecessor done',WAIT)
|
| 11 |
+
def courts_retry():
|
| 12 |
+
u='https://www.uscourts.gov/about-federal-courts/court-role-and-structure/court-website-links'
|
| 13 |
+
r=fetch(u,timeout=180)
|
| 14 |
+
if not r:log('COURTS_RETRY_FAIL');return []
|
| 15 |
+
out=open(f'{ST}/courts.jsonl','w');rows=[];seen=set()
|
| 16 |
+
for h,t in links(r[0],r[1]):
|
| 17 |
+
if not re.search(r'\.uscourts\.gov',h) or 'www.uscourts.gov' in h or not t:continue
|
| 18 |
+
root=urllib.parse.urlsplit(h);root=f'{root.scheme}://{root.netloc}/'
|
| 19 |
+
if root in seen:continue
|
| 20 |
+
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]))
|
| 21 |
+
if root.startswith('http://'):rec['transport']='http_unreachable'
|
| 22 |
+
out.write(json.dumps(rec)+'\n');rows.append(rec)
|
| 23 |
+
out.close();log('courts rows',len(rows));return rows
|
| 24 |
+
ADDR=re.compile(r'(\d{1,6}\s+[A-Z0-9][\w .\'-]{2,60}?(?:Street|St\.?|Avenue|Ave\.?|Boulevard|Blvd\.?|Road|Rd\.?|Drive|Dr\.?|Way|Place|Pl\.?|Square|Plaza|Lane|Ln\.?|Court|Ct\.?|Parkway|Pkwy\.?|Mall|Center)\b[\w .,#-]{0,40}?),?\s+([A-Z][A-Za-z .\'-]{1,40}),\s+([A-Z]{2}|[A-Z][a-z]+(?: [A-Z][a-z]+)?)\.?\s+(\d{5}(?:-\d{4})?)')
|
| 25 |
+
ST2=json.load(open('/workspace/courts/collector/us_iso.json'))
|
| 26 |
+
AB={k.split('-')[1]:k for k in ST2};NM={v.lower():k for k,v in ST2.items()}
|
| 27 |
+
def text(b):
|
| 28 |
+
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())
|
| 29 |
+
def courthouses(courts):
|
| 30 |
+
out=open(f'{ST}/courthouses.jsonl','a');sk=open(f'{ST}/skips.jsonl','a');n=0
|
| 31 |
+
for c in courts:
|
| 32 |
+
if c['url'].startswith('http://'):sk.write(json.dumps(dict(url=c['url'],reason='transport=http_unreachable'))+'\n');continue
|
| 33 |
+
r=fetch(c['url'],delay=5)
|
| 34 |
+
if not r:sk.write(json.dumps(dict(url=c['url'],reason='fetch_fail_or_robots'))+'\n');continue
|
| 35 |
+
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]
|
| 36 |
+
for h in dict.fromkeys(cand):
|
| 37 |
+
if not h.startswith('https://'):continue
|
| 38 |
+
x=fetch(h,delay=5)
|
| 39 |
+
if x:pages.append(x)
|
| 40 |
+
seen=set()
|
| 41 |
+
for pu,b in pages:
|
| 42 |
+
for m in ADDR.finditer(text(b)):
|
| 43 |
+
st=m.group(3);iso=AB.get(st) or NM.get(st.lower())
|
| 44 |
+
if not iso:continue
|
| 45 |
+
key=(m.group(1).lower()[:30],m.group(4))
|
| 46 |
+
if key in seen:continue
|
| 47 |
+
seen.add(key)
|
| 48 |
+
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
|
| 49 |
+
out.flush();sk.flush()
|
| 50 |
+
out.close();log('courthouses rows',n)
|
| 51 |
+
SUPP=['AL','AR','GA','IA','IL','IN','LA','MA','MS','NC','PA','TN','TX','VA','WY']
|
| 52 |
+
def state_rules():
|
| 53 |
+
d='/workspace/courts/staging/state_rules';os.makedirs(d,exist_ok=True)
|
| 54 |
+
os.environ['HOME']=d+'/_home'
|
| 55 |
+
sys.path[:0]=['/workspace/courts/pydeps','/workspace/ipfs_datasets_py_latest']
|
| 56 |
+
from ipfs_datasets_py.processors.legal_scrapers.state_procedure_rules_scraper import scrape_state_procedure_rules as S
|
| 57 |
+
memguard()
|
| 58 |
+
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))
|
| 59 |
+
json.dump(res.get('metadata',{}) if isinstance(res,dict) else {},open(d+'/_run_metadata.json','w'),indent=1,default=str)
|
| 60 |
+
log('state_rules done',str((res or {}).get('status'))[:100])
|
| 61 |
+
if __name__=='__main__':
|
| 62 |
+
log('STAGE2 START pid',os.getpid());wait()
|
| 63 |
+
for f in [lambda:courthouses(courts_retry()),state_rules]:
|
| 64 |
+
try:f()
|
| 65 |
+
except SystemExit:raise
|
| 66 |
+
except Exception as e:log('STAGE_ERR',repr(e)[:300])
|
| 67 |
+
import review;review.build();log('STAGE2 DONE')
|
scrapers_and_normalizers/courts/collector/stage_phase1.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,glob,os,re,hashlib,collections,unicodedata
|
| 2 |
+
B='/workspace/courts';S=B+'/staging/state_county/phase1';H=B+'/hf_stage';O=B+'/review_state_county/phase1_push'
|
| 3 |
+
GAPS={'DE':'phase1 ran; official pages yielded no usable static rows','MT':'no candidate directory/judges/forms page in static landing HTML (site errors)',
|
| 4 |
+
'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)',
|
| 5 |
+
'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'}
|
| 6 |
+
def cov(st):
|
| 7 |
+
s=st['status']
|
| 8 |
+
if s=='ok':return 'complete'
|
| 9 |
+
if 'guard stop' in s:return 'partial_guard_stop'
|
| 10 |
+
if 'phase0' in s or sum(st['counts'].values())==0:return 'blocked'
|
| 11 |
+
return 'partial_host_stopped'
|
| 12 |
+
def nz(x):
|
| 13 |
+
x=unicodedata.normalize('NFKD',x or '').encode('ascii','ignore').decode().lower()
|
| 14 |
+
return re.sub(r'\s+',' ',re.sub(r'[^a-z0-9]+',' ',x)).strip()
|
| 15 |
+
T=['courts','courthouses','judges','forms']
|
| 16 |
+
hub={t:[json.loads(l) for l in open(f'{H}/data/{t}.jsonl')] for t in T}
|
| 17 |
+
URL={'courts':'url','courthouses':None,'judges':None,'forms':'file_url'}
|
| 18 |
+
def nkey(t,r):
|
| 19 |
+
st=r.get('subdivision_iso')
|
| 20 |
+
if t=='judges':return (nz(r.get('full_name')),nz(r.get('court_name')),st)
|
| 21 |
+
if t=='forms':return (nz(r.get('title')),st,r.get('file_sha256'))
|
| 22 |
+
if t=='courthouses':return (nz(r.get('name')),st,nz(r.get('address_line')))
|
| 23 |
+
return (nz(r.get('name')),st)
|
| 24 |
+
states={};flags={'forms_cap250':{},'transport_http_rows':collections.Counter(),'transport_http_skipped_links':collections.Counter()}
|
| 25 |
+
for d in sorted(glob.glob(S+'/*/status.json')):
|
| 26 |
+
st=json.load(open(d));states[st['state']]=st
|
| 27 |
+
for n in st.get('notes',[]):
|
| 28 |
+
if 'capped at 250' in n:flags['forms_cap250'][st['state']]=n
|
| 29 |
+
flags['transport_http_skipped_links'][st['state']]=sum(1 for k in st.get('skips',[]) if k.get('transport')=='http')
|
| 30 |
+
covmap={s:cov(v) for s,v in states.items()}
|
| 31 |
+
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)'}}
|
| 32 |
+
idremap={};out={};keptU={};keptN={}
|
| 33 |
+
for t in T:
|
| 34 |
+
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]}
|
| 35 |
+
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 {}
|
| 36 |
+
c=collections.Counter();new=[]
|
| 37 |
+
for s in sorted(states):
|
| 38 |
+
if s in GAPS:
|
| 39 |
+
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
|
| 40 |
+
f=f'{S}/{s}/{t}.jsonl'
|
| 41 |
+
if not os.path.exists(f):continue
|
| 42 |
+
for l in open(f):
|
| 43 |
+
r=json.loads(l);c['staged']+=1
|
| 44 |
+
if r.get('court_id') in idremap:r['court_id']=idremap[r['court_id']]
|
| 45 |
+
u=r.get(URL[t]) if URL[t] else None;k=nkey(t,r)
|
| 46 |
+
if u and u in hubU or k in hubN:
|
| 47 |
+
c['dupe_hub']+=1
|
| 48 |
+
if t=='courts':idremap[r['court_id']]=(hubU.get(u) or hubN[k])['court_id']
|
| 49 |
+
continue
|
| 50 |
+
if (u and u in seenU) or k in seenN:
|
| 51 |
+
c['dupe_within_phase1']+=1
|
| 52 |
+
if t=='courts':idremap[r['court_id']]=keptU.get(u) or keptN[k]
|
| 53 |
+
continue
|
| 54 |
+
if t=='courts':
|
| 55 |
+
keptN[k]=r['court_id']
|
| 56 |
+
if u:keptU[u]=r['court_id']
|
| 57 |
+
if u:seenU.add(u)
|
| 58 |
+
seenN.add(k)
|
| 59 |
+
if t=='judges':
|
| 60 |
+
if r.get('court_id') not in ({x['court_id'] for x in hub['courts']}|{x['court_id'] for x in out['courts']}):
|
| 61 |
+
r['court_id']=None;c['court_id_nulled_unmatched']+=1
|
| 62 |
+
for x in list(r):
|
| 63 |
+
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)
|
| 64 |
+
r['coverage']=covmap[s];r['source_collection']='official_state_judiciary_sites_phase1_20261028'
|
| 65 |
+
if r.get('transport')=='http':flags['transport_http_rows'][f'{t}:{s}']+=1
|
| 66 |
+
new.append(r)
|
| 67 |
+
out[t]=new;c['added']=len(new);c['before']=len(hub[t]);c['final']=len(hub[t])+len(new);rep['tables'][t]=dict(c)
|
| 68 |
+
# validate
|
| 69 |
+
iso=json.load(open(B+'/collector/us_iso.json'));isos=set(iso)
|
| 70 |
+
cids={r['court_id'] for r in hub['courts']+out['courts']};err=collections.Counter()
|
| 71 |
+
for t in T:
|
| 72 |
+
pk={'courts':'court_id','courthouses':'courthouse_id','judges':'judge_id','forms':'form_id'}[t]
|
| 73 |
+
ids=[r[pk] for r in hub[t]+out[t]]
|
| 74 |
+
if len(ids)!=len(set(ids)):err[t+':dup_pk']+=len(ids)-len(set(ids))
|
| 75 |
+
for r in out[t]:
|
| 76 |
+
if not (r.get('subdivision_iso') or '').startswith('US-'):err[t+':bad_iso']+=1
|
| 77 |
+
if r['subdivision_iso'] not in isos:err[t+':iso_not_in_fk']+=1
|
| 78 |
+
for x in ['source_url','fetched_at','archive_source','license','robots_note','transport']:
|
| 79 |
+
if r.get(x) in (None,''):err[t+':missing_'+x]+=1
|
| 80 |
+
if t in('courthouses','judges') and r.get('court_id') and r['court_id'] not in cids:err[t+':dangling_court_id']+=1
|
| 81 |
+
if t=='forms' and (not r.get('file_sha256') or r.get('file_stored')):err['forms:sha_or_stored']+=1
|
| 82 |
+
if r['coverage'] not in('complete','partial_host_stopped','partial_guard_stop','blocked'):err['bad_cov']+=1
|
| 83 |
+
rep['validation_errors']=dict(err);rep['flags']={k:dict(v) for k,v in flags.items()}
|
| 84 |
+
# unify keys
|
| 85 |
+
for t in T:
|
| 86 |
+
rows=hub[t]+out[t];keys=[]
|
| 87 |
+
for r in rows:
|
| 88 |
+
for k in r:
|
| 89 |
+
if k not in keys:keys.append(k)
|
| 90 |
+
with open(f'{H}/data/{t}.jsonl','w') as fh:
|
| 91 |
+
for r in rows:fh.write(json.dumps({k:r.get(k) for k in keys},ensure_ascii=False)+'\n')
|
| 92 |
+
json.dump(rep,open(O+'/report.json','w'),indent=1);print(json.dumps(rep,indent=1))
|
scrapers_and_normalizers/courts/collector/stage_phase2.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,os,glob,shutil,hashlib,sys,datetime
|
| 2 |
+
B='/workspace/courts';P2=B+'/staging/state_county/phase2';RV=B+'/review_state_county/phase2'
|
| 3 |
+
SRC=B+'/hf_stage_fixup';OUT=B+'/hf_stage_phase2';SC='official_state_judiciary_sites_phase2_20261028'
|
| 4 |
+
COV={'KY':'complete','WY':'complete','ID':'complete','NV':'partial_host_stopped','MN':'partial_host_stopped','IA':'partial_rows_dropped'}
|
| 5 |
+
now=datetime.datetime.now().astimezone().isoformat()
|
| 6 |
+
hub={c:[json.loads(l) for l in open(f'{SRC}/data/{c}.jsonl')] for c in ['courts','courthouses','judges','forms']}
|
| 7 |
+
keys={c:list(hub[c][0]) for c in hub}
|
| 8 |
+
PK={'courts':'court_id','courthouses':'courthouse_id','judges':'judge_id','forms':'form_id'}
|
| 9 |
+
new={c:[] for c in hub}
|
| 10 |
+
for st in sorted(COV):
|
| 11 |
+
for c in hub:
|
| 12 |
+
f=f'{P2}/{st}/{c}.jsonl'
|
| 13 |
+
for l in open(f):
|
| 14 |
+
if l.strip(): new[c].append(json.loads(l))
|
| 15 |
+
# 1) drop IA judges
|
| 16 |
+
ia=[r for r in new['judges'] if r['subdivision_iso']=='US-IA']
|
| 17 |
+
with open(RV+'/removed_ia_judges.jsonl','w') as fh:
|
| 18 |
+
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')
|
| 19 |
+
new['judges']=[r for r in new['judges'] if r['subdivision_iso']!='US-IA']
|
| 20 |
+
# merge IA courthouses
|
| 21 |
+
iac=[r for r in new['courthouses'] if r['subdivision_iso']=='US-IA']
|
| 22 |
+
assert len(iac)==3 and len({r['postal_code'] for r in iac})==1
|
| 23 |
+
keep=iac[0];keep['name']='Iowa Judicial Branch Building'
|
| 24 |
+
with open(RV+'/merged_ia_courthouses.jsonl','w') as fh:
|
| 25 |
+
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')
|
| 26 |
+
drop={r['courthouse_id'] for r in iac[1:]}
|
| 27 |
+
new['courthouses']=[r for r in new['courthouses'] if r['courthouse_id'] not in drop]
|
| 28 |
+
# normalize fields
|
| 29 |
+
for c in new:
|
| 30 |
+
for r in new[c]:
|
| 31 |
+
r['coverage']=COV[r['subdivision_iso'][3:]];r['source_collection']=SC
|
| 32 |
+
if c=='courts': r.setdefault('content_sha256_note',None)
|
| 33 |
+
new[c]=[{k:r.get(k) for k in keys[c]} for r in new[c]]
|
| 34 |
+
# validate strict
|
| 35 |
+
iso=set();m=json.load(open('/workspace/coverage/subnational_state_matrix_20261025.json'))
|
| 36 |
+
for r in m['rows']: iso.add(r.get('iso_3166_2') or r.get('iso'))
|
| 37 |
+
courtids={r['court_id'] for r in hub['courts']+new['courts']}
|
| 38 |
+
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']}
|
| 39 |
+
val={}
|
| 40 |
+
for c in new:
|
| 41 |
+
ids=[r[PK[c]] for r in new[c]];hids={r[PK[c]] for r in hub[c]}
|
| 42 |
+
v={'rows':len(new[c]),'dup_ids':len(ids)-len(set(ids)),'dup_vs_hub':sum(i in hids for i in ids),
|
| 43 |
+
'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),
|
| 44 |
+
'fk_iso_bad':sum(1 for r in new[c] if r.get('subdivision_iso') not in iso),
|
| 45 |
+
'missing_required':sum(1 for r in new[c] for k in REQ[c] if not r.get(k)),
|
| 46 |
+
'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])}
|
| 47 |
+
if c=='judges': v['fk_court_null']=sum(1 for r in new[c] if not r.get('court_id'))
|
| 48 |
+
val[c]=v
|
| 49 |
+
bad=sum(v['dup_ids']+v['dup_vs_hub']+v['fk_court_missing']+v['fk_iso_bad']+v['missing_required']+v['non_https'] for v in val.values())
|
| 50 |
+
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)
|
| 51 |
+
print(json.dumps(val,indent=1),'TOTAL_PROBLEMS',bad)
|
| 52 |
+
if bad or '--build' not in sys.argv: sys.exit(1 if bad else 0)
|
| 53 |
+
bak=B+'/hf_stage_fixup_bak_20261029_pre_phase2'
|
| 54 |
+
if not os.path.exists(bak): shutil.copytree(SRC,bak)
|
| 55 |
+
if os.path.exists(OUT): shutil.rmtree(OUT)
|
| 56 |
+
shutil.copytree(SRC,OUT)
|
| 57 |
+
for c in new:
|
| 58 |
+
with open(f'{OUT}/data/{c}.jsonl','a') as fh:
|
| 59 |
+
for r in new[c]: fh.write(json.dumps(r,ensure_ascii=False)+'\n')
|
| 60 |
+
s=json.load(open(OUT+'/schema.json'))
|
| 61 |
+
for t in s['tables'].values():
|
| 62 |
+
if 'coverage' in t: t['coverage']=t['coverage'].replace('partial_guard_stop,blocked','partial_guard_stop,partial_rows_dropped,blocked')
|
| 63 |
+
json.dump(s,open(OUT+'/schema.json','w'),indent=1)
|
| 64 |
+
with open(OUT+'/README.md','a') as fh: fh.write(open(RV+'/CARD_PHASE2.md').read())
|
| 65 |
+
rc={c:sum(1 for _ in open(f'{OUT}/data/{c}.jsonl')) for c in ['courthouses','courts','forms','judges','rules','state_rules']}
|
| 66 |
+
open(OUT+'/ROWCOUNTS.txt','w').write(''.join(f'data/{c}.jsonl {n}\n' for c,n in rc.items()))
|
| 67 |
+
def sh(p):
|
| 68 |
+
h=hashlib.sha256();h.update(open(p,'rb').read());return h.hexdigest()
|
| 69 |
+
fs=['README.md','ROWCOUNTS.txt','schema.json']+[f'data/{c}.jsonl' for c in rc]
|
| 70 |
+
open(OUT+'/MANIFEST.sha256','w').write(''.join(f'{sh(OUT+"/"+f)} {f}\n' for f in fs))
|
| 71 |
+
print('BUILT',rc,{c:len(new[c]) for c in new})
|
scrapers_and_normalizers/courts/collector/state_county.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""State+county courthouses/courts/judges/forms collector. Phases 0,1,2 (+FL in 2; SC deferred).
|
| 3 |
+
Locked limits: HTTPS only, TLS verify, keyless, max(10s,crawl-delay)/host, stop host on first 403/429/challenge,
|
| 4 |
+
memguard <4.2G pause / 3 strikes stop (exit 3), disk free<12G or staging>2G stop (exit 4). PDFs: url+sha256 only."""
|
| 5 |
+
import os, sys, re, json, time, csv, hashlib, threading, shutil, datetime, urllib.parse as up
|
| 6 |
+
import requests
|
| 7 |
+
from bs4 import BeautifulSoup
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
BASE='/workspace/courts'; ST_DIR=f'{BASE}/staging/state_county'; RV=f'{BASE}/review_state_county'
|
| 10 |
+
LOG=open(f'{BASE}/logs/state_county.log','a',buffering=1)
|
| 11 |
+
UA='Mozilla/5.0 (compatible; justicedao-court-research/0.2; +https://huggingface.co/justicedao)'
|
| 12 |
+
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()
|
| 13 |
+
PH2='CO KY WY NM ID NV MN MS IA FL'.split()
|
| 14 |
+
DEFERRED={'SC':'deferred-by-crawl-delay: robots Crawl-delay 120000s (~33.3h/request); not fetched'}
|
| 15 |
+
NEVER=set('CA IL OR WA WI CT VA KS'.split())
|
| 16 |
+
LIC='see source terms (US state government judiciary website)'
|
| 17 |
+
MAXP={'courthouses':40,'judges':40,'forms':30}; MAXFILES=250; MAXFILEBYTES=40*2**20; MAXHTMLBYTES=5*2**20; TIMEOUT=(15,30)
|
| 18 |
+
CHALL=['cf-chl','challenge-platform','just a moment...','g-recaptcha','hcaptcha','cf-turnstile','leastfactor','_incapsula_','access denied','attention required','px-captcha']
|
| 19 |
+
STOP=threading.Event(); STOPRC=[0]; strikes=[0]; mlock=threading.Lock()
|
| 20 |
+
def now(): return datetime.datetime.now().astimezone().isoformat(timespec='seconds')
|
| 21 |
+
def log(*a): LOG.write(now()+' '+' '.join(map(str,a))+'\n')
|
| 22 |
+
def memavail():
|
| 23 |
+
for l in open('/proc/meminfo'):
|
| 24 |
+
if l.startswith('MemAvailable'): return int(l.split()[1])/2**20
|
| 25 |
+
def du(p):
|
| 26 |
+
t=0
|
| 27 |
+
for r,_,fs in os.walk(p):
|
| 28 |
+
for f in fs:
|
| 29 |
+
try: t+=os.path.getsize(os.path.join(r,f))
|
| 30 |
+
except OSError: pass
|
| 31 |
+
return t
|
| 32 |
+
def memstrike_top5():
|
| 33 |
+
try:
|
| 34 |
+
rows=[]
|
| 35 |
+
for d in os.listdir('/proc'):
|
| 36 |
+
if not d.isdigit(): continue
|
| 37 |
+
try:
|
| 38 |
+
rss=0
|
| 39 |
+
for l in open(f'/proc/{d}/status'):
|
| 40 |
+
if l.startswith('VmRSS'): rss=int(l.split()[1]); break
|
| 41 |
+
cmd=open(f'/proc/{d}/cmdline','rb').read().replace(b'\0',b' ').decode('utf-8','replace').strip()
|
| 42 |
+
rows.append((rss,d,cmd))
|
| 43 |
+
except OSError: pass
|
| 44 |
+
rows.sort(reverse=True)
|
| 45 |
+
for rss,pid,cmd in rows[:5]: log(f'MEMSTRIKE strike={strikes[0]} pid={pid} rss={rss/1024:.0f}MB cmd={cmd[:160]}')
|
| 46 |
+
except Exception as e: log('MEMSTRIKE err',repr(e)[:200])
|
| 47 |
+
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'))
|
| 48 |
+
lastcounted=[0.0]; MYPID=os.getpid()
|
| 49 |
+
def ours(pid,cmd):
|
| 50 |
+
if '/workspace/courts' in cmd: return True
|
| 51 |
+
try:
|
| 52 |
+
p=int(pid)
|
| 53 |
+
while p>1:
|
| 54 |
+
if p==MYPID: return True
|
| 55 |
+
p=int(open(f'/proc/{p}/stat').read().rsplit(')',1)[1].split()[1])
|
| 56 |
+
except Exception: pass
|
| 57 |
+
return False
|
| 58 |
+
def memstrike_top5():
|
| 59 |
+
try:
|
| 60 |
+
rows=[]
|
| 61 |
+
for d in os.listdir('/proc'):
|
| 62 |
+
if not d.isdigit(): continue
|
| 63 |
+
try:
|
| 64 |
+
rss=0
|
| 65 |
+
for l in open(f'/proc/{d}/status'):
|
| 66 |
+
if l.startswith('VmRSS'): rss=int(l.split()[1]); break
|
| 67 |
+
cmd=open(f'/proc/{d}/cmdline','rb').read().replace(b'\0',b' ').decode('utf-8','replace').strip()
|
| 68 |
+
rows.append((rss,d,cmd))
|
| 69 |
+
except OSError: pass
|
| 70 |
+
rows.sort(reverse=True)
|
| 71 |
+
for rss,pid,cmd in rows[:5]: log(f'MEMSTRIKE strike={strikes[0]} pid={pid} rss={rss/1024:.0f}MB cmd={cmd[:160]}')
|
| 72 |
+
if rows and ours(rows[0][1],rows[0][2]): return 'courts_top_rss'
|
| 73 |
+
except Exception as e: log('MEMSTRIKE err',repr(e)[:200])
|
| 74 |
+
return None
|
| 75 |
+
def guards():
|
| 76 |
+
if STOP.is_set(): return False
|
| 77 |
+
with mlock:
|
| 78 |
+
if shutil.disk_usage('/workspace').free/2**30<12 or du(ST_DIR)>2*2**30:
|
| 79 |
+
log('DISKGUARD stop'); STOPRC[0]=4; STOP.set(); return False
|
| 80 |
+
m=memavail()
|
| 81 |
+
if m<MEMFLOOR:
|
| 82 |
+
t=time.time(); counted=(strikes[0]==0 or t-lastcounted[0]>=STRIKEGAP)
|
| 83 |
+
if counted: strikes[0]+=1; lastcounted[0]=t
|
| 84 |
+
log(f'MEMGUARD strike {strikes[0]} memavail={m:.2f}G counted={counted} floor={MEMFLOOR} max={MAXSTRIKES} gap={STRIKEGAP}s')
|
| 85 |
+
if memstrike_top5()=='courts_top_rss':
|
| 86 |
+
log('MEMGUARD courts_top_rss stop'); STOPRC[0]=5; STOP.set(); return False
|
| 87 |
+
if strikes[0]>=MAXSTRIKES: STOPRC[0]=3; STOP.set(); return False
|
| 88 |
+
for _ in range(60):
|
| 89 |
+
time.sleep(10)
|
| 90 |
+
if memavail()>=MEMFLOOR: break
|
| 91 |
+
else: STOPRC[0]=3; STOP.set(); return False
|
| 92 |
+
return True
|
| 93 |
+
class HostBlocked(Exception): pass
|
| 94 |
+
class Host:
|
| 95 |
+
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()
|
| 96 |
+
HOSTS={}; HL=threading.Lock()
|
| 97 |
+
SESS=requests.Session(); SESS.headers['User-Agent']=UA
|
| 98 |
+
BLF=f'{ST_DIR}/blocked_hosts.json'
|
| 99 |
+
def save_block(h,why):
|
| 100 |
+
with HL:
|
| 101 |
+
d=json.load(open(BLF)) if os.path.exists(BLF) else {}
|
| 102 |
+
d[h]={'reason':why,'at':now()}; json.dump(d,open(BLF,'w'),indent=1)
|
| 103 |
+
def load_blocks():
|
| 104 |
+
if os.path.exists(BLF):
|
| 105 |
+
for h,v in json.load(open(BLF)).items(): gethost(h).blocked=v['reason']+' (persisted)'
|
| 106 |
+
def gethost(h):
|
| 107 |
+
with HL:
|
| 108 |
+
if h not in HOSTS: HOSTS[h]=Host(h)
|
| 109 |
+
return HOSTS[h]
|
| 110 |
+
def is_chall(r,body):
|
| 111 |
+
if r.status_code in (403,429): return f'http {r.status_code}'
|
| 112 |
+
b=body[:30000].lower()
|
| 113 |
+
for m in CHALL:
|
| 114 |
+
if m in b: return f'challenge marker {m!r} (http {r.status_code})'
|
| 115 |
+
return None
|
| 116 |
+
def fetch(url,stream=False):
|
| 117 |
+
"""returns (resp, body_bytes or None, sha256, nbytes). Raises HostBlocked."""
|
| 118 |
+
p=up.urlparse(url)
|
| 119 |
+
if p.scheme!='https': return None
|
| 120 |
+
H=gethost(p.netloc)
|
| 121 |
+
with H.lock:
|
| 122 |
+
if H.blocked: raise HostBlocked(H.blocked)
|
| 123 |
+
if H.robots is None: _robots(H)
|
| 124 |
+
if not guards(): raise HostBlocked('guard stop')
|
| 125 |
+
w=H.last+H.delay-time.time()
|
| 126 |
+
if w>0: time.sleep(w)
|
| 127 |
+
H.last=time.time(); H.n+=1
|
| 128 |
+
try:
|
| 129 |
+
r=SESS.get(url,timeout=TIMEOUT,stream=True,allow_redirects=True)
|
| 130 |
+
except requests.RequestException as e:
|
| 131 |
+
log('ERR',url,repr(e)[:200]); return None
|
| 132 |
+
if up.urlparse(r.url).scheme!='https': r.close(); return None
|
| 133 |
+
ct=r.headers.get('content-type','')
|
| 134 |
+
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
|
| 135 |
+
h=hashlib.sha256(); n=0; chunks=[]
|
| 136 |
+
try:
|
| 137 |
+
for c in r.iter_content(65536):
|
| 138 |
+
h.update(c); n+=len(c)
|
| 139 |
+
if keep:
|
| 140 |
+
if n>MAXHTMLBYTES: log('HTMLCAP',url); keep=False; chunks=[]; break
|
| 141 |
+
chunks.append(c)
|
| 142 |
+
if n>MAXFILEBYTES: log('TOOBIG',url); break
|
| 143 |
+
except requests.RequestException as e: log('ERR read',url,repr(e)[:200])
|
| 144 |
+
finally: r.close()
|
| 145 |
+
H.last=time.time()
|
| 146 |
+
body=b''.join(chunks) if (not stream and chunks) else (b'' if not stream else None)
|
| 147 |
+
if r.status_code in (403,429) or ('html' in ct and body is not None):
|
| 148 |
+
c=is_chall(r,(body or b'').decode('utf-8','replace'))
|
| 149 |
+
if c:
|
| 150 |
+
H.blocked=f'{c} at {url}'; log('BLOCK',p.netloc,H.blocked); save_block(p.netloc,H.blocked); raise HostBlocked(H.blocked)
|
| 151 |
+
log('GET',r.status_code,n,url)
|
| 152 |
+
return r,body,h.hexdigest(),n
|
| 153 |
+
def _robots(H):
|
| 154 |
+
H.robots=''
|
| 155 |
+
try:
|
| 156 |
+
w=H.last+H.delay-time.time()
|
| 157 |
+
if w>0: time.sleep(w)
|
| 158 |
+
r=SESS.get(f'https://{H.host}/robots.txt',timeout=TIMEOUT); H.last=time.time(); H.n+=1
|
| 159 |
+
if r.status_code==200 and 'html' not in r.headers.get('content-type',''):
|
| 160 |
+
H.robots=r.text[:200000]
|
| 161 |
+
ua=None
|
| 162 |
+
for l in H.robots.splitlines():
|
| 163 |
+
l=l.split('#')[0].strip(); k,_,v=l.partition(':'); k=k.strip().lower(); v=v.strip()
|
| 164 |
+
if k=='user-agent': ua=v
|
| 165 |
+
elif k=='crawl-delay' and ua=='*':
|
| 166 |
+
try: H.delay=max(H.delay,float(v))
|
| 167 |
+
except ValueError: pass
|
| 168 |
+
log('ROBOTS',H.host,r.status_code,'delay',H.delay)
|
| 169 |
+
except requests.RequestException as e: log('ERR robots',H.host,repr(e)[:200])
|
| 170 |
+
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'],
|
| 171 |
+
'judges':['judicial directory','judge directory','judicial officers','judges','justices','meet the','magistrates','judicial officer','bench'],
|
| 172 |
+
'forms':['forms','self-help forms','court forms','form','self help','self-represented','pro se']}
|
| 173 |
+
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']
|
| 174 |
+
def links(base,soup):
|
| 175 |
+
out=[]
|
| 176 |
+
for a in soup.find_all('a',href=True):
|
| 177 |
+
try: u=up.urljoin(base,a['href'].strip()).split('#')[0]
|
| 178 |
+
except ValueError: continue
|
| 179 |
+
if not u.startswith(('http://','https://')): continue
|
| 180 |
+
out.append((u,' '.join(a.get_text(' ').split())[:200]))
|
| 181 |
+
return out
|
| 182 |
+
def score(cat,u,t):
|
| 183 |
+
s=(t+' '+up.unquote(u)).lower(); sc=0
|
| 184 |
+
for i,k in enumerate(KW[cat]):
|
| 185 |
+
if k in s: sc+=10-min(i,8)
|
| 186 |
+
if any(n in s for n in NEG): sc-=6
|
| 187 |
+
return sc
|
| 188 |
+
def samesite(u,root):
|
| 189 |
+
a=up.urlparse(u).netloc.lower(); b=root.lower()
|
| 190 |
+
reg=lambda h:'.'.join(h.split('.')[-2:])
|
| 191 |
+
return a==b or reg(a)==reg(b)
|
| 192 |
+
def landing_urls():
|
| 193 |
+
d={}
|
| 194 |
+
for r in csv.DictReader(open(f'{BASE}/state_county_source_inventory.csv')): d.setdefault(r['state'],r['url'])
|
| 195 |
+
return d
|
| 196 |
+
ISO=json.load(open(f'{BASE}/collector/us_iso.json'))
|
| 197 |
+
NAMES={v:k[3:] for k,v in ISO.items()}
|
| 198 |
+
def prov(url,sha,extra=None):
|
| 199 |
+
d={'source_url':url,'fetched_at':now(),'archive_source':'live','archive_timestamp':None,'license':LIC,
|
| 200 |
+
'terms_note':'official state judiciary site; public record; cite source','robots_note':'robots advisory (official gov host); crawl-delay honored',
|
| 201 |
+
'transport':'https','content_sha256':sha}
|
| 202 |
+
if extra: d.update(extra)
|
| 203 |
+
return d
|
| 204 |
+
def sid(*a): return hashlib.sha1('|'.join(map(str,a)).encode()).hexdigest()[:16]
|
| 205 |
+
# ---------------- Phase 0 ----------------
|
| 206 |
+
def phase0_state(st):
|
| 207 |
+
out=f'{ST_DIR}/phase0/{st}.json'
|
| 208 |
+
if os.path.exists(out): return
|
| 209 |
+
res={'state':st,'subdivision_iso':f'US-{st}','landing':None,'candidates':{},'chosen':{},'status':'ok','notes':[]}
|
| 210 |
+
if st in DEFERRED:
|
| 211 |
+
res['status']='deferred'; res['notes'].append(DEFERRED[st]); json.dump(res,open(out,'w'),indent=1); return
|
| 212 |
+
url=landing_urls()[st]; res['landing']=url
|
| 213 |
+
try:
|
| 214 |
+
f=fetch(url)
|
| 215 |
+
if not f or f[0].status_code!=200: res['status']=f'landing fail {f[0].status_code if f else "neterr/http"}'
|
| 216 |
+
else:
|
| 217 |
+
r,b,sha,n=f; base=r.url; soup=BeautifulSoup(b,'lxml'); L=links(base,soup)
|
| 218 |
+
if len(L)<8: res['notes'].append(f'only {len(L)} links in static HTML (JS-rendered?)')
|
| 219 |
+
for cat in KW:
|
| 220 |
+
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]
|
| 221 |
+
res['candidates'][cat]=[{'score':s,'url':u,'text':t} for s,u,t in c]
|
| 222 |
+
for cat in KW: # verify top https candidate (1 req per category)
|
| 223 |
+
for cand in res['candidates'][cat]:
|
| 224 |
+
if not cand['url'].startswith('https://'): res['notes'].append(f'{cat}: http-only {cand["url"]} (transport=http, not fetched)'); continue
|
| 225 |
+
if cand['url'] in res['chosen'].values():
|
| 226 |
+
res['chosen'][cat]=cand['url']; break
|
| 227 |
+
g=fetch(cand['url'])
|
| 228 |
+
if g and g[0].status_code==200: res['chosen'][cat]=g[0].url; break
|
| 229 |
+
res['notes'].append(f'{cat}: {cand["url"]} -> {g[0].status_code if g else "err"}')
|
| 230 |
+
if len([x for x in res['notes'] if x.startswith(cat+':')])>=2: break
|
| 231 |
+
except HostBlocked as e: res['status']=f'blocked: {e}'
|
| 232 |
+
json.dump(res,open(out,'w'),indent=1); log('P0',st,res['status'],res['chosen'])
|
| 233 |
+
# ---------------- extraction ----------------
|
| 234 |
+
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)'
|
| 235 |
+
NM=r"([A-Z][a-zA-Z\.'\-]+(?:\s+[A-Z][a-zA-Z\.'\-]*\.?){1,4}(?:,?\s+(?:Jr\.|Sr\.|II|III|IV))?)"
|
| 236 |
+
J1=re.compile(r'^(?:The\s+)?(?:Hon(?:orable|\.)\s+)?'+TITLES+r'\s+'+NM+r'$')
|
| 237 |
+
J2=re.compile(r'^(?:The\s+)?(?:Hon(?:orable|\.)\s+)?'+NM+r',?\s+[-–]?\s*'+TITLES+r'$')
|
| 238 |
+
J3=re.compile(r'^(?:The\s+)?Hon(?:orable|\.)\s+'+NM+r'$')
|
| 239 |
+
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')
|
| 240 |
+
def lines_with_ctx(soup):
|
| 241 |
+
for t in soup(['script','style','noscript','nav','footer','header']): t.decompose()
|
| 242 |
+
out=[]; head=None
|
| 243 |
+
title=(soup.title.get_text(' ').strip() if soup.title else '')
|
| 244 |
+
for el in soup.find_all(['h1','h2','h3','h4','h5','p','li','td','th','div','span','strong','b','address','dt','dd','a']):
|
| 245 |
+
if el.name in('h1','h2','h3','h4','h5'):
|
| 246 |
+
head=' '.join(el.get_text(' ').split())[:200]
|
| 247 |
+
text=soup.get_text('\n')
|
| 248 |
+
cur=title; res=[]
|
| 249 |
+
hs={' '.join(h.get_text(' ').split()) for h in soup.find_all(['h1','h2','h3','h4','h5'])}
|
| 250 |
+
for l in text.split('\n'):
|
| 251 |
+
l=' '.join(l.split())
|
| 252 |
+
if not l: continue
|
| 253 |
+
if l in hs: cur=l
|
| 254 |
+
res.append((l,cur))
|
| 255 |
+
return res,title
|
| 256 |
+
def ext_judges(st,url,sha,soup):
|
| 257 |
+
rows=[]; L,title=lines_with_ctx(soup); seen=set()
|
| 258 |
+
for l,ctx in L:
|
| 259 |
+
if len(l)>90: continue
|
| 260 |
+
m=J1.match(l); name=title_=None
|
| 261 |
+
if m: title_,name=m.group(1),m.group(2)
|
| 262 |
+
else:
|
| 263 |
+
m=J2.match(l)
|
| 264 |
+
if m: name,title_=m.group(1),m.group(2)
|
| 265 |
+
else:
|
| 266 |
+
m=J3.match(l)
|
| 267 |
+
if m: name,title_=m.group(1),'Judge (Honorable)'
|
| 268 |
+
if not name: continue
|
| 269 |
+
name=name.strip(' ,');
|
| 270 |
+
if BADW.search(name) or len(name.split())<2 or len(name)>60: continue
|
| 271 |
+
court=ctx if ctx and 'court' in ctx.lower() else (title if 'court' in title.lower() else ctx or title)
|
| 272 |
+
k=(name,title_,court)
|
| 273 |
+
if k in seen: continue
|
| 274 |
+
seen.add(k)
|
| 275 |
+
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,
|
| 276 |
+
title=title_,subdivision_iso=f'US-{st}',as_of=datetime.date.today().isoformat(),roster_url=url,
|
| 277 |
+
_privacy='official public roster only: name, court, title',**prov(url,sha)))
|
| 278 |
+
return rows
|
| 279 |
+
CITY=lambda st: re.compile(r"^([A-Z][A-Za-z\.'\- ]{1,40}),?\s+(?:"+st+'|'+re.escape(ISO[f'US-{st}'])+r")\.?,?\s+(\d{5})(?:-\d{4})?$")
|
| 280 |
+
STREET=re.compile(r'^(\d{1,6}\s+\S.{2,80}|P\.?\s?O\.?\s+Box\s+\d+.*)$',re.I)
|
| 281 |
+
NAMEOK=re.compile(r'(Court|Courthouse|Justice Center|Judicial|Clerk|Hall of Justice|Building|Magistrate|Center|Complex)',re.I)
|
| 282 |
+
def ext_courthouses(st,url,sha,soup):
|
| 283 |
+
rows=[]; L,title=lines_with_ctx(soup); cre=CITY(st); seen=set()
|
| 284 |
+
for i,(l,ctx) in enumerate(L):
|
| 285 |
+
m=cre.match(l)
|
| 286 |
+
if not m or i==0: continue
|
| 287 |
+
street=L[i-1][0]
|
| 288 |
+
if not STREET.match(street):
|
| 289 |
+
# street and city on one line?
|
| 290 |
+
continue
|
| 291 |
+
name=None
|
| 292 |
+
for j in range(i-2,max(-1,i-5),-1):
|
| 293 |
+
c=L[j][0]
|
| 294 |
+
if NAMEOK.search(c) and len(c)<120 and not STREET.match(c): name=c; break
|
| 295 |
+
name=name or (ctx if ctx and NAMEOK.search(ctx) else None)
|
| 296 |
+
if not name: continue
|
| 297 |
+
k=(name,street)
|
| 298 |
+
if k in seen: continue
|
| 299 |
+
seen.add(k)
|
| 300 |
+
rows.append(dict(courthouse_id=sid(st,name,street),court_id=sid(st,'court',name) if 'court' in name.lower() else None,name=name,
|
| 301 |
+
address_line=street,locality=m.group(1).strip(),postal_code=m.group(2),country='US',subdivision_iso=f'US-{st}',
|
| 302 |
+
lat=None,lon=None,**prov(url,sha)))
|
| 303 |
+
return rows
|
| 304 |
+
FILEEXT=('.pdf','.doc','.docx','.rtf','.dot','.dotx','.xls','.xlsx','.odt')
|
| 305 |
+
FNUM=re.compile(r'\b([A-Z]{1,6}[- ]?\d{1,5}(?:[-.]\d{1,4})?[A-Z]?)\b')
|
| 306 |
+
def ext_formlinks(base,soup):
|
| 307 |
+
out=[]
|
| 308 |
+
for u,t in links(base,soup):
|
| 309 |
+
path=up.urlparse(u).path.lower()
|
| 310 |
+
if path.endswith(FILEEXT): out.append((u,t))
|
| 311 |
+
return out
|
| 312 |
+
def classify_level(name):
|
| 313 |
+
n=name.lower()
|
| 314 |
+
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')]:
|
| 315 |
+
if k in n: return v
|
| 316 |
+
return 'state'
|
| 317 |
+
# ---------------- Phase 1/2 per state ----------------
|
| 318 |
+
def collect_state(ph,st):
|
| 319 |
+
d=f'{ST_DIR}/phase{ph}/{st}'; os.makedirs(d,exist_ok=True)
|
| 320 |
+
if os.path.exists(f'{d}/DONE'): return
|
| 321 |
+
if st in NEVER: log('SKIP never-retry state',st); return
|
| 322 |
+
disc=json.load(open(f'{ST_DIR}/phase0/{st}.json')) if os.path.exists(f'{ST_DIR}/phase0/{st}.json') else {}
|
| 323 |
+
status={'state':st,'status':'ok','notes':[],'pages':{},'skips':[]}
|
| 324 |
+
if st in DEFERRED: status['status']='deferred'; status['notes'].append(DEFERRED[st])
|
| 325 |
+
elif str(disc.get('status','')).startswith('blocked'): status['status']='host stopped in phase0: '+disc['status']
|
| 326 |
+
elif not disc.get('chosen') and not disc.get('landing'): status['status']='no discovery'
|
| 327 |
+
tables={k:[] for k in ('judges','courthouses','forms')}
|
| 328 |
+
ck=f'{d}/ckpt.json'; ckd=json.load(open(ck)) if os.path.exists(ck) else {}
|
| 329 |
+
if status['status']=='ok':
|
| 330 |
+
try:
|
| 331 |
+
for cat in ('courthouses','judges','forms'):
|
| 332 |
+
if cat in ckd: tables[cat]=[json.loads(l) for l in open(f'{d}/{cat}.jsonl')]; continue
|
| 333 |
+
start=disc.get('chosen',{}).get(cat)
|
| 334 |
+
if not start: status['skips'].append({'table':cat,'reason':'no candidate page found in static landing HTML'}); ckd[cat]=0; continue
|
| 335 |
+
root=up.urlparse(start).netloc; q=[start]; seen={start}; npg=0; files=[]
|
| 336 |
+
while q and npg<MAXP[cat] and not STOP.is_set():
|
| 337 |
+
u=q.pop(0); f=fetch(u)
|
| 338 |
+
if not f: status['skips'].append({'url':u,'reason':'http-only or network error','transport':'http' if u.startswith('http:') else 'https'}); continue
|
| 339 |
+
r,b,sha,n=f; npg+=1
|
| 340 |
+
if r.status_code!=200 or 'html' not in r.headers.get('content-type',''): continue
|
| 341 |
+
soup=BeautifulSoup(b,'lxml'); L=links(r.url,soup)
|
| 342 |
+
if cat=='forms':
|
| 343 |
+
for fu,ft in ext_formlinks(r.url,soup):
|
| 344 |
+
if fu not in {x[0] for x in files}: files.append((fu,ft,r.url))
|
| 345 |
+
for lu,lt in L:
|
| 346 |
+
if lu in seen or not samesite(lu,root) or up.urlparse(lu).path.lower().endswith(FILEEXT): continue
|
| 347 |
+
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])):
|
| 348 |
+
seen.add(lu)
|
| 349 |
+
if lu.startswith('https://'): q.append(lu)
|
| 350 |
+
else: status['skips'].append({'url':lu,'reason':'http-only link not fetched','transport':'http'})
|
| 351 |
+
if cat=='judges': tables['judges']+=ext_judges(st,r.url,sha,soup)
|
| 352 |
+
if cat=='courthouses': tables['courthouses']+=ext_courthouses(st,r.url,sha,soup)
|
| 353 |
+
# courthouse/judge info often co-located
|
| 354 |
+
if cat=='courthouses': tables['judges']+=[]
|
| 355 |
+
status['pages'][cat]=npg
|
| 356 |
+
if cat=='forms':
|
| 357 |
+
for fu,ft,src in files[:MAXFILES]:
|
| 358 |
+
if STOP.is_set(): break
|
| 359 |
+
if not fu.startswith('https://'): status['skips'].append({'url':fu,'reason':'http-only form not fetched','transport':'http'}); continue
|
| 360 |
+
g=fetch(fu,stream=True)
|
| 361 |
+
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
|
| 362 |
+
r,_,sha,n=g; fn=up.unquote(up.urlparse(fu).path.rsplit('/',1)[-1])
|
| 363 |
+
m=FNUM.search(ft) or FNUM.search(fn.rsplit('.',1)[0].upper())
|
| 364 |
+
lang='es' if re.search(r'spanish|espa[nñ]ol',ft+fn,re.I) else 'en'
|
| 365 |
+
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,
|
| 366 |
+
subdivision_iso=f'US-{st}',language=lang,file_url=r.url,file_format=fn.rsplit('.',1)[-1].lower() if '.' in fn else None,
|
| 367 |
+
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})))
|
| 368 |
+
if len(files)>MAXFILES: status['notes'].append(f'forms capped at {MAXFILES} of {len(files)} file links')
|
| 369 |
+
if STOP.is_set(): break
|
| 370 |
+
# dedupe + checkpoint
|
| 371 |
+
k={'judges':'judge_id','courthouses':'courthouse_id','forms':'form_id'}[cat]
|
| 372 |
+
u={}; [u.setdefault(x[k],x) for x in tables[cat]]; tables[cat]=list(u.values())
|
| 373 |
+
with open(f'{d}/{cat}.jsonl','w') as fo:
|
| 374 |
+
for x in tables[cat]: fo.write(json.dumps(x)+'\n')
|
| 375 |
+
ckd[cat]=len(tables[cat]); json.dump(ckd,open(ck,'w'))
|
| 376 |
+
except HostBlocked as e:
|
| 377 |
+
status['status']=f'host stopped: {e}'; status['skips'].append({'reason':str(e)})
|
| 378 |
+
if STOP.is_set() and status['status']=='ok': return # leave for resume
|
| 379 |
+
# judges also: dedupe; write partials if blocked
|
| 380 |
+
for cat in ('courthouses','judges','forms'):
|
| 381 |
+
if not os.path.exists(f'{d}/{cat}.jsonl') or cat not in ckd:
|
| 382 |
+
with open(f'{d}/{cat}.jsonl','w') as fo:
|
| 383 |
+
for x in tables[cat]: fo.write(json.dumps(x)+'\n')
|
| 384 |
+
# courts derived from courthouse + judge court names
|
| 385 |
+
courts={}
|
| 386 |
+
for x in tables['courthouses']+tables['judges']:
|
| 387 |
+
nm=x.get('name') if 'courthouse_id' in x else x.get('court_name')
|
| 388 |
+
cid=x.get('court_id')
|
| 389 |
+
if not cid or not nm or 'court' not in nm.lower(): continue
|
| 390 |
+
courts.setdefault(cid,dict(court_id=cid,name=nm,name_local=nm,country='US',subdivision_iso=f'US-{st}',level=classify_level(nm),
|
| 391 |
+
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')}))
|
| 392 |
+
with open(f'{d}/courts.jsonl','w') as fo:
|
| 393 |
+
for x in courts.values(): fo.write(json.dumps(x)+'\n')
|
| 394 |
+
status['counts']={'courts':len(courts),**{k:len(v) for k,v in tables.items()}}
|
| 395 |
+
json.dump(status,open(f'{d}/status.json','w'),indent=1)
|
| 396 |
+
if 'guard stop' not in str(status['status']) and not STOP.is_set(): open(f'{d}/DONE','w').write(now())
|
| 397 |
+
log('STATE DONE',ph,st,status['status'],status.get('counts'))
|
| 398 |
+
def review(ph,states):
|
| 399 |
+
out=f'{RV}/phase{ph}'; os.makedirs(out,exist_ok=True)
|
| 400 |
+
mat=json.load(open('/workspace/coverage/subnational_state_matrix_20261025.json'))['rows']
|
| 401 |
+
fk={r.get('iso_3166_2') for r in mat}|{r.get('iso') for r in mat if r.get('iso')}
|
| 402 |
+
rep={'phase':ph,'generated':now(),'states':{},'validation':{},'skips':{}}
|
| 403 |
+
man=[]
|
| 404 |
+
if ph==0:
|
| 405 |
+
for st in states:
|
| 406 |
+
p=f'{ST_DIR}/phase0/{st}.json'
|
| 407 |
+
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)
|
| 408 |
+
else:
|
| 409 |
+
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'],
|
| 410 |
+
'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']}
|
| 411 |
+
val={t:{'rows':0,'missing_required':0,'bad_fk':0,'dup_ids':0,'non_https':0} for t in req}
|
| 412 |
+
samples={t:[] for t in req}
|
| 413 |
+
for st in states:
|
| 414 |
+
d=f'{ST_DIR}/phase{ph}/{st}'
|
| 415 |
+
if not os.path.exists(f'{d}/status.json'): rep['states'][st]={'status':'not finished'}; continue
|
| 416 |
+
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']}
|
| 417 |
+
rep['skips'][st]=s['skips'][:50]
|
| 418 |
+
for t in req:
|
| 419 |
+
p=f'{d}/{t}.jsonl'
|
| 420 |
+
if not os.path.exists(p): continue
|
| 421 |
+
man.append(p); ids=set(); pk=req[t][0]
|
| 422 |
+
for l in open(p):
|
| 423 |
+
x=json.loads(l); v=val[t]; v['rows']+=1
|
| 424 |
+
if any(x.get(k) in (None,'') for k in req[t]): v['missing_required']+=1
|
| 425 |
+
if x.get('subdivision_iso') not in fk: v['bad_fk']+=1
|
| 426 |
+
if x[pk] in ids: v['dup_ids']+=1
|
| 427 |
+
ids.add(x[pk])
|
| 428 |
+
if x.get('transport')!='https': v['non_https']+=1
|
| 429 |
+
if len(samples[t])<15 and (len(samples[t])<3 or hash(x[pk])%7==0): samples[t].append(x)
|
| 430 |
+
rep['validation']=val
|
| 431 |
+
json.dump(samples,open(f'{out}/samples.json','w'),indent=1)
|
| 432 |
+
rep['hosts']={h:{'requests':H.n,'delay_s':H.delay,'blocked':H.blocked} for h,H in HOSTS.items()}
|
| 433 |
+
json.dump(rep,open(f'{out}/report.json','w'),indent=1)
|
| 434 |
+
with open(f'{out}/MANIFEST.sha256','w') as fo:
|
| 435 |
+
for p in man: fo.write(hashlib.sha256(open(p,'rb').read()).hexdigest()+' '+os.path.relpath(p,BASE)+'\n')
|
| 436 |
+
open(f'{out}/REVIEW_READY','w').write(now()); log('REVIEW_READY',ph)
|
| 437 |
+
def run_pool(fn,states,ph=None):
|
| 438 |
+
with ThreadPoolExecutor(1) as ex:
|
| 439 |
+
list(ex.map(lambda s:(fn(ph,s) if ph is not None else fn(s)),states))
|
| 440 |
+
def main():
|
| 441 |
+
os.makedirs(f'{ST_DIR}/phase0',exist_ok=True)
|
| 442 |
+
allst=PH1+PH2+list(DEFERRED)
|
| 443 |
+
log('START pid',os.getpid(),f'memfloor={MEMFLOOR} maxstrikes={MAXSTRIKES} strikegap={STRIKEGAP}s')
|
| 444 |
+
if not os.path.exists(BLF):
|
| 445 |
+
for st in allst:
|
| 446 |
+
p=f'{ST_DIR}/phase0/{st}.json'
|
| 447 |
+
if os.path.exists(p):
|
| 448 |
+
m=re.search(r'blocked: (.*) at (https://[^/]+)/',json.load(open(p))['status'])
|
| 449 |
+
if m: save_block(up.urlparse(m.group(2)).netloc,m.group(0))
|
| 450 |
+
load_blocks()
|
| 451 |
+
if not os.path.exists(f'{BASE}/PHASE0_DONE'):
|
| 452 |
+
run_pool(phase0_state,allst)
|
| 453 |
+
if STOP.is_set(): return STOPRC[0]
|
| 454 |
+
review(0,allst); open(f'{BASE}/PHASE0_DONE','w').write(now())
|
| 455 |
+
for ph,sts in ((1,PH1),(2,PH2)):
|
| 456 |
+
if os.path.exists(f'{BASE}/PHASE{ph}_DONE'): continue
|
| 457 |
+
run_pool(collect_state,sts,ph)
|
| 458 |
+
if STOP.is_set(): return STOPRC[0]
|
| 459 |
+
review(ph,sts); open(f'{BASE}/PHASE{ph}_DONE','w').write(now())
|
| 460 |
+
return 0
|
| 461 |
+
if __name__=='__main__':
|
| 462 |
+
try: rc=main()
|
| 463 |
+
except Exception as e:
|
| 464 |
+
import traceback; log('CRASH',traceback.format_exc()); rc=1
|
| 465 |
+
log('EXIT rc',rc); sys.exit(rc)
|
scrapers_and_normalizers/courts/collector/state_rules2.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Official state court rules index collector (stage only). Sequential, 1 req/10s+, robots/Crawl-delay honored, HTTPS only."""
|
| 3 |
+
import sys,os,json,re,urllib.parse,hashlib
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import us_fed as U
|
| 6 |
+
from us_fed import log,fetch,links,sid,now
|
| 7 |
+
OUT='/workspace/courts/staging/state_rules/official';os.makedirs(OUT+'/files',exist_ok=True)
|
| 8 |
+
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'),
|
| 9 |
+
('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'),
|
| 10 |
+
('TX','https://www.txcourts.gov/rules-forms/rules-standards/')]
|
| 11 |
+
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()}}
|
| 12 |
+
RULE=re.compile(r'rule|court-rules|courtrules|procedure|\.pdf',re.I)
|
| 13 |
+
def run(st,idx,cap=None):
|
| 14 |
+
done_f=f'{OUT}/{st}.jsonl'
|
| 15 |
+
if os.path.exists(done_f+'.done'):return
|
| 16 |
+
cap=cap or (60 if st=="TX" else 300);delay=720 if st=="TX" else 10
|
| 17 |
+
r=fetch(idx,delay=delay)
|
| 18 |
+
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
|
| 19 |
+
host=urllib.parse.urlsplit(r[0]).netloc;seen=set();n=0
|
| 20 |
+
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]]
|
| 21 |
+
with open(done_f,'w') as o:
|
| 22 |
+
for h,t in cand:
|
| 23 |
+
h=h.split('#')[0]
|
| 24 |
+
if h in seen or n>=cap:continue
|
| 25 |
+
seen.add(h);fn=f'{OUT}/files/{st}_{sid(h)}';g=fetch(h,delay=delay,stream_to=fn)
|
| 26 |
+
if not g:continue
|
| 27 |
+
fu,sha,nb=g
|
| 28 |
+
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
|
| 29 |
+
open(done_f+'.done','w').write(now());log('STATE',st,'rows',n,'of',len(cand),'candidates')
|
| 30 |
+
if __name__=='__main__':
|
| 31 |
+
log('STATE_RULES2 START pid',os.getpid())
|
| 32 |
+
with open(f'{OUT}/skips.jsonl','a') as f:
|
| 33 |
+
for k,v in SKIP.items():f.write(json.dumps(dict(state=k,reason=v))+'\n')
|
| 34 |
+
for st,u in S:
|
| 35 |
+
try:run(st,u)
|
| 36 |
+
except SystemExit:raise
|
| 37 |
+
except Exception as e:log('STATE_ERR',st,repr(e)[:200])
|
| 38 |
+
log('STATE_RULES2 DONE')
|
scrapers_and_normalizers/courts/collector/state_rules3.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Rerun: NE (malformed-link fix), DE (parser fix), KS (cap lifted). Stage only."""
|
| 3 |
+
import sys,os,json,re,urllib.parse,html
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import us_fed as U, state_rules2 as S2
|
| 6 |
+
from us_fed import log
|
| 7 |
+
HREF=re.compile(r'<a\b[^>]*?href\s*=\s*["\']([^"\']+)["\'][^>]*>(.*?)</a>',re.I|re.S)
|
| 8 |
+
def safe_links(base,b):
|
| 9 |
+
out=[]
|
| 10 |
+
for h,t in HREF.findall(b.decode('utf-8','ignore')):
|
| 11 |
+
h=html.unescape(h.strip())
|
| 12 |
+
if h.startswith(('javascript:','mailto:','tel:','#')):continue
|
| 13 |
+
try:u=urllib.parse.urljoin(base,h);urllib.parse.urlsplit(u).hostname
|
| 14 |
+
except ValueError:log('BAD_LINK skipped',h[:80]);continue
|
| 15 |
+
out.append((u,' '.join(re.sub(r'<[^>]+>',' ',t).split())))
|
| 16 |
+
return out
|
| 17 |
+
S2.links=safe_links
|
| 18 |
+
S2.OUT='/workspace/courts/staging/state_rules_rerun';os.makedirs(S2.OUT+'/files',exist_ok=True)
|
| 19 |
+
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)]
|
| 20 |
+
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'}
|
| 21 |
+
_orig=S2.run
|
| 22 |
+
def run(st,u,cap):
|
| 23 |
+
import builtins
|
| 24 |
+
S2.re_cap=cap
|
| 25 |
+
src=open('/workspace/courts/collector/state_rules2.py').read()
|
| 26 |
+
return _orig(st,u)
|
| 27 |
+
if __name__=='__main__':
|
| 28 |
+
log('STATE_RULES3 START pid',os.getpid())
|
| 29 |
+
with open(S2.OUT+'/skips.jsonl','a') as f:
|
| 30 |
+
for k,v in SKIP.items():f.write(json.dumps(dict(state=k,reason=v))+'\n')
|
| 31 |
+
for st,u,cap in JOBS:
|
| 32 |
+
try:S2.run(st,u,cap)
|
| 33 |
+
except SystemExit:raise
|
| 34 |
+
except Exception as e:log('STATE_ERR',st,repr(e)[:200])
|
| 35 |
+
log('STATE_RULES3 DONE')
|
scrapers_and_normalizers/courts/collector/state_rules4.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Resume: KS (skip done URLs), NE (remaining candidates), DE (one more parser look). Stage only."""
|
| 3 |
+
import sys,os,json,re,urllib.parse
|
| 4 |
+
sys.path.insert(0,'/workspace/courts/collector')
|
| 5 |
+
import us_fed as U, state_rules3 as S3
|
| 6 |
+
from us_fed import log,fetch,sid,now
|
| 7 |
+
O='/workspace/courts/staging/state_rules_rerun';OFF='/workspace/courts/staging/state_rules/official'
|
| 8 |
+
RULE=re.compile(r'rule|court-rules|courtrules|procedure|\.pdf',re.I)
|
| 9 |
+
def ids(*fs):
|
| 10 |
+
s=set()
|
| 11 |
+
for f in fs:
|
| 12 |
+
if os.path.exists(f):
|
| 13 |
+
for l in open(f):
|
| 14 |
+
r=json.loads(l);s.add(r['rule_id']);s.add(r.get('file_url',''))
|
| 15 |
+
return s
|
| 16 |
+
def run(st,idx,skip):
|
| 17 |
+
r=fetch(idx,delay=10)
|
| 18 |
+
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
|
| 19 |
+
host=urllib.parse.urlsplit(r[0]).netloc
|
| 20 |
+
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]))
|
| 21 |
+
tmap={h.split('#')[0]:t for h,t in S3.safe_links(r[0],r[1])}
|
| 22 |
+
todo=[h for h in cand if sid(st,h) not in skip and h not in skip]
|
| 23 |
+
log('STATE',st,'candidates',len(cand),'already_done',len(cand)-len(todo),'todo',len(todo))
|
| 24 |
+
if st=='DE' and not cand:
|
| 25 |
+
open(O+'/skips.jsonl','a').write(json.dumps(dict(state='DE',url=idx,reason='no_static_links'))+'\n');return
|
| 26 |
+
n=0
|
| 27 |
+
with open(f'{O}/{st}_resume.jsonl','a') as o:
|
| 28 |
+
for h in todo:
|
| 29 |
+
fn=f'{O}/files/{st}_{sid(h)}';g=fetch(h,delay=10,stream_to=fn)
|
| 30 |
+
if not g:continue
|
| 31 |
+
fu,sha,nb=g
|
| 32 |
+
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
|
| 33 |
+
log('STATE',st,'resume rows',n)
|
| 34 |
+
if __name__=='__main__':
|
| 35 |
+
log('STATE_RULES4 START pid',os.getpid())
|
| 36 |
+
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')]:
|
| 37 |
+
try:run(st,u,ids(f'{OFF}/{st}.jsonl',f'{O}/{st}.jsonl',f'{O}/{st}_resume.jsonl'))
|
| 38 |
+
except SystemExit:raise
|
| 39 |
+
except Exception as e:log('STATE_ERR',st,repr(e)[:200])
|
| 40 |
+
log('STATE_RULES4 DONE')
|