"""Visualize the local split while explaining its limitations."""
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/grouped-synthetic';m=json.loads((O/'manifest.json').read_text());v=json.loads((O/'verify.json').read_text());split=json.loads((O/'split.json').read_text());screen=json.loads((O/'similarity-screen.json').read_text());sections=[]
for partition in ('train','validation'):
 records=[x for x in m['records'] if x['synthetic_partition']==partition];cards=[]
 for r in records[:12]:
  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,mask in enumerate(masks):
   contours,_=cv2.findContours(mask.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(annotated,contours,-1,0,4);cv2.drawContours(annotated,contours,-1,255,2)
  pane=Image.new('L',(780,420),255);d=ImageDraw.Draw(pane);d.text((5,5),'Synthetic image',fill=30);d.text((395,5),'Unverified projected supports',fill=30);pane.paste(Image.fromarray(im).resize((380,380)),(5,30));pane.paste(Image.fromarray(annotated).resize((380,380)),(395,30));fn=r['id']+'-comparison.jpg';pane.save(O/fn,quality=88);labels=', '.join(html.escape(x['source_species']) for x in r['instances']);cards.append('<article><h3>'+html.escape(r['id'])+'</h3><p>Source-name strings: '+labels+'. Overlapping support pairs: '+str(r['overlap_pairs'])+'.</p><a href="'+fn+'"><img loading="lazy" src="'+fn+'" alt="Synthetic image alongside projected supports"></a><p><a href="'+html.escape(r['image'])+'">Full image</a> · <a href="'+html.escape(r['mask_archive'])+'">Support archive</a></p></article>')
 sections.append('<h2>'+('Training' if partition=='train' else 'Comparison')+' examples</h2><p>First 12 recipes in this local partition, selected by order.</p>'+''.join(cards))
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Group-separated synthetic development 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}.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}table{border-collapse:collapse;background:white}td,th{border:1px solid #cddbd2;padding:8px;text-align:left}pre{overflow:auto;background:#edf3ef;padding:12px}</style><main><nav><a href="/results/r112/">Synthetic training</a></nav><h1>Group-separated synthetic development comparison</h1><p class="notice"><strong>Updated location audit:</strong> The UDE sampling supplement links source slides to collection information. A conservative site-code/coordinate grouping is shared across the local training and comparison partitions for 124 of 240 comparison placements. This does not prove duplicate specimens, but the comparison is not location-independent. <a href="/results/r112/ude-sampling-metadata/">See the audit</a>.</p><p><strong>Comparison partition consumed:</strong> these scenes have now been used for the <a href="/results/r112/grouped-baseline/">automatic segmentation baseline</a>; they are no longer unused for model development.</p><p class="notice"><strong>Development control, not an independent biological test.</strong> The source crops, Academy slides and backgrounds were used earlier. Source slide names and Academy slide filenames do not establish different biological samples. Source names and masks are unverified; the background may contain additional diatoms, and no background pixel is a confirmed negative.</p><p>The recipes separate source crop IDs, canonical source filename groups and Academy slide names across two local partitions. A predeclared DCT screen found '''+str(len(screen['flags']))+''' possible duplicate pairs across source partitions at its threshold; it can miss related images. The comparison scenes include only source-name strings present on both sides. Synonyms and morphotype names remain unresolved.</p><table><tr><th>Local partition</th><th>Scenes / placements</th><th>Source images used</th><th>Source filename groups</th><th>Academy slides</th><th>Source-name strings</th></tr><tr><th>Train</th><td>144 / 720</td><td>'''+str(v['source_ids']['train'])+'''</td><td>'''+str(v['source_filename_groups']['train'])+'''</td><td>6</td><td>62</td></tr><tr><th>Comparison</th><td>48 / 240</td><td>'''+str(v['source_ids']['validation'])+'''</td><td>'''+str(v['source_filename_groups']['validation'])+'''</td><td>2</td><td>49</td></tr></table><p>There are '''+str(v['clipped_placements']['train'])+''' / '''+str(v['clipped_placements']['validation'])+''' clipped weak supports and '''+str(v['overlap_pairs']['train'])+''' / '''+str(v['overlap_pairs']['validation'])+''' pairs of overlapping weak supports, respectively. Overlap of projected masks does not prove two visible biological objects or optical realism. Adjacent focus-plane backgrounds from the same location remain on the same side, but pasted 2-D sources do not model their own focus changes.</p><p>The reader requires choosing a partition explicitly and rejects ungrouped manifests when a partition is requested:</p><pre>from pathlib import Path
from diatom_pilot.weak_scene_dataset import WeakSceneDataset
manifest = Path("results/r112/grouped-synthetic/manifest.json")
train = WeakSceneDataset([manifest], synthetic_partition="train")
comparison = WeakSceneDataset([manifest], synthetic_partition="validation")</pre><p><a href="split.json">Source/background group split</a> · <a href="screen-protocol.json">Similarity screen protocol</a> · <a href="similarity-screen.json">Screen results</a> · <a href="scene-protocol.json">Frozen recipes</a> · <a href="manifest.json">All images and supports</a> · <a href="verify.json">Reconstruction and split verification</a> · <a href="reader-check.json">Reader checks</a></p>'''+''.join(sections)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(m['records']),'scenes')
