Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torchvision.transforms as transforms
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from ResNet_for_CC import CC_model # Import updated model
|
| 6 |
+
|
| 7 |
+
# Set device (CPU/GPU)
|
| 8 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
+
|
| 10 |
+
# Load the trained CC_model
|
| 11 |
+
model_path = "CC_net.pt" # Ensure correct path
|
| 12 |
+
model = CC_model(num_classes1=14) # Updated model with classification
|
| 13 |
+
model.load_state_dict(torch.load(model_path, map_location=device))
|
| 14 |
+
model.to(device)
|
| 15 |
+
model.eval()
|
| 16 |
+
|
| 17 |
+
# Define Clothing1M Class Labels
|
| 18 |
+
class_labels = [
|
| 19 |
+
"T-Shirt", "Shirt", "Knitwear", "Chiffon", "Sweater", "Hoodie",
|
| 20 |
+
"Windbreaker", "Jacket", "Downcoat", "Suit", "Shawl", "Dress",
|
| 21 |
+
"Vest", "Underwear"
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
# Define preprocessing for images
|
| 25 |
+
transform = transforms.Compose([
|
| 26 |
+
transforms.Resize(256),
|
| 27 |
+
transforms.CenterCrop(224),
|
| 28 |
+
transforms.ToTensor(),
|
| 29 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
# Function for Image Classification
|
| 33 |
+
def classify_image(image):
|
| 34 |
+
image = transform(image).unsqueeze(0).to(device) # Preprocess image
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
_, output = model(image) # Unpack to get only output_mean
|
| 37 |
+
predicted_class = torch.argmax(output, dim=1).item() # Get class index
|
| 38 |
+
|
| 39 |
+
return f"Predicted Class: {class_labels[predicted_class]}"
|
| 40 |
+
|
| 41 |
+
# Create Gradio Interface
|
| 42 |
+
interface = gr.Interface(
|
| 43 |
+
fn=classify_image,
|
| 44 |
+
inputs=gr.Image(type="pil"),
|
| 45 |
+
outputs="text",
|
| 46 |
+
title="Clothing1M Image Classifier",
|
| 47 |
+
description="Upload a clothing image, and the model will classify it into one of the 14 categories."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Run the Interface
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
interface.launch()
|