import json,html,statistics
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';rows=json.loads((O/'results.json').read_text())['records'];audit=json.loads((O/'quality-audit.json').read_text());fig,ax=plt.subplots(figsize=(7,4));x=np.arange(2)
for off,name,col in [(-.18,'baseline','#367f70'),(.18,'adapted','#ca7754')]:ax.bar(x+off,[sum(r['models'][name]['scores']['30'][t]['matched'] for r in rows) for t in ('0.5','0.75')],.36,label=name,color=col)
ax.set_xticks(x,['IoU ≥0.5','IoU ≥0.75']);ax.set_ylim(0,16);ax.set_ylabel('Matched structural source regions');ax.set_title('New Gündüz file IDs · top 30 per image');ax.legend();fig.tight_layout();fig.savefig(O/'matched-comparison.png',dpi=140);plt.close(fig);sections=[]
for row in rows:
 z=np.load(O/row['archive']);shape=tuple(z['mask_shape']);unpack=lambda key:np.unpackbits(z[key])[:int(np.prod(shape))].reshape(shape).astype(bool);m0=unpack('baseline_bits');m1=unpack('adapted_bits');ids=[f'{x}-{y}' for x,y in z['points'].tolist()];d0=dict(zip(ids,m0));d1=dict(zip(ids,m1));rgb=Image.new('RGBA',(512,512),'black');rgb.paste(Image.open(R/row['source_image']).convert('RGB').resize((512,384),Image.Resampling.LANCZOS),(0,64));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,masks) in enumerate([('Structural source regions',z['refs']),('Original top 30',[d0[k] for k in row['models']['baseline']['ranking'][:30]]),('Point-trained top 30',[d1[k] for k in row['models']['adapted']['ranking'][:30]])]):
  tile=rgb.copy()
  for k,m in enumerate(masks):
   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=f'{row["id"]}-comparison.png';out.save(O/pic);sections.append(f'<section><h3>Source file {html.escape(row["id"])}</h3><p>Structural source regions: {row["references"]}. Original/adapted top-30 matches: {row["models"]["baseline"]["scores"]["30"]["0.5"]["matched"]} / {row["models"]["adapted"]["scores"]["30"]["0.5"]["matched"]}. <a href="/{html.escape(row["source_image"])}">Original image</a></p><img src="{pic}" alt="Source regions and candidate masks from both decoders"></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 separate-source decoder test</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/board.html">Research board</a> · <a href="/results/l78/">Point-decoder development</a><h1>R91: Do the point-trained masks transfer to new source files?</h1><p class="box">Eleven newly selected public Gündüz image files; this dataset differs from the decoder-training archive, but was studied in prior research. File IDs and coarse similarity screens do not establish independent biological specimens or base-model training independence. Intersecting boxes were excluded, so this is not a heavy-overlap test.</p><p>Both decoders matched 11 of 16 structurally derived source regions at IoU ≥0.5 and also 11/16 at IoU ≥0.75, with up to 30 reviewed masks per image. All raw masks and eligible masks had the same aggregate match counts. The original stream kept 88 candidates and the adapted stream kept 83; this is candidate burden, not a false-positive count.</p><img src="matched-comparison.png" alt="Source-region matched counts for original and adapted decoders"><p>The 32 image IDs were sampled before annotation inspection; the first 12 whose binary components had a strict one-to-one correspondence to nonintersecting source boxes were selected before image download. One selected file was quarantined without replacement after its crop was unusually similar to a training crop under the predeclared perceptual screen. Eleven were evaluated. The binary-component mapping is structural evidence, not expert confirmation of individual boundaries; annotation completeness is unknown.</p><p>Original and adapted decoders receive the same 64 automatic point queries on an isotropically downsampled 512×384 source inside a padded 512×512 canvas. Both use quality ≥0.6, area 300–50,000 and mask IoU 0.8 NMS. Raw model masks, scores, eligibility and links are retained. A reference-assisted <a href="quality-audit.json">best-mask quality audit</a> is a biased diagnostic, not unbiased confidence calibration, since candidate references can be incomplete and the best mask is selected using the answer.</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. These overlays are noncommercial derivatives under the same license. <a href="protocol.json">Frozen protocol</a> · <a href="metadata-audit.json">Metadata audit</a> · <a href="leak-screen.json">Leak screening and quarantine</a> · <a href="results.json">All scores, ranks and masks</a> · <a href="/research/r91_verify.py">Replay verifier</a> · <a href="/research/R91.md">Research note</a>.</p><p>The <a href="synthetic/">separate exploratory synthetic crossing follow-up</a> is being prepared after the real-image results; its source pairs and backgrounds are fixed in its own protocol.</p><h2>Field comparisons</h2>{''.join(sections)}</html>''')
