Soundaryasos commited on
Commit
c1701cd
ยท
verified ยท
1 Parent(s): f9b03a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -48
app.py CHANGED
@@ -9,9 +9,13 @@ from sklearn.linear_model import LinearRegression
9
  from wordcloud import WordCloud
10
  import base64
11
  from io import BytesIO
 
 
 
 
12
 
13
  # Initialize sentiment models
14
- bert_sentiment = pipeline("sentiment-analysis")
15
  vader_analyzer = SentimentIntensityAnalyzer()
16
 
17
  # Generate sample past sentiment data
@@ -40,81 +44,62 @@ def generate_wordcloud(text):
40
  return base64.b64encode(img.getvalue()).decode()
41
 
42
  # Streamlit app setup
43
- st.title("Interactive Sentiment Analysis Dashboard")
44
 
45
- # Sidebar for navigation and settings
46
- st.sidebar.header("Sentiment Analysis Controls")
47
- st.sidebar.subheader("Input")
48
- user_input = st.sidebar.text_input('Enter text for sentiment analysis')
49
 
50
  # Display sentiment analysis results
51
- def display_sentiment_analysis(vader_score, bert_result):
52
- st.subheader("Sentiment Analysis Results:")
53
  st.write(f"**VADER Sentiment Score**: {vader_score:.2f}")
54
  st.write(f"**BERT Sentiment**: {bert_result['label']} ({bert_result['score']:.2f})")
55
-
 
56
  sentiment_data = {'Positive': max(0, vader_score), 'Negative': min(0, vader_score), 'Neutral': 1 - abs(vader_score)}
57
  sentiment_df = pd.DataFrame(list(sentiment_data.items()), columns=["Sentiment", "Score"])
58
  st.bar_chart(sentiment_df.set_index("Sentiment"))
59
-
60
  wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'
61
  st.image(wordcloud_img, use_column_width=True)
62
 
63
- # Analyze sentiment on button click
64
- if st.sidebar.button('Analyze Sentiment'):
65
  if user_input:
66
- with st.spinner('Analyzing text...'):
67
  vader_score = vader_analyzer.polarity_scores(user_input)['compound']
68
  bert_result = bert_sentiment(user_input)[0]
69
- display_sentiment_analysis(vader_score, bert_result)
 
70
  else:
71
- st.warning("Please enter some text for analysis.")
72
 
73
  # Past sentiment trends
74
- st.subheader("Past Sentiment Trends (Last 14 Days)")
75
- fig1 = px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
76
  st.plotly_chart(fig1)
77
 
78
  # Future sentiment predictions
79
- st.subheader("Sentiment Prediction for Next 7 Days")
80
- fig2 = px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
81
  st.plotly_chart(fig2)
82
 
83
  # Sentiment distribution pie chart
84
- st.subheader("Sentiment Distribution")
85
- fig3 = px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
86
- names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
87
  st.plotly_chart(fig3)
88
 
89
- # Histogram of Sentiment Scores
90
- st.subheader("Sentiment Score Distribution (Past 14 Days)")
91
- fig4 = px.histogram(df, x='Sentiment Score', nbins=20, title="Sentiment Score Distribution")
92
- st.plotly_chart(fig4)
93
-
94
- # Sentiment heatmap (corrected version)
95
- st.subheader("Sentiment Heatmap (Past 14 Days)")
96
- df['Day'] = df['Date'].dt.dayofweek # Monday=0, Sunday=6
97
- df['Hour'] = np.random.randint(0, 24, len(df)) # Simulating hourly data
98
- heatmap_data = df.pivot(index='Day', columns='Hour', values='Sentiment Score')
99
- fig5 = px.imshow(
100
- heatmap_data,
101
- title="Heatmap of Sentiment Over Time",
102
- labels={'x': 'Hour of Day', 'y': 'Day of Week'},
103
- color_continuous_scale='RdBu'
104
- )
105
- st.plotly_chart(fig5)
106
-
107
  # Sentiment scatter plot
108
- st.subheader("Sentiment Scatter Plot (Past 14 Days)")
109
- fig6 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
110
- st.plotly_chart(fig6)
111
 
112
  # Rolling average sentiment
