blackshadow1 commited on
Commit
bf6b28e
·
verified ·
1 Parent(s): ce6b5b4

Added the new code imp✅✅

Browse files
Files changed (1) hide show
  1. mediSync/app.py +123 -19
mediSync/app.py CHANGED
@@ -3,6 +3,14 @@ import os
3
  import sys
4
  import tempfile
5
  from pathlib import Path
 
 
 
 
 
 
 
 
6
 
7
  import gradio as gr
8
  import matplotlib.pyplot as plt
@@ -386,7 +394,7 @@ class MediSyncApp:
386
 
387
 
388
  def create_interface():
389
- """Create and launch the Gradio interface."""
390
 
391
  app = MediSyncApp()
392
 
@@ -409,20 +417,54 @@ def create_interface():
409
  RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe.
410
  """
411
 
412
- # Get sample image path if available
413
- sample_images_dir = Path(parent_dir) / "data" / "sample"
414
- sample_images = list(sample_images_dir.glob("*.png")) + list(
415
- sample_images_dir.glob("*.jpg")
416
- )
417
-
418
  sample_image_path = None
419
- if sample_images:
420
- sample_image_path = str(sample_images[0])
421
-
422
- # Define interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  with gr.Blocks(
424
- title="MediSync: Multi-Modal Medical Analysis System", theme=gr.themes.Soft()
 
425
  ) as interface:
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  gr.Markdown("""
427
  # MediSync: Multi-Modal Medical Analysis System
428
 
@@ -433,6 +475,7 @@ def create_interface():
433
  1. Upload a chest X-ray image
434
  2. Enter the corresponding medical report text
435
  3. Choose the analysis type: image-only, text-only, or multimodal (combined)
 
436
  """)
437
 
438
  with gr.Tab("Multimodal Analysis"):
@@ -445,7 +488,7 @@ def create_interface():
445
  label="Enter Medical Report Text",
446
  placeholder="Enter the radiologist's report text here...",
447
  lines=10,
448
- value=example_report if sample_image_path is None else None,
449
  )
450
 
451
  multi_analyze_btn = gr.Button(
@@ -456,7 +499,6 @@ def create_interface():
456
  multi_results = gr.HTML(label="Analysis Results")
457
  multi_plot = gr.HTML(label="Visualization")
458
 
459
- # Set up examples if sample image exists
460
  if sample_image_path:
461
  gr.Examples(
462
  examples=[[sample_image_path, example_report]],
@@ -476,7 +518,6 @@ def create_interface():
476
  img_results = gr.HTML(label="Analysis Results")
477
  img_plot = gr.HTML(label="Visualization")
478
 
479
- # Set up example if sample image exists
480
  if sample_image_path:
481
  gr.Examples(
482
  examples=[[sample_image_path]],
@@ -500,7 +541,6 @@ def create_interface():
500
  text_results = gr.HTML(label="Analysis Results")
501
  text_plot = gr.HTML(label="Entity Visualization")
502
 
503
- # Set up example
504
  gr.Examples(
505
  examples=[[example_report]],
506
  inputs=[text_input],
@@ -529,6 +569,16 @@ def create_interface():
529
  This tool is for educational and research purposes only. It is not intended to provide medical advice or replace professional healthcare. Always consult with qualified healthcare providers for medical decisions.
530
  """)
531
 
 
 
 
 
 
 
 
 
 
 
532
  # Set up event handlers
533
  multi_img_enhance.click(
534
  app.enhance_image, inputs=multi_img_input, outputs=multi_img_input
@@ -552,9 +602,63 @@ def create_interface():
552
  outputs=[text_output, text_results, text_plot],
553
  )
554
 
555
- # Run the interface
556
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
 
558
 
559
  if __name__ == "__main__":
560
- create_interface()
 
 
 
 
 
3
  import sys
4
  import tempfile
5
  from pathlib import Path
6
+ import os
7
+ import logging
8
+ from pathlib import Path
9
+ import gradio as gr
10
+ from PIL import Image
11
+ import requests
12
+ import tempfile
13
+
14
 
15
  import gradio as gr
16
  import matplotlib.pyplot as plt
 
394
 
395
 
396
  def create_interface():
397
+ """Create and launch the Gradio interface with all fixes implemented."""
398
 
399
  app = MediSyncApp()
400
 
 
417
  RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe.
418
  """
419
 
420
+ # Get sample image path with robust error handling
 
 
 
 
 
421
  sample_image_path = None
422
+ try:
423
+ sample_images_dir = Path(__file__).parent.parent / "data" / "sample"
424
+ os.makedirs(sample_images_dir, exist_ok=True)
425
+
426
+ # Check for existing images first
427
+ sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))
428
+
429
+ if not sample_images:
430
+ # Download fallback sample image if none exist
431
+ fallback_url = "https://raw.githubusercontent.com/ieee8023/covid-chestxray-dataset/master/images/1-s2.0-S0929664620300449-gr2_lrg-a.jpg"
432
+ sample_path = sample_images_dir / "sample_xray.jpg"
433
+
434
+ try:
435
+ response = requests.get(fallback_url, timeout=10)
436
+ if response.status_code == 200:
437
+ with open(sample_path, 'wb') as f:
438
+ f.write(response.content)
439
+ sample_image_path = str(sample_path)
440
+ logging.info("Successfully downloaded fallback sample image")
441
+ else:
442
+ logging.warning(f"Failed to download sample image. Status code: {response.status_code}")
443
+ except Exception as download_error:
444
+ logging.warning(f"Could not download sample image: {str(download_error)}")
445
+ else:
446
+ sample_image_path = str(sample_images[0])
447
+ except Exception as e:
448
+ logging.error(f"Error setting up sample images: {str(e)}")
449
+
450
+ # Define interface with robust parameter handling
451
  with gr.Blocks(
452
+ title="MediSync: Multi-Modal Medical Analysis System",
453
+ theme=gr.themes.Soft()
454
  ) as interface:
455
+ # Get appointment ID from URL parameters
456
+ try:
457
+ from gradio.context import Context
458
+ appointment_id_value = Context.request.query_params.get("appointment_id", "") if hasattr(Context, 'request') else ""
459
+ except Exception as e:
460
+ logging.warning(f"Could not get URL parameters: {str(e)}")
461
+ appointment_id_value = ""
462
+
463
+ appointment_id = gr.Textbox(
464
+ visible=False,
465
+ value=appointment_id_value
466
+ )
467
+
468
  gr.Markdown("""
469
  # MediSync: Multi-Modal Medical Analysis System
470
 
 
475
  1. Upload a chest X-ray image
476
  2. Enter the corresponding medical report text
477
  3. Choose the analysis type: image-only, text-only, or multimodal (combined)
478
+ 4. Click "End Consultation" when finished to complete your appointment
479
  """)
480
 
481
  with gr.Tab("Multimodal Analysis"):
 
488
  label="Enter Medical Report Text",
489
  placeholder="Enter the radiologist's report text here...",
490
  lines=10,
491
+ value=example_report if not sample_image_path else None,
492
  )
493
 
494
  multi_analyze_btn = gr.Button(
 
499
  multi_results = gr.HTML(label="Analysis Results")
500
  multi_plot = gr.HTML(label="Visualization")
501
 
 
502
  if sample_image_path:
503
  gr.Examples(
504
  examples=[[sample_image_path, example_report]],
 
518
  img_results = gr.HTML(label="Analysis Results")
519
  img_plot = gr.HTML(label="Visualization")
520
 
 
521
  if sample_image_path:
522
  gr.Examples(
523
  examples=[[sample_image_path]],
 
541
  text_results = gr.HTML(label="Analysis Results")
542
  text_plot = gr.HTML(label="Entity Visualization")
543
 
 
544
  gr.Examples(
545
  examples=[[example_report]],
546
  inputs=[text_input],
 
569
  This tool is for educational and research purposes only. It is not intended to provide medical advice or replace professional healthcare. Always consult with qualified healthcare providers for medical decisions.
570
  """)
571
 
572
+ # Consultation completion section
573
+ with gr.Row():
574
+ with gr.Column():
575
+ end_consultation_btn = gr.Button(
576
+ "End Consultation",
577
+ variant="stop",
578
+ size="lg"
579
+ )
580
+ completion_status = gr.HTML()
581
+
582
  # Set up event handlers
583
  multi_img_enhance.click(
584
  app.enhance_image, inputs=multi_img_input, outputs=multi_img_input
 
602
  outputs=[text_output, text_results, text_plot],
603
  )
604
 
605
+ def complete_consultation(appointment_id):
606
+ """Handle consultation completion."""
607
+ if not appointment_id:
608
+ return "<div class='alert alert-error'>No appointment ID found. Please contact support.</div>"
609
+
610
+ try:
611
+ # Replace with your actual Flask app URL
612
+ flask_app_url = "http://127.0.0.1:600/complete_consultation"
613
+
614
+ response = requests.post(
615
+ flask_app_url,
616
+ json={"appointment_id": appointment_id},
617
+ timeout=10
618
+ )
619
+
620
+ if response.status_code == 200:
621
+ return """
622
+ <div class='alert alert-success'>
623
+ Consultation completed successfully. Redirecting...
624
+ <script>
625
+ setTimeout(function() {
626
+ window.location.href = "http://127.0.0.1:600/doctors";
627
+ }, 2000);
628
+ </script>
629
+ </div>
630
+ """
631
+ else:
632
+ return f"""
633
+ <div class='alert alert-error'>
634
+ Error completing appointment (Status: {response.status_code}).
635
+ Please contact support.
636
+ </div>
637
+ """
638
+
639
+ except Exception as e:
640
+ return f"""
641
+ <div class='alert alert-error'>
642
+ Error: {str(e)}
643
+ </div>
644
+ """
645
+
646
+ end_consultation_btn.click(
647
+ fn=complete_consultation,
648
+ inputs=[appointment_id],
649
+ outputs=completion_status
650
+ )
651
+
652
+ try:
653
+ interface.launch()
654
+ except Exception as e:
655
+ logging.error(f"Failed to launch interface: {str(e)}")
656
+ raise RuntimeError("Failed to launch MediSync interface") from e
657
 
658
 
659
  if __name__ == "__main__":
660
+ logging.basicConfig(
661
+ level=logging.INFO,
662
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
663
+ )
664
+ create_interface()