"""Recompute eight selected boundary-point tile masks individually."""
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/r108';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'][:2]:
 assert sha(O/r['archive'])==r['archive_sha256'] and sha(R/r['source'])==r['source_sha256'];z=np.load(O/r['archive']);shape=tuple(z['boundary_mask_shape']);saved=np.unpackbits(z['boundary_mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool)
 if r['view']=='clipped':assert sha(O/r['clipped_image'])==r['clipped_image_sha256'];rgb=np.asarray(Image.open(O/r['clipped_image']).convert('RGB'))
 else:im=Image.open(R/r['source']).convert('RGB');rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS))
 for i in (0,119,136,255):
  x,y,x1,y1=z['boundary_crops'][i].tolist();px,py=z['boundary_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));o=model(points=[[[2*(px-x),2*(py-y)]]],labels=[[1]],verbose=False)[0];sm=cv2.resize(o.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]=sm;q=float(o.boxes.conf.cpu().numpy()[0]);res.append({'field':r['index'],'view':r['view'],'index':i,'exact':bool(np.array_equal(full,saved[i])),'quality_delta':abs(q-float(z['boundary_quality'][i]))})
(O/'sample-replay.json').write_text(json.dumps({'results':res,'warning':'Eight selected single-query replays only, 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))
