"""Render preselected separate-site real-image proposal validation."""
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/r74';P=OUT/'proposals';rows=json.loads((P/'results.json').read_text())['records'];audit=json.loads((OUT/'split-audit.json').read_text());duplicates={x['test_index']:x['development_duplicates'] for x in audit['rows'] if x['development_duplicates']};source=json.loads((OUT/'baseline/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(OUT/'sources'/f"{r['index']:02d}-image.jpg").convert('RGB');a=np.load(P/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(OUT/'baseline'/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(P/file,quality=88);previews.append({'rank':j,'id':ident,'kind':kind,'origin':[x,y],'image':file,'sha256':sha(P/file)})
 manifest.append({'index':r['index'],'previews':previews});gallery=''.join(f'<figure><img src="proposals/{x["image"]}" alt="Automatic mask overlay and any published reference boxes"><figcaption>Rank {x["rank"]} · {html.escape(x["kind"])} · origin {x["origin"]}</figcaption></figure>' for x in previews) or '<p>No top-ranked candidates have mask previews.</p>';vals=', '.join(f"{m}: {r['methods'][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>'''+('<p class="notice">Exact-byte duplicate of a development image; excluded from the posthoc byte-disjoint subset.</p>' if r['index'] in duplicates else '')+f'''<img class="montage" src="proposals/{r['image']}" alt="Published target boxes in green and automatic candidate boxes in red"><p>Top-ten published-box matches: {vals}. <a href="proposals/{r['archive']}">All raw point and contrast masks</a> · <a href="sources/{r['index']:02d}-image.jpg">Original RGB image</a> · <a href="sources/{r['index']:02d}-label.txt">Published YOLO boxes</a>.</p><details><summary>Inspect up to six top-ranked masks</summary><p>Pink areas are unverified model masks on 640 × 640 original-image patches. Green rectangles are published single-taxon boxes added after prediction.</p><div class="gallery">{gallery}</div></details></article>''')
(P/'preview-manifest.json').write_text(json.dumps({'format':'r74-preview-v1','results_sha256':sha(P/'results.json'),'records':manifest},indent=2)+'\n');total=sum(r['target_count'] for r in rows);methods=('detector','point','contrast','detector_point','detector_contrast','three_stream');table=''
for m in methods:
 vals=[sum(r['methods'][m]['budgets'][str(n)]['matched'] for r in rows) for n in (10,50)]+[sum(r['methods'][m]['all']['matched'] for r in rows)];count=sum(r['methods'][m]['retained'] for r in rows);table+='<tr><td>'+m+'</td>'+''.join(f'<td>{x}</td>' for x in vals)+f'<td>{count}</td></tr>'
subset=''
for m in methods:
 q=audit['posthoc_exact_disjoint_metrics'][m];subset+=f'<tr><td>{m}</td><td>{q["top10"]}</td><td>{q["top50"]}</td><td>{q["all"]}</td><td>{q["retained"]}</td></tr>'
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Separate-site real-image proposal validation</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}table{border-collapse:collapse}th,td{padding:8px;border:1px solid #aaa}.table{overflow:auto}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/results/l62/">Development comparison</a> · <a href="/research/R74.md">Research notes</a></nav><h1>Frozen proposal policy on separate real-image sites</h1><p class="notice">These are public marine fossil fields with expert-drawn boxes for one taxon. They are not complete per-diatom mask labels or freshwater test data. Unmatched proposals cannot be labeled false positives; box matching does not establish segmentation accuracy or human-level performance.</p><p>The L62 point/contrast/detector policy was frozen before selecting new sites and downloading images or label contents. The first three matching image/label filenames from each of three distinct site folders were selected and verified against published SHA-256. Three of the nine images are exact-byte duplicates of development images despite different site names, and their published label files differ. The full test is contaminated; the six-image subset below was defined posthoc by removing exact duplicates. Byte-disjointness does not prove independent biological specimens, nonoverlapping fields of view or absence of model-training overlap. Predictions and mask generation precede posthoc box scoring.</p><p class="notice"><strong>Split contamination:</strong> Three G503 images are byte-for-byte copies of G404 development images. Their published box files differ. Results on all nine are not independent validation. <a href="split-audit.json">Inspect exact-byte audit</a>.</p><h2>Prespecified nine-field comparison (includes duplicates)</h2><p>Box IoU ≥0.5, maximum-cardinality one-to-one matching; TARGETS published boxes in nine fields. Baseline and mask-proposal rankings are limited to equal review budgets. Candidate areas and outlines remain unverified.</p><div class="table"><table><tr><th>Method</th><th>Top 10</th><th>Top 50</th><th>All</th><th>Retained candidates</th></tr>ROWS</table></div><h2>Posthoc exact-byte-disjoint subset</h2><p>Six remaining fields contain seven published boxes. This subset was defined after duplicate detection and is not guaranteed biologically independent.</p><div class="table"><table><tr><th>Method</th><th>Top 10</th><th>Top 50</th><th>All</th><th>Retained candidates</th></tr>SUBSET</table></div><p><a href="policy.json">Preselection policy</a> · <a href="pair-selection.json">Selected files</a> · <a href="proposals/protocol.json">Frozen experiment inputs</a> · <a href="proposals/results.json">All candidate scores and masks</a> · <a href="proposals/prefilter-aliases.json">Prefilter suppression aliases</a>. Source: Ishino, Itaki and Fukuda, <a href="https://doi.org/10.17632/457x9c7rp3.2">public fossil diatom dataset</a>, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>; crop previews and overlays are derived from its RGB images.</p>CARDS</main></html>'''.replace('TARGETS',str(total)).replace('ROWS',table).replace('SUBSET',subset).replace('CARDS',''.join(cards));(OUT/'index.html').write_text(page)
