blackshadow1 commited on
Commit
bec3819
·
verified ·
1 Parent(s): 4bba957

updated code ✅✅

Browse files
Files changed (1) hide show
  1. mediSync/app.py +47 -109
mediSync/app.py CHANGED
@@ -467,22 +467,27 @@ def create_interface():
467
  css=custom_css
468
  ) as interface:
469
 
470
- # Appointment ID handling - simplified approach
471
- appointment_id = gr.Textbox(visible=False)
472
-
473
- # Initialize appointment ID from URL using Gradio's built-in method
 
 
 
474
  def get_appointment_id():
475
  try:
476
  from gradio.context import Context
477
  if hasattr(Context, 'request') and hasattr(Context.request, 'query_params'):
478
- return Context.request.query_params.get("appointment_id", "")
 
 
479
  except Exception as e:
480
  logger.warning(f"Could not get URL parameters: {str(e)}")
481
- return ""
482
-
483
  interface.load(
484
  fn=get_appointment_id,
485
- outputs=[appointment_id]
486
  )
487
 
488
  gr.Markdown("""
@@ -492,154 +497,87 @@ def create_interface():
492
  to provide comprehensive medical insights.
493
  """)
494
 
495
- with gr.Tab("Multimodal Analysis"):
496
- with gr.Row():
497
- with gr.Column():
498
- multi_img_input = gr.Image(label="Upload X-ray Image", type="pil")
499
- multi_img_enhance = gr.Button("Enhance Image")
500
- multi_text_input = gr.Textbox(
501
- label="Enter Medical Report Text",
502
- placeholder="Enter the radiologist's report text here...",
503
- lines=10,
504
- value=example_report if not sample_image_path else None,
505
- )
506
- multi_analyze_btn = gr.Button("Analyze Image & Text", variant="primary")
507
- with gr.Column():
508
- multi_results = gr.HTML(label="Analysis Results")
509
- multi_plot = gr.HTML(label="Visualization")
510
-
511
- if sample_image_path:
512
- gr.Examples(
513
- examples=[[sample_image_path, example_report]],
514
- inputs=[multi_img_input, multi_text_input],
515
- label="Example X-ray and Report",
516
- )
517
-
518
- with gr.Tab("Image Analysis"):
519
- with gr.Row():
520
- with gr.Column():
521
- img_input = gr.Image(label="Upload X-ray Image", type="pil")
522
- img_enhance = gr.Button("Enhance Image")
523
- img_analyze_btn = gr.Button("Analyze Image", variant="primary")
524
- with gr.Column():
525
- img_output = gr.Image(label="Processed Image")
526
- img_results = gr.HTML(label="Analysis Results")
527
- img_plot = gr.HTML(label="Visualization")
528
-
529
- if sample_image_path:
530
- gr.Examples(
531
- examples=[[sample_image_path]],
532
- inputs=[img_input],
533
- label="Example X-ray Image",
534
- )
535
-
536
- with gr.Tab("Text Analysis"):
537
- with gr.Row():
538
- with gr.Column():
539
- text_input = gr.Textbox(
540
- label="Enter Medical Report Text",
541
- placeholder="Enter the radiologist's report text here...",
542
- lines=10,
543
- value=example_report,
544
- )
545
- text_analyze_btn = gr.Button("Analyze Text", variant="primary")
546
- with gr.Column():
547
- text_output = gr.Textbox(label="Processed Text")
548
- text_results = gr.HTML(label="Analysis Results")
549
- text_plot = gr.HTML(label="Entity Visualization")
550
-
551
- gr.Examples(
552
- examples=[[example_report]],
553
- inputs=[text_input],
554
- label="Example Medical Report",
555
- )
556
-
557
- with gr.Tab("About"):
558
- gr.Markdown("""
559
- ## About MediSync
560
-
561
- MediSync is an AI-powered healthcare solution that uses multi-modal analysis to provide comprehensive insights from medical images and reports.
562
- """)
563
 
564
  with gr.Row():
565
  with gr.Column():
566
  end_consultation_btn = gr.Button("End Consultation", variant="stop", size="lg")
567
  completion_status = gr.HTML()
568
 
569
- # Event handlers
570
- multi_img_enhance.click(app.enhance_image, inputs=multi_img_input, outputs=multi_img_input)
571
- multi_analyze_btn.click(
572
- app.analyze_multimodal,
573
- inputs=[multi_img_input, multi_text_input],
574
- outputs=[multi_results, multi_plot],
575
- )
576
- img_enhance.click(app.enhance_image, inputs=img_input, outputs=img_output)
577
- img_analyze_btn.click(
578
- app.analyze_image,
579
- inputs=img_input,
580
- outputs=[img_output, img_results, img_plot],
581
- )
582
- text_analyze_btn.click(
583
- app.analyze_text,
584
- inputs=text_input,
585
- outputs=[text_output, text_results, text_plot],
586
- )
587
-
588
- def complete_consultation(appointment_id):
589
- if not appointment_id:
590
  error_html = """
591
  <div class="alert-box alert-error">
592
  <strong>No Appointment ID Found</strong>
593
- <p>Your session may not be properly recorded.</p>
594
  </div>
595
  """
596
  logger.error("Completion attempted without appointment ID")
597
- return error_html
598
 
599
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600
  response = requests.post(
601
  "http://127.0.0.1:600/complete_consultation",
602
- json={"appointment_id": appointment_id},
603
  timeout=10
604
  )
605
 
606
  if response.ok:
607
  success_html = """
608
  <div class="alert-box alert-success">
609
- <strong>Consultation Completed</strong>
 
610
  <p>You will be redirected shortly.</p>
611
  <script>
612
  setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000);
613
  </script>
614
  </div>
615
  """
616
- logger.info(f"Successfully completed appointment {appointment_id}")
617
- return success_html
 
618
  error_msg = f"Server error: {response.status_code}"
619
  if response.text:
620
  error_msg += f" - {response.text[:200]}"
621
  logger.error(error_msg)
622
- return f"""
623
  <div class="alert-box alert-error">
624
- <strong>Error Completing Appointment</strong>
625
  <p>{error_msg}</p>
 
626
  </div>
627
  """
628
  except Exception as e:
629
  logger.error(f"Completion error: {str(e)}")
630
- return f"""
631
  <div class="alert-box alert-error">
632
  <strong>Connection Error</strong>
633
  <p>{str(e)}</p>
 
634
  </div>
635
  """
636
 
637
  end_consultation_btn.click(
638
  fn=complete_consultation,
639
- inputs=[appointment_id],
640
- outputs=[completion_status]
641
  )
642
-
643
  try:
644
  interface.launch()
645
  except Exception as e:
 
467
  css=custom_css
468
  ) as interface:
469
 
470
+ # Session state to track if consultation was properly recorded
471
+ session_state = gr.State({
472
+ 'recorded': False,
473
+ 'appointment_id': ''
474
+ })
475
+
476
+ # Initialize appointment ID from URL
477
  def get_appointment_id():
478
  try:
479
  from gradio.context import Context
480
  if hasattr(Context, 'request') and hasattr(Context.request, 'query_params'):
481
+ appointment_id = Context.request.query_params.get("appointment_id", "")
482
+ if appointment_id:
483
+ return {'recorded': False, 'appointment_id': appointment_id}
484
  except Exception as e:
485
  logger.warning(f"Could not get URL parameters: {str(e)}")
486
+ return {'recorded': False, 'appointment_id': ''}
487
+
488
  interface.load(
489
  fn=get_appointment_id,
490
+ outputs=[session_state]
491
  )
492
 
493
  gr.Markdown("""
 
497
  to provide comprehensive medical insights.
498
  """)
499
 
500
+ # ... (keep all your existing tabs and components)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
 
502
  with gr.Row():
503
  with gr.Column():
504
  end_consultation_btn = gr.Button("End Consultation", variant="stop", size="lg")
505
  completion_status = gr.HTML()
506
 
507
+ def complete_consultation(session_state):
508
+ """Handle consultation completion with proper session recording."""
509
+ if not session_state['appointment_id']:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  error_html = """
511
  <div class="alert-box alert-error">
512
  <strong>No Appointment ID Found</strong>
513
+ <p>Please contact support to ensure your session is recorded.</p>
514
  </div>
515
  """
516
  logger.error("Completion attempted without appointment ID")
517
+ return {'recorded': False, 'appointment_id': ''}, error_html
518
 
519
  try:
520
+ # First verify if already recorded
521
+ if session_state['recorded']:
522
+ success_html = """
523
+ <div class="alert-box alert-success">
524
+ <strong>Consultation Already Completed</strong>
525
+ <p>You will be redirected shortly.</p>
526
+ <script>
527
+ setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 1000);
528
+ </script>
529
+ </div>
530
+ """
531
+ return session_state, success_html
532
+
533
+ # Call your Flask endpoint to record completion
534
  response = requests.post(
535
  "http://127.0.0.1:600/complete_consultation",
536
+ json={"appointment_id": session_state['appointment_id']},
537
  timeout=10
538
  )
539
 
540
  if response.ok:
541
  success_html = """
542
  <div class="alert-box alert-success">
543
+ <strong>Consultation Successfully Recorded</strong>
544
+ <p>Your session has been properly recorded.</p>
545
  <p>You will be redirected shortly.</p>
546
  <script>
547
  setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000);
548
  </script>
549
  </div>
550
  """
551
+ logger.info(f"Successfully recorded appointment {session_state['appointment_id']}")
552
+ return {'recorded': True, 'appointment_id': session_state['appointment_id']}, success_html
553
+
554
  error_msg = f"Server error: {response.status_code}"
555
  if response.text:
556
  error_msg += f" - {response.text[:200]}"
557
  logger.error(error_msg)
558
+ return session_state, f"""
559
  <div class="alert-box alert-error">
560
+ <strong>Recording Failed</strong>
561
  <p>{error_msg}</p>
562
+ <p>Please try again or contact support.</p>
563
  </div>
564
  """
565
  except Exception as e:
566
  logger.error(f"Completion error: {str(e)}")
567
+ return session_state, f"""
568
  <div class="alert-box alert-error">
569
  <strong>Connection Error</strong>
570
  <p>{str(e)}</p>
571
+ <p>Please check your connection and try again.</p>
572
  </div>
573
  """
574
 
575
  end_consultation_btn.click(
576
  fn=complete_consultation,
577
+ inputs=[session_state],
578
+ outputs=[session_state, completion_status]
579
  )
580
+
581
  try:
582
  interface.launch()
583
  except Exception as e: