"""Show all provisional UDE mask candidates and original crops for inspection."""
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/r112/design/ude-calibrated';data=json.loads((O/'manifest.json').read_text());cards=[]
def make_panel(source,masks,dst):
 w,h=source.size;scale=min(250/w,250/h);size=(max(1,round(w*scale)),max(1,round(h*scale)));out=Image.new('RGB',(780,286),'white');d=ImageDraw.Draw(out)
 for i,(title,mask) in enumerate([('Source cutout',None),('Point proposal',masks['point']),('Box proposal',masks['box'])]):
  image=source.convert('RGBA')
  if mask is not None:
   layer=Image.new('RGBA',image.size,(0,150,115,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*110));image=Image.alpha_composite(image,layer)
  x=i*260+(250-size[0])//2;y=26+(250-size[1])//2;out.paste(image.convert('RGB').resize(size,Image.Resampling.LANCZOS),(x,y));d.text((i*260+4,5),title,fill='#183b37')
 out.save(dst,quality=91)
for r in data['records']:
 ident=r['annotation_id'];src=Image.open(R/r['source_image']).convert('L');masks={k:np.asarray(Image.open(O/v['mask']).convert('L'))>0 for k,v in r['mask_proposals'].items()};fn=f'{ident}-comparison.jpg';make_panel(src,masks,O/fn);delta=r['crop_vs_annotation_bbox_delta_px'];cards.append(f'<article><h3>{html.escape(r["source_species"])} · {ident}</h3><p>Source slide: {html.escape(r["source_slide"])}. Original {r["source_crop_size_px"]} pixels at 0.09 µm/px; scaled to {r["target_crop_size_px"]} pixels for {html.escape(r["target_slide"])}. Crop versus recorded annotation-box dimensions: {delta} pixels. Source name and proposed masks are unverified.</p><img loading="lazy" src="{fn}" alt="Original image, point-prompt candidate and box-prompt candidate"><p><a href="/{r["source_image"]}">Original pixels</a> · <a href="{r["scaled_image"]}">Scaled crop</a> · <a href="{r["mask_proposals"]["point"]["mask"]}">Point mask</a> · <a href="{r["mask_proposals"]["box"]["mask"]}">Box mask</a></p></article>')
(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>Calibrated UDE source candidates</title><style>body{font:16px/1.55 system-ui;background:#f4f6f0;color:#183b37;margin:0}main{max-width:1050px;padding:24px;margin:auto}h1,h2,h3{font-family:Georgia,serif}a{color:#096c58}article,.notice{background:white;border:1px solid #cddbd2;border-radius:5px;padding:16px;margin:14px 0}.notice{border-left:5px solid #bd8616}img{max-width:100%;height:auto}</style><body><main><nav><a href="/results/r112/">Synthetic training project</a> · <a href="/research/R112_DESIGN.md">Design</a></nav><h1>Calibrated source crops: candidate masks</h1><p class="notice"><strong>Development material, not segmentation ground truth.</strong> Source annotations are rough rotated rectangles; the two masks were generated by MobileSAM from the cutout center and box. They can include neighbors, miss features or select the wrong object. Source species are dataset labels, not independently verified here. Inspect the original in every case.</p><p>The source publication states a 0.09 µm/pixel scale. We resize each crop to a recorded Academy scan's OME XY calibration, preserving original source pixels separately. These source images are focused stacks; a matching pixel size does not guarantee equivalent optics or resolution. All 64 crops are from previously used training groups; no final test material is included or claimed. Backgrounds and ambiguous instances are not reliable negatives.</p><p><a href="manifest.json">All provenance, prompts, masks and transforms</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Limitations and next steps</a></p>'''+''.join(cards)+'''</main></body></html>''')
print('Rendered',len(cards),'source/mask comparisons')
