"""Posthoc audit of repeated polygon geometry and candidate overlap controls."""
import collections,hashlib,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r82';A=R/'datasets/r82-revvity/annotations/valid.json'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def mask(ann):
 m=np.zeros((1080,1080),np.uint8)
 for poly in ann['segmentation']:cv2.fillPoly(m,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
 return m.astype(bool)
def render(examples,path):
 panel=Image.new('RGB',(900,1020),'white');draw=ImageDraw.Draw(panel)
 for row,(name,a,b) in enumerate(examples):
  union=a|b;y,x=np.nonzero(union);x0=max(0,int(x.min())-20);x1=min(1080,int(x.max())+21);y0=max(0,int(y.min())-20);y1=min(1080,int(y.max())+21);groups=[('Both polygons',[a,b]),('Only first',[a&~b]),('Only second',[b&~a])]
  draw.text((8,row*340+5),name,fill='#203a38')
  for col,(label,masks) in enumerate(groups):
   base=Image.new('RGBA',(x1-x0,y1-y0),'#edf3ef')
   for i,m in enumerate(masks):
    layer=Image.new('RGBA',base.size,['#008a70','#ce5b42'][i%2]);layer.putalpha(Image.fromarray(m[y0:y1,x0:x1].astype('uint8')*140));base=Image.alpha_composite(base,layer)
   base=base.convert('RGB');base.thumbnail((285,285));panel.paste(base,(col*300+5,row*340+50));draw.text((col*300+7,row*340+27),label,fill='#203a38')
 panel.save(path)
def main():
 source=json.loads(A.read_text());audit=json.loads((O/'annotation-audit.json').read_text());groups=collections.defaultdict(list);byid={a['id']:a for a in source['annotations']};images={x['id']:x['file_name'] for x in source['images']}
 for ann in source['annotations']:groups[(ann['image_id'],json.dumps(ann['segmentation'],separators=(',',':')))].append(ann['id'])
 dup=[{'image_id':k[0],'filename':images[k[0]],'annotation_ids':v} for k,v in groups.items() if len(v)>1];assert all(len(x['annotation_ids'])==2 for x in dup);flat=[(r['filename'],p) for r in audit['records'] for p in r['pairs']];same=[p for _,p in flat if p['iou']==1.0];assert len(dup)==len(same)==34
 for row in dup:
  a,b=[byid[i] for i in row['annotation_ids']];assert a['segmentation']==b['segmentation'] and np.array_equal(mask(a),mask(b))
 other=[(name,p) for name,p in flat if p['iou']<1.];assert other;maximum=max(other,key=lambda x:x[1]['iou']);contained=max(other,key=lambda x:x[1]['fraction_smaller']);examples=[('Identical geometry · two IDs',*map(mask,[byid[i] for i in dup[0]['annotation_ids']])),('Most overlapping nonidentical pair',*map(mask,[byid[i] for i in maximum[1]['annotation_ids']])),('Highest smaller-mask coverage',*map(mask,[byid[i] for i in contained[1]['annotation_ids']]))];pic=O/'label-geometry.png';render(examples,pic)
 result={'format':'r82-label-audit-v1','source_audit_sha256':sha(O/'annotation-audit.json'),'script_sha256':sha(Path(__file__)),'duplicate_geometry_groups':dup,'group_count':len(dup),'distinct_ids_in_groups':sum(len(x['annotation_ids']) for x in dup),'additional_ids_relative_to_one_per_group':sum(len(x['annotation_ids'])-1 for x in dup),'affected_filenames':sorted({x['filename'] for x in dup}),'max_nonidentical_pair_iou':{'filename':maximum[0],**maximum[1]},'max_nonidentical_fraction_smaller':{'filename':contained[0],**contained[1]},'image':pic.name,'image_sha256':sha(pic),'warning':'Two IDs with identical polygon coordinates have identical geometry; the file alone does not establish whether they are annotation errors or physically distinct coincident objects. No labels were deleted, merged or treated as verified duplicates.'};(O/'label-audit.json').write_text(json.dumps(result,indent=2)+'\n');print('Identical-coordinate groups',len(dup),'across',len(result['affected_filenames']),'images; nonidentical max IoU',result['max_nonidentical_pair_iou']['iou'],'max fraction',result['max_nonidentical_fraction_smaller']['fraction_smaller'])
if __name__=='__main__':main()
