JoshuaZywoo commited on
Commit
80c829c
·
verified ·
1 Parent(s): f0c74bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -64
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import streamlit as st
2
  from transformers import pipeline
3
 
4
- # Load models
5
  emotion_classifier = pipeline(
6
  "text-classification",
7
  model="j-hartmann/emotion-english-distilroberta-base",
@@ -10,25 +10,23 @@ emotion_classifier = pipeline(
10
  intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
11
  text_generator = pipeline("text2text-generation", model="declare-lab/flan-alpaca-base")
12
 
 
13
  candidate_tasks = [
14
- "change mobile plan",
15
- "top up balance",
16
- "report service outage",
17
- "ask for billing support",
18
- "reactivate service",
19
- "cancel subscription",
20
- "check account status",
21
- "upgrade device"
22
  ]
23
 
 
24
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
25
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
26
 
 
27
  def refine_emotion_label(text, model_emotion):
28
  text_lower = text.lower()
29
  urgent_keywords = ["fix", "now", "immediately", "urgent", "can't", "need", "asap"]
30
  exclamations = text.count("!")
31
- upper_words = sum(1 for word in text.split() if word.isupper())
32
  signal_score = sum([
33
  any(word in text_lower for word in urgent_keywords),
34
  exclamations >= 2,
@@ -38,8 +36,8 @@ def refine_emotion_label(text, model_emotion):
38
  return "urgency"
39
  return model_emotion
40
 
41
- def get_emotion_label(emotion_result, text):
42
- sorted_emotions = sorted(emotion_result[0], key=lambda x: x['score'], reverse=True)
43
  return refine_emotion_label(text, sorted_emotions[0]['label'])
44
 
45
  def get_emotion_score(emotion):
@@ -52,17 +50,15 @@ def get_emotion_score(emotion):
52
 
53
  def generate_response(intent, human=True):
54
  prompt = (
55
- f"You are a telecom customer service assistant. For the customer intent '{intent}', generate a 3-part response:
56
- "
57
- "[Greeting: polite welcome.]
58
- "
59
- "[Middle: mention the customer is currently on Plan X (¥X/month), and suggest switching to Plan Y with XXGB at ¥Y/month. Use fictional placeholder values.]
60
- "
61
  "[End: ask if they'd like to proceed with the new plan or need more details.]"
62
  )
63
  result = text_generator(prompt, max_new_tokens=100, do_sample=False)
64
  return result[0]['generated_text'].strip()
65
 
 
66
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
67
  st.sidebar.title("📁 Customer Selector")
68
 
@@ -71,71 +67,68 @@ if "customers" not in st.session_state:
71
  if "chat_sessions" not in st.session_state:
72
  st.session_state.chat_sessions = {}
73
 
74
- customer_names = list(st.session_state.customers.keys())
75
- selected_customer = st.sidebar.selectbox("Choose a customer:", customer_names)
76
 
77
  if selected_customer not in st.session_state.chat_sessions:
78
  st.session_state.chat_sessions[selected_customer] = {
79
- "chat": [],
80
- "system_result": None,
81
- "agent_reply": "",
82
- "support_required": "",
83
- "user_input": ""
84
  }
85
 
86
  session = st.session_state.chat_sessions[selected_customer]
87
-
88
  st.title("Smart Customer Support Assistant (for Agents Only)")
89
 
 
90
  st.markdown("### Conversation")
91
  for msg in session["chat"]:
92
  avatar = "👤" if msg['role'] == 'user' else ("🤖" if msg.get("auto") else "👨‍💼")
93
  with st.chat_message(msg['role'], avatar=avatar):
94
  st.markdown(msg['content'])
95
 
 
96
  col1, col2 = st.columns([6, 1])
97
  with col1:
98
  user_input = st.text_input("Enter customer message:", key="customer_input")
99
  with col2:
100
- analyze_clicked = st.button("Analyze", use_container_width=True)
101
-
102
- if analyze_clicked and user_input.strip():
103
- session["chat"].append({"role": "user", "content": user_input})
104
- emotion_result = emotion_classifier(user_input)
105
- emotion_label = get_emotion_label(emotion_result, user_input)
106
- emotion_score = get_emotion_score(emotion_label)
107
-
108
- intent_result = intent_classifier(user_input, candidate_tasks)
109
- top_intents = [label for label, score in zip(intent_result['labels'], intent_result['scores']) if score > 0.15][:3]
110
-
111
- content_score = 0.0
112
- if any(x in user_input.lower() for x in ["out of service", "can't", "urgent", "immediately"]):
113
- content_score += 0.4
114
- if any(label in ["top up balance", "reactivate service"] for label in top_intents):
115
- content_score += 0.4
116
-
117
- final_score = 0.5 * emotion_score + 0.5 * content_score
118
-
119
- if final_score < 0.5 and top_intents:
120
- intent = top_intents[0]
121
- response = generate_response(intent, human=True)
122
- session["chat"].append({"role": "assistant", "content": response, "auto": True})
123
- session["system_result"] = None
124
- session["support_required"] = "🟢 Automated response handled this request."
125
- else:
126
- session["system_result"] = {
127
- "emotion": emotion_label,
128
- "tone": "Urgent" if emotion_score > 0.8 else "Concerned" if emotion_score > 0.5 else "Calm",
129
- "intents": top_intents
130
- }
131
- session["support_required"] = "🔴 Human support required."
132
- session["agent_reply"] = ""
133
-
134
- st.rerun()
135
-
136
  if session["support_required"]:
137
  st.markdown(f"### {session['support_required']}")
138
 
 
139
  st.subheader("Agent Response Console")
140
  session["agent_reply"] = st.text_area("Compose your reply:", value=session["agent_reply"], key="agent_reply_box")
141
  if st.button("Send Reply"):
@@ -146,17 +139,18 @@ if st.button("Send Reply"):
146
  session["support_required"] = ""
147
  st.experimental_rerun()
148
 
 
149
  if session["system_result"] is not None:
150
  st.markdown("#### Customer Status")
151
  st.markdown(f"- **Emotion:** {session['system_result']['emotion'].capitalize()}")
152
  st.markdown(f"- **Tone:** {session['system_result']['tone']}")
153
-
154
  st.markdown("#### Detected Customer Needs")
155
- for intent in session['system_result']['intents']:
156
  suggestion = generate_response(intent, human=True)
157
  st.markdown(f"**• {intent.capitalize()}**")
158
  st.code(suggestion)
159
 
 
160
  if st.button("End Conversation"):
161
  session["chat"] = []
162
  session["system_result"] = None
 
1
  import streamlit as st
2
  from transformers import pipeline
3
 
4
+ # Load Models
5
  emotion_classifier = pipeline(
6
  "text-classification",
7
  model="j-hartmann/emotion-english-distilroberta-base",
 
10
  intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
11
  text_generator = pipeline("text2text-generation", model="declare-lab/flan-alpaca-base")
12
 
13
+ # Tasks
14
  candidate_tasks = [
15
+ "change mobile plan", "top up balance", "report service outage",
16
+ "ask for billing support", "reactivate service", "cancel subscription",
17
+ "check account status", "upgrade device"
 
 
 
 
 
18
  ]
19
 
20
+ # Emotion Tiers
21
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
22
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
23
 
24
+ # Utilities
25
  def refine_emotion_label(text, model_emotion):
26
  text_lower = text.lower()
27
  urgent_keywords = ["fix", "now", "immediately", "urgent", "can't", "need", "asap"]
28
  exclamations = text.count("!")
29
+ upper_words = sum(1 for w in text.split() if w.isupper())
30
  signal_score = sum([
31
  any(word in text_lower for word in urgent_keywords),
32
  exclamations >= 2,
 
36
  return "urgency"
37
  return model_emotion
38
 
39
+ def get_emotion_label(result, text):
40
+ sorted_emotions = sorted(result[0], key=lambda x: x['score'], reverse=True)
41
  return refine_emotion_label(text, sorted_emotions[0]['label'])
42
 
43
  def get_emotion_score(emotion):
 
50
 
51
  def generate_response(intent, human=True):
52
  prompt = (
53
+ f"You are a telecom customer service assistant. For the customer intent '{intent}', generate a 3-part response:\n"
54
+ "[Greeting: polite welcome.]\n"
55
+ "[Middle: mention the customer is currently on Plan X (¥X/month), and suggest switching to Plan Y with XXGB at ¥Y/month. Use fictional placeholder values.]\n"
 
 
 
56
  "[End: ask if they'd like to proceed with the new plan or need more details.]"
57
  )
58
  result = text_generator(prompt, max_new_tokens=100, do_sample=False)
59
  return result[0]['generated_text'].strip()
60
 
61
+ # App UI Setup
62
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
63
  st.sidebar.title("📁 Customer Selector")
64
 
 
67
  if "chat_sessions" not in st.session_state:
68
  st.session_state.chat_sessions = {}
69
 
70
+ selected_customer = st.sidebar.selectbox("Choose a customer:", list(st.session_state.customers.keys()))
 
71
 
72
  if selected_customer not in st.session_state.chat_sessions:
73
  st.session_state.chat_sessions[selected_customer] = {
74
+ "chat": [], "system_result": None,
75
+ "agent_reply": "", "support_required": "", "user_input": ""
 
 
 
76
  }
77
 
78
  session = st.session_state.chat_sessions[selected_customer]
 
79
  st.title("Smart Customer Support Assistant (for Agents Only)")
80
 
81
+ # Conversation Window
82
  st.markdown("### Conversation")
83
  for msg in session["chat"]:
84
  avatar = "👤" if msg['role'] == 'user' else ("🤖" if msg.get("auto") else "👨‍💼")
85
  with st.chat_message(msg['role'], avatar=avatar):
86
  st.markdown(msg['content'])
87
 
88
+ # Input & Analysis
89
  col1, col2 = st.columns([6, 1])
90
  with col1:
91
  user_input = st.text_input("Enter customer message:", key="customer_input")
92
  with col2:
93
+ if st.button("Analyze"):
94
+ if user_input.strip():
95
+ session["chat"].append({"role": "user", "content": user_input})
96
+ emotion_result = emotion_classifier(user_input)
97
+ emotion_label = get_emotion_label(emotion_result, user_input)
98
+ emotion_score = get_emotion_score(emotion_label)
99
+
100
+ intent_result = intent_classifier(user_input, candidate_tasks)
101
+ top_intents = [label for label, score in zip(intent_result['labels'], intent_result['scores']) if score > 0.15][:3]
102
+
103
+ content_score = 0.0
104
+ if any(x in user_input.lower() for x in ["out of service", "can't", "urgent", "immediately"]):
105
+ content_score += 0.4
106
+ if any(label in ["top up balance", "reactivate service"] for label in top_intents):
107
+ content_score += 0.4
108
+
109
+ final_score = 0.5 * emotion_score + 0.5 * content_score
110
+
111
+ if final_score < 0.5 and top_intents:
112
+ intent = top_intents[0]
113
+ response = generate_response(intent, human=True)
114
+ session["chat"].append({"role": "assistant", "content": response, "auto": True})
115
+ session["system_result"] = None
116
+ session["support_required"] = "🟢 Automated response handled this request."
117
+ else:
118
+ session["system_result"] = {
119
+ "emotion": emotion_label,
120
+ "tone": "Urgent" if emotion_score > 0.8 else "Concerned" if emotion_score > 0.5 else "Calm",
121
+ "intents": top_intents
122
+ }
123
+ session["support_required"] = "🔴 Human support required."
124
+ session["agent_reply"] = ""
125
+ st.rerun()
126
+
127
+ # Support Tag
 
128
  if session["support_required"]:
129
  st.markdown(f"### {session['support_required']}")
130
 
131
+ # Agent Reply Console
132
  st.subheader("Agent Response Console")
133
  session["agent_reply"] = st.text_area("Compose your reply:", value=session["agent_reply"], key="agent_reply_box")
134
  if st.button("Send Reply"):
 
139
  session["support_required"] = ""
140
  st.experimental_rerun()
141
 
142
+ # Human Needed View
143
  if session["system_result"] is not None:
144
  st.markdown("#### Customer Status")
145
  st.markdown(f"- **Emotion:** {session['system_result']['emotion'].capitalize()}")
146
  st.markdown(f"- **Tone:** {session['system_result']['tone']}")
 
147
  st.markdown("#### Detected Customer Needs")
148
+ for intent in session["system_result"]["intents"]:
149
  suggestion = generate_response(intent, human=True)
150
  st.markdown(f"**• {intent.capitalize()}**")
151
  st.code(suggestion)
152
 
153
+ # End Button
154
  if st.button("End Conversation"):
155
  session["chat"] = []
156
  session["system_result"] = None