grantpitt/clip-vit-large-patch14-336
018
1from typing import Dict, List, Any2from transformers import CLIPTokenizer, CLIPModel3import numpy as np4import os5import torch6 7 8class EndpointHandler:9 def __init__(self, path="."):10 # load the model11 self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")12 self.model = CLIPModel.from_pretrained(path).to(self.device).eval()13 self.tokenizer = CLIPTokenizer.from_pretrained(path)14 15 def __call__(self, data: Dict[str, Any]) -> List[float]:16 """17 data args:18 inputs (:obj: `str` | `PIL.Image` | `np.array`)19 kwargs20 Return:21 A :obj:`list` | `dict`: will be serialized and returned22 """23 # compute the embedding of the input24 query = data["inputs"]25 inputs = self.tokenizer(query, padding=True, return_tensors="pt").to(26 self.device27 )28 with torch.no_grad():29 text_features = self.model.get_text_features(**inputs)30 31 text_features = text_features.cpu().detach().numpy()32 input_embedding = text_features[0]33 34 # normalize the embedding35 input_embedding /= np.linalg.norm(input_embedding)36 37 return input_embedding.tolist()38 