File size: 8,733 Bytes
7306a70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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}')"
                    
                    @classmethod
                    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()