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
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:
.edf (medical), .csv, and .txt EEG file formatsflowchart 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
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
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
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 |
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
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.
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
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.
| 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 |
git clone https://github.com/ScriptOrbit-132/EEG-Signals.git
cd EEG-Signals
pip install -r requirements.txt
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
========================================================
Navigate to http://localhost:5000 and login:
DEMO_CLINICNS2026| 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.
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
POST /api/auth
Content-Type: application/json
{ "practice_id": "DEMO_CLINIC", "key": "NS2026" }
POST /api/predict
Content-Type: application/json
X-Auth-Token: <token>
{ "signal_data": [[...22 channels...]], "patient_id": "patient_001" }
POST /api/predict
Content-Type: multipart/form-data
X-Auth-Token: <token>
file: eeg_recording.edf
GET /api/demo-signal/{normal|preictal|seizure|postictal}
GET /api/health
CHB-MIT Scalp EEG Database (PhysioNet):
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.
| 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 |
MIT License โ see LICENSE for details.
Built with ๐ง by ScriptOrbit