{"cells":[{"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\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input/deepfake-detection-challenge'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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\n\n# Install ffmpeg\n! tar xvf ../input/ffmpeg-static-build/ffmpeg-git-amd64-static.tar.xz\n","execution_count":null,"outputs":[]},{"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":{"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":{"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":{"trusted":true},"cell_type":"code","source":"bias = -0.2942\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.5\n    submission.append([os.path.basename(filename), prob])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(submission, columns=['filename', 'label'])\n\nplt.hist(submission.label, 20)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"threshold = 0.1\n\nfor i in range(len(submission)):\n    fn = submission.filename.values[i]\n    val = submission.label.values[i]\n    ar = os.path.join('/kaggle/input/deepfake-detection-challenge/test_videos', fn)\n    if ar is None:\n        submission.label.values[i] = (val + threshold) / 2\n    if ar == '16:9':\n        submission.label.values[i] = (val + 1 - threshold) / 2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}