Skip to content

MohdAltamish/NeuroScan

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 NeuroScan: Resilient Brain Tumor Diagnostic Workstation

An adversarially robust AI system for MRI-based brain tumor classification, featuring a custom hybrid architecture, physics-based attack simulation, and intelligent signal recovery.

Python PyTorch TensorFlow Flask Streamlit License: MIT


πŸ“Œ Project Title

NeuroScan β€” an end-to-end, adversarially resilient brain tumor diagnostic platform powered by a custom deep learning architecture.


πŸ” Overview

Brain tumor classification from MRI scans is a critical medical AI challenge. Most deployed models fail silently when scans are degraded by hardware noise, motion artifacts, or transmission errors β€” a clinically dangerous gap.

NeuroScan addresses this by building an attack-aware, defense-integrated diagnostic pipeline that:

  • Classifies MRI scans into 4 categories: Glioma, Meningioma, Pituitary Tumor, and No Tumor
  • Simulates real-world scan corruption via a 7-layer adversarial attack engine (OmniChaos)
  • Recovers degraded scans through domain-matched signal healing (VisualHealer + FourierHealer)
  • Exposes all diagnostics via a REST API and two interactive UIs (Streamlit + Gradio)

The model was developed through 5 iterative experiments, evolving from a MobileNetV2 baseline to the final HybridChimeraAI β€” a custom PyTorch architecture combining CNNs, Transformers, and a Mixture-of-Experts (MoE) classifier β€” achieving 96% shielded recovery accuracy on the final benchmark.


πŸ—οΈ Tech Stack & Tools

Layer Technology
Core AI Model PyTorch β€” custom HybridChimeraAI (CNN + Transformer + MoE)
Transfer Learning TensorFlow / Keras β€” MobileNetV2, Xception
Attack Simulation NumPy, SciPy, OpenCV
Defense / Pre-processing OpenCV (CLAHE, Fourier band-stop filter, NL-Means denoising)
REST API Backend Flask, Flask-CORS
Streamlit UI Streamlit, Plotly, Pandas
Gradio UI Gradio
Explainability Custom Class Activation Mapping (CAM) via CNN stem features
Dataset Brain Tumor MRI Dataset β€” Kaggle
Frontend HTML5, Vanilla CSS, JavaScript (SPA with client-side routing)

✨ Features

πŸ”¬ Core AI Capabilities

  • 4-class MRI classification β€” Glioma, Meningioma, Pituitary Tumor, No Tumor
  • HybridChimeraAI β€” custom PyTorch architecture combining:
    • 3-layer CNN stem for spatial feature extraction
    • Transformer encoder (8-head self-attention, 2 layers)
    • Mixture-of-Experts (MoE) classifier with 4 expert sub-networks and a learned gating function
  • Test-Time Augmentation (TTA) β€” 3-vote voting ensemble across clean, rotated, and zoomed views for more stable inference

βš”οΈ OmniChaos Attack Engine β€” 7-Layer Adversarial Simulation

  • 5-Layer Visual Attack β€” elastic pixel warping (Gaussian displacement fields), edge-darkening shadow overlay, and Gaussian noise injection
  • 2-Layer Physics / K-Space Attack β€” Fourier-domain corruption mimicking MRI hardware artifacts (stripe noise caused by frequency-domain spike artifacts β€” a real failure mode in clinical MRI scanners)

πŸ›‘οΈ Intelligent Signal Recovery

  • VisualHealer β€” NL-Means denoising + CLAHE (Contrast Limited Adaptive Histogram Equalization) on LAB color space to recover edge detail from visual noise
  • FourierHealer β€” Fourier-domain band-stop filtering that surgically removes k-space spike artifacts while preserving anatomical structure

πŸ–₯️ Streamlit Command Center β€” 3 Modules

  • Diagnostic Pipeline β€” upload MRI scan β†’ view attack β†’ view recovery β†’ get CAM heatmap + class prediction with confidence scores
  • Chaos Sandbox β€” interactive toggle of individual attack layers with live re-prediction
  • Batch Auditor β€” upload a ZIP of patient scans, get per-image predictions, overall accuracy, and a Plotly confusion matrix

🌐 REST API (Flask)

  • GET /api/health β€” model health + loaded status check
  • POST /api/analyze β€” upload MRI image β†’ returns predicted class, confidence, per-class probabilities, alert status, and base64 images (original / attacked / shielded)

