Panic_Detection / preprocessing.py
Shib-Sankar-Das's picture
Deploy Panic Detection API with FastAPI, CNN model, and Docker configuration
5de794c
"""
Preprocessing utilities for Panic Detection model
"""
import numpy as np
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
class PanicDetectionPreprocessor:
def __init__(self):
"""Initialize encoders and scaler with the same configuration as training"""
self.gender_encoder = LabelEncoder()
self.activity_encoder = LabelEncoder()
self.scaler = MinMaxScaler()
# Fit encoders with expected values (based on your training data)
# Adjust these if your actual categories are different
self.gender_encoder.fit(['Male', 'Female'])
self.activity_encoder.fit(['Running', 'Walking', 'Sitting', 'Standing', 'Cycling'])
# Initialize scaler with approximate ranges from your data
# In production, you should save and load the actual fitted scaler
self.scaler.fit(np.array([
[0, 18, 45, 60, 0, 0], # min values (approximate)
[1, 80, 120, 180, 15000, 4] # max values (approximate)
]))
def preprocess(self, gender: str, age: int, weight: float,
heartrate: int, stepcount: int, activity: str):
"""
Preprocess input data for model prediction
Args:
gender: Gender as string ('Male' or 'Female')
age: Age in years
weight: Weight in kg
heartrate: Heart rate in bpm
stepcount: Step count
activity: Activity type as string
Returns:
Preprocessed numpy array ready for model input
"""
try:
# Encode categorical features
gender_encoded = self.gender_encoder.transform([gender])[0]
activity_encoded = self.activity_encoder.transform([activity])[0]
# Create feature array
features = np.array([[
gender_encoded,
age,
weight,
heartrate,
stepcount,
activity_encoded
]])
# Scale features
features_scaled = self.scaler.transform(features)
# Reshape for CNN input (samples, timesteps, features)
features_reshaped = features_scaled.reshape(1, 6, 1)
return features_reshaped
except Exception as e:
raise ValueError(f"Preprocessing error: {str(e)}")
def get_valid_genders(self):
"""Return list of valid gender values"""
return list(self.gender_encoder.classes_)
def get_valid_activities(self):
"""Return list of valid activity values"""
return list(self.activity_encoder.classes_)