Spaces:
Runtime error
Runtime error
Update mediSync/app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560import loggingimport osimport sysimport tempfilefrom pathlib import Pathimport gradio as grimport matplotlib.pyplot as pltfrom PIL import Image# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))sys.path.append(parent_dir)# Import our modulesfrom models.multimodal_fusion import MultimodalFusionfrom utils.preprocessing import enhance_xray_image, normalize_report_textfrom utils.visualization import (plot_image_prediction,plot_multimodal_results,plot_report_entities,)# Set up logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",handlers=[logging.StreamHandler(), logging.FileHandler("mediSync.log")],)logger = logging.getLogger(__name__)# Create temporary directory for sample data if it doesn't existos.makedirs(os.path.join(parent_dir, "data", "sample"), exist_ok=True)class MediSyncApp:"""Main application class for the MediSync multi-modal medical analysis system."""def __init__(self):"""Initialize the application and load models."""self.logger = logging.getLogger(__name__)self.logger.info("Initializing MediSync application")# Initialize models with None for lazy loadingself.fusion_model = Noneself.image_model = Noneself.text_model = Nonedef load_models(self):"""Load models if not already loaded.Returns:bool: True if models loaded successfully, False otherwise"""try:if self.fusion_model is None:self.logger.info("Loading models...")self.fusion_model = MultimodalFusion()self.image_model = self.fusion_model.image_analyzerself.text_model = self.fusion_model.text_analyzerself.logger.info("Models loaded successfully")return Trueexcept Exception as e:self.logger.error(f"Error loading models: {e}")return Falsedef analyze_image(self, image):"""Analyze a medical image.Args:image: Image file uploaded through GradioReturns:tuple: (image, image_results_html, plot_as_html)"""try:# Ensure models are loadedif not self.load_models() or self.image_model is None:return image, "Error: Models not loaded properly.", None# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Run image analysisself.logger.info(f"Analyzing image: {temp_path}")results = self.image_model.analyze(temp_path)# Create visualizationfig = plot_image_prediction(image,results.get("predictions", []),f"Primary Finding: {results.get('primary_finding', 'Unknown')}",)# Convert to HTML for displayplot_html = self.fig_to_html(fig)# Format results as HTMLhtml_result = f"""<h2>X-ray Analysis Results</h2><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Confidence:</strong> {results.get("confidence", 0):.1%}</p><p><strong>Abnormality Detected:</strong> {"Yes" if results.get("has_abnormality", False) else "No"}</p><h3>Top Predictions:</h3><ul>"""# Add top 5 predictionsfor label, prob in results.get("predictions", [])[:5]:html_result += f"<li>{label}: {prob:.1%}</li>"html_result += "</ul>"# Add explanationexplanation = self.image_model.get_explanation(results)html_result += f"<h3>Analysis Explanation:</h3><p>{explanation}</p>"return image, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in image analysis: {e}")return image, f"Error analyzing image: {str(e)}", Nonedef analyze_text(self, text):"""Analyze a medical report text.Args:text: Report text input through GradioReturns:tuple: (text, text_results_html, entities_plot_html)"""try:# Ensure models are loadedif not self.load_models() or self.text_model is None:return text, "Error: Models not loaded properly.", None# Check for empty textif not text or len(text.strip()) < 10:return (text,"Error: Please enter a valid medical report text (at least 10 characters).",None,)# Normalize textnormalized_text = normalize_report_text(text)# Run text analysisself.logger.info("Analyzing medical report text")results = self.text_model.analyze(normalized_text)# Get entities and create visualizationentities = results.get("entities", {})fig = plot_report_entities(normalized_text, entities)# Convert to HTML for displayentities_plot_html = self.fig_to_html(fig)# Format results as HTMLhtml_result = f"""<h2>Medical Report Analysis Results</h2><p><strong>Severity Level:</strong> {results.get("severity", {}).get("level", "Unknown")}</p><p><strong>Severity Score:</strong> {results.get("severity", {}).get("score", 0)}/4</p><p><strong>Confidence:</strong> {results.get("severity", {}).get("confidence", 0):.1%}</p><h3>Key Findings:</h3><ul>"""# Add findingsfindings = results.get("findings", [])if findings:for finding in findings:html_result += f"<li>{finding}</li>"else:html_result += "<li>No specific findings detailed.</li>"html_result += "</ul>"# Add entitieshtml_result += "<h3>Extracted Medical Entities:</h3>"for category, items in entities.items():if items:html_result += f"<p><strong>{category.capitalize()}:</strong> {', '.join(items)}</p>"# Add follow-up recommendationshtml_result += "<h3>Follow-up Recommendations:</h3><ul>"followups = results.get("followup_recommendations", [])if followups:for rec in followups:html_result += f"<li>{rec}</li>"else:html_result += "<li>No specific follow-up recommendations.</li>"html_result += "</ul>"return text, html_result, entities_plot_htmlexcept Exception as e:self.logger.error(f"Error in text analysis: {e}")return text, f"Error analyzing text: {str(e)}", Nonedef analyze_multimodal(self, image, text):"""Perform multimodal analysis of image and text.Args:image: Image file uploaded through Gradiotext: Report text input through GradioReturns:tuple: (results_html, multimodal_plot_html)"""try:# Ensure models are loadedif not self.load_models() or self.fusion_model is None:return "Error: Models not loaded properly.", None# Check for empty inputsif image is None:return "Error: Please upload an X-ray image for analysis.", Noneif not text or len(text.strip()) < 10:return ("Error: Please enter a valid medical report text (at least 10 characters).",None,)# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Normalize textnormalized_text = normalize_report_text(text)# Run multimodal analysisself.logger.info("Performing multimodal analysis")results = self.fusion_model.analyze(temp_path, normalized_text)# Create visualizationfig = plot_multimodal_results(results, image, text)# Convert to HTML for displayplot_html = self.fig_to_html(fig)# Generate explanationexplanation = self.fusion_model.get_explanation(results)# Format results as HTMLhtml_result = f"""<h2>Multimodal Medical Analysis Results</h2><h3>Overview</h3><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Severity Level:</strong> {results.get("severity", {}).get("level", "Unknown")}</p><p><strong>Severity Score:</strong> {results.get("severity", {}).get("score", 0)}/4</p><p><strong>Agreement Score:</strong> {results.get("agreement_score", 0):.0%}</p><h3>Detailed Findings</h3><ul>"""# Add findingsfindings = results.get("findings", [])if findings:for finding in findings:html_result += f"<li>{finding}</li>"else:html_result += "<li>No specific findings detailed.</li>"html_result += "</ul>"# Add follow-up recommendationshtml_result += "<h3>Recommended Follow-up</h3><ul>"followups = results.get("followup_recommendations", [])if followups:for rec in followups:html_result += f"<li>{rec}</li>"else:html_result += ("<li>No specific follow-up recommendations provided.</li>")html_result += "</ul>"# Add confidence noteconfidence = results.get("severity", {}).get("confidence", 0)html_result += f"""<p><em>Note: This analysis has a confidence level of {confidence:.0%}.Please consult with healthcare professionals for official diagnosis.</em></p>"""return html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in multimodal analysis: {e}")return f"Error in multimodal analysis: {str(e)}", Nonedef enhance_image(self, image):"""Enhance X-ray image contrast.Args:image: Image file uploaded through GradioReturns:PIL.Image: Enhanced image"""try:if image is None:return None# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Enhance imageself.logger.info(f"Enhancing image: {temp_path}")output_path = os.path.join(temp_dir, "enhanced.png")enhance_xray_image(temp_path, output_path)# Load enhanced imageenhanced = Image.open(output_path)return enhancedexcept Exception as e:self.logger.error(f"Error enhancing image: {e}")return image # Return original image on errordef fig_to_html(self, fig):"""Convert matplotlib figure to HTML for display in Gradio."""try:import base64import iobuf = io.BytesIO()fig.savefig(buf, format="png", bbox_inches="tight")buf.seek(0)img_str = base64.b64encode(buf.read()).decode("utf-8")plt.close(fig)return f'<img src="data:image/png;base64,{img_str}" alt="Analysis Plot">'except Exception as e:self.logger.error(f"Error converting figure to HTML: {e}")return "<p>Error displaying visualization.</p>"def create_interface():"""Create and launch the Gradio interface."""app = MediSyncApp()# Example medical report for demoexample_report = """CHEST X-RAY EXAMINATIONCLINICAL HISTORY: 55-year-old male with cough and fever.FINDINGS: The heart size is at the upper limits of normal. The lungs are clear without focal consolidation,effusion, or pneumothorax. There is mild prominence of the pulmonary vasculature. No pleural effusion is seen.There is a small nodular opacity noted in the right lower lobe measuring approximately 8mm, which is suspiciousand warrants further investigation. The mediastinum is unremarkable. The visualized bony structures show no acute abnormalities.IMPRESSION:1. Mild cardiomegaly.2. 8mm nodular opacity in the right lower lobe, recommend follow-up CT for further evaluation.3. No acute pulmonary parenchymal abnormality.RECOMMENDATIONS: 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 SystemThis 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)""")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 sample_image_path is None 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")# Set up examples if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],inputs=[multi_img_input, multi_text_input],label="Example X-ray and Report",)with gr.Tab("Image Analysis"):with 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():img_output = gr.Image(label="Processed Image")img_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]],inputs=[img_input],label="Example X-ray Image",)with gr.Tab("Text Analysis"):with gr.Row():with gr.Column():text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=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")text_plot = gr.HTML(label="Entity Visualization")# Set up examplegr.Examples(examples=[[example_report]],inputs=[text_input],label="Example Medical Report",)with gr.Tab("About"):gr.Markdown("""## 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.""")# 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],)# Run the interfaceinterface.launch()if __name__ == "__main__":create_interface()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593import loggingimport osimport sysimport tempfileimport matplotlib.pyplot as pltfrom PIL import Image# Add parent directory to pathparent_dir = os.path.dirname(os.path.abspath(__file__))sys.path.append(parent_dir)# Import our modulesfrom models.multimodal_fusion import MultimodalFusionfrom utils.preprocessing import enhance_xray_image, normalize_report_textfrom utils.visualization import (plot_image_prediction,plot_multimodal_results,plot_report_entities,)# Set up logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",handlers=[logging.StreamHandler(), logging.FileHandler("mediSync.log")],)logger = logging.getLogger(__name__)# Create temporary directory for sample data if it doesn't existos.makedirs(os.path.join(parent_dir, "data", "sample"), exist_ok=True)class MediSyncApp:"""Main application class for the MediSync multi-modal medical analysis system."""def __init__(self):"""Initialize the application and load models."""self.logger = logging.getLogger(__name__)self.logger.info("Initializing MediSync application")# Initialize models with None for lazy loadingself.fusion_model = Noneself.image_model = Noneself.text_model = Nonedef load_models(self):"""Load models if not already loaded.Returns:bool: True if models loaded successfully, False otherwise"""try:if self.fusion_model is None:self.logger.info("Loading models...")self.fusion_model = MultimodalFusion()self.image_model = self.fusion_model.image_analyzerself.text_model = self.fusion_model.text_analyzerself.logger.info("Models loaded successfully")return Trueexcept Exception as e:self.logger.error(f"Error loading models: {e}")return Falsedef analyze_image(self, image):"""Analyze a medical image.Args:image: Image file uploaded through GradioReturns:tuple: (image, image_results_html, plot_as_html)"""try:# Ensure models are loadedif not self.load_models() or self.image_model is None:return image, "Error: Models not loaded properly.", None# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Run image analysisself.logger.info(f"Analyzing image: {temp_path}")results = self.image_model.analyze(temp_path)# Create visualizationfig = plot_image_prediction(image,results.get("predictions", []),f"Primary Finding: {results.get('primary_finding', 'Unknown')}",)# Convert to HTML for displayplot_html = self.fig_to_html(fig)# Format results as HTMLhtml_result = f"""<h2>X-ray Analysis Results</h2><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Confidence:</strong> {results.get("confidence", 0):.1%}</p><p><strong>Abnormality Detected:</strong> {"Yes" if results.get("has_abnormality", False) else "No"}</p><h3>Top Predictions:</h3><ul>"""# Add top 5 predictionsfor label, prob in results.get("predictions", [])[:5]:html_result += f"<li>{label}: {prob:.1%}</li>"html_result += "</ul>"# Add explanationexplanation = self.image_model.get_explanation(results)html_result += f"<h3>Analysis Explanation:</h3><p>{explanation}</p>"return image, html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in image analysis: {e}")return image, f"Error analyzing image: {str(e)}", Nonedef analyze_text(self, text):"""Analyze a medical report text.Args:text: Report text input through GradioReturns:tuple: (text, text_results_html, entities_plot_html)"""try:# Ensure models are loadedif not self.load_models() or self.text_model is None:return text, "Error: Models not loaded properly.", None# Check for empty textif not text or len(text.strip()) < 10:return (text,"Error: Please enter a valid medical report text (at least 10 characters).",None,)# Normalize textnormalized_text = normalize_report_text(text)# Run text analysisself.logger.info("Analyzing medical report text")results = self.text_model.analyze(normalized_text)# Get entities and create visualizationentities = results.get("entities", {})fig = plot_report_entities(normalized_text, entities)# Convert to HTML for displayentities_plot_html = self.fig_to_html(fig)# Format results as HTMLhtml_result = f"""<h2>Medical Report Analysis Results</h2><p><strong>Severity Level:</strong> {results.get("severity", {}).get("level", "Unknown")}</p><p><strong>Severity Score:</strong> {results.get("severity", {}).get("score", 0)}/4</p><p><strong>Confidence:</strong> {results.get("severity", {}).get("confidence", 0):.1%}</p><h3>Key Findings:</h3><ul>"""# Add findingsfindings = results.get("findings", [])if findings:for finding in findings:html_result += f"<li>{finding}</li>"else:html_result += "<li>No specific findings detailed.</li>"html_result += "</ul>"# Add entitieshtml_result += "<h3>Extracted Medical Entities:</h3>"for category, items in entities.items():if items:html_result += f"<p><strong>{category.capitalize()}:</strong> {', '.join(items)}</p>"# Add follow-up recommendationshtml_result += "<h3>Follow-up Recommendations:</h3><ul>"followups = results.get("followup_recommendations", [])if followups:for rec in followups:html_result += f"<li>{rec}</li>"else:html_result += "<li>No specific follow-up recommendations.</li>"html_result += "</ul>"return text, html_result, entities_plot_htmlexcept Exception as e:self.logger.error(f"Error in text analysis: {e}")return text, f"Error analyzing text: {str(e)}", Nonedef analyze_multimodal(self, image, text):"""Perform multimodal analysis of image and text.Args:image: Image file uploaded through Gradiotext: Report text input through GradioReturns:tuple: (results_html, multimodal_plot_html)"""try:# Ensure models are loadedif not self.load_models() or self.fusion_model is None:return "Error: Models not loaded properly.", None# Check for empty inputsif image is None:return "Error: Please upload an X-ray image for analysis.", Noneif not text or len(text.strip()) < 10:return ("Error: Please enter a valid medical report text (at least 10 characters).",None,)# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Normalize textnormalized_text = normalize_report_text(text)# Run multimodal analysisself.logger.info("Performing multimodal analysis")results = self.fusion_model.analyze(temp_path, normalized_text)# Create visualizationfig = plot_multimodal_results(results, image, text)# Convert to HTML for displayplot_html = self.fig_to_html(fig)# Generate explanationexplanation = self.fusion_model.get_explanation(results)# Format results as HTMLhtml_result = f"""<h2>Multimodal Medical Analysis Results</h2><h3>Overview</h3><p><strong>Primary Finding:</strong> {results.get("primary_finding", "Unknown")}</p><p><strong>Severity Level:</strong> {results.get("severity", {}).get("level", "Unknown")}</p><p><strong>Severity Score:</strong> {results.get("severity", {}).get("score", 0)}/4</p><p><strong>Agreement Score:</strong> {results.get("agreement_score", 0):.0%}</p><h3>Detailed Findings</h3><ul>"""# Add findingsfindings = results.get("findings", [])if findings:for finding in findings:html_result += f"<li>{finding}</li>"else:html_result += "<li>No specific findings detailed.</li>"html_result += "</ul>"# Add follow-up recommendationshtml_result += "<h3>Recommended Follow-up</h3><ul>"followups = results.get("followup_recommendations", [])if followups:for rec in followups:html_result += f"<li>{rec}</li>"else:html_result += ("<li>No specific follow-up recommendations provided.</li>")html_result += "</ul>"# Add confidence noteconfidence = results.get("severity", {}).get("confidence", 0)html_result += f"""<p><em>Note: This analysis has a confidence level of {confidence:.0%}.Please consult with healthcare professionals for official diagnosis.</em></p>"""return html_result, plot_htmlexcept Exception as e:self.logger.error(f"Error in multimodal analysis: {e}")return f"Error in multimodal analysis: {str(e)}", Nonedef enhance_image(self, image):"""Enhance X-ray image contrast.Args:image: Image file uploaded through GradioReturns:PIL.Image: Enhanced image"""try:if image is None:return None# Save uploaded image to a temporary filetemp_dir = tempfile.mkdtemp()temp_path = os.path.join(temp_dir, "upload.png")if isinstance(image, str):# Copy the file if it's a pathfrom shutil import copyfilecopyfile(image, temp_path)else:# Save if it's a Gradio UploadButton imageimage.save(temp_path)# Enhance imageself.logger.info(f"Enhancing image: {temp_path}")output_path = os.path.join(temp_dir, "enhanced.png")enhance_xray_image(temp_path, output_path)# Load enhanced imageenhanced = Image.open(output_path)return enhancedexcept Exception as e:self.logger.error(f"Error enhancing image: {e}")return image # Return original image on errordef fig_to_html(self, fig):"""Convert matplotlib figure to HTML for display in Gradio."""try:import base64import iobuf = io.BytesIO()fig.savefig(buf, format="png", bbox_inches="tight")buf.seek(0)img_str = base64.b64encode(buf.read()).decode("utf-8")plt.close(fig)return f'<img src="data:image/png;base64,{img_str}" alt="Analysis Plot">'except Exception as e:self.logger.error(f"Error converting figure to HTML: {e}")return "<p>Error displaying visualization.</p>"def create_interface():"""Create and return the Gradio interface without launching it.For Hugging Face Spaces compatibility."""try:logging.info("Creating MediSync interface for Hugging Face Spaces")app = MediSyncApp()# Example medical report for demoexample_report = """CHEST X-RAY EXAMINATIONCLINICAL HISTORY: 55-year-old male with cough and fever.FINDINGS: The heart size is at the upper limits of normal. The lungs are clear without focal consolidation,effusion, or pneumothorax. There is mild prominence of the pulmonary vasculature. No pleural effusion is seen.There is a small nodular opacity noted in the right lower lobe measuring approximately 8mm, which is suspiciousand warrants further investigation. The mediastinum is unremarkable. The visualized bony structures show no acute abnormalities.IMPRESSION:1. Mild cardiomegaly.2. 8mm nodular opacity in the right lower lobe, recommend follow-up CT for further evaluation.3. No acute pulmonary parenchymal abnormality.RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe."""# Get sample image path if availableimport osfrom pathlib import Pathcurrent_dir = os.path.dirname(os.path.abspath(__file__))parent_dir = os.path.dirname(current_dir)sample_images_dir = Path(parent_dir) / "mediSync" / "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])# Import gradio here to avoid early initializationimport gradio as gr# Define interfacewith gr.Blocks(title="MediSync: Multi-Modal Medical Analysis System",theme=gr.themes.Soft(),) as interface:gr.Markdown("""# MediSync: Multi-Modal Medical Analysis SystemThis 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)""")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 sample_image_path is None 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")# Set up examples if sample image existsif sample_image_path:gr.Examples(examples=[[sample_image_path, example_report]],inputs=[multi_img_input, multi_text_input],label="Example X-ray and Report",)with gr.Tab("Image Analysis"):with 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():img_output = gr.Image(label="Processed Image")img_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]],inputs=[img_input],label="Example X-ray Image",)with gr.Tab("Text Analysis"):with gr.Row():with gr.Column():text_input = gr.Textbox(label="Enter Medical Report Text",placeholder="Enter the radiologist's report text here...",lines=10,value=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")text_plot = gr.HTML(label="Entity Visualization")# Set up examplegr.Examples(examples=[[example_report]],inputs=[text_input],label="Example Medical Report",)with gr.Tab("About"):gr.Markdown("""## 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.""")# 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],)# Return the interface WITHOUT launching itreturn interfaceexcept Exception as e:logging.error(f"Error creating interface: {e}")import tracebacklogging.error(traceback.format_exc())# Create a simple fallback interfaceimport gradio as grreturn gr.Interface(fn=lambda: f"Error initializing MediSync: {str(e)}",inputs=None,outputs="text",title="MediSync Error",description="There was an error initializing the application. Please check the logs for details.",)if __name__ == "__main__":# For running locally, create and launch the interfaceinterface = create_interface()interface.launch()
mediSync/app.py+593-560