"""Render L89 with corrected panel labels and disclosed synthetic context."""
import hashlib,html,json
from pathlib import Path
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/l89';rows=json.loads((O/'results.json').read_text())['records'];base={(x['pair'],x['condition']):x for x in json.loads((R/'results/l88/results.json').read_text())['records']};tables=[];derived=[];cards=[]
for split in ('development','holdout_source_fields'):
 for cond in ('separated','crossing','near','partial'):
  a=[x for x in rows if x['split']==split and x['condition']==cond];vals=[sum(base[x['pair'],x['condition']]['scores']['tiled']['30']['0.5']['matched'] for x in a),sum(x['scores']['texture']['30']['0.5']['matched'] for x in a),sum(base[x['pair'],x['condition']]['scores']['tiled']['all']['0.5']['matched'] for x in a),sum(x['scores']['texture']['all']['0.5']['matched'] for x in a),sum(base[x['pair'],x['condition']]['scores']['raw']['0.5']['matched'] for x in a),sum(x['scores']['raw']['0.5']['matched'] for x in a)];tables.append(f'<tr><td>{html.escape(split)}</td><td>{cond}</td>'+''.join(f'<td>{v}/4</td>' for v in vals)+'</tr>')
for r in rows:
 img=Image.open(O/r['panel']).convert('RGB');d=ImageDraw.Draw(img)
 for k,title in [(1,'Uniform tiled grid top 30'),(2,'Variance-guided tiles top 30'),(3,'Variance-guided tiles all')]:d.rectangle((k*300,0,k*300+299,27),fill='white');d.text((k*300+5,8),title,fill='#203a38')
 name=r['panel'].replace('.png','-labeled.png');img.save(O/name);derived.append({'source':r['panel'],'source_sha256':r['panel_sha256'],'derived':name,'derived_sha256':hashlib.sha256((O/name).read_bytes()).hexdigest(),'edit':'Replace inherited whole-image/tile panel titles with uniform tile and variance tile labels; image pixels below label unchanged.'});b=base[r['pair'],r['condition']];v=[b['scores']['tiled']['30']['0.5']['matched'],r['scores']['texture']['30']['0.5']['matched'],b['scores']['raw']['0.5']['matched'],r['scores']['raw']['0.5']['matched']];cards.append(f'<section><h2>Pair {r["pair"]}: {html.escape(r["condition"])}</h2><p>Uniform / variance at top 30: {v[0]} / {v[1]} of 2; raw candidates: {v[2]} / {v[3]} of 2. Variance method kept {r["kept_count"]} candidates, {r["edge_kept_count"]} touching crop boundaries.</p><a href="{name}"><img loading="lazy" src="{name}" alt="Source reference and uniform versus variance-guided tile masks"></a><p><a href="/results/l75/{html.escape(r["source_image"])}">Source composite</a> · <a href="{r["archive"]}">Variance masks, crop coordinates and points</a> · <a href="/results/l88/{r["baseline_archive"]}">Uniform baseline masks</a></p></section>')
(O/'figure-provenance.json').write_text(json.dumps(derived,indent=2)+'\n')
(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>L89 image-guided tile points</title><style>body{font:16px/1.5 system-ui;color:#18342f;max-width:1200px;margin:2em auto;padding:0 1em}a{color:#006b59}img{width:100%}table{border-collapse:collapse}td,th{border:1px solid #bbc;padding:.4em}.warn{background:#fff2d6;padding:1em}section{border-top:1px solid #ccd}</style><a href="/results/board.html">Research board</a> · <a href="/results/l88/">Uniform tile baseline</a> · <a href="/results/l89/clean/">Empty-background control</a><h1>L89: Image-guided points inside fixed tiles</h1><p class="warn">Previously examined, artificially composited busy scenes; former source-field holdout is not untouched. Other organisms in the busy background are unlabeled, and synthetic scenes do not validate real severe overlap or human-level segmentation.</p><p>Keep L88's same 16 overlapping crops per scene. Within each crop select 16 spatially separated high local-variance pixels without using any reference mask; compare with the fixed 4×4 tile grid. Both methods use 256 point queries and 16 image encodings per scene, identical candidate filters and NMS. This phase guides <em>points within fixed crops</em>; it does not yet test image-selected crops, additional scales, clean backgrounds or reversed overlaps.</p><table><tr><th>Previous split</th><th>Scene</th><th>Uniform top 30</th><th>Variance top 30</th><th>Uniform all NMS</th><th>Variance all NMS</th><th>Uniform raw</th><th>Variance raw</th></tr>'''+''.join(tables)+'''</table><p>Values are one-to-one matches to four inserted visible supports per row at IoU ≥0.5. On the former-holdout crossings, both methods match 0/4 in the first 30; all-kept results are 2/4 uniform and 3/4 variance, while both raw sets contain 4/4. No complete crossing pair is recovered in the first 30. In development controls the variance method matches 2/4 crossing supports versus 1/4 uniform at top 30, but loses a partial-control support: raw and kept matches there fall from 4/4 to 3/4. The comparisons are small, repeatedly viewed and exploratory.</p><p>After inference, reference-conditioned point membership found 216 of 4,096 uniform queries and 765 of 4,096 variance queries landed on one of the two inserted visible supports. Queries in overlapping crops can repeat the same source area and are counted separately. This is not detection precision or a false-positive rate: other background structures and organisms are not fully labeled, and landing on a support does not guarantee a useful mask.</p><p>The variance method retained 1,526 masks after NMS, 932 touching crop edges. The tiled uniform baseline retained 1,800, 1,203 touching edges. Compute counts are equal in prompts and encodings, but point selection and actual runtime differ. All raw masks and suppression aliases remain saved with original coordinates.</p><p>Source hashes, selected points, mask bounds, filtering, shared NMS and matching were reconstructed using the same point selector; full inference was not rerun. Eight selected single-query replays reproduced their saved batched masks. The posthoc point-membership audit replayed byte-identically. Original output panels inherited incorrect titles; displayed copies correct the titles only, with original and derivative hashes recorded.</p><p><a href="protocol.json">Protocol</a> · <a href="results.json">Scores and ranks</a> · <a href="point-audit.json">Posthoc point audit</a> · <a href="verify.log">Verification</a> · <a href="sample-replay.json">Sample inference replay</a> · <a href="figure-provenance.json">Figure title corrections</a> · <a href="/research/L89.md">Research note</a></p>'''+''.join(cards)+'</html>')
