-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
431 lines (351 loc) · 17.9 KB
/
app.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import streamlit as st
from textblob import TextBlob
import pandas as pd
import altair as alt
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
st.set_page_config(layout="wide")
import nltk
nltk.download('punkt')
from transformers import pipeline
import plotly.express as px
# Load pre-trained emotion detection model
emotion_classifier = pipeline('text-classification', model='j-hartmann/emotion-english-distilroberta-base')
def detect_emotions(text):
return emotion_classifier(text)
def get_sentiment(text):
blob = TextBlob(text)
return blob.sentiment
# Function to convert sentiment to DataFrame
def convert_to_df(sentiment):
sentiment_dict = {'polarity': sentiment.polarity, 'subjectivity': sentiment.subjectivity}
sentiment_df = pd.DataFrame(sentiment_dict.items(), columns=['metric', 'value'])
return sentiment_df
# Function to analyze token sentiment
def analyze_token_sentiment(docx):
analyzer = SentimentIntensityAnalyzer()
pos_list = []
neg_list = []
neu_list = []
for word in docx.split():
res = analyzer.polarity_scores(word)['compound']
if res > 0.1:
# pos_list.append((i, res))
pos_list.append({word: res})
elif res <= -0.1:
neg_list.append({word: res})
else:
neu_list.append(word)
result = {'positives': pos_list, 'negatives': neg_list, 'neutral': neu_list}
return result
# Function to analyze sentence sentiment
def analyze_sentence_sentiment(text):
sentences = TextBlob(text).sentences
sentence_sentiments = []
for sentence in sentences:
sentiment = sentence.sentiment
sentence_sentiments.append({'sentence': str(sentence), 'polarity': sentiment.polarity, 'subjectivity': sentiment.subjectivity})
return sentence_sentiments
# Main function
def main():
#SideBar_Config
st.sidebar.title('Sentiment Analyzer: NLP Web app')
menu = ["Home", "Comparative Analysis", "About"]
choice = st.sidebar.selectbox("Menu", menu)
col_image, col_title_text = st.columns(2)
with col_image:
st.image('images/img1.png', width = 50, use_column_width=True)
with col_title_text:
st.markdown("Sentiment is defined as an attitude toward something. Sentiment analysis focuses on analyzing digital text to determing if the emotional tone of the message is positive, negative, or neutral.")
st.markdown("""
<ul>
<li>
<b>Polarity</b> indicates whether a text is positive, negative, or neutral. It ranges from -1 (very negative) to 1 (very positive).
</li>
<li>
<b>Subjectivity</b> indicates how much the text expresses personal opinions, emotions, or subjective information. Values range from 0 (completely objective) to 1 (completely subjective).
</li>
</ul>
""", unsafe_allow_html=True)
# st.image('images/img1.png', width= 50, use_column_width=True)
# st.title("Sentiment Analysis NLP App")
# st.markdown("This web application analyzes the sentiment of the provided text and gives information about the polarity, subjectivity, and emotional tone.")
# st.markdown("Sentiment is defined as an attitude toward something. Sentiment analysis focuses on analyzing digital text to determing if the emotional tone of the message is positive, negative, or neutral.")
# st.markdown("""
# <ul>
# <li>
# <b>Polarity</b> indicates whether a text is positive, negative, or neutral. It ranges from -1 (very negative) to 1 (very positive).
# </li>
# <li>
# <b>Subjectivity</b> indicates how much the text expresses personal opinions, emotions, or subjective information. Values range from 0 (completely objective) to 1 (completely subjective).
# </li>
# </ul>
# """, unsafe_allow_html=True)
# #SideBar_Config
# st.sidebar.title('Sentiment Analysis NLP App')
st.sidebar.markdown('This web application analyzes the sentiment of the provided text and gives information about the polarity, subjectivity, and emotional tone. ')
st.sidebar.markdown('This web application has the following functionality: ')
st.sidebar.markdown("""<ul>
<li>General-level sentiment analysis</li>
<li>Sentence-level sentiment analysis</li>
<li>Token-level sentiment analysis</li>
<li>Emotion Detection</li>
<li>Comparative sentiment analysis</li>
</ul>""", unsafe_allow_html=True)
st.sidebar.markdown('**For any feedback or question please contact me on my email at [junjunzaragosa2309@gmail.com](https://mail.google.com/mail/u/0/#inbox)**')
st.sidebar.caption('Last updated 2nd July,2024')
if choice == "Home":
st.subheader("Home")
with st.form(key='nlpForm'):
raw_text = st.text_area("Enter Text Here")
submit_button = st.form_submit_button(label='Analyze')
# Layout
col1, col2, col3, col4 = st.columns(4)
if submit_button:
with col1:
st.info("Overall Sentiment")
sentiment = TextBlob(raw_text).sentiment
# st.write(sentiment)
# Emoji
if sentiment.polarity > 0:
st.markdown("**Sentiment**:: Positive :smiley: ")
elif sentiment.polarity < 0:
st.markdown("**Sentiment**:: Negative :angry: ")
else:
st.markdown("**Sentiment**:: Neutral 😐 ")
st.markdown(f"**Polarity**: {sentiment.polarity}")
st.markdown(f"**Subjectivity**: {sentiment.subjectivity}")
# Dataframe
result_df = convert_to_df(sentiment)
st.dataframe(result_df)
# Visualization
c = alt.Chart(result_df).mark_bar().encode(
x='metric',
y='value',
color='metric')
st.altair_chart(c, use_container_width=True)
with col2:
sentence_sentiments = analyze_sentence_sentiment(raw_text)
st.info('Sentence-Level Sentiment')
for s in sentence_sentiments:
st.markdown(f"**Sentence**: {s['sentence']}")
st.markdown(f"**Polarity**: {s['polarity']}, **Subjectivity**: {s['subjectivity']}")
st.markdown("""<hr>""", unsafe_allow_html=True)
with col3:
st.info("Token-Level Sentiment")
token_sentiments = analyze_token_sentiment(raw_text)
st.write(token_sentiments)
with col4:
st.info("Detected Emotion")
emotions = detect_emotions(raw_text)
st.write("Emotion:")
st.write(emotions)
elif choice == "Comparative Analysis":
st.subheader("Comparative Analysis")
with st.form(key='nlpForm'):
raw_text1 = st.text_area("Enter First Text Here")
raw_text2 = st.text_area("Enter Second Text Here")
submit_button = st.form_submit_button(label='Analyze')
col1, col2 = st.columns(2)
if submit_button:
# Sentiment Analysis
sentiment1 = get_sentiment(raw_text1)
sentiment2 = get_sentiment(raw_text2)
with col1:
st.info("Results")
st.markdown("**Sentiment of first text**")
st.markdown(f"""
<ul>
<li><b>Polarity: </b> {sentiment1.polarity}</li>
<li><b>Subjectivity: </b> {sentiment1.subjectivity}</li>
</ul>
""", unsafe_allow_html=True)
st.markdown("**Sentiment of second text**")
st.markdown(f"""
<ul>
<li><b>Polarity: </b> {sentiment2.polarity}</li>
<li><b>Subjectivity: </b> {sentiment2.subjectivity}</li>
</ul>
""", unsafe_allow_html=True)
with col2:
st.info("Graph")
data_polarity = {
"Text": ["Text 1", "Text 2"],
"Sentiment": [sentiment1.polarity, sentiment2.polarity]
}
data_subjectivity = {
"Text": ["Text 1", "Text 2"],
"Subjectivity": [sentiment1.subjectivity, sentiment2.subjectivity]
}
st.markdown("### Polairity")
fig = px.bar(data_polarity, x='Text', y='Sentiment', color='Text', title='Comparative Sentiment Analysis')
st.plotly_chart(fig)
st.markdown("### Subjectivity")
fig = px.bar(data_subjectivity, x='Text', y='Sentiment', color='Text', title='Comparative Sentiment Analysis')
st.plotly_chart(fig)
else:
st.subheader("About")
if __name__ == '__main__':
main()
# import streamlit as st
# from textblob import TextBlob
# import pandas as pd
# import altair as alt
# from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
# from transformers import pipeline
# import plotly.express as px
# import nltk
# st.set_page_config(layout="wide")
# nltk.download('punkt')
# # Main function
# def main():
# # Sidebar Configuration
# st.sidebar.title('Sentiment Analyzer: NLP Web app')
# menu = ["Home", "Comparative Analysis", "About"]
# choice = st.sidebar.selectbox("Menu", menu)
# st.sidebar.markdown('This web application analyzes the sentiment of the provided text and gives information about the polarity, subjectivity, and emotional tone. ')
# st.sidebar.markdown('This web application has the following functionality: ')
# st.sidebar.markdown("""
# <ul>
# <li>General-level sentiment analysis</li>
# <li>Sentence-level sentiment analysis</li>
# <li>Token-level sentiment analysis</li>
# <li>Emotion Detection</li>
# <li>Comparative sentiment analysis</li>
# </ul>
# """, unsafe_allow_html=True)
# st.sidebar.markdown('**For any feedback or questions, please contact me at [junjunzaragosa2309@gmail.com](mailto:junjunzaragosa2309@gmail.com)**')
# st.sidebar.caption('Last updated 2nd July, 2024')
# col_image, col_title_text = st.columns([1, 4])
# with col_image:
# st.image('images/img1.png', width=50, use_column_width=True)
# with col_title_text:
# st.markdown("Sentiment is defined as an attitude toward something. Sentiment analysis focuses on analyzing digital text to determine if the emotional tone of the message is positive, negative, or neutral.")
# st.markdown("""
# <ul>
# <li><b>Polarity</b> indicates whether a text is positive, negative, or neutral. It ranges from -1 (very negative) to 1 (very positive).</li>
# <li><b>Subjectivity</b> indicates how much the text expresses personal opinions, emotions, or subjective information. Values range from 0 (completely objective) to 1 (completely subjective).</li>
# </ul>
# """, unsafe_allow_html=True)
# if choice == "Home":
# st.subheader("Home")
# with st.form(key='nlpForm'):
# raw_text = st.text_area("Enter Text Here")
# submit_button = st.form_submit_button(label='Analyze')
# # Layout
# col1, col2, col3, col4 = st.columns(4)
# if submit_button:
# with col1:
# st.info("Overall Sentiment")
# sentiment = TextBlob(raw_text).sentiment
# if sentiment.polarity > 0:
# st.markdown("**Sentiment**:: Positive :smiley: ")
# elif sentiment.polarity < 0:
# st.markdown("**Sentiment**:: Negative :angry: ")
# else:
# st.markdown("**Sentiment**:: Neutral 😐 ")
# st.markdown(f"**Polarity**: {sentiment.polarity}")
# st.markdown(f"**Subjectivity**: {sentiment.subjectivity}")
# result_df = convert_to_df(sentiment)
# st.dataframe(result_df)
# c = alt.Chart(result_df).mark_bar().encode(
# x='metric',
# y='value',
# color='metric')
# st.altair_chart(c, use_container_width=True)
# with col2:
# sentence_sentiments = analyze_sentence_sentiment(raw_text)
# st.info('Sentence-Level Sentiment')
# for s in sentence_sentiments:
# st.markdown(f"**Sentence**: {s['sentence']}")
# st.markdown(f"**Polarity**: {s['polarity']}, **Subjectivity**: {s['subjectivity']}")
# st.markdown("""<hr>""", unsafe_allow_html=True)
# with col3:
# st.info("Token-Level Sentiment")
# token_sentiments = analyze_token_sentiment(raw_text)
# st.write(token_sentiments)
# with col4:
# st.info("Detected Emotion")
# emotions = detect_emotions(raw_text)
# st.write("Emotion:")
# st.write(emotions)
# elif choice == "Comparative Analysis":
# st.subheader("Comparative Analysis")
# with st.form(key='nlpForm'):
# raw_text1 = st.text_area("Enter First Text Here")
# raw_text2 = st.text_area("Enter Second Text Here")
# submit_button = st.form_submit_button(label='Analyze')
# col1, col2 = st.columns(2)
# if submit_button:
# sentiment1 = get_sentiment(raw_text1)
# sentiment2 = get_sentiment(raw_text2)
# with col1:
# st.info("Results")
# st.markdown("**Sentiment of first text**")
# st.markdown(f"""
# <ul>
# <li><b>Polarity: </b> {sentiment1.polarity}</li>
# <li><b>Subjectivity: </b> {sentiment1.subjectivity}</li>
# </ul>
# """, unsafe_allow_html=True)
# st.markdown("**Sentiment of second text**")
# st.markdown(f"""
# <ul>
# <li><b>Polarity: </b> {sentiment2.polarity}</li>
# <li><b>Subjectivity: </b> {sentiment2.subjectivity}</li>
# </ul>
# """, unsafe_allow_html=True)
# with col2:
# st.info("Graph")
# data_polarity = {
# "Text": ["Text 1", "Text 2"],
# "Sentiment": [sentiment1.polarity, sentiment2.polarity]
# }
# data_subjectivity = {
# "Text": ["Text 1", "Text 2"],
# "Subjectivity": [sentiment1.subjectivity, sentiment2.subjectivity]
# }
# st.markdown("### Polarity")
# fig = px.bar(data_polarity, x='Text', y='Sentiment', color='Text', title='Comparative Sentiment Analysis')
# st.plotly_chart(fig)
# st.markdown("### Subjectivity")
# fig = px.bar(data_subjectivity, x='Text', y='Sentiment', color='Text', title='Comparative Sentiment Analysis')
# st.plotly_chart(fig)
# else:
# st.subheader("About")
# @st.cache_resource
# def load_emotion_classifier():
# return pipeline('text-classification', model='j-hartmann/emotion-english-distilroberta-base')
# def detect_emotions(text):
# emotion_classifier = load_emotion_classifier()
# return emotion_classifier(text)
# def get_sentiment(text):
# blob = TextBlob(text)
# return blob.sentiment
# def convert_to_df(sentiment):
# sentiment_dict = {'polarity': sentiment.polarity, 'subjectivity': sentiment.subjectivity}
# sentiment_df = pd.DataFrame(sentiment_dict.items(), columns=['metric', 'value'])
# return sentiment_df
# def analyze_token_sentiment(docx):
# analyzer = SentimentIntensityAnalyzer()
# pos_list = []
# neg_list = []
# neu_list = []
# for word in docx.split():
# res = analyzer.polarity_scores(word)['compound']
# if res > 0.1:
# pos_list.append({word: res})
# elif res <= -0.1:
# neg_list.append({word: res})
# else:
# neu_list.append(word)
# result = {'positives': pos_list, 'negatives': neg_list, 'neutral': neu_list}
# return result
# def analyze_sentence_sentiment(text):
# sentences = TextBlob(text).sentences
# sentence_sentiments = []
# for sentence in sentences:
# sentiment = sentence.sentiment
# sentence_sentiments.append({'sentence': str(sentence), 'polarity': sentiment.polarity, 'subjectivity': sentiment.subjectivity})
# return sentence_sentiments
# if __name__ == '__main__':
# main()