Spaces:
Runtime error
Runtime error
updated code ✅✅
Browse files448 unmodified lines44945045145245345445515 unmodified lines4714724734744754764774784794804814824834844854864874884894904914924934944 unmodified lines49950050150250350450550650750850951051151251351451551651751813 unmodified lines53253353453553653753820 unmodified lines55956056156256356456511 unmodified lines5775785795805815825835845855865875885895905915925935945955961 unmodified line5985996006016026036046056066076086 unmodified lines615616617618619620621622623624625626448 unmodified lines)def create_interface():"""Create and launch the Gradio interface for Hugging Face Spaces."""app = MediSyncApp()# Example medical report for demo15 unmodified linesRECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Get sample image - simplified for Hugging Face Spacessample_image_path = Nonetry:# Try to use a sample image from the websample_url = "https://raw.githubusercontent.com/ieee8023/covid-chestxray-dataset/master/images/1-s2.0-S0929664620300449-gr2_lrg-a.jpg"response = requests.get(sample_url, timeout=10)if response.status_code == 200:sample_image = Image.open(io.BytesIO(response.content))sample_image_path = sample_imageexcept Exception as e:logging.warning(f"Could not load sample image: {str(e)}")# Define interfacewith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Soft(),css=".alert {padding: 10px; border-radius: 5px;} .alert-error {background-color: #ffebee;} .alert-success {background-color: #e8f5e9;}") 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)4. View the analysis results""")with gr.Tab("Multimodal Analysis"):with gr.Row():with gr.Column():multi_img_input = gr.Image(label="Upload X-ray Image", type="pil")multi_img_enhance = gr.Button("Enhance Image", variant="secondary")multi_text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=example_report,)multi_analyze_btn = gr.Button("Analyze Image & Text", variant="primary")13 unmodified lineswith gr.Row():with gr.Column():img_input = gr.Image(label="Upload X-ray Image", type="pil")img_enhance = gr.Button("Enhance Image", variant="secondary")img_analyze_btn = gr.Button("Analyze Image", variant="primary")with gr.Column():20 unmodified linestext_analyze_btn = gr.Button("Analyze Text", variant="primary")with gr.Column():text_output = gr.Textbox(label="Processed Text", interactive=False)text_results = gr.HTML(label="Analysis Results")text_plot = gr.HTML(label="Entity Visualization")11 unmodified lines### Key Features- **X-ray Image Analysis**: Detects abnormalities in chest X-rays- **Medical Report Processing**: Extracts key information from patient reports- **Multi-modal Integration**: Combines insights from both image and text data### 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.""")# 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,1 unmodified lineoutputs=[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,6 unmodified linesoutputs=[text_output, text_results, text_plot],)# Launch configuration for Hugging Face Spacesinterface.launch(server_name="0.0.0.0",server_port=int(os.getenv("PORT", "7860")),share=False)if __name__ == "__main__":logging.basicConfig(448 unmodified lines44945045145245345445545615 unmodified lines4724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235244 unmodified lines52953053153253353453553653753853954054154254354454554654754854955013 unmodified lines56456556656756856957020 unmodified lines59159259359459559659711 unmodified lines6096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406411 unmodified line6436446456466476486496 unmodified lines656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714448 unmodified lines)def create_interface():"""Create and launch the Gradio interface with all fixes implemented."""app = MediSyncApp()# Example medical report for demo15 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 parameters using JavaScriptappointment_id = gr.Textbox(visible=False,value="",_js="""function() {const params = new URLSearchParams(window.location.search);return params.get('appointment_id') || '';}""")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"):with gr.Row():with 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")13 unmodified lineswith gr.Row():with gr.Column():img_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():20 unmodified linestext_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")text_plot = gr.HTML(label="Entity Visualization")11 unmodified lines### 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,1 unmodified lineoutputs=[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,6 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(
mediSync/app.py+122-34