{"cells":[{"metadata":{},"cell_type":"markdown","source":"![](https://1.bp.blogspot.com/-wWMTXRF9nZo/XfJ42QhkvwI/AAAAAAAAGXY/XXWXquYOXPI_9pai27-JwXRszWcyRcIgwCLcBGAsYHQ/s1600/face.PNG)"},{"metadata":{},"cell_type":"markdown","source":"# Deepfake Detection Challenge"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Review of Data Files"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_sample_metadata = pd.read_json('../input/deepfake-detection-challenge/train_sample_videos/metadata.json').T\ntrain_sample_metadata.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# how to play mp4 video on kaggle"},{"metadata":{"trusted":true},"cell_type":"code","source":"from IPython.display import HTML\nfrom base64 import b64encode\nvid1 = open('/kaggle/input/deepfake-detection-challenge/test_videos/ytddugrwph.mp4','rb').read()\ndata_url = \"data:video/mp4;base64,\" + b64encode(vid1).decode()\nHTML(\"\"\"\n<video width=600 controls>\n      <source src=\"%s\" type=\"video/mp4\">\n</video>\n\"\"\" % data_url)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vid3 = open('/kaggle/input/deepfake-detection-challenge/test_videos/acazlolrpz.mp4','rb').read()\ndata_url = \"data:video/mp4;base64,\" + b64encode(vid3).decode()\nHTML(\"\"\"\n<video width=600 controls>\n      <source src=\"%s\" type=\"video/mp4\">\n</video>\n\"\"\" % data_url)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vid4 = open('/kaggle/input/deepfake-detection-challenge/test_videos/adohdulfwb.mp4','rb').read()\ndata_url = \"data:video/mp4;base64,\" + b64encode(vid4).decode()\nHTML(\"\"\"\n<video width=600 controls>\n      <source src=\"%s\" type=\"video/mp4\">\n</video>\n\"\"\" % data_url)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Recognizing people in a video stream"},{"metadata":{},"cell_type":"markdown","source":"## From video to frames"},{"metadata":{},"cell_type":"markdown","source":"In **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":{"trusted":true},"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        \n\n    \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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pic = plt.imread('image1.jpg')\nprint(pic.shape)\nplt.imshow(pic)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pic = plt.imread('image2.jpg')\ngray = rgb2gray(pic)\nplt.imshow(gray, cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# How to show specific frame "},{"metadata":{"trusted":true},"cell_type":"code","source":"first_Video = \"/kaggle/input/deepfake-detection-challenge/test_videos/ytddugrwph.mp4\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"count = 0\ncap = cv2.VideoCapture(first_Video)\nret,frame = cap.read()\n\nwhile count < 3:\n    cap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))   \n    ret,frame = cap.read()\n    if count == 0:\n        image0 = frame\n    elif count == 1:\n        image1 = frame\n    elif count == 2:\n        image2 = frame\n    \n    #cv2.imwrite( filepath+ \"\\frame%d.jpg\" % count, image)     # Next I will save frame as JPEG\n    count = count + 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display(img):\n    \n    fig = plt.figure(figsize=(8,8))\n    ax = fig.add_subplot(111)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    ax.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(image0)  # frame 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(image1)  # frame 2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(image2)  # frame 3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 5- Face Detection\n\nPlease don't forget to upvote thess kernels, I taked this parts of work from them: https://www.kaggle.com/robikscube/kaggle-deepfake-detection-introduction\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2 as cv\nimport os\nimport matplotlib.pylab as plt\ntrain_dir = '/kaggle/input/deepfake-detection-challenge/train_sample_videos/'\nfig, ax = plt.subplots(1,1, figsize=(15, 15))\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()   \nax.imshow(image)\nax.xaxis.set_visible(False)\nax.yaxis.set_visible(False)\nax.title.set_text(f\"FRAME 0: {video_file.split('/')[-1]}\")\nplt.grid(False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install face_recognition","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Locating a face within an image"},{"metadata":{"trusted":true},"cell_type":"code","source":"import face_recognition\nface_locations = face_recognition.face_locations(image)\n\n# https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py\nfrom PIL import Image\n\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\n    # You can access the actual face itself like this:\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Displaying many test examples and labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image, ImageDraw\n\nfig, axs = plt.subplots(19, 2, figsize=(15, 80))\naxs = np.array(axs)\naxs = axs.reshape(-1)\ni = 0\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:bottom, left:right]\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        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)\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.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Add padding to zoom out of face"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axs = plt.subplots(19, 2, figsize=(10, 80))\naxs = np.array(axs)\naxs = axs.reshape(-1)\ni = 0\npad = 60\nfor fn in train_sample_metadata.index[23:44]:\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        try:\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\n        except:\n            pass\nplt.grid(False)\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 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, please upvote it"},{"metadata":{},"cell_type":"markdown","source":"### Install dependencies"},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Imports"},{"metadata":{"trusted":true},"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'\nprint(f'Running on device: {device}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create MTCNN and Inception Resnet models"},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Process test videos"},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predict classes"},{"metadata":{"trusted":true},"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])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(submission, columns=['filename', 'label'])\nsubmission.sort_values('filename').to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.hist(submission.label, 20)\nplt.show()\nsubmission","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# to be continued...."}],"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":4,"nbformat_minor":1}