FashionLensAI / src /analyzer.py
shashankheg's picture
Fresh deployment commit
b35d642
Raw History Blame Contribute Delete
1.65 kB
from PIL import Image
import torch
from transformers import (
CLIPModel,
CLIPProcessor
)
class FashionAnalyzer:
def __init__(
self,
model_name="openai/clip-vit-base-patch32"
):
self.processor = CLIPProcessor.from_pretrained(
model_name
)
self.model = CLIPModel.from_pretrained(
model_name
)
self.model.eval()
self.categories = [
"t shirt",
"shirt",
"jeans",
"dress",
"watch",
"shoe",
"flip flop",
"jacket",
"hoodie",
"bag"
]
def analyze(
self,
image_path
):
image = Image.open(
image_path
).convert("RGB")
inputs = self.processor(
text=self.categories,
images=image,
return_tensors="pt",
padding=True
)
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs.logits_per_image
probs = logits.softmax(
dim=1
)
best_idx = probs.argmax(
dim=1
).item()
confidence = (
probs[0][best_idx].item()
* 100
)
return {
"category": self.categories[
best_idx
],
"confidence": round(
confidence,
2
)
}
if __name__ == "__main__":
analyzer = FashionAnalyzer()
result = analyzer.analyze(
"data/images/15970.jpg"
)
print(result)