"""Reconstruct local train/validation scenes and verify source/background separation."""
import collections,ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r112_broad_scene_render import render
R=Path(__file__).resolve().parents[1];O=R/'results/r112/grouped-synthetic';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
cv2.setNumThreads(2);p=json.loads((O/'scene-protocol.json').read_text());m=json.loads((O/'manifest.json').read_text());s=json.loads((O/'split.json').read_text());screen=json.loads((O/'similarity-screen.json').read_text());assert m['protocol_sha256']==sha(O/'scene-protocol.json') and m['generator_sha256']==sha(R/'research/r112_grouped_scene_render.py') and p['split_sha256']==sha(O/'split.json') and p['screen_sha256']==sha(O/'similarity-screen.json') and screen['protocol_sha256']==sha(O/'screen-protocol.json');q=set(screen['quarantined_ids']);members={x['annotation_id']:x for x in s['sources']};groups={'train':set(),'validation':set()};ids={'train':set(),'validation':set()};bgs={'train':set(),'validation':set()};names={'train':set(),'validation':set()};counts=collections.Counter();clips=collections.Counter();pairs=collections.Counter()
for a,b in zip(p['scenes'],m['records']):
 part=a['synthetic_partition'];assert b['id']==a['id'] and b['split']=='development_only' and b['synthetic_partition']==part and b['background']==a['background'] and a['background']['synthetic_partition']==part;bgs[part].add(a['background']['slide']);img,masks,items=render(a);assert items==b['instances'];f=O/b['image'];zpath=O/b['mask_archive'];assert sha(f)==b['image_sha256'] and np.array_equal(img,np.asarray(Image.open(f).convert('L'))) and sha(zpath)==b['mask_archive_sha256'];z=np.load(zpath);shape=tuple(z['support_shape']);saved=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);assert np.array_equal(masks,saved) and str(z['background_label_status'])=='unknown' and str(z['transparent_visibility_status'])=='undefined';n=sum(bool((masks[i]&masks[j]).any()) for i in range(len(masks)) for j in range(i+1,len(masks)));assert n==b['overlap_pairs'];pairs[part]+=n;counts[part+'_scenes']+=1
 for x in items:
  ident=x['annotation_id'];assert ident not in q and ident in members and members[ident]['synthetic_partition']==part and x['synthetic_partition']==part and all(x[k]==v for k,v in members[ident].items());groups[part].add(x['canonical_group']);ids[part].add(ident);names[part].add(x['source_species']);clips[part]+=int(x['in_frame_fraction']<1);counts[part+'_placements']+=1
assert len(p['scenes'])==len(m['records'])==192 and counts=={'train_scenes':144,'train_placements':720,'validation_scenes':48,'validation_placements':240};assert not groups['train']&groups['validation'] and not ids['train']&ids['validation'] and not bgs['train']&bgs['validation'] and names['validation']<=names['train'];out={'counts':dict(counts),'source_ids':{k:len(v) for k,v in ids.items()},'source_filename_groups':{k:len(v) for k,v in groups.items()},'background_slides':{k:len(v) for k,v in bgs.items()},'source_name_strings':{k:len(v) for k,v in names.items()},'clipped_placements':dict(clips),'overlap_pairs':dict(pairs),'checks':'Re-rendered every scene and support using shared rendering code; checked source ID, canonical source group and background slide partitions, taxonomy metadata, weak support flags and hashes. Does not establish independent biological samples, accurate labels or masks, optical realism or real-world performance.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
