"""Build an honest visual report from the completed, independently checked replay."""
import json,html
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r92/khanom';d=json.loads((O/'results.json').read_text());rows=d['records'];assert len(rows)==20;dup=json.loads((O/'duplicate-audit.json').read_text());audit={r['name']:r for r in dup['records']}
summary=[]
for group in ('r84','r85'):
 a=[r for r in rows if r['group']==group];total=sum(r['references'] for r in a)
 for threshold in ('0.5','0.75'):
  matches=[sum(r[model]['30'][threshold]['matched'] for r in a) for model in ('sam','cellpose','union')];summary.append(f'<tr><td>{group.upper()} ({len(a)} fields)</td><td>{threshold}</td>'+''.join(f'<td>{m}/{total}</td>' for m in matches)+'</tr>')
pair=[r for r in rows if r['pair_ids']];pairtotal=sum(len(r['pair_ids']) for r in pair)
for threshold in ('0.5','0.75'):
 values=[sum(r['pair_scores'][model][threshold]['matched'] for r in pair) for model in ('sam','cellpose','union')];summary.append(f'<tr><td>R85 weak-intersection objects ({len(pair)} fields)</td><td>{threshold}</td>'+''.join(f'<td>{m}/{pairtotal}</td>' for m in values)+'</tr>')
groupcounts={name:sum(r['pair_scores'][name]['0.5']['matched']==len(r['pair_ids']) for r in pair) for name in ('sam','cellpose','union')}
sections=[]
for r in rows:
 a=audit[r['name']];sections.append(f'<section><h3>{html.escape(r["name"])} · {html.escape(r["filename"])}</h3><p>{r["references"]} source polygons; MobileSAM / Cellpose / union top-30 matches at IoU 0.5: {r["sam"]["30"]["0.5"]["matched"]} / {r["cellpose"]["30"]["0.5"]["matched"]} / {r["union"]["30"]["0.5"]["matched"]}. Union contains {a["pair_iou_ge_0_8"]} candidate pairs with IoU ≥0.8; geometry alone cannot determine identity. <a href="/{html.escape(r["source_path"])}">Original image</a> · <a href="{r["archive"]}">Cellpose arrays and source references</a></p><img src="{r["image"]}" alt="Source polygons and candidates from MobileSAM, Cellpose and their interleaved union"></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>R92 Khanom replay</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/r92/">R92 earlier replay</a> · <a href="/results/board.html">Research board</a><h1>R92: Different-dataset candidate replay</h1><p class="box">All 20 fields and their MobileSAM results were already viewed. Although the dataset differs from the earlier Gündüz test, biological samples and base-model training data are not known to be independent. Only two source polygon pairs overlap, weakly (0.4% and 2.3% of the smaller polygons at original resolution). This is not evidence of severe real-overlap performance or human-level segmentation.</p><p>Compare up to 30 MobileSAM candidates, Cellpose candidates, or a round-robin union of the two without duplicate suppression. One-to-one matching uses source polygons; unannotated image content means candidates cannot be labeled false positives automatically. Model compute and prompting differ.</p><table><tr><th>Reference group</th><th>IoU</th><th>MobileSAM</th><th>Cellpose</th><th>Union</th></tr>'''+''.join(summary)+'''</table><p>Both polygons recovered in the same weak-intersection field at IoU 0.5: MobileSAM '''+str(groupcounts['sam'])+'''/2, Cellpose '''+str(groupcounts['cellpose'])+'''/2, union '''+str(groupcounts['union'])+'''/2. The weak-intersection-object rows rescore only the four polygons belonging to the two pairs; they overlap the R85 totals and must not be added to them. The first 11 fields were run at four CPU threads; the remaining fields used two. The checkpoint was verified before resumption, and all retained masks and scores were reconstructed after completion. No model inference was repeated during score verification.</p><p>Retrospective overlap audit: '''+str(sum(bool(r['edges']) for r in dup['records']))+''' of 20 fields contain at least one candidate pair with IoU ≥0.8 in the top-30 union. Similar masks can be duplicates or distinct overlapping specimens; do not discard them automatically or treat the candidate count as an organism count. <a href="duplicate-audit.json">Inspect pair geometry</a>.</p><p>Source: Khanom, <a href="https://zenodo.org/records/21295927">Images of diatoms for CNN model training</a>, CC BY 4.0. Separate model reuse conditions apply. <a href="protocol.json">Frozen protocol</a> · <a href="resumption.json">Checkpoint and CPU provenance</a> · <a href="results.json">Scores and hashes</a> · <a href="verify.log">Verification log</a> · <a href="/research/r92_khanom_resume.py">Resumable launcher</a> · <a href="/research/R92.md">Research note</a></p><h2>Field comparisons</h2>'''+''.join(sections)+'</html>')
