Spaces:
Runtime error
Runtime error
Update README.md
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# MediSync: Multi-Modal Medical Analysis SystemMediSync is an AI-powered healthcare solution that combines X-ray image analysis with patient report text processing to provide comprehensive medical insights.## Features- **X-ray Image Analysis**: Detects abnormalities in chest X-rays using pre-trained vision models from Hugging Face.- **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 diagnosis suggestions.- **User-friendly Interface**: Simple web interface for uploading images and reports.## Project Structure```mediSync/βββ app.py # Main application with Gradio interfaceβββ models/β βββ image_analyzer.py # X-ray image analysis moduleβ βββ text_analyzer.py # Medical report text analysis moduleβ βββ multimodal_fusion.py # Fusion of image and text insightsβββ utils/β βββ preprocessing.py # Data preprocessing utilitiesβ βββ visualization.py # Result visualization utilitiesβββ data/β βββ sample/ # Sample data for testingβββ tests/ # Unit tests```## Setup Instructions1. Clone this repository:```bashgit clone [repository-url]cd MediSync```2. Install dependencies:```bashpip install -r requirements.txt```3. Run the application:```bashpython app.py```4. Access the web interface at `http://localhost:7860`## Models Used- **X-ray Analysis**: facebook/deit-base-patch16-224-medical-cxr- **Medical Text Analysis**: medicalai/ClinicalBERT- **Additional Support Models**: Medical question answering and entity recognition models## Use Cases- Preliminary screening of chest X-rays- Cross-validation of radiologist reports- Educational tool for medical students- Research tool for studying correlation between visual findings and written reports## NoteThis system is designed as a support tool and should not replace professional medical diagnosis. Always consult with healthcare professionals for medical decisions.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362# MediSync: Multi-Modal Medical Analysis SystemMediSync is an AI-powered healthcare solution that combines X-ray image analysis with patient report text processing to provide comprehensive medical insights.## Features- **X-ray Image Analysis**: Detects abnormalities in chest X-rays using pre-trained vision models from Hugging Face.- **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 diagnosis suggestions.- **User-friendly Interface**: Simple web interface for uploading images and reports.## Project Structure```mediSync/βββ app.py # Main application with Gradio interfaceβββ models/β βββ image_analyzer.py # X-ray image analysis moduleβ βββ text_analyzer.py # Medical report text analysis moduleβ βββ multimodal_fusion.py # Fusion of image and text insightsβββ utils/β βββ preprocessing.py # Data preprocessing utilitiesβ βββ visualization.py # Result visualization utilitiesβββ data/β βββ sample/ # Sample data for testingβββ tests/ # Unit tests```# MediSync: Multi-Modal Medical Analysis System## Comprehensive Technical Documentation### Table of Contents1. [Introduction](#introduction)2. [System Architecture](#system-architecture)3. [Installation](#installation)4. [Usage](#usage)5. [Core Components](#core-components)6. [Model Details](#model-details)7. [API Reference](#api-reference)8. [Extending the System](#extending-the-system)9. [Troubleshooting](#troubleshooting)10. [References](#references)---## IntroductionMediSync is a multi-modal AI system that combines X-ray image analysis with medical report text processing to provide comprehensive medical insights. By leveraging state-of-the-art deep learning models for both vision and language understanding, MediSync can:- Analyze chest X-ray images to detect abnormalities- Extract key clinical information from medical reports- Fuse insights from both modalities for enhanced diagnosis support- Provide comprehensive visualization of analysis resultsThis AI system demonstrates the power of multi-modal fusion in the healthcare domain, where integrating information from multiple sources can lead to more robust and accurate analyses.## System ArchitectureMediSync follows a modular architecture with three main components:1. **Image Analysis Module**: Processes X-ray images using pre-trained vision models2. **Text Analysis Module**: Analyzes medical reports using NLP models3. **Multimodal Fusion Module**: Combines insights from both modalitiesThe system uses the following high-level workflow:```ββββββββββββββββββββ X-ray Image βββββββββββ¬βββββββββββΌβββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββββ Preprocessing βββββΆβ Image Analysis βββββΆβ ββββββββββββββββββββ βββββββββββββββββββ β ββ Multimodal ββββββββββββββββββββ βββββββββββββββββββ β Fusion βββββΆ Resultsβ Medical Report βββββΆβ Text Analysis βββββΆβ ββββββββββββββββββββ βββββββββββββββββββ β ββββββββββββββββββββ```## Installation### Prerequisites- Python 3.8 or higher- Pip package manager### Setup Instructions1. Clone the repository:```bashgit clone [repository-url]cd mediSync```2. Install dependencies:```bashpip install -r requirements.txt```3. Download sample data:```bashpython -m mediSync.utils.download_samples```## Usage### Running the ApplicationTo launch the MediSync application with the Gradio interface:```bashpython run.py```This will:1. Download sample data if not already present2. Initialize the application3. Launch the Gradio web interface### Web InterfaceMediSync provides a user-friendly web interface with three main tabs:1. **Multimodal Analysis**: Upload an X-ray image and enter a medical report for combined analysis2. **Image Analysis**: Upload an X-ray image for image-only analysis3. **Text Analysis**: Enter a medical report for text-only analysis### Command Line UsageYou can also use the core components directly from Python:```pythonfrom mediSync.models import XRayImageAnalyzer, MedicalReportAnalyzer, MultimodalFusion# Initialize modelsfusion_model = MultimodalFusion()# Analyze image and textresults = fusion_model.analyze("path/to/image.jpg", "Medical report text...")# Get explanationexplanation = fusion_model.get_explanation(results)print(explanation)```## Core Components### Image Analysis ModuleThe `XRayImageAnalyzer` class is responsible for analyzing X-ray images:- Uses the DeiT (Data-efficient image Transformers) model fine-tuned on chest X-rays- Detects abnormalities and classifies findings- Provides confidence scores and primary findingsKey methods:- `analyze(image_path)`: Analyzes an X-ray image- `get_explanation(results)`: Generates a human-readable explanation### Text Analysis ModuleThe `MedicalReportAnalyzer` class processes medical report text:- Extracts medical entities (conditions, treatments, tests)- Assesses severity level- Extracts key findings- Suggests follow-up actionsKey methods:- `extract_entities(text)`: Extracts medical entities- `assess_severity(text)`: Determines severity level- `extract_findings(text)`: Extracts key clinical findings- `suggest_followup(text, entities, severity)`: Suggests follow-up actions- `analyze(text)`: Performs comprehensive analysis### Multimodal Fusion ModuleThe `MultimodalFusion` class combines insights from both modalities:- Calculates agreement between image and text analyses- Determines confidence-weighted findings- Provides comprehensive severity assessment- Merges follow-up recommendationsKey methods:- `analyze_image(image_path)`: Analyzes image only- `analyze_text(text)`: Analyzes text only- `analyze(image_path, report_text)`: Performs multimodal analysis- `get_explanation(fused_results)`: Generates comprehensive explanation## Model Details### X-ray Analysis Model- **Model**: facebook/deit-base-patch16-224-medical-cxr- **Architecture**: Data-efficient image Transformer (DeiT)- **Training Data**: Chest X-ray datasets- **Input Size**: 224x224 pixels- **Output**: Classification probabilities for various conditions### Medical Text Analysis Models- **Entity Recognition Model**: samrawal/bert-base-uncased_medical-ner- **Classification Model**: medicalai/ClinicalBERT- **Architecture**: BERT-based transformer models- **Training Data**: Medical text and reports## API Reference### XRayImageAnalyzer```pythonfrom mediSync.models import XRayImageAnalyzer# Initializeanalyzer = XRayImageAnalyzer(model_name="facebook/deit-base-patch16-224-medical-cxr")# Analyze imageresults = analyzer.analyze("path/to/image.jpg")# Get explanationexplanation = analyzer.get_explanation(results)```### MedicalReportAnalyzer```pythonfrom mediSync.models import MedicalReportAnalyzer# Initializeanalyzer = MedicalReportAnalyzer()# Analyze reportresults = analyzer.analyze("Medical report text...")# Access specific componentsentities = results["entities"]severity = results["severity"]findings = results["findings"]recommendations = results["followup_recommendations"]```### MultimodalFusion```pythonfrom mediSync.models import MultimodalFusion# Initializefusion = MultimodalFusion()# Multimodal analysisresults = fusion.analyze("path/to/image.jpg", "Medical report text...")# Get explanationexplanation = fusion.get_explanation(results)```## Extending the System### Adding New ModelsTo add a new image analysis model:1. Create a new class that follows the same interface as `XRayImageAnalyzer`2. Update the `MultimodalFusion` class to use your new model```pythonclass NewXRayModel:def __init__(self, model_name, device=None):# Initialize your modelpassdef analyze(self, image_path):# Implement analysis logicreturn resultsdef get_explanation(self, results):# Generate explanationreturn explanation```### Custom PreprocessingYou can extend the preprocessing utilities in `utils/preprocessing.py` for custom data preparation:```pythondef my_custom_preprocessor(image_path, **kwargs):# Implement custom preprocessingreturn processed_image```### Visualization ExtensionsTo add new visualization options, extend the utilities in `utils/visualization.py`:```pythondef my_custom_visualization(results, **kwargs):# Create custom visualizationreturn figure```## Troubleshooting### Common Issues1. **Model Loading Errors**- Ensure you have a stable internet connection for downloading models- Check that you have sufficient disk space- Try specifying a different model checkpoint2. **Image Processing Errors**- Ensure images are in a supported format (JPEG, PNG)- Check that the image is a valid X-ray image- Try preprocessing the image manually using the utility functions3. **Performance Issues**- For faster inference, use a GPU if available- Reduce image resolution if processing is too slow- Use the text-only analysis for quicker results### LoggingMediSync uses Python's logging module for debug information:```pythonimport logginglogging.basicConfig(level=logging.DEBUG)```Log files are saved to `mediSync.log` in the application directory.## References### Datasets- [MIMIC-CXR](https://physionet.org/content/mimic-cxr/2.0.0/): Large dataset of chest radiographs with reports- [ChestX-ray14](https://www.nih.gov/news-events/news-releases/nih-clinical-center-provides-one-largest-publicly-available-chest-x-ray-datasets-scientific-community): NIH dataset of chest X-rays### Papers- He, K., et al. (2020). "Vision Transformers for Medical Image Analysis"- Irvin, J., et al. (2019). "CheXpert: A Large Chest Radiograph Dataset with Uncertainty Labels and Expert Comparison"- Johnson, A.E.W., et al. (2019). "MIMIC-CXR-JPG, a large publicly available database of labeled chest radiographs"### Tools and Libraries- [Hugging Face Transformers](https://huggingface.co/docs/transformers/index)- [PyTorch](https://pytorch.org/)- [Gradio](https://gradio.app/)---## LicenseThis project is licensed under the MIT License - see the LICENSE file for details.## Acknowledgments- The development of MediSync was inspired by recent advances in multi-modal learning in healthcare.- Special thanks to the open-source community for providing pre-trained models and tools.
README.md+362-64