Spaces:
Sleeping
Sleeping
iamomtiwari
commited on
Commit
•
7d859e4
1
Parent(s):
b28200c
Update app.py
Browse files
app.py
CHANGED
@@ -1,44 +1,47 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
|
6 |
-
# Load the
|
7 |
-
|
8 |
-
|
9 |
|
10 |
-
#
|
11 |
def predict(image):
|
12 |
try:
|
13 |
# Ensure the image is in PIL format
|
14 |
-
if isinstance(image,
|
15 |
-
image
|
16 |
-
|
17 |
-
# Preprocess the
|
18 |
-
inputs =
|
19 |
|
20 |
-
#
|
21 |
with torch.no_grad():
|
22 |
outputs = model(**inputs)
|
23 |
logits = outputs.logits
|
24 |
-
|
25 |
-
# Get the
|
26 |
predicted_class_idx = logits.argmax(-1).item()
|
27 |
|
28 |
-
#
|
29 |
predicted_class_label = model.config.id2label[predicted_class_idx]
|
30 |
-
|
31 |
return f"Predicted class: {predicted_class_label}"
|
32 |
|
33 |
except Exception as e:
|
34 |
return f"Error: {str(e)}"
|
35 |
|
36 |
-
# Create
|
37 |
-
interface = gr.Interface(
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
42 |
|
43 |
-
# Launch the
|
44 |
-
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
|
6 |
+
# Load the ResNet-50 model and feature extractor
|
7 |
+
model = AutoModelForImageClassification.from_pretrained("microsoft/resnet-50")
|
8 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/resnet-50")
|
9 |
|
10 |
+
# Define the prediction function
|
11 |
def predict(image):
|
12 |
try:
|
13 |
# Ensure the image is in PIL format
|
14 |
+
if not isinstance(image, Image.Image):
|
15 |
+
return "Invalid image format. Please upload a valid image."
|
16 |
+
|
17 |
+
# Preprocess the image using the feature extractor
|
18 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
19 |
|
20 |
+
# Perform inference
|
21 |
with torch.no_grad():
|
22 |
outputs = model(**inputs)
|
23 |
logits = outputs.logits
|
24 |
+
|
25 |
+
# Get the class with the highest score
|
26 |
predicted_class_idx = logits.argmax(-1).item()
|
27 |
|
28 |
+
# Map the predicted index to its human-readable label
|
29 |
predicted_class_label = model.config.id2label[predicted_class_idx]
|
30 |
+
|
31 |
return f"Predicted class: {predicted_class_label}"
|
32 |
|
33 |
except Exception as e:
|
34 |
return f"Error: {str(e)}"
|
35 |
|
36 |
+
# Create the Gradio interface
|
37 |
+
interface = gr.Interface(
|
38 |
+
fn=predict,
|
39 |
+
inputs=gr.Image(type="pil", label="Upload Image"),
|
40 |
+
outputs=gr.Text(label="Prediction"),
|
41 |
+
title="ResNet-50 Image Classification",
|
42 |
+
description="Upload an image to classify it into one of the ImageNet classes using the ResNet-50 model."
|
43 |
+
)
|
44 |
|
45 |
+
# Launch the app
|
46 |
+
if __name__ == "__main__":
|
47 |
+
interface.launch()
|