naveenvenkatesh commited on
Commit
a1634d3
1 Parent(s): dc08b8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -54
app.py CHANGED
@@ -12,12 +12,13 @@ from transformers import pipeline
12
  import matplotlib.pyplot as plt
13
  import plotly.express as px
14
 
 
 
15
  class SentimentAnalyzer:
16
  def __init__(self):
17
-
18
  self.model="facebook/bart-large-mnli"
19
 
20
- self.client = OpenAI()
21
 
22
  def analyze_sentiment(self, text):
23
  pipe = pipeline("zero-shot-classification", model=self.model)
@@ -28,17 +29,24 @@ class SentimentAnalyzer:
28
  return sentiment_scores_str
29
 
30
  def emotion_analysis(self,text):
31
- 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.
32
- Please analyze the text and provide the output in the following format: emotion: score [with one result having the highest score]."""
33
- response = self.client.completions.create(
34
- model="text-davinci-003",
35
- prompt=prompt,
 
 
 
 
 
 
 
36
  temperature=1,
37
  max_tokens=60
38
  )
39
 
40
- message = response.choices[0].text.strip().replace("\n","")
41
- print(message)
42
  return message
43
 
44
  def analyze_sentiment_for_graph(self, text):
@@ -55,8 +63,8 @@ Please analyze the text and provide the output in the following format: emotion:
55
  def emotion_analysis_for_graph(self,text):
56
 
57
  list_of_emotion=text.split(":")
58
- label=list_of_emotion[0]
59
- score=list_of_emotion[1]
60
  score_dict={
61
  label:float(score)
62
  }
@@ -67,21 +75,26 @@ Please analyze the text and provide the output in the following format: emotion:
67
  class Summarizer:
68
 
69
  def __init__(self):
70
- self.client = OpenAI()
 
71
 
72
  def generate_summary(self, text):
73
- model_engine = "text-davinci-003"
74
- prompt = f"""summarize the following conversation delimited by triple backticks.
 
 
75
  write within 30 words.
76
- ```{text}``` """
77
- completions = self.client.completions.create(
78
- model=model_engine,
79
- prompt=prompt,
80
- max_tokens=60,
81
- n=1,
82
- temperature=0
 
83
  )
84
- message = completions.choices[0].text.strip()
 
85
  return message
86
 
87
  history_state = gr.State()
@@ -91,20 +104,33 @@ sentiment = SentimentAnalyzer()
91
  class LangChain_Document_QA:
92
 
93
  def __init__(self):
94
- self.client = OpenAI()
 
95
 
96
  def _add_text(self,history, text):
 
97
  history = history + [(text, None)]
98
  history_state.value = history
99
- return history,gr.update(value="", interactive=False)
100
 
101
- def _agent_text(self,history, text):
102
- response = text
103
- history[-1][1] = response
 
 
 
 
 
 
 
104
  history_state.value = history
 
 
 
105
  return history
106
 
 
107
  def _chat_history(self):
 
108
  history = history_state.value
109
  formatted_history = " "
110
  for entry in history:
@@ -142,31 +168,39 @@ class LangChain_Document_QA:
142
  return client,agent
143
 
144
 
145
- def _suggested_answer(self,text):
146
- try:
147
- history = self._chat_history()
148
- start_sequence = "\nCustomer:"
149
- restart_sequence = "\nVodafone Customer Relationship Manager:"
150
- prompt = 'your task is make a conversation between a customer and vodafone telecom customer relationship manager.'
 
151
  file_path = "vodafone_customer_details.json"
152
  with open(file_path) as file:
153
- customer_details = json.load(file)
154
- prompt = f"""{history}{start_sequence}{text}{restart_sequence} if customer ask any information take it from {customer_details}.
155
- if customer say thanks or thankyou tone related messages You should not ask anything to end the conversation with greetings tone.
156
- """
157
- response = self.client.completions.create(
158
- model="text-davinci-003",
159
- prompt=prompt,
 
 
160
  temperature=0,
161
- max_tokens=500
162
  )
163
-
164
- message = response.choices[0].text.strip()
 
 
165
  if ":" in message:
166
  message = re.sub(r'^.*:', '', message)
167
- return message.strip()
168
- except:
169
- return "Hi, How can I help you?"
 
 
 
170
 
171
 
172
  def _text_box(self,customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score):
@@ -205,7 +239,7 @@ class LangChain_Document_QA:
205
 
206
 
207
  def clear_func(self):
208
- history_state.clear()
209
 
210
 
211
  def gradio_interface(self):
@@ -217,7 +251,7 @@ class LangChain_Document_QA:
217
  gr.HTML("""<center><h1 style="color:#f26d25">Generative AI CRM ChatBot</h1></center>""")
218
  with gr.Row():
219
  gr.HTML("<br>")
220
- chatbot = gr.Chatbot([], elem_id="chatbot").style(height=300)
221
  with gr.Row():
222
  with gr.Column(scale=0.50):
223
  txt = gr.Textbox(
@@ -280,13 +314,12 @@ class LangChain_Document_QA:
280
  with gr.Column(scale=0.70, min_width=0):
281
  plot_4 =gr.Plot(label="Agent_Emotion", size=(500, 600))
282
 
283
-
284
  txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt])
285
- txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
286
- txt.submit(self._suggested_answer,txt,txt3)
287
- button.click(self._agent_text, [chatbot,txt3], chatbot)
288
- txt2.submit(self._agent_text, [chatbot, txt2], chatbot).then(
289
- self._agent_text, [chatbot, txt2], chatbot
290
  )
291
  end_btn.click(self._display_history, [], txt4)
292
  emptyBtn.click(self.clear_func,[],[])
 
12
  import matplotlib.pyplot as plt
13
  import plotly.express as px
14
 
15
+ # client = OpenAI()
16
+
17
  class SentimentAnalyzer:
18
  def __init__(self):
 
19
  self.model="facebook/bart-large-mnli"
20
 
21
+ # self.client = OpenAI()
22
 
23
  def analyze_sentiment(self, text):
24
  pipe = pipeline("zero-shot-classification", model=self.model)
 
29
  return sentiment_scores_str
30
 
31
  def emotion_analysis(self,text):
32
+ client = OpenAI()
33
+ print(text,"lkdjrglk")
34
+ conversation = [
35
+ {"role": "system", "content": """You are a Emotion Analyser.Your task is to analyze 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.
36
+ Please analyze the text and provide the output in the following format: emotion: score [with one result having the highest score]."""},
37
+ {"role": "user", "content": f"""
38
+ input text{text}
39
+ """}
40
+ ]
41
+ response = client.chat.completions.create(
42
+ model="gpt-3.5-turbo",
43
+ messages=conversation,
44
  temperature=1,
45
  max_tokens=60
46
  )
47
 
48
+ message = response.choices[0].message.content
49
+ print("sen",message)
50
  return message
51
 
52
  def analyze_sentiment_for_graph(self, text):
 
63
  def emotion_analysis_for_graph(self,text):
64
 
65
  list_of_emotion=text.split(":")
66
+ label=list_of_emotion[1]
67
+ score=list_of_emotion[2]
68
  score_dict={
69
  label:float(score)
70
  }
 
75
  class Summarizer:
76
 
77
  def __init__(self):
78
+ # self.client = OpenAI()
79
+ pass
80
 
81
  def generate_summary(self, text):
82
+ client = OpenAI()
83
+ conversation = [
84
+ {"role": "system", "content": "You are a Summarizer"},
85
+ {"role": "user", "content": f"""summarize the following conversation delimited by triple backticks.
86
  write within 30 words.
