File size: 31,149 Bytes
e50136c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
087532c
e50136c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\debonair\\anaconda3\\lib\\site-packages\\numpy\\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:\n",
      "c:\\Users\\debonair\\anaconda3\\lib\\site-packages\\numpy\\.libs\\libopenblas.XWYDX2IKJW2NMTWSFYNGFUWKQU3LYTCZ.gfortran-win_amd64.dll\n",
      "c:\\Users\\debonair\\anaconda3\\lib\\site-packages\\numpy\\.libs\\libopenblas64__v0.3.23-gcc_10_3_0.dll\n",
      "  warnings.warn(\"loaded more than 1 DLL from .libs:\"\n",
      "c:\\Users\\debonair\\anaconda3\\lib\\site-packages\\tensorflow_addons\\utils\\tfa_eol_msg.py:23: UserWarning: \n",
      "\n",
      "TensorFlow Addons (TFA) has ended development and introduction of new features.\n",
      "TFA has entered a minimal maintenance and release mode until a planned end of life in May 2024.\n",
      "Please modify downstream libraries to take dependencies from other repositories in our TensorFlow community (e.g. Keras, Keras-CV, and Keras-NLP). \n",
      "\n",
      "For more information see: https://github.com/tensorflow/addons/issues/2807 \n",
      "\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import tensorflow as tf\n",
    "import tensorflow_addons\n",
    "import moviepy.editor as mp\n",
    "from facenet_pytorch import MTCNN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "OSError",
     "evalue": "No file or directory found at FINAL-EFFICIENTNETV2-B0",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_25172\\3936866724.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mmtcnn\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mMTCNN\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmargin\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m14\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mkeep_all\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfactor\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m0.7\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mdevice\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'cpu'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;31m#Load model.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mmodel\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mkeras\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodels\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mload_model\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"FINAL-EFFICIENTNETV2-B0\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m~\\AppData\\Roaming\\Python\\Python39\\site-packages\\keras\\utils\\traceback_utils.py\u001b[0m in \u001b[0;36merror_handler\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m     68\u001b[0m             \u001b[1;31m# To get the full stack trace, call:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     69\u001b[0m             \u001b[1;31m# `tf.debugging.disable_traceback_filtering()`\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 70\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0me\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwith_traceback\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfiltered_tb\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     71\u001b[0m         \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     72\u001b[0m             \u001b[1;32mdel\u001b[0m \u001b[0mfiltered_tb\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\AppData\\Roaming\\Python\\Python39\\site-packages\\keras\\saving\\save.py\u001b[0m in \u001b[0;36mload_model\u001b[1;34m(filepath, custom_objects, compile, options)\u001b[0m\n\u001b[0;32m    224\u001b[0m                 \u001b[1;32mif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfilepath_str\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstr\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    225\u001b[0m                     \u001b[1;32mif\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[0mtf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mio\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mexists\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mfilepath_str\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 226\u001b[1;33m                         raise IOError(\n\u001b[0m\u001b[0;32m    227\u001b[0m                             \u001b[1;34mf\"No file or directory found at {filepath_str}\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    228\u001b[0m                         )\n",
      "\u001b[1;31mOSError\u001b[0m: No file or directory found at FINAL-EFFICIENTNETV2-B0"
     ]
    }
   ],
   "source": [
    "# Load face detector\n",
    "mtcnn = MTCNN(margin=14, keep_all=True, factor=0.7, device='cpu')\n",
    "#Load model.\n",
    "model = tf.keras.models.load_model(\"FINAL-EFFICIENTNETV2-B0\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Face Detection function, Reference: (Timesler, 2020);\n",
    "class DetectionPipeline:\n",
    "    \"\"\"Pipeline class for detecting faces in the frames of a video file.\"\"\"\n",
    "\n",
    "    def __init__(self, detector, n_frames=None, batch_size=60, resize=None, input_modality = 'video'):\n",
    "        \"\"\"Constructor for DetectionPipeline class.\n",
    "\n",
    "        Keyword Arguments:\n",
    "            n_frames {int} -- Total number of frames to load. These will be evenly spaced\n",
    "                throughout the video. If not specified (i.e., None), all frames will be loaded.\n",
    "                (default: {None})\n",
    "            batch_size {int} -- Batch size to use with MTCNN face detector. (default: {32})\n",
    "            resize {float} -- Fraction by which to resize frames from original prior to face\n",
    "                detection. A value less than 1 results in downsampling and a value greater than\n",
    "                1 result in upsampling. (default: {None})\n",
    "        \"\"\"\n",
    "        self.detector = detector\n",
    "        self.n_frames = n_frames\n",
    "        self.batch_size = batch_size\n",
    "        self.resize = resize\n",
    "        self.input_modality = input_modality\n",
    "\n",
    "    def __call__(self, filename):\n",
    "        \"\"\"Load frames from an MP4 video and detect faces.\n",
    "\n",
    "        Arguments:\n",
    "            filename {str} -- Path to video.\n",
    "        \"\"\"\n",
    "        # Create video reader and find length\n",
    "        if self.input_modality == 'video':\n",
    "            print('Input modality is video.')\n",
    "            v_cap = cv2.VideoCapture(filename)\n",
    "            v_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
    "\n",
    "            # Pick 'n_frames' evenly spaced frames to sample\n",
    "            if self.n_frames is None:\n",
    "                sample = np.arange(0, v_len)\n",
    "            else:\n",
    "                sample = np.linspace(0, v_len - 1, self.n_frames).astype(int)\n",
    "\n",
    "            # Loop through frames\n",
    "            faces = []\n",
    "            frames = []\n",
    "            for j in range(v_len):\n",
    "                success = v_cap.grab()\n",
    "                if j in sample:\n",
    "                    # Load frame\n",
    "                    success, frame = v_cap.retrieve()\n",
    "                    if not success:\n",
    "                        continue\n",
    "                    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "                    # frame = Image.fromarray(frame)\n",
    "\n",
    "                    # Resize frame to desired size\n",
    "                    if self.resize is not None:\n",
    "                        frame = frame.resize([int(d * self.resize) for d in frame.size])\n",
    "                    frames.append(frame)\n",
    "\n",
    "                    # When batch is full, detect faces and reset frame list\n",
    "                    if len(frames) % self.batch_size == 0 or j == sample[-1]:\n",
    "\n",
    "                        boxes, probs = self.detector.detect(frames)\n",
    "\n",
    "                        for i in range(len(frames)):\n",
    "\n",
    "                            if boxes[i] is None:\n",
    "                                faces.append(face2)     #append previous face frame if no face is detected\n",
    "                                continue\n",
    "\n",
    "                            box = boxes[i][0].astype(int)\n",
    "                            frame = frames[i]\n",
    "                            face = frame[box[1]:box[3], box[0]:box[2]]\n",
    "\n",
    "                            if not face.any():\n",
    "                                faces.append(face2)     #append previous face frame if no face is detected\n",
    "                                continue\n",
    "\n",
    "                            face2 = cv2.resize(face, (224, 224))\n",
    "\n",
    "                            faces.append(face2)\n",
    "\n",
    "                        frames = []\n",
    "\n",
    "            v_cap.release()\n",
    "            return faces\n",
    "\n",
    "        elif self.input_modality == 'image':\n",
    "            print('Input modality is image.')\n",
    "            #Perform inference for image modality.\n",
    "            image = cv2.imread(filename)\n",
    "            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
    "            boxes, probs = self.detector.detect(image)\n",
    "\n",
    "            if boxes is None:\n",
    "                print('No faces found')\n",
    "\n",
    "            box = boxes[0].astype(int)\n",
    "            face = image[box[1]:box[3], box[0]:box[2]]\n",
    "            face = cv2.resize(face, (224, 224))\n",
    "\n",
    "            if not face.any():\n",
    "                print(\"No faces found...\")\n",
    "\n",
    "            return face\n",
    "        \n",
    "        else:\n",
    "            raise ValueError(\"Invalid input modality. Must be either 'video' or image\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "detection_video_pipeline = DetectionPipeline(detector=mtcnn, n_frames=2, batch_size=1, input_modality='video')\n",
    "def deepfakes_video_predict(input_video):\n",
    "\n",
    "    faces = detection_video_pipeline(input_video)\n",
    "    total = 0\n",
    "    real = 0\n",
    "    fake = 0\n",
    "\n",
    "    for face in faces:\n",
    "\n",
    "        face2 = face/255\n",
    "        pred = model.predict(np.expand_dims(face2, axis=0))[0]\n",
    "        total+=1\n",
    "\n",
    "        pred2 = pred[1]\n",
    "\n",
    "        if pred2 > 0.5:\n",
    "          fake+=1\n",
    "        else:\n",
    "          real+=1\n",
    "\n",
    "    fake_ratio = fake/total\n",
    "\n",
    "    text =\"\"\n",
    "    text2 = \"Deepfakes Confidence: \" + str(fake_ratio*100) + \"%\"\n",
    "\n",
    "    if fake_ratio >= 0.37:\n",
    "        text = \"The video is FAKE.\"\n",
    "    else:\n",
    "        text = \"The video is REAL.\"\n",
    "\n",
    "    return text, text2\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "detection_image_pipeline = DetectionPipeline(detector=mtcnn, batch_size = 1, input_modality = 'image')\n",
    "def deepfakes_image_predict(input_image):\n",
    "    faces = detection_image_pipeline(input_image)\n",
    "    face2 = faces/255\n",
    "    pred = model.predict(np.expand_dims(face2, axis = 0))[0]\n",
    "    real, fake = pred[0], pred[1]\n",
    "    if real > 0.5:\n",
    "        text = \"The image is REAL.\"\n",
    "        text2 = \"Deepfakes Confidence: \" + str(round(real*100, 3)) + \"%\"\n",
    "    else:\n",
    "        text = \"The image is FAKE.\"\n",
    "        text2 = \"Deepfakes Confidence: \" + str(round(fake*100, 3)) + \"%\"\n",
    "    return text, text2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input modality is image.\n",
      "1/1 [==============================] - 0s 75ms/step\n",
      "('The video is FAKE.', 'Deepfakes Confidence: 99.957%')\n",
      "Input modality is image.\n",
      "1/1 [==============================] - 0s 85ms/step\n",
      "('The video is REAL.', 'Deepfakes Confidence: 99.992%')\n"
     ]
    }
   ],
   "source": [
    "image_res = deepfakes_image_predict('fake_image.jpg')\n",
    "print(image_res)\n",
    "\n",
    "image_res = deepfakes_image_predict('lady.jpg')\n",
    "print(image_res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input modality is video.\n",
      "1/1 [==============================] - 0s 80ms/step\n",
      "1/1 [==============================] - 0s 71ms/step\n",
      "('The video is FAKE.', 'Deepfakes Confidence: 100.0%')\n"
     ]
    }
   ],
   "source": [
    "video_dir = 'Video1-fake-1-ff.mp4'\n",
    "videos = deepfakes_video_predict(video_dir)\n",
    "print(videos)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input modality is video.\n",
      "1/1 [==============================] - 0s 82ms/step\n",
      "1/1 [==============================] - 0s 78ms/step\n",
      "('The video is REAL.', 'Deepfakes Confidence: 0.0%')\n"
     ]
    }
   ],
   "source": [
    "video_dir = 'real-1.mp4'\n",
    "videos = deepfakes_video_predict(video_dir)\n",
    "print(videos)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Audio modality pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Load model.\n",
    "import torch \n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from rawnet import SincConv, Residual_block\n",
    "\n",
    "\n",
    "\n",
    "d_args = {\n",
    "  \"nb_samp\": 64600,\n",
    "  \"first_conv\": 1024,\n",
    "  \"in_channels\": 1,\n",
    "  \"filts\": [20, [20, 20], [20, 128], [128, 128]],\n",
    "  \"blocks\": [2, 4],\n",
    "  \"nb_fc_node\": 1024,\n",
    "  \"gru_node\": 1024,\n",
    "  \"nb_gru_layer\": 3,\n",
    "  \"nb_classes\": 2}\n",
    "\n",
    "\n",
    "class RawNet(nn.Module):\n",
    "    def __init__(self, d_args, device):\n",
    "        super(RawNet, self).__init__()\n",
    "\n",
    "        \n",
    "        self.device=device\n",
    "\n",
    "        self.Sinc_conv=SincConv(device=self.device,\n",
    "\t\t\tout_channels = d_args['filts'][0],\n",
    "\t\t\tkernel_size = d_args['first_conv'],\n",
    "                        in_channels = d_args['in_channels']\n",
    "        )\n",
    "        \n",
    "        self.first_bn = nn.BatchNorm1d(num_features = d_args['filts'][0])\n",
    "        self.selu = nn.SELU(inplace=True)\n",
    "        self.block0 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][1], first = True))\n",
    "        self.block1 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][1]))\n",
    "        self.block2 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][2]))\n",
    "        d_args['filts'][2][0] = d_args['filts'][2][1]\n",
    "        self.block3 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][2]))\n",
    "        self.block4 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][2]))\n",
    "        self.block5 = nn.Sequential(Residual_block(nb_filts = d_args['filts'][2]))\n",
    "        self.avgpool = nn.AdaptiveAvgPool1d(1)\n",
    "\n",
    "        self.fc_attention0 = self._make_attention_fc(in_features = d_args['filts'][1][-1],\n",
    "            l_out_features = d_args['filts'][1][-1])\n",
    "        self.fc_attention1 = self._make_attention_fc(in_features = d_args['filts'][1][-1],\n",
    "            l_out_features = d_args['filts'][1][-1])\n",
    "        self.fc_attention2 = self._make_attention_fc(in_features = d_args['filts'][2][-1],\n",
    "            l_out_features = d_args['filts'][2][-1])\n",
    "        self.fc_attention3 = self._make_attention_fc(in_features = d_args['filts'][2][-1],\n",
    "            l_out_features = d_args['filts'][2][-1])\n",
    "        self.fc_attention4 = self._make_attention_fc(in_features = d_args['filts'][2][-1],\n",
    "            l_out_features = d_args['filts'][2][-1])\n",
    "        self.fc_attention5 = self._make_attention_fc(in_features = d_args['filts'][2][-1],\n",
    "            l_out_features = d_args['filts'][2][-1])\n",
    "\n",
    "        self.bn_before_gru = nn.BatchNorm1d(num_features = d_args['filts'][2][-1])\n",
    "        self.gru = nn.GRU(input_size = d_args['filts'][2][-1],\n",
    "\t\t\thidden_size = d_args['gru_node'],\n",
    "\t\t\tnum_layers = d_args['nb_gru_layer'],\n",
    "\t\t\tbatch_first = True)\n",
    "\n",
    "        \n",
    "        self.fc1_gru = nn.Linear(in_features = d_args['gru_node'],\n",
    "\t\t\tout_features = d_args['nb_fc_node'])\n",
    "       \n",
    "        self.fc2_gru = nn.Linear(in_features = d_args['nb_fc_node'],\n",
    "\t\t\tout_features = d_args['nb_classes'],bias=True)\n",
    "\t\t\t\n",
    "       \n",
    "        self.sig = nn.Sigmoid()\n",
    "        self.logsoftmax = nn.LogSoftmax(dim=1)\n",
    "        \n",
    "    def forward(self, x, y = None):\n",
    "        \n",
    "        \n",
    "        nb_samp = x.shape[0]\n",
    "        len_seq = x.shape[1]\n",
    "        x=x.view(nb_samp,1,len_seq)\n",
    "        \n",
    "        x = self.Sinc_conv(x)    \n",
    "        x = F.max_pool1d(torch.abs(x), 3)\n",
    "        x = self.first_bn(x)\n",
    "        x =  self.selu(x)\n",
    "        \n",
    "        x0 = self.block0(x)\n",
    "        y0 = self.avgpool(x0).view(x0.size(0), -1) # torch.Size([batch, filter])\n",
    "        y0 = self.fc_attention0(y0)\n",
    "        y0 = self.sig(y0).view(y0.size(0), y0.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x0 * y0 + y0  # (batch, filter, time) x (batch, filter, 1)\n",
    "        \n",
    "\n",
    "        x1 = self.block1(x)\n",
    "        y1 = self.avgpool(x1).view(x1.size(0), -1) # torch.Size([batch, filter])\n",
    "        y1 = self.fc_attention1(y1)\n",
    "        y1 = self.sig(y1).view(y1.size(0), y1.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x1 * y1 + y1 # (batch, filter, time) x (batch, filter, 1)\n",
    "\n",
    "        x2 = self.block2(x)\n",
    "        y2 = self.avgpool(x2).view(x2.size(0), -1) # torch.Size([batch, filter])\n",
    "        y2 = self.fc_attention2(y2)\n",
    "        y2 = self.sig(y2).view(y2.size(0), y2.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x2 * y2 + y2 # (batch, filter, time) x (batch, filter, 1)\n",
    "\n",
    "        x3 = self.block3(x)\n",
    "        y3 = self.avgpool(x3).view(x3.size(0), -1) # torch.Size([batch, filter])\n",
    "        y3 = self.fc_attention3(y3)\n",
    "        y3 = self.sig(y3).view(y3.size(0), y3.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x3 * y3 + y3 # (batch, filter, time) x (batch, filter, 1)\n",
    "\n",
    "        x4 = self.block4(x)\n",
    "        y4 = self.avgpool(x4).view(x4.size(0), -1) # torch.Size([batch, filter])\n",
    "        y4 = self.fc_attention4(y4)\n",
    "        y4 = self.sig(y4).view(y4.size(0), y4.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x4 * y4 + y4 # (batch, filter, time) x (batch, filter, 1)\n",
    "\n",
    "        x5 = self.block5(x)\n",
    "        y5 = self.avgpool(x5).view(x5.size(0), -1) # torch.Size([batch, filter])\n",
    "        y5 = self.fc_attention5(y5)\n",
    "        y5 = self.sig(y5).view(y5.size(0), y5.size(1), -1)  # torch.Size([batch, filter, 1])\n",
    "        x = x5 * y5 + y5 # (batch, filter, time) x (batch, filter, 1)\n",
    "\n",
    "        x = self.bn_before_gru(x)\n",
    "        x = self.selu(x)\n",
    "        x = x.permute(0, 2, 1)     #(batch, filt, time) >> (batch, time, filt)\n",
    "        self.gru.flatten_parameters()\n",
    "        x, _ = self.gru(x)\n",
    "        x = x[:,-1,:]\n",
    "        x = self.fc1_gru(x)\n",
    "        x = self.fc2_gru(x)\n",
    "        output=self.logsoftmax(x)\n",
    "      \n",
    "        return output\n",
    "        \n",
    "        \n",
    "\n",
    "    def _make_attention_fc(self, in_features, l_out_features):\n",
    "\n",
    "        l_fc = []\n",
    "        \n",
    "        l_fc.append(nn.Linear(in_features = in_features,\n",
    "\t\t\t        out_features = l_out_features))\n",
    "\n",
    "        \n",
    "\n",
    "        return nn.Sequential(*l_fc)\n",
    "\n",
    "\n",
    "    def _make_layer(self, nb_blocks, nb_filts, first = False):\n",
    "        layers = []\n",
    "        #def __init__(self, nb_filts, first = False):\n",
    "        for i in range(nb_blocks):\n",
    "            first = first if i == 0 else False\n",
    "            layers.append(Residual_block(nb_filts = nb_filts,\n",
    "\t\t\t\tfirst = first))\n",
    "            if i == 0: nb_filts[0] = nb_filts[1]\n",
    "            \n",
    "        return nn.Sequential(*layers)\n",
    "\n",
    "    def summary(self, input_size, batch_size=-1, device=\"cuda\", print_fn = None):\n",
    "        if print_fn == None: printfn = print\n",
    "        model = self\n",
    "        \n",
    "        def register_hook(module):\n",
    "            def hook(module, input, output):\n",
    "                class_name = str(module.__class__).split(\".\")[-1].split(\"'\")[0]\n",
    "                module_idx = len(summary)\n",
    "                \n",
    "                m_key = \"%s-%i\" % (class_name, module_idx + 1)\n",
    "                summary[m_key] = OrderedDict()\n",
    "                summary[m_key][\"input_shape\"] = list(input[0].size())\n",
    "                summary[m_key][\"input_shape\"][0] = batch_size\n",
    "                if isinstance(output, (list, tuple)):\n",
    "                    summary[m_key][\"output_shape\"] = [\n",
    "\t\t\t\t\t\t[-1] + list(o.size())[1:] for o in output\n",
    "\t\t\t\t\t]\n",
    "                else:\n",
    "                    summary[m_key][\"output_shape\"] = list(output.size())\n",
    "                    if len(summary[m_key][\"output_shape\"]) != 0:\n",
    "                        summary[m_key][\"output_shape\"][0] = batch_size\n",
    "                        \n",
    "                params = 0\n",
    "                if hasattr(module, \"weight\") and hasattr(module.weight, \"size\"):\n",
    "                    params += torch.prod(torch.LongTensor(list(module.weight.size())))\n",
    "                    summary[m_key][\"trainable\"] = module.weight.requires_grad\n",
    "                if hasattr(module, \"bias\") and hasattr(module.bias, \"size\"):\n",
    "                    params += torch.prod(torch.LongTensor(list(module.bias.size())))\n",
    "                summary[m_key][\"nb_params\"] = params\n",
    "                \n",
    "            if (\n",
    "\t\t\t\tnot isinstance(module, nn.Sequential)\n",
    "\t\t\t\tand not isinstance(module, nn.ModuleList)\n",
    "\t\t\t\tand not (module == model)\n",
    "\t\t\t):\n",
    "                hooks.append(module.register_forward_hook(hook))\n",
    "                \n",
    "        device = device.lower()\n",
    "        assert device in [\n",
    "\t\t\t\"cuda\",\n",
    "\t\t\t\"cpu\",\n",
    "\t\t], \"Input device is not valid, please specify 'cuda' or 'cpu'\"\n",
    "        \n",
    "        if device == \"cuda\" and torch.cuda.is_available():\n",
    "            dtype = torch.cuda.FloatTensor\n",
    "        else:\n",
    "            dtype = torch.FloatTensor\n",
    "        if isinstance(input_size, tuple):\n",
    "            input_size = [input_size]\n",
    "        x = [torch.rand(2, *in_size).type(dtype) for in_size in input_size]\n",
    "        summary = OrderedDict()\n",
    "        hooks = []\n",
    "        model.apply(register_hook)\n",
    "        model(*x)\n",
    "        for h in hooks:\n",
    "            h.remove()\n",
    "            \n",
    "        print_fn(\"----------------------------------------------------------------\")\n",
    "        line_new = \"{:>20}  {:>25} {:>15}\".format(\"Layer (type)\", \"Output Shape\", \"Param #\")\n",
    "        print_fn(line_new)\n",
    "        print_fn(\"================================================================\")\n",
    "        total_params = 0\n",
    "        total_output = 0\n",
    "        trainable_params = 0\n",
    "        for layer in summary:\n",
    "            # input_shape, output_shape, trainable, nb_params\n",
    "            line_new = \"{:>20}  {:>25} {:>15}\".format(\n",
    "\t\t\t\tlayer,\n",
    "\t\t\t\tstr(summary[layer][\"output_shape\"]),\n",
    "\t\t\t\t\"{0:,}\".format(summary[layer][\"nb_params\"]),\n",
    "\t\t\t)\n",
    "            total_params += summary[layer][\"nb_params\"]\n",
    "            total_output += np.prod(summary[layer][\"output_shape\"])\n",
    "            if \"trainable\" in summary[layer]:\n",
    "                if summary[layer][\"trainable\"] == True:\n",
    "                    trainable_params += summary[layer][\"nb_params\"]\n",
    "            print_fn(line_new)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = RawNet(d_args = d_args, device = 'cpu')\n",
    "model_dict = model.state_dict()\n",
    "ckpt = torch.load('pre_trained_DF_RawNet2.pth', map_location = torch.device('cpu'))\n",
    "model.load_state_dict(ckpt, model_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "import librosa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_and_preprocess_audio(audio_path):\n",
    "    '''Loads and returns a torch tensor object'''\n",
    "    x, sr = librosa.load(audio_path)\n",
    "    x_pt = torch.Tensor(x)\n",
    "    x_pt = torch.unsqueeze(x_pt, dim = 0)\n",
    "    return x_pt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[2.5792e-05, 3.1405e-05, 4.5405e-05,  ..., 0.0000e+00, 0.0000e+00,\n",
       "         0.0000e+00]])"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds = load_and_preprocess_audio(audio_path = 'audios/DF_E_2000027.flac')\n",
    "ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "grads = model(ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[-6.5565e-06, -1.1934e+01]], grad_fn=<LogSoftmaxBackward0>)"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch = grads[:, 1].data.cpu().numpy().ravel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-11.933539], dtype=float32)"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": [
    "_, batch_pred = grads.max(dim=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0])"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = np.argmin(grads.detach().numpy())\n",
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-11.933546"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grads.detach().numpy()[0][0] + grads.detach().numpy()[0][1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}