Spaces:
Sleeping

Tdanyim commited on
Commit
d159574
·
verified ·
1 Parent(s): dbde161

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -0
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (01) IMPORT LIBRARIES
2
+ # Import Libraries for EDA
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+
6
+ # Import Libraries for Data Preprocessing
7
+ import gradio as gr
8
+ from tensorflow.keras.preprocessing import image as keras_image
9
+
10
+ # Import Libraries for AI Model Training
11
+ import tensorflow as tf
12
+ from tensorflow.keras.optimizers import Adam
13
+ from tensorflow.keras.applications import ResNet50
14
+ from tensorflow.keras.models import Model, Sequential
15
+ from tensorflow.keras.layers import Input, Conv2D, Dropout, Flatten, Dense, MaxPool2D, GlobalAveragePooling2D, BatchNormalization
16
+
17
+
18
+
19
+ # (02) AI MODEL SETUP
20
+ def model_resnet():
21
+
22
+ # Load pre-trained ResNet50 model with weights trained on ImageNet data
23
+ resnet_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # input_shape=(32, 32, 3)
24
+
25
+ # Freeze the layers of the pre-trained model
26
+ for layer in resnet_model.layers:
27
+ layer.trainable = True
28
+
29
+ # Build the custom model using ResNet50 as a feature extractor
30
+ x = resnet_model.output
31
+ x = GlobalAveragePooling2D()(x)
32
+ x = Dense(256,kernel_regularizer='l2',activation='relu')(x)
33
+ x = Dropout(0.5)(x)
34
+ x = Dense(5, activation='softmax')(x)
35
+ model_resnet = Model(inputs=resnet_model.input, outputs=x)
36
+
37
+ # Compile the model
38
+ model_resnet.compile(loss="categorical_crossentropy", optimizer=Adam(learning_rate=0.0001), metrics=["acc"])
39
+
40
+ # # Display the model architecture
41
+ # model_resnet.summary()
42
+
43
+ return model_resnet
44
+
45
+ # Initialize model
46
+ model = model_resnet()
47
+
48
+
49
+
50
+ # (03) GUI
51
+ # Define a dictionary mapping class indices to labels
52
+ class_names = {0: "No DR", 1: "Mild", 2: "Moderate", 3: "Severe", 4: "Proliferative DR"}
53
+
54
+ # For convenience: an ordered list to build a probs dict for gr.Label
55
+ CLASS_LIST = [class_names[i] for i in range(len(class_names))]
56
+
57
+ # Grad-CAM function
58
+ def get_gradcam_heatmap(img_array, model, last_conv_layer_name):
59
+ grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(last_conv_layer_name).output, model.output])
60
+
61
+ with tf.GradientTape() as tape:
62
+ last_conv_layer_output, preds = grad_model(img_array)
63
+ last_conv_layer_output = tf.convert_to_tensor(last_conv_layer_output)
64
+
65
+ class_idx = tf.argmax(preds[0]) # Focus on the predicted class
66
+ class_channel = preds[:, class_idx]
67
+
68
+ grads = tape.gradient(class_channel, last_conv_layer_output)
69
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
70
+ last_conv_layer_output = last_conv_layer_output[0]
71
+ heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
72
+ heatmap = tf.squeeze(heatmap)
73
+
74
+ heatmap = tf.maximum(heatmap, 0)
75
+ heatmap /= tf.math.reduce_max(heatmap)
76
+
77
+ return heatmap.numpy()
78
+
79
+ # Function to display Grad-CAM overlay on the image
80
+ def display_gradcam_on_image(img, heatmap, alpha=0.4):
81
+ heatmap = np.uint8(255 * heatmap) # Rescale heatmap to 0-255
82
+ jet = plt.get_cmap("jet")
83
+ jet_colors = jet(np.arange(256))[:, :3] # Extract RGB values
84
+ jet_heatmap = jet_colors[heatmap] # Apply the colormap to the heatmap
85
+
86
+ jet_heatmap = keras_image.array_to_img(jet_heatmap)
87
+ jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0])) # Resize to match image size
88
+ jet_heatmap = keras_image.img_to_array(jet_heatmap) # Convert back to array
89
+
90
+ # Ensure the heatmap has the correct shape (224, 224, 3)
91
+ jet_heatmap = np.squeeze(jet_heatmap)
92
+
93
+ superimposed_img = jet_heatmap * alpha + img # Ensure same shape
94
+ superimposed_img = np.uint8(superimposed_img) # Convert back to uint8
95
+
96
+ return keras_image.array_to_img(superimposed_img)
97
+
98
+ # Prediction function with Grad-CAM integration
99
+ def predict_dr(image):
100
+ # Convert PIL image to numpy array
101
+ img_array = np.array(image)
102
+
103
+ # Resize and normalize the image
104
+ img_resized = tf.image.resize(img_array, (224, 224))
105
+ img_resized = img_resized / 255.0
106
+ img_resized = np.expand_dims(img_resized, axis=0)
107
+
108
+ # Prediction
109
+ prediction = model.predict(img_resized)
110
+ class_idx = np.argmax(prediction, axis=1)[0]
111
+ class_prob = np.max(prediction)
112
+
113
+ # Get Grad-CAM heatmap
114
+ last_conv_layer_name = "conv5_block3_out" # Adjust according to your model
115
+ heatmap = get_gradcam_heatmap(img_resized, model, last_conv_layer_name)
116
+
117
+ # Overlay heatmap on the original image
118
+ gradcam_img = display_gradcam_on_image(img_array, heatmap)
119
+
120
+ # Prepare the probabilities for display in a sorted list
121
+ probs_dict = {CLASS_LIST[i]: float(prediction[0][i]) for i in range(len(CLASS_LIST))}
122
+ sorted_probs = {k: v for k, v in sorted(probs_dict.items(), key=lambda item: item[1], reverse=True)}
123
+
124
+ return f"{class_idx} - {class_names[class_idx]} ({class_prob:.4%})", sorted_probs, gradcam_img
125
+
126
+ # Load the model before running the interface (Ensure model is loaded correctly)
127
+ model.load_weights("/content/drive/MyDrive/PhD/UofExeter/reconstructionProject/PythonCode/UoEchallenge/LTHE/modelWeight/mcRN50.keras")
128
+
129
+ # Define the Gradio interface for the GUI
130
+ iface = gr.Interface(
131
+ fn=predict_dr, # Function to be called on interaction
132
+ inputs=gr.Image(image_mode='RGB'), # Image input (no 'source' argument)
133
+ outputs=[gr.Label(num_top_classes=5, label="Prediction"), gr.Label(label="Class Probabilities"), gr.Image(label="XAI - Grad-CAM")], # Class prediction, probability, and Grad-CAM image output
134
+ title="Diabetic Retinopathy Detection",
135
+ description="Upload a retinal image to predict the stage of diabetic retinopathy and see the confidence level with a Grad-CAM explanation.",
136
+ examples=["/content/000c1434d8d7.png", "/content/001639a390f0.png"], # Example images
137
+ )
138
+
139
+ # Launch the Gradio interface
140
+ iface.launch(share=True) # , debug=True
141
+