import json,html
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/l76';rows=json.loads((O/'results.json').read_text())['records'];sections=[]
for r in rows:
 z=np.load(O/r['archive']);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(k):v for k,v in zip(z['ids'],m)};pictures={k:Image.open(O/v['image']).convert('RGBA') for k,v in r['images'].items()};out=Image.new('RGB',(1040,1120),'white');d=ImageDraw.Draw(out)
 for row,kind in enumerate(('baseline','focal')):
  for j,ident in enumerate(r['rankings'][kind][:8]):
   source=ident.split(':')[0];source='plane1' if source=='baseline' else source;im=pictures[source].copy();mask=lookup[ident];layer=Image.new('RGBA',im.size,'#008a70');layer.putalpha(Image.fromarray(mask.astype('uint8')*95));im=Image.alpha_composite(im,layer).convert('RGB').resize((250,250));x=(j%4)*260;y=(row*2+j//4)*280;out.paste(im,(x,y+25));d.text((x+3,y+4),f'{kind} #{j+1} · {source}',fill='#203a38')
 gallery=O/f'field-{r["index"]}-individuals.jpg';out.save(gallery,quality=88);counts=', '.join(f'{html.escape(k)}: {v}' for k,v in r['stream_counts'].items());links=' · '.join(f'<a href="{html.escape(v["image"])}">{html.escape(k)}</a>' for k,v in r['images'].items());sections.append(f'<section><h2>Field {r["index"]+1} · {html.escape(r["split"])}</h2><p>{html.escape(r["slide"])}; origin {r["origin_xy"]}; zero-based focal planes {r["planes"]}. Middle-plane retained {r["baseline_count"]}; four-stream retained {r["focal_count"]} ({counts}). Cross-stream IoU ≥0.5 links: {len(r["cross_plane_iou05_links"])}.</p><img src="{r["comparison"]}" alt="Candidate overlays and original planes"><p>Individual candidates on their original source plane: first eight baseline then first eight mixed-stream candidates. Shapes may be debris, merged objects or duplicates.</p><img src="{gallery.name}" alt="Individual candidate masks on their source planes"><p>Native crops and derived fusion: {links}.</p></section>')
(O/'index.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>L76 focal-plane proposals</title><style>body{{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}}img{{max-width:100%}}a{{color:#006b59}}.box{{background:#fff2d6;padding:1em}}section{{border-top:1px solid #ccc;margin-top:2em}}</style><a href="/results/board.html">Research board</a> · <a href="/results/performance/">Performance monitor</a><h1>L76: Do adjacent focal planes yield different proposals?</h1><p class="box">These are four unlabelled fields from two Academy stacks. Model outputs may outline debris, multiple objects or partial structures. Agreement between predictions is not accuracy, and high overlap does not establish specimen identity.</p><p>Fields were fixed by image coordinates before inference. The baseline runs 256 image-only prompts on the middle plane. The comparison runs 64 prompts each on the middle plane, two adjacent planes and a derived focus composite: 256 mask queries in both approaches, but four image encodings rather than one for the focal stream. Its stream rankings are interleaved without removing cross-plane alternatives.</p><p>The focus composite chooses, independently for each 32×32 tile, the plane with the strongest Laplacian energy. It can create seams, choose sharply focused debris or combine different depths. It is a model input, not a faithful optical image or a recommended source for species classification. All original native crops, source scan hashes and each candidate’s plane or fusion provenance are retained. The original stack is single-channel grayscale; no color data was available in these scans.</p><p>Across four fields, the middle-plane stream retained {sum(r['baseline_count'] for r in rows)} candidates, and the four-stream method retained {sum(r['focal_count'] for r in rows)}. The latter includes unmerged cross-plane alternatives and is not an object count. Pixel overlap links record possible associations, not verified tracks. No claims of improved recall, false-positive rate, human-level proficiency or species identification can be made without reference labels.</p><p><a href="/research/L76.md">Research note</a> · <a href="protocol.json">Frozen protocol and source hashes</a> · <a href="results.json">Ranks and cross-plane links</a> · <a href="/research/l76_verify.py">Replay verifier</a></p>{''.join(sections)}</html>''')
