vikasdeep commited on
Commit
26d8e58
·
verified ·
1 Parent(s): 8826095

initial commit

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from facenet_pytorch import MTCNN, InceptionResnetV1
5
+ import numpy as np
6
+ from PIL import Image
7
+ import cv2
8
+ from pytorch_grad_cam import GradCAM
9
+ from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
10
+ from pytorch_grad_cam.utils.image import show_cam_on_image
11
+ import warnings
12
+ warnings.filterwarnings("ignore")
13
+ DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'
14
+
15
+ mtcnn = MTCNN(
16
+ select_largest=False,
17
+ post_process=False,
18
+ device=DEVICE
19
+ ).to(DEVICE).eval()
20
+ model = InceptionResnetV1(
21
+ pretrained="vggface2",
22
+ classify=True,
23
+ num_classes=1,
24
+ device=DEVICE
25
+ )
26
+
27
+ checkpoint = torch.load("resnetinceptionv1_epoch_32.pth", map_location=torch.device('cpu'))
28
+ model.load_state_dict(checkpoint['model_state_dict'])
29
+ model.to(DEVICE)
30
+ model.eval()
31
+ def predict(input_image:Image.Image):
32
+ """Predict the label of the input_image"""
33
+ face = mtcnn(input_image)
34
+ if face is None:
35
+ raise Exception('No face detected')
36
+ face = face.unsqueeze(0) # add the batch dimension
37
+ face = F.interpolate(face, size=(256, 256), mode='bilinear', align_corners=False)
38
+
39
+ # convert the face into a numpy array to be able to plot it
40
+ prev_face = face.squeeze(0).permute(1, 2, 0).cpu().detach().int().numpy()
41
+ prev_face = prev_face.astype('uint8')
42
+
43
+ face = face.to(DEVICE)
44
+ face = face.to(torch.float32)
45
+ face = face / 255.0
46
+ face_image_to_plot = face.squeeze(0).permute(1, 2, 0).cpu().detach().int().numpy()
47
+
48
+ target_layers=[model.block8.branch1[-1]]
49
+ use_cuda = True if torch.cuda.is_available() else False
50
+ cam = GradCAM(model=model, target_layers=target_layers, use_cuda=use_cuda)
51
+ targets = [ClassifierOutputTarget(0)]
52
+
53
+ grayscale_cam = cam(input_tensor=face, targets=targets, eigen_smooth=True)
54
+ grayscale_cam = grayscale_cam[0, :]
55
+ visualization = show_cam_on_image(face_image_to_plot, grayscale_cam, use_rgb=True)
56
+ face_with_mask = cv2.addWeighted(prev_face, 1, visualization, 0.5, 0)
57
+
58
+ with torch.no_grad():
59
+ output = torch.sigmoid(model(face).squeeze(0))
60
+ prediction = "real" if output.item() < 0.5 else "fake"
61
+
62
+ real_prediction = 1 - output.item()
63
+ fake_prediction = output.item()
64
+
65
+ confidences = {
66
+ 'real': real_prediction,
67
+ 'fake': fake_prediction
68
+ }
69
+ return confidences, face_with_mask
70
+ interface = gr.Interface(
71
+ fn=predict,
72
+ inputs=[
73
+ gr.inputs.Image(label="Input Image", type="pil")
74
+ ],
75
+ outputs=[
76
+ gr.outputs.Label(label="Class"),
77
+ gr.outputs.Image(label="Face with Explainability", type="pil")
78
+ ],
79
+ ).launch()