{"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-02-17T09:39:25.315242Z","iopub.execute_input":"2023-02-17T09:39:25.315957Z","iopub.status.idle":"2023-02-17T09:39:26.304015Z","shell.execute_reply.started":"2023-02-17T09:39:25.315903Z","shell.execute_reply":"2023-02-17T09:39:26.303181Z"},"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-02-17T09:39:26.305703Z","iopub.execute_input":"2023-02-17T09:39:26.305974Z","iopub.status.idle":"2023-02-17T09:39:26.85897Z","shell.execute_reply.started":"2023-02-17T09:39:26.30593Z","shell.execute_reply":"2023-02-17T09:39:26.858307Z"},"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-02-17T09:39:26.863971Z","iopub.execute_input":"2023-02-17T09:39:26.864473Z","iopub.status.idle":"2023-02-17T09:39:27.10948Z","shell.execute_reply.started":"2023-02-17T09:39:26.86442Z","shell.execute_reply":"2023-02-17T09:39:27.108708Z"},"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-02-17T09:39:27.112335Z","iopub.execute_input":"2023-02-17T09:39:27.112917Z","iopub.status.idle":"2023-02-17T09:39:44.59375Z","shell.execute_reply.started":"2023-02-17T09:39:27.112868Z","shell.execute_reply":"2023-02-17T09:39:44.5929Z"},"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 face_recognition","metadata":{"execution":{"iopub.status.busy":"2023-02-17T09:39:44.595103Z","iopub.execute_input":"2023-02-17T09:39:44.59535Z"},"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":{"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 = 60 #pad is addded to the plot to zoom out of the face\nfor fn in train_sample_metadata.index[:24]:\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":{"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":{"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 GPY is being used or the CPU\nprint(f'Running on device: {device}')\ntorch.cuda.get_device_name(0)","metadata":{"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":{"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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.hist(submission.label, 20)\nplt.show()\nsubmission","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# to be continued....","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}