rajsecrets0's picture
Create app.py
0849020 verified
raw
history blame
5.95 kB
import streamlit as st
import pandas as pd
import requests
import csv
# Define your API key and endpoint
api_key = 'AIzaSyAQ4dXlOkF8rPC21f6omTS4p6v-uJ2vVIg'
url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent"
headers = {'Content-Type': 'application/json'}
# Cache the sentiment analysis function to improve performance
@st.cache_data
def analyze_sentiment(text):
"""
Analyze the sentiment of the given text using the Gemini API.
"""
system_prompt = """
You are a Sentiment Analysis Tool (SEA). Analyze the following comments and classify the sentiment of each as positive, neutral, or negative.
Return the results in the following format:
Comment: <comment>
Sentiment: <sentiment>
---
Additionally, provide actionable insights into customer satisfaction trends in the following format:
### Suggestions for Improvement:
- <suggestion 1>
- <suggestion 2>
"""
data = {
"contents": [{
"parts": [{"text": f"{system_prompt}\n\n{text}"}]
}]
}
response = requests.post(url, headers=headers, json=data, params={'key': api_key})
if response.status_code == 200:
return response.json()
else:
st.error(f"Request failed with status code {response.status_code}: {response.text}")
return None
def process_file(file):
"""
Process the uploaded file, analyze sentiment for all comments, and display results.
"""
file_text = file.read().decode('utf-8')
sentiment_result = analyze_sentiment(file_text)
if sentiment_result:
response_text = sentiment_result.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', '').strip()
# Parse comments and sentiments
results = []
lines = response_text.split('\n')
comment = None
sentiment = None
for line in lines:
if line.startswith("Comment:"):
comment = line.replace("Comment:", "").strip()
elif line.startswith("Sentiment:"):
sentiment = line.replace("Sentiment:", "").strip()
if comment and sentiment:
results.append((comment, sentiment))
comment = None
sentiment = None
# Display results
df = pd.DataFrame(results, columns=['Comment/Prompt', 'Sentiment'])
st.write("### Predicted Sentiments")
st.dataframe(df)
# Sentiment distribution
sentiment_counts = df['Sentiment'].value_counts().reset_index()
sentiment_counts.columns = ['Sentiment', 'Count']
with st.expander("View Sentiment Distribution"):
st.bar_chart(sentiment_counts.set_index('Sentiment'))
# Suggestions
suggestions = []
current_section = None
for line in lines:
if line.startswith("### Suggestions for Improvement:"):
current_section = "Suggestions for Improvement"
elif current_section and line.startswith("- "):
suggestions.append(line.replace("- ", "").strip())
if suggestions:
st.write("### Suggestions for Improvement")
for suggestion in suggestions:
st.write(f"- {suggestion}")
else:
st.warning("No suggestions available.")
# CSV download
output_file = 'sentiment_analysis_results.csv'
df.to_csv(output_file, index=False)
st.download_button(
label="Download Results as CSV",
data=open(output_file, 'rb').read(),
file_name=output_file,
mime='text/csv',
)
else:
st.error("Sentiment analysis failed.")
# Streamlit layout
st.set_page_config(page_title="Sentiment Analysis Tool", layout="wide")
st.title("Sentiment Analysis Tool (SEA) πŸ’¬")
st.write("Analyze customer feedback with sentiment classification and actionable insights.")
# Sidebar for instructions
with st.sidebar:
st.header("Instructions πŸ“„")
st.write("""
1. Upload a CSV file containing customer feedback in the main area.
2. Analyze real-time feedback using the text input box.
3. Download sentiment analysis results as a CSV file.
""")
st.write("---")
st.header("About")
st.write("This app uses the Gemini API for sentiment analysis and provides actionable insights.")
# Main layout with tabs
tab1, tab2 = st.tabs(["πŸ“ File Analysis", "✍️ Real-Time Feedback"])
with tab1:
st.write("### Upload a CSV file for batch sentiment analysis:")
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
with st.spinner("Processing file..."):
process_file(uploaded_file)
with tab2:
st.write("### Enter your feedback for real-time analysis:")
feedback_input = st.text_area("Enter your feedback:", placeholder="Type your feedback here...")
if st.button("Analyze Sentiment"):
if feedback_input.strip() == "":
st.warning("Please enter some feedback to analyze.")
else:
with st.spinner("Analyzing sentiment..."):
sentiment_result = analyze_sentiment(feedback_input)
if sentiment_result:
sentiment = sentiment_result.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', '').strip().lower()
if "positive" in sentiment:
st.success(f"Sentiment: **Positive** 😊")
elif "neutral" in sentiment:
st.info(f"Sentiment: **Neutral** 😐")
elif "negative" in sentiment:
st.error(f"Sentiment: **Negative** 😠")
else:
st.warning(f"Sentiment: **Unknown** πŸ€”")
else:
st.error("Sentiment analysis failed.")