Karthikeyan commited on
Commit
43e1c6a
1 Parent(s): 108ade7

Create app.py

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