timflash commited on
Commit
2fd14d8
·
1 Parent(s): 97e6f07

Rebuild commit without large PDF

Browse files
Files changed (10) hide show
  1. .gitattributes +4 -0
  2. README.md +80 -11
  3. faiss_index/index.faiss +3 -0
  4. faiss_index/index.pkl +3 -0
  5. knowledge/eeg_sig_proc.pdf +3 -0
  6. main.py +146 -0
  7. processing.py +179 -0
  8. rag.py +133 -0
  9. requirements.txt +20 -0
  10. visuals.py +123 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ knowledge/kcc-sleeptextbook-print.pdf filter=lfs diff=lfs merge=lfs -text
37
+ faiss_index/index.faiss filter=lfs diff=lfs merge=lfs -text
38
+ faiss_index/index.pkl filter=lfs diff=lfs merge=lfs -text
39
+ knowledge/eeg_sig_proc.pdf filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,14 +1,83 @@
 
 
 
 
 
1
  ---
2
- title: NeuroNap
3
- emoji: 🐠
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: 'NeuroNap: EEG-based sleep analysis tool'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🧠 NeuroNap
2
+
3
+ **NeuroNap** is an EEG-based sleep analysis tool that processes EEG CSV files to analyze sleep stages, generate hypnograms, visualize frequency spectra, and provide LLM-driven insights using **Gemini**.
4
+ Built with **Python** and **Gradio**, it uses **YASA** for sleep stage classification and **HMM** for clustering and offers an interactive interface for researchers and clinicians studying sleep patterns.
5
+
6
  ---
7
+
8
+ ## 🚀 Features
9
+
10
+ - **EEG Processing:**
11
+ Processes raw EEG CSV files using **bandpass** and **notch filters** to remove noise and artifacts, ensuring clean, reliable signal data.
12
+
13
+ - **Sleep Stage Classification:**
14
+ Utilizes **YASA** (Yet Another Sleep Analysis) to automatically classify sleep stages — **W, N1, N2, N3, and REM** — and compute essential sleep metrics such as **Total Sleep Time (TST)**, **Sleep Efficiency (SE)**, and **Wake After Sleep Onset (WASO)**.
15
+
16
+ - **Clustering:**
17
+ Applies **Hidden Markov Models (HMM)** to cluster EEG-derived features, revealing latent patterns and transitions across sleep stages.
18
+
19
+ - **Visualizations:**
20
+ Generates detailed plots for **EEG signals**, **hypnograms**, **frequency spectra**, and **band-specific waveforms**, allowing for intuitive data interpretation.
21
+
22
+ - **Sleep Statistics:**
23
+ Displays comprehensive sleep metrics (e.g., **Total Sleep Time**, **Sleep Efficiency**) with expandable tables showing additional parameters like **Time in Bed (TIB)**, **Sleep Period Time (SPT)**, and **latencies**.
24
+
25
+ - **LLM Insights:**
26
+ Integrates **Gemini** via **LangChain** for natural language interaction, using a **FAISS vector store** for context-aware sleep data insights.
27
+
28
+ - **Exportable Outputs:**
29
+ Enables easy download of results in **CSV** format (clean EEG, extracted features, clusters) and **PDF** format (visual reports and plots).
30
+
31
+
32
  ---
33
 
