Skip to content

MoCoMakers/MRIProcessing

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 Brain MRI Segmentation & Analysis - Streamlit App

A Streamlit web application for processing brain MRI data using the BrainMRIAnalyzer processing pipeline. This app provides an intuitive web interface for uploading NIfTI files, running segmentation analysis, and generating comprehensive PDF reports.

✨ Features

  • Real File Upload: Upload and process actual .nii or .nii.gz MRI files
  • Multiple Segmentation Models: Choose from 5 different segmentation models:
    • SynthSeg (FreeSurfer) - Domain agnostic, fast
    • FastSurfer - 100x faster than FreeSurfer
    • HD-BET - Brain extraction and tumor detection
    • nnU-Net - State-of-the-art accuracy
    • MONAI - Comprehensive medical imaging framework
  • LLM-Powered Analysis: Optional AI-powered clinical analysis using:
    • NVIDIA NIM (FREE - recommended, requires API key)
    • Basic reporting (no API key needed)
  • Comprehensive Reports:
    • Detailed segmentation results with volumes and percentages
    • Abnormality detection
    • Clinical analysis
    • Professional PDF reports with multi-view visualizations
  • Workflow: Upload β†’ Process β†’ View Results β†’ Download PDF

πŸš€ Quick Start

Prerequisites

  • Python 3.8 or higher
  • pip package manager

Installation

  1. Clone the repository with submodules:

    This repository uses the BrainMRIAnalyzer library as a git submodule. Clone with submodules included:

    git clone --recursive https://github.com/yourusername/MRIProcessing.git
    cd MRIProcessing

    If you already cloned without --recursive, initialize and update submodules:

    git submodule init
    git submodule update

    Or use the shorthand:

    git submodule update --init --recursive
  2. Install dependencies:

pip install -r requirements.txt
  1. Configure settings (recommended):

    Copy the example environment file and configure it:

    cp .env.example .env

    Then edit .env and replace the placeholder values:

    • Set LLM_PROVIDER=NVIDIA_NIM if you want AI-powered analysis
    • Replace YOUR_NVIDIA_API_KEY_HERE with your actual NVIDIA API key
    • Adjust thresholds and other settings as needed

    See the Configuration section below for details.

Running the App

streamlit run app.py

The app will open in your default web browser at http://localhost:8501

πŸ“– How It Works

Architecture

The app integrates the BrainMRIAnalyzer library located in lib/BrainMRIAnalyzer/ as a git submodule:

MRIProcessing/
β”œβ”€β”€ app.py                          # Main Streamlit application
β”œβ”€β”€ lib/
β”‚   └── BrainMRIAnalyzer/          # Git submodule (from avithal/BrainMRIAnalyzer)
β”‚       └── BrainMRI_Report.py     # Core processing library
β”œβ”€β”€ config.py                       # Configuration loader
β”œβ”€β”€ requirements.txt                # Python dependencies
β”œβ”€β”€ .gitmodules                     # Git submodule configuration
└── README.md                      # This file

Note: The lib/BrainMRIAnalyzer/ directory is a git submodule pointing to the BrainMRIAnalyzer repository. This allows the project to track a specific version of the BrainMRIAnalyzer library while keeping it as a separate repository.

Processing Pipeline

  1. File Upload: User uploads a .nii or .nii.gz file through the Streamlit interface

    • File is validated and stored temporarily
    • No processing occurs at this stage
  2. Model Selection: User selects a segmentation model from the sidebar (default: SynthSeg)

  3. LLM Configuration (optional): User can optionally configure LLM analysis:

    • Basic: No API key needed, provides structured reports
    • NVIDIA NIM: Free API key from https://build.nvidia.com/ (configured in .env)
  4. Process Data: User clicks "πŸ”„ Process Data" button to trigger analysis:

    • BrainSegmentationPipeline loads the MRI data
    • Selected segmentation model processes the data
    • Results are analyzed (with or without LLM)
    • PDF report is automatically generated (includes visualizations)
  5. Results Display:

    • Segmentation results table showing volumes and percentages
    • Abnormality detection summary
    • Clinical analysis text
  6. Download Report:

    • PDF report is ready for download immediately after processing
    • Report includes all segmentation results, visualizations, and clinical analysis

Key Components

app.py - Streamlit Application

  • Handles file uploads via Streamlit's st.file_uploader
  • Provides UI for model and LLM provider selection
  • Displays results in tables and expandable sections
  • Manages session state to maintain results across interactions
  • Integrates with BrainMRIAnalyzer's pipeline and report generation

lib/BrainMRIAnalyzer/BrainMRI_Report.py - Core Library

  • BaseSegmentationModel: Abstract base class for all segmentation models
  • SynthSegModel, FastSurferModel, etc.: Concrete model implementations
  • MedicalLLMAnalyzer: Handles LLM-powered clinical analysis
  • BrainSegmentationPipeline: Main orchestration class that:
    • Loads MRI files
    • Runs segmentation
    • Generates analysis
    • Creates visualizations
    • Generates PDF reports

