sanggusti commited on
Commit
30cb096
·
1 Parent(s): 25941bf

Update to connect states of button to update on another tab, let's pray

Browse files
Files changed (1) hide show
  1. callbackmanager.py +115 -63
callbackmanager.py CHANGED
@@ -95,6 +95,13 @@ def display_form(
95
  def process_fhir_bundle(fhir_bundle):
96
  """Extract and structure patient data from FHIR bundle"""
97
  patients = []
 
 
 
 
 
 
 
98
  for entry in fhir_bundle.get("entry", []):
99
  resource = entry.get("resource", {})
100
  if resource.get("resourceType") == "Patient":
@@ -106,7 +113,7 @@ def create_patient_stripe(patient):
106
  # Safely extract name components
107
  official_name = next(
108
  (n for n in patient.get("name", []) if n.get("use") == "official"),
109
- {}
110
  )
111
  given_names = " ".join(official_name.get("given", ["Unknown"]))
112
  family_name = official_name.get("family", "Unknown")
@@ -117,7 +124,7 @@ def create_patient_stripe(patient):
117
  patient_id = patient.get("id", "Unknown")
118
 
119
  # Extract address information
120
- address = patient.get("address", [{}])[0]
121
  city = address.get("city", "Unknown")
122
  state = address.get("state", "")
123
  postal_code = address.get("postalCode", "")
@@ -129,7 +136,7 @@ def create_patient_stripe(patient):
129
  *{gender} | Born: {birth_date}*
130
  {city}, {state} {postal_code}
131
  """)
132
- gr.Textbox(patient_id, label="Patient ID", visible=False)
133
 
134
  with gr.Column(scale=1):
135
  status = gr.Dropdown(
@@ -142,6 +149,8 @@ def create_patient_stripe(patient):
142
  generate_btn = gr.Button("Generate Report", visible=False)
143
  probability = gr.Label("Risk Probability", visible=False)
144
  documents_btn = gr.Button("View Documents", visible=True)
 
 
145
 
146
  # Dynamic visibility and document handling
147
  def update_components(selected_status):
@@ -152,7 +161,8 @@ def create_patient_stripe(patient):
152
  )
153
 
154
  def show_documents(patient_id):
155
- return CALLBACK_MANAGER.get_patient_documents(patient_id)
 
156
 
157
  status.change(
158
  update_components,
@@ -162,12 +172,69 @@ def create_patient_stripe(patient):
162
 
163
  documents_btn.click(
164
  fn=show_documents,
165
- inputs=patient_id,
166
- outputs=gr.JSON(label="Patient Documents")
167
  )
168
 
169
  return stripe
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  def generate_pdf_from_form(
173
  first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
@@ -289,6 +356,8 @@ CALLBACK_MANAGER = CallbackManager(
289
  client_secret=None
290
  )
291
 
 
 
292
  with gr.Blocks() as demo:
293
  gr.Markdown("# Patient Discharge Form with MeldRx Integration")
294
 
@@ -309,25 +378,17 @@ with gr.Blocks() as demo:
309
  meldrx_pdf_download = gr.File(label="Download Generated PDF")
310
 
311
  auth_submit.click(fn=CALLBACK_MANAGER.set_auth_code, inputs=auth_code_input, outputs=auth_result)
312
- patient_data_button.click(fn=CALLBACK_MANAGER.get_patient_data, inputs=None, outputs=patient_data_output)
313
 
314
- # Add functionality for PDF generation from MeldRx data
315
- meldrx_pdf_button.click(
316
- fn=generate_pdf_from_meldrx,
317
- inputs=patient_data_output,
318
- outputs=[meldrx_pdf_download, meldrx_pdf_status]
319
- )
320
-
321
  with gr.Tab("Show Patients Log"):
322
  gr.Markdown("## Patient Dashboard")
323
 
324
  # Store patient data in a state variable
325
  patient_data_state = gr.State()
326
 
327
- # Pagination controls
328
- with gr.Row() as pagination_row:
329
- prev_btn = gr.Button("Previous Page", visible=False)
330
- next_btn = gr.Button("Next Page", visible=False)
331
 
332
  # Patient stripes container
333
  patient_stripes = gr.Column()
@@ -337,51 +398,6 @@ with gr.Blocks() as demo:
337
 
338
  # Refresh button
339
  refresh_btn = gr.Button("Refresh Data")
340
-
341
- def update_patient_display(patient_data_json):
342
- try:
343
- fhir_bundle = json.loads(patient_data_json)
344
- patients = process_fhir_bundle(fhir_bundle)
345
-
346
- # Update pagination controls
347
- has_prev = any(link["relation"] == "previous" for link in fhir_bundle.get("link", []))
348
- has_next = any(link["relation"] == "next" for link in fhir_bundle.get("link", []))
349
-
350
- # Create stripes
351
- stripes = []
352
- for patient in patients:
353
- stripes.append(create_patient_stripe(patient))
354
-
355
- return (
356
- gr.Row.update(visible=has_prev or has_next),
357
- gr.Column.update(stripes),
358
- gr.Markdown.update(value=f"""
359
- **Bundle Metadata**
360
- Type: {fhir_bundle.get('type', 'Unknown')}
361
- Total Patients: {fhir_bundle.get('total', 0)}
362
- Last Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
363
- """),
364
- {"patients": patients, "bundle": fhir_bundle}
365
- )
366
- except Exception as e:
367
- return (
368
- gr.Row.update(visible=False),
369
- gr.Column.update([]),
370
- gr.Markdown.update(value=f"Error loading patient data: {str(e)}"),
371
- None
372
- )
373
-
374
- # Connect data flow
375
- patient_data_output.change(
376
- fn=update_patient_display,
377
- inputs=patient_data_output,
378
- outputs=[pagination_row, patient_stripes, metadata_md, patient_data_state]
379
- )
380
-
381
- refresh_btn.click(
382
- fn=lambda: CALLBACK_MANAGER.get_patient_data(),
383
- outputs=patient_data_output
384
- )
385
 
386
  with gr.Tab("Discharge Form"):
387
  gr.Markdown("## Patient Details")
@@ -462,5 +478,41 @@ with gr.Blocks() as demo:
462
  ],
463
  outputs=pdf_output
464
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
  demo.launch()
 
95
  def process_fhir_bundle(fhir_bundle):
96
  """Extract and structure patient data from FHIR bundle"""
97
  patients = []
98
+ if not isinstance(fhir_bundle, dict):
99
+ # Try to parse the data if it's a string
100
+ try:
101
+ fhir_bundle = json.loads(fhir_bundle)
102
+ except:
103
+ return []
104
+
105
  for entry in fhir_bundle.get("entry", []):
106
  resource = entry.get("resource", {})
107
  if resource.get("resourceType") == "Patient":
 
113
  # Safely extract name components
114
  official_name = next(
115
  (n for n in patient.get("name", []) if n.get("use") == "official"),
116
+ next((n for n in patient.get("name", [])), {}) # Fallback to first name if no official
117
  )
118
  given_names = " ".join(official_name.get("given", ["Unknown"]))
119
  family_name = official_name.get("family", "Unknown")
 
124
  patient_id = patient.get("id", "Unknown")
125
 
126
  # Extract address information
127
+ address = patient.get("address", [{}])[0] if patient.get("address") else {}
128
  city = address.get("city", "Unknown")
129
  state = address.get("state", "")
130
  postal_code = address.get("postalCode", "")
 
136
  *{gender} | Born: {birth_date}*
137
  {city}, {state} {postal_code}
138
  """)
