"""Create quarantined-aware, scale-calibrated UDE development source candidates."""
import collections,csv,ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-depth';META=Path('/tmp/ude-metadata.csv');CAL=R/'results/r112/design/native-scenes/background-calibration.json'
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 parent!=os.getppid():raise RuntimeError('launcher exited')
 cv2.setNumThreads(2);s=json.loads((O/'selection.json').read_text());d=json.loads((O/'download-report.json').read_text());screen=json.loads((O/'similarity-screen.json').read_text());assert d['selection_sha256']==sha(O/'selection.json') and screen['download_report_sha256']==sha(O/'download-report.json') and sha(META)==s['metadata_sha256'];hashes={r['annotation_id']:r['sha256'] for r in d['images']};quarantine=set(screen['quarantined_new_ids']);records=[r for r in s['rows'] if r['split']=='development' and r['annotation_id'] not in quarantine];wanted={r['annotation_id'] for r in records};assert len(wanted)==len(records) and all(r['split']=='development' for r in records);metadata={}
 with META.open(newline='',encoding='utf-8-sig') as f:
  for r in csv.DictReader(f):
   if r['annotation_id'] in wanted:metadata[r['annotation_id']]=r
 assert set(metadata)==wanted;cal=json.loads(CAL.read_text())['scenes'][:8];out=O/'development';out.mkdir(exist_ok=True);rows=[]
 for i,r in enumerate(records):
  ident=r['annotation_id'];m=metadata[ident];source=O/r['local_file'];assert sha(source)==hashes[ident] and r['genus']==m['genus'] and r['species']==m['species'] and r['subspecies']==m['subspecies'] and r['filename']==m['cutout_filename'];im=np.asarray(Image.open(source).convert('L'));h,w=im.shape;b=cal[i%len(cal)];sx,sy=b['background_um_per_pixel_x'],b['background_um_per_pixel_y'];dw,dh=max(1,round(w*.09/sx)),max(1,round(h*.09/sy));target=out/f'{ident}.png';Image.fromarray(cv2.resize(im,(dw,dh),interpolation=cv2.INTER_AREA)).save(target);box=[int(m[k]) for k in ('bbox_x0','bbox_y0','bbox_x1','bbox_y1')];rows.append({'annotation_id':ident,'source_crop':r['local_file'],'source_sha256':sha(source),'source_dimensions_px':[w,h],'source_genus':m['genus'],'source_species':m['species'],'source_subspecies':m['subspecies'],'source_annotator':m['annotator'],'source_slide_group':r['source_slide'],'source_annotation_shape':m['shape'],'source_annotation_points_global':json.loads(m['points']),'source_annotation_bbox_global':box,'crop_vs_annotation_bbox_delta_px':[w-(box[2]-box[0]+1),h-(box[3]-box[1]+1)],'source_scale_um_px':[.09,.09],'calibration_reference':'https://doi.org/10.1093/gigascience/giae087','target_slide':b['slide'],'target_scale_um_px':[sx,sy],'scaled_crop':str(target.relative_to(O)),'scaled_sha256':sha(target),'scaled_dimensions_px':[dw,dh],'split':'development','taxonomic_status':'unverified source label','mask_status':'no verified instance mask','source_sample_independence':'unknown'})
 outdata={'format':'r112-depth-development-v1','selection_sha256':sha(O/'selection.json'),'download_report_sha256':sha(O/'download-report.json'),'screen_sha256':sha(O/'similarity-screen.json'),'metadata_sha256':sha(META),'calibration_sha256':sha(CAL),'script_sha256':sha(__file__),'license':'UDE DIATOMS in the Wild 2024 CC0; independent model/software terms apply.','warning':'These are development source candidates, not a finished training set or expert-verified labels. All backgrounds and neighbors in crops may be unannotated; no candidate model masks were silently accepted. Filename grouping does not establish biological independence. Validation/test candidate images are not processed here.','records':rows};(O/'development-assets.json').write_text(json.dumps(outdata,indent=2)+'\n');print('Prepared',len(rows),'development crops;',len(quarantine),'quarantined IDs across all partitions;',len({x['source_species'] for x in rows}),'source labels.')
if __name__=='__main__':main()
