forked from aisemble/MemoMed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoMed.py
393 lines (286 loc) · 10.4 KB
/
MemoMed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# a mock conversation dialogue for a clinical visit:
# Patient: Doctor, I've been feeling really tired lately, more than usual. I just don't have the energy to do anything.
# Doctor: I see. Have you noticed any other symptoms?
# Patient: Yes, I've also been experiencing shortness of breath, even when I'm not doing anything strenuous. And I've noticed that my heart has been beaing faster than normal.
# Doctor: "How about your appetite? Any changes there?
# Patient: Now that you mention it, I haven't been eating as much as I usually do. I've also been feeling a bit dizzy and lightheaded at times.
# Example questions:
# what are the major symptoms?
# what might cause these symptoms?
# which specialist I should see?
import openai
import speech_recognition as sr
import streamlit as st
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")
def main():
print(f" ")
if __name__ == "__main__":
main()
# Initialize the conversation history
conversation_history = ChatMessageHistory()
def transcribe_speech():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Speak Anything :")
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print("You said : {}".format(text))
return text
except:
print("Sorry could not recognize your voice")
return None
def transcribe_audio(audio_file):
r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
audio = r.record(source)
try:
text = r.recognize_google(audio)
st.write("Transcript: ", text)
return text
except:
st.write("Sorry, I could not transcribe the file.")
return None
# def generate_notes(transcribed_text):
# template = f"""
# <b>Patient:</b> {transcribed_text}
# <b>Source of Information:</b>
# <b>Date and Time:</b>
# <b>Interpreter/Substitute Decision-Maker:</b>
# <b>Allergies:</b>
# <b>Relevant History and Physical Findings:</b>
# <b>Vital Signs:</b>
# <b>Pertinent Positive/Negative Findings:</b>
# <b>Assessment of Patient Capacity:</b>
# <b>Clinical Assessment:</b>
# <b>Working Diagnosis:</b>
# <b>Differential Diagnosis:</b>
# <b>Final Diagnosis:</b>
# <b>Plan of Action:</b>
# <b>Investigations:</b>
# <b>Consultations:</b>
# <b>Treatment:</b>
# <b>Follow-Up:</b>
# <b>Rationale for the Plan:</b>
# <b>Expectations of Outcomes:</b>
# <b>Medications (Doses and Duration):</b>
# <b>Medication Reconciliation:</b>
# <b>Calls to Consultants:</b>
# <b>Consultant's Name:</b>
# <b>Advice Received:</b>
# <b>Information Given by/to the Patient (or SDM):</b>
# <b>Concerns Raised, Questions Asked, and Responses Given:</b>
# <b>Verification of Patient Understanding:</b>
# <b>Consent Discussion Summary:</b>
# <b>Discharge Instructions:</b>
# <b>Symptoms and Signs that Should Prompt a Reassessment:</b>
# <b>Urgency of Follow Up:</b>
# <b>Where and When to Return:</b>
# <b>Missed Appointments:</b>
# <b>Efforts to Follow Up on Investigation Results:</b>
# <b>Communication with Other Care Providers at Discharge:</b>
# <b>Signature of Writer and Role:</b>
# -End of Note-
# {{
# - The generated note should not include any personally identifiable information (PII) or protected health information (PHI) that could violate privacy laws like HIPAA.
# - The note should be factual and based on the information provided in the transcribed text.
# - The note should not include any speculative or hypothetical information.
# }}
# """
# # Use the OpenAI API to generate the note
# response = openai.ChatCompletion.create(
# model="gpt-4",
# messages=[
# {"role": "system", "content": template},
# {"role": "user", "content": transcribed_text}
# ]
# )
# return response['choices'][0]['message']['content'].strip()
def generate_notes(transcribed_text, template):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": template},
{"role": "user", "content": transcribed_text}
]
)
suggestions = response['choices'][0]['message']['content'].strip()
return suggestions
def generate_suggestions(note):
messages = [
{
"role": "system",
"content": "You are a helpful healthcare assistant that generates suggestions based on medical notes."
},
{
"role": "user",
"content": note
}
]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
suggestion = response['choices'][0]['message']['content']
return suggestion
def chat_with_gpt(prompt, generated_notes, conversation_history):
# Add the generated notes to the conversation history
conversation_history.add_ai_message(generated_notes)
# Add the user's message to the conversation history
conversation_history.add_user_message(prompt)
# Initialize the memory
memory = ConversationBufferMemory()
# Add the conversation history to the memory
memory.chat_memory = conversation_history
# Load the memory variables
memory_variables = memory.load_memory_variables({})
# Use the OpenAI API to generate the response
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": memory_variables['history']}
]
)
# Add the AI's message to the conversation history
conversation_history.add_ai_message(response['choices'][0]['message']['content'])
return response['choices'][0]['message']['content']
# Define the templates
templates = {
"General": """
Patient: {transcribed_text}
Date and Time:
Reason for Visit:
Presenting Symptoms:
Past Medical History:
Physical Examination Findings:
Assessment:
Plan:
Signature:
""",
"Pediatrician": """
Patient: {transcribed_text}
Date and Time of Visit:
Reason for Visit:
Presenting Symptoms:
Duration of Symptoms:
Past Medical History:
Immunization Status:
Growth and Development History:
Physical Examination Findings:
Vital Signs:
Growth Parameters:
Systemic Examination Findings:
Assessment:
Working Diagnosis:
Differential Diagnosis:
Plan:
Investigations:
Treatment Plan:
Follow-Up Plan:
Health Promotion and Disease Prevention Advice:
Parent's Concerns and Questions:
Responses Given:
Signature of Pediatrician:
""",
"ED nurse": """
Patient: {transcribed_text}
Date and Time of Arrival:
Chief Complaint:
Presenting Symptoms:
Duration of Symptoms:
Past Medical History:
Allergies:
Vital Signs on Arrival:
Physical Examination Findings:
Nursing Assessment:
Level of Consciousness:
Pain Assessment:
Other Relevant Findings:
Interventions and Treatments Provided:
Medications Administered:
Procedures Performed:
Response to Interventions:
Change in Condition:
Handover Notes:
Signature of Nurse:
""",
"Surgeon": """
Patient: {transcribed_text}
Date and Time of Consultation:
Reason for Consultation:
Presenting Symptoms:
Duration of Symptoms:
Past Medical History:
Previous Surgeries:
Allergies:
Physical Examination Findings:
Systemic Examination:
Local Examination:
Preoperative Diagnosis:
Differential Diagnosis:
Plan:
Investigations:
Proposed Surgical Procedure:
Risks and Benefits Discussed:
Consent Discussion Summary:
Postoperative Care Plan:
Patient's Concerns and Questions:
Responses Given:
Signature of Surgeon:
"""
}
def main():
st.title("MemoMed: An Auto Note-Taking Tool for Doctors and Nurses")
persona = st.selectbox("Select your persona:", ["General", "Pediatrician", "ED nurse", "Surgeon"])
template = templates[persona]
st.header("Transcribe Audio")
# audio_file = st.file_uploader("Upload Audio", key='audio_file')
# if st.button("Start Transcription"):
# st.button("Transcribing...", disabled=True)
# transcribed_text = transcribe_audio(audio_file)
# st.session_state.transcribed_text = transcribed_text
# st.write(transcribed_text)
# st.button("Transcription Complete", disabled=True)
# Option for upload audio or using microphone
option = st.selectbox("Choose an option", ["Upload Audio File", "Use Microphone"])
if option == "Upload Audio File":
audio_file = st.file_uploader("Upload Audio", type=['wav', 'mp3', 'flac'], key='audio_file')
if st.button("Start Transcription from File"):
st.button("Transcribing...", disabled=True)
transcribed_text = transcribe_audio(audio_file)
st.session_state.transcribed_text = transcribed_text
st.write(transcribed_text)
st.button("Transcription Complete", disabled=True)
elif option == "Use Microphone":
if st.button("Start Transcription from Microphone"):
st.button("Transcribing...", disabled=True)
transcribed_text = transcribe_speech()
st.session_state.transcribed_text = transcribed_text
st.write(transcribed_text)
st.button("Transcription Complete", disabled=True)
# Generate Notes
st.header("Start of the Generate Notes")
notes_input = st.text_area("Input", value=st.session_state.transcribed_text if 'transcribed_text' in st.session_state else '', key='notes_input')
if st.button("Generate Notes"):
notes = generate_notes(notes_input, template)
st.session_state.notes = notes
st.markdown(f"**{notes}**", unsafe_allow_html=True)
# Generate Suggestions
st.header("Start of the Generate Suggestions")
suggestions_input = st.text_area("Input", value=st.session_state.notes if 'notes' in st.session_state else '', key='suggestions_input')
if st.button("Generate Suggestions"):
suggestions = generate_suggestions(suggestions_input)
st.write(suggestions)
st.title("MemoMed Chatbot")
# User input
user_input = st.text_input("Enter your message:")
# Send button
if st.button("Send"):
response = chat_with_gpt(user_input, st.session_state.notes, conversation_history)
st.write(f"AI: {response}")
if __name__ == "__main__":
main()