Project / app.py
SarahMakk's picture
Update app.py
2d14efc verified
raw
history blame
3.35 kB
import streamlit as st
from transformers import pipeline
# Load the Hugging Face models
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
# Define the categories for customer feedback
CATEGORIES = ["Pricing", "Feature", "Customer Service", "Delivery", "Quality"]
# Function to map sentiment to a rating (1 to 5)
def sentiment_to_rating(sentiment_label, sentiment_score):
"""
Convert sentiment analysis results (label and score) to a rating from 1 (most negative) to 5 (most positive).
"""
if sentiment_label == "POSITIVE":
if sentiment_score >= 0.8:
return 5 # Most positive
elif sentiment_score >= 0.6:
return 4
elif sentiment_score >= 0.4:
return 3
else:
return 2
elif sentiment_label == "NEGATIVE":
if sentiment_score >= 0.8:
return 1 # Most negative
elif sentiment_score >= 0.6:
return 2
elif sentiment_score >= 0.4:
return 3
else:
return 4
# Streamlit app UI
st.title("Customer Feedback Categorization and Sentiment Analysis")
st.markdown(
"""
This app can detect the topics and intent of customer feedback
and determine the sentiment (rating from 1 to 5) for each relevant category.
"""
)
# Input text box for customer feedback
feedback_input = st.text_area(
"Enter customer feedback:",
placeholder="Type your feedback here...",
height=200
)
# Confidence threshold for displaying categories
threshold = st.slider(
"Confidence Threshold",
min_value=0.0,
max_value=1.0,
value=0.2,
step=0.05,
help="Categories with scores above this threshold will be displayed."
)
# Classify button
if st.button("Analyze Feedback"):
if not feedback_input.strip():
st.error("Please provide valid feedback text.")
else:
# Perform zero-shot classification
classification_result = classifier(feedback_input, CATEGORIES)
# Filter categories with scores above the threshold
relevant_categories = {
label: score
for label, score in zip(classification_result["labels"], classification_result["scores"])
if score >= threshold
}
if relevant_categories:
st.subheader("Categorized Feedback and Sentiment Ratings")
# Perform sentiment analysis for the feedback
sentiment_result = sentiment_analyzer(feedback_input)
sentiment_score = sentiment_result[0]["score"]
sentiment_label = sentiment_result[0]["label"]
# Display results for each category
for category, score in relevant_categories.items():
sentiment_rating = sentiment_to_rating(sentiment_label, sentiment_score)
st.write(
f"**Category**: {category}\n"
f"**Category Score**: {score:.4f}\n"
f"**Sentiment**: {sentiment_label} ({sentiment_score:.4f})\n"
f"**Rating**: {sentiment_rating}/5"
)
st.markdown("---")
else:
st.warning("No categories matched the selected confidence threshold.")