"""Predeclared oracle-crop mask-choice comparison on Gündüz source components."""
import collections,ctypes,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
from r112_new_taxa_masks import points_for
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r115';D=R/'datasets/r115-gunduz';W=Path('/tmp/mobile_sam.pt')
def iou(a,b):
 u=int((a|b).sum());return float((a&b).sum()/u) if u else 0.
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('launcher exited')
 torch.set_num_threads(2);cv2.setNumThreads(2);p=json.loads((O/'protocol.json').read_text());assert not (O/'results.json').exists() and sha(W)==p['model_sha256'];
 for f,h in p['implementation_sha256'].items():assert sha(R/f)==h,f
 audit=json.loads((O/'annotation-audit.json').read_text());manifest=json.loads((O/'image-manifest.json').read_text());screen=json.loads((O/'leak-screen.json').read_text());assert audit['protocol_sha256']==manifest['protocol_sha256']==screen['protocol_sha256']==sha(O/'protocol.json') and screen['image_manifest_sha256']==sha(O/'image-manifest.json');meta={x['id']:x for x in audit['records']};selected={x['id']:x for x in audit['selected']};quarantine={x['id']:x for x in screen['records']};predictor=Predictor(overrides={'model':str(W),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'conf':0.});(O/'cases').mkdir(exist_ok=True);rows=[];names=['center','minus','plus'];start=time.monotonic()
 for image in manifest['records']:
  ident=image['id'];q=quarantine[ident]
  if q['quarantined']:rows.append({'id':ident,'status':'quarantined','minimum_crop_distance':q['minimum_crop_distance']});continue
  s=selected[ident];metaentry=meta[ident];path=R/image['path'];assert sha(path)==image['sha256'] and sha(D/'masks'/f'{ident}.png')==metaentry['mask_sha256'];source=np.asarray(Image.open(path).convert('L'));raw=np.asarray(Image.open(D/'masks'/f'{ident}.png').convert('L'))>0;_,labels=cv2.connectedComponents(raw.astype('uint8'),connectivity=8);ref=labels==s['component_label'];assert int(ref.sum())==s['component_area'];contours,_=cv2.findContours(ref.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);assert contours;contour=max(contours,key=cv2.contourArea).reshape(-1,2);assert len(contour)>=2;box=metaentry['objects'][s['box_index']]['box'];bx,by,bxx,byy=box;margin=.15*max(bxx-bx,byy-by);x0=max(0,int(np.floor(bx-margin)));y0=max(0,int(np.floor(by-margin)));x1=min(source.shape[1],int(np.ceil(bxx+margin)));y1=min(source.shape[0],int(np.ceil(byy+margin)));crop=source[y0:y1,x0:x1];target=ref[y0:y1,x0:x1];h,w=crop.shape;assert h>0 and w>0 and target.any();pseudo={'source_annotation_points_global':contour.tolist(),'source_annotation_bbox_global':[x0,y0,x1-1,y1-1],'source_dimensions_px':[w,h],'source_annotation_shape':'Polygon'};pts=points_for(pseudo);factor=min(1.,512/max(w,h));iw,ih=max(1,round(w*factor)),max(1,round(h*factor));im=crop if (iw,ih)==(w,h) else cv2.resize(crop,(iw,ih),interpolation=cv2.INTER_AREA);ox,oy=(512-iw)//2,(512-ih)//2;canvas=np.full((512,512),int(np.median(crop)),np.uint8);canvas[oy:oy+ih,ox:ox+iw]=im;model_pts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];predictor.set_image(cv2.cvtColor(canvas,cv2.COLOR_GRAY2BGR));pred=predictor(points=[[[x,y]] for x,y in model_pts],labels=[[1]]*3,verbose=False)[0];assert pred.masks is not None and len(pred.masks.data)==3;masks=[];files={}
  for name,m,score in zip(names,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
   out=cv2.resize(m[oy:oy+ih,ox:ox+iw].astype('uint8'),(w,h),interpolation=cv2.INTER_NEAREST)>0;masks.append(out);fp=O/'cases'/f'{ident}-{name}.png';Image.fromarray(out.astype('uint8')*255).save(fp);files[name]={'file':str(fp.relative_to(O)),'sha256':sha(fp),'area_px':int(out.sum()),'model_quality_not_accuracy':float(score)}
  for name,pixels in [('crop',crop),('reference',target.astype('uint8')*255)]:
   fp=O/'cases'/f'{ident}-{name}.png';Image.fromarray(pixels).save(fp);files[name]={'file':str(fp.relative_to(O)),'sha256':sha(fp)}
  a,b,c=[iou(masks[i],masks[j]) for i,j in ((0,1),(0,2),(1,2))];coverage=float(masks[0].mean());triage='consistent-unverified' if min(a,b,c)>=.75 and .03<=coverage<=.75 else 'needs-inspection';scores=[a+b,a+c,b+c];medoid=max(range(3),key=lambda i:(scores[i],-i));gate=medoid if triage=='needs-inspection' else 0;ref_iou=[iou(m,target) for m in masks];rows.append({'id':ident,'status':'evaluated','source_path':image['path'],'source_sha256':image['sha256'],'component_label':s['component_label'],'box_index':s['box_index'],'component_area_full':s['component_area'],'source_box':box,'crop_bounds_xyxy_exclusive':[x0,y0,x1,y1],'points_xy':pts,'points_in_reference':[bool(target[min(h-1,max(0,round(y))),min(w-1,max(0,round(x)))]) for x,y in pts],'inference_input_size_px':[iw,ih],'inference_padding_offset_xy':[ox,oy],'model_points_xy':model_pts,'pairwise_iou':[a,b,c],'center_crop_fraction':coverage,'triage':triage,'proposal_reference_iou':dict(zip(names,ref_iou)),'medoid_choice':names[medoid],'gated_choice':names[gate],'scores':{'center':ref_iou[0],'medoid':ref_iou[medoid],'gated':ref_iou[gate]},'images':files});print('evaluated',ident,'triage',triage,'IoU',[round(ref_iou[i],3) for i in (0,medoid,gate)],'seconds',round(time.monotonic()-start),flush=True)
 evals=[x for x in rows if x['status']=='evaluated'];summary={}
 for group in ('all','consistent-unverified','needs-inspection'):
  xs=[x for x in evals if group=='all' or x['triage']==group];summary[group]={'cases':len(xs),'methods':{k:{'iou_ge_0_5':sum(x['scores'][k]>=.5 for x in xs),'iou_ge_0_75':sum(x['scores'][k]>=.75 for x in xs),'mean_iou':float(np.mean([x['scores'][k] for x in xs])) if xs else None,'median_iou':float(np.median([x['scores'][k] for x in xs])) if xs else None} for k in ('center','medoid','gated')},'medoid_better':sum(x['scores']['medoid']>x['scores']['center']+1e-9 for x in xs),'medoid_worse':sum(x['scores']['medoid']<x['scores']['center']-1e-9 for x in xs),'gated_better':sum(x['scores']['gated']>x['scores']['center']+1e-9 for x in xs),'gated_worse':sum(x['scores']['gated']<x['scores']['center']-1e-9 for x in xs)}
 out={'format':'r115-gunduz-mask-choice-v1','protocol_sha256':sha(O/'protocol.json'),'annotation_audit_sha256':sha(O/'annotation-audit.json'),'image_manifest_sha256':sha(O/'image-manifest.json'),'leak_screen_sha256':sha(O/'leak-screen.json'),'script_sha256':sha(__file__),'summary':summary,'quarantined_count':sum(x['status']=='quarantined' for x in rows),'records':rows,'warning':p['limits']};(O/'results.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps({'summary':summary,'quarantined':out['quarantined_count']},indent=2),flush=True)
if __name__=='__main__':main()
