"""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-calibrated';D=R/'results/pilot/ude-adaptation-within-genus';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/'selection.json').read_text());assert sha(META)==selection['metadata_sha256'];records=[x for x in selection['rows'] if x['split']=='train'];assert len(records)==64;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
 report=json.loads((D/'download-report.json').read_text());assert sha(D/'selection.json')==report['selection_sha256'];hashes={x['annotation_id']:x['sha256'] for x in report['images']};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;assert h<=512 and w<=512 and m['shape']=='Rectangle';ox=(512-w)//2;oy=(512-h)//2;canvas=np.full((512,512),int(np.median(im)),np.uint8);canvas[oy:oy+h,ox:ox+w]=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+w//2,oy+h//2];box=[ox,oy,ox+w-1,oy+h-1];pm=predict(points=[[pt]],labels=[[1]],verbose=False)[0];bm=predict(bboxes=[box],verbose=False)[0];masks={'point':pm.masks.data.cpu().numpy()[0,oy:oy+h,ox:ox+w].astype(bool),'box':bm.masks.data.cpu().numpy()[0,oy:oy+h,ox:ox+w].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_train_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'),'prompt_point_xy_source':[w//2,h//2],'prompt_box_xyxy_source':[0,0,w-1,h-1],'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/'selection.json'),'download_report_sha256':sha(D/'download-report.json'),'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':'64 historical train crops only; previously consumed and never eligible for independent testing. Rough rotated rectangles 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()
