Spaces:
Runtime error
Runtime error
updated code✅✅
Browse files398 unmodified lines39940040140240340440540640740840912 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724731 unmodified line4754764774784794804814824834844854861 unmodified line48848949049149249349449549649749849950050150250350450511 unmodified lines51751851952052152252316 unmodified lines54054154254354454554610 unmodified lines5575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056061 unmodified line6086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486491 unmodified line651652653654655656657658659660661662663664665666667668669398 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("""1 unmodified lineThis AI-powered healthcare solution combines X-ray image analysis with patient report text processingto provide comprehensive medical insights.## 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"):1 unmodified linewith gr.Column():multi_img_input = gr.Image(label="Upload X-ray Image", type="pil")multi_img_enhance = gr.Button("Enhance Image")multi_text_input = gr.Textbox(label="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("Analyze Image & Text", variant="primary")with gr.Column():multi_results = gr.HTML(label="Analysis Results")multi_plot = gr.HTML(label="Visualization")11 unmodified linesimg_input = gr.Image(label="Upload X-ray Image", type="pil")img_enhance = gr.Button("Enhance Image")img_analyze_btn = gr.Button("Analyze Image", variant="primary")with gr.Column():img_output = gr.Image(label="Processed Image")img_results = gr.HTML(label="Analysis Results")16 unmodified linesvalue=example_report,)text_analyze_btn = gr.Button("Analyze Text", variant="primary")with gr.Column():text_output = gr.Textbox(label="Processed Text")text_results = gr.HTML(label="Analysis Results")10 unmodified lines## About MediSyncMediSync is an AI-powered healthcare solution that uses multi-modal analysis to provide comprehensive insights from medical images and reports.### Key Features- **X-ray Image Analysis**: Detects abnormalities in chest X-rays using pre-trained vision models- **Medical Report Processing**: Extracts key information from patient reports using NLP models- **Multi-modal Integration**: Combines insights from both image and text data for more accurate analysis### Models Used- **X-ray Analysis**: facebook/deit-base-patch16-224-medical-cxr- **Medical Text Analysis**: medicalai/ClinicalBERT### Important DisclaimerThis 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_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,1 unmodified line)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>"""1 unmodified lineend_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()398 unmodified lines39940040140240340440540640712 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844851 unmodified line4874884894904914921 unmodified line49449549649749849950050150250350450550611 unmodified lines51851952052152252316 unmodified lines54054154254354454510 unmodified lines5565575585595605615625635645655665675685695705715725735745755765775785795801 unmodified line5825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156161 unmodified line618619620621622623624625626627398 unmodified linesdef create_interface():"""Create and launch the Gradio interface."""app = MediSyncApp()example_report = """CHEST X-RAY EXAMINATION12 unmodified linesRECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""sample_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 not sample_images: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)logger.info("Downloaded fallback sample image")except Exception as e:logger.warning(f"Could not download sample image: {str(e)}")else:sample_image_path = str(sample_images[0])except Exception as e:logger.error(f"Error handling sample images: {str(e)}")custom_css = """.alert-box {padding: 15px;margin: 10px 0;border-radius: 5px;}.alert-error {background-color: #ffebee;color: #b71c1c;border-left: 5px solid #b71c1c;}.alert-success {background-color: #e8f5e9;color: #1b5e20;border-left: 5px solid #1b5e20;}"""with gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Soft(),css=custom_css) as interface:appointment_id = gr.Textbox(visible=False)interface.load(None,None,None,_js="""function getAppointmentId() {const urlParams = new URLSearchParams(window.location.search);return urlParams.get('appointment_id') || '';}document.getElementById('appointment-id').value = getAppointmentId();""")gr.Markdown("""1 unmodified lineThis AI-powered healthcare solution combines X-ray image analysis with patient report text processingto provide comprehensive medical insights.""")with gr.Tab("Multimodal Analysis"):1 unmodified linewith gr.Column():multi_img_input = gr.Image(label="Upload X-ray Image", type="pil")multi_img_enhance = gr.Button("Enhance Image")multi_text_input = gr.Textbox(label="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("Analyze Image & Text", variant="primary")with gr.Column():multi_results = gr.HTML(label="Analysis Results")multi_plot = gr.HTML(label="Visualization")11 unmodified linesimg_input = gr.Image(label="Upload X-ray Image", type="pil")img_enhance = gr.Button("Enhance Image")img_analyze_btn = gr.Button("Analyze Image", variant="primary")with gr.Column():img_output = gr.Image(label="Processed Image")img_results = gr.HTML(label="Analysis Results")16 unmodified linesvalue=example_report,)text_analyze_btn = gr.Button("Analyze Text", variant="primary")with gr.Column():text_output = gr.Textbox(label="Processed Text")text_results = gr.HTML(label="Analysis Results")10 unmodified lines## About MediSyncMediSync is an AI-powered healthcare solution that uses multi-modal analysis to provide comprehensive insights from medical images and reports.""")with gr.Row():with gr.Column():end_consultation_btn = gr.Button("End Consultation", variant="stop", size="lg")completion_status = gr.HTML()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,1 unmodified line)def complete_consultation(appointment_id):if not appointment_id:return """<div class="alert-box alert-error">No appointment ID found. Please contact support.</div>"""try:response = requests.post("http://127.0.0.1:600/complete_consultation",json={"appointment_id": appointment_id},timeout=10)if response.status_code == 200:return """<div class="alert-box alert-success">Consultation completed successfully. Redirecting...<script>setTimeout(() => window.location.href = "http://127.0.0.1:600/doctors", 2000);</script></div>"""return f"""<div class="alert-box alert-error">Error completing appointment (Status: {response.status_code}).</div>"""except Exception as e:return f"""<div class="alert-box alert-error">Error: {str(e)}</div>"""1 unmodified lineend_consultation_btn.click(fn=complete_consultation,inputs=[appointment_id],outputs=[completion_status])interface.launch()if __name__ == "__main__":create_interface()
mediSync/app.py+60-102