🎨 Web Frontend (SPA)

  • Multi-page Single-Page Application with client-side routing
  • Upload MRI β†’ see diagnostic pipeline results in real time
  • Connects to Flask API backend

πŸ€– Gradio Workstation

  • Lightweight three-panel view: Original β†’ Attacked β†’ Shielded with classification confidence bars and clinical alert status

πŸ“ Project Structure

Brain-Tumor-Detector/
β”‚
β”œβ”€β”€ apex_master.py          # Core PyTorch architecture + attack/defense modules
β”‚   β”œβ”€β”€ HybridChimeraAI     # CNN + Transformer + MoE model
β”‚   β”œβ”€β”€ OmniChaosInjector   # 7-layer adversarial attack engine
β”‚   β”œβ”€β”€ VisualHealer        # NL-Means + CLAHE defense
β”‚   β”œβ”€β”€ FourierHealer       # K-Space band-stop defense
β”‚   └── TTAPipeline         # Test-Time Augmentation inference
β”‚
β”œβ”€β”€ api.py                  # Flask REST API β€” wraps model with /api/analyze endpoint
β”œβ”€β”€ app.py                  # Streamlit Command Center (3-module UI)
β”œβ”€β”€ app_main.py             # Gradio Diagnostic Workstation (TF/Keras)
β”‚
β”œβ”€β”€ frontend/               # Web SPA Frontend
β”‚   β”œβ”€β”€ index.html          # Main entry point
β”‚   β”œβ”€β”€ router.js           # Client-side routing
β”‚   β”œβ”€β”€ styles.css          # Global CSS
β”‚   └── views/              # Page components
β”‚
β”œβ”€β”€ train_robust.py         # Experiment 1: MobileNetV2 baseline
β”œβ”€β”€ train_extreme.py        # Experiment 2: Xception with heavy augmentation
β”œβ”€β”€ train_final_98.py       # Experiment 3: MobileNetV2 + CLAHE fine-tuning
β”œβ”€β”€ train_unbeatable.py     # Experiment 4-5: Final champion model
β”‚
β”œβ”€β”€ real_benchmark.py       # Full test-set evaluation + classification report
β”œβ”€β”€ test_security.py        # Triple-scenario robustness test (Clean/Attack/Shield)
β”œβ”€β”€ verify_robustness.py    # Noise-level stress test
β”œβ”€β”€ check_labels.py         # Label alignment validation
β”œβ”€β”€ generate_attack.py      # Standalone attack/shield visual demo
β”œβ”€β”€ save_visuals.py         # Generate comparison images for presentation
β”‚
β”œβ”€β”€ experiment_log.md       # Full iterative experiment journal (5 experiments)
β”‚
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ Training/           # Kaggle training set (by class folder)
β”‚   └── Testing/            # Kaggle test set (by class folder)
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ v4_Unbeatable_Final.h5    # TF/Keras champion model (96% accuracy)
β”‚   └── apex_master_weights.pth   # PyTorch HybridChimeraAI weights
β”‚
└── presentation_assets/    # Auto-generated comparison/graph images

βš™οΈ Installation & Setup

Prerequisites

  • Python 3.9+
  • CUDA-capable GPU recommended (CPU inference supported)
  • pip

1. Clone the Repository

git clone https://github.com/MohdAltamish/Brain-Tumor-Detector.git
cd Brain-Tumor-Detector

2. Create a Virtual Environment (Recommended)

python -m venv .venv
source .venv/bin/activate     # macOS/Linux
# .venv\Scripts\activate      # Windows

3. Install Dependencies

pip install torch torchvision tensorflow streamlit gradio \
            flask flask-cors \
            opencv-python-headless scipy numpy pillow \
            pandas plotly scikit-learn

4. Download the Dataset

Get the dataset from Kaggle: Brain Tumor MRI Dataset

Place the downloaded folders as:

data/
β”œβ”€β”€ Training/
β”‚   β”œβ”€β”€ glioma/
β”‚   β”œβ”€β”€ meningioma/
β”‚   β”œβ”€β”€ notumor/
β”‚   └── pituitary/
└── Testing/
    β”œβ”€β”€ glioma/
    β”œβ”€β”€ meningioma/
    β”œβ”€β”€ notumor/
    └── pituitary/

5. Train or Download Weights

