Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

28 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿง  NeuroScan โ€” Epileptic Seizure Detection System

A real-time, AI-powered EEG analysis platform for epileptic seizure detection using a hybrid CNN-Transformer architecture with Continuous Wavelet Transform (CWT) feature engineering.

Overview โ€ข Architecture โ€ข Pipeline โ€ข Model โ€ข Quick Start โ€ข API โ€ข Dataset


๐Ÿ“Œ Overview

NeuroScan is an end-to-end clinical-grade EEG analysis system that classifies brain signals into four neurological states in real time:

State Description Clinical Significance
๐ŸŸข Normal Healthy background cortical activity No intervention required
๐ŸŸก Preictal Pre-seizure warning phase Alert clinician, prepare rescue medication
๐Ÿ”ด Seizure (Ictal) Active epileptic seizure event Immediate clinical response required
๐ŸŸ  Postictal Post-seizure recovery state Monitor for secondary events

Key Features:

  • ๐Ÿ”ฌ Real CNN-Transformer hybrid model trained on CHB-MIT Scalp EEG Database
  • ๐ŸŒŠ Continuous Wavelet Transform (CWT) scalogram visualization
  • ๐Ÿ“‹ Auto-generated clinical reports with confidence scoring
  • ๐Ÿ” Session-based clinician authentication (8-hour tokens)
  • ๐Ÿ“ Supports .edf (medical), .csv, and .txt EEG file formats
  • ๐ŸŽฎ Built-in demo mode with synthetic signals for all 4 seizure states

๐Ÿ— High-Level Architecture

flowchart TD
    subgraph INPUT["๐Ÿ“ฅ  INPUT SOURCES"]
        A1["๐Ÿ—‚๏ธ EDF File\n(.edf medical format)"]
        A2["๐Ÿ“„ CSV / TXT File"]
        A3["๐Ÿ”ด Live Demo Signal\n(Normal / Preictal / Seizure / Postictal)"]
        A4["๐Ÿ“ก JSON API Call"]
    end

    subgraph S1["โš™๏ธ  STAGE 1 โ€” Signal Preprocessing"]
        B1["Notch Filter\n60 Hz removal"]
        B2["Bandpass Filter\n0.5 โ€“ 50 Hz"]
        B3["Epoch Extraction\n2s windows @ 256 Hz"]
        B4["Artifact Rejection\n> 300 ยตV discarded"]
        B5["Z-Score Normalization\nper channel"]
    end

    subgraph S2["๐ŸŒŠ  STAGE 2 โ€” CWT Feature Engineering"]
        C1["Complex Morlet Wavelet\ncmor1.5-1.0"]
        C2["Scalogram Generation\n22 ch ร— 50 freq ร— 512 time"]
        C3["PNG Heatmaps\n(base64, for dashboard)"]
    end

    subgraph S3["๐Ÿค–  STAGE 3 โ€” CNN-Transformer Model"]
        D1["2D CNN Blocks\nSpatial Feature Extraction"]
        D2["Reshape Bridge\nโ†’ Sequence of 128 time steps"]
        D3["Transformer Encoder\n2 layers ยท 8 heads ยท d=768"]
        D4["Classifier Head\nSoftmax โ†’ 4 classes"]
    end

    subgraph S4["๐Ÿ“‹  STAGE 4 โ€” Clinical Output"]
        E1["Prediction Label\n+ Confidence Scores"]
        E2["Medical Report\nAuto-generated notes"]
        E3["Clinical Dashboard\nLive waveform ยท Scalograms"]
    end

    A1 & A2 & A3 & A4 --> B1
    B1 --> B2 --> B3 --> B4 --> B5
    B5 --> C1 --> C2 --> C3
    C2 --> D1 --> D2 --> D3 --> D4
    D4 --> E1
    C3 --> E3
    E1 --> E2 --> E3
Loading

๐Ÿ”„ Data Flow

