"""Recompute selected image-guided tile masks one at a time."""
import ctypes,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
from l86_oracle import sha
R=Path(__file__).resolve().parents[1];O=R/'results/l89';S=R/'results/l75';parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if os.getppid()!=parent:raise RuntimeError('launcher exited')
d=json.loads((O/'results.json').read_text());assert sha('/tmp/mobile_sam.pt')==d['checkpoint_sha256'];torch.set_num_threads(2);res=[]
for r in d['records']:
 if (r['pair'],r['condition']) not in ((3,'crossing'),(4,'crossing')):continue
 assert sha(S/r['source_image'])==r['source_image_sha256'] and sha(O/r['archive'])==r['archive_sha256'];z=np.load(O/r['archive']);shape=tuple(z['mask_shape']);saved=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);rgb=np.asarray(Image.open(S/r['source_image']).convert('RGB'))
 for i in (0,119,136,255):
  x,y,x1,y1=z['crops'][i].tolist();px,py=z['points'][i].tolist();crop=Image.fromarray(rgb[y:y1,x:x1]).resize((512,512),Image.Resampling.LANCZOS);model=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});model.set_image(cv2.cvtColor(np.asarray(crop),cv2.COLOR_RGB2BGR));out=model(points=[[[2*(px-x),2*(py-y)]]],labels=[[1]],verbose=False)[0];small=cv2.resize(out.masks.data.cpu().numpy()[0].astype('uint8'),(256,256),interpolation=cv2.INTER_NEAREST).astype(bool);full=np.zeros((512,512),bool);full[y:y1,x:x1]=small;q=float(out.boxes.conf.cpu().numpy()[0]);res.append({'pair':r['pair'],'index':i,'exact':bool(np.array_equal(full,saved[i])),'quality_delta':abs(q-float(z['quality'][i]))})
(O/'sample-replay.json').write_text(json.dumps({'results':res,'warning':'Eight selected single-query replays; not complete inference validation.'},indent=2)+'\n');print('replayed',len(res),'exact',sum(x['exact'] for x in res),'max score difference',max(x['quality_delta'] for x in res))
