|
|
|
|
|
import gradio as gr |
|
|
from transformers import pipeline |
|
|
import plotly.graph_objects as go |
|
|
|
|
|
|
|
|
|
|
|
classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True) |
|
|
|
|
|
|
|
|
def predict_emotion(text): |
|
|
|
|
|
predictions = classifier(text)[0] |
|
|
|
|
|
|
|
|
emotions = [pred['label'] for pred in predictions] |
|
|
scores = [pred['score'] for pred in predictions] |
|
|
|
|
|
|
|
|
top_emotion = emotions[scores.index(max(scores))] |
|
|
|
|
|
|
|
|
fig = go.Figure( |
|
|
data=[ |
|
|
go.Bar(x=emotions, y=scores, marker_color=['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40']) |
|
|
], |
|
|
layout=go.Layout( |
|
|
title="Emotion Probabilities", |
|
|
xaxis_title="Emotions", |
|
|
yaxis_title="Probability", |
|
|
yaxis_range=[0, 1] |
|
|
) |
|
|
) |
|
|
|
|
|
|
|
|
return f"Predicted Emotion: {top_emotion}", fig |
|
|
|
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=predict_emotion, |
|
|
inputs=gr.Textbox(label="Enter a tweet or text", placeholder="e.g., I'm so happy today!"), |
|
|
outputs=[ |
|
|
gr.Text(label="Prediction"), |
|
|
gr.Plot(label="Emotion Probabilities") |
|
|
], |
|
|
title="Emotion Analyzer", |
|
|
description="Enter a tweet or short text to predict its emotion (anger, fear, joy, love, sadness, surprise).", |
|
|
examples=[ |
|
|
["I'm so excited for the weekend!"], |
|
|
["This news is terrifying."], |
|
|
["I miss you so much."] |
|
|
] |
|
|
) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
iface.launch() |