"""Publish all separated-support development fields and source instances."""
import html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/scaleup-separated-scenes';m=json.loads((O/'manifest.json').read_text());v=json.loads((O/'verify.json').read_text());E=html.escape;(O/'overlays').mkdir(exist_ok=True);cards=[]
for i,r in enumerate(m['records']):
 if i<24:
  with np.load(O/r['mask_archive'],allow_pickle=False) as z:
   n=len(r['instances']);ms=np.unpackbits(z['support_bits'],count=n*768*768).reshape(n,768,768).astype('uint8')
  im=Image.open(O/r['image']).convert('RGB');d=ImageDraw.Draw(im);colors=['#ff5757','#57cfff','#e0e75b']
  for j,mask in enumerate(ms):
   contours,_=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
   for contour in contours:
    points=[tuple(int(x) for x in point[0]) for point in contour]
    if len(points)>1:d.line(points+[points[0]],fill=colors[j],width=2)
   ys,xs=np.nonzero(mask)
   if len(xs):d.text((int(np.median(xs)),int(np.median(ys))),str(j+1),fill=colors[j],stroke_width=1,stroke_fill='black')
  im.save(O/'overlays'/f"{r['id']}.png")
 partial=sum(x['in_frame_fraction']<1 for x in r['instances']);names=''.join('<li><a href="/results/r112/species-scaleup/images/'+E(x['annotation_id'])+'.png">'+E(x['source_name'])+' · '+E(x['annotation_id'])+'</a> · projected '+str(x['in_frame_support_pixels'])+' pixels'+(' · partial' if x['in_frame_fraction']<1 else '')+' · '+E(x['mask_triage'])+'</li>' for x in r['instances']);overlay=('<a href="overlays/'+E(r['id'])+'.png"><img loading="lazy" src="overlays/'+E(r['id'])+'.png" alt="Numbered unverified projected support outlines"></a>' if i<24 else '');cards.append('<article><h3>'+E(r['id'])+'</h3><p>'+str(len(r['instances']))+' insertions · '+str(partial)+' partial projected supports · zero inserted-support intersections</p><div class="images"><a href="'+E(r['image'])+'"><img loading="lazy" src="'+E(r['image'])+'" alt="Generated grayscale field"></a>'+overlay+'</div><details><summary>Source instances and support archive</summary><ol>'+names+'</ol><p><a href="'+E(r['mask_archive'])+'">Download support archive</a></p></details></article>')
c=v['counts'];page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Separated-support development scenes</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1250px;margin:auto;padding:24px}a{color:#076c59}.notice{background:#fff8df;border-left:5px solid #b88418;padding:15px}article{background:white;border:1px solid #cbd8d1;padding:12px;margin:14px 0}.images{display:flex;flex-wrap:wrap;gap:10px}.images img{width:min(100%,450px);height:auto;background:#eee}li{padding:2px}pre{overflow:auto;background:#e6eee8;padding:12px}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/scaleup-crowded-scenes/">Crowded scenes</a></nav><h1>Separated-support development scenes</h1><p class="notice"><strong>Separated insertions do not mean empty backgrounds.</strong> The Academy fields can contain unlabeled diatoms and other material, including overlapping the inserted specimens. The backgrounds are unknown everywhere. Projected masks are unverified model proposals, not confirmed instance anatomy, and source names have not been independently reconciled with Academy taxonomy.</p><p>192 grayscale fields contain one, two or three inserted source crops, with their projected masks constrained to have no mutual intersections. The 384 distinct training crops cover 80 source-name strings, four or five per name. Every crop and all Academy background locations were used in prior development, so these fields complement the crowded set but are not an independent validation set. Some edge placements are partial.</p><p>The renderer uses grayscale transmission-style blending and nominal source scale with recorded Academy XY scale; it is not a validated microscope optical model or focus stack. Automated checks found no pairwise intersections among inserted supports and '''+str(c['partial_support'])+''' partial supports. They do not test overlap with real background organisms or establish visibility.</p><p><a href="protocol.json">Fixed recipe</a> · <a href="manifest.json">Scene and source provenance</a> · <a href="verify.json">Verification</a> · <a href="/diatom_pilot/scaleup_crowded_dataset.py">Python readers</a></p><pre>from diatom_pilot.scaleup_crowded_dataset import ScaleupSeparatedDataset
scenes = ScaleupSeparatedDataset("development_training")
example = scenes[0]  # image, projected_weak_supports, unknown background</pre><p><a href="/results/r112/instance-contribution-audit/">Inspect per-instance rendered-pixel contribution diagnostics</a>; these do not measure biological visibility.</p><p><a href="/results/r112/projected-mask-uncertainty/">Compare the three projected mask proposals</a>; same-model agreement is not validated anatomy.</p><h2>All scenes</h2><p>The first 24 include numbered outlines of unverified projected supports. Click any image for native pixels and expand a field for its source list.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'scenes and 24 support overlays')
