Spaces:
Sleeping
Sleeping
Download predictor.py from KnowingFly/depression-detection-api: direct link, hf CLI and curl.
- Browser
- Download file 8.73 kB
-
https://huggingface.co/spaces/KnowingFly/depression-detection-api/resolve/main/predictor.py
- Command line
-
hf download hf://spaces/KnowingFly/depression-detection-api/predictor.py
-
curl -L -o predictor.py https://huggingface.co/spaces/KnowingFly/depression-detection-api/resolve/main/predictor.py
8.73 kB
| import os | |
| import numpy as np | |
| import tensorflow as tf | |
| from tensorflow.keras.applications.efficientnet import preprocess_input | |
| from typing import Tuple, Optional | |
| class DepressionPredictor: | |
| """Depression detection predictor using EfficientNetB0 model.""" | |
| def __init__(self, model_path: str = "model.h5"): | |
| """ | |
| Initialize the predictor with the trained model. | |
| Args: | |
| model_path: Path to the trained model file | |
| """ | |
| self.model: Optional[tf.keras.Model] = None | |
| self.model_path = model_path | |
| self.input_size = (224, 224) | |
| self.class_names = ["depression", "neutral"] | |
| self._load_model() | |
| def _load_model(self) -> None: | |
| """Load the trained model from disk.""" | |
| try: | |
| if os.path.exists(self.model_path): | |
| print(f"Attempting to load model from {self.model_path}...") | |
| # Create a DTypePolicy stub class for Keras 3.x compatibility | |
| # This handles models saved with newer Keras versions | |
| class DTypePolicy: | |
| """Stub for Keras 3.x DTypePolicy to enable loading in Keras 2.x""" | |
| def __init__(self, name='float32', **kwargs): | |
| self.name = name | |
| self._name = name | |
| def __repr__(self): | |
| return f"DTypePolicy('{self.name}')" | |
| def from_config(cls, config): | |
| if isinstance(config, dict): | |
| return cls(name=config.get('name', 'float32')) | |
| return cls(name='float32') | |
| # Custom InputLayer to handle batch_shape -> shape conversion | |
| class CompatibleInputLayer(tf.keras.layers.InputLayer): | |
| def __init__(self, **kwargs): | |
| if 'batch_shape' in kwargs: | |
| batch_shape = kwargs.pop('batch_shape') | |
| if batch_shape is not None: | |
| kwargs['input_shape'] = batch_shape[1:] | |
| # Handle DTypePolicy from newer Keras | |
| if 'dtype' in kwargs: | |
| dtype_val = kwargs['dtype'] | |
| if isinstance(dtype_val, dict): | |
| kwargs['dtype'] = dtype_val.get('config', {}).get('name', 'float32') | |
| elif hasattr(dtype_val, 'name'): | |
| kwargs['dtype'] = dtype_val.name | |
| super().__init__(**kwargs) | |
| # Custom Rescaling layer for Keras 3.x compatibility | |
| class CompatibleRescaling(tf.keras.layers.Rescaling): | |
| def __init__(self, scale, offset=0.0, **kwargs): | |
| kwargs.pop('dtype', None) | |
| super().__init__(scale=scale, offset=offset, **kwargs) | |
| # Custom Dense layer to handle dtype serialization | |
| class CompatibleDense(tf.keras.layers.Dense): | |
| def __init__(self, units, **kwargs): | |
| if 'dtype' in kwargs: | |
| dtype_val = kwargs['dtype'] | |
| if isinstance(dtype_val, dict): | |
| kwargs['dtype'] = dtype_val.get('config', {}).get('name', 'float32') | |
| elif hasattr(dtype_val, 'name'): | |
| kwargs['dtype'] = dtype_val.name | |
| super().__init__(units, **kwargs) | |
| # Build custom objects dict | |
| custom_objects = { | |
| 'InputLayer': CompatibleInputLayer, | |
| 'Rescaling': CompatibleRescaling, | |
| 'Dense': CompatibleDense, | |
| 'DTypePolicy': DTypePolicy, | |
| } | |
| # Try different loading strategies | |
| model_loaded = False | |
| # Strategy 1: Direct load with custom objects | |
| try: | |
| print("Strategy 1: Loading with custom objects...") | |
| self.model = tf.keras.models.load_model( | |
| self.model_path, | |
| custom_objects=custom_objects, | |
| compile=False | |
| ) | |
| model_loaded = True | |
| print("Strategy 1 successful!") | |
| except Exception as e1: | |
| print(f"Strategy 1 failed: {e1}") | |
| # Strategy 2: Load weights only into rebuilt architecture | |
| try: | |
| print("Strategy 2: Rebuilding EfficientNetB0 architecture and loading weights...") | |
| self.model = self._rebuild_model_architecture() | |
| self.model.load_weights(self.model_path, by_name=True, skip_mismatch=True) | |
| model_loaded = True | |
| print("Strategy 2 successful!") | |
| except Exception as e2: | |
| print(f"Strategy 2 failed: {e2}") | |
| if model_loaded: | |
| # Recompile the model | |
| self.model.compile( | |
| optimizer='adam', | |
| loss='binary_crossentropy', | |
| metrics=['accuracy'] | |
| ) | |
| print(f"Model loaded and compiled successfully from {self.model_path}") | |
| else: | |
| print("All loading strategies failed!") | |
| self.model = None | |
| else: | |
| print(f"Warning: Model file not found at {self.model_path}") | |
| self.model = None | |
| except Exception as e: | |
| print(f"Exception encountered: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| self.model = None | |
| def _rebuild_model_architecture(self) -> tf.keras.Model: | |
| """Rebuild the EfficientNetB0 model architecture for weight loading.""" | |
| from tensorflow.keras import layers, Model | |
| # Create the same architecture as in the training notebook | |
| inputs = layers.Input(shape=(224, 224, 3), name='input') | |
| base_model = tf.keras.applications.EfficientNetB0( | |
| include_top=False, | |
| weights='imagenet', | |
| input_tensor=inputs | |
| ) | |
| x = layers.GlobalAveragePooling2D(name='global_avg_pool')(base_model.output) | |
| x = layers.Dropout(0.2, name='dropout1')(x) | |
| x = layers.Dense(256, activation='relu', name='fc1')(x) | |
| x = layers.Dropout(0.2, name='dropout2')(x) | |
| outputs = layers.Dense(1, activation='sigmoid', name='output')(x) | |
| model = Model(inputs, outputs, name='EfficientNetB0_depression') | |
| return model | |
| def is_model_loaded(self) -> bool: | |
| """Check if the model is loaded successfully.""" | |
| return self.model is not None | |
| def preprocess_image(self, image: np.ndarray) -> np.ndarray: | |
| """ | |
| Preprocess image for model inference. | |
| Args: | |
| image: Input image as numpy array (RGB format, 224x224) | |
| Returns: | |
| Preprocessed image ready for model inference | |
| """ | |
| img = image.astype(np.float32) | |
| img = preprocess_input(img) | |
| img = np.expand_dims(img, axis=0) | |
| return img | |
| def predict(self, image: np.ndarray, threshold: float = 0.5) -> Tuple[str, float]: | |
| """ | |
| Predict depression status from face image. | |
| Args: | |
| image: Preprocessed face image (RGB, 224x224) | |
| threshold: Classification threshold (default: 0.5) | |
| Returns: | |
| Tuple of (prediction_label, confidence_score) | |
| Raises: | |
| RuntimeError: If model is not loaded | |
| """ | |
| if not self.is_model_loaded(): | |
| raise RuntimeError("Model is not loaded") | |
| preprocessed = self.preprocess_image(image) | |
| raw_prediction = self.model.predict(preprocessed, verbose=0)[0][0] | |
| if raw_prediction >= threshold: | |
| prediction = "neutral" | |
| confidence = float(raw_prediction) | |
| else: | |
| prediction = "depression" | |
| confidence = float(1 - raw_prediction) | |
| return prediction, confidence | |
| predictor = DepressionPredictor() | |