"""Compare source rough polygons with model-generated source-mask proposals."""
import collections,ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';H=D/'mask-hypotheses';O=D/'polygon-mask-audit';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def rasterize(record):
 w,h=record['source_dimensions_px'];points=np.asarray(record['source_annotation_points_global'],dtype=float).reshape(-1,2);bx,by,*_=record['source_annotation_bbox_global'];points=np.rint(points-np.array([bx,by])).astype(np.int32);assert len(points)>=3;mask=np.zeros((h,w),np.uint8);cv2.fillPoly(mask,[points],1);return mask.astype(bool)
def measure(ref,mask):
 intersection=int((ref&mask).sum());union=int((ref|mask).sum());a=int(ref.sum());b=int(mask.sum());return {'iou':intersection/union if union else None,'intersection_pixels':intersection,'source_polygon_pixels':a,'proposal_pixels':b,'fraction_polygon_covered':intersection/a if a else None,'fraction_proposal_inside_polygon':intersection/b if b else None}
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);p=json.loads((O/'protocol.json').read_text());assert not (O/'results.json').exists() and p['source_assets_sha256']==sha(D/'assets.json') and p['proposal_protocol_sha256']==sha(H/'protocol.json');assets={r['annotation_id']:r for r in json.loads((D/'assets.json').read_text())['records']};out=[]
 for r in p['records']:
  a=assets[r['annotation_id']];assert a['source_annotation_shape']=='Polygon' and a['source_sha256']==r['source_sha256'] and sha(D/a['source_crop'])==a['source_sha256'];path=H/'records'/(r['annotation_id']+'.json');q=json.loads(path.read_text());assert q['source_sha256']==a['source_sha256'] and q['protocol_sha256']==sha(H/'protocol.json');ref=rasterize(a);name=r['annotation_id']+'-rough-polygon.png';Image.fromarray(ref.astype('uint8')*255).save(O/name);metrics={}
  for k in ('center','minus','plus'):
   x=q['masks'][k];mp=H/x['file'];assert sha(mp)==x['sha256'];mask=np.asarray(Image.open(mp).convert('L'))>0;assert mask.shape==ref.shape;metrics[k]=measure(ref,mask)
  out.append({'annotation_id':r['annotation_id'],'source_species':r['source_species'],'source_crop':r['source_crop'],'source_sha256':r['source_sha256'],'proposal_record':str(path.relative_to(D)),'proposal_record_sha256':sha(path),'triage':q['triage'],'source_polygon_image':name,'source_polygon_sha256':sha(O/name),'metrics':metrics})
 stats={}
 for triage in ('consistent-unverified','needs-inspection'):
  subset=[x for x in out if x['triage']==triage];v=[x['metrics']['center']['iou'] for x in subset];stats[triage]={'cases':len(v),'center_iou_ge_05':sum(x is not None and x>=.5 for x in v),'center_iou_ge_075':sum(x is not None and x>=.75 for x in v),'center_iou_lt_025':sum(x is not None and x<.25 for x in v),'center_iou_null':sum(x is None for x in v)}
 result={'format':p['format'],'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(Path(__file__)),'summary':stats,'warning':p['limitations'],'records':out};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(stats,indent=2))
if __name__=='__main__':main()
