"""Apply frozen R36 features to paired real source and synthetic development crops."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
from r112_weak_scenes import transform
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';O=R/'results/r112/design/species-retention-corrected';D=R/'results/r112/species-depth';H=D/'mask-hypotheses';CL=R/'results/pilot/ude-adaptation-within-genus/centroid-pilot/prototypes.npz';W=Path('/tmp/resnet18-f37072fd.pth')
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')
 torch.set_num_threads(2);p=json.loads((O/'protocol.json').read_text());assert sha(S/'manifest.json')==p['scene_manifest_sha256'] and sha(R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json')==p['classifier_protocol_sha256'] and sha(CL)==p['classifier_prototypes_sha256'] and sha(W)==p['classifier_encoder_sha256'];labels=json.loads((R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json').read_text())['label_order'];centroids=np.load(CL)['generic'];assert centroids.shape==(4,512);model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();scenes={x['id']:x for x in json.loads((S/'manifest.json').read_text())['records']};records=[];features=[];start=time.monotonic()
 for i,ref in enumerate(p['records']):
  scene=scenes[ref['scene_id']];v=scene['instances'][ref['instance_index']];assert v['annotation_id']==ref['annotation_id'] and v['source_species']==ref['source_species'] and scene['image_sha256']==ref['scene_image_sha256'] and scene['mask_archive_sha256']==ref['scene_mask_sha256'];source=D/v['source_original'];maskpath=H/v['source_mask_center'];scene_path=S/scene['image'];archive=S/scene['mask_archive'];assert sha(source)==v['source_original_sha256'] and sha(maskpath)==v['source_mask_center_sha256'] and sha(scene_path)==scene['image_sha256'] and sha(archive)==scene['mask_archive_sha256'];raw=Image.open(source).convert('L');ms=np.asarray(Image.open(maskpath).convert('L'))>0;sx,sy=scene['background_um_per_pixel_xy'];transformed,_,dims=transform(np.asarray(raw),ms,sx,sy,v['rotation_ccw_degrees']);valid=np.asarray(Image.new('L',tuple(dims),255).rotate(v['rotation_ccw_degrees'],resample=Image.Resampling.NEAREST,expand=True))>0;assert valid.shape==transformed.shape;transformed=np.where(valid,transformed,int(np.median(np.asarray(raw)))).astype('uint8');h,w=transformed.shape;x=v['center_xy'][0]-w//2;y=v['center_xy'][1]-h//2;x0,y0=max(0,x),max(0,y);x1,y1=min(768,x+w),min(768,y+h);assert x1>x0 and y1>y0;isolated=transformed[y0-y:y1-y,x0-x:x1-x];image=np.asarray(Image.open(scene_path).convert('L'));composite=image[y0:y1,x0:x1];assert composite.shape==isolated.shape;z=np.load(archive);shape=tuple(z['support_shape']);supports=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);target=supports[ref['instance_index']];others=np.logical_or.reduce(np.delete(supports,ref['instance_index'],axis=0)) if len(supports)>1 else np.zeros_like(target);overlap_pixels=int((target&others).sum());target_area=int(target.sum());overlap_fraction=overlap_pixels/target_area if target_area else None;stageimgs={'original':raw,'transformed':Image.fromarray(isolated),'composite':Image.fromarray(composite)};stage={};vecs={}
  for name,img in stageimgs.items():
   vec=embedding(model,img);assert vec.shape==(512,) and np.isfinite(vec).all();scores=centroids@vec;which=int(np.argmax(scores));vecs[name]=vec;fn=O/f"{ref['annotation_id']}-{name}.png";img.save(fn);stage[name]={'image':fn.name,'image_sha256':sha(fn),'prediction':labels[which],'scores':[float(t) for t in scores],'matches_source_name':labels[which]==ref['source_species']}
  f01=float(vecs['original']@vecs['transformed']);f12=float(vecs['transformed']@vecs['composite']);features.append(np.stack([vecs[k] for k in ('original','transformed','composite')]));records.append({**ref,'source_split':'development','source_taxon_status':'unverified source metadata','in_frame_fraction':v['in_frame_fraction'],'source_rectangle_clipped':(x0!=x or y0!=y or x1!=x+w or y1!=y+h),'synthetic_overlap_pixels':overlap_pixels,'synthetic_overlap_fraction_of_target':overlap_fraction,'roi_xyxy':[x0,y0,x1,y1],'stages':stage,'cosine_original_to_transformed':f01,'cosine_transformed_to_composite':f12});(O/'partial.json').write_text(json.dumps({'records':records},indent=2)+'\n')
  if (i+1)%10==0:print(i+1,'/',len(p['records']),'elapsed',round(time.monotonic()-start,1),flush=True)
 np.savez_compressed(O/'features.npz',features=np.stack(features),annotation_ids=np.array([r['annotation_id'] for r in records]));out={'format':'r112-species-retention-corrected-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'features_sha256':sha(O/'features.npz'),'labels':labels,'warning':'Closed-set, source-labeled developmental diagnostic with oracle crop coordinates, not species-accuracy evidence for real Academy scenes; no unknown rejection, source taxonomy and independence unknown.','records':records};(O/'results.json').write_text(json.dumps(out,indent=2)+'\n');print('done',len(records),flush=True)
if __name__=='__main__':main()
