"""Fixed different-dataset replay on previously viewed Khanom source polygons."""
import json,hashlib,time,datetime,os,signal,ctypes
from pathlib import Path
import numpy as np,torch
from PIL import Image,ImageDraw
from cellpose import models
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r92/khanom';W=Path('/tmp/diatom-cellpose-models/cpsam_v2')
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
def masks(arr):return np.stack(arr) if len(arr) else np.zeros((0,512,512),bool)
def panel(rgb,refs,sam,cp,union,path):
 out=Image.new('RGB',(1200,340),'white');d=ImageDraw.Draw(out)
 for k,(title,arr) in enumerate([('Source polygons',refs),('MobileSAM top 30',sam[:30]),('Cellpose top 30',cp[:30]),('Union top 30',union[:30])]):
  tile=Image.fromarray(rgb).convert('RGBA')
  for i,m in enumerate(arr):
   lay=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);lay.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,lay)
  out.paste(tile.convert('RGB').resize((290,290)),(k*300+5,30));d.text((k*300+5,8),title,fill='#203a38')
 out.save(path)
def main():
 # Linux ties the actual Python process to its launcher, so a vanished launcher cannot leave inference running.
 parent=os.getppid();libc=ctypes.CDLL(None,use_errno=True);assert libc.prctl(1,signal.SIGTERM)==0
 if os.getppid()!=parent:raise RuntimeError('Launcher exited before parent-death protection was installed')
 p=json.loads((O/'protocol.json').read_text());assert W.stat().st_size==p['model_bytes'] and sha(W)==p['model_sha256']
 for name,hash in p['input_files'].items():assert sha(R/name)==hash
 resume=json.loads((O/'resumption.json').read_text());assert sha(O/'protocol.json')==resume['protocol_sha256'] and sha(O/'partial-results.json')==resume['checkpoint_sha256'];records=json.loads((O/'partial-results.json').read_text())['records'];assert len(records)==resume['completed'];expected=[f'r84-{i:02d}' for i in range(16)]+[f'r85-{i:02d}' for i in range(4)];assert [r['name'] for r in records]==expected[:len(records)];saved=len(records);print(f'Resuming after {saved} verified fields with two CPU threads',flush=True);pairs=json.loads((R/'results/r85/all-overlap-scan.json').read_text())['overlap_pairs'];torch.set_num_threads(2);model=models.CellposeModel(gpu=False,pretrained_model=str(W),use_bfloat16=False);position=0
 for group in ('r84','r85'):
  D=R/'results'/group;selection=json.loads((D/'selection.json').read_text())['records'];files=json.loads((D/'image-manifest.json').read_text())['files'];prior=json.loads((D/'results.json').read_text())['records'];assert len(selection)==len(files)==len(prior)==(16 if group=='r84' else 4)
  for sel,f,oldrow in zip(selection,files,prior):
   if position<saved:
    assert records[position]['name']==f"{group}-{oldrow['index']:02d}";position+=1;continue
   position+=1
   assert sel['filename']==oldrow['filename'] and sha(R/f['path'])==f['sha256']==oldrow['source_image_sha256'] and sha(D/oldrow['archive'])==oldrow['archive_sha256'];z=np.load(D/oldrow['archive']);refs=z['refs'];ids=z['annotation_ids'].tolist();orig=Image.open(R/f['path']).convert('RGB');assert orig.size==(1600,1200);rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(orig.resize((512,384),Image.Resampling.LANCZOS))
   shape=tuple(z['mask_shape']);raw=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup=dict(zip(z['ids'].tolist(),raw));sam=[lookup[i] for i in oldrow['policies']['64']['ranking']];t=time.monotonic();lab,flows,_=model.eval(rgb,batch_size=1,channel_axis=-1,normalize=True,diameter=None,flow_threshold=.4,cellprob_threshold=0.,min_size=15,max_size_fraction=.4,niter=None,augment=False,tile_overlap=.1,bsize=256,resample=True,compute_masks=True);seconds=time.monotonic()-t;lab=np.asarray(lab);prob=np.asarray(flows[2]);flow=np.asarray(flows[1]);assert lab.shape==prob.shape==(512,512) and np.isfinite(prob).all() and np.isfinite(flow).all();order=sorted((int(x) for x in np.unique(lab) if x),key=lambda j:(-float(prob[lab==j].mean()),j));cp=[lab==j for j in order];union=[]
   for k in range(max(len(sam),len(cp))):
    if k<len(sam):union.append(sam[k])
    if k<len(cp):union.append(cp[k])
   scores={}
   for name,arr in [('sam',sam),('cellpose',cp),('union',union)]:
    scores[name]={str(n):{str(th):match(refs,ids,masks(arr if n=='all' else arr[:n]),th) for th in (.5,.75)} for n in (10,30,'all')}
   assert scores['sam']['30']==oldrow['policies']['64']['scores']['30'];pairids=sorted({i for pair in pairs if pair['coco_file']==sel['coco_file'] and pair['image']==sel['filename'] for i in pair['ids']});ix=[k for k,id in enumerate(ids) if id in pairids];assert len(ix)==len(pairids);pair_scores={name:{str(th):match(refs[ix],[ids[k] for k in ix],masks(arr[:30]),th) for th in (.5,.75)} for name,arr in [('sam',sam),('cellpose',cp),('union',union)]} if ix else None
   name=f"{group}-{oldrow['index']:02d}";arch=O/(name+'.npz');np.savez_compressed(arch,labels=lab,cellprob=prob,flow=flow,refs=refs,annotation_ids=np.array(ids),candidate_labels=np.array(order),pair_ids=np.array(pairids));pic=O/(name+'.png');panel(rgb,refs,sam,cp,union,pic)
   rec={'name':name,'group':group,'filename':sel['filename'],'kind':sel.get('kind','test'),'source_path':f['path'],'source_sha256':f['sha256'],'source_coco':sel['coco_file'],'source_archive':str((D/oldrow['archive']).relative_to(R)),'source_archive_sha256':oldrow['archive_sha256'],'references':len(refs),'pair_ids':pairids,'pair_scores':pair_scores,'sam_count':len(sam),'cellpose_count':len(cp),'union_count':len(union),'seconds':round(seconds,3),'cpu_threads':2,**scores,'archive':arch.name,'archive_sha256':sha(arch),'image':pic.name,'image_sha256':sha(pic)};records.append(rec);(O/'partial-results.tmp').write_text(json.dumps({'records':records},indent=2)+'\n');os.replace(O/'partial-results.tmp',O/'partial-results.json');(O/'progress.tmp').write_text(json.dumps({'completed':len(records),'total':20,'last_case':name,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Checkpoint does not establish process liveness.'},indent=2)+'\n');os.replace(O/'progress.tmp',O/'progress.json');print(len(records),name,'refs',len(refs),'sam/cellpose/union',*[scores[k]['30']['0.5']['matched'] for k in ('sam','cellpose','union')],'seconds',round(seconds,1),flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r92-khanom-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
if __name__=='__main__':main()
