"""Publish paired development candidate fields and outline differences."""
import html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/gated-alternative-scenes';m=json.loads((O/'manifest.json').read_text());E=html.escape;changed=[x for x in m['records'] if x['changed_proposal_indices']];rank=sorted(changed,key=lambda x:(-x['changed_image_pixels'],x['family'],x['id']))[:24];refs=[changed[round(i*(len(changed)-1)/7)] for i in range(8)];selected=[];seen=set()
for x in rank+refs:
 k=(x['family'],x['id'])
 if k not in seen:seen.add(k);selected.append(x)
(O/'overlays').mkdir(exist_ok=True);cards=[]
for x in selected:
 j=x['changed_proposal_indices'][0];n=len(x['instances']);item=x['instances'][j];src=np.asarray(Image.open(R/x['original_image_path']).convert('RGB'));dst=np.asarray(Image.open(O/x['image']).convert('RGB'));arrays=[]
 for f in (R/x['original_mask_archive_path'],O/x['mask_archive']):
  with np.load(f,allow_pickle=False) as z:arrays.append(np.unpackbits(z['support_bits'],count=n*768*768).reshape(n,768,768)[j].astype(bool))
 views=[]
 for kind,img,mask,color in [('center',src,arrays[0],(255,95,50)),('gated',dst,arrays[1],(50,190,255))]:
  overlay=img.copy();edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;overlay[edge]=color;path=O/'overlays'/f"{x['family']}-{x['id']}-{kind}.png";Image.fromarray(overlay).save(path);views.append((kind,path))
 cards.append('<article><h3>'+E(x['family'])+' · '+E(x['id'])+'</h3><p>'+str(len(x['changed_proposal_indices']))+' changed proposal choices · '+str(x['changed_image_pixels'])+' changed scene pixels · original / gated intersecting-support pairs '+str(x['original_support_overlap_pairs'])+' / '+str(x['support_overlap_pairs'])+'</p><p>First changed insertion: '+E(item['source_name'])+' · '+E(item['annotation_id'])+' · center → '+E(item['selected_proposal'])+' · projected area '+str(item['center_in_frame_support_pixels'])+' → '+str(item['in_frame_support_pixels'])+' pixels. Other insertions in this field can also change.</p><div class="views">'+''.join('<figure><a href="/'+E(str(path.relative_to(R)))+'"><img loading="lazy" src="/'+E(str(path.relative_to(R)))+'" alt="'+E(kind)+' scene with one projected outline"></a><figcaption>'+('Original center mask' if kind=='center' else 'Gated candidate mask')+'</figcaption></figure>' for kind,path in views)+'</div><p><a href="/'+E(x['original_image_path'])+'">Original field</a> · <a href="'+E(x['image'])+'">Candidate field</a></p></article>')
table=''
for family in ('crowded','separated','breadth','all'):
 s=m['summary'][family];table+='<tr><th>'+E(family.title())+'</th><td>'+str(s['scenes'])+'</td><td>'+str(s['instances'])+'</td><td>'+str(s['gated_noncenter_instances'])+'</td><td>'+str(s['scenes_with_changed_pixels'])+'</td><td>'+str(s['baseline_overlap_pairs'])+' → '+str(s['gated_overlap_pairs'])+'</td></tr>'
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Experimental gated-mask 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}.views{display:flex;gap:10px;flex-wrap:wrap}figure{margin:0}.views img{width:min(100%,440px);height:auto;background:#e8eee8}figcaption{font-size:.85rem}table{border-collapse:collapse;background:white;max-width:100%;display:block;overflow:auto}td,th{border:1px solid #cbd8d1;padding:8px;text-align:left}pre{overflow:auto;background:#e6eee8;padding:12px}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r115/">Different-source mask-choice study</a></nav><h1>Experimental gated-mask scene variants</h1><p class="notice"><strong>Research candidates, not approved labels.</strong> The rule was promising on two small, reference-assisted proxy comparisons, but source masks, species names and optical blending remain unverified. A model can agree on the wrong object. Academy backgrounds can contain unlabeled organisms everywhere, including under insertions. The existing center-mask scenes are preserved unchanged.</p><p>Each of 573 existing development fields was rendered again using the same source pixels, background, positions, scale, opacity and contrast. If source-mask geometry was flagged for inspection, the proposal that agrees most with the other two was selected; otherwise the center proposal was kept. The original center-mask-derived source-background median was held constant. The image and all projected supports were recomputed, rather than simply relabeling the original pixels.</p><table><tr><th>Source set</th><th>Fields</th><th>Insertions</th><th>Non-center choices</th><th>Fields with changed pixels</th><th>Intersecting support pairs, center → gated</th></tr>'''+table+'''</table><p class="notice"><strong>Area-risk finding:</strong> some gated alternatives visibly cover rectangular or background-like regions. Among 366 unique changed sources, 126 selected masks cover over 75% of the crop; 40 of 409 changed placements grow more than fivefold in projected area. Coverage alone is not an error label, but the visual failures rule out automatic promotion. <a href="/results/r112/gated-mask-risk-audit/">Inspect the risk audit and examples</a>. <a href="/results/r112/gated-risk-review/">Review all 366 changed source masks</a>.</p><p>The 192 fields originally designed to have separated inserted supports now have one intersecting support pair under the gated proposals. These pair counts describe projected masks, not biological overlap or quality. Unchanged scenes remain exact copies by design. The variant is paired with the original, not a source-independent new sample or a validated training improvement.</p><p><a href="protocol.json">Frozen recipe</a> · <a href="manifest.json">All scene records and choices</a> · <a href="verify.json">Verification</a> · <a href="/diatom_pilot/gated_scene_dataset.py">Paired candidate reader</a></p><pre>from diatom_pilot.gated_scene_dataset import GatedCandidateScenes
scenes = GatedCandidateScenes("development_candidate", family="all")
example = scenes[0]  # candidate and original images plus separate weak supports</pre><h2>Paired examples</h2><p>Showing the 24 fields with the most changed image pixels and eight evenly spaced changed-field references, with duplicates removed. These cases are selected to illustrate change, not represent performance. Only the first changed instance per field is outlined; several may have changed.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'paired fields from',len(changed),'changed fields')
