"""Render and independently rescore retained Cellpose label maps."""
import json,hashlib,html
from pathlib import Path
import numpy as np
from l70_cellpose import match
R=Path(__file__).resolve().parents[1];O=R/'results/l79'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
data=json.loads((O/'results.json').read_text());p=json.loads((O/'protocol.json').read_text());assert sha(O/'protocol.json')==data['protocol_sha256'];assert len(data['records'])==19
source_real=json.loads((R/p['source_real']).read_text())['records'];source_syn=json.loads((R/p['source_synthetic']).read_text())['records'];assert sha(R/p['source_real'])==p['source_real_sha256'] and sha(R/p['source_synthetic'])==p['source_synthetic_sha256']
for r in data['records']:
 assert sha(R/r['source'])==r['source_sha256'] and sha(R/r['source_archive'])==r['source_archive_sha256'] and sha(O/r['archive'])==r['archive_sha256'] and sha(O/r['image'])==r['image_sha256'];z=np.load(O/r['archive']);old=np.load(R/r['source_archive']);lab=z['labels'];prob=z['cellprob'];ids=z['refids'].tolist();refs=z['refs'];assert np.array_equal(refs,old['refs'] if r['group']=='real' else old['refs'][ids]);order=sorted((int(x) for x in np.unique(lab) if x),key=lambda x:(-float(prob[lab==x].mean()),x));assert order==r['candidate_order']==z['candidate_labels'].tolist();masks=np.stack([lab==j for j in order]) if order else np.zeros((0,512,512),bool)
 for n in (10,30,'all'):
  for th in (.5,.75):assert match(refs,ids,masks if n=='all' else masks[:n],th)==r['scores'][str(n)][str(th)]
print('verified 19 archives, source hashes, rankings and every matching score')
rows=[]
for group in ('real','synthetic'):
 rr=[r for r in data['records'] if r['group']==group];n=sum(r['references'] for r in rr)
 for th in ('0.5','0.75'):
  a=sum(r['scores']['30'][th]['matched'] for r in rr);b=sum(r['mobile_sam']['30'][th]['matched'] for r in rr);rows.append(f'<tr><td>{group.title()}</td><td>{th}</td><td>{a}/{n}</td><td>{b}/{n}</td><td>{sum(r["candidates"] for r in rr)}</td></tr>')
sections=[]
for r in data['records']:
 sections.append(f'<section><h3>{html.escape(r["name"])}</h3><p>{r["references"]} reference regions; Cellpose {r["candidates"]} labels; top-30 matches at IoU 0.5: Cellpose {r["scores"]["30"]["0.5"]["matched"]}, MobileSAM {r["mobile_sam"]["30"]["0.5"]["matched"]}. <a href="/{html.escape(r["source"])}">Source image</a> · <a href="{r["archive"]}">Raw labels, probabilities and references</a></p><img src="{r["image"]}" alt="Reference, top ranked Cellpose masks and all Cellpose masks"></section>')
(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>L79 Cellpose-SAM v2 replay</title><style>body{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}a{color:#006b59}img{max-width:100%}.box{background:#fff2d6;padding:1em}section{border-top:1px solid #ccc}td,th{padding:.4em;border:1px solid #bbc}table{border-collapse:collapse}</style><a href="/results/board.html">Research board</a> · <a href="/results/r91/">Earlier decoder comparison</a><h1>L79: Can Cellpose-SAM v2 supply useful candidates?</h1><p class="box">Exploratory replay on previously examined cases. Eleven public fields contain structurally derived regions with intersecting boxes excluded; they are not a real heavy-overlap benchmark. Eight synthetic cases are opaque composites, not physical microscopy. Source-file separation does not establish biological or model-training independence. Cellpose labels are pixel-exclusive and cannot encode full instances sharing pixels.</p><p>One-to-one matches to visible/source reference regions, at most 30 masks per image. The models use different proposal procedures and compute; candidate counts are not false positives because the references may be incomplete. This is not evidence of human-level performance or species identification.</p><table><tr><th>Cases</th><th>IoU threshold</th><th>Cellpose top 30</th><th>MobileSAM top 30</th><th>Cellpose labels, all</th></tr>'''+''.join(rows)+'''</table><p>Cellpose masks are ranked by mean predicted cell probability; it is a model-native heuristic, not calibrated confidence. RGB images, masks, probabilities, flow arrays, source hashes and reference scores are retained. Original scans and focus planes remain available for later classification.</p><p>Gündüz source images and derivatives: <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, CC BY-NC-SA 4.0. The <a href="https://huggingface.co/mouseland/cellpose-sam">model card</a> declares BSD-3-Clause, while the <a href="https://github.com/MouseLand/cellpose">Cellpose authors</a> state their models are trained on CC BY-NC data. Verify applicable terms before downstream deployment.</p><p><a href="protocol.json">Protocol and corrected API setting</a> · <a href="results.json">Full results</a> · <a href="/research/l79_report.py">Rescoring and report code</a> · <a href="/research/L79.md">Research note</a></p><h2>Case comparisons</h2>'''+''.join(sections)+'</html>')
