Update callbackmanager.py (#1)
Browse files- Update callbackmanager.py (a791755f777bb8de77d9d4e859c442022ff3f14b)
- callbackmanager.py +146 -44
callbackmanager.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
-
from meldrx import MeldRxAPI
|
3 |
import json
|
4 |
import os
|
5 |
import tempfile
|
@@ -14,6 +14,30 @@ logger = logging.getLogger(__name__)
|
|
14 |
# Import PDF utilities
|
15 |
from pdfutils import PDFGenerator, generate_discharge_summary
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
class CallbackManager:
|
18 |
def __init__(self, redirect_uri: str, client_secret: str = None):
|
19 |
client_id = os.getenv("APPID")
|
@@ -42,7 +66,7 @@ class CallbackManager:
|
|
42 |
if not self.access_token:
|
43 |
logger.warning("Not authenticated when getting patient data")
|
44 |
return "Not authenticated. Please provide a valid authorization code first."
|
45 |
-
|
46 |
# For demo purposes, if there's no actual API connected, return mock data
|
47 |
# Remove this in production and use the real API call
|
48 |
if not hasattr(self.api, 'get_patients') or self.api.get_patients is None:
|
@@ -101,7 +125,7 @@ class CallbackManager:
|
|
101 |
]
|
102 |
}
|
103 |
return json.dumps(mock_data, indent=2)
|
104 |
-
|
105 |
# Real implementation with API call
|
106 |
logger.info("Calling Meldrx API to get patients")
|
107 |
patients = self.api.get_patients()
|
@@ -117,7 +141,7 @@ class CallbackManager:
|
|
117 |
"""Fetch patient documents from MeldRx"""
|
118 |
if not self.access_token:
|
119 |
return "Not authenticated. Please provide a valid authorization code first."
|
120 |
-
|
121 |
try:
|
122 |
# This would call the actual MeldRx API to get documents for a specific patient
|
123 |
# For demonstration, we'll return mock document data
|
@@ -139,7 +163,7 @@ class CallbackManager:
|
|
139 |
]
|
140 |
except Exception as e:
|
141 |
return f"Error retrieving patient documents: {str(e)}"
|
142 |
-
|
143 |
def display_form(
|
144 |
first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
|
145 |
doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
|
@@ -173,10 +197,10 @@ def generate_pdf_from_form(
|
|
173 |
diagnosis, procedures, medications, preparer_name, preparer_job_title
|
174 |
):
|
175 |
"""Generate a PDF discharge form using the provided data"""
|
176 |
-
|
177 |
# Create PDF generator
|
178 |
pdf_gen = PDFGenerator()
|
179 |
-
|
180 |
# Format data for PDF generation
|
181 |
patient_info = {
|
182 |
"first_name": first_name,
|
@@ -190,7 +214,7 @@ def generate_pdf_from_form(
|
|
190 |
"state": state,
|
191 |
"zip": zip_code
|
192 |
}
|
193 |
-
|
194 |
discharge_info = {
|
195 |
"date_of_admission": admission_date,
|
196 |
"date_of_discharge": discharge_date,
|
@@ -198,25 +222,25 @@ def generate_pdf_from_form(
|
|
198 |
"mode_of_admission": admission_method,
|
199 |
"discharge_against_advice": "Yes" if discharge_reason == "Discharge Against Advice" else "No"
|
200 |
}
|
201 |
-
|
202 |
diagnosis_info = {
|
203 |
"diagnosis": diagnosis,
|
204 |
"operation_procedure": procedures,
|
205 |
"treatment": "", # Not collected in the form
|
206 |
"follow_up": "" # Not collected in the form
|
207 |
}
|
208 |
-
|
209 |
medication_info = {
|
210 |
"medications": [medications] if medications else [],
|
211 |
"instructions": "" # Not collected in the form
|
212 |
}
|
213 |
-
|
214 |
prepared_by = {
|
215 |
"name": preparer_name,
|
216 |
"title": preparer_job_title,
|
217 |
"signature": "" # Not collected in the form
|
218 |
}
|
219 |
-
|
220 |
# Generate PDF
|
221 |
pdf_buffer = pdf_gen.generate_discharge_form(
|
222 |
patient_info,
|
@@ -225,13 +249,13 @@ def generate_pdf_from_form(
|
|
225 |
medication_info,
|
226 |
prepared_by
|
227 |
)
|
228 |
-
|
229 |
# Create temporary file to save the PDF
|
230 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
|
231 |
temp_file.write(pdf_buffer.read())
|
232 |
temp_file_path = temp_file.name
|
233 |
temp_file.close()
|
234 |
-
|
235 |
return temp_file_path
|
236 |
|
237 |
def generate_pdf_from_meldrx(patient_data):
|
@@ -242,17 +266,17 @@ def generate_pdf_from_meldrx(patient_data):
|
|
242 |
patient_data = json.loads(patient_data)
|
243 |
except:
|
244 |
return None, "Invalid patient data format"
|
245 |
-
|
246 |
if not patient_data:
|
247 |
return None, "No patient data available"
|
248 |
-
|
249 |
try:
|
250 |
# For demonstration, we'll use the first patient in the list if it's a list
|
251 |
if isinstance(patient_data, list) and len(patient_data):
|
252 |
patient = patient_data[0]
|
253 |
else:
|
254 |
patient = patient_data
|
255 |
-
|
256 |
# Extract patient info
|
257 |
patient_info = {
|
258 |
"name": f"{patient.get('name', {}).get('given', [''])[0]} {patient.get('name', {}).get('family', '')}",
|
@@ -261,7 +285,7 @@ def generate_pdf_from_meldrx(patient_data):
|
|
261 |
"admission_date": datetime.now().strftime("%Y-%m-%d"), # Mock data
|
262 |
"physician": "Dr. Provider" # Mock data
|
263 |
}
|
264 |
-
|
265 |
# Mock LLM-generated content
|
266 |
llm_content = {
|
267 |
"diagnosis": "Diagnosis information would be generated by LLM",
|
@@ -270,16 +294,35 @@ def generate_pdf_from_meldrx(patient_data):
|
|
270 |
"follow_up": "Follow-up instructions would be generated by LLM",
|
271 |
"special_instructions": "Special instructions would be generated by LLM"
|
272 |
}
|
273 |
-
|
274 |
# Create discharge summary
|
275 |
output_dir = tempfile.mkdtemp()
|
276 |
pdf_path = generate_discharge_summary(patient_info, llm_content, output_dir)
|
277 |
-
|
278 |
return pdf_path, "PDF generated successfully"
|
279 |
-
|
280 |
except Exception as e:
|
281 |
return None, f"Error generating PDF: {str(e)}"
|
282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
283 |
# Create a simplified interface to avoid complex component interactions
|
284 |
CALLBACK_MANAGER = CallbackManager(
|
285 |
redirect_uri="https://multitransformer-discharge-guard.hf.space/callback",
|
@@ -288,8 +331,8 @@ CALLBACK_MANAGER = CallbackManager(
|
|
288 |
|
289 |
# Create the UI
|
290 |
with gr.Blocks() as demo:
|
291 |
-
gr.Markdown("# Patient Discharge Form with MeldRx
|
292 |
-
|
293 |
with gr.Tab("Authenticate with MeldRx"):
|
294 |
gr.Markdown("## SMART on FHIR Authentication")
|
295 |
auth_url_output = gr.Textbox(label="Authorization URL", value=CALLBACK_MANAGER.get_auth_url(), interactive=False)
|
@@ -297,41 +340,41 @@ with gr.Blocks() as demo:
|
|
297 |
auth_code_input = gr.Textbox(label="Authorization Code")
|
298 |
auth_submit = gr.Button("Submit Code")
|
299 |
auth_result = gr.Textbox(label="Authentication Result")
|
300 |
-
|
301 |
patient_data_button = gr.Button("Fetch Patient Data")
|
302 |
patient_data_output = gr.Textbox(label="Patient Data", lines=10)
|
303 |
-
|
304 |
# Add button to generate PDF from MeldRx data
|
305 |
meldrx_pdf_button = gr.Button("Generate PDF from MeldRx Data")
|
306 |
meldrx_pdf_status = gr.Textbox(label="PDF Generation Status")
|
307 |
meldrx_pdf_download = gr.File(label="Download Generated PDF")
|
308 |
-
|
309 |
auth_submit.click(fn=CALLBACK_MANAGER.set_auth_code, inputs=auth_code_input, outputs=auth_result)
|
310 |
-
|
311 |
with gr.Tab("Patient Dashboard"):
|
312 |
gr.Markdown("## Patient Data")
|
313 |
dashboard_output = gr.HTML("<p>Fetch patient data from the Authentication tab first.</p>")
|
314 |
-
|
315 |
refresh_btn = gr.Button("Refresh Data")
|
316 |
-
|
317 |
# Simple function to update dashboard based on fetched data
|
318 |
def update_dashboard():
|
319 |
try:
|
320 |
data = CALLBACK_MANAGER.get_patient_data()
|
321 |
if data.startswith("Not authenticated") or data.startswith("Failed") or data.startswith("Error"):
|
322 |
return f"<p>{data}</p>"
|
323 |
-
|
324 |
try:
|
325 |
# Parse the data
|
326 |
patients_data = json.loads(data)
|
327 |
patients = []
|
328 |
-
|
329 |
# Extract patients from bundle
|
330 |
for entry in patients_data.get("entry", []):
|
331 |
resource = entry.get("resource", {})
|
332 |
if resource.get("resourceType") == "Patient":
|
333 |
patients.append(resource)
|
334 |
-
|
335 |
# Generate HTML for each patient
|
336 |
html = "<h3>Patients</h3>"
|
337 |
for patient in patients:
|
@@ -339,11 +382,11 @@ with gr.Blocks() as demo:
|
|
339 |
name = patient.get("name", [{}])[0]
|
340 |
given = " ".join(name.get("given", ["Unknown"]))
|
341 |
family = name.get("family", "Unknown")
|
342 |
-
|
343 |
# Extract other details
|
344 |
gender = patient.get("gender", "unknown").capitalize()
|
345 |
birth_date = patient.get("birthDate", "Unknown")
|
346 |
-
|
347 |
# Generate HTML card
|
348 |
html += f"""
|
349 |
<div style="border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 5px;">
|
@@ -353,13 +396,13 @@ with gr.Blocks() as demo:
|
|
353 |
<p><strong>ID:</strong> {patient.get("id", "Unknown")}</p>
|
354 |
</div>
|
355 |
"""
|
356 |
-
|
357 |
return html
|
358 |
except Exception as e:
|
359 |
return f"<p>Error parsing patient data: {str(e)}</p>"
|
360 |
except Exception as e:
|
361 |
return f"<p>Error fetching patient data: {str(e)}</p>"
|
362 |
-
|
363 |
with gr.Tab("Discharge Form"):
|
364 |
gr.Markdown("## Patient Details")
|
365 |
with gr.Row():
|
@@ -404,16 +447,16 @@ with gr.Blocks() as demo:
|
|
404 |
with gr.Row():
|
405 |
preparer_name = gr.Textbox(label="Name")
|
406 |
preparer_job_title = gr.Textbox(label="Job Title")
|
407 |
-
|
408 |
# Add buttons for both display form and generate PDF
|
409 |
with gr.Row():
|
410 |
submit_display = gr.Button("Display Form")
|
411 |
submit_pdf = gr.Button("Generate PDF")
|
412 |
-
|
413 |
# Output areas
|
414 |
form_output = gr.Markdown()
|
415 |
pdf_output = gr.File(label="Download PDF")
|
416 |
-
|
417 |
# Connect the display form button
|
418 |
submit_display.click(
|
419 |
display_form,
|
@@ -426,7 +469,7 @@ with gr.Blocks() as demo:
|
|
426 |
],
|
427 |
outputs=form_output
|
428 |
)
|
429 |
-
|
430 |
# Connect the generate PDF button
|
431 |
submit_pdf.click(
|
432 |
generate_pdf_from_form,
|
@@ -439,28 +482,87 @@ with gr.Blocks() as demo:
|
|
439 |
],
|
440 |
outputs=pdf_output
|
441 |
)
|
442 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
443 |
# Connect the patient data buttons
|
444 |
patient_data_button.click(
|
445 |
fn=CALLBACK_MANAGER.get_patient_data,
|
446 |
inputs=None,
|
447 |
outputs=patient_data_output
|
448 |
)
|
449 |
-
|
450 |
# Connect refresh button to update dashboard
|
451 |
refresh_btn.click(
|
452 |
fn=update_dashboard,
|
453 |
inputs=None,
|
454 |
outputs=dashboard_output
|
455 |
)
|
456 |
-
|
457 |
# Add functionality for PDF generation from MeldRx data
|
458 |
meldrx_pdf_button.click(
|
459 |
fn=generate_pdf_from_meldrx,
|
460 |
inputs=patient_data_output,
|
461 |
outputs=[meldrx_pdf_download, meldrx_pdf_status]
|
462 |
)
|
463 |
-
|
464 |
# Connect patient data updates to dashboard
|
465 |
patient_data_button.click(
|
466 |
fn=update_dashboard,
|
|
|
1 |
import gradio as gr
|
2 |
+
from meldrx import MeldRxAPI
|
3 |
import json
|
4 |
import os
|
5 |
import tempfile
|
|
|
14 |
# Import PDF utilities
|
15 |
from pdfutils import PDFGenerator, generate_discharge_summary
|
16 |
|
17 |
+
# Import necessary libraries for new file types and AI analysis functions
|
18 |
+
import pydicom # For DICOM
|
19 |
+
import hl7 # For HL7
|
20 |
+
from xml.etree import ElementTree # For XML and CCDA
|
21 |
+
from pypdf import PdfReader # For PDF
|
22 |
+
import csv # For CSV
|
23 |
+
# Assuming your AI analysis functions are in the same script or imported
|
24 |
+
# For now, let's define placeholder AI analysis functions for Gradio context
|
25 |
+
def analyze_dicom_file_with_ai(dicom_file):
|
26 |
+
return "DICOM Analysis Report (Placeholder - Real AI integration needed)"
|
27 |
+
|
28 |
+
def analyze_hl7_file_with_ai(hl7_file):
|
29 |
+
return "HL7 Analysis Report (Placeholder - Real AI integration needed)"
|
30 |
+
|
31 |
+
def analyze_cda_xml_file_with_ai(cda_xml_file):
|
32 |
+
return "CCDA/XML Analysis Report (Placeholder - Real AI integration needed)"
|
33 |
+
|
34 |
+
def analyze_pdf_file_with_ai(pdf_file):
|
35 |
+
return "PDF Analysis Report (Placeholder - Real AI integration needed)"
|
36 |
+
|
37 |
+
def analyze_csv_file_with_ai(csv_file):
|
38 |
+
return "CSV Analysis Report (Placeholder - Real AI integration needed)"
|
39 |
+
|
40 |
+
|
41 |
class CallbackManager:
|
42 |
def __init__(self, redirect_uri: str, client_secret: str = None):
|
43 |
client_id = os.getenv("APPID")
|
|
|
66 |
if not self.access_token:
|
67 |
logger.warning("Not authenticated when getting patient data")
|
68 |
return "Not authenticated. Please provide a valid authorization code first."
|
69 |
+
|
70 |
# For demo purposes, if there's no actual API connected, return mock data
|
71 |
# Remove this in production and use the real API call
|
72 |
if not hasattr(self.api, 'get_patients') or self.api.get_patients is None:
|
|
|
125 |
]
|
126 |
}
|
127 |
return json.dumps(mock_data, indent=2)
|
128 |
+
|
129 |
# Real implementation with API call
|
130 |
logger.info("Calling Meldrx API to get patients")
|
131 |
patients = self.api.get_patients()
|
|
|
141 |
"""Fetch patient documents from MeldRx"""
|
142 |
if not self.access_token:
|
143 |
return "Not authenticated. Please provide a valid authorization code first."
|
144 |
+
|
145 |
try:
|
146 |
# This would call the actual MeldRx API to get documents for a specific patient
|
147 |
# For demonstration, we'll return mock document data
|
|
|
163 |
]
|
164 |
except Exception as e:
|
165 |
return f"Error retrieving patient documents: {str(e)}"
|
166 |
+
|
167 |
def display_form(
|
168 |
first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
|
169 |
doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
|
|
|
197 |
diagnosis, procedures, medications, preparer_name, preparer_job_title
|
198 |
):
|
199 |
"""Generate a PDF discharge form using the provided data"""
|
200 |
+
|
201 |
# Create PDF generator
|
202 |
pdf_gen = PDFGenerator()
|
203 |
+
|
204 |
# Format data for PDF generation
|
205 |
patient_info = {
|
206 |
"first_name": first_name,
|
|
|
214 |
"state": state,
|
215 |
"zip": zip_code
|
216 |
}
|
217 |
+
|
218 |
discharge_info = {
|
219 |
"date_of_admission": admission_date,
|
220 |
"date_of_discharge": discharge_date,
|
|
|
222 |
"mode_of_admission": admission_method,
|
223 |
"discharge_against_advice": "Yes" if discharge_reason == "Discharge Against Advice" else "No"
|
224 |
}
|
225 |
+
|
226 |
diagnosis_info = {
|
227 |
"diagnosis": diagnosis,
|
228 |
"operation_procedure": procedures,
|
229 |
"treatment": "", # Not collected in the form
|
230 |
"follow_up": "" # Not collected in the form
|
231 |
}
|
232 |
+
|
233 |
medication_info = {
|
234 |
"medications": [medications] if medications else [],
|
235 |
"instructions": "" # Not collected in the form
|
236 |
}
|
237 |
+
|
238 |
prepared_by = {
|
239 |
"name": preparer_name,
|
240 |
"title": preparer_job_title,
|
241 |
"signature": "" # Not collected in the form
|
242 |
}
|
243 |
+
|
244 |
# Generate PDF
|
245 |
pdf_buffer = pdf_gen.generate_discharge_form(
|
246 |
patient_info,
|
|
|
249 |
medication_info,
|
250 |
prepared_by
|
251 |
)
|
252 |
+
|
253 |
# Create temporary file to save the PDF
|
254 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
|
255 |
temp_file.write(pdf_buffer.read())
|
256 |
temp_file_path = temp_file.name
|
257 |
temp_file.close()
|
258 |
+
|
259 |
return temp_file_path
|
260 |
|
261 |
def generate_pdf_from_meldrx(patient_data):
|
|
|
266 |
patient_data = json.loads(patient_data)
|
267 |
except:
|
268 |
return None, "Invalid patient data format"
|
269 |
+
|
270 |
if not patient_data:
|
271 |
return None, "No patient data available"
|
272 |
+
|
273 |
try:
|
274 |
# For demonstration, we'll use the first patient in the list if it's a list
|
275 |
if isinstance(patient_data, list) and len(patient_data):
|
276 |
patient = patient_data[0]
|
277 |
else:
|
278 |
patient = patient_data
|
279 |
+
|
280 |
# Extract patient info
|
281 |
patient_info = {
|
282 |
"name": f"{patient.get('name', {}).get('given', [''])[0]} {patient.get('name', {}).get('family', '')}",
|
|
|
285 |
"admission_date": datetime.now().strftime("%Y-%m-%d"), # Mock data
|
286 |
"physician": "Dr. Provider" # Mock data
|
287 |
}
|
288 |
+
|
289 |
# Mock LLM-generated content
|
290 |
llm_content = {
|
291 |
"diagnosis": "Diagnosis information would be generated by LLM",
|
|
|
294 |
"follow_up": "Follow-up instructions would be generated by LLM",
|
295 |
"special_instructions": "Special instructions would be generated by LLM"
|
296 |
}
|
297 |
+
|
298 |
# Create discharge summary
|
299 |
output_dir = tempfile.mkdtemp()
|
300 |
pdf_path = generate_discharge_summary(patient_info, llm_content, output_dir)
|
301 |
+
|
302 |
return pdf_path, "PDF generated successfully"
|
303 |
+
|
304 |
except Exception as e:
|
305 |
return None, f"Error generating PDF: {str(e)}"
|
306 |
|
307 |
+
def generate_discharge_paper_one_click():
|
308 |
+
"""One-click function to fetch patient data and generate discharge paper."""
|
309 |
+
patient_data_str = CALLBACK_MANAGER.get_patient_data()
|
310 |
+
if patient_data_str.startswith("Not authenticated") or patient_data_str.startswith("Failed") or patient_data_str.startswith("Error"):
|
311 |
+
return None, patient_data_str # Return error message if authentication or data fetch fails
|
312 |
+
|
313 |
+
try:
|
314 |
+
patient_data = json.loads(patient_data_str)
|
315 |
+
pdf_path, status_message = generate_pdf_from_meldrx(patient_data)
|
316 |
+
if pdf_path:
|
317 |
+
return pdf_path, status_message
|
318 |
+
else:
|
319 |
+
return None, status_message # Return status message if PDF generation fails
|
320 |
+
except json.JSONDecodeError:
|
321 |
+
return None, "Error: Patient data is not in valid JSON format."
|
322 |
+
except Exception as e:
|
323 |
+
return None, f"Error during discharge paper generation: {str(e)}"
|
324 |
+
|
325 |
+
|
326 |
# Create a simplified interface to avoid complex component interactions
|
327 |
CALLBACK_MANAGER = CallbackManager(
|
328 |
redirect_uri="https://multitransformer-discharge-guard.hf.space/callback",
|
|
|
331 |
|
332 |
# Create the UI
|
333 |
with gr.Blocks() as demo:
|
334 |
+
gr.Markdown("# Patient Discharge Form with MeldRx & Medical File Analysis")
|
335 |
+
|
336 |
with gr.Tab("Authenticate with MeldRx"):
|
337 |
gr.Markdown("## SMART on FHIR Authentication")
|
338 |
auth_url_output = gr.Textbox(label="Authorization URL", value=CALLBACK_MANAGER.get_auth_url(), interactive=False)
|
|
|
340 |
auth_code_input = gr.Textbox(label="Authorization Code")
|
341 |
auth_submit = gr.Button("Submit Code")
|
342 |
auth_result = gr.Textbox(label="Authentication Result")
|
343 |
+
|
344 |
patient_data_button = gr.Button("Fetch Patient Data")
|
345 |
patient_data_output = gr.Textbox(label="Patient Data", lines=10)
|
346 |
+
|
347 |
# Add button to generate PDF from MeldRx data
|
348 |
meldrx_pdf_button = gr.Button("Generate PDF from MeldRx Data")
|
349 |
meldrx_pdf_status = gr.Textbox(label="PDF Generation Status")
|
350 |
meldrx_pdf_download = gr.File(label="Download Generated PDF")
|
351 |
+
|
352 |
auth_submit.click(fn=CALLBACK_MANAGER.set_auth_code, inputs=auth_code_input, outputs=auth_result)
|
353 |
+
|
354 |
with gr.Tab("Patient Dashboard"):
|
355 |
gr.Markdown("## Patient Data")
|
356 |
dashboard_output = gr.HTML("<p>Fetch patient data from the Authentication tab first.</p>")
|
357 |
+
|
358 |
refresh_btn = gr.Button("Refresh Data")
|
359 |
+
|
360 |
# Simple function to update dashboard based on fetched data
|
361 |
def update_dashboard():
|
362 |
try:
|
363 |
data = CALLBACK_MANAGER.get_patient_data()
|
364 |
if data.startswith("Not authenticated") or data.startswith("Failed") or data.startswith("Error"):
|
365 |
return f"<p>{data}</p>"
|
366 |
+
|
367 |
try:
|
368 |
# Parse the data
|
369 |
patients_data = json.loads(data)
|
370 |
patients = []
|
371 |
+
|
372 |
# Extract patients from bundle
|
373 |
for entry in patients_data.get("entry", []):
|
374 |
resource = entry.get("resource", {})
|
375 |
if resource.get("resourceType") == "Patient":
|
376 |
patients.append(resource)
|
377 |
+
|
378 |
# Generate HTML for each patient
|
379 |
html = "<h3>Patients</h3>"
|
380 |
for patient in patients:
|
|
|
382 |
name = patient.get("name", [{}])[0]
|
383 |
given = " ".join(name.get("given", ["Unknown"]))
|
384 |
family = name.get("family", "Unknown")
|
385 |
+
|
386 |
# Extract other details
|
387 |
gender = patient.get("gender", "unknown").capitalize()
|
388 |
birth_date = patient.get("birthDate", "Unknown")
|
389 |
+
|
390 |
# Generate HTML card
|
391 |
html += f"""
|
392 |
<div style="border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 5px;">
|
|
|
396 |
<p><strong>ID:</strong> {patient.get("id", "Unknown")}</p>
|
397 |
</div>
|
398 |
"""
|
399 |
+
|
400 |
return html
|
401 |
except Exception as e:
|
402 |
return f"<p>Error parsing patient data: {str(e)}</p>"
|
403 |
except Exception as e:
|
404 |
return f"<p>Error fetching patient data: {str(e)}</p>"
|
405 |
+
|
406 |
with gr.Tab("Discharge Form"):
|
407 |
gr.Markdown("## Patient Details")
|
408 |
with gr.Row():
|
|
|
447 |
with gr.Row():
|
448 |
preparer_name = gr.Textbox(label="Name")
|
449 |
preparer_job_title = gr.Textbox(label="Job Title")
|
450 |
+
|
451 |
# Add buttons for both display form and generate PDF
|
452 |
with gr.Row():
|
453 |
submit_display = gr.Button("Display Form")
|
454 |
submit_pdf = gr.Button("Generate PDF")
|
455 |
+
|
456 |
# Output areas
|
457 |
form_output = gr.Markdown()
|
458 |
pdf_output = gr.File(label="Download PDF")
|
459 |
+
|
460 |
# Connect the display form button
|
461 |
submit_display.click(
|
462 |
display_form,
|
|
|
469 |
],
|
470 |
outputs=form_output
|
471 |
)
|
472 |
+
|
473 |
# Connect the generate PDF button
|
474 |
submit_pdf.click(
|
475 |
generate_pdf_from_form,
|
|
|
482 |
],
|
483 |
outputs=pdf_output
|
484 |
)
|
485 |
+
|
486 |
+
with gr.Tab("Medical File Analysis"):
|
487 |
+
gr.Markdown("## Analyze Medical Files with DocuNexus AI")
|
488 |
+
with gr.Column():
|
489 |
+
dicom_file = gr.File(file_types=['.dcm'], label="Upload DICOM File (.dcm)")
|
490 |
+
dicom_ai_output = gr.Textbox(label="DICOM Analysis Report", lines=5)
|
491 |
+
analyze_dicom_button = gr.Button("Analyze DICOM with AI")
|
492 |
+
|
493 |
+
hl7_file = gr.File(file_types=['.hl7'], label="Upload HL7 File (.hl7)")
|
494 |
+
hl7_ai_output = gr.Textbox(label="HL7 Analysis Report", lines=5)
|
495 |
+
analyze_hl7_button = gr.Button("Analyze HL7 with AI")
|
496 |
+
|
497 |
+
xml_file = gr.File(file_types=['.xml'], label="Upload XML File (.xml)")
|
498 |
+
xml_ai_output = gr.Textbox(label="XML Analysis Report", lines=5)
|
499 |
+
analyze_xml_button = gr.Button("Analyze XML with AI")
|
500 |
+
|
501 |
+
ccda_file = gr.File(file_types=['.xml', '.cda', '.ccd'], label="Upload CCDA File (.xml, .cda, .ccd)")
|
502 |
+
ccda_ai_output = gr.Textbox(label="CCDA Analysis Report", lines=5)
|
503 |
+
analyze_ccda_button = gr.Button("Analyze CCDA with AI")
|
504 |
+
|
505 |
+
ccd_file = gr.File(file_types=['.ccd'], label="Upload CCD File (.ccd)") # Redundant, as CCDA also handles .ccd, but kept for clarity
|
506 |
+
ccd_ai_output = gr.Textbox(label="CCD Analysis Report", lines=5) # Redundant
|
507 |
+
analyze_ccd_button = gr.Button("Analyze CCD with AI") # Redundant
|
508 |
+
|
509 |
+
|
510 |
+
# Connect AI Analysis Buttons (using placeholder functions for now)
|
511 |
+
analyze_dicom_button.click(
|
512 |
+
lambda file: analyze_dicom_file_with_ai(file.name) if file else "No DICOM file uploaded",
|
513 |
+
inputs=dicom_file, outputs=dicom_ai_output
|
514 |
+
)
|
515 |
+
analyze_hl7_button.click(
|
516 |
+
lambda file: analyze_hl7_file_with_ai(file.name) if file else "No HL7 file uploaded",
|
517 |
+
inputs=hl7_file, outputs=hl7_ai_output
|
518 |
+
)
|
519 |
+
analyze_xml_button.click(
|
520 |
+
lambda file: analyze_cda_xml_file_with_ai(file.name) if file else "No XML file uploaded", # Using CCDA/XML analyzer for generic XML for now
|
521 |
+
inputs=xml_file, outputs=xml_ai_output
|
522 |
+
)
|
523 |
+
analyze_ccda_button.click(
|
524 |
+
lambda file: analyze_cda_xml_file_with_ai(file.name) if file else "No CCDA file uploaded", # Using CCDA/XML analyzer
|
525 |
+
inputs=ccda_file, outputs=ccda_ai_output
|
526 |
+
)
|
527 |
+
analyze_ccd_button.click( # Redundant button, but kept for UI if needed
|
528 |
+
lambda file: analyze_cda_xml_file_with_ai(file.name) if file else "No CCD file uploaded", # Using CCDA/XML analyzer
|
529 |
+
inputs=ccd_file, outputs=ccd_ai_output
|
530 |
+
)
|
531 |
+
|
532 |
+
with gr.Tab("One-Click Discharge Paper"): # New Tab for One-Click Discharge Paper
|
533 |
+
gr.Markdown("## One-Click Medical Discharge Paper Generation")
|
534 |
+
one_click_pdf_button = gr.Button("Generate Discharge Paper (One-Click)")
|
535 |
+
one_click_pdf_status = gr.Textbox(label="Discharge Paper Generation Status")
|
536 |
+
one_click_pdf_download = gr.File(label="Download Discharge Paper")
|
537 |
+
|
538 |
+
one_click_pdf_button.click(
|
539 |
+
generate_discharge_paper_one_click,
|
540 |
+
inputs=[],
|
541 |
+
outputs=[one_click_pdf_download, one_click_pdf_status]
|
542 |
+
)
|
543 |
+
|
544 |
+
|
545 |
# Connect the patient data buttons
|
546 |
patient_data_button.click(
|
547 |
fn=CALLBACK_MANAGER.get_patient_data,
|
548 |
inputs=None,
|
549 |
outputs=patient_data_output
|
550 |
)
|
551 |
+
|
552 |
# Connect refresh button to update dashboard
|
553 |
refresh_btn.click(
|
554 |
fn=update_dashboard,
|
555 |
inputs=None,
|
556 |
outputs=dashboard_output
|
557 |
)
|
558 |
+
|
559 |
# Add functionality for PDF generation from MeldRx data
|
560 |
meldrx_pdf_button.click(
|
561 |
fn=generate_pdf_from_meldrx,
|
562 |
inputs=patient_data_output,
|
563 |
outputs=[meldrx_pdf_download, meldrx_pdf_status]
|
564 |
)
|
565 |
+
|
566 |
# Connect patient data updates to dashboard
|
567 |
patient_data_button.click(
|
568 |
fn=update_dashboard,
|