"""python filters_422.py BOOK_FILES CACHE OUT. Check real documented processing chain and test the preserved arrays in the frozen book geometry."""
from variants_419 import *
def main(d,s,o):
 imgs={k:rd(s/(k+'.png')) for k in ('noisy','gauss','median')};a=imgs['noisy'].astype(float);out={};refs=source(s/'originalTreeImage.jpg',False)[26:-26,26:-26];tables=json.loads((d/'tone_406_results.json').read_text())['correct'];V,X,Y=grid(d);M=masks(X,Y)
 for name,z in [('median',nd.median_filter(a,size=3)),('gauss',nd.convolve(a,np.outer([1,2,1],[1,2,1])/16))]:
  measured=imgs[name];dh,dw=np.array(a.shape)-measured.shape
  if dh>=0 and dw>=0:
   errs=[]
   for iy in range(dh+1):
    for ix in range(dw+1):
     u=z[iy:iy+measured.shape[0],ix:ix+measured.shape[1]];e=u-measured;errs.append({'shift':[iy,ix],'rmse':float(np.sqrt(np.mean(e*e))),'exact_after_floor':float(np.mean(np.floor(u)==measured)),'exact_after_round':float(np.mean(np.rint(u)==measured)),'within1':float(np.mean(abs(e)<=1))})
   out[name+'_recipe']=min(errs,key=lambda v:v['rmse'])
 for n,a in imgs.items():
  v=(a<=otsu(a)).astype(float);v=resize(v,280,round(v.shape[0]*280/v.shape[1]));template,pars=align(v,refs,'full',(140,219,280,286));o1=out[n]={'source':pars,'size':list(a.shape[::-1]),'threshold':otsu(a),'sides':{}}
  for tr,te in [('L','R'),('R','L')]:
   z=render(template[:,::-1],tables[tr]['tone'],X,Y);o1['sides'][tr]={'held':measure(z,V,M[te]),'root':footprint(z,V,Y>=173,20),'tips':[footprint(z,V,M[k],20)['f1'] for k in ('top_tips','left_tips','right_tips')]}
 (o/'filters_422_results.json').write_text(json.dumps(out,indent=2)+'\n')
 print(out['median_recipe'],out['gauss_recipe']);print([(n,o['source']['train_r'],[o['sides'][t]['held']['loops_hit'] for t in 'LR']) for n,o in out.items() if 'source' in o])
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
