"""Publish all paired baseline/adapted weak-support comparisons."""
import collections,html,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];D=R/'results/r112/grouped-synthetic';B=R/'results/r112/grouped-baseline';O=R/'results/r112/decoder-adaptation';ev=json.loads((O/'evaluation.json').read_text());train=json.loads((O/'training-run.json').read_text());retro=json.loads((O/'retrospective.json').read_text());old={x['scene_id']:x for x in json.loads((B/'results.json').read_text())['records']};scenes={x['id']:x for x in json.loads((D/'manifest.json').read_text())['records']};e=html.escape;models=('baseline','adapted');names={'baseline':'Original MobileSAM','adapted':'Adapted decoder'};summary={}
for name in models:
 summary[name]={'candidate_count':sum(x[name]['candidate_count'] for x in ev['records']),'budgets':{}}
 for budget in ('10','30','60','all'):
  summary[name]['budgets'][budget]={}
  for metric in ('main_0.5','main_0.75','nonempty_0.5','nonempty_0.75'):
   values=[x[name]['budgets'][budget]['matches'][metric] for x in ev['records']];keys=values[0]['strata'];summary[name]['budgets'][budget][metric]={'matched':sum(v['matched'] for v in values),'references':sum(v['references'] for v in values),'strata':{k:{kk:sum(v['strata'][k][kk] for v in values) for kk in ('matched','references')} for k in keys}}
(O/'summary.json').write_text(json.dumps({'format':'r112-decoder-summary-v1','evaluation_sha256':__import__('hashlib').sha256((O/'evaluation.json').read_bytes()).hexdigest(),'models':summary,'warning':ev['warning']},indent=2)+'\n')
table=''
for name in models:
 a=summary[name]['budgets']['30']['main_0.5'];b=summary[name]['budgets']['30']['main_0.75'];c=summary[name]['budgets']['all']['main_0.5'];table+='<tr><th>'+names[name]+'</th><td>'+str(a['matched'])+'/'+str(a['references'])+'</td><td>'+str(b['matched'])+'/'+str(b['references'])+'</td><td>'+str(c['matched'])+'/'+str(c['references'])+'</td><td>'+str(summary[name]['candidate_count'])+'</td></tr>'
sub=''
for key,label in [('overlap_at_512','Support overlaps another'),('weak_support_in_frame_lt_095','Under 95% of weak support in frame'),('weak_support_in_frame_lt_050','Under 50% of weak support in frame')]:
 vals=[summary[n]['budgets']['30']['main_0.5']['strata'][key] for n in models];sub+='<tr><th>'+e(label)+'</th>'+''.join('<td>'+str(v['matched'])+'/'+str(v['references'])+'</td>' for v in vals)+'</tr>'
ret=''
for n in models:
 x=retro['summary'][n];ret+='<tr><th>'+names[n]+'</th>'+''.join('<td>'+str(x[k])+'/'+str(x['reference_count'])+'</td>' for k in ('raw_oracle_matches','eligible_oracle_matches','kept_oracle_matches','top30_matches'))+'</tr>'
