#!/usr/bin/env python3 """Derive an OpenAlex-wide queue from screened links and explicit collection mappings.""" from __future__ import annotations import argparse, collections, csv, datetime as dt, hashlib, io, json, os, re, tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CSV_PATH = 'planning/openalex_workqueue.csv' SUMMARY_PATH = 'planning/workqueue_summary.json' STATE_PATH = 'planning/workqueue_state.json' QUEUE_FIELDS = ['priority','domain_id','domain_name','field_id','field_name','subfield_id','subfield_name','topic_count','valid_pdf_count','book_scope_pdf_count','verified_entry_count','distinct_pdf_url_count','collection_count','collection_ids','count_basis','availability','historical_round_status','completed_rounds','last_search_at','last_new_entries','last_new_pdfs','owner','lease_id','generation','lease_expires_at','cooldown_until','prompt_file'] BOOK_TYPES = {'textbook','handbook','scholarly_book','edited_collection','book_chapter','doctoral_thesis','research_thesis','thesis_framing_text','habilitation_thesis','research_report'} def read_jsonl(path): return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] def utc(value=None): if value is None: return dt.datetime.now(dt.timezone.utc) if isinstance(value,str): value=dt.datetime.fromisoformat(value.replace('Z','+00:00')) if not isinstance(value,dt.datetime) or value.tzinfo is None or value.utcoffset()!=dt.timedelta(0): raise ValueError('Queue timestamps must be timezone-aware UTC') return value.astimezone(dt.timezone.utc) def timestamp(value): return utc(value).isoformat(timespec='seconds').replace('+00:00','Z') def atomic(path,text): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) fd,tmp=tempfile.mkstemp(prefix='.'+path.name+'.',dir=path.parent) try: with os.fdopen(fd,'w',encoding='utf-8',newline='') as f: f.write(text);f.flush();os.fsync(f.fileno()) os.replace(tmp,path) finally: if os.path.exists(tmp):os.unlink(tmp) def load_jobs(root): rows=read_jsonl(root/'planning/subfield_jobs.jsonl') ids=[str(r['subfield_id']) for r in rows] if len(ids)!=len(set(ids)):raise ValueError('Duplicate prepared subfield job') with (root/'taxonomy/openalex_subfields.csv').open(newline='',encoding='utf-8') as f: taxonomy=list(csv.DictReader(f)) taxids=[str(r['subfield_id']) for r in taxonomy] if len(taxids)!=len(set(taxids)) or set(taxids)!=set(ids): raise ValueError('Prepared job IDs differ from the saved official subfield taxonomy') return rows def collection_mapping(root,defs,known): p=root/'planning/collection_subfield_map.json' config=json.loads(p.read_text()) if p.exists() else {'schema_version':1,'collections':{}} if config.get('schema_version')!=1 or not isinstance(config.get('collections'),dict): raise ValueError('Invalid explicit collection mapping') registered={d['collection'] for d in defs} if set(config['collections'])-registered:raise ValueError('Mapping names an unknown collection') result={} for d in defs: key=d['collection'];entry=config['collections'].get(key) if entry is None: sid=d.get('openalex_subfield_id') entry={'subfield_ids':[str(sid)] if sid else [],'basis':'explicit_collection_definition' if sid else 'unassigned','rationale':'Explicit subfield association in the collection definition.' if sid else 'No explicit subfield mapping.'} ids=entry.get('subfield_ids') if not isinstance(ids,list) or any(not isinstance(s,str) or s not in known for s in ids) or len(set(ids))!=len(ids): raise ValueError('Invalid mapped subfield IDs for '+key) result[key]=entry return result def historical_finishes(root): result={} for p in sorted((root/'planning').glob('*search_progress.jsonl')): for row in read_jsonl(p): sid=str(row.get('subfield_id',''));finished=row.get('finished_at_utc','') if sid and finished and (sid not in result or utc(finished)>utc(result[sid])):result[sid]=timestamp(finished) return result def build(root,now=None): root=Path(root);now=utc(now);jobs=load_jobs(root);known={str(j['subfield_id']) for j in jobs} defs=json.loads((root/'collections.json').read_text()) if not isinstance(defs,list) or len({d['collection'] for d in defs})!=len(defs):raise ValueError('Invalid collection definitions') mapping=collection_mapping(root,defs,known) records=read_jsonl(root/'data/verified_links.jsonl') grouped=collections.defaultdict(list) for r in records: if r.get('status')!='downloaded_and_screened' or not re.fullmatch('[0-9a-f]{64}',r.get('sha256','')): raise ValueError('Queue counts require verified complete-file SHA256 records') if r['collection'] not in mapping:raise ValueError('Verified row has an unknown collection') grouped[r['collection']].append(r) state_path=root/STATE_PATH state=json.loads(state_path.read_text()) if state_path.exists() else {'schema_version':1,'tasks':{}} if state.get('schema_version')!=1 or not isinstance(state.get('tasks'),dict) or set(state['tasks'])-known: raise ValueError('Invalid authoritative queue state') per=collections.defaultdict(list);cols=collections.defaultdict(list);unassigned=[] for d in defs: c=d['collection'];ids=mapping[c]['subfield_ids'] if not ids: unassigned.append({'collection':c,'verified_entries':len(grouped[c]),'valid_pdf_count':len({r['sha256'] for r in grouped[c]}),'reason':mapping[c].get('rationale','')}) for sid in ids: per[sid].extend(grouped[c]);cols[sid].append(c) finishes=historical_finishes(root);rows=[] for j in jobs: sid=str(j['subfield_id']);t=state['tasks'].get(sid,{}) if not isinstance(t,dict):raise ValueError('Invalid state task '+sid) for name in ['generation','completed_rounds','last_new_entries','last_new_pdfs']: if type(t.get(name,0)) is not int or t.get(name,0)<0:raise ValueError('Invalid queue counter '+name) for name in ['lease_expires_at','cooldown_until','last_search_at']: if t.get(name):utc(t[name]) leased=bool(t.get('lease_expires_at')) and utc(t['lease_expires_at'])>now cooling=bool(t.get('cooldown_until')) and utc(t['cooldown_until'])>now if leased and (not t.get('owner') or not t.get('lease_id') or t.get('generation',0)<1):raise ValueError('Active lease lacks owner or fencing identity') picked=per[sid];hashes={r['sha256'] for r in picked} row={k:j.get(k,'') for k in ['domain_id','domain_name','field_id','field_name','subfield_name','topic_count','prompt_file']} row.update(subfield_id=sid,valid_pdf_count=len(hashes),book_scope_pdf_count=len({r['sha256'] for r in picked if r['work_type'] in BOOK_TYPES}),verified_entry_count=len(picked),distinct_pdf_url_count=len({r['pdf_url'] for r in picked}),collection_count=len(cols[sid]),collection_ids=';'.join(sorted(cols[sid])),count_basis='explicit_editorial_collection_assignments',availability='claimed' if leased else 'cooldown' if cooling else 'available',historical_round_status=j.get('status','planned'),completed_rounds=t.get('completed_rounds',0),last_search_at=t.get('last_search_at','') or finishes.get(sid,''),last_new_entries=t.get('last_new_entries',0),last_new_pdfs=t.get('last_new_pdfs',0),owner=t.get('owner','') if leased else '',lease_id=t.get('lease_id','') if leased else '',generation=t.get('generation',0),lease_expires_at=t.get('lease_expires_at','') if leased else '',cooldown_until=t.get('cooldown_until','')) rows.append(row) rows.sort(key=lambda r:(r['valid_pdf_count'],r['last_search_at'],int(r['subfield_id']))) for rank,row in enumerate(rows,1):row['priority']=rank unmapped={c['collection'] for c in unassigned};unmapped_rows=[r for r in records if r['collection'] in unmapped] mapped=[r for r in records if r['collection'] not in unmapped] summary={'schema_version':1,'generated_at_utc':timestamp(now),'subfields':len(rows),'fields':len({str(j['field_id']) for j in jobs}),'domains':len({str(j['domain_id']) for j in jobs}),'global_verified_entries':len(records),'global_distinct_pdfs':len({r['sha256'] for r in records}),'global_distinct_pdf_urls':len({r['pdf_url'] for r in records}),'mapped_verified_entries':len(mapped),'mapped_distinct_pdfs':len({r['sha256'] for r in mapped}),'unassigned_verified_entries':len(unmapped_rows),'unassigned_distinct_pdfs':len({r['sha256'] for r in unmapped_rows}),'unassigned_collections':unassigned,'zero_pdf_subfields':sum(r['valid_pdf_count']==0 for r in rows),'nonzero_pdf_subfields':sum(r['valid_pdf_count']>0 for r in rows),'subfield_pdf_assignments':sum(r['valid_pdf_count'] for r in rows),'availability':dict(collections.Counter(r['availability'] for r in rows)),'mapping_basis':'Editorial collection-level assignments; not official per-work OpenAlex classification. Only primary IDs from the existing navigation crosswalk are counted. Unassigned works remain in the catalogue but are excluded from subfield counts.','coverage_note':'A zero means no explicitly mapped screened PDF in this catalogue, not that no public work exists. Subfield rounds do not establish exhaustive topic coverage. completed_rounds counts completions through this queue since initialization; historical rounds retain their separate status.','canonical_catalogue_sha256':hashlib.sha256((root/'data/verified_links.jsonl').read_bytes()).hexdigest()} return rows,summary def render(root,now=None): root=Path(root);rows,summary=build(root,now) out=io.StringIO(newline='');writer=csv.DictWriter(out,fieldnames=QUEUE_FIELDS);writer.writeheader();writer.writerows(rows) atomic(root/CSV_PATH,out.getvalue());atomic(root/SUMMARY_PATH,json.dumps(summary,ensure_ascii=False,indent=2)+'\n') return summary def validate(root): root=Path(root);saved=json.loads((root/SUMMARY_PATH).read_text());rows,expected=build(root,now=saved['generated_at_utc']) with (root/CSV_PATH).open(newline='',encoding='utf-8') as f: reader=csv.DictReader(f) if reader.fieldnames!=QUEUE_FIELDS:raise ValueError('Workqueue CSV header differs') actual=list(reader) normalized=[{k:str(r[k]) for k in QUEUE_FIELDS} for r in rows] if actual!=normalized or saved!=expected:raise ValueError('Workqueue counts or states are stale') return expected if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('action',choices=['render','validate']);p.add_argument('root',type=Path,nargs='?',default=ROOT);a=p.parse_args() print(json.dumps(render(a.root) if a.action=='render' else validate(a.root),ensure_ascii=False))