"""Visualize all oracle-assisted published-polygon comparisons."""
import html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/source-mask-polygon-proxy';r=json.loads((O/'results.json').read_text());med=json.loads((O/'medoid-exploration.json').read_text());medcases={x['id']:x for x in med['records']};E=html.escape;(O/'overlays').mkdir(exist_ok=True);cards=[]
for x in r['records']:
 crop=np.asarray(Image.open(O/x['images']['crop']['file']).convert('RGB'));imgs=[]
 for name,col,point in [('reference',(45,215,120),None),('center',(255,95,50),0),('minus',(50,185,255),1),('plus',(225,80,220),2)]:
  mask=np.asarray(Image.open(O/x['images'][name]['file']).convert('L'))>0;out=crop.astype(np.float32);out[mask]=.7*out[mask]+.3*np.array(col,np.float32);edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;out[edge]=col;im=Image.fromarray(np.rint(out).clip(0,255).astype('uint8'))
  if point is not None:
   d=ImageDraw.Draw(im);xx,yy=x['source_points_xy'][point];d.line((xx-4,yy,xx+4,yy),fill=(255,255,0),width=1);d.line((xx,yy-4,xx,yy+4),fill=(255,255,0),width=1)
  path=O/'overlays'/f"{x['id']}-{name}.png";im.save(path);label='Published polygon' if name=='reference' else name.title()+' proposal';imgs.append('<figure><a href="overlays/'+E(path.name)+'"><img loading="lazy" src="overlays/'+E(path.name)+'" alt="'+E(label)+'"></a><figcaption>'+E(label)+'</figcaption></figure>')
 values=x['reference_iou'];pair=', '.join(f'{z:.2f}' for z in x['proposal_pairwise_iou']);cards.append('<article><h3>'+E(x['source_filename'])+' · polygon '+str(x['annotation_id'])+'</h3><p>'+E(x['triage'])+' · center/minus/plus IoU to published polygon '+f"{values['center']:.2f} / {values['minus']:.2f} / {values['plus']:.2f}"+' · proposal pair IoUs '+pair+' · post-hoc medoid: '+E(medcases[x['id']]['chosen'])+' · gated choice: '+E(medcases[x['id']]['gated_choice'])+'</p><div class="views">'+''.join(imgs)+'</div><p><a href="/'+E(x['source_image_path'])+'">Original source field</a> · <a href="'+E(x['images']['crop']['file'])+'">Grayscale oracle crop</a></p></article>')
table=''
for k,label in [('consistent-unverified','Consistent, unverified'),('needs-inspection','Needs inspection')]:
 c=r['counts'][k];table+='<tr><th>'+label+'</th><td>'+str(c['cases'])+'</td><td>'+str(c['center_iou_ge_0_5'])+'/'+str(c['cases'])+'</td><td>'+str(c['center_iou_ge_0_75'])+'/'+str(c['cases'])+'</td><td>'+str(c['all_points_inside_polygon'])+'/'+str(c['cases'])+'</td></tr>'
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Published-polygon mask diagnostic</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1250px;margin:auto;padding:24px}a{color:#076c59}.notice{background:#fff8df;border-left:5px solid #b88418;padding:15px}article{background:white;border:1px solid #cbd8d1;padding:12px;margin:14px 0}.views{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}figure{margin:0}.views img{width:100%;height:220px;object-fit:contain;background:#e8eee8}figcaption{font-size:.85rem}table{border-collapse:collapse;background:white;max-width:100%;display:block;overflow:auto}td,th{border:1px solid #cbd8d1;padding:8px;text-align:left}@media(max-width:700px){.views{grid-template-columns:repeat(2,minmax(0,1fr))}}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/species-scaleup/mask-hypotheses/">UDE proposals</a> · <a href="/results/r84/">Earlier field study</a></nav><h1>Does prompt agreement flag polygon mismatches?</h1><p class="notice"><strong>Small, reference-assisted development diagnostic.</strong> Published source polygons are not independently expert-verified ground truth. The 16 fields were previously used and may have related training data. Crops and prompt positions were calculated from the reference polygons, so they are privileged inputs. These results do not measure automatic detection, species identification, Academy accuracy or real overlap recovery.</p><p>All 29 polygons in the previously used <a href="/results/r84/">R84 fields</a> were cropped using an expanded published bounding box and converted to grayscale. The same single MobileSAM model received center and two principal-axis point prompts derived from the polygon. The pre-existing geometric rule labels a triad consistent only when all three pairwise IoUs are at least 0.75 and the center mask occupies 3–75% of the crop. Triage is not accuracy.</p><table><tr><th>Geometric triage</th><th>Cases</th><th>Center vs published polygon IoU ≥0.5</th><th>Center vs published polygon IoU ≥0.75</th><th>All three prompts inside polygon</th></tr>'''+table+'''</table><p>These counts characterize only these 29 selected polygons under reference-derived crops and prompts. They cannot establish that geometrically consistent UDE masks are correct, that flagged masks are incorrect, or that the rule transfers to other shapes and optical conditions. Some polygon boundaries or source identities may themselves be wrong or incomplete.</p><p>A later, predeclared <a href="/results/r115/">different-source component replay</a> tests these fixed choices on new file IDs; independence and reference quality remain unresolved.</p><h2>Post-hoc proposal choice</h2><p>After inspecting these results, we explored choosing the proposal with the largest combined overlap with the other two (a medoid). It matched 28/29 published polygons at IoU ≥0.5 versus 26/29 for always choosing center; both matched 24/29 at IoU ≥0.75. It improved IoU in eight cases and worsened it in four. A second variant keeps center for consistent triads and chooses the medoid only for flagged triads; on these same cases it matched 28/29 at IoU ≥0.5 and 26/29 at IoU ≥0.75. Both variants were chosen after inspecting the results, so the apparent gains are exploratory and need a genuinely fresh, predeclared comparison. Neither rule proves the chosen mask correct.</p><p><a href="medoid-exploration.json">Post-hoc scores and decisions</a> · <a href="medoid-verify.json">Independent arithmetic check</a></p><p>Source: Khanom, <a href="https://doi.org/10.5281/zenodo.21295927">Images of diatoms for CNN model training</a>, CC BY 4.0. Source folder names are genus-level hints; COCO category names are empty. <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All scores and provenance</a> · <a href="verify.json">Reconstruction checks</a></p><h2>All 29 comparisons</h2><p>Each panel shows the same grayscale oracle crop; green is the published polygon, and orange, blue and magenta show the three model masks. Yellow crosses show the prompts. Click to enlarge.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'comparisons')
