"""Independently recheck Revvity polygon-pair geometry and repeated coordinates."""
import collections,hashlib,json
from pathlib import Path
import cv2,numpy as np
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 main():
 protocol=json.loads((O/'annotation-protocol.json').read_text());audit=json.loads((O/'annotation-audit.json').read_text());labels=json.loads((O/'label-audit.json').read_text());assert sha(A)==protocol['annotation_sha256'] and sha(R/'research/r82_annotation_audit.py')==protocol['audit_script_sha256'] and audit['protocol_sha256']==sha(O/'annotation-protocol.json') and labels['source_audit_sha256']==sha(O/'annotation-audit.json') and labels['script_sha256']==sha(R/'research/r82_label_audit.py') and sha(O/labels['image'])==labels['image_sha256'];raw=json.loads(A.read_text());by=collections.defaultdict(list);groups=collections.defaultdict(list)
 for a in raw['annotations']:by[a['image_id']].append(a);groups[(a['image_id'],json.dumps(a['segmentation'],separators=(',',':')))].append(a['id'])
 duplicates={frozenset(v) for v in groups.values() if len(v)>1};reported={frozenset(v['annotation_ids']) for v in labels['duplicate_geometry_groups']};assert duplicates==reported and len(duplicates)==34 and all(len(v)==2 for v in duplicates);saved={r['image_id']:r for r in audit['records']};paircount=0;totalrefs=0;overlaprefs=0;maxnon=0.;maxfrac=0.
 for image in raw['images']:
  anns=by[image['id']];masks=[];bounds=[]
  for a in anns:
   m=np.zeros((image['height'],image['width']),np.uint8)
   for poly in a['segmentation']:cv2.fillPoly(m,[np.rint(np.array(poly).reshape(-1,2)).astype('int32')],1)
   masks.append(m);x,y,w,h=cv2.boundingRect(m);bounds.append((x,y,x+w,y+h))
  pairs={};overlap=set()
  for i in range(len(masks)):
   for j in range(i):
    a,b=bounds[i],bounds[j];lo_x=max(a[0],b[0]);lo_y=max(a[1],b[1]);hi_x=min(a[2],b[2]);hi_y=min(a[3],b[3])
    if lo_x>=hi_x or lo_y>=hi_y:continue
    shared=int(np.sum(np.bitwise_and(masks[i][lo_y:hi_y,lo_x:hi_x],masks[j][lo_y:hi_y,lo_x:hi_x]),dtype='int64'))
    if shared<10:continue
    ai=int(masks[i].sum());aj=int(masks[j].sum());v=shared/(ai+aj-shared);f=shared/min(ai,aj);pairs[frozenset((anns[j]['id'],anns[i]['id']))]=(shared,v,f);overlap.update((i,j))
    if v<1:maxnon=max(maxnon,v);maxfrac=max(maxfrac,f)
  entry=saved[image['id']];assert entry['filename']==image['file_name'] and entry['instances']==len(anns) and entry['overlap_instances']==len(overlap) and entry['overlap_pairs']==len(pairs);assert len(entry['pairs'])==len(pairs)
  for q in entry['pairs']:
   pixels,v,f=pairs[frozenset(q['annotation_ids'])];assert q['shared_pixels']==pixels and abs(q['iou']-v)<1e-12 and abs(q['fraction_smaller']-f)<1e-12
  paircount+=len(pairs);totalrefs+=len(anns);overlaprefs+=len(overlap)
 assert len(raw['images'])==audit['images']==55 and totalrefs==audit['instances']==1446 and overlaprefs==audit['overlap_instances_at_least_10_pixels']==1042 and paircount==audit['overlap_pairs_at_least_10_pixels']==1312 and abs(maxnon-labels['max_nonidentical_pair_iou']['iou'])<1e-12 and abs(maxfrac-labels['max_nonidentical_fraction_smaller']['fraction_smaller'])<1e-12
 print('Verified 55 images, 1,446 polygon IDs, 1,312 overlap pairs and 34 identical-coordinate groups; no source images or model predictions used.')
if __name__=='__main__':main()
