import gradio as gr import tensorflow as tf import numpy as np from PIL import Image import json import os import logging # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Global variables model = None class_names = [] def load_model(): """Load your trained model with better error handling""" try: # Option 1: Try loading complete model first complete_model_paths = ['model.h5', 'complete_model.h5', 'skin_cancer_model.h5'] for model_path in complete_model_paths: if os.path.exists(model_path): logger.info(f"Loading complete model from {model_path}") model = tf.keras.models.load_model(model_path, compile=False) logger.info("Complete model loaded successfully") logger.info(f"Model input shape: {model.input_shape}") logger.info(f"Model output shape: {model.output_shape}") return model # Option 2: Load from JSON architecture + weights (your specific files) json_path = 'completemodel1 (1).json' weights_path = 'completeweights.weights.h5' if os.path.exists(json_path) and os.path.exists(weights_path): logger.info(f"Loading model architecture from {json_path} and weights from {weights_path}") # Load model architecture with open(json_path, 'r') as json_file: model_json = json_file.read() model = tf.keras.models.model_from_json(model_json) # Load weights model.load_weights(weights_path) logger.info("Model loaded from JSON + weights successfully") logger.info(f"Model input shape: {model.input_shape}") logger.info(f"Model output shape: {model.output_shape}") return model # Option 3: Try alternative JSON file names alternative_json_paths = ['model.json', 'completemodel1.json', 'architecture.json'] for json_path in alternative_json_paths: if os.path.exists(json_path) and os.path.exists(weights_path): logger.info(f"Loading model architecture from {json_path} and weights from {weights_path}") with open(json_path, 'r') as json_file: model_json = json_file.read() model = tf.keras.models.model_from_json(model_json) model.load_weights(weights_path) logger.info("Model loaded from alternative JSON + weights successfully") logger.info(f"Model input shape: {model.input_shape}") logger.info(f"Model output shape: {model.output_shape}") return model # Option 4: Create a common skin cancer model architecture (fallback) if os.path.exists(weights_path): logger.warning("Only weights file found. Trying common skin cancer architecture...") logger.warning("This might not work if architecture doesn't match!") # Common skin cancer classification architecture model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(71, 71, 3)), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(256, (3, 3), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.3), tf.keras.layers.Dense(7, activation='softmax') # 7 classes for skin cancer ]) try: model.load_weights(weights_path) logger.info("Weights loaded into fallback architecture") return model except Exception as e: logger.error(f"Failed to load weights into fallback architecture: {e}") return None logger.error("No valid model files found") logger.error("Available files:", os.listdir('.')) return None except Exception as e: logger.error(f"Error loading model: {e}") return None def load_class_names(): """Load class names with multiple fallback options""" try: # Define the correct order of classes for HAM10000 dataset HAM10000_CLASSES = [ 'Melanoma', 'Melanocytic nevus', 'Basal cell carcinoma', 'Actinic keratosis / Bowen\'s disease', 'Benign keratosis', 'Dermatofibroma', 'Vascular lesion' ] # Try loading from JSON file first json_path = 'class_names_example.json' if os.path.exists(json_path): with open(json_path, 'r') as f: loaded_classes = json.load(f) # Map loaded classes to HAM10000 order if possible if isinstance(loaded_classes, dict): # If it's a mapping dictionary, use it to reorder ordered_classes = [] for class_name in HAM10000_CLASSES: if class_name in loaded_classes: ordered_classes.append(loaded_classes[class_name]) else: ordered_classes.append(class_name) logger.info(f"Loaded and mapped {len(ordered_classes)} class names from JSON") return ordered_classes else: # If it's a list, ensure it matches HAM10000 order if len(loaded_classes) == len(HAM10000_CLASSES): logger.info(f"Loaded {len(loaded_classes)} class names from JSON") return loaded_classes # Try loading from text file txt_path = 'class_names.txt' if os.path.exists(txt_path): with open(txt_path, 'r') as f: loaded_classes = [line.strip() for line in f.readlines() if line.strip()] if len(loaded_classes) == len(HAM10000_CLASSES): logger.info(f"Loaded {len(loaded_classes)} class names from text file") return loaded_classes # Fallback: Use HAM10000 class names in correct order logger.warning("No valid class names file found, using HAM10000 classes in correct order") return HAM10000_CLASSES except Exception as e: logger.error(f"Error loading class names: {e}") # Return HAM10000 classes in correct order as fallback return [ 'Melanoma', 'Melanocytic nevus', 'Basal cell carcinoma', 'Actinic keratosis / Bowen\'s disease', 'Benign keratosis', 'Dermatofibroma', 'Vascular lesion' ] def preprocess_image(image): """Preprocess the input image with validation""" try: if image is None: logger.warning("No image provided") return None logger.info(f"Original image size: {image.size}, mode: {image.mode}") # Convert to RGB if needed if image.mode != 'RGB': image = image.convert('RGB') logger.info("Converted image to RGB") # Resize to model input size (71x71 based on your model) target_size = (71, 71) image = image.resize(target_size, Image.Resampling.LANCZOS) logger.info(f"Resized image to {target_size}") # Convert to array and normalize image_array = np.array(image, dtype=np.float32) / 255.0 logger.info(f"Image array shape: {image_array.shape}") # Add batch dimension image_array = np.expand_dims(image_array, axis=0) logger.info(f"Final input shape: {image_array.shape}") return image_array except Exception as e: logger.error(f"Error preprocessing image: {e}") return None def predict_image(image): """Make prediction with comprehensive error handling""" try: if image is None: return "❌ Please upload an image" if model is None: return "❌ Model not loaded. Please check if model files exist." if not class_names: return "❌ Class names not loaded properly" logger.info("Starting prediction...") # Preprocess image processed_image = preprocess_image(image) if processed_image is None: return "❌ Error processing image" # Make prediction with timeout handling logger.info("Making prediction...") predictions = model.predict(processed_image, verbose=0) logger.info(f"Prediction completed. Output shape: {predictions.shape}") # Handle different prediction formats if len(predictions.shape) > 1: probabilities = predictions[0] else: probabilities = predictions logger.info(f"Probabilities shape: {probabilities.shape}") logger.info(f"Number of classes: {len(class_names)}") # Ensure we don't have dimension mismatch if len(probabilities) != len(class_names): logger.warning(f"Mismatch: {len(probabilities)} predictions vs {len(class_names)} class names") return "❌ Error: Model output doesn't match class names" # Get top prediction predicted_index = np.argmax(probabilities) predicted_class = class_names[predicted_index] confidence = float(probabilities[predicted_index]) logger.info(f"Predicted: {predicted_class} with confidence: {confidence}") # Format result text with class index for debugging result_text = f"Predicted Class: {predicted_class} (Class ID: {predicted_index}, Confidence: {confidence*100:.2f}%)" return result_text except Exception as e: error_msg = f"❌ Error during prediction: {str(e)}" logger.error(error_msg) return error_msg def initialize_model(): """Initialize model and class names""" global model, class_names logger.info("Initializing model and class names...") logger.info(f"Available files: {os.listdir('.')}") # Load class names first class_names = load_class_names() logger.info(f"Available classes: {class_names}") # Load model model = load_model() if model is None: logger.error("Failed to load model - check your files:") logger.error("Expected files:") logger.error("- completemodel1 (1).json + completeweights.weights.h5") logger.error("- OR any complete .h5 model file") else: logger.info("✅ Model loaded successfully") def create_interface(): """Create the Gradio interface with improved error handling""" css = """ .gradio-container { font-family: 'Helvetica Neue', Arial, sans-serif; } .main-header { text-align: center; margin-bottom: 30px; } .prediction-output { font-size: 16px; } .error-message { color: red; font-weight: bold; } """ with gr.Blocks(css=css, title="Skin Cancer Classifier") as demo: gr.Markdown( """ # 🔬 Skin Cancer Classification Model Upload a skin lesion image to get AI-powered classification results! *Instructions:* 1. Upload an image using the file uploader 2. The model will automatically process your image 3. View prediction result *⚠ Disclaimer:* This is for educational purposes only and should not replace professional medical diagnosis. """, elem_classes="main-header" ) # Status indicator model_status = "✅ Ready" if model is not None else "❌ Not Loaded" status_text = gr.Markdown( f"*Model Status:* {model_status}\n" f"*Classes Available:* {len(class_names)}\n" f"*Input Size:* 71x71 pixels" ) with gr.Row(): with gr.Column(scale=1): input_image = gr.Image( type="pil", label="Upload Skin Lesion Image", height=400 ) predict_btn = gr.Button( "🔍 Analyze Image", variant="primary", size="lg" ) # Clear button clear_btn = gr.Button( "🗑 Clear", variant="secondary" ) with gr.Column(scale=1): prediction_text = gr.Markdown( "Upload an image to see prediction result...", elem_classes="prediction-output" ) # Model information with gr.Accordion("ℹ Model Information", open=False): model_info = f""" *Model Details:* - Status: {'✅ Loaded' if model is not None else '❌ Not Loaded'} - Total Classes: {len(class_names)} - Expected Input Size: 71x71 pixels - Model Type: Convolutional Neural Network for Skin Cancer Classification *Skin Condition Classes:* {chr(10).join([f"• {class_name}" for class_name in class_names])} *Files Used:* - Model Architecture: completemodel1 (1).json - Model Weights: completeweights.weights.h5 - Class Names: class_names_example.json *Troubleshooting:* - Make sure all required files exist in the same directory - Check the logs tab for detailed error messages - Ensure image is clear and shows a skin lesion """ gr.Markdown(model_info) # Event handlers predict_btn.click( fn=predict_image, inputs=[input_image], outputs=[prediction_text] ) # Auto-predict on image change input_image.change( fn=predict_image, inputs=[input_image], outputs=[prediction_text] ) # Clear functionality clear_btn.click( lambda: (None, "Upload an image to see prediction result..."), outputs=[input_image, prediction_text] ) return demo # Initialize everything if __name__ == "__main__": # Initialize model and class names first initialize_model() # Create and launch interface demo = create_interface() demo.launch( share=True, server_name="0.0.0.0", server_port=7860, debug=True )# Enable debug mode for better error reporting