Spaces:
Runtime error
Runtime error
added the new js impl.✅✅
Browse files9 unmodified lines1011121314151617181920373 unmodified lines39439539639739839940040140240340412 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694703 unmodified lines47447547647747847948048191 unmodified lines5735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636649 unmodified linesfrom PIL import Imageimport requestsimport tempfileimport gradio as grimport matplotlib.pyplot as pltfrom PIL import Image# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))373 unmodified linesdef create_interface():"""Create and launch the Gradio interface with all fixes implemented."""app = MediSyncApp()# Example medical report for demoexample_report = """CHEST X-RAY EXAMINATION12 unmodified linesRECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Get sample image path with robust error handlingsample_image_path = Nonetry:sample_images_dir = Path(__file__).parent.parent / "data" / "sample"os.makedirs(sample_images_dir, exist_ok=True)# Check for existing images firstsample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))if not sample_images:# Download fallback sample image if none existfallback_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)}")# Define interface with robust parameter handlingwith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Soft()) as interface:# Get appointment ID from URL parameterstry:from gradio.context import Contextappointment_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 = ""appointment_id = gr.Textbox(visible=False,value=appointment_id_value)gr.Markdown("""# MediSync: Multi-Modal Medical Analysis System3 unmodified lines## How to Use1. Upload a chest X-ray image2. Enter the corresponding medical report text3. Choose the analysis type: image-only, text-only, or multimodal (combined)4. Click "End Consultation" when finished to complete your appointment""")with gr.Tab("Multimodal Analysis"):91 unmodified lineswith gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation",variant="stop",size="lg")completion_status = gr.HTML()# Set up event handlersmulti_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>"try:# Replace with your actual Flask app URLflask_app_url = "http://127.0.0.1:600/complete_consultation"response = requests.post(flask_app_url,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></div>"""else:return f"""<div class='alert alert-error'>Error completing appointment (Status: {response.status_code}).Please contact support.</div>"""except Exception as e:return f"""<div class='alert alert-error'>Error: {str(e)}</div>"""end_consultation_btn.click(fn=complete_consultation,inputs=[appointment_id],outputs=completion_status)try:interface.launch()except Exception as e:logging.error(f"Failed to launch interface: {str(e)}")raise RuntimeError("Failed to launch MediSync interface") from eif __name__ == "__main__":logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')create_interface()9 unmodified lines10111213141516171819202122232425373 unmodified lines39940040140240340440540640740812 unmodified lines4214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924933 unmodified lines49749849950050150250350491 unmodified lines5965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986999 unmodified linesfrom PIL import Imageimport requestsimport tempfileimport 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 linesdef create_interface():"""Create and launch the Gradio interface with all fixes."""app = MediSyncApp()# Example medical reportexample_report = """CHEST X-RAY EXAMINATION12 unmodified linesRECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Sample image handlingsample_image_path = Nonetry:sample_images_dir = Path(__file__).parent.parent / "data" / "sample"os.makedirs(sample_images_dir, exist_ok=True)sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))if sample_images:sample_image_path = str(sample_images[0])except Exception as e:logger.error(f"Error handling sample images: {e}")# Custom CSS for stylingcustom_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;}"""with gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Soft(),css=custom_css) as interface:# JavaScript to handle URL parametersjs_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 fieldappointment_id = gr.Textbox(elem_id="appointment-id",visible=False,label="Appointment ID")# Initial JS to extract appointment IDinterface.load(None, None, None, _js=js_code)# Main interface layoutgr.Markdown("""# MediSync: Multi-Modal Medical Analysis System3 unmodified lines## How to Use1. Upload a chest X-ray image2. Enter the corresponding medical report text3. Choose the analysis type4. Click "End Consultation" when finished""")with gr.Tab("Multimodal Analysis"):91 unmodified lineswith gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation",variant="stop",size="lg")completion_status = gr.HTML()def complete_consultation(appointment_id):"""Handle consultation completion."""if not appointment_id: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_htmltry:# Call your Flask endpointresponse = requests.post("http://127.0.0.1:600/complete_consultation",json={"appointment_id": appointment_id},timeout=10)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_htmlelse: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-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-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])# Set up all your existing analysis handlers heremulti_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:logger.error(f"Failed to launch interface: {str(e)}")raiseif __name__ == "__main__":create_interface()
mediSync/app.py+129-94