nativeshiftai commited on
Commit
540ac3a
·
verified ·
1 Parent(s): 9e2008a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -102
app.py CHANGED
@@ -1,145 +1,147 @@
1
  import gradio as gr
2
  import tensorflow as tf
 
3
  import numpy as np
4
- from PIL import Image # Using PIL for image handling
5
- import traceback # Import traceback to get more detailed error info
6
 
7
  # Define the path to your Keras model file
8
- # Make sure 'waste_classification_model_initial.keras' is uploaded to your Hugging Face Space repository
9
  MODEL_PATH = 'ifswaste_classification_model_initial.keras'
10
 
11
- # Define the expected image size for your model
12
- # REPLACE WITH THE ACTUAL SIZE YOUR MODEL EXPECTS (e.g., 224, 224)
13
- IMG_WIDTH = 224
14
- IMG_HEIGHT = 224
15
 
16
- # Define your class labels in the correct order
17
- # REPLACE WITH YOUR ACTUAL CLASS NAMES (e.g., ['Cardboard', 'Glass', 'Metal', 'Paper', 'Plastic', 'Trash'])
18
- CLASS_NAMES = ['plastic', 'paper', 'metal', 'glass', 'battery', 'organic'] # Example class names
19
 
20
  # --- Model Loading ---
21
- # Load the trained Keras model
22
  try:
23
  print(f"Attempting to load model from path: {MODEL_PATH}")
24
  model = tf.keras.models.load_model(MODEL_PATH)
25
  print(f"Model loaded successfully from {MODEL_PATH}")
 
 
26
  except Exception as e:
27
  print(f"Error loading model: {e}")
28
- # Use traceback for more detailed error info during loading
29
  traceback.print_exc()
30
- model = None # Set model to None if loading fails
31
 
32
  # --- Prediction Function ---
33
  def classify_waste(image):
34
  """
35
  Classifies the input image using the loaded Keras model.
36
-
37
- Args:
38
- image: A PIL Image object from Gradio's webcam input.
39
-
40
- Returns:
41
- A dictionary where keys are class names and values are probabilities,
42
- or an error message if the model didn't load or input is invalid.
43
  """
44
- print("--- classify_waste function called ---")
 
45
  if model is None:
46
  print("Error: Model is None inside classify_waste.")
47
  return {"Error": "Model failed to load during app startup."}
48
 
49
  if image is None:
50
- print("Error: No image provided to classify_waste.")
51
  return {"Error": "No image provided."}
52
-
 
 
 
 
 
 
 
53
  try:
54
- print("Image received. Starting pre-processing.")
55
- # Pre-process the image
56
- # 1. Resize the image to the target size
 
 
 
 
 
 
 
57
  print(f"Resizing image to ({IMG_WIDTH}, {IMG_HEIGHT})")
58
  img = image.resize((IMG_WIDTH, IMG_HEIGHT))
59
- print("Image resized.")
60
-
61
- # 2. Convert the image to a numpy array
62
- print("Converting image to numpy array.")
63
  img_array = np.array(img)
64
- print(f"Numpy array shape: {img_array.shape}")
65
-
66
- # 3. Expand dimensions to create a batch of size 1
67
- # The model expects input in the shape (batch_size, height, width, channels)
68
- print("Expanding dimensions for batch size.")
 
 
 
69
  img_array = np.expand_dims(img_array, axis=0)
70
- print(f"Array shape after expanding dims: {img_array.shape}")
71
-
72
-
73
- # 4. Normalize the image data if your model requires it
74
- # Common normalization: scaling pixel values from [0, 255] to [0, 1]
75
- # Adjust this based on how your model was trained!
76
- print("Normalizing image data.")
77
- # Check data type before normalization - common source of errors
78
- if img_array.dtype != np.float32:
79
- print(f"Warning: Image array dtype is {img_array.dtype}. Converting to float32.")
80
- img_array = img_array.astype(np.float32)
81
-
82
- img_array = img_array / 255.0 # Example normalization
83
- print("Image data normalized.")
84
-
85
-
86
- # Make a prediction
87
- print("Making prediction with the model.")
88
- predictions = model.predict(img_array)[0] # Get predictions for the single image
89
- print("Prediction made successfully.")
90
  print(f"Raw predictions: {predictions}")
