Soundaryasos commited on
Commit
282c98d
·
verified ·
1 Parent(s): ac270bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -59
app.py CHANGED
@@ -1,75 +1,87 @@
1
- import os
2
- import streamlit as st
 
 
3
  import pandas as pd
4
  import numpy as np
5
- import matplotlib.pyplot as plt
6
- import seaborn as sns
7
- from wordcloud import WordCloud
8
  from transformers import pipeline
9
  from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
10
- from prophet import Prophet
 
 
 
11
 
12
- # Load sentiment analysis models
13
- vader = SentimentIntensityAnalyzer()
14
  bert_sentiment = pipeline("sentiment-analysis")
 
15
 
16
- # Streamlit UI setup
17
- st.title("Sentiment Analysis & Prediction")
 
 
18
 
19
- # User input
20
- user_input = st.text_area("Enter text for sentiment analysis")
 
 
 
21
 
22
- def analyze_sentiment(text):
23
- """Perform sentiment analysis using VADER and BERT."""
24
- vader_score = vader.polarity_scores(text)['compound']
25
- bert_result = bert_sentiment(text)[0]
26
- return vader_score, bert_result['label'], bert_result['score']
27
 
28
- # Process input
29
- if user_input:
30
- vader_score, bert_label, bert_confidence = analyze_sentiment(user_input)
31
-
32
- # Display results
33
- st.subheader("Sentiment Analysis Results")
34
- st.write(f"**VADER Sentiment Score:** {vader_score}")
35
- st.write(f"**BERT Sentiment:** {bert_label} ({bert_confidence:.2f})")
 
 
 
 
 
 
 
 
 
36
 
37
- # Word Cloud
38
- st.subheader("Word Cloud of Input Text")
39
- wordcloud = WordCloud(width=600, height=400, background_color='white').generate(user_input)
40
- fig, ax = plt.subplots()
41
- ax.imshow(wordcloud, interpolation='bilinear')
42
- ax.axis("off")
43
- st.pyplot(fig)
44
 
45
- # Time Series Data for Prediction
46
- days = 30
47
- date_range = pd.date_range(start=pd.Timestamp.today(), periods=days, freq='D')
48
- sentiment_scores = np.cumsum(np.random.randn(days) * 0.1 + vader_score)
49
- df = pd.DataFrame({'ds': date_range, 'y': sentiment_scores})
50
 
51
- # Facebook Prophet Prediction
52
- model = Prophet()
53
- model.fit(df)
54
- future = model.make_future_dataframe(periods=7)
55
- forecast = model.predict(future)
56
 
57
- # Plot predictions
58
- st.subheader("Sentiment Prediction for Next 7 Days")
59
- fig, ax = plt.subplots()
60
- ax.plot(forecast['ds'], forecast['yhat'], label='Predicted Sentiment', color='blue')
61
- ax.fill_between(forecast['ds'], forecast['yhat_lower'], forecast['yhat_upper'], alpha=0.2, color='blue')
62
- ax.axhline(0, color='black', linestyle='dashed')
63
- ax.set_title("Sentiment Trend Prediction")
64
- ax.set_xlabel("Date")
65
- ax.set_ylabel("Sentiment Score")
66
- ax.legend()
67
- st.pyplot(fig)
68
 
69
- # Explanation
70
- st.subheader("What These Results Mean")
71
- st.write("- **VADER Score:** Measures sentiment from -1 (negative) to +1 (positive)")
72
- st.write("- **BERT Sentiment:** Deep learning-based classification")
73
- st.write("- **Prediction Graph:** Expected sentiment trend for the next 7 days")
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- st.write("\n---\nBuilt with Streamlit, VADER, BERT, and Facebook Prophet 🚀")
 
 
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
13
+ from io import BytesIO
14
 
15
+ # Initialize sentiment models
 
16
  bert_sentiment = pipeline("sentiment-analysis")
17
+ vader_analyzer = SentimentIntensityAnalyzer()
18
 
19
+ # Generate sample past sentiment data
20
+ dates = [datetime.today() - timedelta(days=i) for i in range(14)]
21
+ sentiment_scores = np.random.uniform(-1, 1, len(dates))
22
+ df = pd.DataFrame({"Date": dates, "Sentiment Score": sentiment_scores})
23
 
24
+ # Train a regression model
25
+ X = np.array(range(len(df))).reshape(-1, 1)
26
+ y = df["Sentiment Score"]
27
+ model = LinearRegression()
28
+ model.fit(X, y)
29
 
30
+ # Predict for next 7 days
31
+ future_dates = [datetime.today() + timedelta(days=i) for i in range(1, 8)]
32
+ X_future = np.array(range(len(df), len(df) + 7)).reshape(-1, 1)
33
+ predictions = model.predict(X_future)
 
34
 
35
+ future_df = pd.DataFrame({"Date": future_dates, "Predicted Sentiment": predictions})
36
+
37
+ # Generate Word Cloud
38
+ def generate_wordcloud(text):
39
+ wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
40
+ img = BytesIO()
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
 
86
+ if __name__ == '__main__':
87
+ app.run_server(debug=True)