Spaces:
Sleeping
Sleeping
Delete app_preprocess.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115# Preprocesing Functiondef preprocess_eeg(csv_file, window_size=200, stride=100): """ Preprocess EEG CSV for model inference with artifact removal. Steps: 1. Load CSV. 2. Keep only 'timestampMs' and 'eegRawValueVolts'. 3. Remove rows with poorSignal > 52 or blinkStrength > 100. 4. Create uniform 10ms timestamp grid. 5. Interpolate missing EEG values. 6. Z-score normalize the EEG signal. 7. Window the signal into overlapping segments. Parameters: csv_file: file object or path to CSV window_size: number of samples per window (default 200 → 2s @100Hz) stride: step size between windows (default 100 → 50% overlap) Returns: X_windows: np.array of shape (num_windows, window_size, 1) window_timestamps: np.array of timestamps corresponding to each window start """ # 1. Load CSV df = pd.read_csv(csv_file) # 2. Remove artifact rows if 'poorSignal' in df.columns: df = df[df['poorSignal'] <= 52] if 'blinkStrength' in df.columns: df = df[df['blinkStrength'] <= 100] # 3. Keep only necessary columns if 'timestampMs' not in df.columns or 'eegRawValueVolts' not in df.columns: raise ValueError("CSV must contain 'timestampMs' and 'eegRawValueVolts' columns") df = df[['timestampMs', 'eegRawValueVolts']].copy() # 4. Create uniform 10ms grid ts_min, ts_max = df['timestampMs'].min(), df['timestampMs'].max() ts_grid = np.arange(ts_min, ts_max + 10, 10) # inclusive of last timestamp df_grid = pd.DataFrame({'timestampMs': ts_grid}) # Merge original values onto uniform grid df_merged = pd.merge(df_grid, df, on='timestampMs', how='left') # 5. Interpolate missing values df_merged['eegRawValueVolts'] = df_merged['eegRawValueVolts'].interpolate(method='linear', limit_direction='both') # 6. Z-score normalization eeg_signal = df_merged['eegRawValueVolts'].values eeg_signal = (eeg_signal - np.mean(eeg_signal)) / (np.std(eeg_signal) + 1e-8) df_merged['eegRawValueVolts'] = eeg_signal # 7. Windowing X_windows = [] window_timestamps = [] total_samples = len(df_merged) for start in range(0, total_samples - window_size + 1, stride): segment = df_merged['eegRawValueVolts'].values[start:start + window_size] X_windows.append(segment.reshape(-1, 1)) # shape (window_size, 1) window_timestamps.append(df_merged['timestampMs'].values[start]) # start timestamp for window X_windows = np.array(X_windows) window_timestamps = np.array(window_timestamps) return X_windows, window_timestamps
def predict_eeg(csv_file, model, label_classes=None, window_size=200, stride=100): """ Predict EEG emotion classes for a CSV file. Parameters: csv_file: path or file object for EEG CSV model: loaded Keras CNN-GRU model label_classes: list of class names in the same order as model output window_size: number of samples per window (default 200 → 2s) stride: step size for overlapping windows (default 100 → 50% overlap) Returns: pred_labels: list of predicted class names (one per window) window_timestamps: start timestamps corresponding to each window class_percentages: dict of {class_name: percentage_of_windows} """ # 1. Preprocess EEG X_windows, window_timestamps = preprocess_eeg(csv_file, window_size, stride) if len(X_windows) == 0: raise ValueError("No valid EEG windows could be created from this CSV.") # 2. Predict probabilities preds = model.predict(X_windows, verbose=0) # 3. Get integer class predictions pred_ints = np.argmax(preds, axis=1) # 4. Map to label names if label_classes is None: # fallback default order (must match your training) label_classes = ["focused", "funny", "meditation", "normal", "sad"] pred_labels = [label_classes[i] for i in pred_ints] # 5. Count per-class percentages from collections import Counter counts = Counter(pred_labels) total = len(pred_labels) class_percentages = {cls: counts.get(cls,0)/total*100 for cls in label_classes} return pred_labels, window_timestamps, class_percentagesapp_preprocess.pyDeleted-115