91
-
92
-
93
- # Get the confidence scores for each class
94
- print("Processing prediction results.")
95
- if len(predictions) != len(CLASS_NAMES):
96
- print(f"Error: Number of predictions ({len(predictions)}) does not match number of class names ({len(CLASS_NAMES)}).")
97
- return {"Error": "Prediction output shape mismatch."}
98
-
99
  confidences = {CLASS_NAMES[i]: float(predictions[i]) for i in range(len(CLASS_NAMES))}
100
- print("Confidences calculated.")
101
-
102
- # Sort confidences by probability in descending order for better display
103
  sorted_confidences = dict(sorted(confidences.items(), key=lambda item: item[1], reverse=True))
104
- print("Confidences sorted.")
105
- print("--- classify_waste function finished successfully ---")
106
  return sorted_confidences
107
 
108
  except Exception as e:
109
  print(f"Error during classification: {e}")
110
- # Use traceback to see the exact line where the error occurred
111
  traceback.print_exc()
112
- return {"Error": f"Classification failed: {e}. Check logs for details."}
113
-
114
- # --- Gradio Interface ---
115
- # Define the input component (webcam)
116
- # sources=['webcam'] enables webcam input
117
- # type="pil" is good as it gives a PIL Image object
118
- image_input = gr.Image(sources=['webcam'], type="pil", label="Webcam Feed")
119
-
120
- # Define the output component (label to display probabilities)
121
- # num_top_classes=len(CLASS_NAMES) shows probabilities for all classes
122
- # The gr.Label component automatically creates a box to display the results
123
- label_output = gr.Label(num_top_classes=len(CLASS_NAMES), label="Classification Results")
124
-
125
- # Create the Gradio Interface
126
- if model is not None: # Only create interface if model loaded successfully
127
- gr_interface = gr.Interface(
128
- fn=classify_waste, # The function to run
129
- inputs=image_input, # The input component
130
- outputs=label_output, # The output component
131
- title="Smart Waste Sort Classifier", # Title for the app
132
- description="Point your webcam at an item to classify it.", # Description
133
- live=True # Enable live prediction as webcam feed changes
134
- )
135
-
136
- # Launch the Gradio app
137
- # Setting share=True creates a public link (useful for testing, but be mindful of data)
138
- # Set debug=True for more detailed logs during development
139
- print("Launching Gradio interface.")
140
- gr_interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  else:
142
- print("Gradio interface not launched because the model failed to load.")
143
- # Consider adding a simple Gradio component here to display the error in the UI
144
- # Example: gr.Textbox("Model failed to load. Check logs.", label="Status").launch()
145
-
 
 
 
 
1
  import gradio as gr
2
  import tensorflow as tf
3
+ from tensorflow.keras.applications import efficientnet # Add this import for preprocessing
4
  import numpy as np
5
+ from PIL import Image
6
+ import traceback
7
 
8
  # Define the path to your Keras model file
 
9
  MODEL_PATH = 'ifswaste_classification_model_initial.keras'
10
 
11
+ # Update image dimensions to match training (260x260 instead of 224x224)
12
+ IMG_WIDTH = 260
13
+ IMG_HEIGHT = 260
 
14
 
15
+ # Update class names to match training order exactly
16
+ CLASS_NAMES = ['paper', 'plastic', 'glass', 'battery', 'organic', 'metal']
 
17
 
18
  # --- Model Loading ---
 
19
  try:
20
  print(f"Attempting to load model from path: {MODEL_PATH}")
21
  model = tf.keras.models.load_model(MODEL_PATH)
22
  print(f"Model loaded successfully from {MODEL_PATH}")
23
+ print(f"Model input shape: {model.input_shape}")
24
+ print(f"Model output shape: {model.output_shape}")
25
  except Exception as e:
26
  print(f"Error loading model: {e}")
 
27
  traceback.print_exc()
28
+ model = None
29
 
30
  # --- Prediction Function ---
31
  def classify_waste(image):
32
  """
33
  Classifies the input image using the loaded Keras model.
 
 
 
 
 
 
 
34
  """
35
+ print("=== CLASSIFY_WASTE FUNCTION TRIGGERED ===")
36
+
37
  if model is None:
38
  print("Error: Model is None inside classify_waste.")
39
  return {"Error": "Model failed to load during app startup."}
40
 
41
  if image is None:
42
+ print("Error: Image is None - no valid image data received")
43
  return {"Error": "No image provided."}
