"""python figure_425.py CACHE OUT. Photo attribution and cropped evidence; never redraw missing strokes."""
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont,ImageOps
import numpy as np,sys
def main(s,o):
 w=np.load(o/'predictions.npz');v=w['v']
 F='/usr/share/fonts/truetype/dejavu/DejaVuSans';font=lambda n,b=False:ImageFont.truetype(F+('-Bold' if b else '')+'.ttf',n)
 def txt(d,x,y,v,sz=15,b=False):d.text((x,y),v,font=font(sz,b),fill='#183c34')
 def tile(c,im,x,y,w,h,bg='white'):
  d=ImageDraw.Draw(c);d.rectangle((x,y,x+w-1,y+h-1),fill=bg);im=ImageOps.contain(im,(w,h),Image.Resampling.LANCZOS);c.paste(im,(x+(w-im.width)//2,y+(h-im.height)//2))
 def view(v):return Image.fromarray((255-np.clip(v*4,0,255)).astype('uint8')).convert('RGB')
 c=Image.new('RGB',(800,432),'#f5f3eb');d=ImageDraw.Draw(c);txt(d,19,14,'From a photographed oak to the page-55 tree',23,1)
 for j,(title,im) in enumerate([('2005 photograph',Image.open(s/'oak0.jpeg')),('Solver’s silhouette',Image.open(s/'originalTreeImage.jpg')),('Printed tree · page 55',view(v))]):
  x=17+j*259;txt(d,x,66,title,16,1);tile(c,im,x,98,245,245)
 txt(d,18,358,'The book faces the other way. Backgrounds, crops, and the foot of the tree differ.',15)
 txt(d,18,392,'Photo: R Neil Marshman (Brookie), Wikimedia Commons · CC BY-SA 3.0. Comparison under the same license.',12)
 c.save(o/'oak_lineage_415.jpg',quality=82,optimize=True)
 c=Image.new('RGB',(805,358),'#f5f3eb');d=ImageDraw.Draw(c);txt(d,18,12,'Where the root comparison fails',23,1);txt(d,18,49,'Same coordinates and brightness scale. The full lower window includes both sides of the root.',14)
 for i,(name,ar) in enumerate([('Printed outline',v),('Broad-foot source',w['github_L']),('Short 2024 cutout',w['hd_first_L'])]):
  x=18+i*261;im=view(ar[159:194,47:127]).resize((240,105),Image.Resampling.NEAREST);c.paste(im,(x,106));txt(d,x,80,name,16,1)
 for i,t in enumerate(['29 cells across','58 cells across','No ink at this height']):txt(d,18+i*261,230,t,16,1)
 txt(d,18,280,'Widths are maximum row spans at darkness 20, measured across the full lower window.',13)
 txt(d,18,314,'Original page, fixed left-trained prediction, and the alternative cutout under that identical transform.',13)
 c.save(o/'oak_roots_425.png',optimize=True)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
