Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,12 @@
|
|
1 |
-
import
|
2 |
import mne
|
3 |
import numpy as np
|
4 |
import pandas as pd
|
|
|
5 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
6 |
import torch
|
7 |
-
import os
|
8 |
|
|
|
9 |
model_name = "tiiuae/falcon-7b-instruct"
|
10 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
11 |
model = AutoModelForCausalLM.from_pretrained(
|
@@ -20,57 +21,101 @@ def compute_band_power(psd, freqs, fmin, fmax):
|
|
20 |
band_psd = psd[:, freq_mask].mean()
|
21 |
return float(band_psd)
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
def load_eeg_data(file_path, default_sfreq=256.0, time_col='time'):
|
24 |
"""
|
25 |
-
Load EEG data
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
"""
|
31 |
_, file_ext = os.path.splitext(file_path)
|
32 |
file_ext = file_ext.lower()
|
33 |
|
34 |
if file_ext == '.fif':
|
35 |
raw = mne.io.read_raw_fif(file_path, preload=True)
|
|
|
36 |
elif file_ext == '.csv':
|
37 |
df = pd.read_csv(file_path)
|
38 |
|
39 |
-
#
|
40 |
-
|
41 |
-
if col != time_col:
|
42 |
-
# Drop non-numeric columns if any
|
43 |
-
if not pd.api.types.is_numeric_dtype(df[col]):
|
44 |
-
df = df.drop(columns=[col])
|
45 |
-
|
46 |
-
if time_col in df.columns:
|
47 |
-
# Use the provided time column
|
48 |
time = df[time_col].values
|
49 |
data_df = df.drop(columns=[time_col])
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
51 |
if len(time) < 2:
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
54 |
else:
|
55 |
-
# No
|
56 |
-
|
|
|
|
|
|
|
57 |
data_df = df
|
|
|
58 |
|
59 |
-
# Channels are all remaining columns
|
60 |
ch_names = list(data_df.columns)
|
61 |
data = data_df.values.T # shape: (n_channels, n_samples)
|
62 |
|
63 |
-
# Create MNE info
|
64 |
ch_types = ['eeg'] * len(ch_names)
|
65 |
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
|
66 |
-
|
67 |
raw = mne.io.RawArray(data, info)
|
|
|
68 |
else:
|
69 |
-
raise ValueError("Unsupported file format.
|
70 |
-
|
71 |
return raw
|
72 |
|
73 |
-
def
|
|
|
|
|
74 |
raw = load_eeg_data(file.name, default_sfreq=float(default_sfreq), time_col=time_col)
|
75 |
|
76 |
psd, freqs = mne.time_frequency.psd_welch(raw, fmin=1, fmax=40)
|
@@ -87,30 +132,45 @@ Data Summary: {data_summary}
|
|
87 |
|
88 |
Provide a concise, user-friendly interpretation of these findings in simple terms.
|
89 |
"""
|
90 |
-
|
91 |
inputs = tokenizer.encode(prompt, return_tensors="pt").to(model.device)
|
92 |
outputs = model.generate(
|
93 |
inputs, max_length=200, do_sample=True, top_k=50, top_p=0.95
|
94 |
)
|
95 |
summary = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
96 |
-
|
97 |
return summary
|
98 |
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
|
|
|
|
112 |
)
|
113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
if __name__ == "__main__":
|
116 |
-
|
|
|
1 |
+
import os
|
2 |
import mne
|
3 |
import numpy as np
|
4 |
import pandas as pd
|
5 |
+
import gradio as gr
|
6 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
7 |
import torch
|
|
|
8 |
|
9 |
+
# Load LLM
|
10 |
model_name = "tiiuae/falcon-7b-instruct"
|
11 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
model = AutoModelForCausalLM.from_pretrained(
|
|
|
21 |
band_psd = psd[:, freq_mask].mean()
|
22 |
return float(band_psd)
|
23 |
|
24 |
+
def inspect_file(file):
|
25 |
+
"""
|
26 |
+
Inspect the uploaded file to determine available columns.
|
27 |
+
If FIF: Just inform that it's an MNE file and no time column is needed.
|
28 |
+
If CSV: Return a list of columns (both numeric and non-numeric).
|
29 |
+
"""
|
30 |
+
if file is None:
|
31 |
+
return "No file uploaded.", [], "No preview available."
|
32 |
+
file_path = file.name
|
33 |
+
_, file_ext = os.path.splitext(file_path)
|
34 |
+
|
35 |
+
file_ext = file_ext.lower()
|
36 |
+
if file_ext == ".fif":
|
37 |
+
# FIF files: We know they're MNE compatible
|
38 |
+
# No columns to choose from, just proceed with default analysis
|
39 |
+
return (
|
40 |
+
"FIF file detected. No need for time column selection. Default sampling frequency will be read from file.",
|
41 |
+
[],
|
42 |
+
"FIF file doesn't require further inspection."
|
43 |
+
)
|
44 |
+
elif file_ext == ".csv":
|
45 |
+
# Read a small portion of the CSV to determine columns
|
46 |
+
try:
|
47 |
+
df = pd.read_csv(file_path, nrows=5)
|
48 |
+
except Exception as e:
|
49 |
+
return f"Error reading CSV: {e}", [], "Could not read CSV preview."
|
50 |
+
|
51 |
+
cols = list(df.columns)
|
52 |
+
preview = df.head().to_markdown()
|
53 |
+
return (
|
54 |
+
"CSV file detected. Select a time column if available, or leave it blank and specify a default frequency.",
|
55 |
+
cols,
|
56 |
+
preview
|
57 |
+
)
|
58 |
+
else:
|
59 |
+
return "Unsupported file format.", [], "No preview available."
|
60 |
+
|
61 |
+
|
62 |
def load_eeg_data(file_path, default_sfreq=256.0, time_col='time'):
|
63 |
"""
|
64 |
+
Load EEG data with flexibility.
|
65 |
+
If FIF: Use MNE's read_raw_fif directly.
|
66 |
+
If CSV:
|
67 |
+
- If time_col is given and present in the file, use it.
|
68 |
+
- Otherwise, assume default_sfreq.
|
69 |
"""
|
70 |
_, file_ext = os.path.splitext(file_path)
|
71 |
file_ext = file_ext.lower()
|
72 |
|
73 |
if file_ext == '.fif':
|
74 |
raw = mne.io.read_raw_fif(file_path, preload=True)
|
75 |
+
|
76 |
elif file_ext == '.csv':
|
77 |
df = pd.read_csv(file_path)
|
78 |
|
79 |
+
# If time_col is specified and in df, use it to compute sfreq
|
80 |
+
if time_col and time_col in df.columns:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
time = df[time_col].values
|
82 |
data_df = df.drop(columns=[time_col])
|
83 |
+
|
84 |
+
# Drop non-numeric columns
|
85 |
+
for col in data_df.columns:
|
86 |
+
if not pd.api.types.is_numeric_dtype(data_df[col]):
|
87 |
+
data_df = data_df.drop(columns=[col])
|
88 |
+
|
89 |
if len(time) < 2:
|
90 |
+
# Not enough time points, fallback to default_sfreq
|
91 |
+
sfreq = default_sfreq
|
92 |
+
else:
|
93 |
+
# Compute sfreq from time
|
94 |
+
sfreq = 1.0 / np.mean(np.diff(time))
|
95 |
else:
|
96 |
+
# No time column used, assume default_sfreq
|
97 |
+
# Drop non-numeric columns
|
98 |
+
for col in df.columns:
|
99 |
+
if not pd.api.types.is_numeric_dtype(df[col]):
|
100 |
+
df = df.drop(columns=[col])
|
101 |
data_df = df
|
102 |
+
sfreq = default_sfreq
|
103 |
|
|
|
104 |
ch_names = list(data_df.columns)
|
105 |
data = data_df.values.T # shape: (n_channels, n_samples)
|
106 |
|
|
|
107 |
ch_types = ['eeg'] * len(ch_names)
|
108 |
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
|
|
|
109 |
raw = mne.io.RawArray(data, info)
|
110 |
+
|
111 |
else:
|
112 |
+
raise ValueError("Unsupported file format. Provide a FIF or CSV file.")
|
113 |
+
|
114 |
return raw
|
115 |
|
116 |
+
def analyze_eeg(file, default_sfreq, time_col):
|
117 |
+
if file is None:
|
118 |
+
return "No file uploaded."
|
119 |
raw = load_eeg_data(file.name, default_sfreq=float(default_sfreq), time_col=time_col)
|
120 |
|
121 |
psd, freqs = mne.time_frequency.psd_welch(raw, fmin=1, fmax=40)
|
|
|
132 |
|
133 |
Provide a concise, user-friendly interpretation of these findings in simple terms.
|
134 |
"""
|
|
|
135 |
inputs = tokenizer.encode(prompt, return_tensors="pt").to(model.device)
|
136 |
outputs = model.generate(
|
137 |
inputs, max_length=200, do_sample=True, top_k=50, top_p=0.95
|
138 |
)
|
139 |
summary = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
140 |
return summary
|
141 |
|
142 |
+
|
143 |
+
#########################
|
144 |
+
# BUILD THE GRADIO INTERFACE
|
145 |
+
#########################
|
146 |
+
|
147 |
+
# Step 1: Inspect file
|
148 |
+
def preview_file(file):
|
149 |
+
msg, cols, preview = inspect_file(file)
|
150 |
+
return msg, gr.Dropdown.update(choices=cols, value=None), preview
|
151 |
+
|
152 |
+
with gr.Blocks() as demo:
|
153 |
+
gr.Markdown("# NeuroNarrative-Lite: EEG Summary with Flexible Preprocessing")
|
154 |
+
gr.Markdown(
|
155 |
+
"Upload an EEG file (FIF or CSV). If it's CSV, we will inspect the file and let you choose a time column. "
|
156 |
+
"If no suitable time column is found, leave it blank and provide a default sampling frequency."
|
157 |
)
|
158 |
+
|
159 |
+
file_input = gr.File(label="Upload your EEG data (FIF or CSV)")
|
160 |
+
preview_button = gr.Button("Inspect File")
|
161 |
+
msg_output = gr.Markdown()
|
162 |
+
cols_dropdown = gr.Dropdown(label="Select Time Column (optional)", interactive=True)
|
163 |
+
preview_output = gr.Markdown()
|
164 |
+
|
165 |
+
preview_button.click(preview_file, inputs=[file_input], outputs=[msg_output, cols_dropdown, preview_output])
|
166 |
+
|
167 |
+
default_sfreq_input = gr.Textbox(label="Default Sampling Frequency (Hz) if no time column", value="256")
|
168 |
+
analyze_button = gr.Button("Run Analysis")
|
169 |
+
result_output = gr.Textbox(label="Analysis Summary")
|
170 |
+
|
171 |
+
analyze_button.click(analyze_eeg,
|
172 |
+
inputs=[file_input, default_sfreq_input, cols_dropdown],
|
173 |
+
outputs=[result_output])
|
174 |
|
175 |
if __name__ == "__main__":
|
176 |
+
demo.launch()
|