If this doesn't work gotta rollback
Browse files- callbackmanager.py +71 -298
callbackmanager.py
CHANGED
|
@@ -163,222 +163,8 @@ def display_form(
|
|
| 163 |
- Medications: {medications}
|
| 164 |
- Prepared By: {preparer_name}, {preparer_job_title}
|
| 165 |
"""
|
| 166 |
-
|
| 167 |
-
|
| 168 |
return form
|
| 169 |
|
| 170 |
-
def process_fhir_bundle(fhir_bundle):
|
| 171 |
-
"""Extract and structure patient data from FHIR bundle"""
|
| 172 |
-
patients = []
|
| 173 |
-
if not isinstance(fhir_bundle, dict):
|
| 174 |
-
# Try to parse the data if it's a string
|
| 175 |
-
try:
|
| 176 |
-
fhir_bundle = json.loads(fhir_bundle)
|
| 177 |
-
except:
|
| 178 |
-
return []
|
| 179 |
-
|
| 180 |
-
for entry in fhir_bundle.get("entry", []):
|
| 181 |
-
resource = entry.get("resource", {})
|
| 182 |
-
if resource.get("resourceType") == "Patient":
|
| 183 |
-
patients.append(resource)
|
| 184 |
-
return patients
|
| 185 |
-
|
| 186 |
-
def create_patient_stripe_data(patient):
|
| 187 |
-
"""Extract data from patient to create a stripe (without components or event handlers)"""
|
| 188 |
-
# Safely extract name components
|
| 189 |
-
official_name = next(
|
| 190 |
-
(n for n in patient.get("name", []) if n.get("use") == "official"),
|
| 191 |
-
next((n for n in patient.get("name", [])), {}) # Fallback to first name if no official
|
| 192 |
-
)
|
| 193 |
-
given_names = " ".join(official_name.get("given", ["Unknown"]))
|
| 194 |
-
family_name = official_name.get("family", "Unknown")
|
| 195 |
-
|
| 196 |
-
# Extract demographic information
|
| 197 |
-
gender = patient.get("gender", "unknown").capitalize()
|
| 198 |
-
birth_date = patient.get("birthDate", "Unknown")
|
| 199 |
-
patient_id = patient.get("id", "Unknown")
|
| 200 |
-
|
| 201 |
-
# Extract address information
|
| 202 |
-
address = patient.get("address", [{}])[0] if patient.get("address") else {}
|
| 203 |
-
city = address.get("city", "Unknown")
|
| 204 |
-
state = address.get("state", "")
|
| 205 |
-
postal_code = address.get("postalCode", "")
|
| 206 |
-
|
| 207 |
-
# Return structured data that can be used to display the patient info
|
| 208 |
-
return {
|
| 209 |
-
"name": f"{given_names} {family_name}",
|
| 210 |
-
"gender": gender,
|
| 211 |
-
"birth_date": birth_date,
|
| 212 |
-
"patient_id": patient_id,
|
| 213 |
-
"city": city,
|
| 214 |
-
"state": state,
|
| 215 |
-
"postal_code": postal_code
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
def update_patient_display(patient_data_json):
|
| 219 |
-
"""
|
| 220 |
-
Update the patient display with parsed FHIR data.
|
| 221 |
-
Returns processed data without trying to update UI components directly.
|
| 222 |
-
"""
|
| 223 |
-
try:
|
| 224 |
-
# Handle the case where patient_data_json is an error message
|
| 225 |
-
if isinstance(patient_data_json, str) and (patient_data_json.startswith("Not authenticated") or patient_data_json.startswith("Failed")):
|
| 226 |
-
logger.warning(f"Error in patient data: {patient_data_json}")
|
| 227 |
-
return {
|
| 228 |
-
"has_pagination": False,
|
| 229 |
-
"patients": [],
|
| 230 |
-
"metadata": f"Error: {patient_data_json}",
|
| 231 |
-
"raw_data": None
|
| 232 |
-
}
|
| 233 |
-
|
| 234 |
-
# Parse JSON if it's a string
|
| 235 |
-
if isinstance(patient_data_json, str):
|
| 236 |
-
try:
|
| 237 |
-
fhir_bundle = json.loads(patient_data_json)
|
| 238 |
-
except json.JSONDecodeError as e:
|
| 239 |
-
logger.error(f"JSON decode error: {str(e)} - Data: {patient_data_json[:100]}...")
|
| 240 |
-
return {
|
| 241 |
-
"has_pagination": False,
|
| 242 |
-
"patients": [],
|
| 243 |
-
"metadata": f"Invalid JSON data: {str(e)}",
|
| 244 |
-
"raw_data": None
|
| 245 |
-
}
|
| 246 |
-
else:
|
| 247 |
-
fhir_bundle = patient_data_json
|
| 248 |
-
|
| 249 |
-
# Safety check
|
| 250 |
-
if not isinstance(fhir_bundle, dict):
|
| 251 |
-
logger.error(f"Unexpected data type: {type(fhir_bundle)}")
|
| 252 |
-
return {
|
| 253 |
-
"has_pagination": False,
|
| 254 |
-
"patients": [],
|
| 255 |
-
"metadata": f"Expected dictionary but got {type(fhir_bundle)}",
|
| 256 |
-
"raw_data": None
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
patients = process_fhir_bundle(fhir_bundle)
|
| 260 |
-
|
| 261 |
-
if not patients:
|
| 262 |
-
logger.warning("No patients found in data")
|
| 263 |
-
return {
|
| 264 |
-
"has_pagination": False,
|
| 265 |
-
"patients": [],
|
| 266 |
-
"metadata": "No patients found in the data",
|
| 267 |
-
"raw_data": None
|
| 268 |
-
}
|
| 269 |
-
|
| 270 |
-
# Check pagination
|
| 271 |
-
has_prev = any(link.get("relation") == "previous" for link in fhir_bundle.get("link", []))
|
| 272 |
-
has_next = any(link.get("relation") == "next" for link in fhir_bundle.get("link", []))
|
| 273 |
-
|
| 274 |
-
# Create patient data for display
|
| 275 |
-
patient_data_list = []
|
| 276 |
-
for patient in patients:
|
| 277 |
-
try:
|
| 278 |
-
patient_data = create_patient_stripe_data(patient)
|
| 279 |
-
patient_data_list.append(patient_data)
|
| 280 |
-
except Exception as e:
|
| 281 |
-
logger.error(f"Error processing patient data: {str(e)}")
|
| 282 |
-
# Continue with other patients if one fails
|
| 283 |
-
|
| 284 |
-
logger.info(f"Processed {len(patient_data_list)} patients successfully")
|
| 285 |
-
|
| 286 |
-
# Generate metadata string
|
| 287 |
-
metadata_text = f"""
|
| 288 |
-
**Bundle Metadata**
|
| 289 |
-
Type: {fhir_bundle.get('type', 'Unknown')}
|
| 290 |
-
Total Patients: {fhir_bundle.get('total', len(patients))}
|
| 291 |
-
Last Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
| 292 |
-
"""
|
| 293 |
-
|
| 294 |
-
return {
|
| 295 |
-
"has_pagination": has_prev or has_next,
|
| 296 |
-
"patients": patient_data_list,
|
| 297 |
-
"metadata": metadata_text,
|
| 298 |
-
"raw_data": {"patients": patients, "bundle": fhir_bundle}
|
| 299 |
-
}
|
| 300 |
-
except Exception as e:
|
| 301 |
-
error_msg = f"Error loading patient data: {str(e)}\n{traceback.format_exc()}"
|
| 302 |
-
logger.error(error_msg)
|
| 303 |
-
return {
|
| 304 |
-
"has_pagination": False,
|
| 305 |
-
"patients": [],
|
| 306 |
-
"metadata": error_msg,
|
| 307 |
-
"raw_data": None
|
| 308 |
-
}
|
| 309 |
-
|
| 310 |
-
def fetch_and_display_patients():
|
| 311 |
-
try:
|
| 312 |
-
logger.info("Fetching patient data...")
|
| 313 |
-
# Get data from API
|
| 314 |
-
data = CALLBACK_MANAGER.get_patient_data()
|
| 315 |
-
logger.info(f"Received patient data: {data[:100]}..." if isinstance(data, str) else "Received non-string data")
|
| 316 |
-
|
| 317 |
-
# Handle case when the data is just an error message
|
| 318 |
-
if data.startswith("Not authenticated") or data.startswith("Failed"):
|
| 319 |
-
logger.warning(f"Authentication issue: {data}")
|
| 320 |
-
processed_data = {
|
| 321 |
-
"has_pagination": False,
|
| 322 |
-
"patients": [],
|
| 323 |
-
"metadata": f"Error: {data}",
|
| 324 |
-
"raw_data": None
|
| 325 |
-
}
|
| 326 |
-
else:
|
| 327 |
-
# Process the results
|
| 328 |
-
try:
|
| 329 |
-
processed_data = update_patient_display(data)
|
| 330 |
-
logger.info("Successfully processed patient display data")
|
| 331 |
-
except Exception as e:
|
| 332 |
-
logger.error(f"Error in update_patient_display: {str(e)}\n{traceback.format_exc()}")
|
| 333 |
-
processed_data = {
|
| 334 |
-
"has_pagination": False,
|
| 335 |
-
"patients": [],
|
| 336 |
-
"metadata": f"Error processing patient data: {str(e)}",
|
| 337 |
-
"raw_data": None
|
| 338 |
-
}
|
| 339 |
-
|
| 340 |
-
# Return the raw JSON and processed data
|
| 341 |
-
return [
|
| 342 |
-
data, # For the raw JSON output
|
| 343 |
-
processed_data["has_pagination"], # Update pagination visibility
|
| 344 |
-
format_patient_html(processed_data["patients"]), # HTML for patients
|
| 345 |
-
processed_data["metadata"], # Metadata text
|
| 346 |
-
processed_data["raw_data"] # State data
|
| 347 |
-
]
|
| 348 |
-
|
| 349 |
-
except Exception as e:
|
| 350 |
-
error_msg = f"Unexpected error fetching patient data: {str(e)}\n{traceback.format_exc()}"
|
| 351 |
-
logger.error(error_msg)
|
| 352 |
-
return [
|
| 353 |
-
f"Error: {str(e)}",
|
| 354 |
-
False,
|
| 355 |
-
"",
|
| 356 |
-
error_msg,
|
| 357 |
-
None
|
| 358 |
-
]
|
| 359 |
-
|
| 360 |
-
def format_patient_html(patients):
|
| 361 |
-
"""Format patient list as HTML for display in markdown component"""
|
| 362 |
-
if not patients:
|
| 363 |
-
return "No patients found."
|
| 364 |
-
|
| 365 |
-
html = ""
|
| 366 |
-
for i, patient in enumerate(patients):
|
| 367 |
-
html += f"""
|
| 368 |
-
<div style="padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; background-color: #f9f9f9;">
|
| 369 |
-
<h3>{patient['name']}</h3>
|
| 370 |
-
<p>{patient['gender']} | Born: {patient['birth_date']}</p>
|
| 371 |
-
<p>{patient['city']}, {patient['state']} {patient['postal_code']}</p>
|
| 372 |
-
<p>ID: {patient['patient_id']}</p>
|
| 373 |
-
<hr/>
|
| 374 |
-
<div style="display: flex; justify-content: space-between;">
|
| 375 |
-
<span>Status: Pending Review</span>
|
| 376 |
-
<button onclick="alert('Documents for patient {patient['patient_id']}')">View Documents</button>
|
| 377 |
-
</div>
|
| 378 |
-
</div>
|
| 379 |
-
"""
|
| 380 |
-
return html
|
| 381 |
-
|
| 382 |
def generate_pdf_from_form(
|
| 383 |
first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
|
| 384 |
doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
|
|
@@ -494,13 +280,13 @@ def generate_pdf_from_meldrx(patient_data):
|
|
| 494 |
except Exception as e:
|
| 495 |
return None, f"Error generating PDF: {str(e)}"
|
| 496 |
|
|
|
|
| 497 |
CALLBACK_MANAGER = CallbackManager(
|
| 498 |
redirect_uri="https://multitransformer-discharge-guard.hf.space/callback",
|
| 499 |
client_secret=None
|
| 500 |
)
|
| 501 |
|
| 502 |
-
|
| 503 |
-
|
| 504 |
with gr.Blocks() as demo:
|
| 505 |
gr.Markdown("# Patient Discharge Form with MeldRx Integration")
|
| 506 |
|
|
@@ -513,7 +299,7 @@ with gr.Blocks() as demo:
|
|
| 513 |
auth_result = gr.Textbox(label="Authentication Result")
|
| 514 |
|
| 515 |
patient_data_button = gr.Button("Fetch Patient Data")
|
| 516 |
-
patient_data_output = gr.Textbox(label="Patient Data")
|
| 517 |
|
| 518 |
# Add button to generate PDF from MeldRx data
|
| 519 |
meldrx_pdf_button = gr.Button("Generate PDF from MeldRx Data")
|
|
@@ -521,26 +307,58 @@ with gr.Blocks() as demo:
|
|
| 521 |
meldrx_pdf_download = gr.File(label="Download Generated PDF")
|
| 522 |
|
| 523 |
auth_submit.click(fn=CALLBACK_MANAGER.set_auth_code, inputs=auth_code_input, outputs=auth_result)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
|
| 525 |
-
with gr.Tab("Show Patients Log"):
|
| 526 |
-
gr.Markdown("## Patient Dashboard")
|
| 527 |
-
|
| 528 |
-
# Store patient data in a state variable
|
| 529 |
-
patient_data_state = gr.State()
|
| 530 |
-
|
| 531 |
-
# Pagination controls
|
| 532 |
-
with gr.Row() as pagination_row:
|
| 533 |
-
prev_btn = gr.Button("Previous Page", visible=False)
|
| 534 |
-
next_btn = gr.Button("Next Page", visible=False)
|
| 535 |
-
|
| 536 |
-
# Replace patient stripes with a single markdown component
|
| 537 |
-
patient_display = gr.HTML("No patient data loaded.")
|
| 538 |
-
|
| 539 |
-
# Metadata display
|
| 540 |
-
metadata_md = gr.Markdown()
|
| 541 |
-
|
| 542 |
-
# Refresh button
|
| 543 |
refresh_btn = gr.Button("Refresh Data")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
|
| 545 |
with gr.Tab("Discharge Form"):
|
| 546 |
gr.Markdown("## Patient Details")
|
|
@@ -622,78 +440,33 @@ with gr.Blocks() as demo:
|
|
| 622 |
outputs=pdf_output
|
| 623 |
)
|
| 624 |
|
| 625 |
-
#
|
| 626 |
-
def fetch_and_display_patients():
|
| 627 |
-
try:
|
| 628 |
-
logger.info("Fetching patient data...")
|
| 629 |
-
# Get data from API
|
| 630 |
-
data = CALLBACK_MANAGER.get_patient_data()
|
| 631 |
-
logger.info(f"Received patient data: {data[:100]}..." if isinstance(data, str) else "Received non-string data")
|
| 632 |
-
|
| 633 |
-
# Handle case when the data is just an error message
|
| 634 |
-
if data.startswith("Not authenticated") or data.startswith("Failed"):
|
| 635 |
-
logger.warning(f"Authentication issue: {data}")
|
| 636 |
-
return [
|
| 637 |
-
data, # For the raw JSON output
|
| 638 |
-
{"visible": False}, # For pagination_row
|
| 639 |
-
[], # For patient_stripes
|
| 640 |
-
{"value": f"Error: {data}"}, # For metadata_md
|
| 641 |
-
None # For patient_data_state
|
| 642 |
-
]
|
| 643 |
-
|
| 644 |
-
# Process the results for UI display
|
| 645 |
-
try:
|
| 646 |
-
pagination_update, stripes_update, metadata_update, state_update = update_patient_display(data)
|
| 647 |
-
logger.info("Successfully processed patient display data")
|
| 648 |
-
|
| 649 |
-
return [
|
| 650 |
-
data, # For the raw JSON output
|
| 651 |
-
pagination_update,
|
| 652 |
-
stripes_update,
|
| 653 |
-
metadata_update,
|
| 654 |
-
state_update
|
| 655 |
-
]
|
| 656 |
-
except Exception as e:
|
| 657 |
-
logger.error(f"Error in update_patient_display: {str(e)}\n{traceback.format_exc()}")
|
| 658 |
-
# Return at least the raw data, even if display processing fails
|
| 659 |
-
return [
|
| 660 |
-
data,
|
| 661 |
-
{"visible": False},
|
| 662 |
-
[],
|
| 663 |
-
{"value": f"Error processing patient data: {str(e)}"},
|
| 664 |
-
None
|
| 665 |
-
]
|
| 666 |
-
|
| 667 |
-
except Exception as e:
|
| 668 |
-
error_msg = f"Unexpected error fetching patient data: {str(e)}\n{traceback.format_exc()}"
|
| 669 |
-
logger.error(error_msg)
|
| 670 |
-
return [
|
| 671 |
-
f"Error: {str(e)}",
|
| 672 |
-
{"visible": False},
|
| 673 |
-
[],
|
| 674 |
-
{"value": error_msg},
|
| 675 |
-
None
|
| 676 |
-
]
|
| 677 |
-
|
| 678 |
-
# Connect the patient data button to both display the raw JSON and update the patient display
|
| 679 |
patient_data_button.click(
|
| 680 |
-
fn=
|
| 681 |
inputs=None,
|
| 682 |
-
outputs=
|
| 683 |
)
|
| 684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
# Add functionality for PDF generation from MeldRx data
|
| 686 |
meldrx_pdf_button.click(
|
| 687 |
fn=generate_pdf_from_meldrx,
|
| 688 |
inputs=patient_data_output,
|
| 689 |
outputs=[meldrx_pdf_download, meldrx_pdf_status]
|
| 690 |
)
|
| 691 |
-
|
| 692 |
-
# Connect
|
| 693 |
-
|
| 694 |
-
fn=
|
| 695 |
inputs=None,
|
| 696 |
-
outputs=
|
| 697 |
)
|
| 698 |
|
| 699 |
-
|
|
|
|
|
|
| 163 |
- Medications: {medications}
|
| 164 |
- Prepared By: {preparer_name}, {preparer_job_title}
|
| 165 |
"""
|
|
|
|
|
|
|
| 166 |
return form
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
def generate_pdf_from_form(
|
| 169 |
first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
|
| 170 |
doctor_first_name, doctor_last_name, doctor_middle_initial, hospital_name, doctor_address,
|
|
|
|
| 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",
|
| 286 |
client_secret=None
|
| 287 |
)
|
| 288 |
|
| 289 |
+
# Create the UI
|
|
|
|
| 290 |
with gr.Blocks() as demo:
|
| 291 |
gr.Markdown("# Patient Discharge Form with MeldRx Integration")
|
| 292 |
|
|
|
|
| 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")
|
|
|
|
| 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:
|
| 338 |
+
# Extract name
|
| 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;">
|
| 350 |
+
<h4>{given} {family}</h4>
|
| 351 |
+
<p><strong>Gender:</strong> {gender}</p>
|
| 352 |
+
<p><strong>Birth Date:</strong> {birth_date}</p>
|
| 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")
|
|
|
|
| 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,
|
| 467 |
inputs=None,
|
| 468 |
+
outputs=dashboard_output
|
| 469 |
)
|
| 470 |
|
| 471 |
+
# Launch with sharing enabled for public access
|
| 472 |
+
demo.launch(share=True)
|