File size: 15,875 Bytes
a24a248
8e65023
 
 
 
 
a24a248
42b9758
a24a248
 
6745847
a24a248
 
 
 
cc794df
8e65023
a24a248
cc794df
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc794df
a24a248
 
 
 
 
 
cc794df
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc794df
a24a248
cc794df
a24a248
cc794df
8e65023
 
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e65023
a24a248
 
e971d5b
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e971d5b
a24a248
cc794df
d0832f3
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc794df
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc794df
a24a248
 
 
 
 
 
cc794df
a24a248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc794df
a24a248
ef01b2a
a24a248
 
 
 
 
 
 
 
 
c4b6b56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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