Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModel, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
import json
|
| 5 |
+
import requests
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from torchvision import transforms
|
| 8 |
+
import urllib.request
|
| 9 |
+
|
| 10 |
+
# Load the label-to-class mapping from your Hugging Face repository
|
| 11 |
+
label_map_url = "https://huggingface.co/Maverick98/EcommerceClassifier/resolve/main/label_to_class.json"
|
| 12 |
+
label_to_class = requests.get(label_map_url).json()
|
| 13 |
+
|
| 14 |
+
# Load the model and tokenizer from your Hugging Face repository
|
| 15 |
+
model = AutoModel.from_pretrained("Maverick98/EcommerceClassifier")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained("jinaai/jina-embeddings-v2-base-en")
|
| 17 |
+
|
| 18 |
+
# Define image preprocessing
|
| 19 |
+
transform = transforms.Compose([
|
| 20 |
+
transforms.Resize((224, 224)),
|
| 21 |
+
transforms.ToTensor(),
|
| 22 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 23 |
+
])
|
| 24 |
+
|
| 25 |
+
def load_image(image_path_or_url):
|
| 26 |
+
"""
|
| 27 |
+
Load an image from a URL or local path and preprocess it.
|
| 28 |
+
"""
|
| 29 |
+
if image_path_or_url.startswith("http"):
|
| 30 |
+
with urllib.request.urlopen(image_path_or_url) as url:
|
| 31 |
+
image = Image.open(url).convert('RGB')
|
| 32 |
+
else:
|
| 33 |
+
image = Image.open(image_path_or_url).convert('RGB')
|
| 34 |
+
|
| 35 |
+
image = transform(image)
|
| 36 |
+
image = image.unsqueeze(0) # Add batch dimension
|
| 37 |
+
return image
|
| 38 |
+
|
| 39 |
+
def predict(image_path_or_url, title, threshold=0.7):
|
| 40 |
+
"""
|
| 41 |
+
Predict the top 3 categories for the given image and title.
|
| 42 |
+
Includes "Others" if the confidence of the top prediction is below the threshold.
|
| 43 |
+
"""
|
| 44 |
+
# Preprocess the image
|
| 45 |
+
image = load_image(image_path_or_url)
|
| 46 |
+
|
| 47 |
+
# Tokenize the title
|
| 48 |
+
title_encoding = tokenizer(title, padding='max_length', max_length=32, truncation=True, return_tensors='pt')
|
| 49 |
+
input_ids = title_encoding['input_ids']
|
| 50 |
+
attention_mask = title_encoding['attention_mask']
|
| 51 |
+
|
| 52 |
+
# Predict
|
| 53 |
+
model.eval()
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
output = model(image, input_ids=input_ids, attention_mask=attention_mask)
|
| 56 |
+
probabilities = torch.nn.functional.softmax(output, dim=1)
|
| 57 |
+
top3_probabilities, top3_indices = torch.topk(probabilities, 3, dim=1)
|
| 58 |
+
|
| 59 |
+
# Map the top 3 indices to class names
|
| 60 |
+
top3_classes = [label_to_class[str(idx.item())] for idx in top3_indices[0]]
|
| 61 |
+
|
| 62 |
+
# Check if the highest probability is below the threshold
|
| 63 |
+
if top3_probabilities[0][0].item() < threshold:
|
| 64 |
+
top3_classes.insert(0, "Others")
|
| 65 |
+
top3_probabilities = torch.cat((torch.tensor([[1.0 - top3_probabilities[0][0].item()]]), top3_probabilities), dim=1)
|
| 66 |
+
|
| 67 |
+
# Prepare the output as a dictionary
|
| 68 |
+
results = {}
|
| 69 |
+
for i in range(len(top3_classes)):
|
| 70 |
+
results[top3_classes[i]] = top3_probabilities[0][i].item()
|
| 71 |
+
|
| 72 |
+
return results
|
| 73 |
+
|
| 74 |
+
# Define the Gradio interface
|
| 75 |
+
title_input = gr.inputs.Textbox(label="Product Title", placeholder="Enter the product title here...")
|
| 76 |
+
image_input = gr.inputs.Textbox(label="Image URL or Path", placeholder="Enter image URL or local path here...")
|
| 77 |
+
output = gr.outputs.JSON(label="Top 3 Predictions with Probabilities")
|
| 78 |
+
|
| 79 |
+
gr.Interface(
|
| 80 |
+
fn=predict,
|
| 81 |
+
inputs=[image_input, title_input],
|
| 82 |
+
outputs=output,
|
| 83 |
+
title="Ecommerce Classifier",
|
| 84 |
+
description="This model classifies ecommerce products into one of 434 categories. If the model is unsure, it outputs 'Others'.",
|
| 85 |
+
).launch()
|