import gradio as gr import tensorflow as tf from tensorflow.keras.applications import efficientnet import numpy as np from PIL import Image import traceback import time import sys # Print debugging information to make sure logs are visible print(f"Python version: {sys.version}") print(f"TensorFlow version: {tf.__version__}") print(f"NumPy version: {np.__version__}") print(f"PIL version: {Image.__version__}") # Define the path to your Keras model file MODEL_PATH = 'ifswaste_classification_model_initial.keras' # Image dimensions to match training IMG_WIDTH = 260 IMG_HEIGHT = 260 # Class names to match training order exactly CLASS_NAMES = ['paper', 'plastic', 'glass', 'battery', 'organic', 'metal'] # --- Model Loading --- try: print(f"Attempting to load model from path: {MODEL_PATH}") model = tf.keras.models.load_model(MODEL_PATH) print(f"Model loaded successfully from {MODEL_PATH}") print(f"Model input shape: {model.input_shape}") print(f"Model output shape: {model.output_shape}") except Exception as e: print(f"Error loading model: {e}") traceback.print_exc() model = None # --- Prediction Function --- def classify_waste(image): """ Classifies the input image using the loaded Keras model. """ timestamp = time.strftime("%Y-%m-%d %H:%M:%S") print(f"=== CLASSIFY_WASTE FUNCTION TRIGGERED AT {timestamp} ===") if model is None: print("Error: Model is None inside classify_waste.") return {"Error": 1.0} if image is None: print("Error: Image is None - no valid image data received") return {"No image provided": 1.0} # Print image type and info for debugging print(f"Image type: {type(image)}") if hasattr(image, 'size'): print(f"Image size: {image.size}") elif hasattr(image, 'shape'): print(f"Image shape: {image.shape}") try: # Convert image to PIL Image if it's not already if not isinstance(image, Image.Image): print(f"Converting image from {type(image)} to PIL Image") if isinstance(image, np.ndarray): # Make sure the array has valid values if image.size == 0: print("Error: Empty numpy array") return {"Empty image data": 1.0} # Ensure the array is uint8 for PIL if image.dtype != np.uint8: print(f"Converting array from {image.dtype} to uint8") # Scale values if needed if image.max() <= 1.0: image = (image * 255).astype(np.uint8) else: image = image.astype(np.uint8) # Convert to PIL image = Image.fromarray(image) else: print(f"Unsupported image type: {type(image)}") return {"Unsupported image format": 1.0} # Resize to match training dimensions print(f"Resizing image to ({IMG_WIDTH}, {IMG_HEIGHT})") img = image.resize((IMG_WIDTH, IMG_HEIGHT)) # Check if image has correct mode (RGB) if img.mode != "RGB": print(f"Converting image from {img.mode} to RGB") img = img.convert("RGB") # Convert to numpy array print("Converting image to numpy array") img_array = np.array(img) print(f"Numpy array shape: {img_array.shape}, dtype: {img_array.dtype}") # IMPORTANT: Apply the SAME preprocessing used during training print("Applying EfficientNet preprocessing") img_array = efficientnet.preprocess_input(img_array) print(f"Array shape after preprocessing: {img_array.shape}") # Expand dimensions for batch img_array = np.expand_dims(img_array, axis=0) # Make prediction print("Making prediction with the model") predictions = model.predict(img_array, verbose=0)[0] print(f"Raw predictions: {predictions}") # Format predictions in the way Gradio's Label component expects # Gradio Label component expects a dictionary with class names as keys and confidences as values result = {CLASS_NAMES[i]: float(predictions[i]) for i in range(len(CLASS_NAMES))} print(f"Predictions as dictionary: {result}") print("=== CLASSIFY_WASTE FUNCTION COMPLETED SUCCESSFULLY ===") return result except Exception as e: print(f"Error during classification: {e}") traceback.print_exc() return {"Error: " + str(e): 1.0} # --- Gradio Interface --- if model is not None: print("Creating Gradio interface") with gr.Blocks(title="Smart Waste Sort Classifier") as demo: gr.Markdown("# Smart Waste Sort Classifier") gr.Markdown("Point your webcam at an item and click 'Classify' to identify it.") with gr.Row(): with gr.Column(): # Use webcam input component image_input = gr.Image(sources=["webcam"], type="numpy", label="Webcam Feed") classify_btn = gr.Button("Classify", variant="primary") with gr.Column(): label_output = gr.Label(label="Classification Results") # Connect the button to the classification function classify_btn.click( fn=classify_waste, inputs=image_input, outputs=label_output ) # Also connect the image input directly to enable auto-classification image_input.change( fn=classify_waste, inputs=image_input, outputs=label_output ) print("Launching Gradio interface") demo.launch() else: print("Model failed to load - not launching interface") gr.Interface( fn=lambda: "Model failed to load. Check logs for details.", inputs=None, outputs="text", title="Error Loading Model" ).launch()