"""Publish all nonquarantined source-component 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/r115';r=json.loads((O/'results.json').read_text());E=html.escape;(O/'overlays').mkdir(exist_ok=True);cards=[]
for x in r['records']:
 if x['status']!='evaluated':continue
 crop=np.asarray(Image.open(O/x['images']['crop']['file']).convert('RGB'));views=[]
 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;arr=crop.astype(np.float32);arr[mask]=.7*arr[mask]+.3*np.array(col,np.float32);edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;arr[edge]=col;im=Image.fromarray(np.rint(arr).clip(0,255).astype('uint8'))
  if point is not None:
   d=ImageDraw.Draw(im);xx,yy=x['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='Source component' if name=='reference' else name.title()+' proposal';views.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>')
 scores=x['scores'];cards.append('<article><h3>Source '+E(x['id'])+'</h3><p>'+E(x['triage'])+' · center / medoid / gated source-component IoU '+f"{scores['center']:.3f} / {scores['medoid']:.3f} / {scores['gated']:.3f}"+' · medoid: '+E(x['medoid_choice'])+' · gated: '+E(x['gated_choice'])+'</p><div class="views">'+''.join(views)+'</div><p><a href="/'+E(x['source_path'])+'">Original source image</a> · <a href="'+E(x['images']['crop']['file'])+'">Grayscale reference-derived crop</a></p></article>')
summary=r['summary']['all'];table=''
for key,label in [('center','Center'),('medoid','Agreement medoid'),('gated','Gated medoid')]:
 x=summary['methods'][key];n=summary['cases'];table+='<tr><th>'+label+'</th><td>'+str(x['iou_ge_0_5'])+'/'+str(n)+'</td><td>'+str(x['iou_ge_0_75'])+'/'+str(n)+'</td><td>'+f"{x['mean_iou']:.3f}"+'</td><td>'+f"{x['median_iou']:.3f}"+'</td></tr>'
tri=''.join('<tr><th>'+E(k)+'</th><td>'+str(v['cases'])+'</td><td>'+str(v['methods']['center']['iou_ge_0_5'])+'/'+str(v['cases'])+'</td><td>'+str(v['methods']['gated']['iou_ge_0_5'])+'/'+str(v['cases'])+'</td><td>'+str(v['methods']['center']['iou_ge_0_75'])+'/'+str(v['cases'])+'</td><td>'+str(v['methods']['gated']['iou_ge_0_75'])+'/'+str(v['cases'])+'</td></tr>' for k,v in r['summary'].items() if k!='all')
quarantine=[x for x in r['records'] if x['status']=='quarantined'];page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Different-source mask-choice replay</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/board.html">Research board</a> · <a href="/results/r112/source-mask-polygon-proxy/">Earlier polygon diagnostic</a> · <a href="/results/r112/">Synthetic training</a></nav><h1>Different-source mask-choice replay</h1><p class="notice"><strong>Development result with oracle-derived inputs, not Academy accuracy.</strong> Each target is an 8-connected component structurally matched to a source box, not an expert-confirmed instance boundary. Reference boxes and components set the crop and point prompts. Sample/slide independence and base-model pretraining exposure are unknown; the Gündüz dataset was examined earlier in the project. No real overlapping-object, false-positive or species performance is measured.</p><p>Before fetching these source annotations and image pixels, fixed 48 public file IDs and the mask-choice rules. Of those, 46 passed the structural screen; the first 24 were selected. A predeclared coarse comparison to the 29 previous Khanom polygon crops quarantined four possible matches, without replacement; 20 candidates remained. The fingerprint check can miss related images or flag similar distinct organisms.</p><p>The <strong>center</strong> rule chooses the center-prompt mask. The <strong>agreement medoid</strong> chooses the proposal with the highest sum of IoUs to the other two. The <strong>gated</strong> rule uses that medoid only for a triad flagged by the existing geometric consistency rule; otherwise it keeps the center mask. None chooses using reference IoU.</p><table><tr><th>Choice</th><th>Source-component IoU ≥0.5</th><th>IoU ≥0.75</th><th>Mean IoU</th><th>Median IoU</th></tr>'''+table+'''</table><p>The medoid increased IoU in '''+str(summary['medoid_better'])+''' cases and decreased it in '''+str(summary['medoid_worse'])+'''; the gated rule increased it in '''+str(summary['gated_better'])+''' and decreased it in '''+str(summary['gated_worse'])+'''. These are few correlated, preselected component proxies and should not be generalized to all species or masks.</p><table><tr><th>Geometric triage</th><th>Cases</th><th>Center ≥0.5</th><th>Gated ≥0.5</th><th>Center ≥0.75</th><th>Gated ≥0.75</th></tr>'''+tri+'''</table><p>All three flagged cases gained IoU under the gated rule; the other 17 retained center by construction. Source boxes did not intersect under the structural rule. A model can agree with itself on the wrong region, and this comparison does not validate training labels or overlap recovery.</p><p>Source: Hüseyin Gündüz, <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, CC BY-NC-SA 4.0; attribution and noncommercial/share-alike terms apply to source and derivatives. <a href="protocol.json">Frozen protocol</a> · <a href="annotation-audit.json">Source annotation audit</a> · <a href="leak-screen.json">Similarity screen</a> · <a href="results.json">All scores</a> · <a href="verify.json">Reconstruction checks</a></p><h2>All 20 evaluated candidates</h2><p>Green shows the source component; orange, blue and magenta show the center, minus and plus masks. Yellow crosses mark reference-derived prompts. Click images to inspect the crop.</p>'''+''.join(cards)+'''<h2>Quarantined</h2><p>'''+E(', '.join(x['id'] for x in quarantine))+''' were held out under the frozen similarity rule and are not included in scores or images above. Possible similarity is not proof of shared specimen; no replacement was made.</p></main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'evaluated cases and',len(quarantine),'quarantined IDs')
