Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForImageClassification, AutoImageProcessor
|
3 |
+
from PIL import Image
|
4 |
+
from torchvision import transforms
|
5 |
+
|
6 |
+
# Load your model and processor from Hugging Face Hub
|
7 |
+
model_name = "1ancelot/base_rn"
|
8 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Define the same preprocessing transformations as for validation
|
11 |
+
val_test_resnet_combined_transforms = transforms.Compose([
|
12 |
+
transforms.Resize((224, 224)),
|
13 |
+
transforms.ToTensor(), # Convert image to tensor
|
14 |
+
transforms.Lambda(lambda img: processor(images=img, return_tensors="pt")['pixel_values'].squeeze(0))
|
15 |
+
])
|
16 |
+
|
17 |
+
# Define the prediction function
|
18 |
+
def predict(img):
|
19 |
+
# Apply the same preprocessing transformations
|
20 |
+
img = val_test_resnet_combined_transforms(img)
|
21 |
+
|
22 |
+
# Unsqueeze the image to add batch dimension, as the model expects batch input
|
23 |
+
img = img.unsqueeze(0)
|
24 |
+
|
25 |
+
# Perform inference
|
26 |
+
outputs = model(img)
|
27 |
+
|
28 |
+
# Assuming the model returns logits
|
29 |
+
logits = outputs.logits
|
30 |
+
predicted_class = logits.argmax(-1).item() # Get the predicted class index
|
31 |
+
|
32 |
+
# Return the class as a text output
|
33 |
+
return f"Predicted class: {predicted_class}"
|
34 |
+
|
35 |
+
# Create the Gradio interface
|
36 |
+
iface = gr.Interface(
|
37 |
+
fn=predict,
|
38 |
+
inputs=gr.Image(type="pil"), # Input is a PIL image
|
39 |
+
outputs="text", # Output is the predicted class as text
|
40 |
+
title="Image Classification with base_rn"
|
41 |
+
)
|
42 |
+
|
43 |
+
# Launch the app
|
44 |
+
iface.launch()
|