{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":13319459,"sourceType":"datasetVersion","datasetId":8443768}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# ## AI-Assisted Diabetic Retinopathy (DR) Severity Assessment\n# This script launches a Gradio web interface for the trained DR classification model.\n\n# --- 1. Installation & Imports ---\nprint(\"Installing Gradio...\")\n!pip install -q gradio\n\nimport gradio as gr\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers, Model\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom PIL import Image\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(\"Libraries imported.\")\n\n# --- 2. System Configuration ---\nIMG_SIZE = (384, 384)\nNUM_CLASSES = 5\nCLASS_LABELS = [\"No DR\", \"Mild\", \"Moderate\", \"Severe\", \"Proliferative DR\"]\n\n# --- 3. Model Architecture Definition ---\n# This function defines the model's structure and MUST be identical to the one used for training.\ndef build_simple_model(input_shape=IMG_SIZE + (3,), n_classes=NUM_CLASSES):\n    \"\"\"\n    Builds the EfficientNetB0 model architecture for inference.\n    Initializes with ImageNet weights to ensure correct weight loading.\n    \"\"\"\n    base = EfficientNetB0(include_top=False, weights='imagenet', input_shape=input_shape)\n    inputs = layers.Input(shape=input_shape)\n    x = base(inputs, training=False) # Set training=False for inference\n    x = layers.GlobalAveragePooling2D()(x)\n    x = layers.Dropout(0.3)(x)\n    outputs = layers.Dense(n_classes, activation='softmax')(x)\n    model = Model(inputs, outputs)\n    return model\n\n# --- 4. Load Trained Model ---\nprint(\"Loading the trained DR classification model...\")\ntry:\n    # Build the empty model structure\n    model = build_simple_model()\n\n    # Load the saved weights from your Kaggle Dataset\n    model_path = '/kaggle/input/aptos-best-model-yewale/best_model.h5'\n    model.load_weights(model_path)\n    print(\"✅ Model loaded successfully.\")\nexcept Exception as e:\n    print(f\"🔴 Error loading model: {e}\")\n    model = None # Set model to None if loading fails\n\n# --- 5. Core Prediction Function ---\n# This function takes a user-uploaded image, preprocesses it, and returns the model's prediction.\ndef classify_retina_image(input_image: Image.Image):\n    \"\"\"\n    Takes a PIL image, preprocesses it according to the training pipeline,\n    and returns a dictionary of class labels and their probabilities.\n    \"\"\"\n    if not model:\n        return {\"Error\": \"Model is not available.\"}\n\n    # Preprocessing Steps:\n    # 1. Resize to the model's expected input size (384x384).\n    img = input_image.resize((IMG_SIZE[1], IMG_SIZE[0]))\n    \n    # 2. Convert to a NumPy array and rescale pixel values to [0, 1].\n    img_array = np.array(img) / 255.0\n    \n    # 3. Add a batch dimension.\n    img_batch = np.expand_dims(img_array, axis=0)\n    \n    # Perform prediction\n    prediction_probs = model.predict(img_batch)[0]\n    \n    # Format the output for Gradio's Label component (dictionary of confidences)\n    confidences = {label: float(prob) for label, prob in zip(CLASS_LABELS, prediction_probs)}\n    \n    return confidences\n\n# --- 6. Define the Gradio Interface ---\nprint(\"Configuring the Gradio web interface...\")\n\n# Markdown text for providing clinical context and disclaimers\ndescription_md = \"\"\"\n### **Educational Tool for AI-Assisted DR Severity Assessment**\nUpload a retinal fundus image to see how the AI model classifies the severity of Diabetic Retinopathy.\n\n**Understanding the Severity Levels:**\n* **0 - No DR:** No abnormalities detected.\n* **1 - Mild:** Presence of microaneurysms.\n* **2 - Moderate:** More than just microaneurysms, but less severe than Severe DR.\n* **3 - Severe:** Characterized by >20 intraretinal hemorrhages, definite venous beading, or prominent IRMA.\n* **4 - Proliferative DR:** The most advanced stage, featuring neovascularization or vitreous/preretinal hemorrhage.\n\n*This tool is a demonstration of a deep learning model and is for **educational purposes only**. It is **not a medical device** and should not be used for self-diagnosis or as a substitute for professional medical advice.*\n\"\"\"\n\narticle_md = \"\"\"\n---\n**Disclaimer:** This is an experimental AI tool. The classifications provided are not a medical diagnosis. Always consult a qualified ophthalmologist or healthcare provider for any medical concerns. The model's accuracy, while high, is not perfect and may produce incorrect classifications.\n\"\"\"\n\n# Example images from the original dataset for users to try\n# NOTE: You must add the original competition dataset to your notebook for these paths to work.\nexample_paths = [\n    '/kaggle/input/aptos2019-blindness-detection/train_images/000c1434d8d7.png', # Class 2\n    '/kaggle/input/aptos2019-blindness-detection/train_images/001639a390f0.png', # Class 4\n    '/kaggle/input/aptos2019-blindness-detection/train_images/0024cdab0c1e.png', # Class 1\n    '/kaggle/input/aptos2019-blindness-detection/train_images/002c21358ce6.png'  # Class 0\n]\n\n# Create the Gradio Interface\ndemo = gr.Interface(\n    fn=classify_retina_image,\n    inputs=gr.Image(type=\"pil\", label=\"Upload Retinal Fundus Image\"),\n    outputs=gr.Label(num_top_classes=5, label=\"Classification Results\"),\n    title=\"AI-Assisted Diabetic Retinopathy Severity Assessment\",\n    description=description_md,\n    article=article_md,\n    examples=example_paths,\n    allow_flagging=\"never\",\n    theme=gr.themes.Soft()\n)\n\n# --- 7. Launch the Application ---\nprint(\"Launching Gradio app... A public URL will be generated.\")\n# The 'share=True' argument creates a temporary, public link.\n# The 'debug=True' argument prints helpful messages in the notebook log.\ndemo.launch(share=True, debug=True)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-19T06:39:30.658818Z","iopub.execute_input":"2025-10-19T06:39:30.659005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}