sequenceDiagram
    actor C as ๐Ÿ‘จโ€โš•๏ธ Clinician
    participant D as ๐Ÿ–ฅ๏ธ Dashboard
    participant A as ๐Ÿ Flask API
    participant M as ๐Ÿค– CNN-Transformer

    C->>D: Login (Practice ID + Key)
    D->>A: POST /api/auth
    A-->>D: Session Token (8 hr)

    C->>D: Click "Seizure" demo button
    D->>A: GET /api/demo-signal/seizure
    A-->>D: Synthetic 22ch ร— 512 EEG signal

    D->>A: POST /api/predict
    Note over A: Stage 1 โ€” Notch ยท Bandpass ยท Epoch ยท Z-Score
    Note over A: Stage 2 โ€” CWT โ†’ (22, 50, 512) scalogram
    A->>M: Forward pass
    Note over M: CNN โ†’ Transformer โ†’ Softmax
    M-->>A: [0.01, 0.01, 0.97, 0.01]
    Note over A: Stage 4 โ€” Generate clinical report

    A-->>D: prediction + confidences + scalograms + notes
    D-->>C: Dashboard updates in real time
Loading

๐Ÿ”ฌ Pipeline Stages

Stage 1 โ€” Data Ingestion & Signal Preprocessing

flowchart LR
    RAW["Raw EEG\n22ch ร— N samples\n(ยตV)"]
    N["Notch Filter\n60 Hz IIR\nRemoves power-line noise"]
    BP["Bandpass Filter\n0.5โ€“50 Hz Butterworth 4th order\nRetains brain frequencies"]
    EP["Epoch Extraction\n2s sliding window ยท 512 samples\n50% overlap"]
    AR["Artifact Rejection\nRejects epochs > 300 ยตV\n(muscle/electrode pop)"]
    ZS["Z-Score Normalization\nMean=0 ยท Std=1\nper channel"]
    OUT["Clean Epoch\n22 ร— 512"]

    RAW --> N --> BP --> EP --> AR --> ZS --> OUT
Loading

Supported Input Formats:

Format Parser Use Case
.edf MNE-Python Medical EEG files (European Data Format)
.csv / .txt Built-in CSV reader Exported recordings, research data
JSON body Direct API input Real-time streaming, integrations
Demo button Synthetic generator Testing & demonstration

Stage 2 โ€” CWT Scalogram Generation

flowchart LR
    SIG["1D Signal\nper channel\n512 samples"]
    CWT["Complex Morlet CWT\ncmor1.5-1.0\n1โ€“50 Hz ยท 50 bins"]
    SCALO["2D Scalogram\n50 freq ร— 512 time\nper channel"]
    TENSOR["Final Tensor\n22 ร— 50 ร— 512\nall channels"]
    PNG["PNG Heatmaps\nbase64 encoded\nfor dashboard"]

    SIG --> CWT --> SCALO
    SCALO -->|"ร—22 channels"| TENSOR
    TENSOR --> PNG
Loading

Why CWT? Raw EEG is a noisy 1D voltage trace. The CWT decomposes it into a 2D frequency-time heatmap where seizure-specific patterns โ€” rhythmic 3โ€“8 Hz bursts and spike-wave complexes โ€” become visually distinct and far easier for the CNN to detect.


Stage 3 โ€” CNN-Transformer Hybrid Model

flowchart TD
    IN["Input Tensor\nBatch ร— 22 ร— 50 ร— 512\n22ch ยท 50 freq bins ยท 512 time"]

    subgraph CNN["๐Ÿ–ผ๏ธ  2D CNN โ€” Spatial Feature Extraction"]
        C1["Conv2D 22โ†’32 ยท BatchNorm ยท ReLU\nMaxPool 2ร—2\nโ†’ Batch ร— 32 ร— 25 ร— 256"]
        C2["Conv2D 32โ†’64 ยท BatchNorm ยท ReLU\nMaxPool 2ร—2\nโ†’ Batch ร— 64 ร— 12 ร— 128"]
    end

    BRIDGE["๐Ÿ”€ Reshape Bridge\nPermute + Flatten\nโ†’ Batch ร— 128 timesteps ร— 768 features"]

    subgraph TF["โšก  Transformer Encoder โ€” Temporal Attention"]
        T1["Self-Attention Layer 1\n8 heads ยท d_model=768"]
        T2["Self-Attention Layer 2\n8 heads ยท d_ff=2048"]
    end

    POOL["๐Ÿ“‰ Global Average Pooling\nMean over 128 timesteps\nโ†’ Batch ร— 768"]

    subgraph CLS["๐ŸŽฏ  Classifier Head"]
        L1["Linear 768โ†’256 ยท ReLU ยท Dropout 50%"]
        L2["Linear 256โ†’4 ยท Softmax"]
    end

    OUT["Output\n4 Class Probabilities\nNormal ยท Preictal ยท Seizure ยท Postictal"]

    IN --> C1 --> C2 --> BRIDGE --> T1 --> T2 --> POOL --> L1 --> L2 --> OUT
