JoshuaZywoo commited on
Commit
8333387
·
verified ·
1 Parent(s): 68ffcfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -24
app.py CHANGED
@@ -1,10 +1,8 @@
1
- # Smart Customer Support Assistant (Enhanced UI Version)
2
- # Note: Enhanced UI with role avatars, structured suggestions, and end chat functionality
3
-
4
  import streamlit as st
5
  from transformers import pipeline
6
  import re
7
 
 
8
  emotion_classifier = pipeline(
9
  "text-classification",
10
  model="j-hartmann/emotion-english-distilroberta-base",
@@ -13,6 +11,7 @@ emotion_classifier = pipeline(
13
  intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
14
  text_generator = pipeline("text2text-generation", model="declare-lab/flan-alpaca-base")
15
 
 
16
  candidate_tasks = [
17
  "change mobile plan",
18
  "top up balance",
@@ -24,18 +23,7 @@ candidate_tasks = [
24
  "upgrade device"
25
  ]
26
 
27
- def generate_response(intent, human=True):
28
- if human:
29
- prompt = (
30
- f"You are a telecom customer service agent. For the customer intent '{intent}', provide a helpful reply using this 3-part format: "
31
- "[Greeting: short polite opener.] [Middle: Mention customer is currently using Plan X at ¥X/month (fictional), recommend Plan Y with XXGB at ¥Y/month (fictional).] [Ending: Ask if they want to proceed.]"
32
- )
33
- else:
34
- prompt = (
35
- f"You are a helpful telecom AI assistant. Answer the customer intent '{intent}' in a short, friendly, single sentence. Offer relevant support or recommendation directly, using fictional placeholders like Plan X, ¥X, 10GB etc."
36
- )
37
- return text_generator(prompt, max_new_tokens=80, do_sample=False)[0]['generated_text']
38
-
39
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
40
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
41
 
@@ -65,15 +53,35 @@ def get_emotion_score(emotion):
65
  else:
66
  return 0.2
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
69
  st.sidebar.title("📁 Customer Selector")
 
 
70
  if "customers" not in st.session_state:
71
  st.session_state.customers = {"Customer A": [], "Customer B": [], "Customer C": []}
 
 
 
72
  customer_names = list(st.session_state.customers.keys())
73
  selected_customer = st.sidebar.selectbox("Choose a customer:", customer_names)
74
 
75
- if "chat_sessions" not in st.session_state:
76
- st.session_state.chat_sessions = {}
77
  if selected_customer not in st.session_state.chat_sessions:
78
  st.session_state.chat_sessions[selected_customer] = {
79
  "chat": [],
@@ -82,27 +90,28 @@ if selected_customer not in st.session_state.chat_sessions:
82
  "support_required": "",
83
  "user_input": ""
84
  }
 
85
  session = st.session_state.chat_sessions[selected_customer]
86
 
 
87
  st.title("Smart Customer Support Assistant (for Agents Only)")
88
 
 
89
  st.markdown("### Conversation")
90
  for msg in session["chat"]:
91
  avatar = "👤" if msg['role'] == 'user' else ("🤖" if msg.get("auto") else "👨‍💼")
92
  with st.chat_message(msg['role'], avatar=avatar):
93
  st.markdown(msg['content'])
94
 
95
- col1, col2 = st.columns([6,1])
 
96
  with col1:
97
- session["user_input"] = st.text_input("Enter customer message:", value=session["user_input"])
98
  with col2:
99
  analyze_clicked = st.button("Analyze", use_container_width=True)
100
 
101
- if analyze_clicked and session["user_input"].strip():
102
- user_input = session["user_input"]
103
  session["chat"].append({"role": "user", "content": user_input})
104
- session["user_input"] = ""
105
-
106
  emotion_result = emotion_classifier(user_input)
107
  emotion_label = get_emotion_label(emotion_result, user_input)
108
  emotion_score = get_emotion_score(emotion_label)
@@ -133,18 +142,24 @@ if analyze_clicked and session["user_input"].strip():
133
  session["support_required"] = "🔴 Human support required."
134
  session["agent_reply"] = ""
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"])
141
  if st.button("Send Reply"):
142
  if session["agent_reply"].strip():
143
  session["chat"].append({"role": "assistant", "content": session["agent_reply"], "auto": False})
144
  session["agent_reply"] = ""
145
  session["system_result"] = None
146
  session["support_required"] = ""
 
147
 
 
148
  if session["system_result"] is not None:
149
  st.markdown("#### Customer Status")
150
  st.markdown(f"- **Emotion:** {session['system_result']['emotion'].capitalize()}")
@@ -156,6 +171,7 @@ if session["system_result"] is not None:
156
  st.markdown(f"**• {intent.capitalize()}**")
157
  st.code(suggestion)
158
 
 
159
  if st.button("End Conversation"):
160
  session["chat"] = []
161
  session["system_result"] = None
@@ -163,3 +179,4 @@ if st.button("End Conversation"):
163
  session["support_required"] = ""
164
  session["user_input"] = ""
165
  st.success("Conversation ended and cleared.")
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  import re
4
 
5
+ # Load models
6
  emotion_classifier = pipeline(
7
  "text-classification",
8
  model="j-hartmann/emotion-english-distilroberta-base",
 
11
  intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
12
  text_generator = pipeline("text2text-generation", model="declare-lab/flan-alpaca-base")
13
 
14
+ # Predefined customer intents
15
  candidate_tasks = [
16
  "change mobile plan",
17
  "top up balance",
 
23
  "upgrade device"
24
  ]
25
 
26
+ # Emotion refinement
 
 
 
 
 
 
 
 
 
 
 
27
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
28
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
29
 
 
53
  else:
54
  return 0.2
55
 
56
+ def generate_response(intent, human=True):
57
+ if human:
58
+ prompt = (
59
+ f"You are a telecom customer service agent. For the customer intent '{intent}', generate a 3-sentence response:\n"
60
+ "[Greeting: polite opener.]\n"
61
+ "[Middle: State that current plan is Plan X, ¥X/month, and recommend Plan Y with XXGB at ¥Y/month. Use fictional values.]\n"
62
+ "[End: Ask if they'd like to proceed. One sentence only.]"
63
+ )
64
+ else:
65
+ prompt = (
66
+ f"You are a helpful telecom assistant. Briefly resolve the intent '{intent}' in one sentence. "
67
+ "Use placeholders like Plan X, ¥X/month, and keep the tone friendly."
68
+ )
69
+ result = text_generator(prompt, max_new_tokens=80, do_sample=False)
70
+ return result[0]['generated_text'].strip()
71
+
72
+ # Streamlit config
73
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
74
  st.sidebar.title("📁 Customer Selector")
75
+
76
+ # Session state setup
77
  if "customers" not in st.session_state:
78
  st.session_state.customers = {"Customer A": [], "Customer B": [], "Customer C": []}
79
+ if "chat_sessions" not in st.session_state:
80
+ st.session_state.chat_sessions = {}
81
+
82
  customer_names = list(st.session_state.customers.keys())
83
  selected_customer = st.sidebar.selectbox("Choose a customer:", customer_names)
84
 
 
 
85
  if selected_customer not in st.session_state.chat_sessions:
86
  st.session_state.chat_sessions[selected_customer] = {
87
  "chat": [],
 
90
  "support_required": "",
91
  "user_input": ""
92
  }
93
+
94
  session = st.session_state.chat_sessions[selected_customer]
95
 
96
+ # Title
97
  st.title("Smart Customer Support Assistant (for Agents Only)")
98
 
99
+ # Conversation display
100
  st.markdown("### Conversation")
101
  for msg in session["chat"]:
102
  avatar = "👤" if msg['role'] == 'user' else ("🤖" if msg.get("auto") else "👨‍💼")
103
  with st.chat_message(msg['role'], avatar=avatar):
104
  st.markdown(msg['content'])
105
 
106
+ # Customer input and Analyze
107
+ col1, col2 = st.columns([6, 1])
108
  with col1:
109
+ user_input = st.text_input("Enter customer message:", key="customer_input")
110
  with col2:
111
  analyze_clicked = st.button("Analyze", use_container_width=True)
112
 
113
+ if analyze_clicked and user_input.strip():
 
114
  session["chat"].append({"role": "user", "content": user_input})
 
 
115
  emotion_result = emotion_classifier(user_input)
116
  emotion_label = get_emotion_label(emotion_result, user_input)
117
  emotion_score = get_emotion_score(emotion_label)
 
142
  session["support_required"] = "🔴 Human support required."
143
  session["agent_reply"] = ""
144
 
145
+ st.rerun()
146
+
147
+ # Support judgment display
148
  if session["support_required"]:
149
  st.markdown(f"### {session['support_required']}")
150
 
151
+ # Agent input
152
  st.subheader("Agent Response Console")
153
+ session["agent_reply"] = st.text_area("Compose your reply:", value=session["agent_reply"], key="agent_reply_box")
154
  if st.button("Send Reply"):
155
  if session["agent_reply"].strip():
156
  session["chat"].append({"role": "assistant", "content": session["agent_reply"], "auto": False})
157
  session["agent_reply"] = ""
158
  session["system_result"] = None
159
  session["support_required"] = ""
160
+ st.experimental_rerun()
161
 
162
+ # If human needed: show analysis & suggestions
163
  if session["system_result"] is not None:
164
  st.markdown("#### Customer Status")
165
  st.markdown(f"- **Emotion:** {session['system_result']['emotion'].capitalize()}")
 
171
  st.markdown(f"**• {intent.capitalize()}**")
172
  st.code(suggestion)
173
 
174
+ # End conversation button
175
  if st.button("End Conversation"):
176
  session["chat"] = []
177
  session["system_result"] = None
 
179
  session["support_required"] = ""
180
  session["user_input"] = ""
181
  st.success("Conversation ended and cleared.")
182
+ st.rerun()