"""Run fixed Cellpose DINOv3 settings on R48 source images; checkpoint each."""
import hashlib,json,time
from pathlib import Path
import numpy as np,torch
from PIL import Image
from cellpose import models
from r80_progress import update
R=Path(__file__).resolve().parents[1];O=R/'results/r80';WEIGHT=Path('/tmp/diatom-cellpose-models/cpdino-vitb')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 p=json.loads((O/'protocol.json').read_text())
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 baseline=json.loads((O/'baseline.json').read_text());assert baseline['protocol_sha256']==sha(O/'protocol.json') and len(baseline['records'])==24;source=json.loads((O/'source-audit.json').read_text())['targets'];torch.set_num_threads(4);model=models.CellposeModel(gpu=False,pretrained_model=str(WEIGHT),use_bfloat16=False);records=[]
 for n,row in enumerate(source,1):
  ident=row['id'];checkpoint=O/f'cellpose-{ident}.json'
  if checkpoint.exists():
   rec=json.loads(checkpoint.read_text());assert rec['protocol_sha256']==sha(O/'protocol.json') and sha(O/rec['archive'])==rec['archive_sha256'];records.append(rec);update('Cellpose inference',n,len(source),f'Recovered validated checkpoint for case {ident}.');continue
  rgb=np.asarray(Image.open(row['image_path']).convert('RGB').resize((768,576),Image.Resampling.LANCZOS));t=time.monotonic();labels,flows,_=model.eval(rgb,batch_size=1,channel_axis=-1,normalize=True,diameter=None,flow_threshold=.4,cellprob_threshold=0.,min_size=15,max_size_fraction=.4,niter=None,augment=False,tile_overlap=.1,bsize=384,resample=True,compute_masks=True);seconds=time.monotonic()-t;labels=np.asarray(labels);prob=np.asarray(flows[2]);flow=np.asarray(flows[1]);assert labels.shape==prob.shape==(576,768) and np.isfinite(prob).all() and np.isfinite(flow).all();ids=[int(x) for x in np.unique(labels) if x!=0];ranking=sorted([{'id':str(x),'mean_cellprob':float(prob[labels==x].mean()),'area':int((labels==x).sum())} for x in ids],key=lambda x:(-x['mean_cellprob'],int(x['id'])));archive=O/f'cellpose-{ident}.npz';np.savez_compressed(archive,labels=labels,cellprob=prob,flow=flow);rec={'id':ident,'protocol_sha256':sha(O/'protocol.json'),'archive':archive.name,'archive_sha256':sha(archive),'ranking':ranking,'seconds_inference':round(seconds,3)};checkpoint.write_text(json.dumps(rec,indent=2)+'\n');records.append(rec);update('Cellpose inference',n,len(source),f'Case {ident}: saved {len(ranking)} candidate masks.');print(f'{n}/24 case {ident}: {len(ranking)} masks, {seconds:.1f}s',flush=True)
 (O/'cellpose.json').write_text(json.dumps({'format':'r80-cellpose-v1','protocol_sha256':sha(O/'protocol.json'),'records':records,'warning':'Labels are pixel-exclusive; no complete overlapping-mask inference.'},indent=2)+'\n');update('Cellpose complete',len(source),len(source),'All masks saved; scoring frozen rankings next.')
if __name__=='__main__':main()
