"""Replay a deterministic sample of prompts one at a time."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
R=Path(__file__).resolve().parents[1];O=R/'results/r97'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if os.getppid()!=parent:raise RuntimeError('Launcher exited')
p=json.loads((O/'protocol.json').read_text());assert sha(p['sam_checkpoint'])==p['sam_sha256'];rows=[r for r in json.loads((O/'results.json').read_text())['records'] if r['prompt_count']][:3];torch.set_num_threads(2);results=[]
for r in rows:
 assert sha(R/r['source_image'])==r['source_image_sha256'] and sha(O/r['archive'])==r['archive_sha256'];im=Image.open(R/r['source_image']).convert('RGB');rgb=np.zeros((512,512,3),np.uint8);rgb[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS));z=np.load(O/r['archive']);shape=tuple(z['sam_shape']);m=np.unpackbits(z['sam_bits'])[:np.prod(shape)].reshape(shape).astype(bool);predictor=Predictor(overrides={'model':p['sam_checkpoint'],'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR))
 for i in sorted({0,len(m)//2,len(m)-1}):
  out=predictor(bboxes=[z['clipped_boxes'][i].tolist()],verbose=False)[0];mask=out.masks.data.cpu().numpy()[0].astype(bool);q=float(out.boxes.conf.cpu().numpy()[0]);inter=np.count_nonzero(mask&m[i]);union=np.count_nonzero(mask|m[i]);results.append({'case':r['id'],'prompt_position':i,'exact_mask':bool(np.array_equal(mask,m[i])),'mask_iou':float(inter/union) if union else 1.,'quality_absolute_difference':abs(q-float(z['sam_quality'][i]))})
(O/'single-prompt-replay.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'results':results,'warning':'Sample of prompts, single vs batched inference; not validation of all predictions or real-overlap accuracy.'},indent=2)+'\n');print('sample',len(results),'exact',sum(x['exact_mask'] for x in results),'min IoU',min(x['mask_iou'] for x in results),'max quality diff',max(x['quality_absolute_difference'] for x in results))
