"""Publish area-change review queue for gated source-mask candidates."""
import html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import sha256
R=Path(__file__).resolve().parents[1];O=R/'results/r112/gated-mask-risk-audit';r=json.loads((O/'results.json').read_text());E=html.escape;rows=r['placements'];rank=sorted(rows,key=lambda x:(-x['in_frame_area_ratio'],x['family'],x['scene_id'],x['instance_index']));chosen=[];seen=set()
for x in rank:
 k=(x['source_pool'],x['annotation_id'])
 if k not in seen:seen.add(k);chosen.append(x)
 if len(chosen)==20:break
for i in range(8):
 x=rows[round(i*(len(rows)-1)/7)];k=(x['source_pool'],x['annotation_id'])
 if k not in seen:seen.add(k);chosen.append(x)
(O/'overlays').mkdir(exist_ok=True);cards=[]
for x in chosen:
 record=json.loads((R/x['proposal_record_path']).read_text());root=(R/x['proposal_record_path']).parent.parent;source=np.asarray(Image.open(R/x['source_crop_path']).convert('RGB'));views=[]
 for name,k,col in [('Center source mask','center',(255,95,50)),('Gated source mask',x['selected_proposal'],(50,185,255))]:
  spec=record['masks'][k];path=root/spec['file'];assert sha256(path)==spec['sha256'];mask=np.asarray(Image.open(path).convert('L'))>0;rgb=source.astype(np.float32);rgb[mask]=.7*rgb[mask]+.3*np.array(col,np.float32);edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;rgb[edge]=col;out=O/'overlays'/f"{x['source_pool']}-{x['annotation_id']}-{k}.png";Image.fromarray(np.rint(rgb).clip(0,255).astype('uint8')).save(out);views.append((name,'/'+str(out.relative_to(R))))
 views+=[('Center scene','/'+x['original_image_path']),('Gated scene','/'+x['candidate_image_path'])];cards.append('<article><h3>'+E(x['source_name'])+' · '+E(x['annotation_id'])+'</h3><p>'+E(x['family'])+' · '+E(x['scene_id'])+' · center → '+E(x['selected_proposal'])+' · projected area '+str(x['center_in_frame_area_px'])+' → '+str(x['selected_in_frame_area_px'])+' pixels ('+f"{x['in_frame_area_ratio']:.1f}"+'×) · source coverage '+f"{100*x['center_source_coverage']:.1f}% → {100*x['selected_source_coverage']:.1f}%"+'</p><div class="views">'+''.join('<figure><a href="'+E(path)+'"><img loading="lazy" src="'+E(path)+'" alt="'+E(name)+'"></a><figcaption>'+E(name)+'</figcaption></figure>' for name,path in views)+'</div><p><a href="/'+E(x['source_crop_path'])+'">Original source crop</a></p></article>')
s=r['summary'];page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Gated source-mask risk audit</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:#fff3d8;border-left:5px solid #b88418;padding:15px}article{background:white;border:1px solid #cbd8d1;padding:12px;margin:14px 0}.views{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}figure{margin:0}.views img{width:100%;height:220px;object-fit:contain;background:#e8eee8}figcaption{font-size:.85rem}table{border-collapse:collapse;background:white}td,th{border:1px solid #cbd8d1;padding:8px;text-align:left}@media(max-width:700px){.views{grid-template-columns:repeat(2,minmax(0,1fr))}}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/gated-alternative-scenes/">Gated candidate fields</a> · <a href="/results/r115/">Small proxy replay</a></nav><h1>Gated mask area review</h1><p class="notice"><strong>Do not automatically promote this gated rule.</strong> Some visibly selected masks cover large rectangular or background-like regions. Agreement between the model's prompts can favor the wrong object or background. Neither the center nor gated mask is verified anatomy, and the synthetic image is not expert-reviewed ground truth.</p><p>The gated renderer changed '''+str(s['noncenter_placements'])+''' placements, representing '''+str(s['distinct_changed_sources'])+''' unique source crops. Of those sources, '''+str(s['selected_source_coverage_gt_0_75'])+''' selected masks cover over 75% of the source crop and '''+str(s['selected_source_coverage_gt_0_90'])+''' cover over 90%; '''+str(s['selected_gt_0_75_center_le_0_75'])+''' crossed from at most 75% for center to over 75% for gated. In the generated fields, '''+str(s['placements_with_inframe_area_gt_5x'])+''' of the '''+str(s['noncenter_placements'])+''' changed placements have a projected area more than five times the center support; '''+str(s['placements_with_inframe_area_gt_10x'])+''' exceed ten times.</p><p>These thresholds are descriptive review cues, not rules for accepting or rejecting masks. Real specimens can fill a crop, and a large ratio can reflect a nearly empty center proposal. The concrete failure is that some selected masks visibly encompass background or rectangular regions; stronger comparison and specialist review are required. The candidate images and original scenes remain separate.</p><p><a href="results.json">All source and placement measurements</a> · <a href="verify.json">Checks</a> · <a href="/results/r112/gated-alternative-scenes/">Candidate scene data and paired reader</a></p><p><a href="/results/r112/gated-risk-review/">Review all 366 changed source-mask triads and export feedback</a>. The largest selected masks are shown first for review, not presumed incorrect.</p><h2>Selected cases</h2><p>The first 20 are the largest projected area ratios with at most one example per source; up to eight evenly spaced references were added. This is a deliberately extreme review queue, not an estimate of biological error rate. Scene pairs may contain other changed insertions.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'area-risk comparisons')
