File size: 2,078 Bytes
c3a01f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py for Hugging Face Space (Gradio)
import gradio as gr
from transformers import pipeline
import plotly.graph_objects as go

# Load pre-trained emotion classifier from Hugging Face
# Model trained on datasets similar to dair-ai/emotion (6 emotions: anger, fear, joy, love, sadness, surprise)
classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)

# Define prediction function for Gradio
def predict_emotion(text):
    # Get model predictions (list of [{label, score}] for each emotion)
    predictions = classifier(text)[0]
    
    # Extract emotion labels and scores
    emotions = [pred['label'] for pred in predictions]
    scores = [pred['score'] for pred in predictions]
    
    # Find the top emotion
    top_emotion = emotions[scores.index(max(scores))]
    
    # Create a bar chart with Plotly
    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 top emotion and chart
    return f"Predicted Emotion: {top_emotion}", fig

# Create Gradio interface
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!"],  # Should predict Joy
        ["This news is terrifying."],        # Should predict Fear
        ["I miss you so much."]             # Should predict Sadness
    ]
)

# Launch the interface (handled by Hugging Face Spaces)
if __name__ == "__main__":
    iface.launch()