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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
class SentimentAnalyzer:
|
3 |
+
def __init__(self):
|
4 |
+
self.model="facebook/bart-large-mnli"
|
5 |
+
|
6 |
+
def analyze_sentiment(self, text):
|
7 |
+
pipe = pipeline("zero-shot-classification", model=self.model)
|
8 |
+
label=["positive","negative","neutral"]
|
9 |
+
result = pipe(text, label)
|
10 |
+
sentiment_scores= {result['labels'][0]:result['scores'][0],result['labels'][1]:result['scores'][1],result['labels'][2]:result['scores'][2]}
|
11 |
+
sentiment_scores_str = f"Positive: {sentiment_scores['positive']:.2f}, Neutral: {sentiment_scores['neutral']:.2f}, Negative: {sentiment_scores['negative']:.2f}"
|
12 |
+
return sentiment_scores_str
|
13 |
+
def emotion_analysis(self,text):
|
14 |
+
prompt = f""" Your task is to analyze {text} and predict the emotion using scores. Emotions are categorized into the following list: Sadness, Happiness, Joy, Fear, Disgust, and Anger. You need to provide the emotion with the highest score. The scores should be in the range of 0.0 to 1.0, where 1.0 represents the highest intensity of the emotion.
|
15 |
+
Please analyze the text and provide the output in the following format: emotion: score [with one result having the highest score]."""
|
16 |
+
response = openai.Completion.create(
|
17 |
+
model="text-davinci-003",
|
18 |
+
prompt=prompt,
|
19 |
+
temperature=1,
|
20 |
+
max_tokens=60,
|
21 |
+
top_p=1,
|
22 |
+
frequency_penalty=0,
|
23 |
+
presence_penalty=0
|
24 |
+
)
|
25 |
+
|
26 |
+
message = response.choices[0].text.strip().replace("\n","")
|
27 |
+
print(message)
|
28 |
+
return message
|
29 |
+
|
30 |
+
def analyze_sentiment_for_graph(self, text):
|
31 |
+
pipe = pipeline("zero-shot-classification", model=self.model)
|
32 |
+
label=["positive", "negative", "neutral"]
|
33 |
+
result = pipe(text, label)
|
34 |
+
sentiment_scores = {
|
35 |
+
result['labels'][0]: result['scores'][0],
|
36 |
+
result['labels'][1]: result['scores'][1],
|
37 |
+
result['labels'][2]: result['scores'][2]
|
38 |
+
}
|
39 |
+
return sentiment_scores
|
40 |
+
|
41 |
+
def emotion_analysis_for_graph(self,text):
|
42 |
+
|
43 |
+
list_of_emotion=text.split(":")
|
44 |
+
label=list_of_emotion[0]
|
45 |
+
score=list_of_emotion[1]
|
46 |
+
score_dict={
|
47 |
+
label:float(score)
|
48 |
+
}
|
49 |
+
print(score_dict)
|
50 |
+
return score_dict
|
51 |
+
|
52 |
+
class Summarizer:
|
53 |
+
def __init__(self):
|
54 |
+
pass
|
55 |
+
def generate_summary(self, text):
|
56 |
+
model_engine = "text-davinci-003"
|
57 |
+
prompt = f"""summarize the following conversation delimited by triple backticks.
|
58 |
+
write within 30 words.
|
59 |
+
```{text}``` """
|
60 |
+
completions = openai.Completion.create(
|
61 |
+
engine=model_engine,
|
62 |
+
prompt=prompt,
|
63 |
+
max_tokens=60,
|
64 |
+
n=1,
|
65 |
+
stop=None,
|
66 |
+
temperature=0.5,
|
67 |
+
)
|
68 |
+
message = completions.choices[0].text.strip()
|
69 |
+
return message
|
70 |
+
|
71 |
+
|
72 |
+
history_state = gr.State([])
|
73 |
+
summarizer = Summarizer()
|
74 |
+
sentiment = SentimentAnalyzer()
|
75 |
+
|
76 |
+
class LangChain_Document_QA:
|
77 |
+
|
78 |
+
def __init__(self):
|
79 |
+
pass
|
80 |
+
def _add_text(self,history, text):
|
81 |
+
history = history + [(text, None)]
|
82 |
+
history_state.value = history
|
83 |
+
return history,gr.update(value="", interactive=False)
|
84 |
+
|
85 |
+
def _agent_text(self,history, text):
|
86 |
+
response = text
|
87 |
+
history[-1][1] = response
|
88 |
+
history_state.value = history
|
89 |
+
return history
|
90 |
+
|
91 |
+
def _chat_history(self):
|
92 |
+
history = history_state.value
|
93 |
+
formatted_history = " "
|
94 |
+
for entry in history:
|
95 |
+
customer_text, agent_text = entry
|
96 |
+
formatted_history += f"Customer: {customer_text}\n"
|
97 |
+
if agent_text:
|
98 |
+
formatted_history += f"Agent: {agent_text}\n"
|
99 |
+
return formatted_history
|
100 |
+
|
101 |
+
def _display_history(self):
|
102 |
+
formatted_history=self._chat_history()
|
103 |
+
summary=summarizer.generate_summary(formatted_history)
|
104 |
+
return summary
|
105 |
+
|
106 |
+
def _display_graph(self,sentiment_scores):
|
107 |
+
labels = sentiment_scores.keys()
|
108 |
+
scores = sentiment_scores.values()
|
109 |
+
fig = px.bar(x=scores, y=labels, orientation='h', color=labels, color_discrete_map={"Negative": "red", "Positive": "green", "Neutral": "gray"})
|
110 |
+
fig.update_traces(texttemplate='%{x:.2f}%', textposition='outside')
|
111 |
+
fig.update_layout(height=500, width=200)
|
112 |
+
return fig
|
113 |
+
|
114 |
+
def _history_of_chat(self):
|
115 |
+
history = history_state.value
|
116 |
+
formatted_history = ""
|
117 |
+
client=""
|
118 |
+
agent=""
|
119 |
+
for entry in history:
|
120 |
+
customer_text, agent_text = entry
|
121 |
+
client+=customer_text
|
122 |
+
formatted_history += f"Customer: {customer_text}\n"
|
123 |
+
if agent_text:
|
124 |
+
agent+=agent_text
|
125 |
+
formatted_history += f"Agent: {agent_text}\n"
|
126 |
+
return client,agent
|
127 |
+
|
128 |
+
|
129 |
+
def _suggested_answer(self,text):
|
130 |
+
try:
|
131 |
+
history = self._chat_history()
|
132 |
+
start_sequence = "\nCustomer:"
|
133 |
+
restart_sequence = "\nVodafone Customer Relationship Manager:"
|
134 |
+
prompt = 'your task is make a conversation between a customer and vodafone telecom customer relationship manager.at end the conversation thanks for coming'
|
135 |
+
file_path = "/content/vodafone_customer_details.json"
|
136 |
+
with open(file_path) as file:
|
137 |
+
customer_details = json.load(file)
|
138 |
+
prompt = f"{history}{start_sequence}{text}{restart_sequence} if customer ask any information take it from {customer_details}."
|
139 |
+
response = openai.Completion.create(
|
140 |
+
model="text-davinci-003",
|
141 |
+
prompt=prompt,
|
142 |
+
temperature=0,
|
143 |
+
max_tokens=500,
|
144 |
+
top_p=1,
|
145 |
+
frequency_penalty=0,
|
146 |
+
presence_penalty=0.6,
|
147 |
+
)
|
148 |
+
|
149 |
+
message = response.choices[0].text.strip()
|
150 |
+
if ":" in message:
|
151 |
+
message = re.sub(r'^.*:', '', message)
|
152 |
+
return message.strip()
|
153 |
+
except:
|
154 |
+
return "I can't get the response"
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
def _text_box(self,customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score):
|
159 |
+
agent_score = ", ".join([f"{key}: {value:.2f}" for key, value in agent_sentiment_score.items()])
|
160 |
+
customer_score = ", ".join([f"{key}: {value:.2f}" for key, value in customer_sentiment_score.items()])
|
161 |
+
return f"customer_emotion:{customer_emotion}\nagent_emotion:{agent_emotion}\nAgent_Sentiment_score:{agent_score}\nCustomer_sentiment_score:{customer_score}"
|
162 |
+
|
163 |
+
def _on_sentiment_btn_click(self):
|
164 |
+
client,agent=self._history_of_chat()
|
165 |
+
|
166 |
+
customer_emotion=sentiment.emotion_analysis(client)
|
167 |
+
customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client)
|
168 |
+
|
169 |
+
agent_emotion=sentiment.emotion_analysis(agent)
|
170 |
+
agent_sentiment_score = sentiment.analyze_sentiment_for_graph(agent)
|
171 |
+
|
172 |
+
scores=self._text_box(customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score)
|
173 |
+
|
174 |
+
customer_fig=self._display_graph(customer_sentiment_score)
|
175 |
+
customer_fig.update_layout(title="Sentiment Analysis",width=800)
|
176 |
+
|
177 |
+
agent_fig=self._display_graph(agent_sentiment_score)
|
178 |
+
agent_fig.update_layout(title="Sentiment Analysis",width=800)
|
179 |
+
|
180 |
+
agent_emotion_score = sentiment.emotion_analysis_for_graph(agent_emotion)
|
181 |
+
|
182 |
+
agent_emotion_fig=self._display_graph(agent_emotion_score)
|
183 |
+
agent_emotion_fig.update_layout(title="Emotion Analysis",width=800)
|
184 |
+
|
185 |
+
customer_emotion_score = sentiment.emotion_analysis_for_graph(customer_emotion)
|
186 |
+
|
187 |
+
customer_emotion_fig=self._display_graph(customer_emotion_score)
|
188 |
+
customer_emotion_fig.update_layout(title="Emotion Analysis",width=800)
|
189 |
+
|
190 |
+
return scores,customer_fig,agent_fig,customer_emotion_fig,agent_emotion_fig
|
191 |
+
|
192 |
+
|
193 |
+
def clear_func(self,history_state):
|
194 |
+
history_state.clear()
|
195 |
+
|
196 |
+
|
197 |
+
def gradio_interface(self):
|
198 |
+
with gr.Blocks(css="style.css",theme=gr.themes.Soft()) as demo:
|
199 |
+
with gr.Row():
|
200 |
+
gr.HTML("""<img class="leftimage" align="left" src="https://templates.images.credential.net/1612472097627370951721412474196.png" alt="Image" width="210" height="210">
|
201 |
+
<img align="right" class="rightimage" src="https://download.logo.wine/logo/Vodafone/Vodafone-Logo.wine.png" alt="Image" width="230" height="230" >""")
|
202 |
+
|
203 |
+
with gr.Row():
|
204 |
+
gr.HTML("""<center><h1>Vodafone Generative AI CRM ChatBot</h1></center>""")
|
205 |
+
gr.HTML(
|
206 |
+
"""<br style="color:white;">"""
|
207 |
+
)
|
208 |
+
chatbot = gr.Chatbot([], elem_id="chatbot").style(height=300)
|
209 |
+
with gr.Row():
|
210 |
+
with gr.Column(scale=0.50):
|
211 |
+
txt = gr.Textbox(
|
212 |
+
show_label=False,
|
213 |
+
placeholder="Customer",
|
214 |
+
).style(container=False)
|
215 |
+
with gr.Column(scale=0.50):
|
216 |
+
txt2 = gr.Textbox(
|
217 |
+
show_label=False,
|
218 |
+
placeholder="Agent",
|
219 |
+
).style(container=False)
|
220 |
+
|
221 |
+
with gr.Column(scale=0.40):
|
222 |
+
txt3 =gr.Textbox(
|
223 |
+
show_label=False,
|
224 |
+
placeholder="GPT_Suggestion",
|
225 |
+
).style(container=False)
|
226 |
+
with gr.Column(scale=0.10, min_width=0):
|
227 |
+
button=gr.Button(
|
228 |
+
value="π"
|
229 |
+
)
|
230 |
+
with gr.Row(scale=0.50):
|
231 |
+
emptyBtn = gr.Button(
|
232 |
+
"π§Ή New Conversation",
|
233 |
+
)
|
234 |
+
with gr.Row():
|
235 |
+
with gr.Column(scale=0.40):
|
236 |
+
txt4 =gr.Textbox(
|
237 |
+
show_label=False,
|
238 |
+
lines=4,
|
239 |
+
placeholder="Summary",
|
240 |
+
).style(container=False)
|
241 |
+
with gr.Column(scale=0.10, min_width=0):
|
242 |
+
end_btn=gr.Button(
|
243 |
+
value="End"
|
244 |
+
)
|
245 |
+
with gr.Column(scale=0.40):
|
246 |
+
txt5 =gr.Textbox(
|
247 |
+
show_label=False,
|
248 |
+
lines=4,
|
249 |
+
placeholder="Sentiment",
|
250 |
+
).style(container=False)
|
251 |
+
|
252 |
+
with gr.Column(scale=0.10, min_width=0):
|
253 |
+
Sentiment_btn=gr.Button(
|
254 |
+
value="π",callback=self._on_sentiment_btn_click
|
255 |
+
)
|
256 |
+
with gr.Row():
|
257 |
+
gr.HTML("""<center><h1>Sentiment and Emotion Score Graph</h1></center>""")
|
258 |
+
with gr.Row():
|
259 |
+
with gr.Column(scale=0.70, min_width=0):
|
260 |
+
plot =gr.Plot(label="Customer", size=(500, 600))
|
261 |
+
with gr.Row():
|
262 |
+
with gr.Column(scale=0.70, min_width=0):
|
263 |
+
plot_2 =gr.Plot(label="Agent", size=(500, 600))
|
264 |
+
with gr.Row():
|
265 |
+
with gr.Column(scale=0.70, min_width=0):
|
266 |
+
plot_3 =gr.Plot(label="Customer_Emotion", size=(500, 600))
|
267 |
+
with gr.Row():
|
268 |
+
with gr.Column(scale=0.70, min_width=0):
|
269 |
+
plot_4 =gr.Plot(label="Agent_Emotion", size=(500, 600))
|
270 |
+
|
271 |
+
|
272 |
+
txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt])
|
273 |
+
txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
|
274 |
+
txt.submit(self._suggested_answer,txt,txt3)
|
275 |
+
button.click(self._agent_text, [chatbot,txt3], chatbot)
|
276 |
+
txt2.submit(self._agent_text, [chatbot, txt2], chatbot).then(
|
277 |
+
self._agent_text, [chatbot, txt2], chatbot
|
278 |
+
)
|
279 |
+
end_btn.click(self._display_history, [], txt4)
|
280 |
+
emptyBtn.click(self.clear_func,history_state,[])
|
281 |
+
emptyBtn.click(lambda: None, None, chatbot, queue=False)
|
282 |
+
|
283 |
+
Sentiment_btn.click(self._on_sentiment_btn_click,[],[txt5,plot,plot_2,plot_3,plot_4])
|
284 |
+
|
285 |
+
demo.title = "Vodafone Generative AI CRM ChatBot"
|
286 |
+
demo.launch()
|