Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,14 @@
|
|
1 |
import numpy as np
|
2 |
-
import pandas as pd
|
3 |
import tensorflow as tf
|
4 |
-
from tensorflow.keras.preprocessing.text import Tokenizer
|
5 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
6 |
from sklearn.preprocessing import LabelEncoder
|
7 |
import gradio as gr
|
8 |
import pickle
|
9 |
-
import
|
|
|
|
|
|
|
|
|
10 |
|
11 |
# Load model and tokenizer
|
12 |
model = tf.keras.models.load_model('sentiment_rnn.h5')
|
@@ -19,67 +21,193 @@ with open('tokenizer.pkl', 'rb') as f:
|
|
19 |
label_encoder = LabelEncoder()
|
20 |
label_encoder.fit(["Happy", "Sad", "Neutral"])
|
21 |
|
22 |
-
|
|
|
|
|
|
|
23 |
"""
|
24 |
-
Predict sentiment
|
25 |
"""
|
|
|
|
|
26 |
# Preprocess the text
|
27 |
sequence = tokenizer.texts_to_sequences([text])
|
28 |
padded = pad_sequences(sequence, maxlen=50)
|
29 |
|
30 |
# Make prediction
|
31 |
prediction = model.predict(padded, verbose=0)[0]
|
|
|
|
|
32 |
predicted_class = np.argmax(prediction)
|
33 |
sentiment = label_encoder.inverse_transform([predicted_class])[0]
|
34 |
confidence = float(prediction[predicted_class])
|
35 |
|
36 |
-
# Create confidence dictionary
|
37 |
confidences = {
|
38 |
"Happy": float(prediction[0]),
|
39 |
"Sad": float(prediction[1]),
|
40 |
"Neutral": float(prediction[2])
|
41 |
}
|
42 |
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
submit_btn = gr.Button("Analyze Sentiment")
|
56 |
-
|
57 |
-
examples = gr.Examples(
|
58 |
-
examples=[
|
59 |
-
["I'm feeling great today!"],
|
60 |
-
["My dog passed away..."],
|
61 |
-
["The office is closed tomorrow."],
|
62 |
-
["This is the best day ever!"],
|
63 |
-
["I feel miserable."],
|
64 |
-
["There are 12 books on the shelf."]
|
65 |
-
],
|
66 |
-
inputs=text_input
|
67 |
-
)
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
-
|
|
|
74 |
fn=analyze_text,
|
75 |
-
inputs=text_input,
|
76 |
-
outputs=[
|
77 |
)
|
78 |
|
79 |
text_input.submit(
|
80 |
fn=analyze_text,
|
81 |
-
inputs=text_input,
|
82 |
-
outputs=[
|
83 |
)
|
84 |
|
85 |
# Launch the app
|
|
|
1 |
import numpy as np
|
|
|
2 |
import tensorflow as tf
|
|
|
3 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
4 |
from sklearn.preprocessing import LabelEncoder
|
5 |
import gradio as gr
|
6 |
import pickle
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
from matplotlib import cm
|
9 |
+
import pandas as pd
|
10 |
+
import time
|
11 |
+
import json
|
12 |
|
13 |
# Load model and tokenizer
|
14 |
model = tf.keras.models.load_model('sentiment_rnn.h5')
|
|
|
21 |
label_encoder = LabelEncoder()
|
22 |
label_encoder.fit(["Happy", "Sad", "Neutral"])
|
23 |
|
24 |
+
# Load sample data for examples
|
25 |
+
sample_data = pd.read_csv("sentiment_dataset_1000.csv")
|
26 |
+
|
27 |
+
def predict_sentiment(text, show_details=False):
|
28 |
"""
|
29 |
+
Predict sentiment with detailed analysis
|
30 |
"""
|
31 |
+
start_time = time.time()
|
32 |
+
|
33 |
# Preprocess the text
|
34 |
sequence = tokenizer.texts_to_sequences([text])
|
35 |
padded = pad_sequences(sequence, maxlen=50)
|
36 |
|
37 |
# Make prediction
|
38 |
prediction = model.predict(padded, verbose=0)[0]
|
39 |
+
processing_time = time.time() - start_time
|
40 |
+
|
41 |
predicted_class = np.argmax(prediction)
|
42 |
sentiment = label_encoder.inverse_transform([predicted_class])[0]
|
43 |
confidence = float(prediction[predicted_class])
|
44 |
|
45 |
+
# Create confidence dictionary
|
46 |
confidences = {
|
47 |
"Happy": float(prediction[0]),
|
48 |
"Sad": float(prediction[1]),
|
49 |
"Neutral": float(prediction[2])
|
50 |
}
|
51 |
|
52 |
+
# Create visualization
|
53 |
+
fig = create_confidence_plot(confidences)
|
54 |
+
|
55 |
+
# Additional analysis
|
56 |
+
word_count = len(text.split())
|
57 |
+
char_count = len(text)
|
58 |
+
|
59 |
+
result = {
|
60 |
+
"sentiment": sentiment,
|
61 |
+
"confidence": round(confidence * 100, 2),
|
62 |
+
"confidences": confidences,
|
63 |
+
"processing_time": round(processing_time * 1000, 2),
|
64 |
+
"word_count": word_count,
|
65 |
+
"char_count": char_count,
|
66 |
+
"plot": fig
|
67 |
+
}
|
68 |
+
|
69 |
+
return result
|
70 |
|
71 |
+
def create_confidence_plot(confidences):
|
72 |
+
"""Create a beautiful confidence plot"""
|
73 |
+
labels = list(confidences.keys())
|
74 |
+
values = list(confidences.values())
|
75 |
|
76 |
+
colors = cm.get_cmap('RdYlGn')(np.linspace(0.2, 0.8, len(labels)))
|
77 |
+
|
78 |
+
fig, ax = plt.subplots(figsize=(8, 4))
|
79 |
+
bars = ax.barh(labels, values, color=colors)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
+
# Add value labels
|
82 |
+
for bar in bars:
|
83 |
+
width = bar.get_width()
|
84 |
+
ax.text(width + 0.02, bar.get_y() + bar.get_height()/2,
|
85 |
+
f'{width:.2%}',
|
86 |
+
ha='left', va='center', fontsize=10)
|
87 |
+
|
88 |
+
ax.set_xlim(0, 1)
|
89 |
+
ax.set_title('Sentiment Confidence Scores', pad=20)
|
90 |
+
ax.spines['top'].set_visible(False)
|
91 |
+
ax.spines['right'].set_visible(False)
|
92 |
+
ax.spines['left'].set_visible(False)
|
93 |
+
ax.spines['bottom'].set_visible(False)
|
94 |
+
ax.grid(axis='x', linestyle='--', alpha=0.7)
|
95 |
+
ax.set_facecolor('#f8f9fa')
|
96 |
+
fig.patch.set_facecolor('#f8f9fa')
|
97 |
+
|
98 |
+
return fig
|
99 |
+
|
100 |
+
def get_sentiment_emoji(sentiment):
|
101 |
+
"""Get emoji for sentiment"""
|
102 |
+
emojis = {
|
103 |
+
"Happy": "π",
|
104 |
+
"Sad": "π’",
|
105 |
+
"Neutral": "π"
|
106 |
+
}
|
107 |
+
return emojis.get(sentiment, "")
|
108 |
+
|
109 |
+
def analyze_text(text):
|
110 |
+
"""Main analysis function"""
|
111 |
+
result = predict_sentiment(text)
|
112 |
+
|
113 |
+
emoji = get_sentiment_emoji(result["sentiment"])
|
114 |
+
|
115 |
+
# Create HTML output
|
116 |
+
html_output = f"""
|
117 |
+
<div style="background-color:#f8f9fa; padding:20px; border-radius:10px; margin-bottom:20px;">
|
118 |
+
<h2 style="color:#2c3e50; margin-top:0;">Analysis Result {emoji}</h2>
|
119 |
+
<p><strong>Text:</strong> {text[:200]}{'...' if len(text) > 200 else ''}</p>
|
120 |
+
<p><strong>Sentiment:</strong> <span style="font-weight:bold; color:{'#27ae60' if result['sentiment'] == 'Happy' else '#e74c3c' if result['sentiment'] == 'Sad' else '#3498db'}">{result['sentiment']}</span></p>
|
121 |
+
<p><strong>Confidence:</strong> {result['confidence']}%</p>
|
122 |
+
<p><strong>Processing Time:</strong> {result['processing_time']} ms</p>
|
123 |
+
<p><strong>Word Count:</strong> {result['word_count']}</p>
|
124 |
+
<p><strong>Character Count:</strong> {result['char_count']}</p>
|
125 |
+
</div>
|
126 |
+
"""
|
127 |
+
|
128 |
+
return html_output, result['plot'], json.dumps(result['confidences'], indent=2)
|
129 |
+
|
130 |
+
# Create Gradio interface
|
131 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Sentiment Analysis Dashboard") as demo:
|
132 |
+
with gr.Row():
|
133 |
+
with gr.Column(scale=1):
|
134 |
+
gr.Markdown("""
|
135 |
+
# π Sentiment Analysis Dashboard
|
136 |
+
**Analyze text for emotional sentiment** using our advanced RNN model.
|
137 |
+
""")
|
138 |
+
|
139 |
+
with gr.Group():
|
140 |
+
text_input = gr.Textbox(
|
141 |
+
label="Enter your text",
|
142 |
+
placeholder="Type something to analyze its sentiment...",
|
143 |
+
lines=4,
|
144 |
+
max_lines=8
|
145 |
+
)
|
146 |
+
|
147 |
+
analyze_btn = gr.Button("Analyze", variant="primary")
|
148 |
+
|
149 |
+
with gr.Accordion("Advanced Settings", open=False):
|
150 |
+
show_details = gr.Checkbox(
|
151 |
+
label="Show detailed analysis",
|
152 |
+
value=True
|
153 |
+
)
|
154 |
+
|
155 |
+
gr.Markdown("### Try these examples:")
|
156 |
+
examples = gr.Examples(
|
157 |
+
examples=[
|
158 |
+
["I'm feeling great today!"],
|
159 |
+
["My dog passed away..."],
|
160 |
+
["The office is closed tomorrow."],
|
161 |
+
["This is the best day ever!"],
|
162 |
+
["I feel completely devastated."],
|
163 |
+
["The meeting is scheduled for 2 PM."]
|
164 |
+
],
|
165 |
+
inputs=[text_input],
|
166 |
+
label="Quick Examples"
|
167 |
+
)
|
168 |
+
|
169 |
+
with gr.Column(scale=2):
|
170 |
+
with gr.Tab("Results"):
|
171 |
+
html_output = gr.HTML(label="Analysis Summary")
|
172 |
+
plot_output = gr.Plot(label="Confidence Distribution")
|
173 |
+
|
174 |
+
with gr.Tab("Raw Data"):
|
175 |
+
json_output = gr.JSON(label="Confidence Scores")
|
176 |
+
|
177 |
+
with gr.Tab("About"):
|
178 |
+
gr.Markdown("""
|
179 |
+
## About This Dashboard
|
180 |
+
|
181 |
+
This sentiment analysis tool uses a **Recurrent Neural Network (RNN)** with **LSTM** layers to classify text into three sentiment categories:
|
182 |
+
|
183 |
+
- π Happy (Positive)
|
184 |
+
- π’ Sad (Negative)
|
185 |
+
- π Neutral
|
186 |
+
|
187 |
+
**Model Details:**
|
188 |
+
- Trained on 1,000 labeled examples
|
189 |
+
- 64-unit LSTM layer with regularization
|
190 |
+
- 92% test accuracy
|
191 |
+
|
192 |
+
**How to use:**
|
193 |
+
1. Type or paste text in the input box
|
194 |
+
2. Click "Analyze" or press Enter
|
195 |
+
3. View the sentiment analysis results
|
196 |
+
|
197 |
+
**Try the examples above for quick testing!**
|
198 |
+
""")
|
199 |
|
200 |
+
# Event handlers
|
201 |
+
analyze_btn.click(
|
202 |
fn=analyze_text,
|
203 |
+
inputs=[text_input],
|
204 |
+
outputs=[html_output, plot_output, json_output]
|
205 |
)
|
206 |
|
207 |
text_input.submit(
|
208 |
fn=analyze_text,
|
209 |
+
inputs=[text_input],
|
210 |
+
outputs=[html_output, plot_output, json_output]
|
211 |
)
|
212 |
|
213 |
# Launch the app
|