"""Generate human-readable R80 result and static dashboard entries."""
import datetime,html,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r80';d=json.loads((O/'results.json').read_text());records=d['records'];cp=json.loads((O/'cellpose.json').read_text());audit=json.loads((O/'source-audit.json').read_text());labels={'sam':'MobileSAM only','cellpose':'Cellpose only','sam_first':'SAM first, no deferral','sam_first_08':'SAM first, defer ≥0.8','sam_first_095':'SAM first, defer ≥0.95','cp_first':'Cellpose first, no deferral','cp_first_08':'Cellpose first, defer ≥0.8','cp_first_095':'Cellpose first, defer ≥0.95'};names=list(labels);total_refs=sum(r['reference_count'] for r in records)
def totals(name,budget):
 x=[r['scores'][name][str(budget)] for r in records];return {'n':sum(a['iou05']['candidate_count'] for a in x),'v05':sum(a['iou05']['matched'] for a in x),'v075':sum(a['iou075']['matched'] for a in x),'near':sum(a['near_pairs_iou08'] for a in x)}
rows=[];md=[]
for n in (5,10,20,'all'):
 for name in names:
  q=totals(name,n);row=[str(n),labels[name],str(q['n']),f"{q['v05']}/{total_refs}",f"{q['v075']}/{total_refs}",str(q['near'])];rows.append('<tr>'+''.join('<td>'+html.escape(x)+'</td>' for x in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
base=totals('sam',10);mixed=totals('sam_first',10);defer=totals('sam_first_08',10);strict=totals('sam_first_095',10);times=sum(r['seconds_inference'] for r in cp['records']);cards=[]
for r in records:
 a=r['scores']['sam']['10']['iou05']['matched'];b=r['scores']['sam_first']['10']['iou05']['matched'];c=r['scores']['sam_first_08']['10']['iou05']['matched'];cards.append(f"<article><h3>Source case {html.escape(r['id'])}</h3><img src='{html.escape(r['image'])}' alt='Source references, MobileSAM, Cellpose, mixed, and deferred candidate masks'><p>Top-ten source matches: SAM {a}/{r['reference_count']} · mixed {b}/{r['reference_count']} · deferred {c}/{r['reference_count']}.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R80 · Cross-source deferral check</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1280px;margin:auto;padding:20px}article,.card{background:white;padding:16px;margin:12px 0;border:1px solid #d4ded6}img{max-width:100%}.notice{background:#fff2d6;padding:14px}th,td{padding:8px;text-align:left;border-bottom:1px solid #d4ded6}.scroll{overflow:auto}a{color:#126d55}</style><main><nav><a href="/results/board.html">Research board</a> · <a href="/research/R80.md">Research note</a> · <a href="/results/l69/">Earlier deferral test</a></nav><h1>Does candidate deferral carry to another freshwater source?</h1><p class="notice"><strong>Previously viewed, non-overlap development cases.</strong> The 24 Gündüz source images were selected because binary components could be mapped to nonintersecting boxes. They cannot validate segmentation of overlapping or hidden diatoms. Labels and sample relationships are not independently verified, and the images were inspected in earlier experiments.</p><p>We reproduced the earlier MobileSAM 108-point/detector results, ran the same Cellpose DINOv3 model used before, and applied the already-fixed interleaving and cross-model overlap-deferral rules. Each policy sees the same model outputs; no candidate is deleted by the new mixing or deferral step. The source references are used only for scoring.</p><div class="card"><div class="scroll"><table><tr><th>Max masks per image</th><th>Ranking</th><th>Masks shown</th><th>Source matches ≥0.5</th><th>Source matches ≥0.75</th><th>Pairs IoU ≥0.8</th></tr>{ROWS}</table></div><p>At a ten-mask-per-image limit, MobileSAM matched {BASE}/{TOTAL} source regions, unchanged SAM-first mixing matched {MIX}/{TOTAL}, and 0.8 deferral matched {DEFER}/{TOTAL}. These are source-component matches, not species identification, false-positive rates, or evidence about real overlaps.</p><p>A strong mask overlap can belong to two distinct specimens. Deferral can push the second below a review cap; <a href="/results/r71/">the controlled examples</a> show this risk. Cellpose also assigns each pixel to at most one label, and MobileSAM’s original within-grid NMS precedes the tested ranking.</p></div><h2>Source cases</h2><p>Panels show source components, MobileSAM top ten, Cellpose top ten, SAM-first mixing and 0.8 deferral. Colors distinguish display layers, not biological identities.</p>{CARDS}<p>Cellpose inference took {SECONDS} CPU seconds across these cases, excluding initialization and scoring. The historical MobileSAM run used different settings, so this is not an end-to-end speed comparison.</p><p><a href="results.json">All rankings, assignments and deferral links</a> · <a href="protocol.json">Frozen protocol</a> · <a href="source-audit.json">Source audit</a> · <a href="baseline.json">Reproduced MobileSAM</a> · <a href="cellpose.json">Cellpose archives</a> · <a href="/research/r80_verify.py">Independent verifier</a> · <a href="/datasets/r80-gunduz/">Licensed source mirror</a></p><p>Source: Hüseyin Gündüz, <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, CC BY-NC-SA 4.0; images resized and overlaid. Cellpose training data are described by its authors as CC BY-NC; Meta DINOv3 has separate terms.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards)).replace('{BASE}',str(base['v05'])).replace('{MIX}',str(mixed['v05'])).replace('{DEFER}',str(defer['v05'])).replace('{TOTAL}',str(total_refs)).replace('{SECONDS}',f'{times:.1f}');(O/'index.html').write_text(page)
lines=['# R80 · Frozen mixed-model ranking on a different freshwater source','','[Visual results](/results/r80/) · [frozen protocol](/results/r80/protocol.json) · [scores, rankings and deferral links](/results/r80/results.json) · [MobileSAM reproduction](/results/r80/baseline.json) · [Cellpose masks](/results/r80/cellpose.json) · [source audit](/results/r80/source-audit.json) · [independent verifier](/research/r80_verify.py)','','Apply the frozen R79/L69 mixed-model and 0.8/0.95 deferral policies to all 24 previously viewed R48 Gündüz public cases at the original fixed 768×576 resolution. The binary foreground references are associated to nonintersecting source boxes under a strict structural rule; they are candidate source components, not independently verified biological instances. The selection explicitly rejects intersecting boxes, so this cannot test whether a true second overlapping or partial diatom is lost.','','The R48 108-point/detector MobileSAM pipeline was rerun and its per-case grid count and saved matches, matched IoUs and candidate counts at 5/10/20 and all reproduced before comparison. Historical model masks were not saved, so exact pixel identity with that earlier run cannot be verified. Cellpose DINOv3 uses the pinned R78 checkpoint and the same automatic thresholds. All raw SAM masks, filter metadata, suppression aliases, Cellpose labels and flows are archived. Neither model nor ranking uses reference masks. Deferral reorders candidate IDs without deleting them; Cellpose remains pixel-exclusive, and earlier SAM within-grid NMS can remove alternatives.','','| Max masks per image | Ranking | Masks shown | Source matches ≥0.5 | Source matches ≥0.75 | Pairs IoU ≥0.8 |','|---:|---|---:|---:|---:|---:|']+md
lines+=['',f"At ten masks per image, MobileSAM matches {base['v05']}/{total_refs}, unmodified SAM-first mixing {mixed['v05']}/{total_refs}, and SAM-first 0.8 deferral {defer['v05']}/{total_refs}. Corresponding displayed mask totals are {base['n']}, {mixed['n']} and {defer['n']}; ≥0.8 overlap-pair counts are {base['near']}, {mixed['near']} and {defer['near']}. Match counts are one-to-one, but component identity is source-derived and unverified; assignment identities can differ on ties. Unmatched proposals are not confirmed false positives.",'','The 24 image/mask/XML files matched their recorded hashes. The exact-file and coarse whole-image perceptual screen against the 18 R79 Menne fields flagged '+str(len(audit['cross_source_flagged_pairs']))+' cross-source pairs, but cannot rule out different crops, re-encodings, related specimens or model-training overlap. Sixteen cases were used to train the separate R54 adapted decoder; that checkpoint was not used here. Original selected images, masks and XMLs are also mirrored with verified SHA-256 under `datasets/r80-gunduz/` and retain their CC BY-NC-SA terms. The frozen protocol references temporary paths; `research/r80_restore_inputs.py` can restore missing copies from the mirror without overwriting changed files. Model weights and environment remain in temporary storage.','','An independent verifier checks input hashes, reconstructed source components, each archived model ranking, SAM within-grid NMS, all deferral links, one-to-one assignment optima and budget diagnostics. It does not independently rerun either model. Synthetic R71 controls demonstrate that a high-IoU deferral can postpone a genuinely distinct overlapping instance; 0.8 and 0.95 are ranking heuristics, not biological identity tests. These nonrandom, previously inspected source images cannot support real-overlap, false-positive, species-classification or human-level claims.','','Source: Hüseyin Gündüz, [Diatom Dataset](https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset), CC BY-NC-SA 4.0; resized images and overlays are noncommercial derivatives. Cellpose training data are described by its authors as CC BY-NC; Meta DINOv3 has separate terms.']
(R/'research/R80.md').write_text('\n'.join(lines)+'\n');p=R/'research/board.json';board=json.loads(p.read_text());board['updated']=datetime.date.today().isoformat()
for task in board['tasks']:
 if task['id']=='R80':task.update(status='review',summary=f"24 previously viewed non-overlap cases: SAM {base['v05']}/{total_refs}, mixed {mixed['v05']}/{total_refs}, 0.8 deferred {defer['v05']}/{total_refs} at top ten.",result='/results/r80/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();entry=f"- **R80 · Cross-source deferral:** SAM {base['v05']}/{total_refs}, mixed {mixed['v05']}/{total_refs}, deferred {defer['v05']}/{total_refs} at top ten on previously viewed non-overlap Gündüz cases. [Results](/results/r80/) · [note](research/R80.md).";
if entry not in s:s+='\n'+entry+'\n'
p.write_text(s)
p=R/'results/performance/index.html';s=p.read_text();needle='<section class="panel gap"><h2>Current research</h2>';entry=f'<p><a href="/results/r80/">Cross-source deferral check</a> — SAM {base["v05"]}/{total_refs}, mixed {mixed["v05"]}/{total_refs}, deferred {defer["v05"]}/{total_refs} at top ten; prior non-overlap source cases.</p>'
if entry not in s:s=s.replace(needle,needle+entry,1)
p.write_text(s)