Loading

Training Details:

Parameter Value
Dataset CHB-MIT Scalp EEG Database (24 pediatric patients)
Optimizer AdamW ยท lr=1e-4 ยท weight_decay=1e-2
Scheduler ReduceLROnPlateau ยท factor=0.5 ยท patience=3
Loss Cross-Entropy with class weights [0.1, 0.4, 0.9, 0.4]
Regularization Dropout 50% ยท BatchNorm ยท weight decay
Precision Mixed FP16 (AMP on GPU)

Why class weighting? In real EEG data, seizures are <1% of recording time. Without weighting the model just predicts "Normal" always and still gets 99% accuracy โ€” being clinically useless. Heavier weight on seizure class forces the model to focus on rare events.


Stage 4 โ€” Clinical Dashboard & Output

Output Description
Classification Top predicted class with confidence %
Confidence Scores Full probability distribution across all 4 classes
CWT Scalograms Heatmap images from channels FP1-F7 and C3-P3
Signal Preview 512-point raw waveform for visual inspection
Medical Report Auto-generated clinical notes with recommended actions
Inference Time End-to-end pipeline latency in milliseconds

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.10+
  • pip

1. Clone the Repository

git clone https://github.com/ScriptOrbit-132/EEG-Signals.git
cd EEG-Signals

2. Install Dependencies

pip install -r requirements.txt

3. Run the Server

python code/app.py

You should see:

========================================================
  NeuroScan EEG Analysis API - v1.0
  Model mode : real
  Classes    : ['Normal', 'Preictal', 'Seizure (Ictal)', 'Postictal']
  -------------------------------------------------
  Demo credentials:
    DEMO_CLINIC          -> key: NS2026
    chb_research         -> key: CHB_MIT_001
    neuroscan_dev        -> key: DEV_9999
  -------------------------------------------------
  Open: http://localhost:5000
========================================================

4. Open the Dashboard

Navigate to http://localhost:5000 and login:

  • Practice ID: DEMO_CLINIC
  • Access Key: NS2026

๐ŸŽฎ Demo

Button Simulates Expected Confidence
๐ŸŸข Normal Healthy resting-state EEG ~97% Normal
๐ŸŸก Preictal Pre-seizure warning signals ~89% Preictal
๐Ÿ”ด Seizure Active ictal event with spike-wave bursts ~97% Seizure
๐ŸŸ  Postictal Post-seizure delta slowing ~93% Postictal

File Upload: Drag-and-drop a .edf, .csv, or .txt file for real inference against the trained model.


๐Ÿ“ Project Structure

