-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
128 lines (101 loc) · 4.59 KB
/
main.py
File metadata and controls
128 lines (101 loc) · 4.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
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
121
122
123
124
125
126
127
import streamlit as st
import pandas as pd
from textblob import TextBlob
import io
st.set_page_config(
page_title="Sentiment Analysis App",
page_icon="📊",
layout="wide"
)
def analyze_sentiment(text):
"""Analyze sentiment of a given text using TextBlob"""
try:
blob = TextBlob(str(text))
polarity = blob.sentiment.polarity
subjectivity = blob.sentiment.subjectivity
# Classify sentiment based on polarity
if polarity > 0.1:
sentiment_label = "Positive"
elif polarity < -0.1:
sentiment_label = "Negative"
else:
sentiment_label = "Neutral"
return polarity, subjectivity, sentiment_label
except:
return 0.0, 0.0, "Neutral"
def main():
st.title("📊 Sentiment Analysis Tool")
st.markdown("Upload a CSV file to analyze sentiment and add sentiment values to your data.")
# File uploader
uploaded_file = st.file_uploader("Choose a CSV file", type=['csv'])
if uploaded_file is not None:
try:
# Read CSV file
df = pd.read_csv(uploaded_file)
st.success(f"✅ File loaded successfully! Found {len(df)} rows.")
# Display column names
st.subheader("📋 File Columns")
st.write(df.columns.tolist())
# Column selection
text_column = st.selectbox(
"Select the column containing text to analyze:",
options=df.columns.tolist(),
index=0
)
if st.button("🔍 Analyze Sentiment"):
with st.spinner("Analyzing sentiment... This may take a moment."):
# Analyze sentiment for each row
results = df[text_column].apply(analyze_sentiment)
# Add sentiment columns to dataframe
df['polarity'] = [r[0] for r in results]
df['subjectivity'] = [r[1] for r in results]
df['sentiment'] = [r[2] for r in results]
st.success("✅ Sentiment analysis complete!")
# Display results
st.subheader("📈 Analysis Results")
st.dataframe(df, use_container_width=True)
# Statistics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Rows", len(df))
with col2:
positive_count = len(df[df['sentiment'] == 'Positive'])
st.metric("Positive", positive_count)
with col3:
negative_count = len(df[df['sentiment'] == 'Negative'])
st.metric("Negative", negative_count)
with col4:
neutral_count = len(df[df['sentiment'] == 'Neutral'])
st.metric("Neutral", neutral_count)
# Download button
csv_buffer = io.StringIO()
df.to_csv(csv_buffer, index=False)
csv_data = csv_buffer.getvalue()
st.download_button(
label="📥 Download CSV with Sentiment Analysis",
data=csv_data,
file_name="sentiment_analysis_results.csv",
mime="text/csv"
)
# Store in session state for later use
st.session_state['analyzed_df'] = df
except Exception as e:
st.error(f"❌ Error processing file: {str(e)}")
st.info("Please make sure your CSV file is properly formatted.")
else:
st.info("👆 Please upload a CSV file to get started.")
# Sample CSV format
st.subheader("📝 Expected CSV Format")
sample_data = {
'id': [1, 2, 3],
'text': [
'I love this product! It is amazing.',
'This is terrible. Very disappointed.',
'It is okay, nothing special.'
]
}
sample_df = pd.DataFrame(sample_data)
st.dataframe(sample_df)
st.caption("Your CSV should contain at least one column with text data to analyze.")
if __name__ == "__main__":
main()