dgrant6 commited on
Commit
b4cfebf
Β·
verified Β·
1 Parent(s): 535c788

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -221
app.py CHANGED
@@ -1,222 +1,196 @@
1
- import gradio as gr
2
- import torch
3
- import torch.nn.functional as F
4
- from facenet_pytorch import MTCNN, InceptionResnetV1
5
- import cv2
6
- from pytorch_grad_cam import GradCAM
7
- from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
8
- from pytorch_grad_cam.utils.image import show_cam_on_image
9
- from PIL import Image
10
- import numpy as np
11
- import warnings
12
- from typing import Tuple, List, Dict
13
- import matplotlib.pyplot as plt
14
- from matplotlib.animation import FuncAnimation
15
- import io
16
-
17
- warnings.filterwarnings("ignore")
18
-
19
- # Device configuration
20
- DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
21
-
22
- # Load models
23
- mtcnn = MTCNN(select_largest=False, post_process=False, device=DEVICE).to(DEVICE).eval()
24
- model = InceptionResnetV1(pretrained="vggface2", classify=True, num_classes=1, device=DEVICE)
25
-
26
- checkpoint = torch.load("df_model.pth", map_location=torch.device('cpu'))
27
- model.load_state_dict(checkpoint['model_state_dict'])
28
- model.to(DEVICE)
29
- model.eval()
30
-
31
- def predict_frame(frame: np.ndarray) -> Tuple[str, np.ndarray, Dict[str, float]]:
32
- """Predict whether the input frame contains a real or fake face"""
33
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
34
- frame_pil = Image.fromarray(frame)
35
-
36
- face = mtcnn(frame_pil)
37
- if face is None:
38
- return None, None, None # No face detected
39
-
40
- # Preprocess the face
41
- face = F.interpolate(face.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False)
42
- face = face.to(DEVICE, dtype=torch.float32) / 255.0
43
-
44
- # Predict
45
- with torch.no_grad():
46
- output = torch.sigmoid(model(face).squeeze(0))
47
- fake_confidence = output.item()
48
- real_confidence = 1 - fake_confidence
49
- prediction = "real" if real_confidence > fake_confidence else "fake"
50
-
51
- confidences = {
52
- 'real': real_confidence,
53
- 'fake': fake_confidence
54
- }
55
-
56
- # Visualize
57
- target_layers = [model.block8.branch1[-1]]
58
- cam = GradCAM(model=model, target_layers=target_layers, use_cuda=torch.cuda.is_available())
59
- targets = [ClassifierOutputTarget(0)]
60
- grayscale_cam = cam(input_tensor=face, targets=targets, eigen_smooth=True)
61
- grayscale_cam = grayscale_cam[0, :]
62
- face_np = face.squeeze(0).permute(1, 2, 0).cpu().numpy()
63
- visualization = show_cam_on_image(face_np, grayscale_cam, use_rgb=True)
64
- face_with_mask = cv2.addWeighted((face_np * 255).astype(np.uint8), 1, (visualization * 255).astype(np.uint8), 0.5, 0)
65
-
66
- return prediction, face_with_mask, confidences
67
-
68
- def predict_video(input_video: str) -> Tuple[str, np.ndarray, Dict[str, List[float]], List[np.ndarray]]:
69
- cap = cv2.VideoCapture(input_video)
70
-
71
- frames = []
72
- predictions = []
73
- confidences_real = []
74
- confidences_fake = []
75
- frame_count = 0
76
- skip_frames = 20
77
-
78
- while True:
79
- ret, frame = cap.read()
80
- if not ret:
81
- break
82
- frame_count += 1
83
- if frame_count % skip_frames != 0:
84
- continue
85
-
86
- prediction, frame_with_mask, confidence = predict_frame(frame)
87
- if prediction is None:
88
- continue
89
-
90
- frames.append(frame_with_mask)
91
- predictions.append(prediction)
92
- confidences_real.append(confidence['real'])
93
- confidences_fake.append(confidence['fake'])
94
-
95
- cap.release()
96
-
97
- # Determine the final prediction based on the average confidence
98
- avg_real_confidence = sum(confidences_real) / len(confidences_real)
99
- avg_fake_confidence = sum(confidences_fake) / len(confidences_fake)
100
- final_prediction = 'real' if avg_real_confidence > avg_fake_confidence else 'fake'
101
- final_confidence = max(avg_real_confidence, avg_fake_confidence)
102
-
103
- # Create an animated summary plot
104
- fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10))
105
-
106
- def animate(i):
107
- ax1.clear()
108
- ax2.clear()
109
-
110
- # Confidence over time
111
- ax1.plot(confidences_real[:i+1], label='Real', color='green')
112
- ax1.plot(confidences_fake[:i+1], label='Fake', color='red')
113
- ax1.set_title('Confidence Scores Over Time')
114
- ax1.set_xlabel('Frame')
115
- ax1.set_ylabel('Confidence')
116
- ax1.legend()
117
- ax1.grid(True)
118
- ax1.set_ylim(0, 1)
119
-
120
- # Prediction distribution
121
- labels, counts = np.unique(predictions[:i+1], return_counts=True)
122
- ax2.bar(labels, counts, color=['green', 'red'])
123
- ax2.set_title('Distribution of Predictions')
124
- ax2.set_xlabel('Prediction')
125
- ax2.set_ylabel('Count')
126
- ax2.set_ylim(0, len(predictions))
127
-
128
- plt.tight_layout()
129
-
130
- anim = FuncAnimation(fig, animate, frames=len(confidences_real), repeat=False)
131
-
132
- # Save the animation as a gif
133
- buf = io.BytesIO()
134
- anim.save(buf, writer='pillow', fps=5)
135
- buf.seek(0)
136
- summary_plot = Image.open(buf)
137
-
138
- return final_prediction, final_confidence, summary_plot, {
139
- 'real': confidences_real,
140
- 'fake': confidences_fake
141
- }, frames
142
-
143
- # Custom CSS for a more appealing interface
144
- custom_css = """
145
- #output-container {
146
- display: flex;
147
- justify-content: center;
148
- align-items: center;
149
- flex-direction: column;
150
- }
151
- #confidence-label {
152
- font-size: 24px;
153
- font-weight: bold;
154
- margin-bottom: 10px;
155
- }
156
- #confidence-bar {
157
- width: 100%;
158
- height: 30px;
159
- background-color: #f0f0f0;
160
- border-radius: 15px;
161
- overflow: hidden;
162
- }
163
- #confidence-fill {
164
- height: 100%;
165
- background-color: #4CAF50;
166
- transition: width 0.5s ease-in-out;
167
- }
168
- """
169
-
170
- # Gradio Interface
171
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
172
- gr.Markdown("# πŸ•΅οΈβ€β™‚οΈ DeepFake Video Detective 🎭")
173
- gr.Markdown("Upload a video to determine if it's real or a deepfake. Our AI will analyze it frame by frame!")
174
-
175
- with gr.Row():
176
- input_video = gr.Video(label="πŸ“Ή Upload Your Video")
177
-
178
- with gr.Row():
179
- submit_btn = gr.Button("πŸ” Analyze Video", variant="primary")
180
-
181
- with gr.Row():
182
- with gr.Column():
183
- output_label = gr.Label(label="🏷️ Prediction")
184
- confidence_output = gr.HTML(
185
- """
186
- <div id="output-container">
187
- <div id="confidence-label">Confidence: 0%</div>
188
- <div id="confidence-bar">
189
- <div id="confidence-fill" style="width: 0%;"></div>
190
- </div>
191
- </div>
192
- """
193
- )
194
- summary_plot = gr.Image(label="πŸ“Š Analysis Summary")
195
-
196
- with gr.Row():
197
- output_video = gr.Video(label="🎞️ Processed Video")
198
-
199
- def update_confidence(prediction, confidence):
200
- color = "#4CAF50" if prediction == "real" else "#FF5722"
201
- return f"""
202
- <div id="output-container">
203
- <div id="confidence-label">Confidence: {confidence:.2%}</div>
204
- <div id="confidence-bar">
205
- <div id="confidence-fill" style="width: {confidence:.2%}; background-color: {color};"></div>
206
- </div>
207
- </div>
208
- """
209
-
210
- def process_video(video):
211
- prediction, confidence, summary, _, frames = predict_video(video)
212
- processed_video = np.stack(frames, axis=0)
213
- confidence_html = update_confidence(prediction, confidence)
214
- return {output_label: prediction, confidence_output: confidence_html, summary_plot: summary, output_video: processed_video}
215
-
216
- submit_btn.click(
217
- process_video,
218
- inputs=[input_video],
219
- outputs=[output_label, confidence_output, summary_plot, output_video]
220
- )
221
-
222
  demo.launch()
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from facenet_pytorch import MTCNN, InceptionResnetV1
5
+ import cv2
6
+ from PIL import Image
7
+ import numpy as np
8
+ import warnings
9
+ from typing import Tuple, Dict
10
+ import matplotlib.pyplot as plt
11
+ import io
12
+
13
+ warnings.filterwarnings("ignore")
14
+
15
+ # Device configuration
16
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
17
+
18
+ # Load models
19
+ mtcnn = MTCNN(select_largest=False, post_process=False, device=DEVICE).to(DEVICE).eval()
20
+ model = InceptionResnetV1(pretrained="vggface2", classify=True, num_classes=1, device=DEVICE)
21
+
22
+ checkpoint = torch.load("df_model.pth", map_location=torch.device('cpu'))
23
+ model.load_state_dict(checkpoint['model_state_dict'])
24
+ model.to(DEVICE)
25
+ model.eval()
26
+
27
+ def predict_frame(frame: np.ndarray) -> Tuple[str, Dict[str, float]]:
28
+ """Predict whether the input frame contains a real or fake face"""
29
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
30
+ frame_pil = Image.fromarray(frame)
31
+
32
+ face = mtcnn(frame_pil)
33
+ if face is None:
34
+ return None, None # No face detected
35
+
36
+ # Preprocess the face
37
+ face = F.interpolate(face.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False)
38
+ face = face.to(DEVICE, dtype=torch.float32) / 255.0
39
+
40
+ # Predict
41
+ with torch.no_grad():
42
+ output = torch.sigmoid(model(face).squeeze(0))
43
+ fake_confidence = output.item()
44
+ real_confidence = 1 - fake_confidence
45
+ prediction = "real" if real_confidence > fake_confidence else "fake"
46
+
47
+ confidences = {
48
+ 'real': real_confidence,
49
+ 'fake': fake_confidence
50
+ }
51
+
52
+ return prediction, confidences
53
+
54
+ def predict_video(input_video: str) -> Tuple[str, float, np.ndarray]:
55
+ cap = cv2.VideoCapture(input_video)
56
+
57
+ predictions = []
58
+ confidences_real = []
59
+ confidences_fake = []
60
+ frame_count = 0
61
+ skip_frames = 5 # Analyze every 5th frame for faster processing
62
+
63
+ while True:
64
+ ret, frame = cap.read()
65
+ if not ret:
66
+ break
67
+ frame_count += 1
68
+ if frame_count % skip_frames != 0:
69
+ continue
70
+
71
+ prediction, confidence = predict_frame(frame)
72
+ if prediction is None:
73
+ continue
74
+
75
+ predictions.append(prediction)
76
+ confidences_real.append(confidence['real'])
77
+ confidences_fake.append(confidence['fake'])
78
+
79
+ cap.release()
80
+
81
+ # Determine the final prediction based on the average confidence
82
+ avg_real_confidence = sum(confidences_real) / len(confidences_real)
83
+ avg_fake_confidence = sum(confidences_fake) / len(confidences_fake)
84
+ final_prediction = 'real' if avg_real_confidence > avg_fake_confidence else 'fake'
85
+ final_confidence = max(avg_real_confidence, avg_fake_confidence)
86
+
87
+ # Create a summary plot
88
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
89
+
90
+ # Confidence over time
91
+ ax1.plot(confidences_real, label='Real', color='green')
92
+ ax1.plot(confidences_fake, label='Fake', color='red')
93
+ ax1.set_title('Confidence Scores Over Time')
94
+ ax1.set_xlabel('Frame')
95
+ ax1.set_ylabel('Confidence')
96
+ ax1.legend()
97
+ ax1.grid(True)
98
+
99
+ # Prediction distribution
100
+ labels, counts = np.unique(predictions, return_counts=True)
101
+ ax2.bar(labels, counts, color=['green', 'red'])
102
+ ax2.set_title('Distribution of Predictions')
103
+ ax2.set_xlabel('Prediction')
104
+ ax2.set_ylabel('Count')
105
+
106
+ plt.tight_layout()
107
+
108
+ # Save the plot as an image
109
+ buf = io.BytesIO()
110
+ plt.savefig(buf, format='png')
111
+ buf.seek(0)
112
+ summary_plot = Image.open(buf)
113
+
114
+ return final_prediction, final_confidence, summary_plot
115
+
116
+ # Custom CSS for a more appealing interface
117
+ custom_css = """
118
+ .video-container {
119
+ max-width: 400px;
120
+ margin: 0 auto;
121
+ }
122
+ #output-container {
123
+ display: flex;
124
+ justify-content: center;
125
+ align-items: center;
126
+ flex-direction: column;
127
+ }
128
+ #confidence-label {
129
+ font-size: 24px;
130
+ font-weight: bold;
131
+ margin-bottom: 10px;
132
+ }
133
+ #confidence-bar {
134
+ width: 100%;
135
+ height: 30px;
136
+ background-color: #f0f0f0;
137
+ border-radius: 15px;
138
+ overflow: hidden;
139
+ }
140
+ #confidence-fill {
141
+ height: 100%;
142
+ background-color: #4CAF50;
143
+ transition: width 0.5s ease-in-out;
144
+ }
145
+ """
146
+
147
+ # Gradio Interface
148
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
149
+ gr.Markdown("# πŸ•΅οΈβ€β™‚οΈ DeepFake Video Detective 🎭")
150
+ gr.Markdown("Upload a video to determine if it's real or a deepfake. Our AI will analyze it frame by frame!")
151
+
152
+ with gr.Row():
153
+ with gr.Column(scale=1):
154
+ input_video = gr.Video(label="πŸ“Ή Upload Your Video", elem_classes=["video-container"])
155
+
156
+ with gr.Row():
157
+ submit_btn = gr.Button("πŸ” Analyze Video", variant="primary")
158
+
159
+ with gr.Row():
160
+ with gr.Column():
161
+ output_label = gr.Label(label="🏷️ Prediction")
162
+ confidence_output = gr.HTML(
163
+ """
164
+ <div id="output-container">
165
+ <div id="confidence-label">Confidence: 0%</div>
166
+ <div id="confidence-bar">
167
+ <div id="confidence-fill" style="width: 0%;"></div>
168
+ </div>
169
+ </div>
170
+ """
171
+ )
172
+ summary_plot = gr.Image(label="πŸ“Š Analysis Summary")
173
+
174
+ def update_confidence(prediction, confidence):
175
+ color = "#4CAF50" if prediction == "real" else "#FF5722"
176
+ return f"""
177
+ <div id="output-container">
178
+ <div id="confidence-label">Confidence: {confidence:.2%}</div>
179
+ <div id="confidence-bar">
180
+ <div id="confidence-fill" style="width: {confidence:.2%}; background-color: {color};"></div>
181
+ </div>
182
+ </div>
183
+ """
184
+
185
+ def process_video(video):
186
+ prediction, confidence, summary = predict_video(video)
187
+ confidence_html = update_confidence(prediction, confidence)
188
+ return {output_label: prediction, confidence_output: confidence_html, summary_plot: summary}
189
+
190
+ submit_btn.click(
191
+ process_video,
192
+ inputs=[input_video],
193
+ outputs=[output_label, confidence_output, summary_plot]
194
+ )
195
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  demo.launch()