Option A β€” Train HybridChimeraAI (PyTorch) from scratch:

python apex_master.py
# Trains for 35 epochs, saves: apex_master_weights.pth

Option B β€” Train the TF/Keras champion model:

python train_unbeatable.py
# Trains for 15 epochs with CLAHE + heavy augmentation
# Saves: models/v4_Unbeatable_Final.h5

Pre-trained weights (apex_master_weights.pth, models/v4_Unbeatable_Final.h5) are included in the repository for direct inference without training.


πŸš€ Running the Application

Option 1: Flask REST API

python api.py
# API running at: http://localhost:5050
  • GET http://localhost:5050/api/health β€” health check
  • POST http://localhost:5050/api/analyze β€” send MRI image, receive diagnosis

Option 2: Streamlit Command Center (PyTorch)

streamlit run app.py
# Navigate to: http://localhost:8501

Use the sidebar to switch between:

  • Diagnostic Pipeline β€” upload + analyze scan
  • Chaos Sandbox β€” interactive attack toggle
  • Batch Auditor β€” ZIP upload + confusion matrix

Option 3: Gradio Workstation (TF/Keras)

python app_main.py
# Navigate to the local URL printed in the terminal

Option 4: Web Frontend (SPA)

Open frontend/index.html in a browser (requires Flask API running on port 5050).


πŸ§ͺ Technical Workflow

─────────────────────────────────────────────────────────────
                        INPUT MRI SCAN
─────────────────────────────────────────────────────────────
                              β”‚
                              β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚     OmniChaos Attack Engine    β”‚
              β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
              β”‚  β”‚ 5-Layer Visual Attack   β”‚  β”‚
              β”‚  β”‚  β€’ Elastic Pixel Warp   β”‚  β”‚
              β”‚  β”‚  β€’ Shadow Overlay       β”‚  β”‚
              β”‚  β”‚  β€’ Gaussian Noise       β”‚  β”‚
              β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
              β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
              β”‚  β”‚ 2-Layer K-Space Attack  β”‚  β”‚
              β”‚  β”‚  β€’ Fourier Transform    β”‚  β”‚
              β”‚  β”‚  β€’ Frequency Spike Inj. β”‚  β”‚
              β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚     Defense / Healing Layer    β”‚
              β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
              β”‚  β”‚ VisualHealer            β”‚  β”‚
              β”‚  β”‚  β€’ NL-Means Denoising   β”‚  β”‚
              β”‚  β”‚  β€’ CLAHE Enhancement    β”‚  β”‚
              β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
              β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
              β”‚  β”‚ FourierHealer           β”‚  β”‚
              β”‚  β”‚  β€’ Band-Stop Mask       β”‚  β”‚
              β”‚  β”‚  β€’ Inverse FFT Recon.   β”‚  β”‚
              β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚        HybridChimeraAI         β”‚
              β”‚                               β”‚
              β”‚  [1] CNN Stem                 β”‚
              β”‚      3 conv blocks            β”‚
              β”‚      (64 β†’ 128 β†’ 256 filters) β”‚
              β”‚             β”‚                 β”‚
              β”‚  [2] Transformer Encoder      β”‚
              β”‚      8-head self-attention    β”‚
              β”‚      2 encoder layers         β”‚
              β”‚             β”‚                 β”‚
              β”‚  [3] Mixture of Experts       β”‚
              β”‚      4 expert sub-networks    β”‚
              β”‚      Learned gating function  β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚  Test-Time Augmentation (TTA) β”‚
              β”‚  3-vote ensemble inference    β”‚
              β”‚  (clean + rotated + zoomed)   β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
─────────────────────────────────────────────────────────────
        Diagnosis + CAM Heatmap + Confidence Score
─────────────────────────────────────────────────────────────

🎨 Modern SPA Frontend & Clinical Dashboard

NeuroScan features a high-performance, single-page application (SPA) built with Vanilla JS and CSS, designed for rapid clinical decision support. The interface connects seamlessly to the Flask REST API to provide real-time diagnostics and system monitoring.

🏠 Main Workstation (Dashboard)

The central hub for clinical operations, providing a high-level overview of engine status, API connectivity, and recent diagnostic activity. Dashboard

πŸ”¬ Diagnostic Pipeline

A deep-dive view into the 3-stage analysis: Original Scan β†’ OmniChaos Attack β†’ Shielded Recovery. Radiologists can verify the AI's robustness before confirming a diagnosis. Diagnostic Pipeline

