{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Deepfake Detection","metadata":{}},{"cell_type":"markdown","source":"# 1. Imports","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom skimage.color import rgb2gray\nimport cv2\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom scipy import ndimage\nimport os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport skimage.io\nimport matplotlib\nimport matplotlib.pyplot as plt","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2023-05-14T08:04:37.010262Z","iopub.execute_input":"2023-05-14T08:04:37.010586Z","iopub.status.idle":"2023-05-14T08:04:38.003632Z","shell.execute_reply.started":"2023-05-14T08:04:37.010528Z","shell.execute_reply":"2023-05-14T08:04:38.002861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2. Review of Data Files","metadata":{}},{"cell_type":"code","source":"train_sample_metadata = pd.read_json('../input/deepfake-detection-challenge/train_sample_videos/metadata.json').T\ntrain_sample_metadata.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:04:38.005483Z","iopub.execute_input":"2023-05-14T08:04:38.005874Z","iopub.status.idle":"2023-05-14T08:04:38.642483Z","shell.execute_reply.started":"2023-05-14T08:04:38.005730Z","shell.execute_reply":"2023-05-14T08:04:38.641589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sample_metadata.groupby('label')['label'].count().plot(figsize=(15, 5), kind='bar', title='Distribution of Labels in the Training Set')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:04:38.643926Z","iopub.execute_input":"2023-05-14T08:04:38.644217Z","iopub.status.idle":"2023-05-14T08:04:38.908290Z","shell.execute_reply.started":"2023-05-14T08:04:38.644169Z","shell.execute_reply":"2023-05-14T08:04:38.907433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3. Recognizing people in a video stream","metadata":{}},{"cell_type":"markdown","source":"## From video to frames\nIn **cv2.VideoCapture(VIDEO_STREAM)**, we just have to mention the video name with it’s extension. \n\nYou can set frame rate which is widely known as fps (frames per second). Here I set 0.5 so it will capture a frame at every 0.5 seconds, means 2 frames (images) for each second.\n\nIt will save images with name as **image1.jpg**, **image2.jpg** and so on.","metadata":{}},{"cell_type":"code","source":"import cv2\n\nVIDEO_STREAM = \"/kaggle/input/deepfake-detection-challenge/test_videos/ytddugrwph.mp4\"\n#VIDEO_STREAM_OUT = \"/kaggle/input/deepfake-detection-challenge/test_videos/Result.mp4\"\n\nvidcap = cv2.VideoCapture(VIDEO_STREAM)\ndef getFrame(sec):\n    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)\n    hasFrames,image = vidcap.read()\n    if hasFrames:\n        cv2.imwrite(\"image\"+str(count)+\".jpg\", image) # save frame as JPG file\n        plt.imshow(image)\n    return hasFrames\nsec = 0\nframeRate = 0.5 #//it will capture image in each 0.5 second\ncount=1\nsuccess = getFrame(sec)\nwhile success:\n    count = count + 1\n    sec = sec + frameRate\n    sec = round(sec, 2)\n    success = getFrame(sec)","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:04:38.909905Z","iopub.execute_input":"2023-05-14T08:04:38.910460Z","iopub.status.idle":"2023-05-14T08:04:56.739877Z","shell.execute_reply.started":"2023-05-14T08:04:38.910392Z","shell.execute_reply":"2023-05-14T08:04:56.736411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. Face Detection\n\nSource: https://www.kaggle.com/robikscube/kaggle-deepfake-detection-introduction\n","metadata":{}},{"cell_type":"markdown","source":"## Locating a face within an image","metadata":{}},{"cell_type":"code","source":"!pip install '/kaggle/input/dlibpkg/dlib-19.19.0' -vvv","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:04:56.744302Z","iopub.execute_input":"2023-05-14T08:04:56.744862Z","iopub.status.idle":"2023-05-14T08:15:21.145291Z","shell.execute_reply.started":"2023-05-14T08:04:56.744612Z","shell.execute_reply":"2023-05-14T08:15:21.144409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install face_recognition","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:15:21.147335Z","iopub.execute_input":"2023-05-14T08:15:21.147651Z","iopub.status.idle":"2023-05-14T08:15:50.056211Z","shell.execute_reply.started":"2023-05-14T08:15:21.147602Z","shell.execute_reply":"2023-05-14T08:15:50.055268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import face_recognition\nimport cv2 as cv\nimport os\nimport matplotlib.pylab as plt\nfrom PIL import Image\ntrain_dir = '/kaggle/input/deepfake-detection-challenge/train_sample_videos/'\ntrain_video_files = [train_dir + x for x in os.listdir(train_dir)]\n# video_file = train_video_files[30]\nvideo_file = '/kaggle/input/deepfake-detection-challenge/train_sample_videos/afoovlsmtx.mp4'\ncap = cv.VideoCapture(video_file)\nsuccess, image = cap.read()\nimage = cv.cvtColor(image, cv.COLOR_BGR2RGB)\ncap.release() \nface_locations = face_recognition.face_locations(image)\n\n# https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py\nprint(\"I found {} face(s) in this photograph.\".format(len(face_locations)))\n\nfor face_location in face_locations:\n\n    # Print the location of each face in this image\n    top, right, bottom, left = face_location\n    print(\"A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}\".format(top, left, bottom, right))\n    # Access the actual face itself:\n    face_image = image[top:bottom, left:right]\n    fig, ax = plt.subplots(1,1, figsize=(5, 5))\n    plt.grid(False)\n    ax.xaxis.set_visible(False)\n    ax.yaxis.set_visible(False)\n    ax.imshow(face_image)","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:15:50.058669Z","iopub.execute_input":"2023-05-14T08:15:50.058976Z","iopub.status.idle":"2023-05-14T08:15:54.827682Z","shell.execute_reply.started":"2023-05-14T08:15:50.058921Z","shell.execute_reply":"2023-05-14T08:15:54.826868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5. Display test examples and labels","metadata":{}},{"cell_type":"code","source":"from PIL import Image, ImageDraw\n\nfig, axs = plt.subplots(19, 2, figsize=(10, 80))\naxs = np.array(axs)\naxs = axs.reshape(-1)\ni = 0\npad = 30 #pad is addded to the plot to zoom out of the face\nfor fn in train_sample_metadata.index[:23]:\n    label = train_sample_metadata.loc[fn]['label']\n    orig = train_sample_metadata.loc[fn]['label']\n    video_file = f'/kaggle/input/deepfake-detection-challenge/train_sample_videos/{fn}'\n    ax = axs[i]\n    cap = cv.VideoCapture(video_file)\n    success, image = cap.read()\n    image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n    face_locations = face_recognition.face_locations(image)\n    if len(face_locations) > 0:\n        # Print first face\n        face_location = face_locations[0]\n        top, right, bottom, left = face_location\n        face_image = image[top-pad:bottom+pad, left-pad:right+pad]\n        ax.imshow(face_image)\n        ax.grid(False)\n        ax.title.set_text(f'{fn} - {label}')\n        ax.xaxis.set_visible(False)\n        ax.yaxis.set_visible(False)\n        # Find landmarks\n        face_landmarks_list = face_recognition.face_landmarks(face_image)\n        if len(face_landmarks_list) > 0:\n            face_landmarks = face_landmarks_list[0]\n            pil_image = Image.fromarray(face_image)\n            d = ImageDraw.Draw(pil_image)\n            for facial_feature in face_landmarks.keys():\n                d.line(face_landmarks[facial_feature], width=2, fill='yellow')\n            landmark_face_array = np.array(pil_image)\n            ax2 = axs[i+1]\n            ax2.imshow(landmark_face_array)\n            ax2.grid(False)\n            ax2.title.set_text(f'{fn} - {label}')\n            ax2.xaxis.set_visible(False)\n            ax2.yaxis.set_visible(False)\n            i += 2\nplt.grid(False)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:15:54.829163Z","iopub.execute_input":"2023-05-14T08:15:54.829730Z","iopub.status.idle":"2023-05-14T08:16:29.526502Z","shell.execute_reply.started":"2023-05-14T08:15:54.829673Z","shell.execute_reply":"2023-05-14T08:16:29.525635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(axs))","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:16:29.527733Z","iopub.execute_input":"2023-05-14T08:16:29.528131Z","iopub.status.idle":"2023-05-14T08:16:29.535391Z","shell.execute_reply.started":"2023-05-14T08:16:29.528085Z","shell.execute_reply":"2023-05-14T08:16:29.534516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 6. Baseline submission using Facenet\n\n#### Baseline code is taked from this kernel: https://www.kaggle.com/climbest/facial-recognition-model-in-pytorch-change-bias","metadata":{}},{"cell_type":"markdown","source":"### Install dependencies","metadata":{}},{"cell_type":"code","source":"%%capture\n# Install facenet-pytorch\n%pip install /kaggle/input/facenet-pytorch-vggface2/facenet_pytorch-1.0.1-py3-none-any.whl\n\n# Copy model checkpoints to torch cache so they are loaded automatically by the package\n!mkdir -p /tmp/.cache/torch/checkpoints/\n!cp /kaggle/input/facenet-pytorch-vggface2/20180402-114759-vggface2-logits.pth /tmp/.cache/torch/checkpoints/vggface2_DG3kwML46X.pt\n!cp /kaggle/input/facenet-pytorch-vggface2/20180402-114759-vggface2-features.pth /tmp/.cache/torch/checkpoints/vggface2_G5aNV2VSMn.pt","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:16:29.536962Z","iopub.execute_input":"2023-05-14T08:16:29.537497Z","iopub.status.idle":"2023-05-14T08:16:40.457724Z","shell.execute_reply.started":"2023-05-14T08:16:29.537417Z","shell.execute_reply":"2023-05-14T08:16:40.456539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport glob\nimport torch\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n# See github.com/timesler/facenet-pytorch:\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\n\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu' #checks if GPU is being used or the CPU\nprint(f'Running on device: {device}')\ntorch.cuda.get_device_name(0)","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:16:40.459773Z","iopub.execute_input":"2023-05-14T08:16:40.460115Z","iopub.status.idle":"2023-05-14T08:16:41.927785Z","shell.execute_reply.started":"2023-05-14T08:16:40.460061Z","shell.execute_reply":"2023-05-14T08:16:41.926960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create MTCNN and Inception Resnet models","metadata":{}},{"cell_type":"code","source":"# Load face detector\nmtcnn = MTCNN(device=device).eval()\n\n# Load facial recognition model\nresnet = InceptionResnetV1(pretrained='vggface2', num_classes=2, device=device).eval()","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:16:41.929305Z","iopub.execute_input":"2023-05-14T08:16:41.929876Z","iopub.status.idle":"2023-05-14T08:16:59.618741Z","shell.execute_reply.started":"2023-05-14T08:16:41.929820Z","shell.execute_reply":"2023-05-14T08:16:59.617749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 7. Process test videos","metadata":{}},{"cell_type":"code","source":"# Get all test videos\nfilenames = glob.glob('/kaggle/input/deepfake-detection-challenge/test_videos/*.mp4')\n\n# Number of frames to sample (evenly spaced) from each video\nn_frames = 10\n\nX = []\nwith torch.no_grad():\n    for i, filename in enumerate(filenames):\n        print(f'Processing {i+1:5n} of {len(filenames):5n} videos\\r', end='')\n        \n        try:\n            # Create video reader and find length\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            sample = np.linspace(0, v_len - 1, n_frames).round().astype(int)\n            imgs = []\n            for j in range(v_len):\n                success, vframe = v_cap.read()\n                vframe = cv2.cvtColor(vframe, cv2.COLOR_BGR2RGB)\n                if j in sample:\n                    imgs.append(Image.fromarray(vframe))\n            v_cap.release()\n            \n            # Pass image batch to MTCNN as a list of PIL images\n            faces = mtcnn(imgs)\n            \n            # Filter out frames without faces\n            faces = [f for f in faces if f is not None]\n            faces = torch.stack(faces).to(device)\n            \n            # Generate facial feature vectors using a pretrained model\n            embeddings = resnet(faces)\n            \n            # Calculate centroid for video and distance of each face's feature vector from centroid\n            centroid = embeddings.mean(dim=0)\n            X.append((embeddings - centroid).norm(dim=1).cpu().numpy())\n        except KeyboardInterrupt:\n            raise Exception(\"Stopped.\")\n        except:\n            X.append(None)","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:16:59.620190Z","iopub.execute_input":"2023-05-14T08:16:59.620526Z","iopub.status.idle":"2023-05-14T08:44:51.608340Z","shell.execute_reply.started":"2023-05-14T08:16:59.620471Z","shell.execute_reply":"2023-05-14T08:44:51.607553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 8. Predict classes","metadata":{}},{"cell_type":"code","source":"bias = -0.4\nweight = 0.068235746\n\nsubmission = []\nfor filename, x_i in zip(filenames, X):\n    if x_i is not None and len(x_i) == 10:\n        prob = 1 / (1 + np.exp(-(bias + (weight * x_i).sum())))\n    else:\n        prob = 0.6\n    submission.append([os.path.basename(filename), prob])","metadata":{"execution":{"iopub.status.busy":"2023-05-14T08:44:51.609960Z","iopub.execute_input":"2023-05-14T08:44:51.610259Z","iopub.status.idle":"2023-05-14T08:44:51.624257Z","shell.execute_reply.started":"2023-05-14T08:44:51.610209Z","shell.execute_reply":"2023-05-14T08:44:51.623533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 9. Output","metadata":{}},{"cell_type":"code","source":"submission = pd.DataFrame(submission, columns=['filename', 'label'])\nsubmission.sort_values('filename').to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-14T09:12:34.796528Z","iopub.execute_input":"2023-05-14T09:12:34.796866Z","iopub.status.idle":"2023-05-14T09:12:34.809556Z","shell.execute_reply.started":"2023-05-14T09:12:34.796811Z","shell.execute_reply":"2023-05-14T09:12:34.808556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nplot=sns.distplot(submission.label,bins=30,kde=True,color='purple',hist_kws={\"edgecolor\": 'black'})\nplot.set(xlabel='Probability')","metadata":{"execution":{"iopub.status.busy":"2023-05-14T09:12:39.166295Z","iopub.execute_input":"2023-05-14T09:12:39.166651Z","iopub.status.idle":"2023-05-14T09:12:39.546509Z","shell.execute_reply.started":"2023-05-14T09:12:39.166591Z","shell.execute_reply":"2023-05-14T09:12:39.545249Z"},"trusted":true},"execution_count":null,"outputs":[]}]}