"""Render image-only box selection replay and rerun."""
import json,html
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r68';rs=json.loads((OUT/'results.json').read_text())['records'];rr=json.loads((OUT/'rerun-results.json').read_text())['records'];methods=('prefix','spatial','box_detector','hybrid')
def table(xs):
 rows=''
 for budget in (20,40):
  for method in methods:
   scores=[x['scores'][f'{method}_{budget}'] for x in xs];vals=[sum(y['budgets'][str(n)]['matched'] for y in scores) for n in (5,10,20)]+[sum(y['all']['matched'] for y in scores)];ret=sum(y['retained'] for y in scores);rows+=f'<tr><td>{method}</td><td>{budget}</td>'+''.join(f'<td>{v}</td>' for v in vals)+f'<td>{ret}</td></tr>'
 return rows
cards=''
for x in rs:
 den=len(x['source_ids']);vals=', '.join(f"{m} {x['scores'][m+'_40']['budgets']['10']['matched']}/{den}" for m in methods);cards+=f'<article><h2>{html.escape(x["condition"])} · pair {x["pair"]}</h2><img src="{x["image"]}" alt="Synthetic targets and box selection comparisons"><p>Top 10 at 40 boxes per plane: {vals}. <a href="{x["source_archive"]}">Original planes</a> · <a href="{x["contrast_archive"]}">All candidate boxes and masks</a> · <a href="{x["clahe_archive"]}">CLAHE outputs</a>.</p></article>'
rerun=''.join(f'<tr><td>{x["scene_index"]} · {html.escape(x["condition"])}</td><td>{x["policy"]}</td><td>{x["inference_seconds"]:.2f}</td><td>{sum(y["mask_changed"] for y in x["per_plane"])}</td><td>{sum(y["eligibility_changes"] for y in x["per_plane"])}</td></tr>' for x in rr)
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Image-only contrast box selection</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1520px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:16px}article{background:white;padding:14px;margin:16px 0}img{width:100%}table{border-collapse:collapse}th,td{padding:8px;border:1px solid #aaa;text-align:left}.table{overflow:auto}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R68.md">Research notes</a></nav><h1>Selecting contrast boxes before SAM inference</h1><p class="notice">Exploratory replay on previously examined R64 synthetic scenes. Three pairs repeat across conditions. Synthetic masks and additive blur are not expert real-slide labels and do not establish human-level accuracy.</p><p>Before consulting each box's saved segmentation mask or reference labels, we choose 20 or 40 boxes per plane using the original contrast ordering, 4×4 spatial round robin, overlap with same-plane detector boxes, or a detector/spatial hybrid. The fixed three-stream ranking and IoU ≥0.8 mask suppression then run unchanged. Full synthetic masks are matched one-to-one at IoU ≥0.5. Replay itself uses already generated masks and does not measure inference time.</p><h2>Nine crossing scenes: 18 targets</h2><div class="table"><table><tr><th>Policy</th><th>Boxes/plane</th><th>Top 5</th><th>Top 10</th><th>Top 20</th><th>All</th><th>Retained masks</th></tr>ROWS</table></div><p>The 80-box baseline matched 9/18 at top 10 and 10/18 with all candidates. Equal totals need not mean the same targets: spatial-40 lost an 80-box match in one scene but gained one in another. A different-source validation is needed.</p><h2>Actual prompt inference on four selected scenes</h2><p>Reruns use saved selected box coordinates; time includes five SAM image encodings and mask inference but excludes box generation, detector, NMS and scoring. One run per case is not a production benchmark. Changed-mask and eligibility columns compare each new output against the stored 80-box run.</p><div class="table"><table><tr><th>Scene</th><th>Policy</th><th>Seconds</th><th>Changed masks</th><th>Eligibility changes</th></tr>RERUN</table></div><p><a href="protocol.json">Replay protocol</a> · <a href="results.json">Scores and selected IDs</a> · <a href="rerun-protocol.json">Rerun protocol</a> · <a href="rerun-results.json">Rerun masks and timing</a>. Natural-background-only controls contain unannotated objects; candidate counts are not false positives. Public foreground: Gündüz et al., <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>; provenance in <a href="/results/r64/">R64</a>.</p>CARDS</main></html>'''.replace('ROWS',table([x for x in rs if x['condition'].startswith('crossing_')])).replace('RERUN',rerun).replace('CARDS',cards);(OUT/'index.html').write_text(page)
