File size: 4,315 Bytes
72a2ba1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

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()