Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,75 +1,87 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
|
|
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
-
import
|
| 6 |
-
import seaborn as sns
|
| 7 |
-
from wordcloud import WordCloud
|
| 8 |
from transformers import pipeline
|
| 9 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 10 |
-
from
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
vader = SentimentIntensityAnalyzer()
|
| 14 |
bert_sentiment = pipeline("sentiment-analysis")
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
return vader_score, bert_result['label'], bert_result['score']
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
st.subheader("Word Cloud of Input Text")
|
| 39 |
-
wordcloud = WordCloud(width=600, height=400, background_color='white').generate(user_input)
|
| 40 |
-
fig, ax = plt.subplots()
|
| 41 |
-
ax.imshow(wordcloud, interpolation='bilinear')
|
| 42 |
-
ax.axis("off")
|
| 43 |
-
st.pyplot(fig)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
sentiment_scores = np.cumsum(np.random.randn(days) * 0.1 + vader_score)
|
| 49 |
-
df = pd.DataFrame({'ds': date_range, 'y': sentiment_scores})
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
future = model.make_future_dataframe(periods=7)
|
| 55 |
-
forecast = model.predict(future)
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
ax.fill_between(forecast['ds'], forecast['yhat_lower'], forecast['yhat_upper'], alpha=0.2, color='blue')
|
| 62 |
-
ax.axhline(0, color='black', linestyle='dashed')
|
| 63 |
-
ax.set_title("Sentiment Trend Prediction")
|
| 64 |
-
ax.set_xlabel("Date")
|
| 65 |
-
ax.set_ylabel("Sentiment Score")
|
| 66 |
-
ax.legend()
|
| 67 |
-
st.pyplot(fig)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
| 1 |
+
import dash
|
| 2 |
+
from dash import dcc, html
|
| 3 |
+
import plotly.express as px
|
| 4 |
+
import plotly.graph_objects as go
|
| 5 |
import pandas as pd
|
| 6 |
import numpy as np
|
| 7 |
+
from datetime import datetime, timedelta
|
|
|
|
|
|
|
| 8 |
from transformers import pipeline
|
| 9 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 10 |
+
from sklearn.linear_model import LinearRegression
|
| 11 |
+
from wordcloud import WordCloud
|
| 12 |
+
import base64
|
| 13 |
+
from io import BytesIO
|
| 14 |
|
| 15 |
+
# Initialize sentiment models
|
|
|
|
| 16 |
bert_sentiment = pipeline("sentiment-analysis")
|
| 17 |
+
vader_analyzer = SentimentIntensityAnalyzer()
|
| 18 |
|
| 19 |
+
# Generate sample past sentiment data
|
| 20 |
+
dates = [datetime.today() - timedelta(days=i) for i in range(14)]
|
| 21 |
+
sentiment_scores = np.random.uniform(-1, 1, len(dates))
|
| 22 |
+
df = pd.DataFrame({"Date": dates, "Sentiment Score": sentiment_scores})
|
| 23 |
|
| 24 |
+
# Train a regression model
|
| 25 |
+
X = np.array(range(len(df))).reshape(-1, 1)
|
| 26 |
+
y = df["Sentiment Score"]
|
| 27 |
+
model = LinearRegression()
|
| 28 |
+
model.fit(X, y)
|
| 29 |
|
| 30 |
+
# Predict for next 7 days
|
| 31 |
+
future_dates = [datetime.today() + timedelta(days=i) for i in range(1, 8)]
|
| 32 |
+
X_future = np.array(range(len(df), len(df) + 7)).reshape(-1, 1)
|
| 33 |
+
predictions = model.predict(X_future)
|
|
|
|
| 34 |
|
| 35 |
+
future_df = pd.DataFrame({"Date": future_dates, "Predicted Sentiment": predictions})
|
| 36 |
+
|
| 37 |
+
# Generate Word Cloud
|
| 38 |
+
def generate_wordcloud(text):
|
| 39 |
+
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
|
| 40 |
+
img = BytesIO()
|
| 41 |
+
wordcloud.to_image().save(img, format='PNG')
|
| 42 |
+
return base64.b64encode(img.getvalue()).decode()
|
| 43 |
+
|
| 44 |
+
# Dash app setup
|
| 45 |
+
app = dash.Dash(__name__)
|
| 46 |
+
app.layout = html.Div([
|
| 47 |
+
html.H1("Sentiment Analysis Dashboard", style={'textAlign': 'center', 'color': '#333'}),
|
| 48 |
+
html.Div([
|
| 49 |
+
dcc.Input(id='text_input', type='text', placeholder='Enter text here...', style={'width': '70%'}),
|
| 50 |
+
html.Button('Analyze', id='analyze_btn', style={'margin-left': '10px'})
|
| 51 |
+
], style={'textAlign': 'center', 'margin-bottom': '20px'}),
|
| 52 |
|
| 53 |
+
html.Div(id='sentiment_output', style={'fontSize': '20px', 'textAlign': 'center'}),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
dcc.Graph(id='sentiment_trend',
|
| 56 |
+
figure=px.line(df, x='Date', y='Sentiment Score', title='Past Sentiment Trends', markers=True, line_shape='spline')
|
| 57 |
+
),
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
dcc.Graph(id='future_trend',
|
| 60 |
+
figure=px.line(future_df, x='Date', y='Predicted Sentiment', title='Sentiment Prediction for Next 7 Days', markers=True, line_shape='spline')
|
| 61 |
+
),
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
dcc.Graph(id='sentiment_pie',
|
| 64 |
+
figure=px.pie(values=[sum(df['Sentiment Score'] > 0), sum(df['Sentiment Score'] <= 0)],
|
| 65 |
+
names=['Positive', 'Negative'], title='Sentiment Distribution', hole=0.3)
|
| 66 |
+
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
html.Img(id='wordcloud_img', style={'width': '50%', 'margin-top': '20px', 'display': 'block', 'margin-left': 'auto', 'margin-right': 'auto'})
|
| 69 |
+
])
|
| 70 |
+
|
| 71 |
+
@app.callback(
|
| 72 |
+
[dash.dependencies.Output('sentiment_output', 'children'),
|
| 73 |
+
dash.dependencies.Output('wordcloud_img', 'src')],
|
| 74 |
+
[dash.dependencies.Input('analyze_btn', 'n_clicks')],
|
| 75 |
+
[dash.dependencies.State('text_input', 'value')]
|
| 76 |
+
)
|
| 77 |
+
def analyze_sentiment(n_clicks, text):
|
| 78 |
+
if n_clicks:
|
| 79 |
+
vader_score = vader_analyzer.polarity_scores(text)['compound']
|
| 80 |
+
bert_result = bert_sentiment(text)[0]
|
| 81 |
+
explanation = f"VADER Score: {vader_score:.2f}, BERT Sentiment: {bert_result['label']} ({bert_result['score']:.2f})"
|
| 82 |
+
wordcloud_img = f'data:image/png;base64,{generate_wordcloud(text)}'
|
| 83 |
+
return explanation, wordcloud_img
|
| 84 |
+
return '', ''
|
| 85 |
|
| 86 |
+
if __name__ == '__main__':
|
| 87 |
+
app.run_server(debug=True)
|