"""Show renderer interventions and quantitative limitations."""
import html,json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r112/instance-contribution-audit';r=json.loads((O/'results.json').read_text());E=html.escape;rows=r['records'];table=''
for family in ('crowded','separated','breadth','all'):
 xs=[x for x in rows if family=='all' or x['family']==family];mean=np.array([x['mean_absolute_change_inside_support'] for x in xs]);s=r['summary'][family];table+='<tr><th>'+E(family.title())+'</th><td>'+str(len(xs))+'</td><td>'+str(s['zero_changed_pixels'])+'</td><td>'+str(int((mean<1).sum()))+'</td><td>'+str(int((mean<2).sum()))+'</td><td>'+f'{float(np.median(mean)):.2f}'+'</td></tr>'
examples=[x for x in rows if 'examples' in x];examples.sort(key=lambda x:(x['changed_fraction'] if x['changed_fraction'] is not None else -1,x['family'],x['scene_id'],x['instance_index']));cards=[]
for x in examples:
 root='/results/r112/species-breadth/images/' if x['family']=='breadth' else '/results/r112/species-scaleup/images/';imgs=[('Source crop',root+x['annotation_id']+'.png')]+[(name,'/'+x['examples'][k]['path']) for name,k in [('With insertion','with'),('Without this insertion','without'),('Absolute difference ×10','difference_x10')]];cards.append('<article><h3>'+E(x['family'])+' · '+E(x['scene_id'])+' · instance '+str(x['instance_index']+1)+'</h3><p>Source: '+E(x['source_name'])+' · '+E(x['annotation_id'])+' · changed '+str(x['changed_pixels'])+'/'+str(x['support_pixels'])+' projected pixels ('+f"{100*x['changed_fraction']:.1f}%"+') · mean change '+f"{x['mean_absolute_change_inside_support']:.2f}"+' / 255 · '+str(x['overlap_support_pixels'])+' support pixels overlap other projected supports</p><div class="views">'+''.join('<figure><a href="'+E(path)+'"><img loading="lazy" src="'+E(path)+'" alt="'+E(title)+'"></a><figcaption>'+E(title)+'</figcaption></figure>' for title,path in imgs)+'</div></article>')
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rendered contribution 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:#fff8df;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;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}@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/breadth-diverse-scenes/">Additional source-name scenes</a></nav><h1>What does each synthetic insertion change?</h1><p class="notice"><strong>This is a renderer diagnostic, not a biological visibility or accuracy measurement.</strong> A source crop and its projected mask may be wrong or include neighbors; the Academy background may contain other diatoms. A larger pixel difference does not prove a species can be identified. A small difference does not prove a person cannot see an organism.</p><p>For each of 3,998 inserted sources in 573 development fields, the original image was reconstructed and compared with the same image rendered without that particular insertion. Both versions use the original layer order, clipping and 8-bit rounding. The table counts instances by the mean absolute gray-level change inside the unverified projected support; no training or test decisions are made from these numbers.</p><table><tr><th>Scene set</th><th>Insertions</th><th>No pixels changed</th><th>Mean change &lt;1 / 255</th><th>Mean change &lt;2 / 255</th><th>Median mean change</th></tr>'''+table+'''</table><p>Thresholds are descriptive, not quality cutoffs. Overlap with another projected support does not establish real biological occlusion; the difference image includes the effect of compositing and quantization. The ×10 images below amplify absolute differences for inspection and saturate values above 25.5, so they do not show the original contrast.</p><p><a href="protocol.json">Frozen audit</a> · <a href="results.json">All per-instance measurements</a> · <a href="verify.json">Checks and reconstructed examples</a> · <a href="/diatom_pilot/scaleup_crowded_dataset.py">Dataset readers</a></p><pre>from diatom_pilot.scaleup_crowded_dataset import ScaleupCrowdedDataset
scenes = ScaleupCrowdedDataset("development_training", include_contribution_audit=True)
example = scenes[0]  # rendered_pixel_contributions are diagnostic, not visibility masks</pre><h2>Paired examples</h2><p>The first 30 were selected by the smallest fraction of projected support pixels changed; another 15 were evenly spaced references, with duplicates removed. Click to view native pixels. All masks and source names remain unverified.</p>'''+''.join(cards)+'''</main></html>''';(O/'index.html').write_text(page);print('published',len(cards),'counterfactual examples')
