Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 5 |
-
import traceback
|
| 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 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
IMG_HEIGHT = 224
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 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
|
| 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("
|
|
|
|
| 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:
|
| 51 |
return {"Error": "No image provided."}
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
print(f"Resizing image to ({IMG_WIDTH}, {IMG_HEIGHT})")
|
| 58 |
img = image.resize((IMG_WIDTH, IMG_HEIGHT))
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
print("Converting image to numpy array.")
|
| 63 |
img_array = np.array(img)
|
| 64 |
-
print(f"Numpy array shape: {img_array.shape}")
|
| 65 |
-
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
img_array = np.expand_dims(img_array, axis=0)
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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("
|
| 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}
|
| 113 |
-
|
| 114 |
-
# --- Gradio Interface ---
|
| 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 |
else:
|
| 142 |
-
print("
|
| 143 |
-
|
| 144 |
-
|
| 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()
|