"""Visualize every weak-label scene and its uncertain 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/weak-breadth-depth-v1';p=json.loads((O/'manifest.json').read_text());sections=[]
for r in p['records']:
 im=np.asarray(Image.open(O/r['image']).convert('L'));z=np.load(O/r['mask_archive']);shape=tuple(z['support_shape']);masks=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);annotated=im.copy()
 for j,m in enumerate(masks):
  contours,_=cv2.findContours(m.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(annotated,contours,-1,0,4);cv2.drawContours(annotated,contours,-1,255,2)
  ys,xs=np.where(m)
  if len(xs):cv2.putText(annotated,str(j+1),(int(np.median(xs)),int(np.median(ys))),cv2.FONT_HERSHEY_SIMPLEX,.6,0,3,cv2.LINE_AA);cv2.putText(annotated,str(j+1),(int(np.median(xs)),int(np.median(ys))),cv2.FONT_HERSHEY_SIMPLEX,.6,255,1,cv2.LINE_AA)
 pane=Image.new('L',(780,420),'white');d=ImageDraw.Draw(pane);pane.paste(Image.fromarray(im).resize((380,380),Image.Resampling.LANCZOS),(5,30));pane.paste(Image.fromarray(annotated).resize((380,380),Image.Resampling.LANCZOS),(395,30));d.text((8,6),'Synthetic image',fill=30);d.text((398,6),'Unverified projected supports',fill=30);fn=r['id']+'-comparison.jpg';pane.save(O/fn,quality=88);labels=', '.join(html.escape(x['source_species']) for x in r['instances']);sections.append(f'<article><h3>{html.escape(r["id"])} · {len(r["instances"])} inserted candidates</h3><p>Source labels (unverified): {labels}. Overlapping support pairs: {r["overlap_pairs"]}.</p><a href="{fn}"><img loading="lazy" src="{fn}" alt="Synthetic scene and outlined unverified supports"></a><p><a href="{r["image"]}">Grayscale image</a> · <a href="{r["mask_archive"]}">Overlapping support archive</a></p></article>')
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Weak-label synthetic scenes</title><style>body{font:16px/1.55 system-ui;background:#f4f6f0;color:#193b37;margin:0}main{max-width:1050px;margin:auto;padding:24px}a{color:#096c58}h1,h2,h3{font-family:Georgia,serif}.notice,article{background:white;border:1px solid #cddbd2;padding:16px;margin:14px 0}.notice{border-left:5px solid #bc851b}img{max-width:100%;height:auto}</style><body><main><nav><a href="/results/r112/">Synthetic training project</a> · <a href="/results/r112/breadth-depth/mask-hypotheses/">Source mask hypotheses</a></nav><h1>Weak-label development scenes</h1><p class="notice"><strong>Not validated training data or an evaluation set.</strong> The inserted outlines come from unverified model-predicted masks, source species are unverified dataset names, and original Academy backgrounds can contain diatoms. Transparent visibility is undefined; the entire original background must remain unknown, not be treated as confirmed negative.</p><p>These 160 grayscale scenes reuse 112 source crops across 20 source-named species and eight Academy backgrounds. Each class has 40 placements; placements are not independent specimens. The labels are development hypotheses, not verified specimens. Source 0.09 µm/pixel was mapped to each background's OME XY calibration, then each cutout was rotated and blended through a deliberately simple additive proxy. The renderer is not an optical microscope simulation; many added structures are faint or hard to see, and matching pixel scale does not guarantee diagnostic detail.</p><p>The right-hand view draws outlines of all separate projected supports; overlapping outlines and unknown background structures are not verified biological segmentation. Low visibility, clipping, artifacts and domain mismatch require further work before training.</p><p><a href="protocol.json">Frozen construction protocol</a> · <a href="manifest.json">Source, calibration and all scene recipes</a> · <a href="verify.log">Reconstruction checks</a> · <a href="/research/R112_DESIGN.md">Research note</a></p>'''+''.join(sections)+'''</main></body></html>''')
print('Rendered',len(sections),'scenes.')
