grantpitt commited on
Commit
7755815
1 Parent(s): ce19dc9

add custom handler

Browse files
Files changed (1) hide show
  1. handler.py +37 -0
handler.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import CLIPTokenizer, CLIPModel
3
+ import numpy as np
4
+ import os
5
+ import torch
6
+
7
+
8
+ class EndpointHandler:
9
+ def __init__(self, path="."):
10
+ # load the model
11
+ 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
+ kwargs
20
+ Return:
21
+ A :obj:`list` | `dict`: will be serialized and returned
22
+ """
23
+ # compute the embedding of the input
24
+ query = data["inputs"]
25
+ inputs = self.tokenizer(query, padding=True, return_tensors="pt").to(
26
+ self.device
27
+ )
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 embedding
35
+ input_embedding /= np.linalg.norm(input_embedding)
36
+
37
+ return input_embedding.tolist()