Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,7 +11,9 @@ 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 |
|
@@ -23,21 +25,24 @@ class SentimentAnalyzer:
|
|
23 |
# Create a conversation for the OpenAI chat API
|
24 |
conversation = [
|
25 |
{"role": "system", "content": "You are a helpful assistant."},
|
26 |
-
{"role": "user", "content": f""" Your task is find the
|
27 |
-
|
28 |
-
|
|
|
|
|
29 |
"""}
|
30 |
]
|
31 |
|
32 |
# Call OpenAI GPT-3.5-turbo
|
33 |
chat_completion = client.chat.completions.create(
|
34 |
-
model = "gpt-3.5-turbo
|
35 |
messages = conversation,
|
36 |
max_tokens=500,
|
37 |
temperature=0
|
38 |
)
|
39 |
|
40 |
response = chat_completion.choices[0].message.content
|
|
|
41 |
return response
|
42 |
|
43 |
|
@@ -46,57 +51,25 @@ class SentimentAnalyzer:
|
|
46 |
# Create a conversation for the OpenAI chat API
|
47 |
conversation = [
|
48 |
{"role": "system", "content": "You are a helpful assistant."},
|
49 |
-
{"role": "user", "content": f""" Your task is
|
50 |
-
|
|
|
|
|
51 |
"""}
|
52 |
]
|
53 |
|
54 |
# Call OpenAI GPT-3.5-turbo
|
55 |
chat_completion = client.chat.completions.create(
|
56 |
-
model = "gpt-3.5-turbo
|
57 |
messages = conversation,
|
58 |
max_tokens=500,
|
59 |
temperature=0
|
60 |
)
|
61 |
|
62 |
response = chat_completion.choices[0].message.content
|
63 |
-
|
|
|
64 |
|
65 |
-
# 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.\
|
66 |
-
# you are analyze the text and provide the output in the following json format heigher to lower order: '''["label1","label2","label3"][score1,score2,score3]'''
|
67 |
-
# """
|
68 |
-
# response = client.completions.create(
|
69 |
-
# model="text-davinci-003",
|
70 |
-
# prompt=prompt,
|
71 |
-
# temperature=0,
|
72 |
-
# max_tokens=60,
|
73 |
-
# top_p=1,
|
74 |
-
# frequency_penalty=0,
|
75 |
-
# presence_penalty=0
|
76 |
-
# )
|
77 |
-
|
78 |
-
# Extract the generated text
|
79 |
-
sentiment_scores = response
|
80 |
-
start_index = sentiment_scores.find("[")
|
81 |
-
end_index = sentiment_scores.find("]")
|
82 |
-
list1_text = sentiment_scores[start_index + 1: end_index]
|
83 |
-
list2_text = sentiment_scores[end_index + 2:-1]
|
84 |
-
sentiment = list(map(str.strip, list1_text.split(",")))
|
85 |
-
scores = list(map(float, list2_text.split(",")))
|
86 |
-
score_dict={"Sentiment": sentiment, "Score": scores}
|
87 |
-
print(score_dict)
|
88 |
-
return score_dict
|
89 |
-
|
90 |
-
def emotion_analysis_for_graph(self,text):
|
91 |
-
start_index = text.find("[")
|
92 |
-
end_index = text.find("]")
|
93 |
-
list1_text = text[start_index + 1: end_index]
|
94 |
-
list2_text = text[end_index + 2:-1]
|
95 |
-
emotions = list(map(str.strip, list1_text.split(",")))
|
96 |
-
scores = list(map(float, list2_text.split(",")))
|
97 |
-
score_dict={"Emotion": emotions, "Score": scores}
|
98 |
-
print(score_dict)
|
99 |
-
return score_dict
|
100 |
|
101 |
|
102 |
class Summarizer:
|
@@ -108,7 +81,7 @@ class Summarizer:
|
|
108 |
# Create a conversation for the OpenAI chat API
|
109 |
conversation = [
|
110 |
{"role": "system", "content": "You are a helpful assistant."},
|
111 |
-
{"role": "user", "content": f"""summarize the following conversation delimited by triple backticks. write within
|
112 |
]
|
113 |
|
114 |
# Call OpenAI GPT-3.5-turbo
|
@@ -133,61 +106,49 @@ class LangChain_Document_QA:
|
|
133 |
# openai.api_key=os.getenv("OPENAI_API_KEY")
|
134 |
pass
|
135 |
|
136 |
-
def _add_text(self,history, text):
|
137 |
-
history = history + [(text, None)]
|
138 |
-
history_state.value = history
|
139 |
-
return history,gr.update(value="", interactive=False)
|
140 |
-
|
141 |
-
def _agent_text(self,history, text):
|
142 |
-
response = text
|
143 |
-
history[-1][1] = response
|
144 |
-
history_state.value = history
|
145 |
-
return history
|
146 |
-
|
147 |
-
def _chat_history(self):
|
148 |
-
history = history_state.value
|
149 |
-
formatted_history = " "
|
150 |
-
for entry in history:
|
151 |
-
customer_text, agent_text = entry
|
152 |
-
formatted_history += f"Patient: {customer_text}\n"
|
153 |
-
if agent_text:
|
154 |
-
formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
|
155 |
-
return formatted_history
|
156 |
-
|
157 |
def _display_history(self):
|
158 |
formatted_history=self._chat_history()
|
|
|
159 |
summary=summarizer.generate_summary(formatted_history)
|
160 |
return summary
|
161 |
|
162 |
-
def _display_graph(self,
|
163 |
-
|
164 |
-
|
165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
return fig
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
172 |
return fig
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
agent=""
|
178 |
-
for entry in history:
|
179 |
-
customer_text, agent_text = entry
|
180 |
-
client+=customer_text
|
181 |
-
formatted_history += f"Patient: {customer_text}\n"
|
182 |
-
if agent_text:
|
183 |
-
agent+=agent_text
|
184 |
-
formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
|
185 |
-
return client,agent
|
186 |
-
|
187 |
-
|
188 |
-
def _suggested_answer(self,history, text):
|
189 |
-
# try:
|
190 |
-
history_list = self._chat_history()
|
191 |
try:
|
192 |
file_path = "patient_details.json"
|
193 |
with open(file_path) as file:
|
@@ -197,65 +158,48 @@ class LangChain_Document_QA:
|
|
197 |
|
198 |
# Create a conversation for the OpenAI chat API
|
199 |
conversation = [
|
200 |
-
{"role": "system", "content": "You are a
|
201 |
-
{"role": "user", "content": f"""
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
|
|
211 |
]
|
212 |
|
213 |
# Call OpenAI GPT-3.5-turbo
|
214 |
chat_completion = client.chat.completions.create(
|
215 |
-
model = "gpt-3.5-turbo
|
216 |
messages = conversation,
|
217 |
-
max_tokens=
|
218 |
temperature=0
|
219 |
)
|
220 |
|
221 |
response = chat_completion.choices[0].message.content
|
222 |
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
history_state.value = history
|
227 |
-
return history
|
228 |
-
# except:
|
229 |
-
# history[-1][1] = "How can I help you?"
|
230 |
-
# history_state.value = history
|
231 |
-
# return history
|
232 |
-
|
233 |
-
|
234 |
-
def _text_box(self,customer_emotion,customer_sentiment_score):
|
235 |
-
sentiment_str = ', '.join([f'{label}: {score}' for label, score in zip(customer_sentiment_score['Sentiment'], customer_sentiment_score['Score'])])
|
236 |
-
#emotion_str = ', '.join([f'{emotion}: {score}' for emotion, score in zip(customer_emotion['Emotion'], customer_emotion['Score'])])
|
237 |
-
return f"Sentiment: {sentiment_str},\nEmotion: {customer_emotion}"
|
238 |
-
|
239 |
-
def _on_sentiment_btn_click(self):
|
240 |
-
client=self._history_of_chat()
|
241 |
-
|
242 |
-
customer_emotion=sentiment.emotion_analysis(client)
|
243 |
-
customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client)
|
244 |
-
|
245 |
-
scores=self._text_box(customer_emotion,customer_sentiment_score)
|
246 |
|
247 |
-
customer_fig=self._display_graph(customer_sentiment_score)
|
248 |
-
customer_fig.update_layout(title="Sentiment Analysis",width=800)
|
249 |
|
250 |
-
|
|
|
251 |
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
|
|
|
|
|
|
|
|
|
|
|
256 |
|
257 |
-
def clear_func(self):
|
258 |
-
history_state.clear()
|
259 |
|
260 |
def gradio_interface(self):
|
261 |
with gr.Blocks(css="style.css",theme='JohnSmith9982/small_and_pretty') as demo:
|
@@ -267,25 +211,22 @@ class LangChain_Document_QA:
|
|
267 |
with gr.Row():
|
268 |
with gr.Column(scale=1):
|
269 |
with gr.Row():
|
270 |
-
chatbot = gr.Chatbot(
|
271 |
with gr.Row():
|
272 |
with gr.Column(scale=0.90):
|
273 |
txt = gr.Textbox(show_label=False,placeholder="Patient")
|
274 |
with gr.Column(scale=0.10):
|
275 |
-
emptyBtn = gr.
|
|
|
276 |
|
277 |
with gr.Accordion("Conversational AI Analytics", open = False):
|
278 |
with gr.Row():
|
279 |
-
with gr.Column(scale=0
|
280 |
txt4 =gr.Textbox(
|
281 |
show_label=False,
|
282 |
lines=4,
|
283 |
placeholder="Summary")
|
284 |
-
|
285 |
-
txt5 =gr.Textbox(
|
286 |
-
show_label=False,
|
287 |
-
lines=4,
|
288 |
-
placeholder="Sentiment")
|
289 |
with gr.Row():
|
290 |
with gr.Column(scale=0.50, min_width=0):
|
291 |
end_btn=gr.Button(value="End")
|
@@ -301,16 +242,20 @@ class LangChain_Document_QA:
|
|
301 |
plot_3 =gr.Plot(label="Patient_Emotion")
|
302 |
|
303 |
|
304 |
-
|
305 |
-
self._suggested_answer, [chatbot,txt],chatbot)
|
306 |
-
|
307 |
# txt.submit(self._suggested_answer, [chatbot,txt],chatbot)
|
308 |
# button.click(self._agent_text, [chatbot,txt3], chatbot)
|
309 |
-
|
310 |
-
|
311 |
-
|
|
|
|
|
|
|
|
|
312 |
|
313 |
-
Sentiment_btn.click(self._on_sentiment_btn_click,
|
314 |
|
315 |
demo.title = "AI Mental Healthcare ChatBot"
|
316 |
demo.launch(debug = True)
|
|
|
11 |
from transformers import pipeline
|
12 |
import matplotlib.pyplot as plt
|
13 |
import plotly.express as px
|
14 |
+
import pandas as pd
|
15 |
+
import json
|
16 |
+
import plotly.graph_objects as go
|
17 |
|
18 |
client = OpenAI()
|
19 |
|
|
|
25 |
# Create a conversation for the OpenAI chat API
|
26 |
conversation = [
|
27 |
{"role": "system", "content": "You are a helpful assistant."},
|
28 |
+
{"role": "user", "content": f""" Your task is find the emotions for this converstion.
|
29 |
+
Conversation: {text}
|
30 |
+
lables : [Sadness, Happiness, Fear, Anger]
|
31 |
+
provide emotion score for each label for given conversation.
|
32 |
+
Return answer should be in valid JSON format only.
|
33 |
"""}
|
34 |
]
|
35 |
|
36 |
# Call OpenAI GPT-3.5-turbo
|
37 |
chat_completion = client.chat.completions.create(
|
38 |
+
model = "gpt-3.5-turbo",
|
39 |
messages = conversation,
|
40 |
max_tokens=500,
|
41 |
temperature=0
|
42 |
)
|
43 |
|
44 |
response = chat_completion.choices[0].message.content
|
45 |
+
print("emotion_analysis", response)
|
46 |
return response
|
47 |
|
48 |
|
|
|
51 |
# Create a conversation for the OpenAI chat API
|
52 |
conversation = [
|
53 |
{"role": "system", "content": "You are a helpful assistant."},
|
54 |
+
{"role": "user", "content": f""" Your task is analyse the conversarion to provide the sentiment analysis.
|
55 |
+
```converstion: {text}```
|
56 |
+
```labels :[ positive, negative, neutral]```
|
57 |
+
provide sentiment score for each label for given conversation. Return answer should be in valid JSON format only.
|
58 |
"""}
|
59 |
]
|
60 |
|
61 |
# Call OpenAI GPT-3.5-turbo
|
62 |
chat_completion = client.chat.completions.create(
|
63 |
+
model = "gpt-3.5-turbo",
|
64 |
messages = conversation,
|
65 |
max_tokens=500,
|
66 |
temperature=0
|
67 |
)
|
68 |
|
69 |
response = chat_completion.choices[0].message.content
|
70 |
+
print("analyze_sentiment_for_graph", response)
|
71 |
+
return response
|
72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
|
75 |
class Summarizer:
|
|
|
81 |
# Create a conversation for the OpenAI chat API
|
82 |
conversation = [
|
83 |
{"role": "system", "content": "You are a helpful assistant."},
|
84 |
+
{"role": "user", "content": f"""summarize the following conversation delimited by triple backticks. write within 60 words.```{text}``` """}
|
85 |
]
|
86 |
|
87 |
# Call OpenAI GPT-3.5-turbo
|
|
|
106 |
# openai.api_key=os.getenv("OPENAI_API_KEY")
|
107 |
pass
|
108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
def _display_history(self):
|
110 |
formatted_history=self._chat_history()
|
111 |
+
# formatted_history = _suggested_answer()
|
112 |
summary=summarizer.generate_summary(formatted_history)
|
113 |
return summary
|
114 |
|
115 |
+
def _display_graph(self,json_string):
|
116 |
+
# Parse the JSON string into a dictionary
|
117 |
+
json_data = json.loads(json_string)
|
118 |
+
|
119 |
+
sentiments = list(json_data.keys())
|
120 |
+
scores = list(json_data.values())
|
121 |
+
|
122 |
+
fig = go.Figure(data=[go.Bar(x=sentiments, y=scores, marker_color=['green', 'red', 'blue'])])
|
123 |
+
|
124 |
+
fig.update_layout(
|
125 |
+
title='Sentiment Analysis Scores',
|
126 |
+
xaxis=dict(title='Sentiment'),
|
127 |
+
yaxis=dict(title='Score'),
|
128 |
+
)
|
129 |
+
|
130 |
return fig
|
131 |
+
|
132 |
+
def _display_graph_emotion(self,json_string):
|
133 |
+
# Parse the JSON string into a dictionary
|
134 |
+
json_data = json.loads(json_string)
|
135 |
+
|
136 |
+
sentiments = list(json_data.keys())
|
137 |
+
scores = list(json_data.values())
|
138 |
+
|
139 |
+
fig = go.Figure(data=[go.Bar(x=sentiments, y=scores, marker_color=['green', 'red', 'blue'])])
|
140 |
+
|
141 |
+
fig.update_layout(
|
142 |
+
title='Emotion Analysis Scores',
|
143 |
+
xaxis=dict(title='Emotions'),
|
144 |
+
yaxis=dict(title='Score'),
|
145 |
+
)
|
146 |
+
|
147 |
return fig
|
148 |
+
|
149 |
+
|
150 |
+
def _suggested_answer(self, text, chat_history):
|
151 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
try:
|
153 |
file_path = "patient_details.json"
|
154 |
with open(file_path) as file:
|
|
|
158 |
|
159 |
# Create a conversation for the OpenAI chat API
|
160 |
conversation = [
|
161 |
+
{"role": "system", "content": "You are a Mental Healthcare Chatbot."},
|
162 |
+
{"role": "user", "content": f"""You are a Mental Healthcare Chatbot.
|
163 |
+
Ask more about the patient's problem as step by step.
|
164 |
+
Then give the short mental healthcare solution for patient's problems.
|
165 |
+
|
166 |
+
```Chat History:{chat_history}```
|
167 |
+
|
168 |
+
Patient Query:{text}.
|
169 |
+
Mental Healthcare Chatbot:
|
170 |
+
|
171 |
+
|
172 |
+
"""}
|
173 |
]
|
174 |
|
175 |
# Call OpenAI GPT-3.5-turbo
|
176 |
chat_completion = client.chat.completions.create(
|
177 |
+
model = "gpt-3.5-turbo",
|
178 |
messages = conversation,
|
179 |
+
max_tokens=300,
|
180 |
temperature=0
|
181 |
)
|
182 |
|
183 |
response = chat_completion.choices[0].message.content
|
184 |
|
185 |
+
chat_history.append((text, response))
|
186 |
+
|
187 |
+
return "", chat_history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
|
|
|
|
189 |
|
190 |
+
def _on_sentiment_btn_click(self, history):
|
191 |
+
# client=self._history_of_chat()
|
192 |
|
193 |
+
customer_emotion=sentiment.emotion_analysis(history)
|
194 |
+
|
195 |
+
customer_sentiment_score = sentiment.analyze_sentiment_for_graph(history)
|
196 |
|
197 |
+
sentiment_graph = self._display_graph(customer_sentiment_score)
|
198 |
+
|
199 |
+
emotion_graph = self._display_graph_emotion(customer_emotion)
|
200 |
+
|
201 |
+
return sentiment_graph, emotion_graph
|
202 |
|
|
|
|
|
203 |
|
204 |
def gradio_interface(self):
|
205 |
with gr.Blocks(css="style.css",theme='JohnSmith9982/small_and_pretty') as demo:
|
|
|
211 |
with gr.Row():
|
212 |
with gr.Column(scale=1):
|
213 |
with gr.Row():
|
214 |
+
chatbot = gr.Chatbot()
|
215 |
with gr.Row():
|
216 |
with gr.Column(scale=0.90):
|
217 |
txt = gr.Textbox(show_label=False,placeholder="Patient")
|
218 |
with gr.Column(scale=0.10):
|
219 |
+
emptyBtn = gr.ClearButton([txt, chatbot])
|
220 |
+
# emptyBtn = gr.Button()
|
221 |
|
222 |
with gr.Accordion("Conversational AI Analytics", open = False):
|
223 |
with gr.Row():
|
224 |
+
with gr.Column(scale=1.0):
|
225 |
txt4 =gr.Textbox(
|
226 |
show_label=False,
|
227 |
lines=4,
|
228 |
placeholder="Summary")
|
229 |
+
|
|
|
|
|
|
|
|
|
230 |
with gr.Row():
|
231 |
with gr.Column(scale=0.50, min_width=0):
|
232 |
end_btn=gr.Button(value="End")
|
|
|
242 |
plot_3 =gr.Plot(label="Patient_Emotion")
|
243 |
|
244 |
|
245 |
+
# txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt]).then(
|
246 |
+
# self._suggested_answer, [chatbot,txt],chatbot)
|
247 |
+
# txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
|
248 |
# txt.submit(self._suggested_answer, [chatbot,txt],chatbot)
|
249 |
# button.click(self._agent_text, [chatbot,txt3], chatbot)
|
250 |
+
|
251 |
+
txt.submit(self._suggested_answer, [txt,chatbot],[txt,chatbot])
|
252 |
+
print("chatbot", chatbot)
|
253 |
+
|
254 |
+
end_btn.click(summarizer.generate_summary,chatbot, txt4)
|
255 |
+
# emptyBtn.click(self.clear_func,[],[])
|
256 |
+
# emptyBtn.click(lambda: None, None, chatbot, queue=False)
|
257 |
|
258 |
+
Sentiment_btn.click(self._on_sentiment_btn_click,chatbot,[plot,plot_3])
|
259 |
|
260 |
demo.title = "AI Mental Healthcare ChatBot"
|
261 |
demo.launch(debug = True)
|