Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,185 +1,105 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
-
import matplotlib.pyplot as plt
|
| 5 |
-
from datetime import datetime, timedelta
|
| 6 |
-
from sklearn.preprocessing import MinMaxScaler
|
| 7 |
-
from sklearn.linear_model import LogisticRegression
|
| 8 |
-
from sklearn.ensemble import RandomForestRegressor
|
| 9 |
-
from sklearn.model_selection import train_test_split
|
| 10 |
-
from sklearn.metrics import mean_squared_error
|
| 11 |
from transformers import pipeline
|
| 12 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 13 |
-
import
|
| 14 |
-
import
|
| 15 |
-
from
|
| 16 |
-
import
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
YOUTUBE_API_KEY = "AIzaSyAChqXPaiNE9hKhApkgjgonzdgiCCOo"
|
| 29 |
-
|
| 30 |
-
reddit = praw.Reddit(client_id=REDDIT_CLIENT_ID, client_secret=REDDIT_CLIENT_SECRET, user_agent=REDDIT_USER_AGENT)
|
| 31 |
-
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
|
| 32 |
-
bert_classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 33 |
vader_analyzer = SentimentIntensityAnalyzer()
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
continue
|
| 121 |
-
|
| 122 |
-
scaler = MinMaxScaler()
|
| 123 |
-
daily_sentiment['scaled_score'] = scaler.fit_transform(daily_sentiment[['combined_score']])
|
| 124 |
-
|
| 125 |
-
# Prepare features: use lagged sentiment scores and tweet counts
|
| 126 |
-
X = pd.DataFrame({
|
| 127 |
-
'lag1_score': daily_sentiment['scaled_score'].shift(1),
|
| 128 |
-
'tweet_count': daily_sentiment['tweet_count']
|
| 129 |
-
}).dropna()
|
| 130 |
-
y = daily_sentiment['scaled_score'][1:] # Align with lagged features
|
| 131 |
-
|
| 132 |
-
if len(X) < 5: # Minimum data for meaningful split
|
| 133 |
-
st.warning(f"Not enough {platform} data points for prediction after lagging.")
|
| 134 |
-
fig, ax = plt.subplots()
|
| 135 |
-
ax.plot(daily_sentiment['date'], daily_sentiment['combined_score'], label='Historical')
|
| 136 |
-
ax.legend()
|
| 137 |
-
st.pyplot(fig)
|
| 138 |
-
continue
|
| 139 |
-
|
| 140 |
-
# Split data for validation
|
| 141 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 142 |
-
|
| 143 |
-
# Train Logistic Regression (using regression mode with continuous output)
|
| 144 |
-
lr_model = LogisticRegression(max_iter=1000)
|
| 145 |
-
lr_model.fit(X_train, (y_train > 0.5).astype(int)) # Binary classification for validation
|
| 146 |
-
lr_pred_train = lr_model.predict_proba(X_train)[:, 1]
|
| 147 |
-
lr_mse = mean_squared_error(y_train, lr_pred_train)
|
| 148 |
-
|
| 149 |
-
# Train Random Forest
|
| 150 |
-
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
|
| 151 |
-
rf_model.fit(X_train, y_train)
|
| 152 |
-
rf_pred_train = rf_model.predict(X_train)
|
| 153 |
-
rf_mse = mean_squared_error(y_train, rf_pred_train)
|
| 154 |
-
|
| 155 |
-
# Weighted ensemble based on inverse MSE
|
| 156 |
-
total_mse = lr_mse + rf_mse
|
| 157 |
-
lr_weight = (1 - lr_mse / total_mse) if total_mse > 0 else 0.5
|
| 158 |
-
rf_weight = (1 - rf_mse / total_mse) if total_mse > 0 else 0.5
|
| 159 |
-
|
| 160 |
-
# Predict 30 days into the future
|
| 161 |
-
last_data = X.iloc[-1:].copy()
|
| 162 |
-
predictions = []
|
| 163 |
-
future_dates = [daily_sentiment['date'].iloc[-1] + timedelta(days=i) for i in range(1, 31)]
|
| 164 |
-
|
| 165 |
-
for _ in range(30):
|
| 166 |
-
lr_pred = lr_model.predict_proba(last_data)[:, 1][0]
|
| 167 |
-
rf_pred = rf_model.predict(last_data)[0]
|
| 168 |
-
ensemble_pred = lr_weight * lr_pred + rf_weight * rf_pred
|
| 169 |
-
predictions.append(ensemble_pred)
|
| 170 |
-
last_data['lag1_score'] = ensemble_pred # Update lag for next prediction
|
| 171 |
-
|
| 172 |
-
predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1)).flatten()
|
| 173 |
-
|
| 174 |
-
st.subheader(f"{platform} 30-Day Prediction (Ensemble: LR + RF)")
|
| 175 |
-
fig, ax = plt.subplots()
|
| 176 |
-
ax.plot(daily_sentiment['date'], daily_sentiment['combined_score'], 'g-', label='Historical')
|
| 177 |
-
ax.plot(future_dates, predictions, 'b--', label=f'Predicted (LR: {lr_weight:.2f}, RF: {rf_weight:.2f})')
|
| 178 |
-
ax.legend()
|
| 179 |
-
st.pyplot(fig)
|
| 180 |
-
|
| 181 |
-
st.subheader(f"{platform} Random Forest SHAP")
|
| 182 |
-
explainer = shap.TreeExplainer(rf_model)
|
| 183 |
-
shap_values = explainer.shap_values(X)
|
| 184 |
-
shap.summary_plot(shap_values, X, show=False)
|
| 185 |
-
st.pyplot(plt.gcf())
|
|
|
|
| 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
|
| 11 |
+
from io import BytesIO
|
| 12 |
+
import nltk
|
| 13 |
+
from textblob import TextBlob
|
| 14 |
+
|
| 15 |
+
nltk.download('punkt')
|
| 16 |
+
|
| 17 |
+
# Initialize sentiment models
|
| 18 |
+
bert_sentiment = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
vader_analyzer = SentimentIntensityAnalyzer()
|
| 20 |
|
| 21 |
+
# Generate sample past sentiment data
|
| 22 |
+
dates = [datetime.today() - timedelta(days=i) for i in range(14)]
|
| 23 |
+
sentiment_scores = np.random.uniform(-1, 1, len(dates))
|
| 24 |
+
df = pd.DataFrame({"Date": dates, "Sentiment Score": sentiment_scores})
|
| 25 |
+
|
| 26 |
+
# Train a regression model
|
| 27 |
+
X = np.array(range(len(df))).reshape(-1, 1)
|
| 28 |
+
y = df["Sentiment Score"]
|
| 29 |
+
model = LinearRegression()
|
| 30 |
+
model.fit(X, y)
|
| 31 |
+
|
| 32 |
+
# Predict for next 7 days
|
| 33 |
+
future_dates = [datetime.today() + timedelta(days=i) for i in range(1, 8)]
|
| 34 |
+
X_future = np.array(range(len(df), len(df) + 7)).reshape(-1, 1)
|
| 35 |
+
predictions = model.predict(X_future)
|
| 36 |
+
|
| 37 |
+
future_df = pd.DataFrame({"Date": future_dates, "Predicted Sentiment": predictions})
|
| 38 |
+
|
| 39 |
+
# Generate Word Cloud
|
| 40 |
+
def generate_wordcloud(text):
|
| 41 |
+
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
|
| 42 |
+
img = BytesIO()
|
| 43 |
+
wordcloud.to_image().save(img, format='PNG')
|
| 44 |
+
return base64.b64encode(img.getvalue()).decode()
|
| 45 |
+
|
| 46 |
+
# Streamlit app setup
|
| 47 |
+
st.title("๐ Advanced Sentiment Analysis Dashboard")
|
| 48 |
+
|
| 49 |
+
# Sidebar for user input
|
| 50 |
+
st.sidebar.header("๐ Sentiment Analysis Controls")
|
| 51 |
+
user_input = st.sidebar.text_area("Enter text for sentiment analysis")
|
| 52 |
+
|
| 53 |
+
# Display sentiment analysis results
|
| 54 |
+
def display_sentiment_analysis(vader_score, bert_result, textblob_score):
|
| 55 |
+
st.subheader("๐ Sentiment Analysis Results:")
|
| 56 |
+
st.write(f"**VADER Sentiment Score**: {vader_score:.2f}")
|
| 57 |
+
st.write(f"**BERT Sentiment**: {bert_result['label']} ({bert_result['score']:.2f})")
|
| 58 |
+
st.write(f"**TextBlob Sentiment Polarity**: {textblob_score:.2f}")
|
| 59 |
+
|
| 60 |
+
sentiment_data = {'Positive': max(0, vader_score), 'Negative': min(0, vader_score), 'Neutral': 1 - abs(vader_score)}
|
| 61 |
+
sentiment_df = pd.DataFrame(list(sentiment_data.items()), columns=["Sentiment", "Score"])
|
| 62 |
+
st.bar_chart(sentiment_df.set_index("Sentiment"))
|
| 63 |
+
|
| 64 |
+
wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'
|
| 65 |
+
st.image(wordcloud_img, use_column_width=True)
|
| 66 |
+
|
| 67 |
+
if st.sidebar.button("Analyze Sentiment"):
|
| 68 |
+
if user_input:
|
| 69 |
+
with st.spinner("Analyzing text..."):
|
| 70 |
+
vader_score = vader_analyzer.polarity_scores(user_input)['compound']
|
| 71 |
+
bert_result = bert_sentiment(user_input)[0]
|
| 72 |
+
textblob_score = TextBlob(user_input).sentiment.polarity
|
| 73 |
+
display_sentiment_analysis(vader_score, bert_result, textblob_score)
|
| 74 |
+
else:
|
| 75 |
+
st.warning("โ ๏ธ Please enter some text for analysis.")
|
| 76 |
+
|
| 77 |
+
# Past sentiment trends
|
| 78 |
+
st.subheader("๐
Past Sentiment Trends (Last 14 Days)")
|
| 79 |
+
fig1 = px.line(df, x='Date', y='Sentiment Score', title='Sentiment Over Time', markers=True, line_shape='spline')
|
| 80 |
+
st.plotly_chart(fig1)
|
| 81 |
+
|
| 82 |
+
# Future sentiment predictions
|
| 83 |
+
st.subheader("๐ฎ Sentiment Prediction for Next 7 Days")
|
| 84 |
+
fig2 = px.line(future_df, x='Date', y='Predicted Sentiment', title='Predicted Sentiment Trend', markers=True, line_shape='spline')
|
| 85 |
+
st.plotly_chart(fig2)
|
| 86 |
+
|
| 87 |
+
# Sentiment distribution pie chart
|
| 88 |
+
st.subheader("๐ Sentiment Distribution")
|
| 89 |
+
fig3 = px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)], names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
|
| 90 |
+
st.plotly_chart(fig3)
|
| 91 |
+
|
| 92 |
+
# Sentiment scatter plot
|
| 93 |
+
st.subheader("๐ Sentiment Scatter Plot (Last 14 Days)")
|
| 94 |
+
fig4 = px.scatter(df, x='Date', y='Sentiment Score', title='Sentiment Over Time')
|
| 95 |
+
st.plotly_chart(fig4)
|
| 96 |
+
|
| 97 |
+
# Rolling average sentiment
|
| 98 |
+
st.subheader("๐ Rolling Average of Sentiment (7-Day Window)")
|
| 99 |
+
df['Rolling Avg Sentiment'] = df['Sentiment Score'].rolling(window=7).mean()
|
| 100 |
+
fig5 = px.line(df, x='Date', y='Rolling Avg Sentiment', title="7-Day Rolling Average Sentiment")
|
| 101 |
+
st.plotly_chart(fig5)
|
| 102 |
+
|
| 103 |
+
# Reset button
|
| 104 |
+
if st.sidebar.button('๐ Reset Analysis'):
|
| 105 |
+
st.experimental_rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|