"""Build a static per-mask visual comparison; source arrays remain downloadable."""
import html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r110';p=json.loads((O/'protocol.json').read_text());new=json.loads((O/'results.json').read_text());old=json.loads((R/'results/l76/results.json').read_text());sections=[];meta=[]
names={'whole':'Whole-image MobileSAM','tile':'Tiled MobileSAM','yolo':'YOLO boxes + MobileSAM','cellpose':'Cellpose-DINO'}
def unpack(z,key,shape):return np.unpackbits(z[key])[:int(np.prod(z[shape]))].reshape(z[shape]).astype(bool)
def draw(im,masks):
 out=im.convert('RGBA')
 for i,m in enumerate(masks):
  layer=Image.new('RGBA',im.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*90));out=Image.alpha_composite(out,layer)
 return out.convert('RGB')
for f,r,prior in zip(p['fields'],new['records'],old['records']):
 n=f['index'];z=np.load(O/r['archive']);oz=np.load(R/'results/l76'/prior['archive']);whole=unpack(oz,'mask_bits','mask_shape');lookup=dict(zip(oz['ids'].tolist(),whole));tm=unpack(z,'tile_bits','tile_shape');tl=dict(zip(z['tile_ids'].tolist(),tm));ym=unpack(z,'yolo_sam_bits','yolo_sam_shape');labels=z['cp_labels'];methods={'whole':[(v,lookup[v]) for v in prior['rankings']['baseline']],'tile':[(v,tl[v]) for v in r['tile_ranking']],'yolo':[(f'box-{i+1}',m) for i,m in enumerate(ym)],'cellpose':[(str(v['id']),labels==v['id']) for v in r['cellpose_ranking']]};im=Image.open(R/f['middle_image']).convert('RGB');cards=[]
 for key,items in methods.items():
  folder=O/f'field-{n}-{key}';folder.mkdir(exist_ok=True);visible=items[:30];composite=draw(im,[v[1] for v in visible[:10]]);composite.save(folder/'top10.jpg',quality=90)
  options=[]
  for j,(ident,mask) in enumerate(visible):
   overlay=Image.new('RGBA',im.size,(0,138,112,0));overlay.putalpha(Image.fromarray(mask.astype('uint8')*110));overlay.save(folder/f'{j+1:02d}.png',optimize=True);options.append(f'<option value="{j+1:02d}.png">#{j+1} · {html.escape(str(ident))}</option>')
  if visible:
   view=f'<div class="stack"><img src="/{f["middle_image"]}" alt="Original middle plane"><img class="overlay" src="{folder.name}/01.png" alt="Selected candidate mask"></div><label>Individual candidate <select onchange="this.closest(\'article\').querySelector(\'.overlay\').src=\'{folder.name}/\'+this.value">{"".join(options)}</select></label>'
  else:view='<p>No retained candidates.</p>'
  cards.append(f'<article><h3>{names[key]}</h3><p>{len(items)} retained; displaying up to 30. Top 10 overlay:</p><img src="{folder.name}/top10.jpg" alt="First ten proposal masks"><details><summary>Inspect individual masks</summary>{view}</details></article>')
 plane_links=' · '.join(f'<a href="/results/l76/{prior["images"][f"plane{i}"]["image"]}">Plane {f["planes"][i]}</a>' for i in range(3)); timings=', '.join(f'{k.replace("_"," ")}: {v}s' for k,v in r['seconds'].items());sections.append(f'<section><h2>Field {n+1}</h2><p>{html.escape(f["slide"])} · native origin {f["origin_xy"]} · middle plane {f["planes"][1]} · pixel scale {f["xy_um_per_pixel"]} µm/px.</p><p>Original native crops: {plane_links}. <a href="/results/l76/">Focal-stream results</a> · <a href="{r["archive"]}">New output archive</a> · <a href="/results/l76/{prior["archive"]}">Cached whole-field archive</a></p><p>New-method wall times on two CPU threads, including inference warm-up where applicable: {html.escape(timings)}. These timings are not controlled benchmarks. Whole-field results were reused; the earlier run did not time that method separately.</p><div class="grid">{"".join(cards)}</div></section>');meta.append({k:len(v) for k,v in methods.items()})
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Academy segmentation comparison</title><style>body{font:16px/1.5 system-ui;color:#183c37;background:#f4f6f0;margin:0}main{max-width:1400px;margin:auto;padding:24px}a{color:#116b59}h1,h2,h3{font-family:Georgia,serif}section{border-top:1px solid #cbd8cf;margin-top:2em}.notice,article{background:white;padding:16px;border:1px solid #cedbd4;border-radius:5px}.notice{border-left:5px solid #bd8616}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}img{max-width:100%;height:auto}details{margin-top:12px}summary{cursor:pointer;color:#116b59}.stack{position:relative}.stack img{display:block;width:100%}.stack .overlay{position:absolute;inset:0}select{max-width:100%;font:inherit}</style><body><main><nav><a href="/results/assessment/">Assessment</a> · <a href="/results/progress.html">Progress</a> · <a href="/results/board.html">Board</a></nav><h1>Academy slide segmentation: four-way comparison</h1><p class="notice"><strong>Exploratory, unlabeled fields.</strong> The colored shapes are candidate masks, not confirmed diatoms. A top-ten overlay can conceal overlapping candidates; expand “Inspect individual masks” to compare one at a time. We cannot calculate recall, false-positive rate, human-level performance or a winner from these images.</p><p>All methods use the same native middle focal plane, on four previously examined fixed fields from two slides. Whole-image MobileSAM uses cached L76 outputs. Tiled MobileSAM uses 256 points and 16 image encodings, YOLO uses detector boxes to prompt MobileSAM, and Cellpose-DINO uses a separate automatic model. Up to 30 retained candidates per method are available; the overview shows the first 10. Scores and compute are not comparable between methods. Cellpose returns pixel-exclusive labels, so it cannot represent independent overlapping masks in one run.</p><p>Raw middle and neighboring planes remain available for interpretation. A better-looking outline does not establish that a candidate is a diatom or correctly separates overlapping specimens. Slide relationships are unknown, and the fields are not a held-out benchmark. Cropped grayscale planes and coordinates preserve access to the original stack for later species-level work.</p><p><a href="/research/R110.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">Rankings, source hashes and timings</a> · <a href="run.log">Run log</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Candidate counts per field:',meta)
