"""Publish weak-support recovery results and visual overlays for all scenes."""
import collections,html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];D=R/'results/r112/grouped-synthetic';O=R/'results/r112/grouped-baseline';r=json.loads((O/'results.json').read_text());scenes={x['id']:x for x in json.loads((D/'manifest.json').read_text())['records']};policies=('sam64','sam256','yolo');names={'sam64':'MobileSAM · 64 points','sam256':'MobileSAM · 256 points','yolo':'Prior YOLOv8 segmentation'};summary={}
for policy in policies:
 summary[policy]={}
 for budget in ('10','30','60','all'):
  summary[policy][budget]={}
  for metric in ('main_0.5','main_0.75','nonempty_0.5','nonempty_0.75'):
   matched=0;refs=0;strata=collections.defaultdict(lambda:collections.Counter())
   for row in r['records']:
    v=row['policies'][policy]['budgets'][budget]['matches'][metric];matched+=v['matched'];refs+=v['references']
    for k,x in v['strata'].items():strata[k]['matched']+=x['matched'];strata[k]['references']+=x['references']
   summary[policy][budget][metric]={'matched':matched,'references':refs,'strata':dict(strata)}
 summary[policy]['candidate_count']=sum(row['policies'][policy]['candidate_count'] for row in r['records'])
(O/'summary.json').write_text(json.dumps({'format':'r112-grouped-baseline-summary-v1','warning':r['warning'],'scenes':len(r['records']),'policies':summary},indent=2)+'\n');e=html.escape
table=''
for policy in policies:
 a=summary[policy]['30']['main_0.5'];b=summary[policy]['30']['main_0.75'];c=summary[policy]['all']['main_0.5'];table+='<tr><th>'+e(names[policy])+'</th><td>'+str(a['matched'])+'/'+str(a['references'])+'</td><td>'+str(b['matched'])+'/'+str(b['references'])+'</td><td>'+str(c['matched'])+'/'+str(c['references'])+'</td><td>'+str(summary[policy]['candidate_count'])+'</td></tr>'
subrows=''
for key,label in [('overlap_at_512','Support overlaps another'),('weak_support_in_frame_lt_095','Less than 95% of support in frame'),('weak_support_in_frame_lt_050','Less than 50% of support in frame')]:
 vals=[summary[policy]['30']['main_0.5']['strata'][key] for policy in policies];subrows+='<tr><th>'+e(label)+'</th>'+''.join('<td>'+str(v['matched'])+'/'+str(v['references'])+'</td>' for v in vals)+'</tr>'
