File size: 5,426 Bytes
b154803 17db978 b154803 17db978 b154803 17db978 b154803 17db978 b154803 17db978 b154803 a5ec5fb 748388d b154803 49fc6d1 b154803 17db978 b154803 17db978 b154803 17db978 b154803 daf618b |
1 2 3 4 5 6 7 8 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
import gradio as gr
from transformers import pipeline
import pandas as pd
import plotly.graph_objects as go
# Load the emotion classification model
model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion"
classifier = pipeline("text-classification", model=model_id)
# Define emotion labels mapping (LABEL_0 to LABEL_5)
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
# Label mapping from model output to emotion names
LABEL_MAPPING = {
'LABEL_0': 'sadness',
'LABEL_1': 'joy',
'LABEL_2': 'love',
'LABEL_3': 'anger',
'LABEL_4': 'fear',
'LABEL_5': 'surprise'
}
# Emoji mapping for emotions
EMOTION_EMOJIS = {
'sadness': 'π’',
'joy': 'π',
'love': 'β€οΈ',
'anger': 'π ',
'fear': 'π¨',
'surprise': 'π²'
}
def classify_emotion(text):
"""
Classify the emotion in the given text and return results with visualization
"""
if not text.strip():
return None, "Please enter some text to analyze."
# Get predictions
preds = classifier(text, return_all_scores=True)[0]
# Create DataFrame and map labels to emotion names
df = pd.DataFrame(preds)
df['emotion'] = df['label'].map(LABEL_MAPPING)
df['score'] = df['score'] * 100 # Convert to percentage
# Add emojis to labels
df['display_label'] = df['emotion'].map(lambda x: f"{EMOTION_EMOJIS.get(x, '')} {x.capitalize()}")
# Sort by score for better visualization
df = df.sort_values('score', ascending=True)
# Create horizontal bar chart using Plotly
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F']
fig = go.Figure(go.Bar(
x=df['score'],
y=df['display_label'],
orientation='h',
marker=dict(
color=df['score'],
colorscale='Viridis',
showscale=False
),
text=df['score'].round(2),
texttemplate='%{text}%',
textposition='outside'
))
fig.update_layout(
title={
'text': 'Emotion Classification Results',
'x': 0.5,
'xanchor': 'center'
},
xaxis_title='Confidence (%)',
yaxis_title='',
height=450,
margin=dict(l=20, r=80, t=60, b=40),
plot_bgcolor='rgba(13, 13, 9, 0.05)',
paper_bgcolor='rgba(13, 13, 9, 0.05)',
font=dict(size=12, color='white')
)
fig.update_xaxes(range=[0, 105], gridcolor='lightgray')
# Format results as text with emojis
results_text = "### π― Prediction Results\n\n"
sorted_df = df.sort_values('score', ascending=False)
top_emotion = sorted_df.iloc[0]
results_text += f"**Top Emotion:** {EMOTION_EMOJIS.get(top_emotion['emotion'], '')} **{top_emotion['emotion'].capitalize()}** ({top_emotion['score']:.2f}%)\n\n"
results_text += "---\n\n**All Emotions:**\n\n"
for _, row in sorted_df.iterrows():
emoji = EMOTION_EMOJIS.get(row['emotion'], '')
bar_length = int(row['score'] / 5)
bar = 'β' * bar_length
results_text += f"{emoji} **{row['emotion'].capitalize()}**: {row['score']:.2f}% {bar}\n\n"
return fig, results_text
# Example texts
examples = [
["I was feeling very alone today walking down on road"],
["I am so happy and excited about this new opportunity!"],
["This makes me really angry and frustrated!"],
["I'm scared about what might happen next..."],
["What a beautiful day, I love this!"],
["Wow! I can't believe this just happened!"],
["I feel so sad and disappointed about the news."]
]
# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft(), title="Emotion Classifier") as demo:
gr.Markdown(
"""
# π Emotion Classification
Analyze the emotional tone of any text using AI. This model can detect **6 emotions**:
Sadness π’, Joy π, Love β€οΈ, Anger π , Fear π¨, and Surprise π²
**Model:** S-4-G-4-R/distilbert-base-uncased-finetuned-emotion
"""
)
with gr.Row():
with gr.Column(scale=1):
text_input = gr.Textbox(
label="π Enter text to analyze",
placeholder="Type or paste your text here...",
lines=5
)
classify_btn = gr.Button("π Classify Emotion", variant="primary", size="lg")
gr.Markdown("### π‘ Try these examples:")
gr.Examples(
examples=examples,
inputs=text_input,
label=None
)
with gr.Column(scale=1):
results_text = gr.Markdown(label="Results")
with gr.Row():
plot_output = gr.Plot(label="π Emotion Probabilities")
gr.Markdown(
"""
---
**How it works:** The model analyzes your text and assigns confidence scores to each of the 6 emotions.
Higher percentages indicate stronger presence of that emotion in the text.
"""
)
# Connect the button
classify_btn.click(
fn=classify_emotion,
inputs=text_input,
outputs=[plot_output, results_text]
)
# Also trigger on Enter key
text_input.submit(
fn=classify_emotion,
inputs=text_input,
outputs=[plot_output, results_text]
)
# Launch the app
demo.launch() |