πŸ—‚οΈ Batch Auditor

Designed for large-scale clinical audits, the Batch Auditor processes ZIP archives of MRI scans, generating comprehensive performance metrics and match-confidence reports. Batch Auditor

πŸ“Š AI Insights & Ecosystem

Real-time tracking of anomaly detection rates, engine efficiency, and dataset metrics. This module ensures the model is performing within clinical safety parameters. AI Insights

πŸ‘₯ Clinical Repository (Patient Records)

A secure management system for neurological profiles, allowing physicians to search, filter, and review historical scan results. Patient Records

πŸ“œ System Audit Log

An immutable ledger of every system interaction, from user logins to parameter overrides, ensuring full clinical accountability and traceability. Audit Log

βš™οΈ Engine Control Center (System Config)

Advanced configuration for the Neural Core, allowing real-time adjustment of AI sensitivity profiles and operational protocols. System Config


πŸ“Š Experiment Results

The system was developed through 5 iterative experiments, each with a hypothesis, architecture change, results, and analysis:

# Architecture Val Acc Clean Test Under Attack Shielded Recovery
1 MobileNetV2 + Median Filter 80.9% 66% 38% 58%
2 Xception (overfitting) 73.3% 56% 42% 42%
3 MobileNetV2 + CLAHE Fine-tune 91.8% β€” β€” β€”
4 v3 Robustness Validation β€” 74% 42% 70%
5 βœ… MobileNetV2 + Heavy Aug (Champion) 92.7% 96% 40% 96%

Training Performance - Xception Model Xception Performance

Training Performance - v3 Booster Model Final v3 Performance

Key Insight

The Fourier-based K-Space attack intentionally drops accuracy to ~40% by targeting the frequency domain directly. The FourierHealer restores performance to 96% baseline by applying a surgical band-stop mask β€” proving that domain-aware defenses are essential for real-world medical AI robustness.


πŸ–ΌοΈ Demo Screenshots

Clean MRI Signal Attack Shielded Recovery
Original diagnostic scan OmniChaos 7-layer corruption Defense pipeline restored

Adversarial Attack Comparison

Pituitary Tumor Prediction
Pituitary Tumor β€” 99.5% confidence after adversarial recovery

Meningioma Prediction
Meningioma β€” 93.4% confidence with visible tumor mass in CAM focus area

No Tumor Prediction
No Tumor β€” 99.9% confidence on clean healthy scan


πŸ”‘ Key Technical Highlights for Judges

  1. Custom architecture from scratch β€” HybridChimeraAI is not a fine-tuned pretrained model; it combines spatial feature extraction (CNN), global context (Transformer), and specialized decision-making (MoE) in a single unified forward pass.

  2. Physics-grounded attack simulation β€” The K-Space attack is based on actual MRI hardware failure modes (frequency-domain spike artifacts), not random pixel noise. This makes it a clinically meaningful robustness test.

  3. Domain-matched defenses β€” VisualHealer and FourierHealer are paired to match the specific attack type, demonstrating that defense mechanisms must be designed based on the signal degradation domain.

  4. Iterative scientific methodology β€” The experiment log documents 5 complete training runs with hypothesis, architecture change, results, and analysis β€” following standard ML research practice.

  5. Full-stack deployment β€” The project ships with a Flask REST API, a Streamlit multi-module diagnostic workstation, a Gradio app, and a Vanilla JS SPA frontend β€” ready for end-to-end evaluation.

  6. Production-ready Batch Auditor β€” the Streamlit Batch Auditor accepts ZIP uploads of patient scans, produces per-image predictions and a Plotly confusion matrix β€” suitable for radiologist-style workflow evaluation.


⚠️ Disclaimer

This project is a research prototype developed for academic and hackathon purposes. It is not intended for clinical diagnosis. All predictions should be reviewed by a qualified medical professional. The adversarial attack simulation is included for robustness research only.


πŸ‘€ Author

Mohd Altamish
B.Tech Computer Science Engineering, GL Bajaj Institute of Technology and Management (2025–2029)
LinkedIn: Mohd-Altamish
GitHub: @MohdAltamish


πŸ“„ License

This project is licensed under the MIT License. See LICENSE for details.

About

An AI-powered diagnostic tool that classifies brain MRI scans and automatically heals signal interference and noise.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors