Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines1314151617184 unmodified lines232425262728293031323334353637389 unmodified lines4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612 unmodified linesfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoder# Ensure necessary NLTK data is availablenltk.download('punkt')4 unmodified linesst.markdown("Analyze sentiments with deep insights and visualizations")# Sidebar for user inputst.sidebar.header("Upload your dataset")uploaded_file = st.sidebar.file_uploader("Upload a CSV file", type=["csv"])if uploaded_file is not None:df = pd.read_csv(uploaded_file)st.sidebar.success("File uploaded successfully!")else:st.sidebar.warning("Please upload a CSV file to proceed.")# Sample Text Inputst.sidebar.subheader("Enter Text for Sentiment Analysis")user_input = st.sidebar.text_area("Type or paste text here", "The product is amazing!")9 unmodified linesresult = bert_sentiment(text)[0]return result['label']if user_input:vader_result = analyze_vader_sentiment(user_input)bert_result = analyze_bert_sentiment(user_input)st.sidebar.markdown(f"**VADER Sentiment:** {vader_result}")st.sidebar.markdown(f"**BERT Sentiment:** {bert_result}")# If dataset is uploaded, analyze sentimentsif uploaded_file is not None:df['VADER Sentiment'] = df['text'].apply(analyze_vader_sentiment)df['BERT Sentiment'] = df['text'].apply(analyze_bert_sentiment)# Sentiment Distributionst.subheader("๐ Sentiment Distribution")fig, ax = plt.subplots()sns.countplot(x=df['VADER Sentiment'], palette="coolwarm", ax=ax)st.pyplot(fig)# Word Cloudst.subheader("โ๏ธ Word Cloud")sentiment_filter = st.selectbox("Filter Word Cloud by Sentiment", ["All", "Positive", "Neutral", "Negative"])if sentiment_filter != "All":filtered_df = df[df['VADER Sentiment'] == sentiment_filter]else:filtered_df = dfall_text = " ".join(filtered_df['text'].dropna().astype(str))wordcloud = WordCloud(width=800, height=400, background_color='white').generate(all_text)st.image(wordcloud.to_array(), use_column_width=True)# Sentiment Over Time (Simulated for Demo)st.subheader("๐ Sentiment Trend Over Time")df['date'] = pd.date_range(end=datetime.today(), periods=len(df), freq='D')sentiment_map = {'Positive': 1, 'Neutral': 0, 'Negative': -1}df['sentiment_score'] = df['VADER Sentiment'].map(sentiment_map)fig = px.line(df, x='date', y='sentiment_score', title='Sentiment Trend')st.plotly_chart(fig)# Regression Model for Sentiment Predictionst.subheader("๐ Sentiment Prediction")label_encoder = LabelEncoder()df['sentiment_encoded'] = label_encoder.fit_transform(df['VADER Sentiment'])X = np.array(range(len(df))).reshape(-1, 1)y = df['sentiment_encoded']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)model = LinearRegression()model.fit(X_train, y_train)future_days = np.array(range(len(df), len(df) + 30)).reshape(-1, 1)predicted_sentiments = model.predict(future_days)fig_pred = px.line(x=range(len(df), len(df) + 30), y=predicted_sentiments, title='Predicted Sentiment Trend')st.plotly_chart(fig_pred)# Interactive Pie Chartst.subheader("๐ Sentiment Breakdown")sentiment_counts = df['VADER Sentiment'].value_counts()fig_pie = px.pie(names=sentiment_counts.index, values=sentiment_counts.values, title="Sentiment Breakdown")st.plotly_chart(fig_pie)# Sentiment Heatmapst.subheader("๐ฅ Sentiment Heatmap")heatmap_df = df.pivot_table(index=df['date'].dt.date, columns='VADER Sentiment', aggfunc='size', fill_value=0)fig_heatmap = px.imshow(heatmap_df.T, title="Sentiment Heatmap", labels=dict(x="Date", y="Sentiment", color="Count"))st.plotly_chart(fig_heatmap)# Keyword Sentiment Analysisst.subheader("๐ Keyword Sentiment Analysis")keyword = st.text_input("Enter a keyword to analyze sentiment", "great")keyword_df = df[df['text'].str.contains(keyword, case=False, na=False)]st.write(keyword_df[['text', 'VADER Sentiment']])# Download Report as CSVst.subheader("๐ Download Report")csv = df.to_csv(index=False).encode('utf-8')st.download_button(label="Download CSV", data=csv, file_name="sentiment_analysis.csv", mime='text/csv')st.sidebar.markdown("Developed with โค๏ธ")12 unmodified lines13141516171819204 unmodified lines2526272829309 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511612 unmodified linesfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoderfrom io import BytesIOimport base64# Ensure necessary NLTK data is availablenltk.download('punkt')4 unmodified linesst.markdown("Analyze sentiments with deep insights and visualizations")# Sidebar for user inputst.sidebar.subheader("Enter Text for Sentiment Analysis")user_input = st.sidebar.text_area("Type or paste text here", "The product is amazing!")9 unmodified linesresult = bert_sentiment(text)[0]return result['label']def analyze_textblob_sentiment(text):return "Positive" if TextBlob(text).sentiment.polarity > 0 else "Negative" if TextBlob(text).sentiment.polarity < 0 else "Neutral"if user_input:vader_result = analyze_vader_sentiment(user_input)bert_result = analyze_bert_sentiment(user_input)textblob_result = analyze_textblob_sentiment(user_input)st.sidebar.markdown(f"**VADER Sentiment:** {vader_result}")st.sidebar.markdown(f"**BERT Sentiment:** {bert_result}")st.sidebar.markdown(f"**TextBlob Sentiment:** {textblob_result}")# Simulated past sentiment datadates = [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 modelX = np.array(range(len(df))).reshape(-1, 1)y = df["Sentiment Score"]model = LinearRegression()model.fit(X, y)# Predict for next 7 daysfuture_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})# Past sentiment trendsst.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 predictionsst.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 chartst.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 plotst.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 sentimentst.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)# Generate Word Clouddef 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()# Word Cloudst.subheader("โ๏ธ Word Cloud")if user_input:wordcloud_img = f'data:image/png;base64,{generate_wordcloud(user_input)}'st.image(wordcloud_img, use_column_width=True)# Download Report as CSVst.subheader("๐ Download Report")csv = df.to_csv(index=False).encode('utf-8')st.download_button(label="Download CSV", data=csv, file_name="sentiment_analysis.csv", mime='text/csv')st.sidebar.markdown("Developed with โค๏ธ")
app.py+68-78