"""Render real-image candidate proposals and top-ranked local mask previews."""
import hashlib,html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l62';rows=json.loads((OUT/'results.json').read_text())['records'];source=json.loads((ROOT/'results/r73/results.json').read_text())['records'];manifest=[];cards=[]
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
for r,s in zip(rows,source):
 image=Image.open(ROOT/'results/r73/sources'/f"{r['index']:02d}-image.jpg").convert('RGB');a=np.load(OUT/r['archive'],allow_pickle=False);bitrows=a['mask_bits'];raw={q['id']:q for q in r['raw_candidates']};dets={q['candidate_id']:q for q in s['sam_candidates']};previews=[]
 for j,ident in enumerate(r['methods']['three_stream']['ranking'][:6],1):
  if ident in raw:
   q=raw[ident];x,y=q['origin'];mask=np.unpackbits(bitrows[q['mask_index']])[:640*640].reshape(640,640).astype(bool);kind=q['kind']
  elif ident in dets:
   q=dets[ident];x,y=q['origin'];mask=np.asarray(Image.open(ROOT/'results/r73'/q['mask']).convert('L'))>0;kind='detector'
  else:continue
  crop=image.crop((x,y,x+640,y+640)).convert('RGBA');layer=Image.new('RGBA',crop.size,'#e85956');layer.putalpha(Image.fromarray(mask.astype('uint8')*100));im=Image.alpha_composite(crop,layer).convert('RGB');draw=ImageDraw.Draw(im)
  for bb in s['target_boxes']:
   l=max(0,bb[0]-x);t=max(0,bb[1]-y);right=min(640,bb[2]-x);bottom=min(640,bb[3]-y)
   if l<right and t<bottom:draw.rectangle([l,t,right,bottom],outline='#00a975',width=5)
  file=f'field-{r["index"]:02d}-top-{j:02d}.jpg';im.resize((320,320),Image.Resampling.LANCZOS).save(OUT/file,quality=88);previews.append({'rank':j,'id':ident,'kind':kind,'origin':[x,y],'image':file,'sha256':sha(OUT/file)})
 manifest.append({'index':r['index'],'previews':previews});gallery=''.join(f'<figure><img src="{x["image"]}" alt="Automatic mask overlay and any published target boxes in this crop"><figcaption>Rank {x["rank"]} · {html.escape(x["kind"])} · origin {x["origin"]}</figcaption></figure>' for x in previews) or '<p>No top-ranked candidates have available mask previews.</p>';scores=r['methods'];vals=', '.join(f"{m}: {scores[m]['budgets']['10']['matched']}/{r['target_count']}" for m in ('detector','point','contrast','three_stream'));cards.append(f'''<article><h2>Field {r['index']} · {html.escape(r['site'])}</h2><img class="montage" src="{r['image']}" alt="Published target boxes in green and automatic candidate boxes in red"><p>Top-ten published box matches: {vals}. <a href="{r['archive']}">All raw prompt masks</a> · <a href="/results/r73/sources/{r['index']:02d}-image.jpg">Original RGB image</a>.</p><details><summary>Inspect masks for up to six top-ranked candidates</summary><p>Pink areas are unverified model masks on their original 640 × 640 patches; green rectangles are published single-taxon boxes shown only after prediction.</p><div class="gallery">{gallery}</div></details></article>''')
(OUT/'preview-manifest.json').write_text(json.dumps({'format':'l62-preview-v1','results_sha256':sha(OUT/'results.json'),'records':manifest},indent=2)+'\n')
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Real-image point and contrast proposals</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1920px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:16px}article{background:white;padding:14px;margin:16px 0}.montage{width:100%}.gallery{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:8px}figure{margin:0}figure img{width:100%}summary{cursor:pointer;font-weight:bold}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/results/r73/">Published box baseline</a> · <a href="/research/L62.md">Research notes</a></nav><h1>Point and contrast proposals on real annotated fields</h1><p class="notice">These are previously inspected development images of marine fossil material, with published boxes for one species only. Box matching does not score mask boundaries, and unannotated objects and debris are not negative labels. Results do not establish freshwater, overlap-instance or human-level accuracy.</p><p>Each 2400 × 2400 RGB field is divided into 25 overlapping 640 × 640 patches. Per patch, 16 fixed point prompts and up to 20 spatially selected contrast boxes are generated from the image without using published labels. SAM masks are filtered and ranked, then combined with the prior tiled detector stream. Green outlines are published single-species boxes; red outlines are candidate mask bounding boxes or detector boxes. Published boxes were used only for posthoc one-to-one box IoU ≥0.5 scoring.</p><p>On these nine development fields (10 published boxes), the baseline tiled detector matched 3/10 within its first ten candidates. Point masks alone matched 5/10, and the mixed three-stream ranking matched <strong>7/10 at top ten</strong>, 8/10 at top fifty and 9/10 with all retained candidates. The mixed stream retained 1,368 candidates, and the experiment generated 7,772 raw prompt masks. Counts and unmatched candidates are not false-positive estimates. Box NMS may suppress valid overlapping instances; all input masks and prefilter/final suppression aliases are preserved.</p><p><a href="protocol.json">Frozen development protocol</a> · <a href="results.json">Scores, prompts and rankings</a> · <a href="prefilter-aliases.json">Point and contrast suppression aliases</a> · <a href="preview-manifest.json">Preview hashes</a>. Public source: Ishino, Itaki and Fukuda, <a href="https://doi.org/10.17632/457x9c7rp3.2">fossil diatom dataset</a>, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>; crops and overlays are derivatives.</p>CARDS</main></html>'''.replace('CARDS',''.join(cards));(OUT/'index.html').write_text(page)
