JoshuaZywoo commited on
Commit
e3ac22d
·
verified ·
1 Parent(s): ae8e54d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -31
app.py CHANGED
@@ -1,13 +1,10 @@
1
  # Smart Customer Support Assistant (Enhanced UI Version)
2
- # Note: Core analysis logic remains unchanged, now with text generation and customer selection
3
 
4
  import streamlit as st
5
  from transformers import pipeline
6
  import re
7
 
8
- # ------------------------------
9
- # Load models (now includes 3rd: text generation)
10
- # ------------------------------
11
  emotion_classifier = pipeline(
12
  "text-classification",
13
  model="j-hartmann/emotion-english-distilroberta-base",
@@ -16,9 +13,6 @@ emotion_classifier = pipeline(
16
  intent_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
17
  text_generator = pipeline("text2text-generation", model="declare-lab/flan-alpaca-base")
18
 
19
- # ------------------------------
20
- # Candidate tasks / prompts
21
- # ------------------------------
22
  candidate_tasks = [
23
  "change mobile plan",
24
  "top up balance",
@@ -30,22 +24,23 @@ candidate_tasks = [
30
  "upgrade device"
31
  ]
32
 
33
- def generate_response(intent):
34
- prompt = (
35
- f"Generate a customer service reply for: '{intent}'. "
36
- "Structure your answer into: 1. Greeting, 2. Summary of customer's current situation (e.g., current plan is Plan X costing ¥X/month or balance is ¥X), "
37
- "3. Your suggested recommendation (e.g., upgrade to Plan Y with XX GB), and 4. End with a helpful and polite question. "
38
- "Use anonymized or placeholder values for all specific customer data."
39
- )
40
- output = text_generator(prompt, max_new_tokens=100, do_sample=True)[0]['generated_text']
41
- return output
 
 
 
 
42
 
43
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
44
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
45
 
46
- # ------------------------------
47
- # Emotion processing
48
- # ------------------------------
49
  def refine_emotion_label(text, model_emotion):
50
  text_lower = text.lower()
51
  urgent_keywords = ["fix", "now", "immediately", "urgent", "can't", "need", "asap"]
@@ -72,9 +67,6 @@ def get_emotion_score(emotion):
72
  else:
73
  return 0.2
74
 
75
- # ------------------------------
76
- # UI: Sidebar for customer selection
77
- # ------------------------------
78
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
79
  st.sidebar.title("📁 Customer Selector")
80
  if "customers" not in st.session_state:
@@ -82,7 +74,6 @@ if "customers" not in st.session_state:
82
  customer_names = list(st.session_state.customers.keys())
83
  selected_customer = st.sidebar.selectbox("Choose a customer:", customer_names)
84
 
85
- # Load or init selected customer's session
86
  if "chat_sessions" not in st.session_state:
87
  st.session_state.chat_sessions = {}
88
  if selected_customer not in st.session_state.chat_sessions:
@@ -94,14 +85,12 @@ if selected_customer not in st.session_state.chat_sessions:
94
  }
95
  session = st.session_state.chat_sessions[selected_customer]
96
 
97
- # ------------------------------
98
- # Main Interface
99
- # ------------------------------
100
  st.title("Smart Customer Support Assistant (for Agents Only)")
101
 
102
  st.markdown("### Conversation")
103
  for msg in session["chat"]:
104
- with st.chat_message(msg['role']):
 
105
  st.markdown(msg['content'])
106
 
107
  col1, col2 = st.columns([6,1])
@@ -129,8 +118,8 @@ if analyze_clicked and user_input.strip():
129
 
130
  if final_score < 0.5 and top_intents:
131
  intent = top_intents[0]
132
- response = generate_response(intent)
133
- session["chat"].append({"role": "assistant", "content": response})
134
  session["system_result"] = None
135
  session["support_required"] = "🟢 Automated response handled this request."
136
  else:
@@ -148,7 +137,7 @@ st.subheader("Agent Response Console")
148
  session["agent_reply"] = st.text_area("Compose your reply:", value=session["agent_reply"])
149
  if st.button("Send Reply"):
150
  if session["agent_reply"].strip():
151
- session["chat"].append({"role": "assistant", "content": session["agent_reply"]})
152
  session["agent_reply"] = ""
153
  session["system_result"] = None
154
  session["support_required"] = ""
@@ -160,6 +149,13 @@ if session["system_result"] is not None:
160
 
161
  st.markdown("#### Detected Customer Needs")
162
  for intent in session['system_result']['intents']:
163
- suggestion = generate_response(intent)
164
  st.markdown(f"**• {intent.capitalize()}**")
165
  st.code(suggestion)
 
 
 
 
 
 
 
 
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
  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
  "upgrade device"
25
  ]
26
 
27
+ def generate_response(intent, human=True):
28
+ if human:
29
+ prompt = (
30
+ f"Write a customer service message for intent '{intent}'. Structure into: "
31
+ "1. Greeting, 2. Description of customer's current service (Plan X ¥X/GB, etc.) and a suitable new option, "
32
+ "3. A polite closing question. Use placeholder data (Plan X, ¥X, etc.)."
33
+ )
34
+ else:
35
+ prompt = (
36
+ f"Reply to the following user request automatically: '{intent}'. Directly resolve the request in one helpful message. "
37
+ "If it's plan change, suggest suitable options. Use placeholders (Plan A ¥X/5GB, Plan B ¥Y/15GB, etc.)."
38
+ )
39
+ return text_generator(prompt, max_new_tokens=100, do_sample=True)[0]['generated_text']
40
 
41
  urgent_emotions = {"anger", "frustration", "anxiety", "urgency", "afraid", "annoyed"}
42
  moderate_emotions = {"confused", "sad", "tired", "concerned", "sadness"}
43
 
 
 
 
44
  def refine_emotion_label(text, model_emotion):
45
  text_lower = text.lower()
46
  urgent_keywords = ["fix", "now", "immediately", "urgent", "can't", "need", "asap"]
 
67
  else:
68
  return 0.2
69
 
 
 
 
70
  st.set_page_config(page_title="Smart Customer Support Assistant", layout="wide")
71
  st.sidebar.title("📁 Customer Selector")
72
  if "customers" not in st.session_state:
 
74
  customer_names = list(st.session_state.customers.keys())
75
  selected_customer = st.sidebar.selectbox("Choose a customer:", customer_names)
76
 
 
77
  if "chat_sessions" not in st.session_state:
78
  st.session_state.chat_sessions = {}
79
  if selected_customer not in st.session_state.chat_sessions:
 
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])
 
118
 
119
  if final_score < 0.5 and top_intents:
120
  intent = top_intents[0]
121
+ response = generate_response(intent, human=False)
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:
 
137
  session["agent_reply"] = st.text_area("Compose your reply:", value=session["agent_reply"])
138
  if st.button("Send Reply"):
139
  if session["agent_reply"].strip():
140
+ session["chat"].append({"role": "assistant", "content": session["agent_reply"], "auto": False})
141
  session["agent_reply"] = ""
142
  session["system_result"] = None
143
  session["support_required"] = ""
 
149
 
150
  st.markdown("#### Detected Customer Needs")
151
  for intent in session['system_result']['intents']:
152
+ suggestion = generate_response(intent, human=True)
153
  st.markdown(f"**• {intent.capitalize()}**")
154
  st.code(suggestion)
155
+
156
+ if st.button("End Conversation"):
157
+ session["chat"] = []
158
+ session["system_result"] = None
159
+ session["agent_reply"] = ""
160
+ session["support_required"] = ""
161
+ st.success("Conversation ended and cleared.")