import gradio as gr import tensorflow as tf import numpy as np from PIL import Image import cv2 from tensorflow.keras.models import model_from_json import os print("✅ Gradio app: Starting up...") # --- LOAD THE TRAINED MODEL --- # Model architecture and weights are expected in the same directory as the app.py script model_architecture_path = './model_architecture.json' model_weights_path = './model_weights.weights.h5' model = None # Initialize model as None try: print("✅ Gradio app: Attempting to load model from JSON and H5 weights...") if os.path.exists(model_architecture_path) and os.path.exists(model_weights_path): with open(model_architecture_path, 'r') as json_file: loaded_model_json = json_file.read() # Need custom objects if your model uses them (e.g., custom layers) # For this specific EfficientNet-like structure, standard layers might suffice # If you have custom layers, you'll need custom_objects parameter model = model_from_json(loaded_model_json) model.load_weights(model_weights_path) print("✅ Gradio app: Model loaded successfully from JSON and H5 weights") else: print("❌ Gradio app: Model architecture or H5 weights file not found.") except Exception as load_e: print(f"❌ Gradio app: Error loading model: {load_e}") model = None # Ensure model is None on failure if model is None: print("🛑 Gradio app: Model could not be loaded. Prediction function will not work.") # --- PREDICTION FUNCTION FOR GRADIO --- def predict_cataract(image): """Predict cataract with the loaded model""" if model is None: return "Error: Model could not be loaded. Cannot make prediction." try: # Preprocess image img_array = np.array(image) # Ensure image is in RGB format if it's grayscale or RGBA if img_array.shape[-1] == 4: img_array = cv2.cvtColor(img_array, cv2.COLOR_RGBA2RGB) elif len(img_array.shape) == 2: img_array = cv2.cvtColor(img_array, cv2.COLOR_GRAY2RGB) img_array = cv2.resize(img_array, (224, 224)) img_array = img_array.astype('float32') / 255.0 img_array = np.expand_dims(img_array, axis=0) # Make prediction prediction = model.predict(img_array)[0][0] # Convert to percentage and class probability = float(prediction) class_name = "Normal" if probability < 0.5 else "Cataract" # Calculate confidence based on which class was predicted confidence = probability if class_name == "Cataract" else (1 - probability) confidence_percent = confidence * 100 result = f""" 🚨 **OVERFITTED MODEL WARNING** 🚨 This model has data leakage - results are unreliable! 📊 **Prediction**: {class_name} 📈 **Confidence**: {confidence_percent:.1f}% 🎭 **Raw Score**: {probability:.4f} ⚠️ **Do NOT trust these results for medical decisions!** This is for educational demonstration only. """ return result except Exception as e: return f"Error during prediction: {str(e)}" # Create Gradio interface demo = gr.Interface( fn=predict_cataract, inputs=gr.Image(type="pil", label="Upload Eye Image"), outputs=gr.Textbox(label="Overfitted Prediction (Unreliable!)"), title="👁️ Cataract Detection - OVERFITTED BEAST 🚨", description=""" **⚠️ WARNING: This model has intentional data leakage!** This demonstrates what happens when ML models "cheat" by seeing the same data during training and validation. The high accuracy (96.7%) is FAKE and doesn't represent real medical AI capability. 🎯 **Educational Purpose**: Show the importance of proper data splitting in medical AI. 🏥 **Real Medical AI**: Typically achieves 80-90% accuracy with proper validation. """, # Add example images (you'll need to upload example images to the repo) # Make sure example images are in the 'hf_model_overfitted' directory before upload examples=[], # Add example paths here, e.g., ["example1.jpg", "example2.jpg"] theme=gr.themes.Soft() ) if __name__ == "__main__": print(" 🚀 Gradio app: Launching interface...") demo.launch()