Soundaryasos's picture
Update app.py
ef6fd25 verified
raw
history blame
4.82 kB
import streamlit as st
from transformers import pipeline
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import plotly.express as px
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()
# Streamlit app setup
st.title("Interactive Sentiment Analysis Dashboard")
# Sidebar for navigation and settings
st.sidebar.header("Sentiment Analysis Controls")
st.sidebar.subheader("Input")
user_input = st.sidebar.text_input('Enter text for sentiment analysis')
# Display sentiment analysis results
def display_sentiment_analysis(vader_score, bert_result):
st.subheader("Sentiment Analysis Results:")
st.write(f"**VADER Sentiment Score**: {vader_score:.2f}")
st.write(f"**BERT Sentiment**: {bert_result['label']} ({bert_result['score']:.2f})")
sentiment_data = {'Positive': max(0, vader_score), 'Negative': min(0, vader_score), 'Neutral': 1 - abs(vader_score)}
sentiment_df = pd.DataFrame(list(sentiment_data.items()), columns=["Sentiment", "Score"])
st.bar_chart(sentiment_df.set_index("Sentiment"))
wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'
st.image(wordcloud_img, use_column_width=True)
# Analyze sentiment on button click
if st.sidebar.button('Analyze Sentiment'):
if user_input:
with st.spinner('Analyzing text...'):
vader_score = vader_analyzer.polarity_scores(user_input)['compound']
bert_result = bert_sentiment(user_input)[0]
display_sentiment_analysis(vader_score, bert_result)
else:
st.warning("Please enter some text for analysis.")
# Past sentiment trends
st.subheader("Past Sentiment Trends (Last 14 Days)")
fig1 = px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
st.plotly_chart(fig1)
# Future sentiment predictions
st.subheader("Sentiment Prediction for Next 7 Days")
fig2 = px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
st.plotly_chart(fig2)
# Sentiment distribution pie chart
st.subheader("Sentiment Distribution")
fig3 = px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
st.plotly_chart(fig3)
# Histogram of Sentiment Scores
st.subheader("Sentiment Score Distribution (Past 14 Days)")
fig4 = px.histogram(df, x='Sentiment Score', nbins=20, title="Sentiment Score Distribution")
st.plotly_chart(fig4)
# Sentiment heatmap (fixed version)
st.subheader("Sentiment Heatmap (Past 14 Days)")
df['Day'] = df['Date'].dt.dayofweek # Monday=0, Sunday=6
heatmap_data = df.groupby('Day')['Sentiment Score'].mean().reset_index()
heatmap_data = heatmap_data.pivot(index='Day', columns=None, values='Sentiment Score')
fig5 = px.imshow(
[heatmap_data.values],
title="Heatmap of Sentiment Over Time",
labels={'x': 'Day of Week', 'y': 'Sentiment Score'},
color_continuous_scale='RdBu'
)
st.plotly_chart(fig5)
# Sentiment scatter plot
st.subheader("Sentiment Scatter Plot (Past 14 Days)")
fig6 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
st.plotly_chart(fig6)
# Rolling average sentiment
st.subheader("Rolling Average of Sentiment (7-Day Window)")
df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
fig7 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="Rolling Average of Sentiment (7-Day Window)")
st.plotly_chart(fig7)
# Reset button
if st.sidebar.button('Reset Analysis'):
st.experimental_rerun()