"""Prepare source-preserving, slide-calibrated UDE development assets."""
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/diversity-fetch';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);selection=json.loads((O/'selection.json').read_text());download=json.loads((O/'download-report.json').read_text());assert sha(O/'selection.json')==download['selection_sha256'] and sha(META)==selection['metadata_sha256'] and not download['cross_split_exact_image_duplicates'];cal=json.loads(CAL.read_text())['scenes'][:8];expected=selection['rows'];wanted={x['annotation_id'] for x in expected};assert len(expected)==len(wanted)==120;d={x['annotation_id']:x for x in download['images']};assert set(d)==wanted;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;target=O/'calibrated';target.mkdir(exist_ok=True);rows=[]
 for i,r in enumerate(expected):
  ident=r['annotation_id'];source=O/r['local_file'];assert sha(source)==d[ident]['sha256'];m=metadata[ident];assert all(r[k]==m[k] for k in ('genus','species','subspecies','annotation_id')) and r['filename']==m['cutout_filename'];im=np.asarray(Image.open(source).convert('L'));h,w=im.shape;bg=cal[i%len(cal)];sx=bg['background_um_per_pixel_x'];sy=bg['background_um_per_pixel_y'];dw=max(1,round(w*.09/sx));dh=max(1,round(h*.09/sy));scaled=cv2.resize(im,(dw,dh),interpolation=cv2.INTER_AREA);p=target/f'{ident}.png';Image.fromarray(scaled).save(p);bbox=[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_image_id':m['image_id'],'source_annotation_shape':m['shape'],'source_annotation_points_global':json.loads(m['points']),'source_annotation_bbox_global':bbox,'crop_vs_annotation_bbox_delta_px':[w-(bbox[2]-bbox[0]+1),h-(bbox[3]-bbox[1]+1)],'source_scale_um_px':[.09,.09],'calibration_reference':'https://doi.org/10.1093/gigascience/giae087','academy_target_slide':bg['slide'],'target_scale_um_px':[sx,sy],'scaled_crop':str(p.relative_to(O)),'scaled_sha256':sha(p),'scaled_dimensions_px':[dw,dh],'resampling':'INTER_AREA; axis dimensions round(source pixel count * source_um_per_pixel / target_um_per_pixel)','label_status':'unverified source taxonomy and rough bounding annotation; no validated segmentation mask','split_status':'development only; biological independence unknown'})
 out={'format':'r112-diverse-ude-calibrated-v1','selection_sha256':sha(O/'selection.json'),'download_sha256':sha(O/'download-report.json'),'metadata_sha256':sha(META),'calibration_sha256':sha(CAL),'script_sha256':sha(__file__),'license':'UDE DIATOMS in the Wild 2024 dataset CC0; model/software and other-source terms are separate.','warning':'Development only. Original rough labels and source taxonomy are not validated. Box annotations/crops may contain other organisms; no pixel-accurate segmentation labels. Source slide names do not establish biological independence. Pixel-scale matching does not guarantee optical match.','records':rows};(O/'assets.json').write_text(json.dumps(out,indent=2)+'\n');print('Prepared',len(rows),'calibrated source assets;',len({x['source_species'] for x in rows}),'taxa;',len({x['source_slide_group'] for x in rows}),'source-slide names.')
if __name__=='__main__':main()