139
+ patient_id_box = gr.Textbox(patient_id, label="Patient ID", visible=False)
140
 
141
  with gr.Column(scale=1):
142
  status = gr.Dropdown(
 
149
  generate_btn = gr.Button("Generate Report", visible=False)
150
  probability = gr.Label("Risk Probability", visible=False)
151
  documents_btn = gr.Button("View Documents", visible=True)
152
+
153
+ doc_output = gr.JSON(label="Patient Documents", visible=False)
154
 
155
  # Dynamic visibility and document handling
156
  def update_components(selected_status):
 
161
  )
162
 
163
  def show_documents(patient_id):
164
+ docs = CALLBACK_MANAGER.get_patient_documents(patient_id)
165
+ return gr.JSON.update(value=docs, visible=True)
166
 
167
  status.change(
168
  update_components,
 
172
 
173
  documents_btn.click(
174
  fn=show_documents,
175
+ inputs=patient_id_box,
176
+ outputs=doc_output
177
  )
178
 
179
  return stripe
180
 
181
+ def update_patient_display(patient_data_json):
182
+ """
183
+ Update the patient display with parsed FHIR data
184
+
185
+ Args:
186
+ patient_data_json: JSON string of FHIR patient data
187
+
188
+ Returns:
189
+ Tuple of updates for the UI components
190
+ """
191
+ try:
192
+ # Handle the case where patient_data_json is an error message
193
+ if patient_data_json.startswith("Not authenticated") or patient_data_json.startswith("Failed"):
194
+ return (
195
+ gr.Row.update(visible=False),
196
+ gr.Column.update([]),
197
+ gr.Markdown.update(value=f"Error: {patient_data_json}"),
198
+ None
199
+ )
200
+
201
+ fhir_bundle = json.loads(patient_data_json) if isinstance(patient_data_json, str) else patient_data_json
202
+ patients = process_fhir_bundle(fhir_bundle)
203
+
204
+ if not patients:
205
+ return (
206
+ gr.Row.update(visible=False),
207
+ gr.Column.update([]),
208
+ gr.Markdown.update(value="No patients found in the data"),
209
+ None
210
+ )
211
+
212
+ # Update pagination controls
213
+ has_prev = any(link.get("relation") == "previous" for link in fhir_bundle.get("link", []))
214
+ has_next = any(link.get("relation") == "next" for link in fhir_bundle.get("link", []))
215
+
216
+ # Create stripes
217
+ stripes = [create_patient_stripe(patient) for patient in patients]
218
+
219
+ return (
220
+ gr.Row.update(visible=has_prev or has_next),
221
+ gr.Column.update(value=stripes),
222
+ gr.Markdown.update(value=f"""
223
+ **Bundle Metadata**
224
+ Type: {fhir_bundle.get('type', 'Unknown')}
225
+ Total Patients: {fhir_bundle.get('total', len(patients))}
226
+ Last Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
227
+ """),
228
+ {"patients": patients, "bundle": fhir_bundle}
229
+ )
230
+ except Exception as e:
231
+ import traceback
232
+ return (
233
+ gr.Row.update(visible=False),
234
+ gr.Column.update([]),
235
+ gr.Markdown.update(value=f"Error loading patient data: {str(e)}\n{traceback.format_exc()}"),
236
+ None
237
+ )
238
 
239
  def generate_pdf_from_form(
240
  first_name, last_name, middle_initial, dob, age, sex, address, city, state, zip_code,
 
356
  client_secret=None
357
  )
358
 
359
+
360
+
361
  with gr.Blocks() as demo:
362
  gr.Markdown("# Patient Discharge Form with MeldRx Integration")
363
 
 
378
  meldrx_pdf_download = gr.File(label="Download Generated PDF")
379
 
380
  auth_submit.click(fn=CALLBACK_MANAGER.set_auth_code, inputs=auth_code_input, outputs=auth_result)
 
381
 
 
 
 
 
 
 
 
382
  with gr.Tab("Show Patients Log"):
383
  gr.Markdown("## Patient Dashboard")
384
 
385
  # Store patient data in a state variable
386
  patient_data_state = gr.State()
387
 
388
+ # Pagination controls
389
+ with gr.Row(visible=False) as pagination_row:
390
+ prev_btn = gr.Button("Previous Page")
391
+ next_btn = gr.Button("Next Page")
392
 
393
  # Patient stripes container
394
  patient_stripes = gr.Column()
 
398
 
399
  # Refresh button
400
  refresh_btn = gr.Button("Refresh Data")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
  with gr.Tab("Discharge Form"):
403
  gr.Markdown("## Patient Details")
 
478
  ],
