Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
3 |
+
from PIL import Image
|
4 |
+
import requests
|
5 |
+
from io import BytesIO
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
# Load the pre-trained model and tokenizer
|
9 |
+
model_name = "distilbert/distilbert-base-uncased"
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
11 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
12 |
+
|
13 |
+
# Function to preprocess the image
|
14 |
+
def preprocess_image(image):
|
15 |
+
image = Image.open(BytesIO(image))
|
16 |
+
image = image.resize((256, 256)) # Resize the image to match the model's input size
|
17 |
+
return np.array(image)
|
18 |
+
|
19 |
+
# Function to make predictions
|
20 |
+
def classify_image(image):
|
21 |
+
image = preprocess_image(image)
|
22 |
+
inputs = tokenizer(image, return_tensors="pt", padding=True, truncation=True)
|
23 |
+
outputs = model(**inputs)
|
24 |
+
logits = outputs.logits.detach().numpy()[0]
|
25 |
+
probabilities = np.exp(logits) / np.exp(logits).sum(-1)
|
26 |
+
predicted_class = np.argmax(probabilities)
|
27 |
+
return {str(i): float(prob) for i, prob in enumerate(probabilities)}
|
28 |
+
|
29 |
+
# Create a Gradio interface
|
30 |
+
input_image = gr.inputs.Image(shape=(256, 256))
|
31 |
+
output_label = gr.outputs.Label(num_top_classes=3)
|
32 |
+
gr.Interface(classify_image, inputs=input_image, outputs=output_label).launch()
|