113
- st.subheader("Rolling Average of Sentiment (7-Day Window)")
114
  df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
115
- fig7 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="Rolling Average of Sentiment (7-Day Window)")
116
- st.plotly_chart(fig7)
117
 
118
  # Reset button
119
- if st.sidebar.button('Reset Analysis'):
120
- st.experimental_rerun()
 
9
  from wordcloud import WordCloud
10
  import base64
11
  from io import BytesIO
12
+ import nltk
13
+ from textblob import TextBlob
14
+
15
+ nltk.download('punkt')
16
 
17
  # Initialize sentiment models
18
+ bert_sentiment = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
19
  vader_analyzer = SentimentIntensityAnalyzer()
20
 
21
  # Generate sample past sentiment data
 
44
  return base64.b64encode(img.getvalue()).decode()
45
 
46
  # Streamlit app setup
47
+ st.title("๐ŸŒŸ Advanced Sentiment Analysis Dashboard")
48
 
49
+ # Sidebar for user input
50
+ st.sidebar.header("๐Ÿ” Sentiment Analysis Controls")
51
+ user_input = st.sidebar.text_area("Enter text for sentiment analysis")
 
52
 
53
  # Display sentiment analysis results
54
+ def display_sentiment_analysis(vader_score, bert_result, textblob_score):
55
+ st.subheader("๐Ÿ“Š Sentiment Analysis Results:")
56
  st.write(f"**VADER Sentiment Score**: {vader_score:.2f}")
57
  st.write(f"**BERT Sentiment**: {bert_result['label']} ({bert_result['score']:.2f})")
58
+ st.write(f"**TextBlob Sentiment Polarity**: {textblob_score:.2f}")
59
+
60
  sentiment_data = {'Positive': max(0, vader_score), 'Negative': min(0, vader_score), 'Neutral': 1 - abs(vader_score)}
61
  sentiment_df = pd.DataFrame(list(sentiment_data.items()), columns=["Sentiment", "Score"])
62
  st.bar_chart(sentiment_df.set_index("Sentiment"))
63
+
64
  wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'
65
  st.image(wordcloud_img, use_column_width=True)
66
 
67
+ if st.sidebar.button("Analyze Sentiment"):
 
68
  if user_input:
69
+ with st.spinner("Analyzing text..."):
70
  vader_score = vader_analyzer.polarity_scores(user_input)['compound']
71
  bert_result = bert_sentiment(user_input)[0]
72
+ textblob_score = TextBlob(user_input).sentiment.polarity
73
+ display_sentiment_analysis(vader_score, bert_result, textblob_score)
74
  else:
75
+ st.warning("โš ๏ธ Please enter some text for analysis.")
76
 
77
  # Past sentiment trends
78
+ st.subheader("๐Ÿ“… Past Sentiment Trends (Last 14 Days)")
79
+ fig1 = px.line(df, x='Date', y='Sentiment Score', title='Sentiment Over Time', markers=True, line_shape='spline')
80
  st.plotly_chart(fig1)
81
 
82
  # Future sentiment predictions
83
+ st.subheader("๐Ÿ”ฎ Sentiment Prediction for Next 7 Days")
84
+ fig2 = px.line(future_df, x='Date', y='Predicted Sentiment', title='Predicted Sentiment Trend', markers=True, line_shape='spline')
85
  st.plotly_chart(fig2)
86
 
87
  # Sentiment distribution pie chart
88
+ st.subheader("๐Ÿ“Š Sentiment Distribution")
89
+ fig3 = px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)], names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
 
90
  st.plotly_chart(fig3)
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  # Sentiment scatter plot
93
+ st.subheader("๐Ÿ”Ž Sentiment Scatter Plot (Last 14 Days)")
94
+ fig4 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
95
+ st.plotly_chart(fig4)
96
 
97
  # Rolling average sentiment
98
+ st.subheader("๐Ÿ“ˆ Rolling Average of Sentiment (7-Day Window)")
99
  df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
100
+ fig5 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="7-Day Rolling Average Sentiment")
101
+ st.plotly_chart(fig5)
102
 
103
  # Reset button
104
+ if st.sidebar.button('๐Ÿ”„ Reset Analysis'):
105
+ st.experimental_rerun()