Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,6 +11,7 @@ import cv2
|
|
11 |
from pytorch_grad_cam import GradCAM
|
12 |
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
13 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
|
|
14 |
|
15 |
with zipfile.ZipFile("examples.zip","r") as zip_ref:
|
16 |
zip_ref.extractall(".")
|
@@ -49,56 +50,81 @@ for example_name in examples_names:
|
|
49 |
np.random.shuffle(examples) # shuffle
|
50 |
|
51 |
@spaces.GPU
|
52 |
-
def
|
53 |
-
|
54 |
-
face = mtcnn(input_image)
|
55 |
if face is None:
|
56 |
-
|
57 |
-
|
|
|
58 |
face = F.interpolate(face, size=(256, 256), mode='bilinear', align_corners=False)
|
59 |
|
60 |
-
# convert the face into a numpy array to be able to plot it
|
61 |
-
prev_face = face.squeeze(0).permute(1, 2, 0).cpu().detach().int().numpy()
|
62 |
-
prev_face = prev_face.astype('uint8')
|
63 |
-
|
64 |
face = face.to(DEVICE)
|
65 |
face = face.to(torch.float32)
|
66 |
face = face / 255.0
|
67 |
-
face_image_to_plot = face.squeeze(0).permute(1, 2, 0).cpu().detach().
|
68 |
-
|
69 |
-
target_layers=[model.block8.branch1[-1]]
|
70 |
-
cam = GradCAM(model=model, target_layers=target_layers)
|
71 |
-
targets = [ClassifierOutputTarget(0)]
|
72 |
|
73 |
grayscale_cam = cam(input_tensor=face, targets=targets, eigen_smooth=True)
|
74 |
grayscale_cam = grayscale_cam[0, :]
|
75 |
visualization = show_cam_on_image(face_image_to_plot, grayscale_cam, use_rgb=True)
|
76 |
-
|
77 |
-
|
78 |
with torch.no_grad():
|
79 |
output = torch.sigmoid(model(face).squeeze(0))
|
80 |
prediction = "real" if output.item() < 0.5 else "fake"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
-
|
83 |
-
fake_prediction = output.item()
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
interface = gr.Interface(
|
92 |
-
fn=
|
93 |
inputs=[
|
94 |
-
gr.
|
95 |
-
gr.components.Text(label="Your Text Input") # Updated component import
|
96 |
],
|
97 |
outputs=[
|
98 |
-
gr.
|
99 |
-
gr.components.Text(label="Your Text Output"), # Updated component import
|
100 |
-
gr.components.Image(label="Face with Explainability", type="numpy") # Updated component import and type
|
101 |
],
|
102 |
-
|
103 |
-
|
104 |
-
)
|
|
|
|
|
|
|
|
11 |
from pytorch_grad_cam import GradCAM
|
12 |
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
13 |
from pytorch_grad_cam.utils.image import show_cam_on_image
|
14 |
+
import tempfile
|
15 |
|
16 |
with zipfile.ZipFile("examples.zip","r") as zip_ref:
|
17 |
zip_ref.extractall(".")
|
|
|
50 |
np.random.shuffle(examples) # shuffle
|
51 |
|
52 |
@spaces.GPU
|
53 |
+
def process_frame(frame, mtcnn, model, cam, targets):
|
54 |
+
face = mtcnn(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
|
|
|
55 |
if face is None:
|
56 |
+
return frame, None, None
|
57 |
+
|
58 |
+
face = face.unsqueeze(0)
|
59 |
face = F.interpolate(face, size=(256, 256), mode='bilinear', align_corners=False)
|
60 |
|
|
|
|
|
|
|
|
|
61 |
face = face.to(DEVICE)
|
62 |
face = face.to(torch.float32)
|
63 |
face = face / 255.0
|
64 |
+
face_image_to_plot = face.squeeze(0).permute(1, 2, 0).cpu().detach().numpy()
|
|
|
|
|
|
|
|
|
65 |
|
66 |
grayscale_cam = cam(input_tensor=face, targets=targets, eigen_smooth=True)
|
67 |
grayscale_cam = grayscale_cam[0, :]
|
68 |
visualization = show_cam_on_image(face_image_to_plot, grayscale_cam, use_rgb=True)
|
69 |
+
|
|
|
70 |
with torch.no_grad():
|
71 |
output = torch.sigmoid(model(face).squeeze(0))
|
72 |
prediction = "real" if output.item() < 0.5 else "fake"
|
73 |
+
confidence = 1 - output.item() if prediction == "real" else output.item()
|
74 |
+
|
75 |
+
return visualization, prediction, confidence
|
76 |
+
|
77 |
+
@spaces.GPU
|
78 |
+
def predict_video(input_video: str):
|
79 |
+
"""Predict the labels for each frame of the input video"""
|
80 |
+
cap = cv2.VideoCapture(input_video)
|
81 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
82 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
83 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
84 |
+
|
85 |
+
target_layers = [model.block8.branch1[-1]]
|
86 |
+
cam = GradCAM(model=model, target_layers=target_layers)
|
87 |
+
targets = [ClassifierOutputTarget(0)]
|
88 |
+
|
89 |
+
temp_output = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False)
|
90 |
+
out = cv2.VideoWriter(temp_output.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
|
91 |
+
|
92 |
+
while cap.isOpened():
|
93 |
+
ret, frame = cap.read()
|
94 |
+
if not ret:
|
95 |
+
break
|
96 |
|
97 |
+
processed_frame, prediction, confidence = process_frame(frame, mtcnn, model, cam, targets)
|
|
|
98 |
|
99 |
+
if processed_frame is not None:
|
100 |
+
# Resize the processed frame to match the original video dimensions
|
101 |
+
processed_frame = cv2.resize(processed_frame, (width, height))
|
102 |
+
|
103 |
+
# Add text with prediction and confidence
|
104 |
+
text = f"{prediction}: {confidence:.2f}"
|
105 |
+
cv2.putText(processed_frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
106 |
+
|
107 |
+
out.write(processed_frame)
|
108 |
+
else:
|
109 |
+
# If no face is detected, write the original frame
|
110 |
+
out.write(frame)
|
111 |
+
|
112 |
+
cap.release()
|
113 |
+
out.release()
|
114 |
+
|
115 |
+
return temp_output.name
|
116 |
|
117 |
interface = gr.Interface(
|
118 |
+
fn=predict_video,
|
119 |
inputs=[
|
120 |
+
gr.Video(label="Input Video")
|
|
|
121 |
],
|
122 |
outputs=[
|
123 |
+
gr.Video(label="Output Video")
|
|
|
|
|
124 |
],
|
125 |
+
title="Video Deepfake Detection",
|
126 |
+
description="Upload a video to detect deepfakes in each frame."
|
127 |
+
)
|
128 |
+
|
129 |
+
if __name__ == "__main__":
|
130 |
+
interface.launch()
|