S-4-G-4-R commited on
Commit
b154803
Β·
verified Β·
1 Parent(s): 965829e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -105
app.py CHANGED
@@ -1,106 +1,161 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- import pandas as pd
4
- import plotly.graph_objects as go
5
-
6
- # Load the emotion classification model
7
- model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion"
8
- classifier = pipeline("text-classification", model=model_id)
9
-
10
- def classify_emotion(text):
11
- """
12
- Classify the emotion in the given text and return results with visualization
13
- """
14
- if not text.strip():
15
- return None, "Please enter some text to analyze."
16
-
17
- # Get predictions
18
- preds = classifier(text, return_all_scores=True)[0]
19
-
20
- # Create DataFrame
21
- df = pd.DataFrame(preds)
22
- df['score'] = df['score'] * 100 # Convert to percentage
23
- df = df.sort_values('score', ascending=True)
24
-
25
- # Create horizontal bar chart using Plotly
26
- fig = go.Figure(go.Bar(
27
- x=df['score'],
28
- y=df['label'],
29
- orientation='h',
30
- marker=dict(color='steelblue')
31
- ))
32
-
33
- fig.update_layout(
34
- title=f'Emotion Classification Results',
35
- xaxis_title='Probability (%)',
36
- yaxis_title='Emotion',
37
- height=400,
38
- margin=dict(l=100, r=20, t=60, b=40)
39
- )
40
-
41
- # Format results as text
42
- results_text = "**Prediction Results:**\n\n"
43
- sorted_df = df.sort_values('score', ascending=False)
44
- for _, row in sorted_df.iterrows():
45
- results_text += f"- **{row['label']}**: {row['score']:.2f}%\n"
46
-
47
- return fig, results_text
48
-
49
- # Example texts
50
- examples = [
51
- "I was feeling very alone today walking down on road",
52
- "I am so happy and excited about this new opportunity!",
53
- "This makes me really angry and frustrated.",
54
- "I'm scared about what might happen next.",
55
- "What a beautiful day, I love this!",
56
- "I feel so sad and disappointed about the news."
57
- ]
58
-
59
- # Create Gradio interface
60
- with gr.Blocks(title="Emotion Classifier") as demo:
61
- gr.Markdown(
62
- """
63
- # 🎭 Emotion Classification
64
- Enter any text to analyze its emotional content. The model will classify it into different emotion categories.
65
-
66
- **Model:** S-4-G-4-R/distilbert-base-uncased-finetuned-emotion
67
- """
68
- )
69
-
70
- with gr.Row():
71
- with gr.Column():
72
- text_input = gr.Textbox(
73
- label="Enter text to analyze",
74
- placeholder="Type your text here...",
75
- lines=3
76
- )
77
- classify_btn = gr.Button("Classify Emotion", variant="primary")
78
-
79
- with gr.Column():
80
- results_text = gr.Markdown(label="Results")
81
-
82
- plot_output = gr.Plot(label="Emotion Probabilities")
83
-
84
- # Examples section
85
- gr.Examples(
86
- examples=examples,
87
- inputs=text_input,
88
- label="Try these examples:"
89
- )
90
-
91
- # Connect the button
92
- classify_btn.click(
93
- fn=classify_emotion,
94
- inputs=text_input,
95
- outputs=[plot_output, results_text]
96
- )
97
-
98
- # Also trigger on Enter key
99
- text_input.submit(
100
- fn=classify_emotion,
101
- inputs=text_input,
102
- outputs=[plot_output, results_text]
103
- )
104
-
105
- # Launch the app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  demo.launch()
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import pandas as pd
4
+ import plotly.graph_objects as go
5
+
6
+ # Load the emotion classification model
7
+ model_id = "S-4-G-4-R/distilbert-base-uncased-finetuned-emotion"
8
+ classifier = pipeline("text-classification", model=model_id)
9
+
10
+ # Define emotion labels
11
+ EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
12
+
13
+ # Emoji mapping for emotions
14
+ EMOTION_EMOJIS = {
15
+ 'sadness': '😒',
16
+ 'joy': '😊',
17
+ 'love': '❀️',
18
+ 'anger': '😠',
19
+ 'fear': '😨',
20
+ 'surprise': '😲'
21
+ }
22
+
23
+ def classify_emotion(text):
24
+ """
25
+ Classify the emotion in the given text and return results with visualization
26
+ """
27
+ if not text.strip():
28
+ return None, "Please enter some text to analyze."
29
+
30
+ # Get predictions
31
+ preds = classifier(text, return_all_scores=True)[0]
32
+
33
+ # Create DataFrame
34
+ df = pd.DataFrame(preds)
35
+ df['score'] = df['score'] * 100 # Convert to percentage
36
+
37
+ # Add emojis to labels
38
+ df['display_label'] = df['label'].map(lambda x: f"{EMOTION_EMOJIS.get(x, '')} {x.capitalize()}")
39
+
40
+ # Sort by score for better visualization
41
+ df = df.sort_values('score', ascending=True)
42
+
43
+ # Create horizontal bar chart using Plotly
44
+ colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F']
45
+
46
+ fig = go.Figure(go.Bar(
47
+ x=df['score'],
48
+ y=df['display_label'],
49
+ orientation='h',
50
+ marker=dict(
51
+ color=df['score'],
52
+ colorscale='Viridis',
53
+ showscale=False
54
+ ),
55
+ text=df['score'].round(2),
56
+ texttemplate='%{text}%',
57
+ textposition='outside'
58
+ ))
59
+
60
+ fig.update_layout(
61
+ title={
62
+ 'text': 'Emotion Classification Results',
63
+ 'x': 0.5,
64
+ 'xanchor': 'center'
65
+ },
66
+ xaxis_title='Confidence (%)',
67
+ yaxis_title='',
68
+ height=450,
69
+ margin=dict(l=20, r=80, t=60, b=40),
70
+ plot_bgcolor='rgba(0,0,0,0)',
71
+ paper_bgcolor='rgba(0,0,0,0)',
72
+ font=dict(size=12)
73
+ )
74
+
75
+ fig.update_xaxis(range=[0, 105], gridcolor='lightgray')
76
+
77
+ # Format results as text with emojis
78
+ results_text = "### 🎯 Prediction Results\n\n"
79
+ sorted_df = df.sort_values('score', ascending=False)
80
+
81
+ top_emotion = sorted_df.iloc[0]
82
+ results_text += f"**Top Emotion:** {EMOTION_EMOJIS.get(top_emotion['label'], '')} **{top_emotion['label'].capitalize()}** ({top_emotion['score']:.2f}%)\n\n"
83
+ results_text += "---\n\n**All Emotions:**\n\n"
84
+
85
+ for _, row in sorted_df.iterrows():
86
+ emoji = EMOTION_EMOJIS.get(row['label'], '')
87
+ bar_length = int(row['score'] / 5)
88
+ bar = 'β–ˆ' * bar_length
89
+ results_text += f"{emoji} **{row['label'].capitalize()}**: {row['score']:.2f}% {bar}\n\n"
90
+
91
+ return fig, results_text
92
+
93
+ # Example texts
94
+ examples = [
95
+ ["I was feeling very alone today walking down on road"],
96
+ ["I am so happy and excited about this new opportunity!"],
97
+ ["This makes me really angry and frustrated!"],
98
+ ["I'm scared about what might happen next..."],
99
+ ["What a beautiful day, I love this!"],
100
+ ["Wow! I can't believe this just happened!"],
101
+ ["I feel so sad and disappointed about the news."]
102
+ ]
103
+
104
+ # Create Gradio interface
105
+ with gr.Blocks(theme=gr.themes.Soft(), title="Emotion Classifier") as demo:
106
+ gr.Markdown(
107
+ """
108
+ # 🎭 Emotion Classification
109
+ Analyze the emotional tone of any text using AI. This model can detect **6 emotions**:
110
+ Sadness 😒, Joy 😊, Love ❀️, Anger 😠, Fear 😨, and Surprise 😲
111
+
112
+ **Model:** S-4-G-4-R/distilbert-base-uncased-finetuned-emotion
113
+ """
114
+ )
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ text_input = gr.Textbox(
119
+ label="πŸ“ Enter text to analyze",
120
+ placeholder="Type or paste your text here...",
121
+ lines=5
122
+ )
123
+ classify_btn = gr.Button("πŸ” Classify Emotion", variant="primary", size="lg")
124
+
125
+ gr.Markdown("### πŸ’‘ Try these examples:")
126
+ gr.Examples(
127
+ examples=examples,
128
+ inputs=text_input,
129
+ label=None
130
+ )
131
+
132
+ with gr.Column(scale=1):
133
+ results_text = gr.Markdown(label="Results")
134
+
135
+ with gr.Row():
136
+ plot_output = gr.Plot(label="πŸ“Š Emotion Probabilities")
137
+
138
+ gr.Markdown(
139
+ """
140
+ ---
141
+ **How it works:** The model analyzes your text and assigns confidence scores to each of the 6 emotions.
142
+ Higher percentages indicate stronger presence of that emotion in the text.
143
+ """
144
+ )
145
+
146
+ # Connect the button
147
+ classify_btn.click(
148
+ fn=classify_emotion,
149
+ inputs=text_input,
150
+ outputs=[plot_output, results_text]
151
+ )
152
+
153
+ # Also trigger on Enter key
154
+ text_input.submit(
155
+ fn=classify_emotion,
156
+ inputs=text_input,
157
+ outputs=[plot_output, results_text]
158
+ )
159
+
160
+ # Launch the app
161
  demo.launch()