import json,html
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
import matplotlib;matplotlib.use('Agg')
import matplotlib.pyplot as plt
R=Path(__file__).resolve().parents[1];O=R/'results/r91/synthetic';rows=json.loads((O/'results.json').read_text())['records'];conds=['separated','cross_front0','cross_front1','partial'];fig,axes=plt.subplots(1,2,figsize=(11,4));x=np.arange(4)
for ax,split in zip(axes,['development','source_file_holdout']):
 for off,name,col in [(-.18,'baseline','#367f70'),(.18,'adapted','#ca7754')]:
  vals=[sum(r['models'][name]['scores']['30']['0.5']['matched'] for r in rows if r['split']==split and r['condition']==c) for c in conds];ax.bar(x+off,vals,.36,label=name,color=col)
 ax.set_title('Development' if split=='development' else 'Source-file replay');ax.set_xticks(x,['separated','source 0 front','source 1 front','partial'],rotation=15);ax.set_ylim(0,4.5);ax.set_ylabel('Top-30 visible matches');ax.legend()
fig.tight_layout();fig.savefig(O/'summary.png',dpi=140);plt.close(fig);sections=[]
for r in rows:
 z=np.load(O/r['archive']);shape=tuple(z['mask_shape']);unpack=lambda key:np.unpackbits(z[key])[:int(np.prod(shape))].reshape(shape).astype(bool);a=unpack('baseline_bits');b=unpack('adapted_bits');ids=[f'{x}-{y}' for x,y in z['points'].tolist()];ma=dict(zip(ids,a));mb=dict(zip(ids,b));rgb=Image.open(O/r['image']).convert('RGBA');out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Rendered visible supports',z['refs']),('Original top 30',[ma[k] for k in r['models']['baseline']['ranking'][:30]]),('Point-trained top 30',[mb[k] for k in r['models']['adapted']['ranking'][:30]])]):
  tile=rgb.copy()
  for k,m in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((350,350)),(j*360+5,35));draw.text((j*360+5,10),title,fill='#203a38')
 pic=r['image'].replace('.png','-comparison.png');out.save(O/pic);b0=r['models']['baseline']['scores']['30']['0.5']['matched'];b1=r['models']['adapted']['scores']['30']['0.5']['matched'];sections.append(f'<section><h3>Pair {r["pair"]} · {html.escape(r["split"])} · {r["condition"]}</h3><p>Visible source targets {len(r["included_targets"])}; top-30 IoU ≥0.5 matches original {b0}, adapted {b1}. <a href="{r["image"]}">Source composite</a></p><img src="{pic}" alt="Rendered references and candidate masks"></section>')
(O/'index.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R91 new-cutout synthetic replay</title><style>body{{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}}img{{max-width:100%}}a{{color:#006b59}}.box{{background:#fff2d6;padding:1em}}section{{border-top:1px solid #ccc}}</style><a href="/results/r91/">R91 real-image comparison</a> · <a href="/results/board.html">Research board</a><h1>R91: New-cutout synthetic crossings and partials</h1><p class="box">Exploratory follow-up selected after the real-image results. Sixteen opaque composites use eight new file IDs and four new crop locations on previously studied Academy slides. Source-file separation and coarse similarity screening do not establish biological independence. The rendering is not a microscope optical model.</p><p>On the two source-file replay pairs, both decoders matched 3/4 visible targets when source 0 was in front and 2/4 when source 1 was in front at top 30 and IoU ≥0.5. At IoU ≥0.75, they matched 2/4 versus 3/4 when source 0 was in front, and 2/4 each in the other order. These are small correlated proxy cases and do not establish generalization.</p><img src="summary.png" alt="Top-30 visible-support matches across synthetic conditions"><p>Both models use the same 256 unlabelled point prompts, eligibility filters and IoU 0.8 NMS. The back reference is its rendered visible support outside the front source; objects with fewer than 50 visible pixels are excluded and recorded. Full source silhouettes and original public RGB files are preserved separately. Masks of unannotated background objects are not confirmed false positives.</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. These composite outputs are noncommercial derivatives under the same license; local Academy background conditions also apply.</p><p><a href="protocol.json">Frozen follow-up protocol</a> · <a href="results.json">All scores, masks and provenance</a> · <a href="/research/r91_synthetic_verify.py">Replay verifier</a> · <a href="/research/R91.md">Research note</a></p><h2>Scene comparisons</h2>{''.join(sections)}</html>''')
