Local preservation snapshot, not a new deployment or simulation acceptance.
70 lines
3.5 KiB
Python
70 lines
3.5 KiB
Python
"""Pinned OneFormer comparison on recorded views; no rover commands."""
|
|
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 CLIPTokenizer, OneFormerConfig, OneFormerForUniversalSegmentation, OneFormerProcessor, OneFormerImageProcessor
|
|
|
|
|
|
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)
|
|
assets = Path('/assets')
|
|
descriptor = json.loads(Path('/adapter/model.json').read_text())
|
|
for name, expected in descriptor['files'].items():
|
|
assert sha(assets/name) == expected, name
|
|
metadata = json.loads(Path('/adapter/metadata-source.json').read_text())
|
|
assert sha(Path('/adapter/ade20k_panoptic.json')) == metadata['sha256']
|
|
config = json.loads((assets/'preprocessor_config.json').read_text())
|
|
config['repo_path'] = '/adapter'
|
|
processor = OneFormerProcessor(image_processor=OneFormerImageProcessor(**config),
|
|
tokenizer=CLIPTokenizer.from_pretrained(assets, local_files_only=True))
|
|
model = OneFormerForUniversalSegmentation(OneFormerConfig.from_pretrained(assets, local_files_only=True))
|
|
state = torch.load(assets/'pytorch_model.bin', weights_only=True, map_location='cpu')
|
|
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']
|
|
original=Image.open(path).convert('RGB')
|
|
for crop in (True,False):
|
|
side=min(original.size);x=(original.width-side)//2;y=(original.height-side)//2
|
|
image=original.crop((x,y,x+side,y+side)) if crop else original
|
|
inputs=processor(images=image,task_inputs=['semantic'],return_tensors='pt').to('cuda')
|
|
torch.cuda.synchronize();begin=time.monotonic()
|
|
with torch.inference_mode():
|
|
prediction=model(**inputs)
|
|
labels=processor.post_process_semantic_segmentation(prediction,target_sizes=[(image.height,image.width)])[0].cpu().numpy().astype(np.uint8)
|
|
torch.cuda.synchronize();elapsed=time.monotonic()-begin
|
|
name=path.stem+('-crop' if crop else '-full')
|
|
Image.fromarray(labels).save(output/(name+'.labels.png'))
|
|
colors=np.zeros((*labels.shape,3),dtype=np.uint8)
|
|
colors[np.isin(labels,(11,52))]=[20,220,170];colors[labels==6]=[220,40,50]
|
|
Image.blend(image,Image.fromarray(colors),.45).save(output/(name+'.jpg'))
|
|
ids,counts=np.unique(labels,return_counts=True)
|
|
row=dict(case=name,source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),inference_seconds=elapsed,
|
|
sidewalk_fraction=float(np.isin(labels,(11,52)).mean()),road_fraction=float((labels==6).mean()),
|
|
classes={model.config.id2label[int(i)]:int(n) for i,n in zip(ids,counts)})
|
|
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()
|