"""python joint_391.py BOOK_FILES OUTPUT_DIR. Full-page, not hand-cropped, tree search; compare raw tone with ink boundaries filled before search."""
from pathlib import Path
import numpy as np,json,sys,hashlib
from PIL import Image
from scipy.ndimage import binary_fill_holes,binary_closing,gaussian_filter
from tree_search_371 import scores,top
def main(d,o):
 im=Image.open(d/'notice_2016_363.jpg').convert('L').crop((190,305,365,471));widths=[55,70,85,100,115,130,145];qs={k:np.array(im.resize((k,round(k*166/175)),Image.Resampling.BILINEAR),float) for k in widths}
 paper=[];big=json.loads((o/'scan_385_results.json').read_text());man={f['file']:f['sha256'] for f in json.loads((d/'jpeg_source_manifest.json').read_bytes())['files']}
 for i in range(75):
  f=d/f'{i:02}.jpg';assert hashlib.sha256(f.read_bytes()).hexdigest()==man[f.name];p=Image.open(f).convert('L');raw=(255-np.asarray(p.resize((240,360),Image.Resampling.BOX))).astype(float)/255;medium=255-np.asarray(p.resize((600,900),Image.Resampling.BOX));ink=binary_fill_holes(binary_closing(medium>9,iterations=1));filled=np.asarray(Image.fromarray(ink.astype('uint8')*255).resize((240,360),Image.Resampling.BOX),float)/255;results={}
  for lab,a in [('raw',raw),('filled',gaussian_filter(filled,1))]:
   best=None
   for w,q in qs.items():
    r,x,y=top(scores(a,q,.015));entry={'r':round(r,7),'x_y_width':[x,y,w]}
    if best is None or r>best['r']:best=entry
   results[lab]=best
  row=dict(archive=i,**results);row['weaker_of_poster_emblem_and_filled_tree']=round(min(big['pages'][i]['masked_poster']['r'],results['filled']['r']),7);paper.append(row)
 out={'widths':widths,'formula':'min(masked_poster_emblem_correlation, filled_tree_correlation); locations fitted independently; descriptive, no p-value','pages':paper,'ranks':{k:[v['archive'] for v in sorted(paper,key=(lambda p:-p[k]['r']) if k!='weaker_of_poster_emblem_and_filled_tree' else (lambda p:-p[k]))] for k in ('raw','filled','weaker_of_poster_emblem_and_filled_tree')}};(o/'joint_391_results.json').write_text(json.dumps(out,indent=2)+'\n')
 for k,ls in out['ranks'].items():print(k,[(j,paper[j][k]) for j in ls[:7]],'p55 rank',ls.index(72)+1,flush=True)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
