Upload handler.py
Browse files- handler.py +20 -0
handler.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import CLIPModel, CLIPProcessor
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 6 |
+
|
| 7 |
+
model = CLIPModel.from_pretrained(".").to(device)
|
| 8 |
+
processor = CLIPProcessor.from_pretrained(".")
|
| 9 |
+
|
| 10 |
+
def inference(inputs):
|
| 11 |
+
text = inputs.get("text", None)
|
| 12 |
+
|
| 13 |
+
if text:
|
| 14 |
+
processed = processor(text=[text], return_tensors="pt", truncation=True).to(device)
|
| 15 |
+
with torch.no_grad():
|
| 16 |
+
emb = model.get_text_features(**processed)
|
| 17 |
+
emb = torch.nn.functional.normalize(emb, dim=-1)
|
| 18 |
+
return emb.cpu().numpy().tolist()
|
| 19 |
+
|
| 20 |
+
return {"error": "No valid input provided"}
|