dhairyashah commited on
Commit
10269f1
verified
1 Parent(s): fddcc1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -32
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 predict(input_image:Image.Image, true_label:str):
53
- """Predict the label of the input_image"""
54
- face = mtcnn(input_image)
55
  if face is None:
56
- raise Exception('No face detected')
57
- face = face.unsqueeze(0) # add the batch dimension
 
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().int().numpy()
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
- face_with_mask = cv2.addWeighted(prev_face, 1, visualization, 0.5, 0)
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
- real_prediction = 1 - output.item()
83
- fake_prediction = output.item()
84
 
85
- confidences = {
86
- 'real': real_prediction,
87
- 'fake': fake_prediction
88
- }
89
- return confidences, true_label, face_with_mask
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  interface = gr.Interface(
92
- fn=predict,
93
  inputs=[
94
- gr.components.Image(label="Input Image", type="pil"), # Updated component import and type
95
- gr.components.Text(label="Your Text Input") # Updated component import
96
  ],
97
  outputs=[
98
- gr.components.Label(label="Class"), # Updated component import
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
- examples=[[examples[i]["path"], examples[i]["label"]] for i in range(10)],
103
- cache_examples=True # Adjusted according to the new parameter for caching examples if needed
104
- ).launch()
 
 
 
 
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()