"""Prepare provisional box/point masks and calibrated crops from UDE development cutouts."""
import csv,ctypes,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/ude-prefix';D=R/'results/r14/prefix';META=Path('/tmp/ude-metadata.csv');PAPER='https://academic.oup.com/gigascience/article/doi/10.1093/gigascience/giae087/7912108'
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 main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if os.getppid()!=parent:raise RuntimeError('launcher exited')
 torch.set_num_threads(2);cv2.setNumThreads(2);O.mkdir(parents=True,exist_ok=True)
 if (O/'manifest.json').exists():raise FileExistsError('Output exists; use another destination')
 selection=json.loads((D/'reference-manifest.json').read_text());assert sha(META)==selection['metadata_sha256'];records=selection['rows'];assert len(records)==61;wanted={x['annotation_id'] for x in records};meta={}
 with META.open(newline='') as f:
  for r in csv.DictReader(f):
   if r['annotation_id'] in wanted:meta[r['annotation_id']]=r
 assert set(meta)==wanted
 hashes={x['annotation_id']:x['sha256'] for x in records};cal=json.loads((R/'results/r112/design/native-scenes/background-calibration.json').read_text());backgrounds=cal['scenes'][:8];model='/tmp/mobile_sam.pt';checkpoint_hash=sha(model);outputs=[];start=time.monotonic()
 for i,record in enumerate(records):
  ident=record['annotation_id'];m=meta[ident];ip=D/record['local_file'];assert sha(ip)==hashes[ident] and record['species']==m['species'] and record['genus']==m['genus'] and record['filename']==m['cutout_filename'];im=np.asarray(Image.open(ip).convert('L'));h,w=im.shape;factor=min(1.0,512/max(h,w));iw=max(1,round(w*factor));ih=max(1,round(h*factor));model_im=im if (iw,ih)==(w,h) else cv2.resize(im,(iw,ih),interpolation=cv2.INTER_AREA);ox=(512-iw)//2;oy=(512-ih)//2;canvas=np.full((512,512),int(np.median(im)),np.uint8);canvas[oy:oy+ih,ox:ox+iw]=model_im;predict=Predictor(overrides={'model':model,'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predict.set_image(cv2.cvtColor(canvas,cv2.COLOR_GRAY2BGR));pt=[ox+iw//2,oy+ih//2];box=[ox,oy,ox+iw-1,oy+ih-1];pm=predict(points=[[pt]],labels=[[1]],verbose=False)[0];bm=predict(bboxes=[box],verbose=False)[0];masks={'point':cv2.resize(pm.masks.data.cpu().numpy()[0,oy:oy+ih,ox:ox+iw].astype('uint8'),(w,h),interpolation=cv2.INTER_NEAREST).astype(bool),'box':cv2.resize(bm.masks.data.cpu().numpy()[0,oy:oy+ih,ox:ox+iw].astype('uint8'),(w,h),interpolation=cv2.INTER_NEAREST).astype(bool)};q={'point':float(pm.boxes.conf[0]),'box':float(bm.boxes.conf[0])};bg=backgrounds[i%len(backgrounds)];tx=bg['background_um_per_pixel_x'];ty=bg['background_um_per_pixel_y'];tw=max(1,round(w*.09/tx));th=max(1,round(h*.09/ty));scaled=cv2.resize(im,(tw,th),interpolation=cv2.INTER_AREA);Image.fromarray(scaled).save(O/f'{ident}-scaled.png');outm={}
  for key,mask in masks.items():
   f=O/f'{ident}-{key}-mask.png';Image.fromarray(mask.astype('uint8')*255).save(f);scaledmask=cv2.resize(mask.astype('uint8'),(tw,th),interpolation=cv2.INTER_NEAREST);sf=O/f'{ident}-{key}-scaled-mask.png';Image.fromarray(scaledmask*255).save(sf);outm[key]={'mask':f.name,'sha256':sha(f),'scaled_mask':sf.name,'scaled_sha256':sha(sf),'quality_model_score_not_accuracy':q[key],'area_pixels':int(mask.sum())}
  coords=[int(m['bbox_x0']),int(m['bbox_y0']),int(m['bbox_x1']),int(m['bbox_y1'])];outputs.append({'annotation_id':ident,'source_slide':record['source_slide'],'source_split':'historical_single_slide_prefix_consumed','source_image':str(ip.relative_to(R)),'source_sha256':sha(ip),'source_genus':m['genus'],'source_species':m['species'],'source_subspecies':m['subspecies'],'source_annotator':m['annotator'],'annotation_shape':m['shape'],'annotation_points_global':json.loads(m['points']),'annotation_bbox_global':coords,'source_crop_size_px':[w,h],'crop_vs_annotation_bbox_delta_px':[w-(coords[2]-coords[0]+1),h-(coords[3]-coords[1]+1)],'source_um_per_pixel_xy':[.09,.09],'source_calibration_reference':PAPER,'target_slide':bg['slide'],'target_um_per_pixel_xy':[tx,ty],'resampling':'INTER_AREA image; INTER_NEAREST mask; dimensions round(source pixels * source um/pixel / target um/pixel)','target_crop_size_px':[tw,th],'scaled_image':f'{ident}-scaled.png','scaled_sha256':sha(O/f'{ident}-scaled.png'),'model_input_content_px':[iw,ih],'model_input_offset_xy':[ox,oy],'model_prompt_point_xy':pt,'model_prompt_box_xyxy':box,'inference_downsample_ratio':factor,'mask_proposals':outm,'mask_and_species_status':'Unverified model-generated candidate masks and source taxon metadata; no independent specimen-level annotation or admissibility check.','sample_independence':'unknown'})
  if (i+1)%8==0:print(i+1,'/',len(records),'elapsed',round(time.monotonic()-start,1),flush=True)
 result={'format':'r112-ude-calibrated-proposals-v1','source':'UDE DIATOMS in the Wild 2024, CC0; source labels and cutouts are not independently verified','selection_sha256':sha(D/'reference-manifest.json'),'source_prefix_sha256':selection['source_prefix_sha256'],'metadata_sha256':sha(META),'target_calibration_sha256':sha(R/'results/r112/design/native-scenes/background-calibration.json'),'model_sha256':checkpoint_hash,'script_sha256':sha(__file__),'scope':'61 historical cutouts from a single source-slide prefix; previously consumed and never eligible for independent testing. Rough rectangle/circle annotations are not segmentation masks. Do not use as training ground truth until mask, species and source grouping quality gates are met.','records':outputs};(O/'manifest.json').write_text(json.dumps(result,indent=2)+'\n');print('complete',len(outputs),'elapsed',round(time.monotonic()-start,1),flush=True)
if __name__=='__main__':main()