config.py - Configuration Management

  • Loads settings from .env file
  • Provides defaults if .env is not present
  • Manages model paths, thresholds, and report settings

πŸ“Š Usage Guide

Step 1: Upload a File

  1. Click "Choose a NIfTI file" button
  2. Select a .nii or .nii.gz file from your computer
  3. The file will be uploaded and stored (not processed yet)

Step 2: Configure Settings (Optional)

In the sidebar:

  • Segmentation Model: Choose which model to use (default: SynthSeg)
  • LLM Analysis Provider:
    • Select "Basic" for no AI analysis (fastest, no API key needed)
    • Select "NVIDIA NIM" for AI-powered analysis (requires NVIDIA_API_KEY in .env file)

Step 3: Process Data

  1. Click the "πŸ”„ Process Data" button
  2. Wait for processing to complete (this may take a few moments)
  3. The PDF report is automatically generated during processing

Step 4: View Results

After processing, you'll see:

  • File Information: Name, size, dimensions, model used
  • Segmentation Results Table:
    • Brain regions (White Matter, Gray Matter, CSF, Ventricles, Lesions, Tumors)
    • Volumes in mmΒ³ and cmΒ³
    • Percentages
    • Confidence scores
    • Status (Normal/Abnormal)
  • Abnormality Summary: Count of abnormal findings
  • Clinical Analysis: Text analysis of findings

Step 5: Download Report

  • Click "πŸ“₯ Download PDF Report" to download the automatically generated PDF
  • The PDF includes all segmentation results, visualizations, and clinical analysis

πŸ”§ Configuration

Environment Variables (.env)

The project uses a .env file for configuration. Create this file by copying the template provided below.

Quick Setup:

  1. Create your .env file:

    Copy the example file if it exists:

    cp .env.example .env

    Or create a new .env file manually and copy the configuration template from the "Configuration Options" section below.

  2. Edit .env and replace placeholder values:

    • Open .env in a text editor
    • Replace YOUR_NVIDIA_API_KEY_HERE with your actual NVIDIA API key (if using NVIDIA NIM)
    • Set LLM_PROVIDER=NVIDIA_NIM if you want AI-powered analysis (or leave as Basic for no AI)
    • Adjust other settings as needed

Getting Your NVIDIA API Key (FREE):

  1. Visit build.nvidia.com
  2. Sign up for a free account (no credit card required)
  3. Navigate to the API Keys section
  4. Generate a new API key
  5. Copy the key and paste it in your .env file

Configuration Options:

Create a .env file in the project root with the following content (or copy from .env.example if it exists):

# BrainMRIAnalyzer Configuration
# Copy this content to create your .env file

# Model Configuration
MODEL_NAME=SynthSeg              # Segmentation model to use
MODEL_PATH=

# Processing Thresholds
ANOMALY_THRESHOLD=0.5           # Threshold for anomaly detection
VENTRICLE_THRESHOLD=2.5         # Threshold for enlarged ventricles
LESION_THRESHOLD=0.5            # Threshold for lesion detection
TUMOR_THRESHOLD=0.3             # Threshold for tumor detection

# Report Configuration
REPORT_OUTPUT_DIR=./output      # Directory for generated reports
REPORT_TITLE=Brain MRI Segmentation & Analysis Report

# LLM Configuration
# Options: Basic, NVIDIA_NIM
# Set to NVIDIA_NIM to enable AI-powered analysis (requires API key below)
LLM_PROVIDER=Basic

# NVIDIA NIM API Configuration
# Get your FREE API key at: https://build.nvidia.com/
# Replace YOUR_NVIDIA_API_KEY_HERE with your actual API key
NVIDIA_API_KEY=YOUR_NVIDIA_API_KEY_HERE

# Processing Options
ENABLE_ABNORMALITY_DETECTION=true
ENABLE_CONFIDENCE_SCORES=true

Example: To enable NVIDIA NIM analysis, your .env file should look like:

