import json,shutil
from PIL import Image,ImageChops
import numpy as np
root='/tmp/issue-16096/evidence/'
before=json.load(open(root+'captures-before.json'));after=json.load(open(root+'captures-after.json'))
results=[]
for b,a in zip(before,after):
 name=f"{b['width']}-{b['theme']}"
 for c in [b,a]:
  x,y=[Image.open(c[k]['screenshotPath']).convert('RGB') for k in ['a','b']]
  assert not ImageChops.difference(x,y).getbbox(),name+' unstable'
  shutil.copyfile(c['b']['screenshotPath'],root+c['revision']+'-'+name+'.png')
 x=np.array(Image.open(b['b']['screenshotPath']).convert('RGB')).astype('int16');y=np.array(Image.open(a['b']['screenshotPath']).convert('RGB')).astype('int16')
 d=np.abs(x-y);Image.fromarray(np.minimum(d*4,255).astype('uint8')).save(root+'diff-zero-'+name+'.png')
 mask=d.max(axis=2)>16;out=np.zeros_like(x,dtype='uint8');out[mask]=[255,0,160];Image.fromarray(out).save(root+'diff-threshold16-'+name+'.png')
 results.append({'pair':name,'size':list(x.shape),'changedPixelsAny':int((d.max(axis=2)>0).sum()),'changedPixelsThreshold16':int(mask.sum()),'settledEqual':True})
json.dump(results,open(root+'diff-stats.json','w'),indent=2);print(json.dumps(results,indent=2))
