luck210 commited on
Commit
c3a01f0
·
verified ·
1 Parent(s): c670f07

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py for Hugging Face Space (Gradio)
2
+ import gradio as gr
3
+ from transformers import pipeline
4
+ import plotly.graph_objects as go
5
+
6
+ # Load pre-trained emotion classifier from Hugging Face
7
+ # Model trained on datasets similar to dair-ai/emotion (6 emotions: anger, fear, joy, love, sadness, surprise)
8
+ classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=True)
9
+
10
+ # Define prediction function for Gradio
11
+ def predict_emotion(text):
12
+ # Get model predictions (list of [{label, score}] for each emotion)
13
+ predictions = classifier(text)[0]
14
+
15
+ # Extract emotion labels and scores
16
+ emotions = [pred['label'] for pred in predictions]
17
+ scores = [pred['score'] for pred in predictions]
18
+
19
+ # Find the top emotion
20
+ top_emotion = emotions[scores.index(max(scores))]
21
+
22
+ # Create a bar chart with Plotly
23
+ fig = go.Figure(
24
+ data=[
25
+ go.Bar(x=emotions, y=scores, marker_color=['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'])
26
+ ],
27
+ layout=go.Layout(
28
+ title="Emotion Probabilities",
29
+ xaxis_title="Emotions",
30
+ yaxis_title="Probability",
31
+ yaxis_range=[0, 1]
32
+ )
33
+ )
34
+
35
+ # Return top emotion and chart
36
+ return f"Predicted Emotion: {top_emotion}", fig
37
+
38
+ # Create Gradio interface
39
+ iface = gr.Interface(
40
+ fn=predict_emotion,
41
+ inputs=gr.Textbox(label="Enter a tweet or text", placeholder="e.g., I'm so happy today!"),
42
+ outputs=[
43
+ gr.Text(label="Prediction"),
44
+ gr.Plot(label="Emotion Probabilities")
45
+ ],
46
+ title="Emotion Analyzer",
47
+ description="Enter a tweet or short text to predict its emotion (anger, fear, joy, love, sadness, surprise).",
48
+ examples=[
49
+ ["I'm so excited for the weekend!"], # Should predict Joy
50
+ ["This news is terrifying."], # Should predict Fear
51
+ ["I miss you so much."] # Should predict Sadness
52
+ ]
53
+ )
54
+
55
+ # Launch the interface (handled by Hugging Face Spaces)
56
+ if __name__ == "__main__":
57
+ iface.launch()