Soundaryasos's picture
Update app.py
282c98d verified
raw
history blame
3.53 kB
import dash
from dash import dcc, html
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from transformers import pipeline
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from sklearn.linear_model import LinearRegression
from wordcloud import WordCloud
import base64
from io import BytesIO
# Initialize sentiment models
bert_sentiment = pipeline("sentiment-analysis")
vader_analyzer = SentimentIntensityAnalyzer()
# Generate sample past sentiment data
dates = [datetime.today() - timedelta(days=i) for i in range(14)]
sentiment_scores = np.random.uniform(-1, 1, len(dates))
df = pd.DataFrame({"Date": dates, "Sentiment Score": sentiment_scores})
# Train a regression model
X = np.array(range(len(df))).reshape(-1, 1)
y = df["Sentiment Score"]
model = LinearRegression()
model.fit(X, y)
# Predict for next 7 days
future_dates = [datetime.today() + timedelta(days=i) for i in range(1, 8)]
X_future = np.array(range(len(df), len(df) + 7)).reshape(-1, 1)
predictions = model.predict(X_future)
future_df = pd.DataFrame({"Date": future_dates, "Predicted Sentiment": predictions})
# Generate Word Cloud
def generate_wordcloud(text):
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
img = BytesIO()
wordcloud.to_image().save(img, format='PNG')
return base64.b64encode(img.getvalue()).decode()
# Dash app setup
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1("Sentiment Analysis Dashboard", style={'textAlign': 'center', 'color': '#333'}),
html.Div([
dcc.Input(id='text_input', type='text', placeholder='Enter text here...', style={'width': '70%'}),
html.Button('Analyze', id='analyze_btn', style={'margin-left': '10px'})
], style={'textAlign': 'center', 'margin-bottom': '20px'}),
html.Div(id='sentiment_output', style={'fontSize': '20px', 'textAlign': 'center'}),
dcc.Graph(id='sentiment_trend',
figure=px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
),
dcc.Graph(id='future_trend',
figure=px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
),
dcc.Graph(id='sentiment_pie',
figure=px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
),
html.Img(id='wordcloud_img', style={'width': '50%', 'margin-top': '20px', 'display': 'block', 'margin-left': 'auto', 'margin-right': 'auto'})
])
@app.callback(
[dash.dependencies.Output('sentiment_output', 'children'),
dash.dependencies.Output('wordcloud_img', 'src')],
[dash.dependencies.Input('analyze_btn', 'n_clicks')],
[dash.dependencies.State('text_input', 'value')]
)
def analyze_sentiment(n_clicks, text):
if n_clicks:
vader_score = vader_analyzer.polarity_scores(text)['compound']
bert_result = bert_sentiment(text)[0]
explanation = f"VADER Score: {vader_score:.2f}, BERT Sentiment: {bert_result['label']} ({bert_result['score']:.2f})"
wordcloud_img = f'data:image/png;base64,{generate_wordcloud(text)}'
return explanation, wordcloud_img
return '', ''
if __name__ == '__main__':
app.run_server(debug=True)