"""Text-conditioned segmentation qualification, with no navigation authority.""" import hashlib import json import time from datetime import datetime, timezone from pathlib import Path import numpy as np import torch from PIL import Image from transformers import CLIPSegConfig, CLIPSegForImageSegmentation, CLIPSegProcessor PROMPTS = ['sidewalk', 'road', 'crosswalk', 'building', 'wall', 'vegetation', 'stairs'] def sha(path): digest = hashlib.sha256() with path.open('rb') as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b''): digest.update(chunk) return digest.hexdigest() def main(): torch.set_num_threads(3) root = Path('/assets') descriptor = json.loads(Path('/adapter/model.json').read_text()) for name, expected in descriptor['files'].items(): assert sha(root / name) == expected, name processor = CLIPSegProcessor.from_pretrained(root, local_files_only=True) model = CLIPSegForImageSegmentation(CLIPSegConfig.from_pretrained(root, local_files_only=True)) state = torch.load(root / 'pytorch_model.bin', weights_only=True, map_location='cpu') # Legacy Transformers saved these deterministic buffers; current versions # regenerate them. Verify equality before removing only those extra keys. for key in ('clip.text_model.embeddings.position_ids', 'clip.vision_model.embeddings.position_ids'): if key in state and key not in model.state_dict(): assert torch.equal(state.pop(key), model.get_buffer(key)), key model.load_state_dict(state, strict=True) del state model.cuda().eval() rows = [] output = Path('/evidence') for source in json.loads(Path('/inputs/manifest.json').read_text()): path = Path('/inputs') / source['file'] assert sha(path) == source['sha256'] image = Image.open(path).convert('RGB') inputs = processor(text=PROMPTS, images=[image] * len(PROMPTS), padding=True, return_tensors='pt').to('cuda') torch.cuda.synchronize() begin = time.monotonic() with torch.inference_mode(): logits = model(**inputs).logits logits = torch.nn.functional.interpolate(logits[:,None], size=(image.height,image.width), mode='bilinear', align_corners=False)[:,0] scores = logits.sigmoid().cpu().numpy() torch.cuda.synchronize() elapsed = time.monotonic() - begin # Scores for separate prompts are diagnostic similarities, not calibrated probabilities. labels = scores.argmax(axis=0) known = scores.max(axis=0) >= .5 colors = np.zeros((*labels.shape,3), dtype=np.uint8) for label,color in [(0,[20,220,170]),(1,[220,40,50]),(2,[240,200,20])]: colors[(labels==label)&known] = color Image.blend(image,Image.fromarray(colors),.45).save(output/(path.stem+'.jpg')) np.savez_compressed(output/(path.stem+'.npz'),scores=scores.astype(np.float16),prompts=np.array(PROMPTS)) row=dict(source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),inference_seconds=elapsed, fractions={prompt:float(((labels==i)&known).mean()) for i,prompt in enumerate(PROMPTS)}, max_scores={prompt:float(scores[i].max()) for i,prompt in enumerate(PROMPTS)}) rows.append(row) (output/'results.json').write_text(json.dumps(rows,indent=2)) print(json.dumps(row),flush=True) (output/'artifact-sha256.json').write_text(json.dumps({p.name:sha(p) for p in output.iterdir() if p.is_file()},indent=2)) if __name__=='__main__': main()