Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torchvision.transforms as transforms
|
4 |
+
from PIL import Image
|
5 |
+
import gradio as gr
|
6 |
+
|
7 |
+
# Load your trained model
|
8 |
+
with torch.no_grad():
|
9 |
+
model = torch.load('classifier.pt')
|
10 |
+
|
11 |
+
# Define the preprocessing function for the input image
|
12 |
+
def preprocess(image):
|
13 |
+
transform = transforms.Compose([
|
14 |
+
transforms.Resize((224, 224)),
|
15 |
+
transforms.ToTensor(),
|
16 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
17 |
+
])
|
18 |
+
image = Image.fromarray(image.astype('uint8'), 'RGB')
|
19 |
+
image = transform(image)
|
20 |
+
return image.unsqueeze(0)
|
21 |
+
|
22 |
+
# Define the predict function
|
23 |
+
def predict(image):
|
24 |
+
# Preprocess the image
|
25 |
+
input_tensor = preprocess(image)
|
26 |
+
|
27 |
+
# Make a prediction
|
28 |
+
with torch.no_grad():
|
29 |
+
output = model(input_tensor)
|
30 |
+
|
31 |
+
# Perform post-processing if needed (e.g., softmax for probabilities)
|
32 |
+
# Replace this with your actual post-processing logic
|
33 |
+
probabilities = torch.softmax(output, dim=1).squeeze().tolist()
|
34 |
+
|
35 |
+
# Map the class indices to class labels
|
36 |
+
class_labels = ["Class1", "Class2", "Class3", "Class4"]
|
37 |
+
|
38 |
+
# Create a dictionary with class labels and probabilities
|
39 |
+
predictions = {label: prob for label, prob in zip(class_labels, probabilities)}
|
40 |
+
|
41 |
+
return predictions
|
42 |
+
|
43 |
+
# Create the Gradio interface
|
44 |
+
iface = gr.Interface(
|
45 |
+
fn=predict,
|
46 |
+
inputs=gr.Image(),
|
47 |
+
outputs=gr.Label(num_top_classes=4),
|
48 |
+
live=True
|
49 |
+
)
|
50 |
+
|
51 |
+
# Launch the Gradio app
|
52 |
+
iface.launch()
|