import html,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r96';d=json.loads((O/'results.json').read_text());rows=d['records'];assert len(rows)==33
summary=[]
for fam,cat,tag,label in [('train',None,'hidden','Withheld training objects'),('evaluation','real','all','Gündüz real'),('evaluation','synthetic','all','Synthetic visible regions')]:
 a=[r for r in rows if r['family']==fam and (cat is None or r['category']==cat)];den=sum(len(r['subsets'][tag]) for r in a)
 for th in ('0.5','0.75'):
  vals=[sum(r['scores'][name]['30'][tag][th]['matched'] for r in a) for name in ('yolo','sam','both')];summary.append(f'<tr><td>{label} ({len(a)} fields)</td><td>{th}</td>'+''.join(f'<td>{x}/{den}</td>' for x in vals)+'</tr>')
sections=[]
for r in rows:
 tag='hidden' if r['family']=='train' else 'all';v=[r['scores'][name]['30'][tag]['0.5']['matched'] for name in ('yolo','sam','both')];sections.append(f'<section><h3>{html.escape(r["name"])}</h3><p>{len(r["subsets"][tag])} reference regions; {r["prompt_count"]} model-proposed boxes. Top-30 YOLO / SAM / alternating matches: {v[0]} / {v[1]} / {v[2]}. <a href="/{html.escape(r["source"])}">Source image</a> · <a href="{r["archive"]}">Refined masks and paired boxes</a></p><img src="{r["image"]}" alt="Reference regions and original, refined and alternating candidate 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>R96 model-box mask refinement</title><style>body{font:16px/1.55 system-ui;max-width:1200px;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/l84/">Low-confidence diagnosis</a><h1>R96: Refine model-proposed boxes into masks</h1><p class="box">Retrospective development test. Fourteen fields contain deliberately withheld training annotations and were seen during training; the 19 other cases were viewed in previous studies. Real source references exclude intersecting boxes, and synthetic crossings are not physical microscopy. The result does not establish biological independence, severe real-overlap recovery or human-level performance.</p><p>Take up to 30 valid boxes per field from the saved partial-standard YOLO model at confidence ≥0.001, in YOLO confidence order. Prompt MobileSAM with each box; no reference label selects or positions a prompt. Compare the original YOLO mask and the SAM mask for the same box, ranked identically, plus an alternating list that keeps both. A top-30 alternating list can include at most 15 boxes, so it has a different composition even though the display budget is equal.</p><table><tr><th>Cases</th><th>IoU</th><th>YOLO mask</th><th>SAM box mask</th><th>Alternating masks</th></tr>'''+''.join(summary)+'''</table><p>Cells show one-to-one matches to available source/visible regions with at most 30 displayed masks per field. On the viewed real fields, SAM's box masks improved over the corresponding YOLO masks, particularly at IoU 0.75. However, the earlier separate SAM/Cellpose proposal combination matched 16/16 at IoU 0.5 and 15/16 at 0.75 on these same real fields, using a different prompt procedure and compute. On synthetic scenes the earlier combination matched 13/16 and 12/16. Thus this is a promising refinement mechanism, not a demonstrated replacement for the stronger existing development baseline.</p><p>The test issued '''+str(sum(r['prompt_count'] for r in rows))+''' extra SAM box prompts across 33 fields. The source YOLO predictions already underwent internal NMS and a 100-output cap; missed boxes cannot be recovered by this refinement. Low confidence may cause high review burden, and unannotated material means unmatched candidates are not verified false positives. Original source images and candidate masks remain separately accessible.</p><p>Nine selected prompts were also rerun individually: all nine reproduced their saved batched masks exactly, with maximum native score difference below 0.000001. The score verifier replayed all selection, ordering and one-to-one matches from saved masks, without repeating all inference.</p><p>Sources: <a href="https://zenodo.org/records/21295927">Khanom diatoms</a> and <a href="https://doi.org/10.5281/zenodo.7079005">River Menne data</a>, CC BY 4.0; <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Gündüz diatoms</a>, CC BY-NC-SA 4.0. Model/software and local Academy background terms also apply.</p><p><a href="protocol.json">Protocol</a> · <a href="results.json">Paired masks, prompts and scores</a> · <a href="verify.log">Verification</a> · <a href="single-prompt-replay.json">Nine-prompt inference replay</a> · <a href="/research/R96.md">Research note</a></p><h2>Case comparisons</h2><p>Each panel shows the first ten masks; table scores use up to 30. Orange references are deliberately withheld training annotations; candidate colors have no taxonomic meaning.</p>'''+''.join(sections)+'</html>')
