Spaces:
Runtime error
Runtime error
added the new js impl.✅✅
Browse files9 unmodified lines101112131413141516171819202122232425373 unmodified lines39940040139739840240340440140540640740812 unmodified lines4214224234204244254264274284254264294284294304304314324334344354364374384394404414424434444454314324484334344354364374384394404414424434444454464474484494504514524534544554564574504584524534594604614624554564574584594604614634644654664674684694704714724734744754764774784794804814824834654844854864874884894904914924933 unmodified lines49749849947747850050150250350491 unmodified lines5965975985765996006016026036045825835845855865875885895905915925935945955965975985996006016026036046056066076086086096106116126136146156166176186196206216226116126136236246156256266276286196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486336346356496506516526536546386556566576416426586596606616626636646656666676496686696706716726736746756766776786796806816826836846856866876886896906916926936946556566576956966976986606616626636646999 unmodified linesfrom PIL import Imageimport requestsimport tempfile
import gradio as grimport matplotlib.pyplot as pltfrom PIL import Imageimport osimport loggingimport requestsfrom pathlib import Pathfrom typing import Optionalimport gradio as grfrom PIL import Image
# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))373 unmodified lines
def create_interface(): """Create and launch the Gradio interface with all fixes implemented."""
"""Create and launch the Gradio interface with all fixes.""" app = MediSyncApp()
# Example medical report for demo # Example medical report example_report = """ CHEST X-RAY EXAMINATION 12 unmodified lines RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe. """
# Get sample image path with robust error handling # Sample image handling sample_image_path = None try: sample_images_dir = Path(__file__).parent.parent / "data" / "sample" os.makedirs(sample_images_dir, exist_ok=True) # Check for existing images first sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg")) if not sample_images: if sample_images: # Download fallback sample image if none exist fallback_url = "https://raw.githubusercontent.com/ieee8023/covid-chestxray-dataset/master/images/1-s2.0-S0929664620300449-gr2_lrg-a.jpg" sample_path = sample_images_dir / "sample_xray.jpg" try: response = requests.get(fallback_url, timeout=10) if response.status_code == 200: with open(sample_path, 'wb') as f: f.write(response.content) sample_image_path = str(sample_path) logging.info("Successfully downloaded fallback sample image") else: logging.warning(f"Failed to download sample image. Status code: {response.status_code}") except Exception as download_error: logging.warning(f"Could not download sample image: {str(download_error)}") else: sample_image_path = str(sample_images[0]) except Exception as e: logging.error(f"Error setting up sample images: {str(e)}") logger.error(f"Error handling sample images: {e}")
# Custom CSS for styling custom_css = """ .alert-box { padding: 15px; margin: 10px 0; border-radius: 5px; font-family: sans-serif; } .alert-error { background-color: #ffebee; color: #b71c1c; border-left: 5px solid #b71c1c; } .alert-success { background-color: #e8f5e9; color: #1b5e20; border-left: 5px solid #1b5e20; } .fa-icon { margin-right: 8px; } """
# Define interface with robust parameter handling with gr.Blocks( title="MediSync: Multi-Modal Medical Analysis System", theme=gr.themes.Soft() title="MediSync: Multi-Modal Medical Analysis System", theme=gr.themes.Soft(), css=custom_css ) as interface: # Get appointment ID from URL parameters try: from gradio.context import Context appointment_id_value = Context.request.query_params.get("appointment_id", "") if hasattr(Context, 'request') else "" except Exception as e: logging.warning(f"Could not get URL parameters: {str(e)}") appointment_id_value = "" # JavaScript to handle URL parameters js_code = """ function getAppointmentId() { const urlParams = new URLSearchParams(window.location.search); return urlParams.get('appointment_id') || ''; } function setAppointmentId() { const id = getAppointmentId(); if (id) { document.getElementById('appointment-id').value = id; console.log('Appointment ID set:', id); } } window.onload = setAppointmentId; """
# Hidden appointment ID field appointment_id = gr.Textbox( elem_id="appointment-id", visible=False, value=appointment_id_value label="Appointment ID" )
# Initial JS to extract appointment ID interface.load(None, None, None, _js=js_code)
# Main interface layout gr.Markdown(""" # MediSync: Multi-Modal Medical Analysis System 3 unmodified lines ## How to Use 1. Upload a chest X-ray image 2. Enter the corresponding medical report text 3. Choose the analysis type: image-only, text-only, or multimodal (combined) 4. Click "End Consultation" when finished to complete your appointment 3. Choose the analysis type 4. Click "End Consultation" when finished """)
with gr.Tab("Multimodal Analysis"):91 unmodified lines with gr.Row(): with gr.Column(): end_consultation_btn = gr.Button( "End Consultation", "End Consultation", variant="stop", size="lg" ) completion_status = gr.HTML()
# Set up event handlers multi_img_enhance.click( app.enhance_image, inputs=multi_img_input, outputs=multi_img_input ) multi_analyze_btn.click( app.analyze_multimodal, inputs=[multi_img_input, multi_text_input], outputs=[multi_results, multi_plot], )
img_enhance.click(app.enhance_image, inputs=img_input, outputs=img_output) img_analyze_btn.click( app.analyze_image, inputs=img_input, outputs=[img_output, img_results, img_plot], )
text_analyze_btn.click( app.analyze_text, inputs=text_input, outputs=[text_output, text_results, text_plot], )
def complete_consultation(appointment_id): """Handle consultation completion.""" if not appointment_id: return "<div class='alert alert-error'>No appointment ID found. Please contact support.</div>" error_html = """ <div class="alert-box alert-error"> <i class="fas fa-exclamation-triangle fa-icon"></i> <strong>No Appointment ID Found</strong> <p>Your session may not be properly recorded.</p> <p>You will be redirected back to the main page.</p> </div> <script> setTimeout(() => window.location.href = "http://127.0.0.1:600/complete_appointment", 3000); </script> """ logger.error("Completion attempted without appointment ID") return error_html try: # Replace with your actual Flask app URL flask_app_url = "http://127.0.0.1:600/complete_consultation" # Call your Flask endpoint response = requests.post( flask_app_url, "http://127.0.0.1:600/complete_consultation", json={"appointment_id": appointment_id}, timeout=10 ) if response.status_code == 200: return """ <div class='alert alert-success'> Consultation completed successfully. Redirecting... <script> setTimeout(function() { window.location.href = "http://127.0.0.1:600/doctors"; }, 2000); </script>
if response.ok: success_html = """ <div class="alert-box alert-success"> <i class="fas fa-check-circle fa-icon"></i> <strong>Consultation Completed</strong> <p>You will be redirected shortly.</p> </div> <script> setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000); </script> """ logger.info(f"Successfully completed appointment {appointment_id}") return success_html else: error_msg = f"Server error: {response.status_code}" if response.text: error_msg += f" - {response.text[:200]}" logger.error(error_msg) return f""" <div class='alert alert-error'> Error completing appointment (Status: {response.status_code}). Please contact support. <div class="alert-box alert-error"> <i class="fas fa-exclamation-triangle fa-icon"></i> <strong>Error Completing Appointment</strong> <p>{error_msg}</p> </div> """ except Exception as e: logger.error(f"Completion error: {str(e)}") return f""" <div class='alert alert-error'> Error: {str(e)} <div class="alert-box alert-error"> <i class="fas fa-exclamation-triangle fa-icon"></i> <strong>Connection Error</strong> <p>{str(e)}</p> </div> """
end_consultation_btn.click( fn=complete_consultation, inputs=[appointment_id], outputs=completion_status outputs=[completion_status] )
# Set up all your existing analysis handlers here multi_img_enhance.click( app.enhance_image, inputs=multi_img_input, outputs=multi_img_input ) multi_analyze_btn.click( app.analyze_multimodal, inputs=[multi_img_input, multi_text_input], outputs=[multi_results, multi_plot], ) img_enhance.click(app.enhance_image, inputs=img_input, outputs=img_output) img_analyze_btn.click( app.analyze_image, inputs=img_input, outputs=[img_output, img_results, img_plot], ) text_analyze_btn.click( app.analyze_text, inputs=text_input, outputs=[text_output, text_results, text_plot], )
try: interface.launch() except Exception as e: logging.error(f"Failed to launch interface: {str(e)}") raise RuntimeError("Failed to launch MediSync interface") from e
logger.error(f"Failed to launch interface: {str(e)}") raise
if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) create_interface() create_interface()mediSync/app.py+129-94