Karthikeyan commited on
Commit
5e31da7
1 Parent(s): 836a196

Delete app.py

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