LLM_PROVIDER=NVIDIA_NIM
NVIDIA_API_KEY=nvapi-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Important Notes:

  • The .env file is not tracked by git (it's in .gitignore) to keep your API keys secure
  • Never commit your .env file with real API keys
  • The sidebar will show a status indicator if the NVIDIA API key is found in .env
  • You can still select the LLM provider in the sidebar, but the API key is always read from .env for security

πŸ“¦ Dependencies

All dependencies are listed in requirements.txt:

  • streamlit - Web application framework
  • numpy - Numerical computing
  • nibabel - NIfTI file I/O
  • reportlab - PDF generation
  • matplotlib - Visualization
  • requests - HTTP requests for NVIDIA NIM API (optional)

Install all dependencies:

pip install -r requirements.txt

🎯 Detected Brain Regions

The segmentation models identify:

  • White Matter: Central brain tissue
  • Gray Matter: Cortical tissue
  • Cerebrospinal Fluid (CSF): Fluid surrounding brain
  • Ventricles: Fluid-filled cavities
  • Lesions: Abnormal tissue areas
  • Tumors: Abnormal growth masses

⚠️ Abnormality Detection

The system automatically flags:

  • Enlarged ventricles (hydrocephalus indicators)
  • Tissue lesions (potential MS, stroke, etc.)
  • Tumors or masses
  • Abnormal tissue volumes
  • Asymmetries

πŸ“ Output Files

Generated files are saved to the output/ directory:

  • brain_analysis_report_[timestamp].pdf - Detailed PDF report (includes visualizations and all analysis results)
  • Note: Visualizations are included in the PDF report, not generated as separate image files

πŸ”’ Privacy & Data Retention

Automatic Cleanup: All uploaded files and generated reports are automatically deleted after 15 minutes for privacy protection. This includes:

  • Uploaded NIfTI files (.nii, .nii.gz)
  • Generated PDF reports
  • Temporary processing files
  • Session state data

The cleanup runs automatically on each app interaction, ensuring medical data is never stored longer than necessary.

System Requirements for Cleanup Feature

The automatic cleanup feature requires:

  1. File System Permissions: The application must have read/write/delete permissions for:

    • The output/ directory (where PDFs are generated)
    • The system temporary directory (where uploaded files are temporarily stored)
  2. Streamlit Deployment: When deploying behind an Apache proxy or other reverse proxy:

    • Ensure the Streamlit process has write access to the output/ directory
    • The temporary directory must be writable (typically handled automatically by the OS)
    • Consider setting up a cron job or systemd timer as a backup cleanup mechanism (optional)
  3. Production Deployment Considerations:

    • Apache Proxy Setup: Ensure Apache allows sufficient timeout for file processing
    • File System: Use a local filesystem (not network-mounted) for better performance and reliability
    • Disk Space: Monitor disk usage; cleanup prevents accumulation but ensure sufficient space for concurrent users
    • Backup Cleanup: For production, consider adding a cron job to clean files older than 15 minutes as a safety net:
      # Example cron job (runs every 5 minutes)
      */5 * * * * find /path/to/MRIProcessing/output -type f -mmin +15 -delete
  4. Session State: Streamlit's session state is cleared automatically when data exceeds 15 minutes, but ensure:

    • Streamlit server has sufficient memory for concurrent sessions
    • Session state cleanup doesn't interfere with active processing

Note: The cleanup is designed to fail silently to avoid disrupting user experience. Check application logs if you need to verify cleanup is working correctly.

πŸ”„ Updating the Submodule

To update the BrainMRIAnalyzer submodule to the latest version:

cd lib/BrainMRIAnalyzer
git pull origin main
cd ../..
git add lib/BrainMRIAnalyzer
git commit -m "Update BrainMRIAnalyzer submodule"

Or update from the root directory:

git submodule update --remote lib/BrainMRIAnalyzer
git add lib/BrainMRIAnalyzer
git commit -m "Update BrainMRIAnalyzer submodule"

πŸ” Troubleshooting

Submodule Issues

If lib/BrainMRIAnalyzer/ appears empty after cloning:

  • The submodule wasn't initialized. Run:
    git submodule update --init --recursive

If you see "fatal: not a git repository" errors:

  • The submodule may not be properly initialized. Try:
    git submodule init
    git submodule update

Import Errors

If you see import errors for BrainMRIAnalyzer:

  • Ensure the lib/BrainMRIAnalyzer/ directory exists
  • Check that BrainMRI_Report.py is in that directory
  • Verify the submodule is initialized: git submodule status
  • The app automatically adds lib/ to the Python path

File Upload Issues

  • Ensure the file is a valid NIfTI format (.nii or .nii.gz)
  • Check file size limits (Streamlit default is 200MB)
  • Verify the file isn't corrupted

LLM API Errors

  • NVIDIA NIM: Verify your API key is correct and account is active
  • Check that NVIDIA_API_KEY is set correctly in your .env file
  • Use "Basic" mode if API key is not available or invalid

Processing Errors

  • Check that all dependencies are installed: pip install -r requirements.txt
  • Verify the MRI file is valid and readable
  • Check console output for detailed error messages

πŸ§ͺ Testing

Test the submodule is properly initialized:

git submodule status

Test the import system:

python -c "import sys; from pathlib import Path; sys.path.insert(0, str(Path('lib'))); from BrainMRIAnalyzer.BrainMRI_Report import SynthSegModel; print('OK')"

πŸ“š References

βš–οΈ Disclaimer

This tool is for research and educational purposes only. It is not intended for clinical diagnosis or treatment decisions. Always consult qualified healthcare professionals for medical advice.

🀝 Contributing

Contributions are welcome! Areas for improvement:

  • Additional segmentation model integrations
  • Enhanced visualization options
  • DICOM file support
  • Batch processing capabilities
  • Docker containerization

πŸ“ License

This project uses the BrainMRIAnalyzer library. Please refer to the original repository for license information.


Built with ❀️ using Streamlit and BrainMRIAnalyzer

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages