Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PIL import Image
|
3 |
+
from transformers import pipeline
|
4 |
+
import pandas as pd
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
|
7 |
+
# Disable PyplotGlobalUseWarning
|
8 |
+
st.set_option('deprecation.showPyplotGlobalUse', False)
|
9 |
+
|
10 |
+
# Create an image classification pipeline with scores
|
11 |
+
pipe = pipeline("image-classification", model="trpakov/vit-face-expression", top_k=None)
|
12 |
+
|
13 |
+
# Streamlit app
|
14 |
+
st.title("Emotion Recognition with vit-face-expression")
|
15 |
+
|
16 |
+
# Upload images
|
17 |
+
uploaded_images = st.file_uploader("Upload images", type=["jpg", "png"], accept_multiple_files=True)
|
18 |
+
|
19 |
+
# Store selected file names
|
20 |
+
selected_file_names = []
|
21 |
+
|
22 |
+
# Display thumbnail images alongside file names and sizes in the sidebar
|
23 |
+
selected_images = []
|
24 |
+
if uploaded_images:
|
25 |
+
|
26 |
+
# Add a "Select All" checkbox in the sidebar
|
27 |
+
select_all = st.sidebar.checkbox("Select All", False)
|
28 |
+
|
29 |
+
for idx, img in enumerate(uploaded_images):
|
30 |
+
image = Image.open(img)
|
31 |
+
checkbox_key = f"{img.name}_checkbox_{idx}" # Unique key for each checkbox
|
32 |
+
# Display thumbnail image and checkbox in sidebar
|
33 |
+
st.sidebar.image(image, caption=f"{img.name} {img.size / 1024.0:.1f} KB", width=40)
|
34 |
+
#selected = st.sidebar.checkbox(f"Select {img.name}", value=False, key=checkbox_key)
|
35 |
+
# If "Select All" is checked, all individual checkboxes are selected
|
36 |
+
selected = st.sidebar.checkbox(f"Select {img.name}", value=select_all, key=checkbox_key)
|
37 |
+
|
38 |
+
|
39 |
+
if selected:
|
40 |
+
selected_images.append(image)
|
41 |
+
selected_file_names.append(img.name)
|
42 |
+
|
43 |
+
if st.button("Predict Emotions") and selected_images:
|
44 |
+
emotions = []
|
45 |
+
if len(selected_images) == 2:
|
46 |
+
# Predict emotion for each selected image using the pipeline
|
47 |
+
results = [pipe(image) for image in selected_images]
|
48 |
+
|
49 |
+
# Display images and predicted emotions side by side
|
50 |
+
col1, col2 = st.columns(2)
|
51 |
+
for i in range(2):
|
52 |
+
predicted_class = results[i][0]["label"]
|
53 |
+
predicted_emotion = predicted_class.split("_")[-1].capitalize()
|
54 |
+
emotions.append(predicted_emotion)
|
55 |
+
col = col1 if i == 0 else col2
|
56 |
+
col.image(selected_images[i], caption=f"Predicted emotion: {predicted_emotion}", use_column_width=True)
|
57 |
+
col.write(f"Emotion Scores: {predicted_emotion}: {results[i][0]['score']:.4f}")
|
58 |
+
# Use the index to get the corresponding filename
|
59 |
+
col.write(f"Original File Name: {selected_file_names[i]}")
|
60 |
+
|
61 |
+
# Display the keys and values of all results
|
62 |
+
st.write("Keys and Values of all results:")
|
63 |
+
col1, col2 = st.columns(2)
|
64 |
+
for i, result in enumerate(results):
|
65 |
+
col = col1 if i == 0 else col2
|
66 |
+
col.write(f"Keys and Values of results[{i}]:")
|
67 |
+
for res in result:
|
68 |
+
label = res["label"]
|
69 |
+
score = res["score"]
|
70 |
+
col.write(f"{label}: {score:.4f}")
|
71 |
+
else:
|
72 |
+
# Predict emotion for each selected image using the pipeline
|
73 |
+
results = [pipe(image) for image in selected_images]
|
74 |
+
|
75 |
+
# Display images and predicted emotions
|
76 |
+
for i, (image, result) in enumerate(zip(selected_images, results)):
|
77 |
+
predicted_class = result[0]["label"]
|
78 |
+
predicted_emotion = predicted_class.split("_")[-1].capitalize()
|
79 |
+
emotions.append(predicted_emotion)
|
80 |
+
st.image(image, caption=f"Predicted emotion: {predicted_emotion}", use_column_width=True)
|
81 |
+
st.write(f"Emotion Scores for #{i+1} Image")
|
82 |
+
st.write(f"{predicted_emotion}: {result[0]['score']:.4f}")
|
83 |
+
# Use the index to get the corresponding filename
|
84 |
+
st.write(f"Original File Name: {selected_file_names[i] if i < len(selected_file_names) else 'Unknown'}")
|
85 |
+
|
86 |
+
# Calculate emotion statistics
|
87 |
+
emotion_counts = pd.Series(emotions).value_counts()
|
88 |
+
|
89 |
+
# Define a color map that matches the emotions to specific colors
|
90 |
+
color_map = {
|
91 |
+
'Neutral': '#B38B6D', # Taupe
|
92 |
+
'Happy': '#FFFF00', # Yellow
|
93 |
+
'Sad': '#0000FF', # Blue
|
94 |
+
'Angry': '#FF0000', # Red
|
95 |
+
'Disgust': '#008000', # Green
|
96 |
+
'Surprise': '#FFA500', # Orange (Bright)
|
97 |
+
'Fear': '#000000' # Black
|
98 |
+
# Add more emotions and their corresponding colors here
|
99 |
+
}
|
100 |
+
|
101 |
+
# Calculate the total number of faces analyzed
|
102 |
+
total_faces = len(selected_images)
|
103 |
+
|
104 |
+
# Use the color map to assign colors to the pie chart
|
105 |
+
pie_colors = [color_map.get(emotion, '#999999') for emotion in emotion_counts.index] # Default to grey if not found
|
106 |
+
|
107 |
+
# Plot pie chart with total faces in the title
|
108 |
+
st.write("Emotion Distribution (Pie Chart):")
|
109 |
+
fig_pie, ax_pie = plt.subplots()
|
110 |
+
#font color
|
111 |
+
ax_pie.pie(emotion_counts, labels=emotion_counts.index, autopct='%1.1f%%', startangle=140, colors=pie_colors, textprops={'color': 'white', 'weight': 'bold'})
|
112 |
+
|
113 |
+
ax_pie.pie(emotion_counts, labels=emotion_counts.index, autopct='%1.1f%%', startangle=140, colors=pie_colors)
|
114 |
+
ax_pie.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
|
115 |
+
# Add total faces to the title
|
116 |
+
ax_pie.set_title(f"Total Faces Analyzed: {total_faces}")
|
117 |
+
st.pyplot(fig_pie)
|
118 |
+
|
119 |
+
# Use the same color map for the bar chart
|
120 |
+
bar_colors = [color_map.get(emotion, '#999999') for emotion in emotion_counts.index] # Default to grey if not found
|
121 |
+
|
122 |
+
# Plot bar chart with total faces in the title
|
123 |
+
st.write("Emotion Distribution (Bar Chart):")
|
124 |
+
fig_bar, ax_bar = plt.subplots()
|
125 |
+
emotion_counts.plot(kind='bar', color=bar_colors, ax=ax_bar)
|
126 |
+
ax_bar.set_xlabel('Emotion')
|
127 |
+
ax_bar.set_ylabel('Count')
|
128 |
+
# Add total faces to the title
|
129 |
+
ax_bar.set_title(f"Emotion Distribution - Total Faces Analyzed: {total_faces}")
|
130 |
+
ax_bar.yaxis.set_major_locator(plt.MaxNLocator(integer=True)) # Ensure integer ticks on Y-axis
|
131 |
+
# Display bar values as integers
|
132 |
+
for i in ax_bar.patches:
|
133 |
+
ax_bar.text(i.get_x() + i.get_width() / 2, i.get_height() + 0.1, int(i.get_height()), ha='center', va='bottom')
|
134 |
+
|
135 |
+
st.pyplot(fig_bar)
|