479
  outputs=pdf_output
480
  )
481
+
482
+ # Define a function to handle fetching and displaying patients
483
+ def fetch_and_display_patients():
484
+ data = CALLBACK_MANAGER.get_patient_data()
485
+
486
+ # Process the results for UI display
487
+ pagination_update, stripes_update, metadata_update, state_update = update_patient_display(data)
488
+
489
+ return [
490
+ data, # For the raw JSON output
491
+ pagination_update,
492
+ stripes_update,
493
+ metadata_update,
494
+ state_update
495
+ ]
496
+
497
+ # Connect the patient data button to both display the raw JSON and update the patient display
498
+ patient_data_button.click(
499
+ fn=fetch_and_display_patients,
500
+ inputs=None,
501
+ outputs=[patient_data_output, pagination_row, patient_stripes, metadata_md, patient_data_state]
502
+ )
503
+
504
+ # Add functionality for PDF generation from MeldRx data
505
+ meldrx_pdf_button.click(
506
+ fn=generate_pdf_from_meldrx,
507
+ inputs=patient_data_output,
508
+ outputs=[meldrx_pdf_download, meldrx_pdf_status]
509
+ )
510
+
511
+ # Connect refresh button in patient log tab
512
+ refresh_btn.click(
513
+ fn=fetch_and_display_patients,
514
+ inputs=None,
515
+ outputs=[patient_data_output, pagination_row, patient_stripes, metadata_md, patient_data_state]
516
+ )
517
 
518
  demo.launch()