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/l78';S=R/'results/l75';rows=json.loads((O/'evaluation.json').read_text())['records'];audits={(r['pair'],r['condition']):r for r in json.loads((O/'target-audit.json').read_text())['records']};conds=['separated','crossing','near','partial'];x=np.arange(4);fig,axes=plt.subplots(1,2,figsize=(10,4))
for ax,split in zip(axes,['development','holdout_source_fields']):
 for dx,model,color in [(-.18,'baseline','#367f70'),(.18,'adapted','#ca7754')]:
  vals=[sum(r['models'][model]['scores']['quality']['30']['visible']['0.5']['matched'] for r in rows if r['split']==split and r['condition']==cond) for cond in conds];ax.bar(x+dx,vals,.36,label=model,color=color)
 ax.set_title('Development' if split=='development' else 'Source-field replay');ax.set_xticks(x,conds,rotation=15);ax.set_ylabel('Top-30 visible matches (4 targets)');ax.set_ylim(0,4.5);ax.legend()
fig.tight_layout();fig.savefig(O/'matched-comparison.png',dpi=140);plt.close(fig);sections=[]
for r in rows:
 a=np.load(S/r['source_archive']);b=np.load(O/r['adapted_archive']);unpack=lambda z:np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);m0=unpack(a);m1=unpack(b);map0={str(i):v for i,v in zip(a['ids'],m0)};map1={str(i):v for i,v in zip(b['ids'],m1)};rgb=Image.open(S/r['source_image']).convert('RGBA');out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Visible synthetic reference',a['refs_visible']),('Original top 30',[map0[k] for k in r['models']['baseline']['rankings']['quality'][:30]]),('Point-trained top 30',[map1[k] for k in r['models']['adapted']['rankings']['quality'][:30]])]):
  tile=rgb.copy()
  for k,mask in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(mask.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"pair-{r['pair']}-{r['condition']}-comparison.png";out.save(O/pic);b0=r['models']['baseline']['scores']['quality']['30']['visible']['0.5']['matched'];b1=r['models']['adapted']['scores']['quality']['30']['visible']['0.5']['matched'];sections.append(f'<section><h3>Pair {r["pair"]} · {html.escape(r["split"])} · {r["condition"]}</h3><p>Top 30 visible matches: baseline {b0}/{r["references"]}, adapted {b1}/{r["references"]}. <a href="/results/l75/{r["source_image"]}">Original composite</a></p><img src="{pic}" alt="Synthetic references and candidate masks from two 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>L78 point-trained segmentation decoder</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/l75/">Earlier fixed synthetic scenes</a><h1>L78: Does training on point prompts improve crossings?</h1><p class="box">This is a small exploratory experiment on previously examined synthetic scenes. Training and evaluation use different image files from the same public archive, but specimen independence is unknown and training source selection was modified after an evaluation-similarity audit. These results do not establish real diatom overlap or human-level performance.</p><p>On the two separate source-field crossing scenes, the point-trained decoder matched 1 of 4 visible shapes in the top 30 versus 0 for the original decoder at IoU ≥0.5. With all kept candidates, it matched 3 versus 2; among all raw point masks, a reference-assisted oracle found 4 versus 2. These are correlated proxy cases and raw-oracle matches are not an automatic review strategy.</p><img src="matched-comparison.png" alt="Bar chart of baseline and adapted visible-reference matches"><p>At the stricter IoU ≥0.75 on those crossings, both matched 0/4 at top 30; all-kept scores were 1/4 original and 0/4 adapted. The two newly matchable raw rear masks improved only from IoUs 0.488 and 0.496 to 0.515 and 0.521. In one scene the raw match was removed by the same-stream IoU 0.8 NMS; in the other its first matching retained candidate ranked 60th. These threshold-adjacent gains need stronger independent testing.</p><p>The model was trained on 64 reference-derived point examples from 24 rendered scenes; image and prompt encoders remained frozen. Evaluation uses the same 256 automatic image-grid points for both decoders, fixed quality/area/NMS filtering and the same candidate budgets. Candidate confidence can be recalibrated by training, so raw-mask availability is reported separately. Baseline cached masks were independently regenerated for the first 12 prompts per scene, not every prompt. Training loss is not accuracy.</p><p>The first training-source selection contained an apparent near duplicate of an evaluation image despite different filenames; it was replaced before training. The revised selection excluded related filename groups and no crop pair had a coarse perceptual-hash distance ≤8, but this is not proof of biological independence. Original RGB sources, background provenance, prompts, checkpoints and all candidate masks are retained. Full-in-frame source silhouettes are synthetic, not observed hidden contours; background labels are incomplete.</p><p><a href="/research/L78.md">Research note</a> · <a href="protocol.json">Training protocol</a> · <a href="training-run.json">Training record</a> · <a href="evaluation-protocol.json">Evaluation protocol</a> · <a href="evaluation.json">All scores and masks</a> · <a href="target-audit.json">Reference-assisted target audit</a> · <a href="initial-source-audit.json">Initial similarity audit</a> · <a href="source-audit.json">Revised similarity audit</a> · <a href="/experiments/checkpoints/l78-point-decoder.README.md">Checkpoint provenance</a></p><h2>Scene comparisons</h2><p>Each colored overlay is a candidate; drawing order can hide overlapping boundaries. The original composite and source masks are available separately.</p>{''.join(sections)}</html>''')
