Soundaryasos commited on
Commit
7545f62
·
verified ·
1 Parent(s): 75f5af6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -48
app.py CHANGED
@@ -1,12 +1,10 @@
1
- import dash
2
- from dash import dcc, html
3
- import plotly.express as px
4
- import plotly.graph_objects as go
5
- import pandas as pd
6
- import numpy as np
7
- from datetime import datetime, timedelta
8
  from transformers import pipeline
9
  from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
 
 
 
 
10
  from sklearn.linear_model import LinearRegression
11
  from wordcloud import WordCloud
12
  import base64
@@ -41,48 +39,85 @@ def generate_wordcloud(text):
41
  wordcloud.to_image().save(img, format='PNG')
42
  return base64.b64encode(img.getvalue()).decode()
43
 
44
- # Dash app setup
45
- app = dash.Dash(__name__)
46
- app.layout = html.Div([
47
- html.H1("Sentiment Analysis Dashboard", style={'textAlign': 'center', 'color': '#333'}),
48
- html.Div([
49
- dcc.Input(id='text_input', type='text', placeholder='Enter text here...', style={'width': '70%'}),
50
- html.Button('Analyze', id='analyze_btn', style={'margin-left': '10px'})
51
- ], style={'textAlign': 'center', 'margin-bottom': '20px'}),
52
-
53
- html.Div(id='sentiment_output', style={'fontSize': '20px', 'textAlign': 'center'}),
54
-
55
- dcc.Graph(id='sentiment_trend',
56
- figure=px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
57
- ),
58
-
59
- dcc.Graph(id='future_trend',
60
- figure=px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
61
- ),
62
 
63
- dcc.Graph(id='sentiment_pie',
64
- figure=px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
65
- names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
66
- ),
67
 
68
- html.Img(id='wordcloud_img', style={'width': '50%', 'margin-top': '20px', 'display': 'block', 'margin-left': 'auto', 'margin-right': 'auto'})
69
- ])
70
-
71
- @app.callback(
72
- [dash.dependencies.Output('sentiment_output', 'children'),
73
- dash.dependencies.Output('wordcloud_img', 'src')],
74
- [dash.dependencies.Input('analyze_btn', 'n_clicks')],
75
- [dash.dependencies.State('text_input', 'value')]
76
- )
77
- def analyze_sentiment(n_clicks, text):
78
- if n_clicks:
79
- vader_score = vader_analyzer.polarity_scores(text)['compound']
80
- bert_result = bert_sentiment(text)[0]
81
- explanation = f"VADER Score: {vader_score:.2f}, BERT Sentiment: {bert_result['label']} ({bert_result['score']:.2f})"
82
- wordcloud_img = f'data:image/png;base64,{generate_wordcloud(text)}'
83
- return explanation, wordcloud_img
84
- return '', ''
85
- if __name__ == '__main__':
86
- app.run_server(host='0.0.0.0', port=7860, debug=False, use_reloader=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
 
 
 
 
 
88
 
 
 
 
 
1
+ import streamlit as st
 
 
 
 
 
 
2
  from transformers import pipeline
3
  from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
4
+ import numpy as np
5
+ import pandas as pd
6
+ from datetime import datetime, timedelta
7
+ import plotly.express as px
8
  from sklearn.linear_model import LinearRegression
9
  from wordcloud import WordCloud
10
  import base64
 
39
  wordcloud.to_image().save(img, format='PNG')
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 explanation and detailed sentiment scores
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
+ # Display sentiment breakdown in a bar chart
57
+ sentiment_data = {'Positive': max(0, vader_score), 'Negative': min(0, vader_score), 'Neutral': 1 - abs(vader_score)}
58
+ sentiment_df = pd.DataFrame(list(sentiment_data.items()), columns=["Sentiment", "Score"])
 
59
 
60
+ st.bar_chart(sentiment_df.set_index("Sentiment"))
61
+
62
+ # Generate and display the word cloud
63
+ wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'
64
+ st.image(wordcloud_img, use_column_width=True)
65
+
66
+ # Analyze sentiment on button click
67
+ if st.sidebar.button('Analyze Sentiment'):
68
+ if user_input:
69
+ with st.spinner('Analyzing text...'):
70
+ # VADER sentiment analysis
71
+ vader_score = vader_analyzer.polarity_scores(user_input)['compound']
72
+
73
+ # BERT sentiment analysis
74
+ bert_result = bert_sentiment(user_input)[0]
75
+
76
+ # Display sentiment analysis details
77
+ display_sentiment_analysis(vader_score, bert_result)
78
+ else:
79
+ st.warning("Please enter some text for analysis.")
80
+
81
+ # Section for past sentiment trends
82
+ st.subheader("Past Sentiment Trends (Last 14 Days)")
83
+ fig1 = px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
84
+ st.plotly_chart(fig1)
85
+
86
+ # Section for future sentiment predictions
87
+ st.subheader("Sentiment Prediction for Next 7 Days")
88
+ fig2 = px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
89
+ st.plotly_chart(fig2)
90
+
91
+ # Sentiment Distribution Pie Chart
92
+ st.subheader("Sentiment Distribution")
93
+ fig3 = px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
94
+ names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
95
+ st.plotly_chart(fig3)
96
+
97
+ # Histogram of Sentiment Scores (Distribution)
98
+ st.subheader("Sentiment Score Distribution (Past 14 Days)")
99
+ fig4 = px.histogram(df, x='Sentiment Score', nbins=20, title="Sentiment Score Distribution")
100
+ st.plotly_chart(fig4)
101
+
102
+ # Time-Series Heatmap for Sentiment Over Time
103
+ st.subheader("Sentiment Heatmap (Past 14 Days)")
104
+ df['Day'] = df['Date'].dt.dayofweek
105
+ df['Hour'] = df['Date'].dt.hour
106
+ heatmap_data = df.pivot('Day', 'Hour', 'Sentiment Score')
107
+ fig5 = px.imshow(heatmap_data, title="Heatmap of Sentiment Over Time", labels={'x': 'Hour of Day', 'y': 'Day of Week'})
108
+ st.plotly_chart(fig5)
109
+
110
+ # Scatter plot of Sentiment over Time
111
+ st.subheader("Sentiment Scatter Plot (Past 14 Days)")
112
+ fig6 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
113
+ st.plotly_chart(fig6)
114
 
115
+ # Rolling average of Sentiment (7-day window)
116
+ st.subheader("Rolling Average of Sentiment (7-Day Window)")
117
+ df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
118
+ fig7 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="Rolling Average of Sentiment (7-Day Window)")
119
+ st.plotly_chart(fig7)
120
 
121
+ # Reset button to clear inputs and visualizations
122
+ if st.sidebar.button('Reset Analysis'):
123
+ st.experimental_rerun()