File size: 12,517 Bytes
7ac2436
 
 
 
 
fcb1ba4
7ac2436
 
 
 
 
 
fcb1ba4
 
7ac2436
 
c3df38b
fcb1ba4
c3df38b
7ac2436
 
 
 
 
 
 
c3df38b
7ac2436
fcb1ba4
a1634d3
 
 
 
 
 
 
 
 
228f115
a1634d3
7ac2436
c3df38b
7ac2436
 
a1634d3
 
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1634d3
 
7ac2436
 
 
c3df38b
7ac2436
 
 
 
c3df38b
7ac2436
a1634d3
fcb1ba4
c3df38b
7ac2436
0e5f1a5
a1634d3
 
 
7ac2436
a1634d3
 
 
 
228f115
a1634d3
 
 
7ac2436
a1634d3
 
7ac2436
 
 
 
 
 
 
 
 
a1634d3
c3df38b
7ac2436
a1634d3
7ac2436
 
 
a1634d3
 
 
 
 
7ac2436
 
 
a1634d3
7ac2436
a1634d3
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1634d3
fcb1ba4
a1634d3
 
c3df38b
 
a1634d3
 
 
 
 
 
 
228f115
a1634d3
c3df38b
a1634d3
c3df38b
a1634d3
 
 
 
c3df38b
 
a1634d3
 
 
 
c3df38b
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3df38b
7ac2436
a1634d3
c3df38b
 
7ac2436
c3df38b
10baefe
7ac2436
b839cd2
c3df38b
 
 
 
a1634d3
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3df38b
7ac2436
 
 
 
 
c3df38b
 
 
 
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3df38b
7ac2436
 
 
 
 
 
 
 
 
 
 
 
 
 
a1634d3
 
 
 
 
7ac2436
 
c3df38b
 
 
7ac2436
 
c3df38b
 
7ac2436
c3df38b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import os
import mimetypes
import requests
import tempfile
import gradio as gr
from openai import AzureOpenAI
import re
import json
from transformers import pipeline
import matplotlib.pyplot as plt
import plotly.express as px

client = AzureOpenAI()

class SentimentAnalyzer:
    def __init__(self):
        self.model="facebook/bart-large-mnli" 
        
        
    def analyze_sentiment(self, text):
        pipe = pipeline("zero-shot-classification", model=self.model)
        label=["positive","negative","neutral"]
        result = pipe(text, label)
        sentiment_scores= {result['labels'][0]:result['scores'][0],result['labels'][1]:result['scores'][1],result['labels'][2]:result['scores'][2]}
        sentiment_scores_str = f"Positive: {sentiment_scores['positive']:.2f}, Neutral: {sentiment_scores['neutral']:.2f}, Negative: {sentiment_scores['negative']:.2f}"
        return sentiment_scores_str
        
    def emotion_analysis(self,text):
        
        print(text,"lkdjrglk") 
        conversation = [
          {"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.
            Please analyze the text and provide the output in the following format: emotion: score [with one result having the highest score]."""},
          {"role": "user", "content": f"""
            input text{text}
            """}
            ]
        response = client.chat.completions.create(
            model="GPT-3",
            messages=conversation,
            temperature=1,
            max_tokens=60
        )

        message = response.choices[0].message.content
        print("sen",message)
        return message

    def analyze_sentiment_for_graph(self, text):
        pipe = pipeline("zero-shot-classification", model=self.model)
        label=["positive", "negative", "neutral"]
        result = pipe(text, label)
        sentiment_scores = {
            result['labels'][0]: result['scores'][0],
            result['labels'][1]: result['scores'][1],
            result['labels'][2]: result['scores'][2]
        }
        return sentiment_scores

    def emotion_analysis_for_graph(self,text):

        list_of_emotion=text.split(":")
        label=list_of_emotion[1]
        score=list_of_emotion[2]
        score_dict={
          label:float(score)
        }
        print(score_dict)
        return score_dict


class Summarizer:
    
    def __init__(self):
        # self.client = OpenAI()      
        pass
        
    def generate_summary(self, text):
        
        conversation = [
          {"role": "system", "content": "You are a Summarizer"},
          {"role": "user", "content": f"""summarize the following conversation delimited by triple backticks.
                     write within 30 words.
                     ```{text}```
            """}
            ]
        response = client.chat.completions.create(
            model="GPT-3",
            messages=conversation,
            temperature=1,
            max_tokens=100
        )

        message = response.choices[0].message.content
        return message

history_state = gr.State()
summarizer = Summarizer()
sentiment = SentimentAnalyzer()

class LangChain_Document_QA:

    def __init__(self):
        pass 
        
    def _add_text(self,history, text):

        history = history + [(text, None)]
        history_state.value = history

        return history, gr.Textbox(value="", interactive=False)

    def _agent_text(self,text,history):
        
        history[-1][1] = text
        history_state.value = history
        return history


    def _chat_history(self):
        print("chat history",history_state.value)
        history = history_state.value
        formatted_history = " "
        for entry in history:
            customer_text, agent_text = entry
            formatted_history += f"Customer: {customer_text}\n"
            if agent_text:
                formatted_history += f"Agent: {agent_text}\n"
        return formatted_history

    def _display_history(self):
        formatted_history=self._chat_history()
        summary=summarizer.generate_summary(formatted_history)
        return summary

    def _display_graph(self,sentiment_scores):
        labels = sentiment_scores.keys()
        scores = sentiment_scores.values()
        fig = px.bar(x=scores, y=labels, orientation='h', color=labels, color_discrete_map={"Negative": "red", "Positive": "green", "Neutral": "gray"})
        fig.update_traces(texttemplate='%{x:.2f}%', textposition='outside')
        fig.update_layout(height=500, width=200)
        return fig

    def _history_of_chat(self):
        history = history_state.value
        formatted_history = ""
        client=""
        agent=""
        for entry in history:
            customer_text, agent_text = entry
            client+=customer_text
            formatted_history += f"Customer: {customer_text}\n"
            if agent_text:
                agent+=agent_text
                formatted_history += f"Agent: {agent_text}\n"
        return client,agent


    def _suggested_answer(self,history,text):
            
            self._add_text(history,text)
            text_history = self._chat_history()
            file_path = "vodafone_customer_details.json"
            with open(file_path) as file:
                context = json.load(file)
            conversation = [
              {"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}"},
              {"role": "user", "content": f""" this is the user question:{text}..
                """}
                ]
            response = client.chat.completions.create(
                model="GPT-3",
                messages=conversation,
                temperature=0,
                max_tokens=100
            )
            
            message = response.choices[0].message.content
            print("message",message)
            
            if  ":" in message:
              message = re.sub(r'^.*:', '', message)
              history.append((text, message))
            else:
              history.append((text, message))
            return "",message
    

    def _text_box(self,customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score):
        agent_score = ", ".join([f"{key}: {value:.2f}" for key, value in agent_sentiment_score.items()])
        customer_score = ", ".join([f"{key}: {value:.2f}" for key, value in customer_sentiment_score.items()])
        return f"customer_emotion:{customer_emotion}\nagent_emotion:{agent_emotion}\nAgent_Sentiment_score:{agent_score}\nCustomer_sentiment_score:{customer_score}"

    def _on_sentiment_btn_click(self):
        client,agent=self._history_of_chat()

        customer_emotion=sentiment.emotion_analysis(client)
        customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client)

        agent_emotion=sentiment.emotion_analysis(agent)
        agent_sentiment_score = sentiment.analyze_sentiment_for_graph(agent)

        scores=self._text_box(customer_emotion,agent_emotion,agent_sentiment_score,customer_sentiment_score)

        customer_fig=self._display_graph(customer_sentiment_score)
        customer_fig.update_layout(title="Sentiment Analysis",width=800)

        agent_fig=self._display_graph(agent_sentiment_score)
        agent_fig.update_layout(title="Sentiment Analysis",width=800)

        agent_emotion_score = sentiment.emotion_analysis_for_graph(agent_emotion)

        agent_emotion_fig=self._display_graph(agent_emotion_score)
        agent_emotion_fig.update_layout(title="Emotion Analysis",width=800)

        customer_emotion_score = sentiment.emotion_analysis_for_graph(customer_emotion)

        customer_emotion_fig=self._display_graph(customer_emotion_score)
        customer_emotion_fig.update_layout(title="Emotion Analysis",width=800)

        return scores,customer_fig,agent_fig,customer_emotion_fig,agent_emotion_fig


    def clear_func(self):
      history_state = gr.State([])


    def gradio_interface(self):
      with gr.Blocks(css="style.css",theme="snehilsanyal/scikit-learn") as demo:

          with gr.Row():
            gr.HTML("""<center><img src="https://hakunamatatatech.com/wp-content/uploads/2019/06/logohms-160x4.png" alt="Image"></center>""")
          with gr.Row():  
            gr.HTML("""<center><h1 style="color:#f26d25">Generative AI CRM ChatBot</h1></center>""")
          with gr.Row():
            gr.HTML("<br>")
          chatbot = gr.Chatbot().style(height=300)
          with gr.Row():
              with gr.Column(scale=0.50):
                  txt = gr.Textbox(
                      show_label=False,
                      placeholder="Customer",
                  ).style(container=False)
              with gr.Column(scale=0.50):
                  txt2 = gr.Textbox(
                      show_label=False,
                      placeholder="Agent",
                  ).style(container=False)

              with gr.Column(scale=0.40):
                  txt3 =gr.Textbox(
                      show_label=False,
                      placeholder="Chatbot_Suggestion",
                  ).style(container=False)
              with gr.Column(scale=0.10, min_width=0):
                  button=gr.Button(
                      value="🚀"
                  )
              with gr.Row(scale=0.50):
                  emptyBtn = gr.Button(
                      "🧹 New Conversation",
                  )
          with gr.Row():
              with gr.Column(scale=0.40):
                  txt4 =gr.Textbox(
                      show_label=False,
                      lines=4,
                      placeholder="Summary",
                  ).style(container=False)
              with gr.Column(scale=0.10, min_width=0):
                  end_btn=gr.Button(
                      value="End"
                  )
              with gr.Column(scale=0.40):
                  txt5 =gr.Textbox(
                      show_label=False,
                      lines=4,
                      placeholder="Sentiment",
                  ).style(container=False)

              with gr.Column(scale=0.10, min_width=0):
                  Sentiment_btn=gr.Button(
                      value="📊",callback=self._on_sentiment_btn_click
                  )
          with gr.Row():
            gr.HTML("""<center><h1 style="color:#fff">Sentiment and Emotion Score Graph</h1></center>""")
          with gr.Row():
              with gr.Column(scale=0.70, min_width=0):
                  plot =gr.Plot(label="Customer", size=(500, 600))
          with gr.Row():
              with gr.Column(scale=0.70, min_width=0):
                  plot_2 =gr.Plot(label="Agent", size=(500, 600))
          with gr.Row():
              with gr.Column(scale=0.70, min_width=0):
                  plot_3 =gr.Plot(label="Customer_Emotion", size=(500, 600))
          with gr.Row():
              with gr.Column(scale=0.70, min_width=0):
                  plot_4 =gr.Plot(label="Agent_Emotion", size=(500, 600))

          txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt])
          # txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
          txt.submit(self._suggested_answer, [chatbot, txt], [txt,txt3])
          button.click(self._agent_text, [txt3,chatbot], chatbot)
          txt2.submit(self._agent_text, [txt2,chatbot ], chatbot).then(
              self._agent_text, [txt2,chatbot], chatbot
          )
          end_btn.click(self._display_history, [], txt4)
          emptyBtn.click(self.clear_func,[],[])
          emptyBtn.click(lambda: None, None, chatbot, queue=False)

          Sentiment_btn.click(self._on_sentiment_btn_click,[],[txt5,plot,plot_2,plot_3,plot_4])

      demo.launch(debug = True)

document_qa =LangChain_Document_QA()
document_qa.gradio_interface()