Update app.py
Browse files
app.py
CHANGED
|
@@ -16,23 +16,33 @@ except Exception as e:
|
|
| 16 |
model = tf.keras.Model(inputs, outputs)
|
| 17 |
|
| 18 |
# ==============================================================================
|
| 19 |
-
# --- Grad-CAM Heatmap Generation Functions ---
|
| 20 |
# ==============================================================================
|
| 21 |
-
|
| 22 |
def get_last_conv_layer_name(model):
|
|
|
|
| 23 |
for layer in reversed(model.layers):
|
| 24 |
if len(layer.output.shape) == 4:
|
| 25 |
return layer.name
|
| 26 |
raise ValueError("Could not find a conv layer in the model")
|
| 27 |
|
| 28 |
def make_gradcam_heatmap(img_array, model, last_conv_layer_name):
|
|
|
|
| 29 |
grad_model = tf.keras.models.Model(
|
| 30 |
model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
|
| 31 |
)
|
| 32 |
with tf.GradientTape() as tape:
|
| 33 |
-
last_conv_layer_output, preds = grad_model([img_array])
|
| 34 |
class_channel = preds[0]
|
|
|
|
| 35 |
grads = tape.gradient(class_channel, last_conv_layer_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
| 37 |
last_conv_layer_output = last_conv_layer_output[0]
|
| 38 |
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
|
@@ -41,6 +51,7 @@ def make_gradcam_heatmap(img_array, model, last_conv_layer_name):
|
|
| 41 |
return heatmap.numpy()
|
| 42 |
|
| 43 |
def superimpose_gradcam(original_img_pil, heatmap):
|
|
|
|
| 44 |
original_img = np.array(original_img_pil)
|
| 45 |
heatmap = cv2.resize(heatmap, (original_img.shape[1], original_img.shape[0]))
|
| 46 |
heatmap = np.uint8(255 * heatmap)
|
|
@@ -51,11 +62,14 @@ def superimpose_gradcam(original_img_pil, heatmap):
|
|
| 51 |
# ==============================================================================
|
| 52 |
# --- Main Prediction Function ---
|
| 53 |
# ==============================================================================
|
| 54 |
-
|
| 55 |
last_conv_layer_name = get_last_conv_layer_name(model)
|
| 56 |
|
| 57 |
def predict_and_visualize(img):
|
|
|
|
| 58 |
try:
|
|
|
|
|
|
|
|
|
|
| 59 |
img_resized = img.resize((224, 224))
|
| 60 |
img_array = image.img_to_array(img_resized) / 255.0
|
| 61 |
img_array_expanded = np.expand_dims(img_array, axis=0)
|
|
@@ -69,7 +83,7 @@ def predict_and_visualize(img):
|
|
| 69 |
superimposed_image = superimpose_gradcam(img, heatmap)
|
| 70 |
|
| 71 |
return labels, superimposed_image
|
| 72 |
-
|
| 73 |
except Exception as e:
|
| 74 |
print("--- GRADIO APP ERROR ---")
|
| 75 |
traceback.print_exc()
|
|
@@ -78,9 +92,8 @@ def predict_and_visualize(img):
|
|
| 78 |
return {error_msg: 0.0}, None
|
| 79 |
|
| 80 |
# ==============================================================================
|
| 81 |
-
# --- Gradio Interface
|
| 82 |
# ==============================================================================
|
| 83 |
-
|
| 84 |
gr.Interface(
|
| 85 |
fn=predict_and_visualize,
|
| 86 |
inputs=gr.Image(type="pil", label="📷 Upload a Face Image"),
|
|
@@ -90,15 +103,8 @@ gr.Interface(
|
|
| 90 |
],
|
| 91 |
title="✨ Deepfake Image Detector with Visual Explanation ✨",
|
| 92 |
description="""
|
| 93 |
-
**Detect whether an uploaded image is Real or AI-Generated (Deepfake).**
|
| 94 |
-
The confidence bars show the model's certainty
|
| 95 |
-
|
| 96 |
-
Below, the **Grad-CAM heatmap** highlights the regions the model focused on (red = most important).
|
| 97 |
-
|
| 98 |
-
⚡ **Instructions:**
|
| 99 |
-
1. Upload a face image (JPEG/PNG).
|
| 100 |
-
2. Wait a few seconds for the prediction and heatmap.
|
| 101 |
-
3. Observe the confidence bars and heatmap for model explanation.
|
| 102 |
""",
|
| 103 |
-
theme="default"
|
| 104 |
-
).launch()
|
|
|
|
| 16 |
model = tf.keras.Model(inputs, outputs)
|
| 17 |
|
| 18 |
# ==============================================================================
|
| 19 |
+
# --- Grad-CAM Heatmap Generation Functions (with final fix) ---
|
| 20 |
# ==============================================================================
|
|
|
|
| 21 |
def get_last_conv_layer_name(model):
|
| 22 |
+
"""Finds the name of the last convolutional layer in the model."""
|
| 23 |
for layer in reversed(model.layers):
|
| 24 |
if len(layer.output.shape) == 4:
|
| 25 |
return layer.name
|
| 26 |
raise ValueError("Could not find a conv layer in the model")
|
| 27 |
|
| 28 |
def make_gradcam_heatmap(img_array, model, last_conv_layer_name):
|
| 29 |
+
"""Generates the Grad-CAM heatmap."""
|
| 30 |
grad_model = tf.keras.models.Model(
|
| 31 |
model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
|
| 32 |
)
|
| 33 |
with tf.GradientTape() as tape:
|
| 34 |
+
last_conv_layer_output, preds = grad_model([img_array], training=False)
|
| 35 |
class_channel = preds[0]
|
| 36 |
+
|
| 37 |
grads = tape.gradient(class_channel, last_conv_layer_output)
|
| 38 |
+
|
| 39 |
+
# <-- FIX: Add a safety check in case the gradient does not exist.
|
| 40 |
+
if grads is None:
|
| 41 |
+
print("Warning: Gradient is None. Cannot compute heatmap. Returning a blank map.")
|
| 42 |
+
# Return a blank (black) map of the same size as the feature map.
|
| 43 |
+
h, w = last_conv_layer_output.shape[1:3]
|
| 44 |
+
return np.zeros((h, w), dtype=np.float32)
|
| 45 |
+
|
| 46 |
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
| 47 |
last_conv_layer_output = last_conv_layer_output[0]
|
| 48 |
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
|
|
|
| 51 |
return heatmap.numpy()
|
| 52 |
|
| 53 |
def superimpose_gradcam(original_img_pil, heatmap):
|
| 54 |
+
"""Overlays the heatmap on the original image."""
|
| 55 |
original_img = np.array(original_img_pil)
|
| 56 |
heatmap = cv2.resize(heatmap, (original_img.shape[1], original_img.shape[0]))
|
| 57 |
heatmap = np.uint8(255 * heatmap)
|
|
|
|
| 62 |
# ==============================================================================
|
| 63 |
# --- Main Prediction Function ---
|
| 64 |
# ==============================================================================
|
|
|
|
| 65 |
last_conv_layer_name = get_last_conv_layer_name(model)
|
| 66 |
|
| 67 |
def predict_and_visualize(img):
|
| 68 |
+
"""Performs prediction and generates the Grad-CAM heatmap."""
|
| 69 |
try:
|
| 70 |
+
if img is None: # Handle case where user clears the image
|
| 71 |
+
return None, None
|
| 72 |
+
|
| 73 |
img_resized = img.resize((224, 224))
|
| 74 |
img_array = image.img_to_array(img_resized) / 255.0
|
| 75 |
img_array_expanded = np.expand_dims(img_array, axis=0)
|
|
|
|
| 83 |
superimposed_image = superimpose_gradcam(img, heatmap)
|
| 84 |
|
| 85 |
return labels, superimposed_image
|
| 86 |
+
|
| 87 |
except Exception as e:
|
| 88 |
print("--- GRADIO APP ERROR ---")
|
| 89 |
traceback.print_exc()
|
|
|
|
| 92 |
return {error_msg: 0.0}, None
|
| 93 |
|
| 94 |
# ==============================================================================
|
| 95 |
+
# --- Gradio Interface ---
|
| 96 |
# ==============================================================================
|
|
|
|
| 97 |
gr.Interface(
|
| 98 |
fn=predict_and_visualize,
|
| 99 |
inputs=gr.Image(type="pil", label="📷 Upload a Face Image"),
|
|
|
|
| 103 |
],
|
| 104 |
title="✨ Deepfake Image Detector with Visual Explanation ✨",
|
| 105 |
description="""
|
| 106 |
+
**Detect whether an uploaded image is Real or AI-Generated (Deepfake).**
|
| 107 |
+
The confidence bars show the model's certainty, and the heatmap highlights the regions the model focused on (red = most important).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
""",
|
| 109 |
+
theme="default"
|
| 110 |
+
).launch()
|