Soundaryasos's picture
Update app.py
c1701cd verified
raw
history blame
4.31 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
import nltk
from textblob import TextBlob
nltk.download('punkt')
# Initialize sentiment models
bert_sentiment = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
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("๐ŸŒŸ Advanced Sentiment Analysis Dashboard")
# Sidebar for user input
st.sidebar.header("๐Ÿ” Sentiment Analysis Controls")
user_input = st.sidebar.text_area("Enter text for sentiment analysis")
# Display sentiment analysis results
def display_sentiment_analysis(vader_score, bert_result, textblob_score):
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})")
st.write(f"**TextBlob Sentiment Polarity**: {textblob_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)
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]
textblob_score = TextBlob(user_input).sentiment.polarity
display_sentiment_analysis(vader_score, bert_result, textblob_score)
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='Sentiment Over Time', 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='Predicted Sentiment Trend', 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)
# Sentiment scatter plot
st.subheader("๐Ÿ”Ž Sentiment Scatter Plot (Last 14 Days)")
fig4 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
st.plotly_chart(fig4)
# Rolling average sentiment
st.subheader("๐Ÿ“ˆ Rolling Average of Sentiment (7-Day Window)")
df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
fig5 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="7-Day Rolling Average Sentiment")
st.plotly_chart(fig5)
# Reset button
if st.sidebar.button('๐Ÿ”„ Reset Analysis'):
st.experimental_rerun()