34
+ ## ⚙️ Installation
35
+
36
+ ```bash
37
+ # Clone the repository
38
+ git clone https://github.com/yourusername/NeuroNap.git
39
+ cd NeuroNap
40
+
41
+ # Create a virtual environment
42
+ python -m venv venv
43
+
44
+ # Activate the environment
45
+ source venv/bin/activate # On Windows: venv\Scripts\activate
46
+
47
+ # Install dependencies
48
+ pip install -r requirements.txt
49
+ ```
50
+
51
+ 🔑 **API Setup**
52
+ Set your Gemini API key in a `.env` file:
53
+ ```bash
54
+ echo "GEMINI_API_KEY=your_api_key" > .env
55
+ ```
56
+
57
+ 🧩 **Knowledge Embeddings**
58
+
59
+ Before running the app, generate embeddings from your knowledge PDFs:
60
+
61
+ ```bash
62
+ python rag.py
63
+ ```
64
+ Place relevant research papers or notes in the knowledge/ folder before running the above command.
65
+
66
+ 🖥️ **Usage**
67
+
68
+ Launch the Gradio interface:
69
+ ```bash
70
+ python main.py
71
+ ```
72
+ Then:
73
+
74
+ 1. **Upload** an EEG CSV file (e.g., `EEGDATA.csv`).
75
+ 2. **View** sleep stage visualizations, HMM clusters, and frequency spectra.
76
+ 3. **Interact** with the **"Chat with NeuroNap"** feature to get context-aware insights.
77
+ 4. **Download** processed data and reports in **CSV** or **PDF** format.
78
+
79
+ ## 📦 Requirements
80
+
81
+ - **Python 3.9+**
82
+ - See `requirements.txt` for the full dependency list
83
+
faiss_index/index.faiss ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f582048dd219190525d0df43072f7dbbc125963dd429eb92acaa45cc0f8b0c2
3
+ size 1379373
faiss_index/index.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b7c9149372c508c2578ed9d0507107989e8e8ebd45717fe9ad51d7830278762
3
+ size 928310
knowledge/eeg_sig_proc.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:566380955227b608de4fdc0fdd7e93ba85d11ed34c11e8b97fbd6301e78a5a44
3
+ size 3598747
main.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from processing import process_eeg
4
+ from visuals import plot_eeg_signals, plot_hypnogram, plot_frequency_spectra, plot_band_waveforms
5
+ from rag import setup_rag, chat_with_llm, update_vectorstore_with_user_results
6
+ import os
7
+ import logging
8
+
9
+ # Configure logger
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(levelname)s - %(message)s',
13
+ handlers=[
14
+ logging.FileHandler('neuronap.log'),
15
+ logging.StreamHandler()
16
+ ]
17
+ )
18
+ logger = logging.getLogger(__name__)
19
+
20
+ def analyze_eeg(file):
21
+ logger.info("Starting EEG analysis")
22
+ if file is None:
23
+ logger.error("No CSV file uploaded")
24
+ raise ValueError("No CSV file uploaded.")
25
+ file_path = file.name
26
+ logger.info(f"Processing file: {file_path}")
27
+ eeg_uv, eeg_uv_bp, eeg_uv_notched, hypno, stats, features_df, hmm_labels, fs, time_s = process_eeg(file_path)
28
+ logger.info("EEG processing completed")
29
+ signals_img = plot_eeg_signals(time_s, eeg_uv, eeg_uv_bp, eeg_uv_notched)
30
+ hypno_img = plot_hypnogram(hypno)
31
+ spectra_img = plot_frequency_spectra(eeg_uv_notched, fs)
32
+ bands_img = plot_band_waveforms(eeg_uv_notched, fs)
33
+
34
+ # Define key metrics with human-readable names for interface preview
35
+ key_metrics = {
36
+ 'TST': 'Total Sleep Time (minutes)',
37
+ 'SE': 'Sleep Efficiency (%)',
38
+ 'REM': 'REM Sleep (minutes)',
39
+ 'N3': 'Deep Sleep (N3) (minutes)',
40
+ 'WASO': 'Wake After Sleep Onset (minutes)'
41
+ }
42
+
43
+ # Format stats preview for interface default view
44
+ stats_preview = {k: stats.get(k) for k in key_metrics.keys() if k in stats}
45
+ stats_preview_str = "\n".join([
46
+ f"• {key_metrics[k]}: {v:.2f} {'%' if k in ['SE', '%N1', '%N2', '%N3', '%REM', '%NREM', 'SME'] else 'minutes'}"
47
+ for k, v in stats_preview.items()
48
+ ])
49
+
50
+ # Format full stats for user_results.txt
51
+ stats_full_str = "\n".join([
52
+ f"• {k.replace('_', ' ').title()}: {v:.2f} {'%' if k in ['SE', '%N1', '%N2', '%N3', '%REM', '%NREM', 'SME'] else 'minutes'}"
53
+ for k, v in stats.items()
54
+ ])
55
+
56
+ # Full stats table for interface expanded view
57
+ stats_full = pd.DataFrame(list(stats.items()), columns=['Metric', 'Value']).to_html(classes='stats-table', index=False)
58
+
59
+ # Include full stats in user_results for saving to file
60
+ user_results = f"Sleep Statistics:\n{stats_full_str}\nHypnogram: {hypno}\n"
61
+ logger.info("Updating vectorstore with user results")
62
+ vectorstore = update_vectorstore_with_user_results(user_results)
63
+ qa_chain = setup_rag()
64
+
65
+ # Generate previews and full tables for features and clusters
66
+ features_preview = features_df.head(5).to_html(classes='compact-table')
67
+ features_full = features_df.to_html(classes='compact-table')
68
+ clusters_preview = pd.DataFrame({'Cluster': hmm_labels}).head(5).to_html(classes='compact-table')
69
+ clusters_full = pd.DataFrame({'Cluster': hmm_labels}).to_html(classes='compact-table')
70
+
71
+ logger.info("Analysis completed, returning outputs")
72
+ return (
73
+ signals_img, hypno_img, spectra_img, bands_img, stats_preview_str, stats_full,
74
+ features_preview, features_full, clusters_preview, clusters_full,
75
+ qa_chain,
76
+ "clean_eeg.csv", "features.csv", "eeg_clusters.csv",
77
+ "eeg_signal_plot.pdf", "hypnogram_plot.pdf", "eeg_fft_welch.pdf", "eeg_bands_plot.pdf"
78
+ )
79
+
80
+ def handle_chat(query, qa_chain):
81
+ logger.info(f"Handling chat query: {query}")
82
+ if not query or qa_chain is None:
83
+ logger.warning("Invalid query or no QA chain available")
84
+ return "Please analyze an EEG file first and provide a query."
85
+ return chat_with_llm(query, qa_chain)
86
+
87
+ with gr.Blocks(title="NeuroNap", css=".compact-table { font-size: 12px; max-height: 300px; overflow-y: auto; } .stats-table { font-size: 14px; border-collapse: collapse; width: 50%; } .stats-table th, .stats-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }") as demo:
88
+ logger.info("Initializing Gradio interface")
89
+ qa_chain_state = gr.State(None)
90
+ gr.Markdown("# NeuroNap: EEG Sleep Monitoring System")
91
+ with gr.Column():
92
+ with gr.Row():
93
+ file_input = gr.File(label="Upload EEG CSV (e.g., EEGDATA.CSV)")
94
+ analyze_btn = gr.Button("Analyze")
95
+ with gr.Row():
96
+ signals_output = gr.Image(label="EEG Signals")
97
+ hypno_output = gr.Image(label="Hypnogram")
98
+ with gr.Row():
99
+ spectra_output = gr.Image(label="Frequency Spectra")
100
+ bands_output = gr.Image(label="Frequency Bands")
101
+ with gr.Group():
102
+ gr.Markdown("### Sleep Statistics")
103
+ stats_preview_output = gr.Textbox(label="Key Sleep Statistics")
104
+ with gr.Accordion("Show All Sleep Statistics", open=False):
105
+ stats_full_output = gr.HTML(label="Full Statistics")
106
+ with gr.Group():
107
+ gr.Markdown("### Extracted Features")
108
+ features_preview_output = gr.HTML(label="Features Preview")
109
+ with gr.Accordion("Show Full Features Table", open=False):
110
+ features_full_output = gr.HTML(label="Full Features")
111
+ with gr.Group():
112
+ gr.Markdown("### HMM Clusters")
113
+ clusters_preview_output = gr.HTML(label="Clusters Preview")
114
+ with gr.Accordion("Show Full Clusters Table", open=False):
115
+ clusters_full_output = gr.HTML(label="Full Clusters")
116
+ with gr.Group():
117
+ gr.Markdown("### Chat with NeuroNap")
118
+ chat_input = gr.Textbox(label="Ask about your sleep data", lines=2)
119
+ chat_btn = gr.Button("Send")
120
+ chat_output = gr.Textbox(label="LLM Response", lines=4)
121
+ with gr.Group():
122
+ gr.Markdown("### Downloads")
123
+ with gr.Row():
124
+ clean_csv = gr.File(label="Download clean_eeg.csv")
125
+ features_csv = gr.File(label="Download features.csv")
126
+ clusters_csv = gr.File(label="Download eeg_clusters.csv")
127
+ with gr.Row():
128
+ signals_pdf = gr.File(label="Download eeg_signal_plot.pdf")
129
+ hypno_pdf = gr.File(label="Download hypnogram_plot.pdf")
130
+ spectra_pdf = gr.File(label="Download eeg_fft_welch.pdf")
131
+ bands_pdf = gr.File(label="Download eeg_bands_plot.pdf")
132
+
133
+ analyze_btn.click(
134
+ analyze_eeg,
135
+ inputs=file_input,
136
+ outputs=[
137
+ signals_output, hypno_output, spectra_output, bands_output,
138
+ stats_preview_output, stats_full_output,
139
+ features_preview_output, features_full_output, clusters_preview_output, clusters_full_output,
140
+ qa_chain_state, clean_csv, features_csv, clusters_csv, signals_pdf, hypno_pdf, spectra_pdf, bands_pdf
141
+ ]
142
+ )
143
+ chat_btn.click(handle_chat, inputs=[chat_input, qa_chain_state], outputs=chat_output)
144
+
145
+ logger.info("Launching Gradio interface")
146
+ demo.launch(share=True)
processing.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from scipy.signal import butter, filtfilt, iirnotch, welch, hilbert
4
+ from scipy.interpolate import interp1d
5
+ import yasa
6
+ import mne
7
+ import antropy as ant
8
+ from sklearn.decomposition import PCA
9
+ from hmmlearn.hmm import GaussianHMM
10
+ from sklearn.preprocessing import StandardScaler
11
+ import logging
12
+ import os
13
+
14
+ # Configure logger
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s - %(levelname)s - %(message)s',
18
+ handlers=[
19
+ logging.FileHandler('neuronap.log'),
20
+ logging.StreamHandler()
21
+ ]
22
+ )
23
+ logger = logging.getLogger(__name__)
24
+
25
+ def butter_bandpass(lowcut, highcut, fs, order=2):
26
+ nyquist = 0.5 * fs
27
+ low = lowcut / nyquist
28
+ high = highcut / nyquist
29
+ b, a = butter(order, [low, high], btype='band')
30
+ logger.info(f"Created bandpass filter: {lowcut}-{highcut} Hz, order={order}")
31
+ return b, a
32
+
33
+ def detect_spindles(epoch, fs, low=12, high=16, threshold=1.0, min_duration=0.3):
34
+ b, a = butter(4, [low/(fs/2), high/(fs/2)], btype='band')
35
+ sig = filtfilt(b, a, epoch)
36
+ env = np.abs(hilbert(sig))
37
+ thresh_val = np.mean(env) + threshold * np.std(env)
38
+ mask = env > thresh_val
39
+ spindle_times = []
40
+ in_spindle = False
41
+ start = 0
42
+ for i, val in enumerate(mask):
43
+ if val and not in_spindle:
44
+ start = i
45
+ in_spindle = True
46
+ elif not val and in_spindle:
47
+ end = i
48
+ if (end - start) / fs >= min_duration:
49
+ spindle_times.append(start)
50
+ in_spindle = False
51
+ logger.info(f"Detected {len(spindle_times)} spindles in epoch")
52
+ return len(spindle_times)
53
+
54
+ def detect_slow_waves(epoch, fs, low=0.5, high=2, threshold=1.0, min_duration=0.2):
55
+ b, a = butter(4, [low/(fs/2), high/(fs/2)], btype='band')
56
+ sig = filtfilt(b, a, epoch)
57
+ amp = np.abs(sig)
58
+ thresh_val = np.mean(amp) + threshold * np.std(amp)
59
+ mask = amp > thresh_val
60
+ slow_wave_times = []
61
+ in_wave = False
62
+ start = 0
63
+ for i, val in enumerate(mask):
64
+ if val and not in_wave:
65
+ start = i
66
+ in_wave = True
67
+ elif not val and in_wave:
68
+ end = i
69
+ if (end - start) / fs >= min_duration:
70
+ slow_wave_times.append(start)
71
+ in_wave = False
72
+ logger.info(f"Detected {len(slow_wave_times)} slow waves in epoch")
73
+ return len(slow_wave_times)
74
+
75
+ def extract_features(epochs, fs):
76
+ logger.info(f"Extracting features from {len(epochs)} epochs")
77
+ features = []
78
+ for ep in epochs:
79
+ f, psd = welch(ep, fs=fs, nperseg=fs*4)
80
+ total_power = np.sum(psd)
81
+ delta = np.sum(psd[(f >= 0.5) & (f < 4)])
82
+ theta = np.sum(psd[(f >= 4) & (f < 8)])
83
+ alpha = np.sum(psd[(f >= 8) & (f < 13)])
84
+ sigma = np.sum(psd[(f >= 12) & (f < 16)])
85
+ beta = np.sum(psd[(f >= 13) & (f < 32)])
86
+ rel_delta = delta / total_power if total_power else 0
87
+ rel_theta = theta / total_power if total_power else 0
88
+ rel_alpha = alpha / total_power if total_power else 0
89
+ rel_sigma = sigma / total_power if total_power else 0
90
+ rel_beta = beta / total_power if total_power else 0
91
+ samp_entropy = ant.sample_entropy(ep)
92
+ spindle_count = detect_spindles(ep, fs)
93
+ slow_wave_count = detect_slow_waves(ep, fs)
94
+ features.append([rel_delta, rel_theta, rel_alpha, rel_sigma, rel_beta, samp_entropy, spindle_count, slow_wave_count])
95
+ feature_names = ['rel_delta', 'rel_theta', 'rel_alpha', 'rel_sigma', 'rel_beta', 'sample_entropy', 'spindle_count', 'slow_wave_count']
96
+ features_df = pd.DataFrame(features, columns=feature_names)
97
+ features_df.to_csv('features.csv', index=False)
98
+ logger.info("Saved features to features.csv")
99
+ return features_df
100
+
101
+ def process_eeg(file_path):
102
+ logger.info(f"Processing EEG file: {file_path}")
103
+ if not os.path.exists(file_path):
104
+ logger.error(f"CSV file not found: {file_path}")
105
+ raise FileNotFoundError(f"CSV file not found: {file_path}")
106
+ df = pd.read_csv(file_path)
107
+ if 'time_ms' not in df.columns or 'adc_value' not in df.columns:
108
+ logger.error("CSV must contain 'time_ms' and 'adc_value' columns")
109
+ raise ValueError("CSV must contain 'time_ms' and 'adc_value' columns")
110
+ adc_values = pd.to_numeric(df['adc_value'], errors='coerce').values
111
+ time_ms = pd.to_numeric(df['time_ms'], errors='coerce').values
112
+ mask = ~np.isnan(adc_values) & ~np.isnan(time_ms)
113
+ adc_values = adc_values[mask]
114
+ time_ms = time_ms[mask]
115
+ logger.info(f"Loaded {len(adc_values)} valid data points")
116
+ v_ref = 3.3
117
+ gain = 15000
118
+ voltage_raw = adc_values * (v_ref / 4095)
119
+ estimated_bias = np.mean(voltage_raw)
120
+ voltage = voltage_raw - estimated_bias
121
+ eeg_uv = voltage * 1e6 / gain
122
+ df_res = pd.DataFrame({'time_ms': time_ms, 'adc_vals': adc_values})
123
+ df_clean = df_res.groupby('time_ms', as_index=False).agg({'adc_vals': 'mean'})
124
+ sample_rate_hz = 256
125
+ delta_ms = 1000 / sample_rate_hz
126
+ min_time = df_clean['time_ms'].min()
127
+ max_time = df_clean['time_ms'].max()
128
+ new_times = np.arange(min_time, max_time + delta_ms, delta_ms)
129
+ interpolator = interp1d(df_clean['time_ms'], df_clean['adc_vals'], kind='linear', fill_value='extrapolate')
130
+ new_adc_vals = interpolator(new_times)
131
+ df_res = pd.DataFrame({'time_ms': new_times, 'adc_vals': new_adc_vals})
132
+ voltage = (df_res['adc_vals'] * (v_ref / 4095)) - estimated_bias
133
+ eeg_uv = voltage * 1e6 / gain
134
+ df_res['time_s'] = df_res['time_ms'] / 1000
135
+ df_res['eeg_uv'] = eeg_uv
136
+ fs = 256.0
137
+ lowcut = 0.5
138
+ highcut = 30.0
139
+ nyquist = 0.5 * fs
140
+ low = lowcut / nyquist
141
+ high = highcut / nyquist
142
+ b, a = butter(2, [low, high], btype='band')
143
+ eeg_uv_bp = filtfilt(b, a, eeg_uv)
144
+ logger.info("Applied bandpass filter (0.5-30 Hz)")
145
+ notch_freq = 50.0
146
+ q = 30.0
147
+ b_notch, a_notch = iirnotch(notch_freq, q, fs)
148
+ eeg_uv_notched = filtfilt(b_notch, a_notch, eeg_uv_bp)
149
+ logger.info("Applied notch filter (50 Hz)")
150
+ clean_eeg = pd.DataFrame({'time_s': df_res['time_s'], 'eeg_uv': eeg_uv, 'eeg_bpf': eeg_uv_bp, 'eeg_notch': eeg_uv_notched})
151
+ clean_eeg.to_csv('clean_eeg.csv', index=False)
152
+ logger.info("Saved clean EEG data to clean_eeg.csv")
153
+ info = mne.create_info(ch_names=['Fz'], sfreq=fs, ch_types=['eeg'])
154
+ raw = mne.io.RawArray(eeg_uv_notched.reshape(1, -1), info)
155
+ sl = yasa.SleepStaging(raw, eeg_name='Fz')
156
+ hypno = sl.predict()
157
+ logger.info("Completed YASA sleep staging")
158
+ epoch_length = int(30 * fs)
159
+ num_epochs = len(eeg_uv_notched) // epoch_length
160
+ epochs = eeg_uv_notched[:num_epochs * epoch_length].reshape(num_epochs, epoch_length)
161
+ features_df = extract_features(epochs, fs)
162
+ scaler = StandardScaler()
163
+ features_scaled = scaler.fit_transform(features_df)
164
+ pca = PCA(n_components=5)
165
+ features_pca = pca.fit_transform(features_scaled)
166
+ logger.info("Applied PCA with 5 components")
167
+ model = GaussianHMM(n_components=5, covariance_type="full", n_iter=2000, tol=1e-6, random_state=42)
168
+ model.fit(features_pca)
169
+ hmm_labels = model.predict(features_pca)
170
+ logger.info("Completed HMM clustering")
171
+ clustered_features = features_df.copy()
172
+ clustered_features['cluster'] = hmm_labels
173
+ clustered_features.to_csv('eeg_clusters.csv', index=False)
174
+ logger.info("Saved clustered features to eeg_clusters.csv")
175
+ hypno_int = yasa.hypno_str_to_int(hypno)
176
+ sf_hyp = 1 / 30
177
+ stats = yasa.sleep_statistics(hypno_int, sf_hyp)
178
+ logger.info("Computed sleep statistics")
179
+ return eeg_uv, eeg_uv_bp, eeg_uv_notched, hypno, stats, features_df, hmm_labels, fs, df_res['time_s'].values
rag.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ from dotenv import load_dotenv
4
+ from langchain_community.document_loaders import PyPDFLoader, TextLoader
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain.chains import RetrievalQA
8
+ from langchain.prompts import PromptTemplate
9
+ from langchain_huggingface import HuggingFaceEmbeddings
10
+ from langchain_google_genai import ChatGoogleGenerativeAI
11
+ import logging
12
+
13
+ # Configure logger
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s - %(levelname)s - %(message)s',
17
+ handlers=[
18
+ logging.FileHandler('neuronap.log'),
19
+ logging.StreamHandler()
20
+ ]
21
+ )
22
+ logger = logging.getLogger(__name__)
23
+
24
+ load_dotenv()
25
+ os.environ["GOOGLE_API_KEY"] = os.getenv("GEMINI_API_KEY", "")
26
+ if not os.environ["GOOGLE_API_KEY"]:
27
+ logger.error("GEMINI_API_KEY not found in .env file")
28
+ raise ValueError("GEMINI_API_KEY not found in .env file")
29
+ logger.info("Loaded environment variables")
30
+
31
+ # Initialize embeddings and text splitter
32
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
33
+ try:
34
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
35
+ logger.info("Initialized sentence-transformers embeddings")
36
+ except Exception as e:
37
+ logger.error(f"Failed to initialize embeddings: {e}")
38
+ raise
39
+
40
+ def create_knowledge_embeddings():
41
+ logger.info("Starting creation of knowledge embeddings")
42
+ knowledge_files = glob.glob("knowledge/*.pdf")
43
+ if not knowledge_files:
44
+ logger.error("No .pdf files found in 'knowledge' folder")
45
+ raise FileNotFoundError("No .pdf files found in 'knowledge' folder.")
46
+
47
+ all_docs = []
48
+ for file_path in knowledge_files:
49
+ try:
50
+ logger.info(f"Loading PDF: {file_path}")
51
+ loader = PyPDFLoader(file_path)
52
+ documents = loader.load()
53
+ texts = text_splitter.split_documents(documents)
54
+ all_docs.extend(texts)
55
+ logger.info(f"Successfully loaded and split {file_path} with {len(texts)} chunks")
56
+ except Exception as e:
57
+ logger.error(f"Error loading {file_path}: {e}")
58
+
59
+ if not all_docs:
60
+ logger.error("No valid documents loaded from knowledge folder")
61
+ raise ValueError("No valid documents loaded from knowledge folder.")
62
+
63
+ logger.info(f"Creating FAISS index with {len(all_docs)} document chunks")
64
+ try:
65
+ vectorstore = FAISS.from_documents(all_docs, embeddings)
66
+ vectorstore.save_local("faiss_index")
67
+ logger.info("FAISS embeddings created and saved to 'faiss_index'")
68
+ except Exception as e:
69
+ logger.error(f"Error creating FAISS index: {e}")
70
+ raise
71
+
72
+ def load_vectorstore():
73
+ logger.info("Loading FAISS vectorstore")
74
+ if not os.path.exists("faiss_index"):
75
+ logger.error("FAISS index not found")
76
+ raise FileNotFoundError("FAISS index not found. Run create_knowledge_embeddings first.")
77
+ vectorstore = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
78
+ logger.info("FAISS vectorstore loaded successfully")
79
+ return vectorstore
80
+
81
+ def update_vectorstore_with_user_results(user_results):
82
+ logger.info("Updating vectorstore with user results")
83
+ vectorstore = load_vectorstore()
84
+ with open("user_results.txt", "w", encoding="utf-8") as f:
85
+ f.write(user_results)
86
+ user_loader = TextLoader("user_results.txt")
87
+ user_docs = user_loader.load()
88
+ user_texts = text_splitter.split_documents(user_docs)
89
+ vectorstore.add_documents(user_texts)
90
+ vectorstore.save_local("faiss_index")
91
+ logger.info("User results added to vectorstore and saved")
92
+ return vectorstore
93
+
94
+ def setup_rag():
95
+ logger.info("Setting up RAG chain")
96
+ try:
97
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0.5)
98
+ logger.info("Initialized Gemini 2.0 Flash LLM")
99
+ except Exception as e:
100
+ logger.error(f"Error initializing LLM: {e}. Check GEMINI_API_KEY or quota")
101
+ raise
102
+ vectorstore = load_vectorstore()
103
+ prompt_template = """\
104
+ You are an expert assistant in EEG-based sleep analysis. Use the provided context from sleep stage definitions, EEG characteristics, and user-specific results to answer the query.
105
+ Context: {context}
106
+ User Query: {question}
107
+ Provide a clear, educational response in plain text, avoiding Markdown symbols (e.g., **, *). Use bullet points (•) for lists and exact values from user data if referenced. Include concise explanations for each metric or finding.
108
+ """
109
+ PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
110
+ qa_chain = RetrievalQA.from_chain_type(
111
+ llm=llm,
112
+ chain_type="stuff",
113
+ retriever=vectorstore.as_retriever(),
114
+ return_source_documents=True,
115
+ chain_type_kwargs={"prompt": PROMPT}
116
+ )
117
+ logger.info("RAG chain setup completed")
118
+ return qa_chain
119
+
120
+ def chat_with_llm(query, qa_chain):
121
+ logger.info(f"Processing query: {query}")
122
+ try:
123
+ result = qa_chain({"query": query})["result"]
124
+ logger.info("Query processed successfully")
125
+ return result
126
+ except Exception as e:
127
+ logger.error(f"Error processing query: {e}")
128
+ return f"Error processing query: {e}. Check GEMINI_API_KEY or quota"
129
+
130
+ if __name__ == "__main__":
131
+ logger.info("Running rag.py as main script")
132
+ os.makedirs("knowledge", exist_ok=True)
133
+ create_knowledge_embeddings()
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ pandas
3
+ numpy
4
+ scipy
5
+ matplotlib
6
+ yasa
7
+ mne
8
+ antropy
9
+ hmmlearn
10
+ scikit-learn
11
+ langchain
12
+ langchain-google-genai
13
+ google-generativeai
14
+ langchain-community
15
+ langchain-huggingface
16
+ faiss-cpu
17
+ python-dotenv
18
+ pillow
19
+ pypdf
20
+ sentence-transformers
visuals.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import numpy as np
3
+ import yasa
4
+ import io
5
+ from PIL import Image
6
+ from processing import butter_bandpass, filtfilt
7
+ import logging
8
+
9
+ # Configure logger
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(levelname)s - %(message)s',
13
+ handlers=[
14
+ logging.FileHandler('neuronap.log'),
15
+ logging.StreamHandler()
16
+ ]
17
+ )
18
+ logger = logging.getLogger(__name__)
19
+
20
+ def plot_eeg_signals(time_s, eeg_uv, eeg_uv_bp, eeg_uv_notched):
21
+ logger.info("Generating EEG signals plot")
22
+ plt.figure(figsize=(12, 8))
23
+ plt.plot(time_s, eeg_uv, label='Raw EEG (µV)', alpha=0.5)
24
+ plt.plot(time_s, eeg_uv_bp, label='Bandpass EEG (0.5-30 Hz)', linewidth=2)
25
+ plt.plot(time_s, eeg_uv_notched, label='Notched EEG (50 Hz)', linewidth=2, linestyle='--')
26
+ plt.title("EEG Signal: Raw vs Filtered", fontsize=42)
27
+ plt.xlabel("Time (s)", fontsize=36)
28
+ plt.ylabel("Amplitude (µV)", fontsize=36)
29
+ plt.xticks(fontsize=28)
30
+ plt.yticks(fontsize=28)
31
+ plt.grid(True)
32
+ plt.legend(fontsize=18.5, loc='upper right') # Explicit loc to avoid warning
33
+ plt.tight_layout()
34
+ plt.savefig("eeg_signal_plot.pdf", format='pdf', dpi=300)
35
+ logger.info("Saved EEG signals plot to eeg_signal_plot.pdf")
36
+ buf = io.BytesIO()
37
+ plt.savefig(buf, format='png')
38
+ buf.seek(0)
39
+ img = Image.open(buf)
40
+ plt.close()
41
+ return img
42
+
43
+ def plot_frequency_spectra(eeg_uv_notched, fs):
44
+ logger.info("Generating frequency spectra plot")
45
+ from scipy.signal import welch
46
+ f_welch, psd_welch = welch(eeg_uv_notched, fs, nperseg=1024, noverlap=512)
47
+ plt.figure(figsize=(12, 12))
48
+ plt.subplot(2,1,1)
49
+ n = len(eeg_uv_notched)
50
+ freqs_fft = np.fft.fftfreq(n, d=1/fs)
51
+ fft_magnitude = np.abs(np.fft.fft(eeg_uv_notched)) / n
52
+ plt.plot(freqs_fft[:n//2], fft_magnitude[:n//2] * 2, linewidth=2)
53
+ plt.title("FFT Spectrum", fontsize=28)
54
+ plt.xlabel("Frequency (Hz)", fontsize=24)
55
+ plt.ylabel("Magnitude (µV)", fontsize=24)
56
+ plt.grid(True)
57
+ plt.subplot(2,1,2)
58
+ plt.semilogy(f_welch, psd_welch, linewidth=2)
59
+ plt.title("Welch PSD", fontsize=28)
60
+ plt.xlabel("Frequency (Hz)", fontsize=24)
61
+ plt.ylabel("Power/Frequency (µV²/Hz)", fontsize=24)
62
+ plt.grid(True)
63
+ plt.tight_layout()
64
+ plt.savefig("eeg_fft_welch.pdf", format='pdf', dpi=300)
65
+ logger.info("Saved frequency spectra plot to eeg_fft_welch.pdf")
66
+ buf = io.BytesIO()
67
+ plt.savefig(buf, format='png')
68
+ buf.seek(0)
69
+ img = Image.open(buf)
70
+ plt.close()
71
+ return img
72
+
73
+ def plot_band_waveforms(eeg_uv_notched, fs, start_s=3000, end_s=3020):
74
+ logger.info("Generating frequency bands plot")
75
+ time_s = np.arange(len(eeg_uv_notched)) / fs
76
+ mask = (time_s >= start_s) & (time_s <= end_s)
77
+ window = eeg_uv_notched[mask]
78
+ time_window = time_s[mask]
79
+ eeg_delta = filtfilt(*butter_bandpass(0.5, 4, fs), window)
80
+ eeg_theta = filtfilt(*butter_bandpass(4, 8, fs), window)
81
+ eeg_alpha = filtfilt(*butter_bandpass(8, 13, fs), window)
82
+ eeg_beta = filtfilt(*butter_bandpass(13, 30, fs), window)
83
+ plt.figure(figsize=(16, 18))
84
+ plt.subplot(4,1,1); plt.plot(time_window, eeg_delta, linewidth=2); plt.title("Delta (0.5-4 Hz)", fontsize=28)
85
+ plt.subplot(4,1,2); plt.plot(time_window, eeg_theta, linewidth=2); plt.title("Theta (4-8 Hz)", fontsize=28)
86
+ plt.subplot(4,1,3); plt.plot(time_window, eeg_alpha, linewidth=2); plt.title("Alpha (8-13 Hz)", fontsize=28)
87
+ plt.subplot(4,1,4); plt.plot(time_window, eeg_beta, linewidth=2); plt.title("Beta (13-30 Hz)", fontsize=28)
88
+ plt.tight_layout()
89
+ plt.savefig("eeg_bands_plot.pdf", format='pdf', dpi=300)
90
+ logger.info("Saved frequency bands plot to eeg_bands_plot.pdf")
91
+ buf = io.BytesIO()
92
+ plt.savefig(buf, format='png')
93
+ buf.seek(0)
94
+ img = Image.open(buf)
95
+ plt.close()
96
+ return img
97
+
98
+ def plot_hypnogram(hypno):
99
+ logger.info("Generating hypnogram plot")
100
+ hypno_int = yasa.hypno_str_to_int(hypno)
101
+ time_minutes = np.arange(len(hypno_int)) * 0.5
102
+ start_min, end_min = 40, 170
103
+ start_epoch = int(start_min / 0.5)
104
+ end_epoch = int(end_min / 0.5)
105
+ window_time = time_minutes[start_epoch:end_epoch]
106
+ window_hypno = hypno_int[start_epoch:end_epoch]
107
+ plt.figure(figsize=(16, 6))
108
+ plt.step(window_time, window_hypno, where='post', color='navy', linewidth=3)
109
+ plt.gca().invert_yaxis()
110
+ plt.yticks([4, 3, 2, 1, 0], ['W', 'N1', 'N2', 'N3', 'R'], fontsize=28)
111
+ plt.xlabel('Time (minutes)', fontsize=32)
112
+ plt.ylabel('Sleep Stage', fontsize=32)
113
+ plt.title(f'Hypnogram ({start_min}-{end_min} min)', fontsize=36)
114
+ plt.grid(axis='x', linestyle='--', alpha=0.5)
115
+ plt.tight_layout()
116
+ plt.savefig("hypnogram_plot.pdf", format='pdf', dpi=300)
117
+ logger.info("Saved hypnogram to hypnogram_plot.pdf")
118
+ buf = io.BytesIO()
119
+ plt.savefig(buf, format='png')
120
+ buf.seek(0)
121
+ img = Image.open(buf)
122
+ plt.close()
123
+ return img