"""Publish all rare-name development scenes and projected supports."""
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/breadth-diverse-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<21:
  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','#e579f0','#71ef95','#ffa844','#f2a9cc','#b1a1ff','#ffffff','#ff9595','#67ceba','#faedac','#eabaff','#87d4ff']
  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'] is not None and x['in_frame_fraction']<1 for x in r['instances']);names=''.join('<li><a href="/results/r112/species-breadth/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'] is not None and 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 projected support outlines"></a>' if i<21 else '');cards.append('<article><h3>'+E(r['id'])+'</h3><p>'+E(r['mode'])+' · '+str(len(r['instances']))+' insertions · '+str(r['support_overlap_pairs'])+' intersecting support pairs · '+str(partial)+' partial supports</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>Sources 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>Additional source-name 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/species-breadth/">Additional source pool</a></nav><h1>Additional source-name scenes</h1><p class="notice"><strong>Weak development data, not verified training labels.</strong> All source names are public-dataset labels, not independently reconciled with Academy taxonomy. Masks are unverified model proposals, backgrounds may contain real unlabeled diatoms even under insertions, and separate projected supports do not establish biological visibility or hidden anatomy. Source crops may contain neighbors.</p><p>98 grayscale fields use all 784 additional source crops from prior training-location components, covering 137 source-name strings and 55 genera. Fields contain 2–14 inserted sources at varied sizes, rotations, opacity, contrast and locations. Fourteen two-insertion fields constrain the generated supports not to intersect; the rest use spread or clustered placement. The source components were selected from earlier training groups only, but the broader source pool has exposed the earlier tuning and check groups. Neither these fields nor that older split is an independent final benchmark.</p><p>Geometry checks found '''+str(c['scenes_with_overlap'])+''' fields with intersecting projected supports, '''+str(c['overlap_pairs'])+''' intersecting support pairs and '''+str(c['partial_support'])+''' partial supports. These counts characterize rendering, not model performance. The Academy backgrounds and public specimens are reused development data; the blending is an approximate single-plane proxy, not verified microscope optics.</p><p><a href="protocol.json">Frozen recipe</a> · <a href="manifest.json">Scene and source provenance</a> · <a href="verify.json">Verification</a> · <a href="/results/r112/species-breadth/prior-split-exposure.json">Prior split exposure</a> · <a href="/diatom_pilot/scaleup_crowded_dataset.py">Python scene readers</a></p><pre>from diatom_pilot.scaleup_crowded_dataset import BreadthDiverseSceneDataset
scenes = BreadthDiverseSceneDataset("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 21 include numbered projected-support outlines. Click images for native pixels; expand the source list for links to original crops.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'fields and 21 overlays')
