karthikeyan-r commited on
Commit
9729ada
·
0 Parent(s):

Duplicate from Syrahealthorg/HealthCare_workforce

Browse files
Files changed (6) hide show
  1. .gitattributes +35 -0
  2. README.md +13 -0
  3. app.py +281 -0
  4. patient_details.json +117 -0
  5. requirements.txt +16 -0
  6. style.css +12 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: HealthCare Workforce
3
+ emoji: 👁
4
+ colorFrom: indigo
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 3.35.2
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: Syrahealthorg/HealthCare_workforce
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import pandas as pd
15
+
16
+
17
+ class SentimentAnalyzer:
18
+ def __init__(self):
19
+ # self.model="facebook/bart-large-mnli"
20
+ openai.api_key=os.getenv("OPENAI_API_KEY")
21
+ def emotion_analysis(self,text):
22
+ 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.\
23
+ 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]
24
+ The scores should be in the range of 0.0 to 1.0, where 1.0 represents the highest intensity of the emotion.
25
+ """
26
+ response = openai.Completion.create(
27
+ model="text-davinci-003",
28
+ prompt=prompt,
29
+ temperature=0,
30
+ max_tokens=60,
31
+ top_p=1,
32
+ frequency_penalty=0,
33
+ presence_penalty=0
34
+ )
35
+ message = response.choices[0].text.strip().replace("\n","")
36
+ return message
37
+
38
+ def analyze_sentiment_for_graph(self, text):
39
+ 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.\
40
+ you are analyze the text and provide the output in the following json format heigher to lower order: '''["label1","label2","label3"][score1,score2,score3]'''
41
+ """
42
+ response = openai.Completion.create(
43
+ model="text-davinci-003",
44
+ prompt=prompt,
45
+ temperature=0,
46
+ max_tokens=60,
47
+ top_p=1,
48
+ frequency_penalty=0,
49
+ presence_penalty=0
50
+ )
51
+
52
+ # Extract the generated text
53
+ sentiment_scores = response.choices[0].text.strip()
54
+ start_index = sentiment_scores.find("[")
55
+ end_index = sentiment_scores.find("]")
56
+ list1_text = sentiment_scores[start_index + 1: end_index]
57
+ list2_text = sentiment_scores[end_index + 2:-1]
58
+ sentiment = list(map(str.strip, list1_text.split(",")))
59
+ scores = list(map(float, list2_text.split(",")))
60
+ score_dict={"Sentiment": sentiment, "Score": scores}
61
+ print(score_dict)
62
+ return score_dict
63
+
64
+ def emotion_analysis_for_graph(self,text):
65
+ start_index = text.find("[")
66
+ end_index = text.find("]")
67
+ list1_text = text[start_index + 1: end_index]
68
+ list2_text = text[end_index + 2:-1]
69
+ emotions = list(map(str.strip, list1_text.split(",")))
70
+ scores = list(map(float, list2_text.split(",")))
71
+ score_dict={"Emotion": emotions, "Score": scores}
72
+ print(score_dict)
73
+ return score_dict
74
+
75
+
76
+ class Summarizer:
77
+ def __init__(self):
78
+ openai.api_key=os.getenv("OPENAI_API_KEY")
79
+ def generate_summary(self, text):
80
+ model_engine = "text-davinci-003"
81
+ prompt = f"""summarize the following conversation delimited by triple backticks. write within 30 words.```{text}``` """
82
+ completions = openai.Completion.create(
83
+ engine=model_engine,
84
+ prompt=prompt,
85
+ max_tokens=60,
86
+ n=1,
87
+ stop=None,
88
+ temperature=0.5,
89
+ )
90
+ message = completions.choices[0].text.strip()
91
+ return message
92
+
93
+ history_state = gr.State()
94
+ summarizer = Summarizer()
95
+ sentiment = SentimentAnalyzer()
96
+
97
+ class LangChain_Document_QA:
98
+
99
+ def __init__(self):
100
+ openai.api_key=os.getenv("OPENAI_API_KEY")
101
+
102
+ def _add_text(self,history, text):
103
+ history = history + [(text, None)]
104
+ history_state.value = history
105
+ return history,gr.update(value="", interactive=False)
106
+
107
+ def _agent_text(self,history, text):
108
+ response = text
109
+ history[-1][1] = response
110
+ history_state.value = history
111
+ return history
112
+
113
+ def _chat_history(self):
114
+ history = history_state.value
115
+ formatted_history = " "
116
+ for entry in history:
117
+ customer_text, agent_text = entry
118
+ formatted_history += f"Patient: {customer_text}\n"
119
+ if agent_text:
120
+ formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
121
+ return formatted_history
122
+
123
+ def _display_history(self):
124
+ formatted_history=self._chat_history()
125
+ summary=summarizer.generate_summary(formatted_history)
126
+ return summary
127
+
128
+ def _display_graph(self,sentiment_scores):
129
+ df = pd.DataFrame(sentiment_scores)
130
+ fig = px.bar(df, x='Score', y='Sentiment', orientation='h', labels={'Score': 'Score', 'Labels': 'Sentiment'})
131
+ fig.update_layout(height=500, width=200)
132
+ return fig
133
+ def _display_graph_emotion(self,customer_emotion_score):
134
+
135
+ fig = px.pie(customer_emotion_score, values='Score', names='Emotion', title='Emotion Distribution', hover_data=['Score'])
136
+ #fig.update_traces(texttemplate='Emotion', textposition='outside')
137
+ fig.update_layout(height=500, width=200)
138
+ return fig
139
+ def _history_of_chat(self):
140
+ history = history_state.value
141
+ formatted_history = ""
142
+ client=""
143
+ agent=""
144
+ for entry in history:
145
+ customer_text, agent_text = entry
146
+ client+=customer_text
147
+ formatted_history += f"Patient: {customer_text}\n"
148
+ if agent_text:
149
+ agent+=agent_text
150
+ formatted_history += f"Mental Healthcare Doctor Chatbot: {agent_text}\n"
151
+ return client,agent
152
+
153
+
154
+ def _suggested_answer(self,text):
155
+ try:
156
+ history = self._chat_history()
157
+ try:
158
+ file_path = "patient_details.json"
159
+ with open(file_path) as file:
160
+ patient_details = json.load(file)
161
+ except:
162
+ pass
163
+
164
+ prompt = f"""Analyse the patient json If asked for information take it from {patient_details} \
165
+ 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 \
166
+ 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. \
167
+ first start the conversation ask existing patient or new patient. if new patient get name,age,gender,contact,address from the patient and start. \
168
+ if existing customer get name,age,gender,contact,address details and start the chat about existing issues and current issues. \
169
+ if patient say thanking tone message to end the conversation with a thanking greeting when the patient expresses gratitude. \
170
+ Chat History:['''{history}''']
171
+ Patient: ['''{text}''']
172
+ Perform as Mental Healthcare Doctor Chatbot
173
+ """
174
+ response = openai.Completion.create(
175
+ model="text-davinci-003",
176
+ prompt=prompt,
177
+ temperature=0,
178
+ max_tokens=500,
179
+ top_p=1,
180
+ frequency_penalty=0,
181
+ presence_penalty=0.6,
182
+ )
183
+
184
+ message = response.choices[0].text.strip()
185
+ if ":" in message:
186
+ message = re.sub(r'^.*:', '', message)
187
+ return message.strip()
188
+ except:
189
+ return "How can I help you?"
190
+
191
+
192
+
193
+ def _text_box(self,customer_emotion,customer_sentiment_score):
194
+ sentiment_str = ', '.join([f'{label}: {score}' for label, score in zip(customer_sentiment_score['Sentiment'], customer_sentiment_score['Score'])])
195
+ #emotion_str = ', '.join([f'{emotion}: {score}' for emotion, score in zip(customer_emotion['Emotion'], customer_emotion['Score'])])
196
+ return f"Sentiment: {sentiment_str},\nEmotion: {customer_emotion}"
197
+
198
+ def _on_sentiment_btn_click(self):
199
+ client=self._history_of_chat()
200
+
201
+ customer_emotion=sentiment.emotion_analysis(client)
202
+ customer_sentiment_score = sentiment.analyze_sentiment_for_graph(client)
203
+
204
+ scores=self._text_box(customer_emotion,customer_sentiment_score)
205
+
206
+ customer_fig=self._display_graph(customer_sentiment_score)
207
+ customer_fig.update_layout(title="Sentiment Analysis",width=800)
208
+
209
+ customer_emotion_score = sentiment.emotion_analysis_for_graph(customer_emotion)
210
+
211
+ customer_emotion_fig=self._display_graph_emotion(customer_emotion_score)
212
+ customer_emotion_fig.update_layout(title="Emotion Analysis",width=800)
213
+ return scores,customer_fig,customer_emotion_fig
214
+
215
+
216
+ def clear_func(self):
217
+ history_state.clear()
218
+
219
+ def gradio_interface(self):
220
+ with gr.Blocks(css="style.css",theme=gr.themes.Glass()) as demo:
221
+ with gr.Row():
222
+ gr.HTML("""<center><img class="image" src="https://www.syrahealth.com/images/SyraHealth_Logo_Dark.svg" alt="Image" width="210" height="210"></center>
223
+ """)
224
+ with gr.Row():
225
+ gr.HTML("""<center><h1>AI Mental Healthcare ChatBot</h1></center>""")
226
+ chatbot = gr.Chatbot([], elem_id="chatbot").style(height=360)
227
+ with gr.Row():
228
+ with gr.Column(scale=0.8):
229
+ txt = gr.Textbox(
230
+ show_label=False,
231
+ placeholder="Patient").style(container=False)
232
+
233
+ with gr.Column(scale=0.2):
234
+ emptyBtn = gr.Button("🧹 Clear")
235
+ with gr.Row():
236
+ with gr.Column(scale=0.80):
237
+ txt3 =gr.Textbox(
238
+ show_label=False,
239
+ placeholder="AI Healthcare Suggesstion").style(container=False)
240
+ with gr.Column(scale=0.20, min_width=0):
241
+ button=gr.Button(value="🚀send")
242
+ with gr.Row():
243
+ with gr.Column(scale=0.50):
244
+ txt4 =gr.Textbox(
245
+ show_label=False,
246
+ lines=4,
247
+ placeholder="Summary").style(container=False)
248
+ with gr.Column(scale=0.50):
249
+ txt5 =gr.Textbox(
250
+ show_label=False,
251
+ lines=4,
252
+ placeholder="Sentiment").style(container=False)
253
+ with gr.Row():
254
+ with gr.Column(scale=0.50, min_width=0):
255
+ end_btn=gr.Button(value="End")
256
+ with gr.Column(scale=0.50, min_width=0):
257
+ Sentiment_btn=gr.Button(value="📊",callback=self._on_sentiment_btn_click)
258
+ with gr.Row():
259
+ gr.HTML("""<center><h1>Sentiment and Emotion Score Graph</h1></center>""")
260
+ with gr.Row():
261
+ with gr.Column(scale=1, min_width=0):
262
+ plot =gr.Plot(label="Patient", size=(500, 600))
263
+ with gr.Row():
264
+ with gr.Column(scale=1, min_width=0):
265
+ plot_3 =gr.Plot(label="Patient_Emotion", size=(500, 600))
266
+
267
+
268
+ txt_msg = txt.submit(self._add_text, [chatbot, txt], [chatbot, txt])
269
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt])
270
+ txt.submit(self._suggested_answer,txt,txt3)
271
+ button.click(self._agent_text, [chatbot,txt3], chatbot)
272
+ end_btn.click(self._display_history, [], txt4)
273
+ emptyBtn.click(self.clear_func,[],[])
274
+ emptyBtn.click(lambda: None, None, chatbot, queue=False)
275
+
276
+ Sentiment_btn.click(self._on_sentiment_btn_click,[],[txt5,plot,plot_3])
277
+
278
+ demo.title = "AI Mental Healthcare ChatBot"
279
+ demo.launch()
280
+ document_qa =LangChain_Document_QA()
281
+ document_qa.gradio_interface()
patient_details.json ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "patients": [
3
+ {
4
+ "id": "P001",
5
+ "name": "John Smith",
6
+ "age": 32,
7
+ "gender": "Male",
8
+ "contact": "+1 123-456-7890",
9
+ "address": "123 Main Street, City, Country",
10
+ "issue": {
11
+ "description": "The patient is experiencing symptoms of anxiety and panic attacks.",
12
+ "symptoms": ["restlessness", "shortness of breath", "heart palpitations"],
13
+ "diagnosis": "Panic Disorder",
14
+ "treatment": "Prescribed anti-anxiety medication and advised cognitive-behavioral therapy."
15
+ }
16
+ },
17
+ {
18
+ "id": "P002",
19
+ "name": "Sarah Johnson",
20
+ "age": 41,
21
+ "gender": "Female",
22
+ "contact": "+1 234-567-8901",
23
+ "address": "456 Elm Street, City, Country",
24
+ "issue": {
25
+ "description": "The patient is experiencing persistent sadness and loss of appetite.",
26
+ "symptoms": ["low mood", "fatigue", "weight loss"],
27
+ "diagnosis": "Major Depressive Disorder",
28
+ "treatment": "Prescribed antidepressant medication and recommended psychotherapy sessions."
29
+ }
30
+ },
31
+ {
32
+ "id": "P003",
33
+ "name": "Michael Williams",
34
+ "age": 27,
35
+ "gender": "Male",
36
+ "contact": "+1 345-678-9012",
37
+ "address": "789 Oak Avenue, City, Country",
38
+ "issue": {
39
+ "description": "The patient is experiencing difficulty concentrating and irritability.",
40
+ "symptoms": ["inability to focus", "mood swings", "agitation"],
41
+ "diagnosis": "Attention Deficit Hyperactivity Disorder (ADHD)",
42
+ "treatment": "Prescribed stimulant medication and advised behavioral therapy."
43
+ }
44
+ },
45
+ {
46
+ "id": "P004",
47
+ "name": "Emily Davis",
48
+ "age": 35,
49
+ "gender": "Female",
50
+ "contact": "+1 456-789-0123",
51
+ "address": "987 Maple Lane, City, Country",
52
+ "issue": {
53
+ "description": "The patient is experiencing intrusive thoughts and compulsive behaviors.",
54
+ "symptoms": ["obsessions", "rituals", "anxiety"],
55
+ "diagnosis": "Obsessive-Compulsive Disorder (OCD)",
56
+ "treatment": "Prescribed selective serotonin reuptake inhibitor (SSRI) medication and recommended exposure and response prevention therapy."
57
+ }
58
+ },
59
+ {
60
+ "id": "P005",
61
+ "name": "David Wilson",
62
+ "age": 48,
63
+ "gender": "Male",
64
+ "contact": "+1 567-890-1234",
65
+ "address": "321 Pine Street, City, Country",
66
+ "issue": {
67
+ "description": "The patient is experiencing mood swings and episodes of elevated energy.",
68
+ "symptoms": ["mania", "irritability", "decreased need for sleep"],
69
+ "diagnosis": "Bipolar Disorder",
70
+ "treatment": "Prescribed mood stabilizer medication and advised regular therapy sessions."
71
+ }
72
+ },
73
+ {
74
+ "id": "P006",
75
+ "name": "Olivia Thompson",
76
+ "age": 29,
77
+ "gender": "Female",
78
+ "contact": "+1 678-901-2345",
79
+ "address": "543 Cedar Road, City, Country",
80
+ "issue": {
81
+ "description": "The patient is experiencing social withdrawal and lack of interest in activities.",
82
+ "symptoms": ["isolation", "anhedonia", "low motivation"],
83
+ "diagnosis": "Major Depressive Disorder",
84
+ "treatment": "Prescribed antidepressant medication and recommended supportive counseling."
85
+ }
86
+ },
87
+ {
88
+ "id": "P007",
89
+ "name": "Daniel Anderson",
90
+ "age": 36,
91
+ "gender": "Male",
92
+ "contact": "+1 789-012-3456",
93
+ "address": "876 Oak Street, City, Country",
94
+ "issue": {
95
+ "description": "The patient is experiencing recurrent nightmares and flashbacks.",
96
+ "symptoms": ["nightmares", "hypervigilance", "emotional distress"],
97
+ "diagnosis": "Post-Traumatic Stress Disorder (PTSD)",
98
+ "treatment": "Prescribed selective serotonin reuptake inhibitor (SSRI) medication and advised trauma-focused therapy."
99
+ }
100
+ },
101
+ {
102
+ "id": "P008",
103
+ "name": "Sophia Martinez",
104
+ "age": 42,
105
+ "gender": "Female",
106
+ "contact": "+1 890-123-4567",
107
+ "address": "234 Elm Avenue, City, Country",
108
+ "issue": {
109
+ "description": "The patient is experiencing excessive worry and physical tension.",
110
+ "symptoms": ["chronic worrying", "muscle tension", "restlessness"],
111
+ "diagnosis": "Generalized Anxiety Disorder",
112
+ "treatment": "Prescribed anti-anxiety medication and advised relaxation techniques."
113
+ }
114
+ }
115
+ ]
116
+ }
117
+
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ tensorflow
3
+ transformers
4
+ openai
5
+ tiktoken
6
+ langchain
7
+ requests
8
+ validators
9
+ pytesseract
10
+ tabulate
11
+ nltk
12
+ python-dotenv
13
+ faiss-cpu
14
+ plotly
15
+ pandas
16
+ plotly-express
style.css ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .leftimage{
2
+ padding-top:75px;
3
+ margin-left:250px;
4
+ }
5
+ .rightimage{
6
+ margin-right:260px;
7
+ margin-top:15px;
8
+ }
9
+
10
+ .height{
11
+ height:60px;
12
+ }