Spaces:
No application file
No application file
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
# Step 1: Load the model and feature extractor
|
| 6 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224")
|
| 7 |
+
model = AutoModelForImageClassification.from_pretrained("google/vit-base-patch16-224")
|
| 8 |
+
|
| 9 |
+
# Step 2: Define the function for prediction
|
| 10 |
+
def recognize_image(image):
|
| 11 |
+
# Convert the input image to RGB
|
| 12 |
+
image = Image.fromarray(image).convert("RGB")
|
| 13 |
+
|
| 14 |
+
# Preprocess the image
|
| 15 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
| 16 |
+
|
| 17 |
+
# Make predictions
|
| 18 |
+
outputs = model(**inputs)
|
| 19 |
+
predicted_class_idx = outputs.logits.argmax(-1).item()
|
| 20 |
+
|
| 21 |
+
# Get the predicted class label
|
| 22 |
+
return model.config.id2label[predicted_class_idx]
|
| 23 |
+
|
| 24 |
+
# Step 3: Create a Gradio interface
|
| 25 |
+
app = gr.Interface(
|
| 26 |
+
fn=recognize_image, # Prediction function
|
| 27 |
+
inputs=gr.Image(type="numpy"), # Input: Image
|
| 28 |
+
outputs="text", # Output: Predicted label
|
| 29 |
+
title="Image Recognition App" # App title
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Launch the app
|
| 33 |
+
app.launch()
|