Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
+
# Import necessary libraries
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torchvision import transforms
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# Download the labels file if not present
|
| 11 |
+
os.system("wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt")
|
| 12 |
+
|
| 13 |
+
# Load ResNet model
|
| 14 |
+
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True).eval()
|
| 15 |
+
|
| 16 |
+
# Function for model inference
|
| 17 |
+
def inference(input_image):
|
| 18 |
+
try:
|
| 19 |
+
# Preprocess the input image
|
| 20 |
+
preprocess = transforms.Compose([
|
| 21 |
+
transforms.Resize(256),
|
| 22 |
+
transforms.CenterCrop(224),
|
| 23 |
+
transforms.ToTensor(),
|
| 24 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
input_tensor = preprocess(input_image)
|
| 28 |
+
input_batch = input_tensor.unsqueeze(0) # Create a mini-batch as expected by the model
|
| 29 |
+
|
| 30 |
+
# Move the input and model to GPU for speed if available
|
| 31 |
+
if torch.cuda.is_available():
|
| 32 |
+
input_batch = input_batch.to('cuda')
|
| 33 |
+
model.to('cuda')
|
| 34 |
+
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
output = model(input_batch)
|
| 37 |
+
|
| 38 |
+
# The output has unnormalized scores. To get probabilities, run a softmax on it.
|
| 39 |
+
probabilities = torch.nn.functional.softmax(output[0], dim=0)
|
| 40 |
+
|
| 41 |
+
# Read the categories from the labels file
|
| 42 |
+
with open("imagenet_classes.txt", "r") as f:
|
| 43 |
+
categories = [s.strip() for s in f.readlines()]
|
| 44 |
+
|
| 45 |
+
# Show top categories per image
|
| 46 |
+
top5_prob, top5_catid = torch.topk(probabilities, 5)
|
| 47 |
+
result = {categories[top5_catid[i]]: top5_prob[i].item() for i in range(top5_prob.size(0))}
|
| 48 |
+
|
| 49 |
+
return result
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return {"error": str(e)}
|
| 52 |
+
|
| 53 |
+
# Gradio Interface setup
|
| 54 |
+
inputs = gr.Image(type='pil', label="Upload Image")
|
| 55 |
+
outputs = gr.Label(num_top_classes=5, label="Predictions") # Removed 'type' parameter
|
| 56 |
+
|
| 57 |
+
# Launch Gradio Interface
|
| 58 |
+
gr.Interface(inference, inputs, outputs, title="ResNet Image Classifier", description="Classify images using ResNet", analytics_enabled=False).launch()
|