"""Frozen R96 YOLO-box/SAM method on R80 fields passing similarity quarantine."""
import ctypes,datetime,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image,ImageDraw
from ultralytics import YOLO
from ultralytics.models.sam import Predictor
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/r97';D=R/'datasets/r80-gunduz'
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 stack(a):return np.stack([x['mask'] for x in a]) if a else np.zeros((0,512,512),bool)
def padresize(mask):
 out=np.zeros((512,512),bool);out[64:448]=cv2.resize(mask.astype('uint8'),(512,384),interpolation=cv2.INTER_NEAREST).astype(bool);return out
def paint(rgb,refs,yolo,sam,history,path):
 out=Image.new('RGB',(1200,340),'white');d=ImageDraw.Draw(out)
 for k,(title,arr) in enumerate([('Source regions',refs),('YOLO masks top 30',[x['mask'] for x in yolo[:30]]),('SAM box masks top 30',[x['mask'] for x in sam[:30]]),('R80 baseline top 30',[x['mask'] for x in history[: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():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if os.getppid()!=parent:raise RuntimeError('Launcher exited')
 p=json.loads((O/'protocol.json').read_text());assert sha(R/p['model'])==p['model_sha256'] and sha(Path(p['sam_checkpoint']))==p['sam_sha256']
 for f,h in p['inputs'].items():assert sha(R/f)==h
 screen=json.loads((O/'source-screen.json').read_text());assert screen['protocol_sha256']==sha(O/'protocol.json') and len(screen['records'])==24 and sha(R/'research/r97_source_screen.py')==screen['script_sha256'];source={x['id']:x for x in json.loads((R/'results/r80/source-audit.json').read_text())['targets']};base={x['id']:x for x in json.loads((R/'results/r80/baseline.json').read_text())['records']};history={x['id']:x for x in json.loads((R/'results/r80/results.json').read_text())['records']};chosen=[x for x in screen['records'] if not x['quarantined']];torch.set_num_threads(2);yolo=YOLO(str(R/p['model']));records=[]
 for i,row in enumerate(chosen):
  ident=row['id'];ip=D/'images'/f'{ident}.png';mp=D/'masks'/f'{ident}.png';xp=D/'xml'/f'{ident}.xml';assert sha(ip)==row['source_image_sha256'] and sha(mp)==row['source_mask_sha256'] and sha(xp)==row['source_xml_sha256'];im=Image.open(ip).convert('RGB');assert im.width*3==im.height*4;rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS));binary=np.asarray(Image.open(mp).convert('L'))>0;_,labels=cv2.connectedComponents(binary.astype('uint8'),connectivity=8);instances=base[ident]['instances'];refs=[]
  for v in instances:
   mask=labels==v['component_label'];assert int(mask.sum())==v['area'];refs.append(padresize(mask))
  refs=np.stack(refs);ids=[x['box_index'] for x in instances];hist=history[ident];assert sha(R/'results/r80'/hist['sam_archive'])==hist['sam_archive_sha256'] and sha(R/'results/r80'/hist['cellpose_archive'])==hist['cellpose_archive_sha256'];old=np.load(R/'results/r80'/hist['sam_archive']);shape=tuple(old['mask_shape']);oldm=np.unpackbits(old['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);sm=dict(zip(old['ids'].tolist(),oldm));cp=np.load(R/'results/r80'/hist['cellpose_archive'])['labels'];rank=hist['rankings']['sam_first'];cache={};historical=[]
  for name in rank:
   if name not in cache:
    typ,sub=name.split(':',1);m=sm[sub] if typ=='sam' else cp==int(sub);cache[name]=padresize(m)
   historical.append({'id':name,'mask':cache[name]})
  t=time.monotonic();out=yolo.predict(cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR),imgsz=640,conf=.001,iou=.7,device='cpu',retina_masks=True,max_det=100,verbose=False)[0];ytime=time.monotonic()-t
  if out.masks is None:assert out.boxes is None or len(out.boxes)==0;ym=np.zeros((0,512,512),bool);q=np.array([],np.float32);boxes=np.zeros((0,4),np.float32);classes=np.array([],np.int32)
  else:ym=out.masks.data.cpu().numpy().astype(bool);q=out.boxes.conf.cpu().numpy();boxes=out.boxes.xyxy.cpu().numpy();classes=out.boxes.cls.cpu().numpy().astype('int32');assert ym.shape[1:]==(512,512) and len(ym)==len(q)==len(boxes)==len(classes)<=100 and np.isfinite(q).all()
  order=sorted(range(len(ym)),key=lambda j:(-float(q[j]),j));selected=[]
  for j in order:
   if float(q[j])<.001:continue
   box=np.clip(boxes[j],0,511).astype('float64')
   if box[2]-box[0]<1 or box[3]-box[1]<1:continue
   selected.append({'id':f'yolo:{j}','source_index':int(j),'quality':float(q[j]),'bbox':box.tolist(),'mask':ym[j]})
   if len(selected)==30:break
  refined=[];t=time.monotonic()
  if selected:
   model=Predictor(overrides={'model':p['sam_checkpoint'],'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});model.set_image(cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR))
   for j in range(0,len(selected),12):
    batch=selected[j:j+12];out=model(bboxes=[x['bbox'] for x in batch],verbose=False)[0];assert out.masks is not None and len(out.masks.data)==len(batch)
    for x,m,s in zip(batch,out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
     m=m.astype(bool);s=float(s);assert m.shape==(512,512) and np.isfinite(s);refined.append({'id':f"sam:{x['source_index']}",'mask':m,'quality':s})
  stime=time.monotonic()-t;assert len(refined)==len(selected);alternating=[x for j in range(len(selected)) for x in (selected[j],refined[j])];scores={}
  for method,items in [('yolo',selected),('sam_box',refined),('both',alternating),('historical',historical)]:scores[method]={str(n):{str(t):match(refs,ids,stack(items if n=='all' else items[:n]),t) for t in (.5,.75)} for n in (10,30,'all')}
  archive=O/(ident+'.npz');np.savez_compressed(archive,yolo_bits=np.packbits(ym.ravel()),yolo_shape=np.array(ym.shape),quality=q,boxes=boxes,classes=classes,order=np.array(order),sam_bits=np.packbits(stack(refined).ravel()),sam_shape=np.array((len(refined),512,512)),sam_quality=np.asarray([x['quality'] for x in refined]),selected_indices=np.asarray([x['source_index'] for x in selected]),clipped_boxes=np.asarray([x['bbox'] for x in selected],np.float64).reshape(-1,4),refs=refs,ids=np.asarray(ids));pic=O/(ident+'.png');paint(rgb,refs,selected,refined,historical,pic);rec={'id':ident,'source_image':str(ip.relative_to(R)),'source_image_sha256':sha(ip),'source_mask_sha256':sha(mp),'source_xml_sha256':sha(xp),'used_for_r54_training':row['used_for_r54_training'],'references':len(refs),'yolo_output_count':len(ym),'hit_yolo_cap':len(ym)==100,'prompt_count':len(selected),'historical_count':len(historical),'historical_sam_archive':hist['sam_archive'],'historical_sam_archive_sha256':hist['sam_archive_sha256'],'historical_cp_archive':hist['cellpose_archive'],'historical_cp_archive_sha256':hist['cellpose_archive_sha256'],'rankings':{'yolo':[x['id'] for x in selected],'sam_box':[x['id'] for x in refined],'both':[x['id'] for x in alternating],'historical':rank},'scores':scores,'seconds':{'yolo':round(ytime,3),'sam':round(stime,3)},'archive':archive.name,'archive_sha256':sha(archive),'image':pic.name,'image_sha256':sha(pic)};records.append(rec);tmp=O/'partial.tmp';tmp.write_text(json.dumps({'records':records},indent=2)+'\n');os.replace(tmp,O/'partial-results.json');tmp=O/'progress.tmp';tmp.write_text(json.dumps({'completed':len(records),'total':len(chosen),'last_case':ident,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Checkpoint does not establish process liveness.'},indent=2)+'\n');os.replace(tmp,O/'progress.json');print(i+1,ident,'prompts',len(selected),'top30 yolo/sam/historical',*[scores[k]['30']['0.5']['matched'] for k in ('yolo','sam_box','historical')],flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r97-r80-replay-v1','protocol_sha256':sha(O/'protocol.json'),'source_screen_sha256':sha(O/'source-screen.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
if __name__=='__main__':main()
