wyyadd commited on
Commit
d30298c
1 Parent(s): 402b016

feat: update pipeline

Browse files
Files changed (4) hide show
  1. deepfakeconfig.py +6 -3
  2. deepfakemodel.py +5 -3
  3. pipeline.py +41 -60
  4. requirements.txt +1 -3
deepfakeconfig.py CHANGED
@@ -1,7 +1,10 @@
1
  from transformers import PretrainedConfig
2
- import torch
 
 
3
  class DeepFakeConfig(PretrainedConfig):
4
  model_type = "ResNet"
5
- def __init__(self,**kwargs):
 
6
  super().__init__(**kwargs)
7
- self.DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'
 
1
  from transformers import PretrainedConfig
2
+ import torch
3
+
4
+
5
  class DeepFakeConfig(PretrainedConfig):
6
  model_type = "ResNet"
7
+
8
+ def __init__(self, **kwargs):
9
  super().__init__(**kwargs)
10
+ self.DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'
deepfakemodel.py CHANGED
@@ -1,9 +1,11 @@
1
- from transformers import PreTrainedModel
2
- from facenet_pytorch import MTCNN, InceptionResnetV1
3
  from .deepfakeconfig import DeepFakeConfig
4
 
 
5
  class DeepFakeModel(PreTrainedModel):
6
  config_class = DeepFakeConfig
 
7
  def __init__(self, config):
8
  super().__init__(config)
9
  self.model = InceptionResnetV1(
@@ -15,4 +17,4 @@ class DeepFakeModel(PreTrainedModel):
15
 
16
 
17
  DeepFakeConfig.register_for_auto_class()
18
- DeepFakeModel.register_for_auto_class("AutoModelForImageClassification")
 
1
+ from facenet_pytorch import InceptionResnetV1
2
+ from transformers import PreTrainedModel
3
  from .deepfakeconfig import DeepFakeConfig
4
 
5
+
6
  class DeepFakeModel(PreTrainedModel):
7
  config_class = DeepFakeConfig
8
+
9
  def __init__(self, config):
10
  super().__init__(config)
11
  self.model = InceptionResnetV1(
 
17
 
18
 
19
  DeepFakeConfig.register_for_auto_class()
20
+ DeepFakeModel.register_for_auto_class("AutoModelForImageClassification")
pipeline.py CHANGED
@@ -1,72 +1,53 @@
1
- from transformers.pipelines import PIPELINE_REGISTRY
2
- from transformers import Pipeline, AutoModelForImageClassification
3
  import torch
 
4
  from PIL import Image
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 facenet_pytorch import MTCNN
10
- import torch.nn.functional as F
 
11
 
12
  class DeepFakePipeline(Pipeline):
13
- def __init__(self,**kwargs):
14
- Pipeline.__init__(self,**kwargs)
 
15
  def _sanitize_parameters(self, **kwargs):
16
  return {}, {}, {}
 
17
  def preprocess(self, inputs):
18
  return inputs
19
- def _forward(self,input):
20
- return input
21
- def postprocess(self,confidences,face_with_mask):
22
- out = {"confidences":confidences,
23
- "face_with_mask": face_with_mask}
24
- return out
25
 
26
- def predict(self,input_image:str):
27
- DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'
28
- mtcnn = MTCNN(
29
- select_largest=False,
30
- post_process=False,
31
- device=DEVICE)
32
- mtcnn.to(DEVICE)
33
- model = self.model.model
34
- model.to(DEVICE)
35
 
36
- input_image = Image.open(input_image)
37
- face = mtcnn(input_image)
38
- if face is None:
39
- raise Exception('No face detected')
40
-
41
- face = face.unsqueeze(0) # add the batch dimension
42
- face = F.interpolate(face, size=(256, 256), mode='bilinear', align_corners=False)
43
-
44
- # convert the face into a numpy array to be able to plot it
45
- prev_face = face.squeeze(0).permute(1, 2, 0).cpu().detach().int().numpy()
46
- prev_face = prev_face.astype('uint8')
47
-
48
- face = face.to(DEVICE)
49
- face = face.to(torch.float32)
50
- face = face / 255.0
51
- face_image_to_plot = face.squeeze(0).permute(1, 2, 0).cpu().detach().int().numpy()
52
-
53
- target_layers=[model.block8.branch1[-1]]
54
- cam = GradCAM(model=model, target_layers=target_layers)
55
- targets = [ClassifierOutputTarget(0)]
56
- grayscale_cam = cam(input_tensor=face, targets=targets,eigen_smooth=True)
57
- grayscale_cam = grayscale_cam[0, :]
58
- visualization = show_cam_on_image(face_image_to_plot, grayscale_cam, use_rgb=True)
59
- face_with_mask = cv2.addWeighted(prev_face, 1, visualization, 0.5, 0)
60
 
61
- with torch.no_grad():
62
- output = torch.sigmoid(model(face).squeeze(0))
63
- prediction = "real" if output.item() < 0.5 else "fake"
64
-
65
- real_prediction = 1 - output.item()
66
- fake_prediction = output.item()
67
-
68
- confidences = {
69
- 'real': real_prediction,
70
- 'fake': fake_prediction
71
- }
72
- return self.postprocess(confidences, face_with_mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ import torch.nn.functional as F
3
  from PIL import Image
 
 
 
 
4
  from facenet_pytorch import MTCNN
5
+ from transformers import Pipeline
6
+
7
 
8
  class DeepFakePipeline(Pipeline):
9
+ def __init__(self, **kwargs):
10
+ Pipeline.__init__(self, **kwargs)
11
+
12
  def _sanitize_parameters(self, **kwargs):
13
  return {}, {}, {}
14
+
15
  def preprocess(self, inputs):
16
  return inputs
 
 
 
 
 
 
17
 
18
+ def _forward(self, input):
19
+ return input
 
 
 
 
 
 
 
20
 
21
+ def postprocess(self, confidences):
22
+ out = {"confidences": confidences}
23
+ return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ def predict(self, input_image: Image.Image):
26
+ DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'
27
+ mtcnn = MTCNN(
28
+ select_largest=False,
29
+ post_process=False,
30
+ device=DEVICE)
31
+ mtcnn.to(DEVICE)
32
+ model = self.model.model
33
+ model.to(DEVICE)
34
+
35
+ face = mtcnn(input_image)
36
+ if face is None:
37
+ raise Exception('No face detected')
38
+
39
+ face = face.unsqueeze(0) # add the batch dimension
40
+ face = F.interpolate(face, size=(256, 256), mode='bilinear', align_corners=False)
41
+ face = face.to(DEVICE)
42
+ face = face.to(torch.float32)
43
+ face = face / 255.0
44
+
45
+ with torch.no_grad():
46
+ output = torch.sigmoid(model(face).squeeze(0))
47
+ real_prediction = 1 - output.item()
48
+ fake_prediction = output.item()
49
+ confidences = {
50
+ 'real': real_prediction,
51
+ 'fake': fake_prediction
52
+ }
53
+ return self.postprocess(confidences)
requirements.txt CHANGED
@@ -1,6 +1,4 @@
1
  Pillow
2
  facenet-pytorch==2.5.2
3
- torch==1.11.0
4
- opencv-python
5
- grad-cam
6
  transformers
 
1
  Pillow
2
  facenet-pytorch==2.5.2
3
+ torch
 
 
4
  transformers