robertselvam commited on
Commit
01f29ca
1 Parent(s): 960ea29

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +283 -0
app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from openai 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
+ import pandas as pd
15
+
16
+ client = OpenAI()
17
+
18
+ class SentimentAnalyzer:
19
+ def __init__(self):
20
+ pass
21
+
22
+ def emotion_analysis(self,text):
23
+ prompt = f""" Your task is find the top 3 emotion for this converstion {text}: <Sadness, Happiness, Fear, Disgust, Anger> and it's emotion score for the Mental Healthcare Doctor Chatbot and patient conversation text.\
24
+ you are analyze the text and provide the output in the following list format heigher to lower order: ["emotion1","emotion2","emotion3"][score1,score2,score3]''' [with top 3 result having the highest score]
25
+ The scores should be in the range of 0.0 to 1.0, where 1.0 represents the highest intensity of the emotion.
26
+ """
27
+ response = client.completions.create(
28
+ model="text-davinci-003",
29
+ prompt=prompt,
30
+ temperature=0,
31
+ max_tokens=60,
32
+ top_p=1,
33
+ frequency_penalty=0,
34
+ presence_penalty=0
35
+ )
36
+ message = response.choices[0].text
37
+ return message
38
+
39
+ def analyze_sentiment_for_graph(self, text):
40
+ prompt = f""" Your task is find the setiments for this converstion {text} : <labels = positive, negative, neutral> and it's sentiment score for the Mental Healthcare Doctor Chatbot and patient conversation text.\
41
+ you are analyze the text and provide the output in the following json format heigher to lower order: '''["label1","label2","label3"][score1,score2,score3]'''
42
+ """
43
+ response = client.completions.create(
44
+ model="text-davinci-003",
45
+ prompt=prompt,
46
+ temperature=0,
47
+ max_tokens=60,
48
+ top_p=1,
49
+ frequency_penalty=0,
50
+ presence_penalty=0
51
+ )
52
+
53
+ # Extract the generated text
54
+ sentiment_scores = response.choices[0].text.strip()
55
+ start_index = sentiment_scores.find("[")
56
+ end_index = sentiment_scores.find("]")
57
+ list1_text = sentiment_scores[start_index + 1: end_index]
58
+ list2_text = sentiment_scores[end_index + 2:-1]
59
+ sentiment = list(map(str.strip, list1_text.split(",")))
60
+ scores = list(map(float, list2_text.split(",")))
61
+ score_dict={"Sentiment": sentiment, "Score": scores}
62
+ print(score_dict)
63
+ return score_dict
64
+
65
+ def emotion_analysis_for_graph(self,text):
66
+ start_index = text.find("[")
67
+ end_index = text.find("]")
68
+ list1_text = text[start_index + 1: end_index]
69
+ list2_text = text[end_index + 2:-1]
70
+ emotions = list(map(str.strip, list1_text.split(",")))
71
+ scores = list(map(float, list2_text.split(",")))
72
+ score_dict={"Emotion": emotions, "Score": scores}
73
+ print(score_dict)
74
+ return score_dict
75
+
76
+
77
+ class Summarizer:
78
+ def __init__(self):
79
+ # openai.api_key=os.getenv("OPENAI_API_KEY")
80
+ pass
81
+ def generate_summary(self, text):
82
+ model_engine = "text-davinci-003"
83
+ prompt = f"""summarize the following conversation delimited by triple backticks. write within 30 words.```{text}``` """
84
+ completions = client.completions.create(
85
+ engine=model_engine,
86
+ prompt=prompt,
87
+ max_tokens=60,
88
+ n=1,
89
+ stop=None,
90
+ temperature=0.5,
91
+ )
92
+ message = completions.choices[0].text.strip()
93
+ return message
94
+
95
+ history_state = gr.State()
96
+ summarizer = Summarizer()
97
+ sentiment = SentimentAnalyzer()
98
+
99
+ class LangChain_Document_QA:
100
+
101
+ def __init__(self):
102
+ # openai.api_key=os.getenv("OPENAI_API_KEY")
103
+ pass
104
+
105
+ def _add_text(self,history, text):
106
+ history = history + [(text, None)]
107
+ history_state.value = history
108
+ return history,gr.update(value="", interactive=False)
109
+
110
+ def _agent_text(self,history, text):
111
+ response = text
112
+ history[-1][1] = response
113
+ history_state.value = history
114
+ return history
115
+
116
+ def _chat_history(self):
117
+ history = history_state.value
118
+ formatted_history = " "
119
+ for entry in history:
120
+ customer_text, agent_text = entry
121
+ formatted_history += f"Patient: {customer_text}\n"
122
+ if agent_text:
123
+ formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
124
+ return formatted_history
125
+
126
+ def _display_history(self):
127
+ formatted_history=self._chat_history()
128
+ summary=summarizer.generate_summary(formatted_history)
129
+ return summary
130
+
131
+ def _display_graph(self,sentiment_scores):
132
+ df = pd.DataFrame(sentiment_scores)
133
+ fig = px.bar(df, x='Score', y='Sentiment', orientation='h', labels={'Score': 'Score', 'Labels': 'Sentiment'})
134
+ fig.update_layout(height=500, width=200)
135
+ return fig
136
+ def _display_graph_emotion(self,customer_emotion_score):
137
+
138
+ fig = px.pie(customer_emotion_score, values='Score', names='Emotion', title='Emotion Distribution', hover_data=['Score'])
139
+ #fig.update_traces(texttemplate='Emotion', textposition='outside')
140
+ fig.update_layout(height=500, width=200)
141
+ return fig
142
+ def _history_of_chat(self):
143
+ history = history_state.value
144
+ formatted_history = ""
145
+ client=""
146
+ agent=""
147
+ for entry in history:
148
+ customer_text, agent_text = entry
149
+ client+=customer_text
150
+ formatted_history += f"Patient: {customer_text}\n"
151
+ if agent_text:
152
+ agent+=agent_text
153
+ formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
154
+ return client,agent
155
+
156
+
157
+ def _suggested_answer(self,history, text):
158
+ # try:
159
+ history_list = self._chat_history()
160
+ try:
161
+ file_path = "patient_details.json"
162
+ with open(file_path) as file:
163
+ patient_details = json.load(file)
164
+ except:
165
+ pass
166
+
167
+ prompt = f"""Analyse the patient json If asked for information take it from {patient_details} \
168
+ you first get patient details : <get name,age,gender,contact,address from patient> if not match patient json information start new chat else match patient \
169
+ json information ask previous: <description,symptoms,diagnosis,treatment talk about patient> As an empathic AI Mental Healthcare Doctor Chatbot, provide effective solutions to patients' mental health concerns. \
170
+ first start the conversation ask existing patient or new patient. if new patient get name,age,gender,contact,address from the patient and start. \
171
+ if existing customer get name,age,gender,contact,address details and start the chat about existing issues and current issues. \
172
+ if patient say thanking tone message to end the conversation with a thanking greeting when the patient expresses gratitude. \
173
+ Chat History:['''{history_list}''']
174
+ Patient: ['''{text}''']
175
+ Perform as Mental Healthcare Doctor Chatbot
176
+ """
177
+ response = client.completions.create(
178
+ model="text-davinci-003",
179
+ prompt=prompt,
180
+ temperature=0,
181
+ max_tokens=500,
182
+ top_p=1,
183
+ frequency_penalty=0,
184
+ presence_penalty=0.6,
185
+ )
186
+
187
+ message = response.choices[0].text.strip()
188
+ if ":" in message:
189
+ message = re.sub(r'^.*:', '', message)
190
+ history[-1][1] = message.strip()
191
+ history_state.value = history
192
+ return history
193
+ # except:
194
+ # history[-1][1] = "How can I help you?"
195
+ # history_state.value = history
196
+ # return history
197
+
198
+
199
+ def _text_box(self,customer_emotion,customer_sentiment_score):
200
+ sentiment_str = ', '.join([f'{label}: {score}' for label, score in zip(customer_sentiment_score['Sentiment'], customer_sentiment_score['Score'])])
201
+ #emotion_str = ', '.join([f'{emotion}: {score}' for emotion, score in zip(customer_emotion['Emotion'], customer_emotion['Score'])])
202
+ return f"Sentiment: {sentiment_str},\nEmotion: {customer_emotion}"
203
+
204
+ def _on_sentiment_btn_click(self):
205
+ client=self._history_of_chat()
206
+
207
+ customer_emotion=sentiment.emotion_analysis(client)
208
+ customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client)
209
+
210
+ scores=self._text_box(customer_emotion,customer_sentiment_score)
211
+
212
+ customer_fig=self._display_graph(customer_sentiment_score)
213
+ customer_fig.update_layout(title="Sentiment Analysis",width=800)
214
+
215
+ customer_emotion_score = sentiment.emotion_analysis_for_graph(customer_emotion)
216
+
217
+ customer_emotion_fig=self._display_graph_emotion(customer_emotion_score)
218
+ customer_emotion_fig.update_layout(title="Emotion Analysis",width=800)
219
+ return scores,customer_fig,customer_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='JohnSmith9982/small_and_pretty') as demo:
227
+ with gr.Row():
228
+ gr.HTML("""<center><img class="image" src="https://www.syrahealth.com/images/SyraHealth_Logo_Dark.svg" alt="Image" width="210" height="210"></center>
229
+ """)
230
+ with gr.Row():
231
+ gr.HTML("""<center><h1>AI Mental Healthcare ChatBot</h1></center>""")
232
+ with gr.Row():
233
+ with gr.Column(scale=1):
234
+ with gr.Row():
235
+ chatbot = gr.Chatbot([], elem_id="chatbot")
236
+ with gr.Row():
237
+ with gr.Column(scale=0.90):
238
+ txt = gr.Textbox(show_label=False,placeholder="Patient")
239
+ with gr.Column(scale=0.10):
240
+ emptyBtn = gr.Button("🧹 Clear")
241
+
242
+ with gr.Accordion("Conversational AI Analytics", open = False):
243
+ with gr.Row():
244
+ with gr.Column(scale=0.50):
245
+ txt4 =gr.Textbox(
246
+ show_label=False,
247
+ lines=4,
248
+ placeholder="Summary")
249
+ with gr.Column(scale=0.50):
250
+ txt5 =gr.Textbox(
251
+ show_label=False,
252
+ lines=4,
253
+ placeholder="Sentiment")
254
+ with gr.Row():
255
+ with gr.Column(scale=0.50, min_width=0):
256
+ end_btn=gr.Button(value="End")
257
+ with gr.Column(scale=0.50, min_width=0):
258
+ Sentiment_btn=gr.Button(value="📊")
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=1, min_width=0):
263
+ plot =gr.Plot(label="Patient")
264
+ with gr.Row():
265
+ with gr.Column(scale=1, min_width=0):
266
+ plot_3 =gr.Plot(label="Patient_Emotion")
267
+
268
+
269
+ txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt]).then(
270
+ self._suggested_answer, [chatbot,txt],chatbot)
271
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
272
+ # txt.submit(self._suggested_answer, [chatbot,txt],chatbot)
273
+ # button.click(self._agent_text, [chatbot,txt3], chatbot)
274
+ end_btn.click(self._display_history, [], txt4)
275
+ emptyBtn.click(self.clear_func,[],[])
276
+ emptyBtn.click(lambda: None, None, chatbot, queue=False)
277
+
278
+ Sentiment_btn.click(self._on_sentiment_btn_click,[],[txt5,plot,plot_3])
279
+
280
+ demo.title = "AI Mental Healthcare ChatBot"
281
+ demo.launch(debug = True)
282
+ document_qa =LangChain_Document_QA()
283
+ document_qa.gradio_interface()