Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import requests
|
| 4 |
-
import
|
| 5 |
|
| 6 |
# Define your API key and endpoint
|
| 7 |
api_key = 'AIzaSyAQ4dXlOkF8rPC21f6omTS4p6v-uJ2vVIg'
|
|
@@ -37,67 +37,87 @@ def analyze_sentiment(text):
|
|
| 37 |
st.error(f"Request failed with status code {response.status_code}: {response.text}")
|
| 38 |
return None
|
| 39 |
|
| 40 |
-
def
|
| 41 |
"""
|
| 42 |
-
|
| 43 |
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
if line.startswith("Comment:"):
|
| 56 |
-
comment = line.replace("Comment:", "").strip()
|
| 57 |
-
elif line.startswith("Sentiment:"):
|
| 58 |
-
sentiment = line.replace("Sentiment:", "").strip()
|
| 59 |
-
if comment and sentiment:
|
| 60 |
-
results.append((comment, sentiment))
|
| 61 |
-
comment = None
|
| 62 |
-
sentiment = None
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
st.bar_chart(sentiment_counts.set_index('Sentiment'))
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
current_section = "Suggestions for Improvement"
|
| 81 |
-
elif current_section and line.startswith("- "):
|
| 82 |
-
suggestions.append(line.replace("- ", "").strip())
|
| 83 |
-
if suggestions:
|
| 84 |
-
st.write("### Suggestions for Improvement")
|
| 85 |
-
for suggestion in suggestions:
|
| 86 |
-
st.write(f"- {suggestion}")
|
| 87 |
-
else:
|
| 88 |
-
st.warning("No suggestions available.")
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
else:
|
| 100 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
# Streamlit layout
|
| 103 |
st.set_page_config(page_title="Sentiment Analysis Tool", layout="wide")
|
|
@@ -108,9 +128,9 @@ st.write("Analyze customer feedback with sentiment classification and actionable
|
|
| 108 |
with st.sidebar:
|
| 109 |
st.header("Instructions π")
|
| 110 |
st.write("""
|
| 111 |
-
1. Upload
|
| 112 |
2. Analyze real-time feedback using the text input box.
|
| 113 |
-
3. Download sentiment analysis results as
|
| 114 |
""")
|
| 115 |
st.write("---")
|
| 116 |
st.header("About")
|
|
@@ -120,11 +140,27 @@ with st.sidebar:
|
|
| 120 |
tab1, tab2 = st.tabs(["π File Analysis", "βοΈ Real-Time Feedback"])
|
| 121 |
|
| 122 |
with tab1:
|
| 123 |
-
st.write("### Upload
|
| 124 |
-
|
| 125 |
-
if
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
with tab2:
|
| 130 |
st.write("### Enter your feedback for real-time analysis:")
|
|
@@ -146,4 +182,4 @@ with tab2:
|
|
| 146 |
else:
|
| 147 |
st.warning(f"Sentiment: **Unknown** π€")
|
| 148 |
else:
|
| 149 |
-
st.error("Sentiment analysis failed.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import requests
|
| 4 |
+
import json
|
| 5 |
|
| 6 |
# Define your API key and endpoint
|
| 7 |
api_key = 'AIzaSyAQ4dXlOkF8rPC21f6omTS4p6v-uJ2vVIg'
|
|
|
|
| 37 |
st.error(f"Request failed with status code {response.status_code}: {response.text}")
|
| 38 |
return None
|
| 39 |
|
| 40 |
+
def read_file_content(file, file_type):
|
| 41 |
"""
|
| 42 |
+
Read the entire content of the file based on its type.
|
| 43 |
"""
|
| 44 |
+
if file_type == 'csv':
|
| 45 |
+
df = pd.read_csv(file)
|
| 46 |
+
text = ' '.join(df.apply(lambda x: ' '.join(x.dropna().astype(str)), axis=1))
|
| 47 |
+
elif file_type == 'xlsx':
|
| 48 |
+
df = pd.read_excel(file)
|
| 49 |
+
text = ' '.join(df.apply(lambda x: ' '.join(x.dropna().astype(str)), axis=1))
|
| 50 |
+
elif file_type == 'json':
|
| 51 |
+
df = pd.read_json(file)
|
| 52 |
+
text = ' '.join(df.apply(lambda x: ' '.join(x.dropna().astype(str)), axis=1))
|
| 53 |
+
elif file_type == 'txt' or file_type == 'md':
|
| 54 |
+
text = file.read().decode('utf-8')
|
| 55 |
+
else:
|
| 56 |
+
st.error("Unsupported file type.")
|
| 57 |
+
return None
|
| 58 |
+
return text
|
| 59 |
|
| 60 |
+
def process_large_text(text, chunk_size=5000):
|
| 61 |
+
"""
|
| 62 |
+
Split large text into smaller chunks for processing.
|
| 63 |
+
"""
|
| 64 |
+
chunks = [text[i:i + chunk_size] for i in range(0, len(text), chunk_size)]
|
| 65 |
+
return chunks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
def display_sentiment_results(response_text, file_name):
|
| 68 |
+
"""
|
| 69 |
+
Display sentiment analysis results for a single file.
|
| 70 |
+
"""
|
| 71 |
+
# Parse comments and sentiments
|
| 72 |
+
results = []
|
| 73 |
+
lines = response_text.split('\n')
|
| 74 |
+
comment = None
|
| 75 |
+
sentiment = None
|
| 76 |
+
for line in lines:
|
| 77 |
+
if line.startswith("Comment:"):
|
| 78 |
+
comment = line.replace("Comment:", "").strip()
|
| 79 |
+
elif line.startswith("Sentiment:"):
|
| 80 |
+
sentiment = line.replace("Sentiment:", "").strip()
|
| 81 |
+
if comment and sentiment:
|
| 82 |
+
results.append((comment, sentiment))
|
| 83 |
+
comment = None
|
| 84 |
+
sentiment = None
|
| 85 |
|
| 86 |
+
# Display results
|
| 87 |
+
st.write(f"### Sentiment Analysis Results for **{file_name}**")
|
| 88 |
+
df_results = pd.DataFrame(results, columns=['Comment/Prompt', 'Sentiment'])
|
| 89 |
+
st.dataframe(df_results)
|
|
|
|
| 90 |
|
| 91 |
+
# Sentiment distribution
|
| 92 |
+
sentiment_counts = df_results['Sentiment'].value_counts().reset_index()
|
| 93 |
+
sentiment_counts.columns = ['Sentiment', 'Count']
|
| 94 |
+
with st.expander(f"View Sentiment Distribution for {file_name}"):
|
| 95 |
+
st.bar_chart(sentiment_counts.set_index('Sentiment'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# Suggestions
|
| 98 |
+
suggestions = []
|
| 99 |
+
current_section = None
|
| 100 |
+
for line in lines:
|
| 101 |
+
if line.startswith("### Suggestions for Improvement:"):
|
| 102 |
+
current_section = "Suggestions for Improvement"
|
| 103 |
+
elif current_section and line.startswith("- "):
|
| 104 |
+
suggestions.append(line.replace("- ", "").strip())
|
| 105 |
+
if suggestions:
|
| 106 |
+
st.write("### Suggestions for Improvement")
|
| 107 |
+
for suggestion in suggestions:
|
| 108 |
+
st.write(f"- {suggestion}")
|
| 109 |
else:
|
| 110 |
+
st.warning("No suggestions available.")
|
| 111 |
+
|
| 112 |
+
# CSV download
|
| 113 |
+
output_file = f"sentiment_analysis_results_{file_name}.csv"
|
| 114 |
+
df_results.to_csv(output_file, index=False)
|
| 115 |
+
st.download_button(
|
| 116 |
+
label=f"Download Results for {file_name} as CSV",
|
| 117 |
+
data=open(output_file, 'rb').read(),
|
| 118 |
+
file_name=output_file,
|
| 119 |
+
mime='text/csv',
|
| 120 |
+
)
|
| 121 |
|
| 122 |
# Streamlit layout
|
| 123 |
st.set_page_config(page_title="Sentiment Analysis Tool", layout="wide")
|
|
|
|
| 128 |
with st.sidebar:
|
| 129 |
st.header("Instructions π")
|
| 130 |
st.write("""
|
| 131 |
+
1. Upload one or more files containing customer feedback in the main area.
|
| 132 |
2. Analyze real-time feedback using the text input box.
|
| 133 |
+
3. Download sentiment analysis results as CSV files.
|
| 134 |
""")
|
| 135 |
st.write("---")
|
| 136 |
st.header("About")
|
|
|
|
| 140 |
tab1, tab2 = st.tabs(["π File Analysis", "βοΈ Real-Time Feedback"])
|
| 141 |
|
| 142 |
with tab1:
|
| 143 |
+
st.write("### Upload one or more files for batch sentiment analysis:")
|
| 144 |
+
uploaded_files = st.file_uploader("Choose files", type=["csv", "xlsx", "json", "txt", "md"], accept_multiple_files=True)
|
| 145 |
+
if uploaded_files:
|
| 146 |
+
for uploaded_file in uploaded_files:
|
| 147 |
+
file_type = uploaded_file.name.split('.')[-1]
|
| 148 |
+
with st.spinner(f"Processing {uploaded_file.name}..."):
|
| 149 |
+
# Read the entire file content
|
| 150 |
+
text = read_file_content(uploaded_file, file_type)
|
| 151 |
+
if text:
|
| 152 |
+
# Process large text in chunks if necessary
|
| 153 |
+
chunks = process_large_text(text)
|
| 154 |
+
combined_results = ""
|
| 155 |
+
for chunk in chunks:
|
| 156 |
+
sentiment_result = analyze_sentiment(chunk)
|
| 157 |
+
if sentiment_result:
|
| 158 |
+
response_text = sentiment_result.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', '').strip()
|
| 159 |
+
combined_results += response_text + "\n"
|
| 160 |
+
if combined_results:
|
| 161 |
+
display_sentiment_results(combined_results, uploaded_file.name)
|
| 162 |
+
else:
|
| 163 |
+
st.error(f"Sentiment analysis failed for {uploaded_file.name}.")
|
| 164 |
|
| 165 |
with tab2:
|
| 166 |
st.write("### Enter your feedback for real-time analysis:")
|
|
|
|
| 182 |
else:
|
| 183 |
st.warning(f"Sentiment: **Unknown** π€")
|
| 184 |
else:
|
| 185 |
+
st.error("Sentiment analysis failed.")
|