Spaces:
Running on Zero
Running on Zero
Download src/analyzer.py from shashankheg/FashionLensAI: direct link, hf CLI and curl.
- Browser
- Download file 1.65 kB
-
https://huggingface.co/spaces/shashankheg/FashionLensAI/resolve/main/src/analyzer.py
- Command line
-
hf download hf://spaces/shashankheg/FashionLensAI/src/analyzer.py
-
curl -L -o analyzer.py https://huggingface.co/spaces/shashankheg/FashionLensAI/resolve/main/src/analyzer.py
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) |