boards=[]
for row in ev['records']:
 oldrow=old[row['scene_id']];scene=scenes[row['scene_id']];b=np.load(B/oldrow['archive']);shape=tuple(b['mask_shape']);baseline=np.unpackbits(b['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);rs=tuple(b['reference_shape']);refs=np.unpackbits(b['reference_bits'])[:np.prod(rs)].reshape(rs).astype(bool);a=np.load(O/row['adapted_archive']);shape=tuple(a['mask_shape']);adapted=np.unpackbits(a['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);im=np.asarray(Image.open(D/scene['image']).convert('L').resize((512,512),Image.Resampling.LANCZOS));base=cv2.cvtColor(im,cv2.COLOR_GRAY2RGB);views=[('Scene',base.copy()),('Weak projected supports',base.copy())]
 def outline(v,m,c):
  contours,_=cv2.findContours(m.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);cv2.drawContours(v,contours,-1,(0,0,0),4);cv2.drawContours(v,contours,-1,c,2)
 for m in refs:outline(views[1][1],m,(255,220,80))
 for name,masks in [('baseline',baseline),('adapted',adapted)]:
  v=base.copy();ranking=row[name]['ranking'][:30];matched={x['candidate_index'] for x in row[name]['budgets']['30']['matches']['main_0.5']['assignments']}
  for k in ranking:outline(v,masks[k],(40,210,150) if k in matched else (245,150,40))
  views.append((names[name]+' · top 30',v))
 pane=Image.new('RGB',(1300,360),'white');d=ImageDraw.Draw(pane)
 for j,(title,im) in enumerate(views):pane.paste(Image.fromarray(im).resize((320,320)),(j*325+2,30));d.text((j*325+4,7),title,fill='#193b37')
 fn=row['scene_id']+'-paired.jpg';pane.save(O/fn,quality=88);b=row['baseline']['budgets']['30']['matches']['main_0.5'];a=row['adapted']['budgets']['30']['matches']['main_0.5'];boards.append('<article><h3>'+e(row['scene_id'])+'</h3><p>Weak supports matched: original '+str(b['matched'])+'/'+str(b['references'])+'; adapted '+str(a['matched'])+'/'+str(a['references'])+'.</p><a href="'+fn+'"><img loading="lazy" src="'+fn+'" alt="Input, unverified projected supports and original/adapted mask proposals"></a><p><a href="/results/r112/grouped-synthetic/'+e(scene['image'])+'">Source image</a> · <a href="'+e(row['adapted_archive'])+'">Saved adapted candidates</a></p></article>')
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Weak-positive decoder adaptation</title><style>body{font:16px/1.55 system-ui;background:#f4f6f0;color:#193b37;margin:0}main{max-width:1350px;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;display:block;overflow:auto}td,th{border:1px solid #cddbd2;padding:8px;text-align:left}</style><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/grouped-baseline/">Original baseline</a> · <a href="/results/r112/grouped-prompt-diagnostic/">Prompt diagnostic</a></nav><h1>Can weak-positive training improve automatic masks?</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 class="notice"><strong>The adaptation worsened this development comparison.</strong> These scores match unverified synthetic supports, not biological ground truth. The source images and Academy slides were used before, filename groups do not prove biological independence, and the backgrounds can contain unlabeled organisms. No real-field accuracy, precision, species identification or deployment readiness is established.</p><p>For '''+str(train['examples'])+''' synthetic training scenes, selected one positive grid point from the overlap of three correlated source-mask proposals, outside other inserted supports where possible. The original image and prompt encoders were frozen; the MobileSAM decoder was trained for two epochs. A direct positive-only term used the unverified consensus proxy. Everywhere else, a soft teacher-distillation term encouraged the original model’s output; that term can still propagate model errors and produce gradients outside the proxy. It does not mark the background as confirmed negative.</p><p>Both models used identical 256 automatic image-only prompts, 512-pixel input, area and quality filters, NMS and top-30 budgets on the same 48 already-consumed grouped comparison scenes. The decoder quality output was not separately calibrated after training. Every target here was at least 50 pixels at 512; matching uses one-to-one IoU to weak supports.</p><table><tr><th>Model</th><th>Top 30 · IoU ≥0.5</th><th>Top 30 · IoU ≥0.75</th><th>All kept · IoU ≥0.5</th><th>Candidates across 48 scenes</th></tr>'''+table+'''</table><h2>Overlap and clipping proxies</h2><p>Breakdowns use the same global one-to-one assignments; categories overlap and should not be summed. A projected overlap or clipped weak support is not an independently verified biological case.</p><table><tr><th>Proxy category · top 30 · IoU ≥0.5</th><th>Original</th><th>Adapted</th></tr>'''+sub+'''</table><h2>Post-hoc trace</h2><p>After seeing the result, we also checked the maximum matches available in raw and eligible proposals. These are <strong>reference-assisted oracles</strong>, not a deployable ranking or a second independent test. Different stages can assign different candidate/support pairs.</p><table><tr><th>Model</th><th>All raw</th><th>Eligible before NMS</th><th>All kept after NMS</th><th>Top 30</th></tr>'''+ret+'''</table><p>Of the 12,288 raw point masks per model, '''+format(retro['summary']['baseline']['area_over_50000'],',')+''' original and '''+format(retro['summary']['adapted']['area_over_50000'],',')+''' adapted masks exceeded the 50,000-pixel area limit. Large-mask growth is a possible part of this failure, not proof of its cause. The teacher quality scores were not calibrated after adaptation.</p><p><a href="protocol.json">Frozen training and evaluation protocol</a> · <a href="training-prompts.json">Selected training prompts</a> · <a href="training-run.json">Training record</a> · <a href="training-verify.json">Training checks</a> · <a href="evaluation.json">Evaluation scores</a> · <a href="evaluation-verify.json">Score verification</a> · <a href="inference-replay.json">Four-scene inference replay</a> · <a href="retrospective.json">Post-hoc trace</a></p><h2>All 48 paired scenes</h2><p>Yellow outlines are unverified supports; green outlines are candidates assigned to a support at IoU ≥0.5, and orange are other candidates. Orange candidates are <strong>not confirmed false positives</strong>. Overlay order can hide overlap. Click to enlarge.</p>'''+''.join(boards)+'''</main></html>''';(O/'index.html').write_text(page);print(json.dumps({'top30':{k:summary[k]['budgets']['30']['main_0.5'] for k in models},'retrospective':retro['summary']},indent=2))
