Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,8 @@ import time
|
|
| 12 |
import os
|
| 13 |
import tempfile
|
| 14 |
from urllib.parse import urlparse
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Set up logging
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -21,6 +23,41 @@ logger = logging.getLogger(__name__)
|
|
| 21 |
tf.get_logger().setLevel('ERROR')
|
| 22 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# Class mappings
|
| 25 |
CLASS_NAMES = {
|
| 26 |
0: 'AcrimSat', 1: 'Aquarius', 2: 'Aura', 3: 'Calipso', 4: 'Cloudsat',
|
|
@@ -118,7 +155,7 @@ def download_model_with_progress(url, timeout=120):
|
|
| 118 |
return None, f"Download error: {str(e)}"
|
| 119 |
|
| 120 |
def load_model(model_name):
|
| 121 |
-
"""Load model from Hugging Face with enhanced error handling"""
|
| 122 |
|
| 123 |
# Check cache first
|
| 124 |
if model_name in model_cache:
|
|
@@ -150,8 +187,12 @@ def load_model(model_name):
|
|
| 150 |
tmp_file.write(model_bytes.read())
|
| 151 |
tmp_file_path = tmp_file.name
|
| 152 |
|
| 153 |
-
# Load model from temporary file
|
| 154 |
-
model = tf.keras.models.load_model(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
# Clean up temporary file
|
| 157 |
try:
|
|
@@ -192,6 +233,31 @@ def preprocess_image(image, target_size=(224, 224)):
|
|
| 192 |
except Exception as e:
|
| 193 |
return None, f"Error preprocessing image: {str(e)}"
|
| 194 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
def predict_with_model(model, image, model_name):
|
| 196 |
"""Make prediction with a specific model"""
|
| 197 |
if model is None:
|
|
@@ -199,8 +265,14 @@ def predict_with_model(model, image, model_name):
|
|
| 199 |
try:
|
| 200 |
start_time = time.time()
|
| 201 |
|
| 202 |
-
#
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
inference_time = (time.time() - start_time) * 1000
|
| 205 |
|
| 206 |
# Handle different output shapes
|
|
|
|
| 12 |
import os
|
| 13 |
import tempfile
|
| 14 |
from urllib.parse import urlparse
|
| 15 |
+
from tensorflow import keras
|
| 16 |
+
from tensorflow.keras import layers, models
|
| 17 |
|
| 18 |
# Set up logging
|
| 19 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 23 |
tf.get_logger().setLevel('ERROR')
|
| 24 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 25 |
|
| 26 |
+
# ========== CUSTOM LAYERS DEFINITIONS ==========
|
| 27 |
+
@keras.saving.register_keras_serializable()
|
| 28 |
+
class RepeatChannels(keras.layers.Layer):
|
| 29 |
+
"""Converts single channel (depth) to 3 channels for RGB models"""
|
| 30 |
+
def __init__(self, **kwargs):
|
| 31 |
+
super(RepeatChannels, self).__init__(**kwargs)
|
| 32 |
+
|
| 33 |
+
def call(self, inputs):
|
| 34 |
+
return tf.repeat(inputs, 3, axis=-1)
|
| 35 |
+
|
| 36 |
+
def get_config(self):
|
| 37 |
+
config = super(RepeatChannels, self).get_config()
|
| 38 |
+
return config
|
| 39 |
+
|
| 40 |
+
# Add any other custom layers your models might need
|
| 41 |
+
@keras.saving.register_keras_serializable()
|
| 42 |
+
class CustomLayer(keras.layers.Layer):
|
| 43 |
+
"""Template for additional custom layers if needed"""
|
| 44 |
+
def __init__(self, **kwargs):
|
| 45 |
+
super(CustomLayer, self).__init__(**kwargs)
|
| 46 |
+
|
| 47 |
+
def call(self, inputs):
|
| 48 |
+
return inputs
|
| 49 |
+
|
| 50 |
+
def get_config(self):
|
| 51 |
+
config = super(CustomLayer, self).get_config()
|
| 52 |
+
return config
|
| 53 |
+
|
| 54 |
+
# Custom objects dictionary for model loading
|
| 55 |
+
CUSTOM_OBJECTS = {
|
| 56 |
+
'RepeatChannels': RepeatChannels,
|
| 57 |
+
'CustomLayer': CustomLayer,
|
| 58 |
+
# Add more custom layers here as needed
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
# Class mappings
|
| 62 |
CLASS_NAMES = {
|
| 63 |
0: 'AcrimSat', 1: 'Aquarius', 2: 'Aura', 3: 'Calipso', 4: 'Cloudsat',
|
|
|
|
| 155 |
return None, f"Download error: {str(e)}"
|
| 156 |
|
| 157 |
def load_model(model_name):
|
| 158 |
+
"""Load model from Hugging Face with enhanced error handling and custom objects"""
|
| 159 |
|
| 160 |
# Check cache first
|
| 161 |
if model_name in model_cache:
|
|
|
|
| 187 |
tmp_file.write(model_bytes.read())
|
| 188 |
tmp_file_path = tmp_file.name
|
| 189 |
|
| 190 |
+
# Load model from temporary file with custom objects
|
| 191 |
+
model = tf.keras.models.load_model(
|
| 192 |
+
tmp_file_path,
|
| 193 |
+
custom_objects=CUSTOM_OBJECTS,
|
| 194 |
+
compile=False
|
| 195 |
+
)
|
| 196 |
|
| 197 |
# Clean up temporary file
|
| 198 |
try:
|
|
|
|
| 233 |
except Exception as e:
|
| 234 |
return None, f"Error preprocessing image: {str(e)}"
|
| 235 |
|
| 236 |
+
def handle_multi_input_prediction(model, image, model_name):
|
| 237 |
+
"""Handle models that expect multiple inputs (RGB + Depth + Tabular)"""
|
| 238 |
+
try:
|
| 239 |
+
# For multi-input models, we need to provide dummy inputs for missing modalities
|
| 240 |
+
rgb_input = image
|
| 241 |
+
|
| 242 |
+
# Create dummy depth input (grayscale version of RGB)
|
| 243 |
+
depth_input = np.mean(image, axis=-1, keepdims=True) # Convert RGB to grayscale
|
| 244 |
+
depth_input = np.repeat(depth_input, 3, axis=-1) # Repeat to make it 3-channel
|
| 245 |
+
|
| 246 |
+
# Create dummy tabular input
|
| 247 |
+
if model_name == "Custom CNN":
|
| 248 |
+
tabular_input = np.random.random((image.shape[0], 10)) # Adjust size as needed
|
| 249 |
+
else:
|
| 250 |
+
tabular_input = np.random.random((image.shape[0], 1))
|
| 251 |
+
|
| 252 |
+
# Try multi-input prediction
|
| 253 |
+
predictions = model.predict([rgb_input, depth_input, tabular_input], verbose=0)
|
| 254 |
+
return predictions
|
| 255 |
+
|
| 256 |
+
except Exception as e:
|
| 257 |
+
logger.warning(f"Multi-input prediction failed for {model_name}: {e}")
|
| 258 |
+
# Fallback to single input
|
| 259 |
+
return model.predict(image, verbose=0)
|
| 260 |
+
|
| 261 |
def predict_with_model(model, image, model_name):
|
| 262 |
"""Make prediction with a specific model"""
|
| 263 |
if model is None:
|
|
|
|
| 265 |
try:
|
| 266 |
start_time = time.time()
|
| 267 |
|
| 268 |
+
# Check if model expects multiple inputs
|
| 269 |
+
if len(model.input_shape) > 1 or (hasattr(model, 'input') and isinstance(model.input, list)):
|
| 270 |
+
# Multi-input model
|
| 271 |
+
predictions = handle_multi_input_prediction(model, image, model_name)
|
| 272 |
+
else:
|
| 273 |
+
# Single input model
|
| 274 |
+
predictions = model.predict(image, verbose=0)
|
| 275 |
+
|
| 276 |
inference_time = (time.time() - start_time) * 1000
|
| 277 |
|
| 278 |
# Handle different output shapes
|