Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines678910112 unmodified lines1415161718191 unmodified line21222324252627113 unmodified lines14114214314414514699 unmodified lines24624724824925025125221 unmodified lines27427527627727827994 unmodified lines3743753763773783793809 unmodified lines3903913923933943955 unmodified linesfrom datetime import datetime, timedeltaimport plotly.express as pxfrom sklearn.linear_model import Ridgefrom wordcloud import WordCloudimport base64from io import BytesIO2 unmodified linesimport prawfrom googleapiclient.discovery import buildimport os# --------------------------# Initial Setup & Configuration1 unmodified line# Set page configst.set_page_config(page_title="๐ SentimentSync: Live Sentiment Analysis Dashboard",page_icon="๐",layout="wide")113 unmodified linesst.error(f"Error generating word cloud: {str(e)}")return ""# --------------------------# Data Fetching Functions# --------------------------99 unmodified lines# --------------------------def main():st.title("๐ SentimentSync: Live Sentiment Analysis Dashboard")# Sidebar controlswith st.sidebar:21 unmodified linesst.markdown("---")st.markdown("### Settings")show_raw_data = st.checkbox("Show raw data", value=False)st.markdown("---")st.button("๐ Reset Analysis")94 unmodified linesst.subheader("๐ Word Cloud")combined_text = " ".join(df['text'])wordcloud_img = f'data:image/png;base64,{generate_wordcloud(combined_text)}'st.image(wordcloud_img, use_column_width=True)# Filter recent data (last 14 days)df['date'] = pd.to_datetime(df['date'])9 unmodified linesst.subheader("๐ Sentiment Distribution")plot_sentiment_distribution(df_recent, keyword)# Raw data (if enabled)if show_raw_data:st.subheader("๐ Raw Data")5 unmodified lines678910111213142 unmodified lines17181920212223241 unmodified line26272829303132113 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329499 unmodified lines39439539639739839940021 unmodified lines42242342442542642742894 unmodified lines5235245255265275285299 unmodified lines5395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795 unmodified linesfrom datetime import datetime, timedeltaimport plotly.express as pxfrom sklearn.linear_model import Ridgefrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_absolute_errorfrom wordcloud import WordCloudimport base64from io import BytesIO2 unmodified linesimport prawfrom googleapiclient.discovery import buildimport osfrom statsmodels.tsa.arima.model import ARIMAfrom prophet import Prophet# --------------------------# Initial Setup & Configuration1 unmodified line# Set page configst.set_page_config(page_title="๐ SentimentSync: Live Sentiment Analysis & Prediction Dashboard",page_icon="๐",layout="wide")113 unmodified linesst.error(f"Error generating word cloud: {str(e)}")return ""def prepare_time_series_data(df):"""Prepare time series data for forecasting"""try:# Resample to daily datats_df = df.set_index('date').resample('D').agg({'Average': 'mean','VADER': 'mean','BERT': 'mean','TextBlob': 'mean'}).ffill().reset_index()# Create featurests_df['day_of_week'] = ts_df['date'].dt.dayofweekts_df['day_of_month'] = ts_df['date'].dt.dayts_df['days_since_start'] = (ts_df['date'] - ts_df['date'].min()).dt.daysreturn ts_dfexcept Exception as e:st.error(f"Error preparing time series data: {str(e)}")return Nonedef predict_sentiment_prophet(df, periods=15):"""Predict future sentiment using Facebook Prophet"""try:# Prepare data for Prophetprophet_df = df[['date', 'Average']].rename(columns={'date': 'ds', 'Average': 'y'})# Initialize and fit modelmodel = Prophet(daily_seasonality=True,weekly_seasonality=True,yearly_seasonality=False)model.fit(prophet_df)# Make future dataframefuture = model.make_future_dataframe(periods=periods)# Predictforecast = model.predict(future)return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].rename(columns={'ds': 'date','yhat': 'predicted_sentiment','yhat_lower': 'lower_bound','yhat_upper': 'upper_bound'})except Exception as e:st.error(f"Error with Prophet prediction: {str(e)}")return Nonedef predict_sentiment_arima(df, periods=15):"""Predict future sentiment using ARIMA"""try:# Fit ARIMA modelmodel = ARIMA(df['Average'], order=(2, 1, 2))model_fit = model.fit()# Make predictionsforecast = model_fit.forecast(steps=periods)# Create future dateslast_date = df['date'].max()future_dates = [last_date + timedelta(days=i) for i in range(1, periods+1)]return pd.DataFrame({'date': future_dates,'predicted_sentiment': forecast,'model': 'ARIMA'})except Exception as e:st.error(f"Error with ARIMA prediction: {str(e)}")return Nonedef predict_sentiment_rf(df, periods=15):"""Predict future sentiment using Random Forest"""try:# Prepare featurests_df = prepare_time_series_data(df)if ts_df is None or len(ts_df) < 10:return NoneX = ts_df[['days_since_start', 'day_of_week', 'day_of_month']]y = ts_df['Average']# Train modelmodel = RandomForestRegressor(n_estimators=100, random_state=42)model.fit(X, y)# Create future featureslast_date = ts_df['date'].max()future_dates = [last_date + timedelta(days=i) for i in range(1, periods+1)]future_days_since = [(d - ts_df['date'].min()).days for d in future_dates]future_X = pd.DataFrame({'days_since_start': future_days_since,'day_of_week': [d.weekday() for d in future_dates],'day_of_month': [d.day for d in future_dates]})# Make predictionspredictions = model.predict(future_X)return pd.DataFrame({'date': future_dates,'predicted_sentiment': predictions,'model': 'Random Forest'})except Exception as e:st.error(f"Error with Random Forest prediction: {str(e)}")return Nonedef plot_sentiment_predictions(history_df, predictions):"""Plot historical data and predictions"""try:# Prepare historical datahistory_df = history_df.set_index('date').resample('D')['Average'].mean().reset_index()# Create figurefig = px.line(history_df, x='date', y='Average',title='Historical Sentiment & Future Predictions',labels={'Average': 'Sentiment Score'})# Add prediction tracesfor model_name, pred_df in predictions.items():if pred_df is not None:fig.add_scatter(x=pred_df['date'], y=pred_df['predicted_sentiment'],mode='lines', name=f'{model_name} Prediction',line=dict(dash='dot'))# Add confidence interval if availableif 'lower_bound' in pred_df.columns and 'upper_bound' in pred_df.columns:fig.add_trace(px.area(pred_df, x='date',y_upper='upper_bound',y_lower='lower_bound',title='').data[0])fig.update_layout(hovermode="x unified", showlegend=True)return figexcept Exception as e:st.error(f"Error plotting predictions: {str(e)}")return None# --------------------------# Data Fetching Functions# --------------------------99 unmodified lines# --------------------------def main():st.title("๐ SentimentSync: Live Sentiment Analysis & Prediction Dashboard")# Sidebar controlswith st.sidebar:21 unmodified linesst.markdown("---")st.markdown("### Settings")show_raw_data = st.checkbox("Show raw data", value=False)enable_prediction = st.checkbox("Enable sentiment prediction", value=True)st.markdown("---")st.button("๐ Reset Analysis")94 unmodified linesst.subheader("๐ Word Cloud")combined_text = " ".join(df['text'])wordcloud_img = f'data:image/png;base64,{generate_wordcloud(combined_text)}'st.image(wordcloud_img, use_container_width=True)# Filter recent data (last 14 days)df['date'] = pd.to_datetime(df['date'])9 unmodified linesst.subheader("๐ Sentiment Distribution")plot_sentiment_distribution(df_recent, keyword)# Sentiment predictionif enable_prediction and len(df_recent) >= 7: # Need at least 7 days of datast.subheader("๐ฎ Sentiment Prediction (Next 15 Days)")with st.spinner("Training prediction models..."):# Prepare time series datats_df = prepare_time_series_data(df_recent)if ts_df is not None and len(ts_df) >= 7:# Get predictions from different modelspredictions = {'Prophet': predict_sentiment_prophet(ts_df),'ARIMA': predict_sentiment_arima(ts_df),'Random Forest': predict_sentiment_rf(ts_df)}# Filter out None predictionsvalid_predictions = {k: v for k, v in predictions.items() if v is not None}if valid_predictions:# Plot predictionsfig = plot_sentiment_predictions(df_recent, valid_predictions)if fig:st.plotly_chart(fig, use_container_width=True)# Show prediction detailsst.subheader("๐ Prediction Details")for model_name, pred_df in valid_predictions.items():st.markdown(f"**{model_name} Prediction**")st.dataframe(pred_df.set_index('date').style.format("{:.2f}"), use_container_width=True)else:st.warning("Could not generate predictions with the available data.")else:st.warning("Not enough data points for reliable prediction. Need at least 7 days of data.")# Raw data (if enabled)if show_raw_data:st.subheader("๐ Raw Data")
app.py+187-3