Satwickchikkala1 commited on
Commit
f234b07
·
verified ·
1 Parent(s): 7c1d3a9

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +108 -0
  2. deepfake_mobilenet_model.h5 +3 -0
  3. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from tensorflow.keras.preprocessing import image
5
+ from PIL import Image
6
+ import cv2
7
+ import traceback
8
+
9
+ # Load the trained model
10
+ try:
11
+ model = tf.keras.models.load_model("./model/deepfake_mobilenet_model.h5")
12
+ except Exception as e:
13
+ print(f"Error loading model. Make sure the path is correct. Error: {e}")
14
+ inputs = tf.keras.Input(shape=(224, 224, 3))
15
+ outputs = tf.keras.layers.Dense(1, activation="sigmoid")(tf.keras.layers.GlobalAveragePooling2D()(inputs))
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][:, 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]
39
+ heatmap = tf.squeeze(heatmap)
40
+ heatmap = tf.maximum(heatmap, 0) / (tf.math.reduce_max(heatmap) + 1e-8)
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)
47
+ heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
48
+ superimposed_img = cv2.addWeighted(original_img, 0.6, heatmap, 0.4, 0)
49
+ return Image.fromarray(superimposed_img)
50
+
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)
62
+
63
+ prediction = model.predict(img_array_expanded, verbose=0)[0][0]
64
+ real_conf = float(prediction)
65
+ fake_conf = float(1 - prediction)
66
+ labels = {"Real Image": real_conf, "Fake Image": fake_conf}
67
+
68
+ heatmap = make_gradcam_heatmap(img_array_expanded, model, last_conv_layer_name)
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()
76
+ print("------------------------")
77
+ error_msg = f"Error: {e}"
78
+ return {error_msg: 0.0}, None
79
+
80
+ # ==============================================================================
81
+ # --- Gradio Interface with Improved Design ---
82
+ # ==============================================================================
83
+
84
+ gr.Interface(
85
+ fn=predict_and_visualize,
86
+ inputs=gr.Image(type="pil", label="📷 Upload a Face Image"),
87
+ outputs=[
88
+ gr.Label(num_top_classes=2, label="🧠 Model Prediction"),
89
+ gr.Image(label="🔥 Grad-CAM Heatmap Overlay")
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 for both **Real** and **Fake** categories.
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
+ examples=[
104
+ ["sample_images/real1.jpg"],
105
+ ["sample_images/fake1.jpg"]
106
+ ],
107
+ theme="default" # you can later try 'soft', 'grass', or 'peach'
108
+ ).launch()
deepfake_mobilenet_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6530c0a9c0d2400a25c467e7234636a245adedc770e5db9a5efa92c18fe517d
3
+ size 11540600
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ tensorflow
3
+ pillow
4
+ matplotlib
5
+ numpy