small=summary['sam256']['30']['nonempty_0.5']['strata']['small_1_to_49_pixels']['references'];tiny=''.join('<td>'+str(summary[k]['30']['nonempty_0.5']['strata']['small_1_to_49_pixels']['matched'])+'/'+str(small)+'</td>' for k in policies);subrows+='<tr><th>Small supports, 1–49 pixels (nonempty reference matching)</th>'+tiny+'</tr>'
cards=[]
for row in r['records']:
 s=scenes[row['scene_id']];image=np.asarray(Image.open(D/s['image']).convert('L').resize((512,512),Image.Resampling.LANCZOS));z=np.load(O/row['archive']);shape=tuple(z['mask_shape']);cands=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);shape2=tuple(z['reference_shape']);refs=np.unpackbits(z['reference_bits'])[:np.prod(shape2)].reshape(shape2).astype(bool);base=cv2.cvtColor(image,cv2.COLOR_GRAY2RGB);views=[('Scene',base.copy()),('Weak projected supports',base.copy())]
 def outline(canvas,mask,color):
  contours,_=cv2.findContours(mask.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(canvas,contours,-1,(0,0,0),4);cv2.drawContours(canvas,contours,-1,color,2)
 for mask in refs:outline(views[1][1],mask,(255,220,80))
 for policy in ('sam256','yolo'):
  view=base.copy();rank=row['policies'][policy]['ranking'][:30];matched={x['candidate_index'] for x in row['policies'][policy]['budgets']['30']['matches']['main_0.5']['assignments']}
  for ix in rank:outline(view,cands[ix],(40,210,150) if ix in matched else (245,150,40))
  views.append((names[policy]+' · top 30',view))
 pane=Image.new('RGB',(1300,360),'white');draw=ImageDraw.Draw(pane)
 for j,(title,view) in enumerate(views):pane.paste(Image.fromarray(view).resize((320,320)),(j*325+2,30));draw.text((j*325+4,7),title,fill='#193b37')
 fn=row['scene_id']+'-comparison.jpg';pane.save(O/fn,quality=88);sam=row['policies']['sam256']['budgets']['30']['matches']['main_0.5'];y=row['policies']['yolo']['budgets']['30']['matches']['main_0.5'];cards.append('<article><h3>'+e(row['scene_id'])+'</h3><p>Weak supports matched at IoU ≥0.5: MobileSAM '+str(sam['matched'])+'/'+str(sam['references'])+'; prior YOLOv8 '+str(y['matched'])+'/'+str(y['references'])+'.</p><a href="'+fn+'"><img loading="lazy" src="'+fn+'" alt="Scene, weak supports, and two model candidate outlines"></a><p><a href="/results/r112/grouped-synthetic/'+e(s['image'])+'">Original scene</a> · <a href="'+e(row['archive'])+'">Saved candidates and weak supports</a></p></article>')
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Segmentation baseline on grouped synthetic scenes</title><style>body{font:16px/1.55 system-ui;background:#f4f6f0;color:#193b37;margin:0}main{max-width:1350px;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;display:block;overflow:auto}td,th{border:1px solid #cddbd2;padding:8px;text-align:left}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/grouped-synthetic/">Grouped scenes</a></nav><h1>Can automatic proposals recover the inserted supports?</h1><p class="notice"><strong>Updated location audit:</strong> The UDE sampling supplement links source slides to collection information. A conservative site-code/coordinate grouping is shared across the local training and comparison partitions for 124 of 240 comparison placements. This does not prove duplicate specimens, but the comparison is not location-independent. <a href="/results/r112/ude-sampling-metadata/">See the audit</a>.</p><p class="notice"><strong>Weak synthetic development diagnostic, not real segmentation accuracy.</strong> Source masks and identities are unverified model hypotheses, and their projected extents do not establish visible anatomy. Academy backgrounds can contain unannotated diatoms; unmatched predictions are not confirmed false positives. The scene sources and slides were used in earlier work, and filename grouping does not prove biological independence.</p><p>All 48 local comparison scenes were resized from 768 to 512 pixels and processed without revealing insertion positions. MobileSAM used fixed grids of 64 or 256 image-only points; the YOLOv8 model is the earlier R95 mixed-12 development checkpoint, not a latest or out-of-box model. Model candidates are matched one-to-one to projected weak supports. The main table includes supports of at least 50 pixels after resizing; it is a measure of matching these synthetic proxies, not biological recall or precision.</p><table><tr><th>Model</th><th>Top 30 · IoU ≥0.5</th><th>Top 30 · IoU ≥0.75</th><th>All candidates · IoU ≥0.5</th><th>Candidates across 48 scenes</th></tr>'''+table+'''</table><h2>Overlapping and partial proxy supports</h2><p>Counts use the same per-scene one-to-one assignments, so categories may overlap and must not be summed. Overlap is measured on the resized projected supports; clipping is measured on the original projected support and is not confirmed biological truncation. The last row uses the separate all-nonempty matching denominator.</p><table><tr><th>Proxy category · top 30 · IoU ≥0.5</th>'''+''.join('<th>'+e(names[k])+'</th>' for k in policies)+'</tr>'+subrows+'''</table><p><a href="protocol.json">Frozen protocol</a> · <a href="summary.json">Aggregate counts</a> · <a href="results.json">All per-scene scores and rankings</a> · <a href="verify.json">Reconstruction and scoring checks</a> · <a href="inference-replay.json">Four-scene inference replay</a></p><h2>All 48 comparison scenes</h2><p>Yellow outlines are unverified projected supports. Green outlines are top-30 candidates assigned to one of those supports at IoU ≥0.5; orange outlines are other candidates and are <strong>not confirmed false positives</strong>. Overlay drawing order can hide overlaps. Click any panel to enlarge.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print(json.dumps({'scenes':len(r['records']),'top30_main_05':{k:summary[k]['30']['main_0.5'] for k in policies}},indent=2))
