Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from fastai.learner import load_learner
|
3 |
+
from fastai.vision.all import *
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
|
6 |
+
# Load the trained model
|
7 |
+
learn = load_learner('emotion_model')
|
8 |
+
|
9 |
+
# Define function to preprocess image
|
10 |
+
def preprocess_image(image):
|
11 |
+
# Convert image to PILImage
|
12 |
+
image_pil = PILImage.create(image)
|
13 |
+
# Apply same transformations as done during training
|
14 |
+
image_resized = Resize(224)(image_pil)
|
15 |
+
return image_resized
|
16 |
+
|
17 |
+
# Define function to predict emotion and generate confidence bar chart
|
18 |
+
def predict_emotion(image):
|
19 |
+
# Preprocess the image
|
20 |
+
processed_image = preprocess_image(image)
|
21 |
+
# Predict the emotion
|
22 |
+
pred_class, pred_idx, outputs = learn.predict(processed_image)
|
23 |
+
# Get class names
|
24 |
+
class_names = learn.dls.vocab
|
25 |
+
# Generate confidence values
|
26 |
+
confidences = [outputs[idx].item() for idx in range(len(outputs))]
|
27 |
+
# Generate bar chart
|
28 |
+
plt.bar(class_names, confidences)
|
29 |
+
plt.xlabel('Emotion')
|
30 |
+
plt.ylabel('Confidence')
|
31 |
+
plt.title('Confidence of Predicted Emotions')
|
32 |
+
plt.xticks(rotation=45)
|
33 |
+
plt.tight_layout()
|
34 |
+
return plt
|
35 |
+
|
36 |
+
# Define Gradio interface
|
37 |
+
iface = gr.Interface(
|
38 |
+
fn=predict_emotion,
|
39 |
+
inputs="image",
|
40 |
+
outputs="plot",
|
41 |
+
title="Emotion Prediction",
|
42 |
+
description="Upload an image and get the confidence of predicted emotions",
|
43 |
+
interpretation="default",
|
44 |
+
live=True
|
45 |
+
)
|
46 |
+
|
47 |
+
# Launch the interface
|
48 |
+
iface.launch()
|