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.
- Real File Upload: Upload and process actual
.niior.nii.gzMRI 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
- Python 3.8 or higher
- pip package manager
-
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 MRIProcessingIf you already cloned without
--recursive, initialize and update submodules:git submodule init git submodule update
Or use the shorthand:
git submodule update --init --recursive
-
Install dependencies:
pip install -r requirements.txt-
Configure settings (recommended):
Copy the example environment file and configure it:
cp .env.example .env
Then edit
.envand replace the placeholder values:- Set
LLM_PROVIDER=NVIDIA_NIMif you want AI-powered analysis - Replace
YOUR_NVIDIA_API_KEY_HEREwith your actual NVIDIA API key - Adjust thresholds and other settings as needed
See the Configuration section below for details.
- Set
streamlit run app.pyThe app will open in your default web browser at http://localhost:8501
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.
-
File Upload: User uploads a
.niior.nii.gzfile through the Streamlit interface- File is validated and stored temporarily
- No processing occurs at this stage
-
Model Selection: User selects a segmentation model from the sidebar (default: SynthSeg)
-
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)
-
Process Data: User clicks "π Process Data" button to trigger analysis:
BrainSegmentationPipelineloads the MRI data- Selected segmentation model processes the data
- Results are analyzed (with or without LLM)
- PDF report is automatically generated (includes visualizations)
-
Results Display:
- Segmentation results table showing volumes and percentages
- Abnormality detection summary
- Clinical analysis text
-
Download Report:
- PDF report is ready for download immediately after processing
- Report includes all segmentation results, visualizations, and clinical analysis
- 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
- 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
- Loads settings from
.envfile - Provides defaults if
.envis not present - Manages model paths, thresholds, and report settings
- Click "Choose a NIfTI file" button
- Select a
.niior.nii.gzfile from your computer - The file will be uploaded and stored (not processed yet)
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_KEYin.envfile)
- Click the "π Process Data" button
- Wait for processing to complete (this may take a few moments)
- The PDF report is automatically generated during processing
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
- Click "π₯ Download PDF Report" to download the automatically generated PDF
- The PDF includes all segmentation results, visualizations, and clinical analysis
The project uses a .env file for configuration. Create this file by copying the template provided below.
-
Create your
.envfile:Copy the example file if it exists:
cp .env.example .env
Or create a new
.envfile manually and copy the configuration template from the "Configuration Options" section below. -
Edit
.envand replace placeholder values:- Open
.envin a text editor - Replace
YOUR_NVIDIA_API_KEY_HEREwith your actual NVIDIA API key (if using NVIDIA NIM) - Set
LLM_PROVIDER=NVIDIA_NIMif you want AI-powered analysis (or leave asBasicfor no AI) - Adjust other settings as needed
- Open
- Visit build.nvidia.com
- Sign up for a free account (no credit card required)
- Navigate to the API Keys section
- Generate a new API key
- Copy the key and paste it in your
.envfile
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=trueExample: To enable NVIDIA NIM analysis, your .env file should look like:
LLM_PROVIDER=NVIDIA_NIM
NVIDIA_API_KEY=nvapi-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxImportant Notes:
- The
.envfile is not tracked by git (it's in.gitignore) to keep your API keys secure - Never commit your
.envfile 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
.envfor security
All dependencies are listed in requirements.txt:
streamlit- Web application frameworknumpy- Numerical computingnibabel- NIfTI file I/Oreportlab- PDF generationmatplotlib- Visualizationrequests- HTTP requests for NVIDIA NIM API (optional)
Install all dependencies:
pip install -r requirements.txtThe 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
The system automatically flags:
- Enlarged ventricles (hydrocephalus indicators)
- Tissue lesions (potential MS, stroke, etc.)
- Tumors or masses
- Abnormal tissue volumes
- Asymmetries
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
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.
The automatic cleanup feature requires:
-
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)
- The
-
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)
- Ensure the Streamlit process has write access to the
-
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
-
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.
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"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
If you see import errors for BrainMRIAnalyzer:
- Ensure the
lib/BrainMRIAnalyzer/directory exists - Check that
BrainMRI_Report.pyis in that directory - Verify the submodule is initialized:
git submodule status - The app automatically adds
lib/to the Python path
- Ensure the file is a valid NIfTI format (
.niior.nii.gz) - Check file size limits (Streamlit default is 200MB)
- Verify the file isn't corrupted
- NVIDIA NIM: Verify your API key is correct and account is active
- Check that
NVIDIA_API_KEYis set correctly in your.envfile - Use "Basic" mode if API key is not available or invalid
- 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
Test the submodule is properly initialized:
git submodule statusTest 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')"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.
Contributions are welcome! Areas for improvement:
- Additional segmentation model integrations
- Enhanced visualization options
- DICOM file support
- Batch processing capabilities
- Docker containerization
This project uses the BrainMRIAnalyzer library. Please refer to the original repository for license information.
Built with β€οΈ using Streamlit and BrainMRIAnalyzer