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

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +222 -0
  2. df_model.pth +3 -0
  3. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
df_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:794ebe83c6a7d7959c30c175030b4885e2b9fa175f1cc3e582236595d119f52b
3
+ size 282395989
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ jupyter==1.0.0
2
+ gradio==3.35.2
3
+ Pillow==9.5.0
4
+ facenet-pytorch==2.5.3
5
+ torch==2.0.1
6
+ torchvision==0.15.2
7
+ opencv-python==4.7.0.72
8
+ grad-cam==1.4.6
9
+ numpy==1.24.3
10
+ matplotlib==3.7.1