EEG-Signals/
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ neuroscan_dashboard.html       # Frontend โ€” clinical dashboard UI
โ”œโ”€โ”€ ๐Ÿง  backend_model_completed.pt     # Pre-trained model weights (~45 MB)
โ”œโ”€โ”€ ๐Ÿ“Š processed_metadata.csv         # Training data index mapping
โ”œโ”€โ”€ ๐Ÿ“ฆ requirements.txt               # Python dependencies
โ”œโ”€โ”€ ๐Ÿ“– README.md                      # This file
โ”œโ”€โ”€ ๐Ÿ“‹ SETUP.md                       # Quick setup guide
โ”‚
โ””โ”€โ”€ code/
    โ”œโ”€โ”€ ๐Ÿ app.py                     # Flask API โ€” all 4 pipeline stages
    โ”œโ”€โ”€ ๐Ÿค– model.py                   # EEG_2D_Hybrid_Model definition
    โ”œโ”€โ”€ ๐ŸŒŠ preprocess_features.py     # CWT feature extraction (train + inference)
    โ”œโ”€โ”€ ๐Ÿ”ง preprocess_seizure_only.py # Targeted seizure data preprocessor
    โ”œโ”€โ”€ ๐Ÿ” find_hardest_seizure.py    # Edge case seizure locator
    โ”œโ”€โ”€ ๐Ÿงช test_manual_seizure.py     # Model accuracy verification
    โ”œโ”€โ”€ ๐Ÿ“ˆ train_full.py              # Full training pipeline
    โ”œโ”€โ”€ โšก train_optimized.py          # Memory-optimized training
    โ”œโ”€โ”€ ๐Ÿ”„ run_pipeline.py            # End-to-end pipeline runner
    โ”œโ”€โ”€ ๐Ÿ“Š resource_monitor.py        # Hardware safety guard
    โ”œโ”€โ”€ โš™๏ธ training_config.yaml       # Resource threshold config
    โ””โ”€โ”€ ๐ŸŒ render.yaml                # Render.com deployment config

๐Ÿ”Œ API Reference

Authentication

POST /api/auth
Content-Type: application/json

{ "practice_id": "DEMO_CLINIC", "key": "NS2026" }

Predict โ€” JSON

POST /api/predict
Content-Type: application/json
X-Auth-Token: <token>

{ "signal_data": [[...22 channels...]], "patient_id": "patient_001" }

Predict โ€” File Upload

POST /api/predict
Content-Type: multipart/form-data
X-Auth-Token: <token>

file: eeg_recording.edf

Demo Signal

GET /api/demo-signal/{normal|preictal|seizure|postictal}

Health Check

GET /api/health

๐Ÿงฌ Dataset

CHB-MIT Scalp EEG Database (PhysioNet):

  • 24 pediatric patients with intractable epilepsy
  • 22-channel EEG (international 10-20 system)
  • 256 Hz sampling rate ยท ~983 hours ยท 198 annotated seizures
FP1-F7  F7-T7  T7-P7  P7-O1  FP1-F3  F3-C3  C3-P3  P3-O1
FP2-F4  F4-C4  C4-P4  P4-O2  FP2-F8  F8-T8  T8-P8  P8-O2
FZ-CZ   CZ-PZ  P7-T7  T7-FT9 FT9-FT10 FT10-T8

Shoeb, A. H. (2009). Application of Machine Learning to Epileptic Seizure Onset Detection and Treatment. PhD Thesis, MIT.


โš™๏ธ Tech Stack

Layer Technology Role
Backend Flask 3.0+ REST API server
Frontend HTML / CSS / JS Clinical dashboard UI
Deep Learning PyTorch 2.2+ CNN-Transformer model
Signal Processing SciPy IIR / Butterworth filters
Wavelet Transform PyWavelets CWT scalogram generation
EEG Parsing MNE-Python Medical EDF file reader
Visualization Matplotlib Scalogram PNG rendering
Deployment Gunicorn + Render Production WSGI server

๐Ÿ“š References

  1. Abiyev, R. et al. (2020). Identification of Epileptic EEG Signals Using CNN. Applied Sciences, 10(12), 4089.
  2. Shoeb, A. H. (2009). Application of Machine Learning to Epileptic Seizure Onset Detection and Treatment. PhD Thesis, MIT.
  3. Goldberger, A. et al. (2000). PhysioBank, PhysioToolkit, and PhysioNet. Circulation, 101(23), e215โ€“e220.

๐Ÿ“œ License

MIT License โ€” see LICENSE for details.


Built with ๐Ÿง  by ScriptOrbit

About

๐Ÿง  AI-powered EEG analysis platform for real-time epileptic seizure detection using CWT feature engineering and a hybrid CNN-Transformer deep learning architecture. โšก๐Ÿ“Š Built with PyTorch, Flask & MNE-Python.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages