Spaces:
Runtime error
Runtime error
Added the new code imp✅✅
Browse files2 unmodified lines345678377 unmodified lines38638738838939039139216 unmodified lines4094104114124134144154164174184194204214224234244254264274284 unmodified lines4334344354364374386 unmodified lines4454464474484494504514 unmodified lines45645745845946046146213 unmodified lines47647747847948048148217 unmodified lines50050150250350450550622 unmodified lines52953053153253353417 unmodified lines5525535545555565575585595602 unmodified linesimport sysimport tempfilefrom pathlib import Pathimport gradio as grimport matplotlib.pyplot as plt377 unmodified linesdef create_interface():"""Create and launch the Gradio interface."""app = MediSyncApp()16 unmodified linesRECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Get sample image path if availablesample_images_dir = Path(parent_dir) / "data" / "sample"sample_images = list(sample_images_dir.glob("*.png")) + list(sample_images_dir.glob("*.jpg"))sample_image_path = Noneif sample_images:sample_image_path = str(sample_images[0])# Define interfacewith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System", theme=gr.themes.Soft()) as interface:gr.Markdown("""# MediSync: Multi-Modal Medical Analysis System4 unmodified lines1. Upload a chest X-ray image2. Enter the corresponding medical report text3. Choose the analysis type: image-only, text-only, or multimodal (combined)""")with gr.Tab("Multimodal Analysis"):6 unmodified lineslabel="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=example_report if sample_image_path is None else None,)multi_analyze_btn = gr.Button(4 unmodified linesmulti_results = gr.HTML(label="Analysis Results")multi_plot = gr.HTML(label="Visualization")# Set up examples if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],13 unmodified linesimg_results = gr.HTML(label="Analysis Results")img_plot = gr.HTML(label="Visualization")# Set up example if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path]],17 unmodified linestext_results = gr.HTML(label="Analysis Results")text_plot = gr.HTML(label="Entity Visualization")# Set up examplegr.Examples(examples=[[example_report]],inputs=[text_input],22 unmodified linesThis 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.""")# Set up event handlersmulti_img_enhance.click(app.enhance_image, inputs=multi_img_input, outputs=multi_img_input17 unmodified linesoutputs=[text_output, text_results, text_plot],)# Run the interfaceinterface.launch()if __name__ == "__main__":create_interface()2 unmodified lines345678910111213141516377 unmodified lines39439539639739839940016 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704 unmodified lines4754764774784794804816 unmodified lines4884894904914924934944 unmodified lines49950050150250350413 unmodified lines51851952052152252317 unmodified lines54154254354454554622 unmodified lines56957057157257357457557657757857958058158258358417 unmodified lines6026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636642 unmodified linesimport sysimport tempfilefrom pathlib import Pathimport osimport loggingfrom pathlib import Pathimport gradio as grfrom PIL import Imageimport requestsimport tempfileimport gradio as grimport matplotlib.pyplot as plt377 unmodified linesdef create_interface():"""Create and launch the Gradio interface with all fixes implemented."""app = MediSyncApp()16 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 System4 unmodified lines1. 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"):6 unmodified lineslabel="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=example_report if not sample_image_path else None,)multi_analyze_btn = gr.Button(4 unmodified linesmulti_results = gr.HTML(label="Analysis Results")multi_plot = gr.HTML(label="Visualization")if sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],13 unmodified linesimg_results = gr.HTML(label="Analysis Results")img_plot = gr.HTML(label="Visualization")if sample_image_path:gr.Examples(examples=[[sample_image_path]],17 unmodified linestext_results = gr.HTML(label="Analysis Results")text_plot = gr.HTML(label="Entity Visualization")gr.Examples(examples=[[example_report]],inputs=[text_input],22 unmodified linesThis 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.""")# Consultation completion sectionwith 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_input17 unmodified linesoutputs=[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()
mediSync/app.py+123-19