Update app.py
Browse files
app.py
CHANGED
|
@@ -1,106 +1,161 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
from transformers import pipeline
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import plotly.graph_objects as go
|
| 5 |
-
|
| 6 |
-
# Load the emotion classification model
|
| 7 |
-
model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion"
|
| 8 |
-
classifier = pipeline("text-classification", model=model_id)
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
demo.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import plotly.graph_objects as go
|
| 5 |
+
|
| 6 |
+
# Load the emotion classification model
|
| 7 |
+
model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion"
|
| 8 |
+
classifier = pipeline("text-classification", model=model_id)
|
| 9 |
+
|
| 10 |
+
# Define emotion labels
|
| 11 |
+
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
| 12 |
+
|
| 13 |
+
# Emoji mapping for emotions
|
| 14 |
+
EMOTION_EMOJIS = {
|
| 15 |
+
'sadness': 'π’',
|
| 16 |
+
'joy': 'π',
|
| 17 |
+
'love': 'β€οΈ',
|
| 18 |
+
'anger': 'π ',
|
| 19 |
+
'fear': 'π¨',
|
| 20 |
+
'surprise': 'π²'
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
def classify_emotion(text):
|
| 24 |
+
"""
|
| 25 |
+
Classify the emotion in the given text and return results with visualization
|
| 26 |
+
"""
|
| 27 |
+
if not text.strip():
|
| 28 |
+
return None, "Please enter some text to analyze."
|
| 29 |
+
|
| 30 |
+
# Get predictions
|
| 31 |
+
preds = classifier(text, return_all_scores=True)[0]
|
| 32 |
+
|
| 33 |
+
# Create DataFrame
|
| 34 |
+
df = pd.DataFrame(preds)
|
| 35 |
+
df['score'] = df['score'] * 100 # Convert to percentage
|
| 36 |
+
|
| 37 |
+
# Add emojis to labels
|
| 38 |
+
df['display_label'] = df['label'].map(lambda x: f"{EMOTION_EMOJIS.get(x, '')} {x.capitalize()}")
|
| 39 |
+
|
| 40 |
+
# Sort by score for better visualization
|
| 41 |
+
df = df.sort_values('score', ascending=True)
|
| 42 |
+
|
| 43 |
+
# Create horizontal bar chart using Plotly
|
| 44 |
+
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F']
|
| 45 |
+
|
| 46 |
+
fig = go.Figure(go.Bar(
|
| 47 |
+
x=df['score'],
|
| 48 |
+
y=df['display_label'],
|
| 49 |
+
orientation='h',
|
| 50 |
+
marker=dict(
|
| 51 |
+
color=df['score'],
|
| 52 |
+
colorscale='Viridis',
|
| 53 |
+
showscale=False
|
| 54 |
+
),
|
| 55 |
+
text=df['score'].round(2),
|
| 56 |
+
texttemplate='%{text}%',
|
| 57 |
+
textposition='outside'
|
| 58 |
+
))
|
| 59 |
+
|
| 60 |
+
fig.update_layout(
|
| 61 |
+
title={
|
| 62 |
+
'text': 'Emotion Classification Results',
|
| 63 |
+
'x': 0.5,
|
| 64 |
+
'xanchor': 'center'
|
| 65 |
+
},
|
| 66 |
+
xaxis_title='Confidence (%)',
|
| 67 |
+
yaxis_title='',
|
| 68 |
+
height=450,
|
| 69 |
+
margin=dict(l=20, r=80, t=60, b=40),
|
| 70 |
+
plot_bgcolor='rgba(0,0,0,0)',
|
| 71 |
+
paper_bgcolor='rgba(0,0,0,0)',
|
| 72 |
+
font=dict(size=12)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
fig.update_xaxis(range=[0, 105], gridcolor='lightgray')
|
| 76 |
+
|
| 77 |
+
# Format results as text with emojis
|
| 78 |
+
results_text = "### π― Prediction Results\n\n"
|
| 79 |
+
sorted_df = df.sort_values('score', ascending=False)
|
| 80 |
+
|
| 81 |
+
top_emotion = sorted_df.iloc[0]
|
| 82 |
+
results_text += f"**Top Emotion:** {EMOTION_EMOJIS.get(top_emotion['label'], '')} **{top_emotion['label'].capitalize()}** ({top_emotion['score']:.2f}%)\n\n"
|
| 83 |
+
results_text += "---\n\n**All Emotions:**\n\n"
|
| 84 |
+
|
| 85 |
+
for _, row in sorted_df.iterrows():
|
| 86 |
+
emoji = EMOTION_EMOJIS.get(row['label'], '')
|
| 87 |
+
bar_length = int(row['score'] / 5)
|
| 88 |
+
bar = 'β' * bar_length
|
| 89 |
+
results_text += f"{emoji} **{row['label'].capitalize()}**: {row['score']:.2f}% {bar}\n\n"
|
| 90 |
+
|
| 91 |
+
return fig, results_text
|
| 92 |
+
|
| 93 |
+
# Example texts
|
| 94 |
+
examples = [
|
| 95 |
+
["I was feeling very alone today walking down on road"],
|
| 96 |
+
["I am so happy and excited about this new opportunity!"],
|
| 97 |
+
["This makes me really angry and frustrated!"],
|
| 98 |
+
["I'm scared about what might happen next..."],
|
| 99 |
+
["What a beautiful day, I love this!"],
|
| 100 |
+
["Wow! I can't believe this just happened!"],
|
| 101 |
+
["I feel so sad and disappointed about the news."]
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
# Create Gradio interface
|
| 105 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Emotion Classifier") as demo:
|
| 106 |
+
gr.Markdown(
|
| 107 |
+
"""
|
| 108 |
+
# π Emotion Classification
|
| 109 |
+
Analyze the emotional tone of any text using AI. This model can detect **6 emotions**:
|
| 110 |
+
Sadness π’, Joy π, Love β€οΈ, Anger π , Fear π¨, and Surprise π²
|
| 111 |
+
|
| 112 |
+
**Model:** S-4-G-4-R/distilbert-base-uncased-finetuned-emotion
|
| 113 |
+
"""
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
with gr.Row():
|
| 117 |
+
with gr.Column(scale=1):
|
| 118 |
+
text_input = gr.Textbox(
|
| 119 |
+
label="π Enter text to analyze",
|
| 120 |
+
placeholder="Type or paste your text here...",
|
| 121 |
+
lines=5
|
| 122 |
+
)
|
| 123 |
+
classify_btn = gr.Button("π Classify Emotion", variant="primary", size="lg")
|
| 124 |
+
|
| 125 |
+
gr.Markdown("### π‘ Try these examples:")
|
| 126 |
+
gr.Examples(
|
| 127 |
+
examples=examples,
|
| 128 |
+
inputs=text_input,
|
| 129 |
+
label=None
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
with gr.Column(scale=1):
|
| 133 |
+
results_text = gr.Markdown(label="Results")
|
| 134 |
+
|
| 135 |
+
with gr.Row():
|
| 136 |
+
plot_output = gr.Plot(label="π Emotion Probabilities")
|
| 137 |
+
|
| 138 |
+
gr.Markdown(
|
| 139 |
+
"""
|
| 140 |
+
---
|
| 141 |
+
**How it works:** The model analyzes your text and assigns confidence scores to each of the 6 emotions.
|
| 142 |
+
Higher percentages indicate stronger presence of that emotion in the text.
|
| 143 |
+
"""
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
# Connect the button
|
| 147 |
+
classify_btn.click(
|
| 148 |
+
fn=classify_emotion,
|
| 149 |
+
inputs=text_input,
|
| 150 |
+
outputs=[plot_output, results_text]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Also trigger on Enter key
|
| 154 |
+
text_input.submit(
|
| 155 |
+
fn=classify_emotion,
|
| 156 |
+
inputs=text_input,
|
| 157 |
+
outputs=[plot_output, results_text]
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Launch the app
|
| 161 |
demo.launch()
|