"""Visualize every paired source, transformed and synthetic crop."""
import collections,html,json
from pathlib import Path
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/species-retention';data=json.loads((O/'results.json').read_text());r=data['records'];stages=('original','transformed','composite');cards=[]
for x in r:
 out=Image.new('L',(780,300),'white');d=ImageDraw.Draw(out)
 for j,k in enumerate(stages):
  im=Image.open(O/x['stages'][k]['image']).convert('L');im.thumbnail((240,240),Image.Resampling.LANCZOS);out.paste(im,(j*260+(250-im.width)//2,30+(240-im.height)//2));d.text((j*260+5,6),k,fill=25)
 name=x['annotation_id']+'-comparison.jpg';out.save(O/name,quality=90);descriptions=' · '.join(f'{html.escape(k)}: {html.escape(x["stages"][k]["prediction"])}' for k in stages);overlap=x['synthetic_overlap_fraction_of_target'];overlap='unknown' if overlap is None else f'{overlap:.1%}';cards.append(f'<article><h3>{html.escape(x["source_species"])} · {x["annotation_id"]}</h3><p>{descriptions}</p><p>Source-support fraction in frame: {x["in_frame_fraction"]:.1%}; synthetic-support overlap: {overlap}. These are geometry diagnostics, not visibility or instance truth.</p><a href="{name}"><img loading="lazy" src="{name}" alt="Original, transformed and composited source crop"></a><p><a href="{x["stages"]["original"]["image"]}">Original</a> · <a href="{x["stages"]["transformed"]["image"]}">Transformed crop</a> · <a href="{x["stages"]["composite"]["image"]}">Composite crop</a></p></article>')
counts={s:sum(v['stages'][s]['matches_source_name'] for v in r) for s in stages}
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Species signal retention diagnostic</title><style>body{font:16px/1.55 system-ui;background:#f3f6f0;color:#193b37;margin:0}main{max-width:1000px;margin:auto;padding:25px}h1,h2,h3{font-family:Georgia,serif}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}</style><body><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/weak-development-v1/">Weak synthetic scenes</a></nav><h1>Does rendering retain species signal?</h1><p class="notice"><strong>Small exploratory diagnostic, not Academy accuracy.</strong> A previously trained generic ResNet centroid classifier is forced to choose among four species; it has no unknown option. Labels are unverified UDE metadata. The crops, scenes and model were already used in development, and slide-name separation does not prove biological independence.</p><p>For each of 59 distinct source cutouts, show its first recorded synthetic placement. Use original pixels, the physically resampled and rotated source crop limited to the visible frame, and the matching rectangle from the final synthetic field. The last rectangle uses known insertion coordinates: it does not test a detector. Transform, clipping, insertion, neighbors, background and crop differences are intertwined.</p><p>Matches to source species names: original '''+str(counts['original'])+'''/59, transformed '''+str(counts['transformed'])+'''/59, composite '''+str(counts['composite'])+'''/59. This is evidence of a possible degradation of information available to this specific classifier under this renderer, not proof that species features were destroyed or a general estimate of identification performance. Individual successes and failures are shown below.</p><p><a href="protocol.json">Pre-inference selection and protocol</a> · <a href="results.json">All outputs and geometry</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Interpretation</a></p>'''+''.join(cards)+'''</main></body></html>''')
print('Rendered',len(r),'paired cases;',counts)
