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/r85';rows=json.loads((O/'results.json').read_text())['records'];sel=json.loads((O/'selection.json').read_text())['records'];files=json.loads((O/'image-manifest.json').read_text())['files'];sections=[]
for row,s,f in zip(rows,sel,files):
 z=np.load(O/row['archive']);masks=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(i):m for i,m in zip(z['ids'],masks)};rgb=Image.new('RGB',(512,512),'black');rgb.paste(Image.open(R/f['path']).convert('RGB').resize((512,384),Image.Resampling.LANCZOS),(0,64));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Published source polygons',z['refs']),('64 prompts: top 30',[lookup[i] for i in row['policies']['64']['ranking'][:30]]),('256 prompts: top 30',[lookup[i] for i in row['policies']['256']['ranking'][:30]])]):
  tile=rgb.convert('RGBA')
  for k,m in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((350,350)),(j*360+5,35));draw.text((j*360+5,10),title,fill='#203a38')
 pic=f'field-{row["index"]:02d}.png';out.save(O/pic);sections.append(f'<h3>{html.escape(row["filename"])} · {s["kind"]}</h3><p>{row["reference_count"]} source polygons; 64 prompts top 30: {row["policies"]["64"]["scores"]["30"]["0.5"]["matched"]}, 256 prompts: {row["policies"]["256"]["scores"]["30"]["0.5"]["matched"]}. <a href="/{f["path"]}">Original image</a></p><img src="{pic}" alt="Source reference and candidate mask comparison">')
(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>R85 diatom overlap search</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}}</style><a href="/results/board.html">Research board</a><h1>R85: Searching for real overlapping diatom references</h1><p class="box"><strong>Small overlaps only:</strong> We found two source-polygon pairs in the scanned training, validation and test annotation files of the <a href="https://zenodo.org/records/21295927">Khanom public dataset</a>. Their shared areas cover only 0.4% and 2.3% of the smaller source polygons. These are not a test of severe occlusion.</p><p>The two overlap fields contain five reference shapes altogether. Both 64- and 256-prompt methods matched all five at IoU ≥ 0.5 with a 30-candidate budget per field; at 0.75 they matched four. This includes one non-overlapping third polygon. Two metadata-selected controls are shown below. The data and geometry were audited before selection; the small cases do not establish biological independence or human-level performance.</p><p>The entire largest test annotation files contain 104 polygons across 85 fields and no overlapping pair sharing ten or more pixels. A further scan of the largest train and validation files found the two pairs above. Cross-split filename duplication affects parts of this dataset; the four chosen validation filenames do not appear in the source train or test annotation lists, but related samples may still recur.</p><p>Other public data provide complementary inputs but not this missing reference: the <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC10847640/">FMPD paper</a> describes expert species and bounding-box labels, useful for proposal detection rather than mask overlap evaluation. <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC11604061/">UDE Diatoms in the Wild</a> includes difficult real diatoms but describes rough object outlines and cutouts; these are not verified full hidden-instance masks. Continue looking for better sources and use synthetic controls while labeling evidence honestly.</p><p><a href="/research/R85.md">Research note</a> · <a href="all-overlap-scan.json">Source overlap inventory</a> · <a href="overlap-scan.json">Test-split audit</a> · <a href="selection.json">Selection</a> · <a href="protocol.json">Protocol</a> · <a href="results.json">Results</a> · <a href="/research/r85_verify.py">Replay verifier</a></p><h2>Field comparisons</h2>{''.join(sections)}</html>''')
