fashion-clip / handler.py
EMaghakyan's picture
Removed hardcoded url
17063fb
raw
history blame
1.16 kB
from typing import Dict, List, Any
from transformers import CLIPModel, AutoProcessor, AutoTokenizer
import torch
from PIL import Image
import requests
class EndpointHandler:
def __init__(self, path=""):
self.model = CLIPModel.from_pretrained("patrickjohncyh/fashion-clip")
self.processor = AutoProcessor.from_pretrained("patrickjohncyh/fashion-clip")
self.tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
parameters = data.pop("parameters", {"mode": "text"})
inputs = data.pop("inputs", data)
with torch.no_grad():
if parameters["mode"] == "text":
inputs = self.tokenizer(inputs, padding=True, return_tensors="pt")
features = self.model.get_text_features(**inputs)
if parameters["mode"] == "image":
image = Image.open(requests.get(inputs, stream=True).raw)
inputs = self.processor(images=image, return_tensors="pt")
features = self.model.get_image_features(**inputs)
return features[0].tolist()