"""Publish source rough polygons versus unverified model source masks."""
import html,json,statistics
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';H=D/'mask-hypotheses';O=D/'polygon-mask-audit';r=json.loads((O/'results.json').read_text());cards=[]
for x in r['records']:
 img=np.asarray(Image.open(D/x['source_crop']).convert('RGB'));ref=np.asarray(Image.open(O/x['source_polygon_image']).convert('L'))>0;q=json.loads((D/x['proposal_record']).read_text());mask=np.asarray(Image.open(H/q['masks']['center']['file']).convert('L'))>0
 def outlined(arr,mask,color):
  out=arr.copy();contours,_=cv2.findContours(mask.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(out,contours,-1,(0,0,0),3);cv2.drawContours(out,contours,-1,color,1);return out
 merged=outlined(outlined(img,ref,(255,210,30)),mask,(30,220,175));views=[('Source crop',img),('Rough source polygon',outlined(img,ref,(255,210,30))),('Center model proposal',outlined(img,mask,(30,220,175))),('Both outlines',merged)];pane=Image.new('RGB',(1040,300),'white');draw=ImageDraw.Draw(pane)
 for j,(title,view) in enumerate(views):
  pic=Image.fromarray(view);pic.thumbnail((250,250),Image.Resampling.LANCZOS);pane.paste(pic,(j*260+(250-pic.width)//2,27+(250-pic.height)//2));draw.text((j*260+4,5),title,fill='#193b37')
 f=x['annotation_id']+'-comparison.jpg';pane.save(O/f,quality=90);m=x['metrics']['center'];cards.append('<article><h3>'+html.escape(x['source_species'])+' · '+html.escape(x['annotation_id'])+'</h3><p>Geometric triage: '+html.escape(x['triage'])+'. Center IoU with rough polygon: '+f"{m['iou']:.3f}"+'; fraction of proposed mask inside polygon: '+f"{m['fraction_proposal_inside_polygon']:.3f}"+'.</p><a href="'+f+'"><img loading="lazy" src="'+f+'" alt="Original crop, rough polygon, candidate mask and both outlines"></a><p><a href="/results/r112/species-scaleup/'+html.escape(x['source_crop'])+'">Source crop</a> · <a href="'+html.escape(x['source_polygon_image'])+'">Rasterized source polygon</a> · <a href="/results/r112/species-scaleup/mask-hypotheses/'+html.escape(q['masks']['center']['file'])+'">Center proposal</a></p></article>')
a=r['summary']['consistent-unverified'];b=r['summary']['needs-inspection'];ious=[x['metrics']['center']['iou'] for x in r['records'] if x['metrics']['center']['iou'] is not None];inside=[x['metrics']['center']['fraction_proposal_inside_polygon'] for x in r['records'] if x['metrics']['center']['fraction_proposal_inside_polygon'] is not None];page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rough polygon and model-mask comparison</title><style>body{font:16px/1.55 system-ui;background:#f4f6f0;color:#193b37;margin:0}main{max-width:1150px;margin:auto;padding:24px}a{color:#096c58}.notice,article{background:white;border:1px solid #cddbd2;padding:16px;margin:14px 0}.notice{border-left:5px solid #bc851b}img{max-width:100%;height:auto}table{border-collapse:collapse;background:white}td,th{border:1px solid #cddbd2;padding:8px;text-align:left}</style><main><nav><a href="/results/r112/species-scaleup/">Expanded source pool</a> · <a href="/results/r112/species-scaleup/mask-hypotheses/">Mask proposals</a></nav><h1>Do model masks agree with rough source polygons?</h1><p class="notice"><strong>Descriptive comparison, not mask accuracy.</strong> The UDE authors describe the original shapes as rough annotations, often with margins. A model mask can be more anatomically precise than a rough polygon and still have low IoU, or agree with an inaccurate polygon and still be wrong. These 28 examples are not a random or independently adjudicated test.</p><p>Before inspecting agreement, selected all 28 Polygon-shaped annotations in the 4,000-crop development pool. We rasterized each published source polygon in crop coordinates and compared it with all three model hypotheses. The table shows the center proposal only, split by the existing same-model geometric triage. Thresholds summarize overlap with the source outline; they are not acceptance gates.</p><table><tr><th>Triage</th><th>Cases</th><th>Center IoU ≥0.5</th><th>Center IoU ≥0.75</th><th>Center IoU &lt;0.25</th></tr><tr><td>Consistent-unverified</td><td>'''+str(a['cases'])+'</td><td>'+str(a['center_iou_ge_05'])+'</td><td>'+str(a['center_iou_ge_075'])+'</td><td>'+str(a['center_iou_lt_025'])+'''</td></tr><tr><td>Needs inspection</td><td>'''+str(b['cases'])+'</td><td>'+str(b['center_iou_ge_05'])+'</td><td>'+str(b['center_iou_ge_075'])+'</td><td>'+str(b['center_iou_lt_025'])+'''</td></tr></table><p>Across all 28 cases, median center-mask IoU with the rough polygon is '''+f'{statistics.median(ious):.3f}'+''' and the median fraction of the proposed mask inside the polygon is '''+f'{statistics.median(inside):.3f}'+'''. This pattern is compatible with polygons being broader than proposals; it does not determine which boundary is biologically correct. Both source and model may miss other organisms.</p><p><a href="protocol.json">Predeclared selection and metrics</a> · <a href="results.json">All center and alternate-mask metrics</a> · <a href="verify.json">Recomputation checks</a></p><h2>All 28 cases</h2><p>Gold outlines the rough source polygon; teal outlines the center model proposal. Click to enlarge. Source taxonomy remains unreconciled with Academy concepts.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('rendered',len(cards),'cases')