87
+ ```{text}```
88
+ """}
89
+ ]
90
+ response = client.chat.completions.create(
91
+ model="gpt-3.5-turbo",
92
+ messages=conversation,
93
+ temperature=1,
94
+ max_tokens=100
95
  )
96
+
97
+ message = response.choices[0].message.content
98
  return message
99
 
100
  history_state = gr.State()
 
104
  class LangChain_Document_QA:
105
 
106
  def __init__(self):
107
+ # self.client = OpenAI()
108
+ pass
109
 
110
  def _add_text(self,history, text):
111
+
112
  history = history + [(text, None)]
113
  history_state.value = history
 
114
 
115
+ return history, gr.Textbox(value="", interactive=False)
116
+
117
+ def _agent_text(self,text,history):
118
+ # respond = []
119
+ # print("history",history)
120
+ # print(type(history))
121
+ # text = [text for _, text in history][-1]
122
+ # print("agent",history_state.value)
123
+
124
+ history[-1][1] = text
125
  history_state.value = history
126
+ # message = [tup[-1] for tup in history]
127
+ # respond.append(("", message))
128
+ # print(respond)
129
  return history
130
 
131
+
132
  def _chat_history(self):
133
+ print("chat history",history_state.value)
134
  history = history_state.value
135
  formatted_history = " "
136
  for entry in history:
 
168
  return client,agent
169
 
170
 
171
+ def _suggested_answer(self,history,text):
172
+ # try:
173
+ client = OpenAI()
174
+ self._add_text(history,text)
175
+ text_history = self._chat_history()
176
+ # start_sequence = "\nCustomer:"
177
+ # restart_sequence = "\nVodafone Customer Care:"
178
  file_path = "vodafone_customer_details.json"
179
  with open(file_path) as file:
180
+ context = json.load(file)
181
+ conversation = [
182
+ {"role": "system", "content": f"You Are Vodafone Sim AI Chatbot. Use the following pieces of context{context} to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Use three sentences maximum. Keep the answer as concise as possible. if user say hi, hello you say welcome greetings like hi, hello. if user say thankyou, thanks tone you say thanking Greetings like You're welcome!.conversation history{context}"},
183
+ {"role": "user", "content": f""" this is the user question:{text}..
184
+ """}
185
+ ]
186
+ response = client.chat.completions.create(
187
+ model="gpt-3.5-turbo",
188
+ messages=conversation,
189
  temperature=0,
190
+ max_tokens=100
191
  )
192
+
193
+ message = response.choices[0].message.content
194
+ print("message",message)
195
+
196
  if ":" in message:
197
  message = re.sub(r'^.*:', '', message)
198
+ history.append((text, message))
199
+ else:
200
+ history.append((text, message))
201
+ return "",message
202
+ # except:
203
+ # return "Hi, How can I help you?"
204
 
205
 
206
  def _text_box(self,customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score):
 
239
 
240
 
241
  def clear_func(self):
242
+ history_state = gr.State([])
243
 
244
 
245
  def gradio_interface(self):
 
251
  gr.HTML("""<center><h1 style="color:#f26d25">Generative AI CRM ChatBot</h1></center>""")
252
  with gr.Row():
253
  gr.HTML("<br>")
254
+ chatbot = gr.Chatbot().style(height=300)
255
  with gr.Row():
256
  with gr.Column(scale=0.50):
257
  txt = gr.Textbox(
 
314
  with gr.Column(scale=0.70, min_width=0):
315
  plot_4 =gr.Plot(label="Agent_Emotion", size=(500, 600))
316
 
 
317
  txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt])
318
+ # txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
319
+ txt.submit(self._suggested_answer, [chatbot, txt], [txt,txt3])
320
+ button.click(self._agent_text, [txt3,chatbot], chatbot)
321
+ txt2.submit(self._agent_text, [txt2,chatbot ], chatbot).then(
322
+ self._agent_text, [txt2,chatbot], chatbot
323
  )
324
  end_btn.click(self._display_history, [], txt4)
325
  emptyBtn.click(self.clear_func,[],[])