SarahMakk commited on
Commit
df6a94f
·
verified ·
1 Parent(s): 80d4bd4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -22
app.py CHANGED
@@ -1,5 +1,10 @@
1
  import streamlit as st
2
  from transformers import pipeline
 
 
 
 
 
3
 
4
  # Load the Hugging Face pipelines
5
  classifier = pipeline("zero-shot-classification", model="MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli")
@@ -15,6 +20,7 @@ st.markdown(
15
  This app uses Hugging Face models to detect the topics and intent of customer feedback
16
  and determine the sentiment (positive or negative) for each relevant category.
17
  A single feedback may belong to multiple categories, such as Pricing, Feature, and Customer Service.
 
18
  """
19
  )
20
 
@@ -22,7 +28,8 @@ st.markdown(
22
  feedback_input = st.text_area(
23
  "Enter customer feedback:",
24
  placeholder="Type your feedback here...",
25
- height=200
 
26
  )
27
 
28
  # Confidence threshold for zero-shot classification
@@ -32,7 +39,7 @@ threshold = st.slider(
32
  max_value=1.0,
33
  value=0.2,
34
  step=0.05,
35
- help="Categories with scores above this threshold will be displayed."
36
  )
37
 
38
  # Classify button
@@ -40,29 +47,51 @@ if st.button("Classify Feedback"):
40
  if not feedback_input.strip():
41
  st.error("Please provide valid feedback text.")
42
  else:
43
- # Perform zero-shot classification
44
- classification_result = classifier(feedback_input, CATEGORIES)
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- # Filter categories with scores above the threshold
47
- relevant_categories = {
48
- label: round(score, 4)
49
- for label, score in zip(classification_result["labels"], classification_result["scores"])
50
- if score >= threshold
51
- }
 
52
 
53
- # Check if there are any relevant categories
54
- if relevant_categories:
55
- st.subheader("Categorized Feedback with Sentiment Analysis")
 
 
 
 
56
 
57
- for category, score in relevant_categories.items():
58
- # Extract the part of feedback relevant to the category for sentiment analysis
59
- sentiment_result = sentiment_analyzer(feedback_input)
60
- sentiment_label = sentiment_result[0]["label"]
61
- sentiment_score = round(sentiment_result[0]["score"], 4)
62
 
63
- # Display the category, confidence score, and sentiment result
 
 
 
 
 
64
  st.write(f"### **{category}**")
65
- st.write(f"- Confidence: {score}")
66
- st.write(f"- Sentiment: {sentiment_label} (Score: {sentiment_score})")
67
- else:
 
 
 
 
68
  st.warning("No categories matched the selected confidence threshold.")
 
1
  import streamlit as st
2
  from transformers import pipeline
3
+ import nltk
4
+ import numpy as np
5
+
6
+ # Download NLTK data for sentence tokenization
7
+ nltk.download('punkt')
8
 
9
  # Load the Hugging Face pipelines
10
  classifier = pipeline("zero-shot-classification", model="MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli")
 
20
  This app uses Hugging Face models to detect the topics and intent of customer feedback
21
  and determine the sentiment (positive or negative) for each relevant category.
22
  A single feedback may belong to multiple categories, such as Pricing, Feature, and Customer Service.
23
+ The feedback is split into sentences, and each sentence is categorized and analyzed for sentiment.
24
  """
25
  )
26
 
 
28
  feedback_input = st.text_area(
29
  "Enter customer feedback:",
30
  placeholder="Type your feedback here...",
31
+ height=200,
32
+ value="I was shocked to see the price tag on this new gadget—it’s way too expensive for what it offers, especially compared to competitors! Despite the issues I faced with my order, the customer service team's effort to rectify the situation was commendable, though their follow-up could have used some improvement for full satisfaction."
33
  )
34
 
35
  # Confidence threshold for zero-shot classification
 
39
  max_value=1.0,
40
  value=0.2,
41
  step=0.05,
42
+ help="Categories with confidence scores above this threshold will be displayed."
43
  )
44
 
45
  # Classify button
 
47
  if not feedback_input.strip():
48
  st.error("Please provide valid feedback text.")
49
  else:
50
+ # Split the feedback into sentences
51
+ sentences = nltk.sent_tokenize(feedback_input)
52
+ if not sentences:
53
+ st.error("Could not split feedback into sentences.")
54
+ st.stop()
55
+
56
+ # Dictionary to store results for each category
57
+ category_results = {category: [] for category in CATEGORIES}
58
+
59
+ # Process each sentence
60
+ for sentence in sentences:
61
+ # Perform zero-shot classification on the sentence
62
+ classification_result = classifier(sentence, CATEGORIES, multi_label=True)
63
 
64
+ # Get categories with scores above the threshold
65
+ for label, score in zip(classification_result["labels"], classification_result["scores"]):
66
+ if score >= threshold:
67
+ # Perform sentiment analysis on the sentence
68
+ sentiment_result = sentiment_analyzer(sentence)
69
+ sentiment_label = sentiment_result[0]["label"]
70
+ sentiment_score = round(sentiment_result[0]["score"], 4)
71
 
72
+ # Store the result for the category
73
+ category_results[label].append({
74
+ "sentence": sentence,
75
+ "confidence": round(score, 4),
76
+ "sentiment": sentiment_label,
77
+ "sentiment_score": sentiment_score
78
+ })
79
 
80
+ # Display the results
81
+ st.subheader("Categorized Feedback with Sentiment Analysis")
 
 
 
82
 
83
+ # Flag to check if any categories were found
84
+ found_categories = False
85
+
86
+ for category, results in category_results.items():
87
+ if results: # If the category has any sentences
88
+ found_categories = True
89
  st.write(f"### **{category}**")
90
+ for result in results:
91
+ st.write(f"- **Sentence**: {result['sentence']}")
92
+ st.write(f" - Confidence: {result['confidence']}")
93
+ st.write(f" - Sentiment: {result['sentiment']} (Score: {result['sentiment_score']})")
94
+ st.write("") # Add a blank line for readability
95
+
96
+ if not found_categories:
97
  st.warning("No categories matched the selected confidence threshold.")