JoshuaZywoo commited on
Commit
66128ac
Β·
verified Β·
1 Parent(s): 0e52653

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -44
app.py CHANGED
@@ -1,48 +1,63 @@
1
  import streamlit as st
2
  from transformers import pipeline
 
3
 
4
- # Load models
5
- emotion_classifier = pipeline(
6
- "text-classification",
7
- model="bhadresh-savani/distilbert-base-uncased-emotion",
8
- top_k=3
9
- )
10
 
11
- intent_classifier = pipeline(
12
- "zero-shot-classification",
13
- model="facebook/bart-large-mnli"
14
- )
15
-
16
- # Define emotion priority rules
17
- urgent_emotions = {"anger", "annoyance", "disgust", "frustration", "sadness"}
18
- moderate_emotions = {"confusion", "concern", "nervousness", "fear"}
19
- low_emotions = {"neutral", "approval", "excitement", "joy", "curiosity"}
20
-
21
- # Define candidate customer intents
22
  candidate_tasks = [
23
- "change data plan",
24
  "upgrade phone",
25
  "top up balance",
26
- "report network issue",
27
- "ask for billing help",
28
  "request human support",
29
- "check account status",
30
- "suspend service",
31
- "reactivate number",
32
- "cancel subscription"
33
  ]
34
 
35
- def assess_priority(emotion):
 
 
 
 
 
 
 
 
36
  if emotion in urgent_emotions:
37
- return "πŸ”΄ High", "βœ… Immediate human support is recommended."
38
  elif emotion in moderate_emotions:
39
- return "🟠 Moderate", "⚠️ Human support may be needed soon."
40
- else:
41
- return "🟒 Low", "❌ No human support needed. Automated response is sufficient."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # Streamlit App Interface
44
- st.set_page_config(page_title="AI Customer Support Analyzer", layout="centered")
45
- st.title("πŸ“ž AI Customer Emotion & Intent Analyzer")
46
 
47
  user_input = st.text_area("Please enter the customer's message or conversation:", height=150)
48
 
@@ -52,26 +67,58 @@ if st.button("Analyze"):
52
  else:
53
  with st.spinner("Analyzing..."):
54
 
55
- # --- Emotion Classification ---
56
  emotion_results = emotion_classifier(user_input)
57
  top_emotion = emotion_results[0][0]
58
  emotion_label = top_emotion['label']
59
  emotion_score = top_emotion['score']
60
- priority_level, recommendation = assess_priority(emotion_label)
61
 
 
 
 
 
 
 
 
 
 
 
 
62
  st.subheader("πŸ“Œ Emotion Analysis")
63
  st.write(f"**Primary Emotion**: {emotion_label}")
64
  st.write(f"**Confidence Score**: {emotion_score:.2f}")
65
 
66
- st.subheader("πŸ›ŽοΈ Support Priority Recommendation")
67
- st.write(f"**Priority Level**: {priority_level}")
68
- st.success(recommendation)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- # --- Intent Detection ---
71
- task_result = intent_classifier(user_input, candidate_tasks)
72
- top_tasks = task_result['labels'][:3]
73
- top_scores = task_result['scores'][:3]
74
 
75
- st.subheader("βš™οΈ Detected Possible Customer Intents")
76
- for label, score in zip(top_tasks, top_scores):
77
- st.write(f"πŸ”Έ **{label}** (confidence: {score:.2f})")
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
+ import re
4
 
5
+ # Load HuggingFace models
6
+ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", top_k=3)
7
+ intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
 
 
8
 
9
+ # Candidate intents
 
 
 
 
 
 
 
 
 
 
10
  candidate_tasks = [
11
+ "change mobile plan",
12
  "upgrade phone",
13
  "top up balance",
14
+ "report service outage",
15
+ "ask for billing support",
16
  "request human support",
17
+ "reactivate service",
18
+ "cancel subscription",
19
+ "check account status"
 
20
  ]
21
 
22
+ # Define emotion priority rules
23
+ urgent_emotions = {"anger", "annoyance", "disgust", "frustration", "sadness"}
24
+ moderate_emotions = {"confusion", "concern", "nervousness", "fear"}
25
+
26
+ # Helper: Calculate support score
27
+ def calculate_support_score(text, emotion):
28
+ score = 0.0
29
+
30
+ # Emotion-based scoring
31
  if emotion in urgent_emotions:
32
+ score += 0.5
33
  elif emotion in moderate_emotions:
34
+ score += 0.3
35
+
36
+ # Symbol analysis
37
+ if "!" in text:
38
+ score += 0.1 * min(text.count("!"), 3) # max +0.3
39
+
40
+ # Keyword triggers
41
+ urgent_keywords = ["not working", "out of service", "no signal", "urgent", "immediately", "stopped"]
42
+ for kw in urgent_keywords:
43
+ if kw in text.lower():
44
+ score += 0.2
45
+ break
46
+
47
+ return min(score, 1.0)
48
+
49
+ # Helper: Generate auto-response
50
+ def generate_auto_reply(top_intent):
51
+ intent_responses = {
52
+ "change mobile plan": "You can change your mobile plan by visiting your account dashboard or exploring our latest offers here: [link].",
53
+ "top up balance": "To restore service, please top up your balance through our payment portal: [link].",
54
+ "check account status": "You can check your account status and active services via our self-service portal: [link].",
55
+ }
56
+ return intent_responses.get(top_intent.lower(), "We have received your request and are processing it.")
57
 
58
+ # App UI
59
+ st.set_page_config(page_title="AI Customer Support Decision Engine", layout="centered")
60
+ st.title("πŸ“ž AI Customer Emotion, Intent & Support Decision Analyzer")
61
 
62
  user_input = st.text_area("Please enter the customer's message or conversation:", height=150)
63
 
 
67
  else:
68
  with st.spinner("Analyzing..."):
69
 
70
+ # 1. Emotion Analysis
71
  emotion_results = emotion_classifier(user_input)
72
  top_emotion = emotion_results[0][0]
73
  emotion_label = top_emotion['label']
74
  emotion_score = top_emotion['score']
 
75
 
76
+ # 2. Support Score
77
+ support_score = calculate_support_score(user_input, emotion_label)
78
+
79
+ # 3. Intent Detection
80
+ intent_result = intent_classifier(user_input, candidate_tasks)
81
+ top_labels = intent_result['labels']
82
+ top_scores = intent_result['scores']
83
+ intent_pairs = list(zip(top_labels, top_scores))
84
+ filtered_intents = [(label, score) for label, score in intent_pairs if score > 0.15]
85
+
86
+ # Display emotion
87
  st.subheader("πŸ“Œ Emotion Analysis")
88
  st.write(f"**Primary Emotion**: {emotion_label}")
89
  st.write(f"**Confidence Score**: {emotion_score:.2f}")
90
 
91
+ # Display support recommendation
92
+ st.subheader("πŸ›ŽοΈ Human Support Priority")
93
+ st.write(f"**Support Score**: {support_score:.2f}")
94
+ if support_score >= 0.7:
95
+ st.error("πŸ”΄ Strongly Recommend Human Support")
96
+ elif support_score >= 0.4:
97
+ st.warning("🟠 Consider Human Support")
98
+ else:
99
+ st.success("🟒 Automated Response is Sufficient")
100
+
101
+ # Output decision
102
+ st.subheader("🧠 System Recommendation")
103
+ if support_score < 0.4:
104
+ top_intent = top_labels[0]
105
+ st.markdown(f"πŸ€– **Auto-reply Recommendation**: _{top_intent}_")
106
+ st.info(generate_auto_reply(top_intent))
107
+ else:
108
+ st.markdown("πŸ‘©β€πŸ’Ό **Customer Intent Summary for Human Agent:**")
109
+
110
+ if filtered_intents:
111
+ st.markdown("### πŸ”Ί Priority Pyramid")
112
+ st.markdown(f"- **Primary Intent**: {filtered_intents[0][0]} (confidence: {filtered_intents[0][1]:.2f})")
113
 
114
+ if len(filtered_intents) > 1:
115
+ st.markdown("### πŸ”Έ Secondary Intents")
116
+ for label, score in filtered_intents[1:]:
117
+ st.markdown(f"- {label} (confidence: {score:.2f})")
118
 
119
+ st.markdown("### πŸ”Ή Additional Clues")
120
+ if "!" in user_input:
121
+ st.write("- Urgent tone detected (multiple '!')")
122
+ st.write(f"- Detected Emotion: {emotion_label}")
123
+ else:
124
+ st.info("No clear customer intents detected.")