Penthes commited on
Commit
4afe9b1
·
verified ·
1 Parent(s): 00b8653

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -22
app.py CHANGED
@@ -37,16 +37,17 @@ class_labels = ["glass", "metal", "organic", "paper", "plastic"]
37
 
38
 
39
  def load_model():
40
- """Load the trained TensorFlow/Keras model from model/ directory"""
41
  try:
42
- # Try loading different formats from model/ directory
 
 
 
43
  model_files = [
44
- './model/waste_model.keras', # Keras format (recommended)
45
- './model/waste_model.h5', # H5 format
46
- './model/best_model.keras', # Checkpoint from training
47
  'model/waste_model.keras',
48
  'model/waste_model.h5',
49
- 'model/best_model.keras',
 
50
  ]
51
 
52
  model = None
@@ -55,28 +56,64 @@ def load_model():
55
  for model_file in model_files:
56
  if os.path.exists(model_file):
57
  try:
58
- model = tf.keras.models.load_model(model_file)
59
- loaded_from = model_file
60
- logger.info(f"Model loaded successfully from {model_file}")
61
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  except Exception as e:
63
  logger.warning(f"Failed to load {model_file}: {e}")
64
  continue
65
 
66
  if model is None:
67
- logger.error("No model file found in any location. Creating dummy model for testing.")
68
- # Create dummy model with same architecture for testing
69
- model = tf.keras.Sequential([
70
- tf.keras.layers.Rescaling(1./255, input_shape=(224, 224, 3)),
71
- tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet'),
72
- tf.keras.layers.GlobalAveragePooling2D(),
73
- tf.keras.layers.Dense(128, activation='relu'),
74
- tf.keras.layers.Dropout(0.2),
75
- tf.keras.layers.Dense(5, activation='softmax')
76
- ])
77
- logger.warning("Using dummy model - predictions will be random!")
78
  else:
79
- logger.info(f"Successfully loaded model from: {loaded_from}")
 
 
 
 
 
 
80
 
81
  return model
82
 
@@ -84,6 +121,37 @@ def load_model():
84
  logger.error(f"Critical error loading model: {e}")
85
  raise Exception(f"Model loading failed: {e}")
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def preprocess_image(image_data):
88
  """
89
  Preprocess image to match training pipeline:
 
37
 
38
 
39
  def load_model():
40
+ """Load the trained TensorFlow/Keras model with version compatibility handling"""
41
  try:
42
+ # Debug info
43
+ logger.info(f"TensorFlow version: {tf.__version__}")
44
+ logger.info("=== DEBUGGING MODEL LOADING ===")
45
+
46
  model_files = [
 
 
 
47
  'model/waste_model.keras',
48
  'model/waste_model.h5',
49
+ './model/waste_model.keras',
50
+ './model/waste_model.h5',
51
  ]
52
 
53
  model = None
 
56
  for model_file in model_files:
57
  if os.path.exists(model_file):
58
  try:
59
+ logger.info(f"Attempting to load: {model_file}")
60
+
61
+ # Try different loading methods for compatibility
62
+ try:
63
+ # Method 1: Standard loading
64
+ model = tf.keras.models.load_model(model_file, compile=False)
65
+ logger.info(f"✅ Loaded with standard method: {model_file}")
66
+ loaded_from = model_file
67
+ break
68
+ except Exception as e1:
69
+ logger.warning(f"Standard loading failed: {e1}")
70
+
71
+ # Method 2: Load with custom objects (for compatibility)
72
+ try:
73
+ custom_objects = {
74
+ 'InputLayer': tf.keras.layers.InputLayer,
75
+ 'Rescaling': tf.keras.layers.Rescaling,
76
+ }
77
+ model = tf.keras.models.load_model(
78
+ model_file,
79
+ custom_objects=custom_objects,
80
+ compile=False
81
+ )
82
+ logger.info(f"✅ Loaded with custom objects: {model_file}")
83
+ loaded_from = model_file
84
+ break
85
+ except Exception as e2:
86
+ logger.warning(f"Custom objects loading failed: {e2}")
87
+
88
+ # Method 3: Try loading weights only
89
+ try:
90
+ # Create model architecture first, then load weights
91
+ model = create_model_architecture()
92
+ if model_file.endswith('.h5'):
93
+ model.load_weights(model_file)
94
+ logger.info(f"✅ Loaded weights only: {model_file}")
95
+ loaded_from = f"{model_file} (weights only)"
96
+ break
97
+ except Exception as e3:
98
+ logger.warning(f"Weights loading failed: {e3}")
99
+ continue
100
+
101
  except Exception as e:
102
  logger.warning(f"Failed to load {model_file}: {e}")
103
  continue
104
 
105
  if model is None:
106
+ logger.warning("All loading methods failed. Creating model from architecture...")
107
+ model = create_model_architecture()
108
+ logger.warning("⚠️ Using untrained model - predictions will be random!")
 
 
 
 
 
 
 
 
109
  else:
110
+ logger.info(f" Model loaded successfully from: {loaded_from}")
111
+ # Recompile the model
112
+ model.compile(
113
+ optimizer='adam',
114
+ loss='categorical_crossentropy',
115
+ metrics=['accuracy']
116
+ )
117
 
118
  return model
119
 
 
121
  logger.error(f"Critical error loading model: {e}")
122
  raise Exception(f"Model loading failed: {e}")
123
 
124
+ def create_model_architecture():
125
+ """Create the model architecture matching your training setup"""
126
+ try:
127
+ # Create the same architecture as in your training notebook
128
+ base_model = tf.keras.applications.MobileNetV2(
129
+ weights='imagenet',
130
+ include_top=False,
131
+ input_shape=(224, 224, 3)
132
+ )
133
+
134
+ # Freeze base model
135
+ base_model.trainable = False
136
+
137
+ # Create complete model
138
+ model = tf.keras.Sequential([
139
+ tf.keras.layers.Rescaling(1./255, input_shape=(224, 224, 3)),
140
+ base_model,
141
+ tf.keras.layers.GlobalAveragePooling2D(),
142
+ tf.keras.layers.Dropout(0.2),
143
+ tf.keras.layers.Dense(128, activation='relu'),
144
+ tf.keras.layers.Dropout(0.5),
145
+ tf.keras.layers.Dense(5, activation='softmax') # 5 classes
146
+ ])
147
+
148
+ logger.info("Created model architecture successfully")
149
+ return model
150
+
151
+ except Exception as e:
152
+ logger.error(f"Failed to create model architecture: {e}")
153
+ raise
154
+
155
  def preprocess_image(image_data):
156
  """
157
  Preprocess image to match training pipeline: