ass handler
Browse files- .gitignore +1 -0
- handler.py +31 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
handler.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from transformers import CLIPTokenizer, CLIPModel
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class EndpointHandler:
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
# load the model
|
| 9 |
+
repo_id = "openai/clip-vit-large-patch14-336"
|
| 10 |
+
self.model = CLIPModel.from_pretrained(repo_id)
|
| 11 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(repo_id)
|
| 12 |
+
|
| 13 |
+
def __call__(self, data: Dict[str, Any]) -> List[float]:
|
| 14 |
+
"""
|
| 15 |
+
data args:
|
| 16 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
| 17 |
+
kwargs
|
| 18 |
+
Return:
|
| 19 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
| 20 |
+
"""
|
| 21 |
+
# compute the embedding of the input
|
| 22 |
+
query = data["inputs"]
|
| 23 |
+
inputs = self.tokenizer(query, padding=True, return_tensors="pt")
|
| 24 |
+
text_features = self.model.get_text_features(**inputs)
|
| 25 |
+
text_features = text_features.detach().numpy()
|
| 26 |
+
input_embedding = text_features[0]
|
| 27 |
+
|
| 28 |
+
# normalize the embedding
|
| 29 |
+
input_embedding = input_embedding / np.linalg.norm(input_embedding)
|
| 30 |
+
|
| 31 |
+
return input_embedding.tolist()
|