Update app.py
Browse files
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
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
import
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
model
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 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()
|