File size: 2,695 Bytes
90a248e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Frozen original YOLOE+SAM3, shared by initialization and recovery."""
from pathlib import Path
import os,hashlib
import numpy as np
import torch

class Recognizer:
    def __init__(self,root):
        from ultralytics import YOLOE
        import ultralytics.nn.text_model as tm
        import sam3.model_builder as builder
        from sam3.model.sam3_image_processor import Sam3Processor
        root=Path(root);weights=root/'playground/Pretrained_models/YOLOE/yoloe-11l-seg.pt'
        assert hashlib.sha256(weights.read_bytes()).hexdigest()=='a993fb0fc7c8830939ae14e6434a925dd1179428158c2761482eb8a8d8a3699f'
        self.yolo=YOLOE(str(weights)).to('cuda:0')
        old=tm.build_text_model
        tm.build_text_model=lambda variant,device=None:tm.MobileCLIP('blt',device) if variant=='mobileclip:blt' else old(variant,device)
        cwd=Path.cwd()
        try:
            os.chdir(weights.parent);names=['bowl','plate'];self.yolo.set_classes(names,self.yolo.get_text_pe(names))
        finally:os.chdir(cwd)
        def checked(model,path):
            checkpoint=torch.load(path,map_location='cpu',weights_only=True);checkpoint=checkpoint.get('model',checkpoint)
            weights={k.replace('detector.',''):v for k,v in checkpoint.items() if 'detector' in k}
            weights.update({k.replace('tracker.','inst_interactive_predictor.model.'):v for k,v in checkpoint.items() if 'tracker' in k})
            result=model.load_state_dict(weights,strict=False)
            assert not(set(dict(model.named_parameters()))&set(result.missing_keys))
        builder._load_checkpoint=checked
        self.sam=builder.build_sam3_image_model(checkpoint_path=str(root/'playground/Pretrained_models/SAM3/sam3.pt'),load_from_HF=False,enable_inst_interactivity=True).eval().requires_grad_(False)
        self.processor=Sam3Processor(self.sam)
    @torch.inference_mode()
    def __call__(self,image):
        out=[]
        pred=self.yolo.predict(image,imgsz=640,conf=.15,iou=.5,device=0,verbose=False,retina_masks=True)[0]
        if pred.masks is not None:
            for m,c,s in zip(pred.masks.data,pred.boxes.cls,pred.boxes.conf):out.append(dict(mask=m.cpu().numpy()>.5,label=pred.names[int(c)],score=float(s),backend='yoloe'))
        with torch.autocast('cuda',dtype=torch.bfloat16):
            state=self.processor.set_image(image)
            for label in ['bowl','plate']:
                self.processor.reset_all_prompts(state);r=self.processor.set_text_prompt(label,state)
                for m,s in zip(r['masks'],r['scores']):
                    if float(s)>=.3:out.append(dict(mask=m.cpu().numpy().squeeze()>.5,label=label,score=float(s),backend='sam3'))
        return out