|
|
import gradio as gr |
|
|
from transformers import pipeline |
|
|
import pandas as pd |
|
|
import plotly.graph_objects as go |
|
|
|
|
|
|
|
|
model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion" |
|
|
classifier = pipeline("text-classification", model=model_id) |
|
|
|
|
|
|
|
|
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise'] |
|
|
|
|
|
|
|
|
LABEL_MAPPING = { |
|
|
'LABEL_0': 'sadness', |
|
|
'LABEL_1': 'joy', |
|
|
'LABEL_2': 'love', |
|
|
'LABEL_3': 'anger', |
|
|
'LABEL_4': 'fear', |
|
|
'LABEL_5': 'surprise' |
|
|
} |
|
|
|
|
|
|
|
|
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." |
|
|
|
|
|
|
|
|
preds = classifier(text, return_all_scores=True)[0] |
|
|
|
|
|
|
|
|
df = pd.DataFrame(preds) |
|
|
df['emotion'] = df['label'].map(LABEL_MAPPING) |
|
|
df['score'] = df['score'] * 100 |
|
|
|
|
|
|
|
|
df['display_label'] = df['emotion'].map(lambda x: f"{EMOTION_EMOJIS.get(x, '')} {x.capitalize()}") |
|
|
|
|
|
|
|
|
df = df.sort_values('score', ascending=True) |
|
|
|
|
|
|
|
|
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') |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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."] |
|
|
] |
|
|
|
|
|
|
|
|
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. |
|
|
""" |
|
|
) |
|
|
|
|
|
|
|
|
classify_btn.click( |
|
|
fn=classify_emotion, |
|
|
inputs=text_input, |
|
|
outputs=[plot_output, results_text] |
|
|
) |
|
|
|
|
|
|
|
|
text_input.submit( |
|
|
fn=classify_emotion, |
|
|
inputs=text_input, |
|
|
outputs=[plot_output, results_text] |
|
|
) |
|
|
|
|
|
|
|
|
demo.launch() |