File size: 1,928 Bytes
88e0bae c54b3d1 88e0bae c54b3d1 88e0bae c54b3d1 88e0bae c54b3d1 88e0bae c54b3d1 88e0bae c54b3d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
from typing import List, Dict
from PIL.Image import Image
import os
import torch
from transformers import AutoModel, AutoProcessor
MODEL_NAME = "Marqo/marqo-fashionCLIP"
HF_TOKEN = os.environ.get("HF_TOKEN")
class FashionCLIPEncoder:
def __init__(self):
self.device = torch.device("cpu")
self.processor = AutoProcessor.from_pretrained(
MODEL_NAME,
trust_remote_code=True,
token=HF_TOKEN
)
try:
self.model = AutoModel.from_pretrained(
MODEL_NAME,
trust_remote_code=True,
device_map=None,
token=HF_TOKEN
)
self.model = self.model.to(self.device)
self.model.eval()
except Exception as e:
print(f"Error initializing model: {str(e)}")
raise
def encode_text(self, texts: List[str]) -> List[List[float]]:
kwargs = {
"padding": "max_length",
"return_tensors": "pt",
"truncation": True,
}
inputs = self.processor(text=texts, **kwargs)
with torch.no_grad():
batch = {k: v.to(self.device) for k, v in inputs.items()}
return self._encode_text(batch)
def encode_images(self, images: List[Image]) -> List[List[float]]:
kwargs = {
"return_tensors": "pt",
}
inputs = self.processor(images=images, **kwargs)
with torch.no_grad():
batch = {k: v.to(self.device) for k, v in inputs.items()}
return self._encode_images(batch)
def _encode_text(self, batch: Dict) -> List[List[float]]:
return self.model.get_text_features(**batch).detach().cpu().numpy().tolist()
def _encode_images(self, batch: Dict) -> List[List[float]]:
return self.model.get_image_features(**batch).detach().cpu().numpy().tolist() |