44
+
45
+ # Print image type and info for debugging
46
+ print(f"Image type: {type(image)}")
47
+ if hasattr(image, 'size'):
48
+ print(f"Image size: {image.size}")
49
+ elif hasattr(image, 'shape'):
50
+ print(f"Image shape: {image.shape}")
51
+
52
  try:
53
+ # Convert image to PIL Image if it's not already
54
+ if not isinstance(image, Image.Image):
55
+ print(f"Converting image from {type(image)} to PIL Image")
56
+ if isinstance(image, np.ndarray):
57
+ image = Image.fromarray(image.astype('uint8'))
58
+ else:
59
+ print(f"Unsupported image type: {type(image)}")
60
+ return {"Error": f"Unsupported image type: {type(image)}"}
61
+
62
+ # Resize to match training dimensions
63
  print(f"Resizing image to ({IMG_WIDTH}, {IMG_HEIGHT})")
64
  img = image.resize((IMG_WIDTH, IMG_HEIGHT))
65
+
66
+ # Convert to numpy array
67
+ print("Converting image to numpy array")
 
68
  img_array = np.array(img)
69
+ print(f"Numpy array shape: {img_array.shape}, dtype: {img_array.dtype}")
70
+
71
+ # IMPORTANT: Apply the SAME preprocessing used during training
72
+ print("Applying EfficientNet preprocessing")
73
+ img_array = efficientnet.preprocess_input(img_array)
74
+ print(f"Array shape after preprocessing: {img_array.shape}")
75
+
76
+ # Expand dimensions for batch
77
  img_array = np.expand_dims(img_array, axis=0)
78
+
79
+ # Make prediction
80
+ print("Making prediction with the model")
81
+ predictions = model.predict(img_array)[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  print(f"Raw predictions: {predictions}")
83
+
84
+ # Map predictions to class names
 
 
 
 
 
 
85
  confidences = {CLASS_NAMES[i]: float(predictions[i]) for i in range(len(CLASS_NAMES))}
 
 
 
86
  sorted_confidences = dict(sorted(confidences.items(), key=lambda item: item[1], reverse=True))
87
+ print("=== CLASSIFY_WASTE FUNCTION COMPLETED SUCCESSFULLY ===")
 
88
  return sorted_confidences
89
 
90
  except Exception as e:
91
  print(f"Error during classification: {e}")
 
92
  traceback.print_exc()
93
+ return {"Error": f"Classification failed: {e}"}
94
+
95
+ # --- Gradio Interface with Blocks ---
96
+ def create_gradio_interface():
97
+ with gr.Blocks() as demo:
98
+ gr.Markdown("# Smart Waste Sort Classifier")
99
+ gr.Markdown("Point your webcam at an item and click 'Classify' to identify it.")
100
+
101
+ with gr.Row():
102
+ with gr.Column():
103
+ # Use webcam with explicit capture button
104
+ image_input = gr.Image(source="webcam", type="pil", label="Webcam Feed")
105
+ classify_btn = gr.Button("Classify Waste", variant="primary")
106
+
107
+ with gr.Column():
108
+ label_output = gr.Label(num_top_classes=len(CLASS_NAMES), label="Classification Results")
109
+ debug_output = gr.Textbox(label="Debug Info", visible=True)
110
+
111
+ # Connect the button click to the classify function
112
+ classify_btn.click(
113
+ fn=classify_waste,
114
+ inputs=image_input,
115
+ outputs=label_output
116
+ )
117
+
118
+ # Add a secondary connection to show status in the UI
119
+ classify_btn.click(
120
+ fn=lambda img: "Image captured and sent for classification" if img is not None else "No image captured - please allow camera access",
121
+ inputs=image_input,
122
+ outputs=debug_output
123
+ )
124
+
125
+ # Add a clear button for convenience
126
+ clear_btn = gr.Button("Clear")
127
+ clear_btn.click(
128
+ fn=lambda: (None, "Cleared", None),
129
+ inputs=[],
130
+ outputs=[image_input, debug_output, label_output]
131
+ )
132
+
133
+ return demo
134
+
135
+ # Launch the interface
136
+ if model is not None:
137
+ print("Launching Gradio interface")
138
+ demo = create_gradio_interface()
139
+ demo.launch()
140
  else:
141
+ print("Model failed to load - not launching interface")
142
+ gr.Interface(
143
+ fn=lambda: "Model failed to load. Check logs for details.",
144
+ inputs=None,
145
+ outputs="text",
146
+ title="Error Loading Model"
147
+ ).launch()