{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Two Datasets are required and both are public named maruti, filled metadata "},{"metadata":{"trusted":true},"cell_type":"code","source":"%%capture\n!pip install ../input/maruti/facenet_pytorch-2.2.7-py3-none-any.whl\n!pip install --no-deps ../input/maruti/maruti-1.3.1-py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from maruti.imports.ml import *","execution_count":null,"outputs":[]},{"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\nfrom facenet_pytorch import MTCNN\nfrom torch.nn.utils.rnn import pack_sequence\ntest_dir = '../input/deepfake-detection-challenge/test_videos/'\ntest_videos = sorted(os.listdir(test_dir))\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"remove this code line it is just so that it won't take much time to commit\nSTART"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_videos = test_videos[:20]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"END\nDon't remove anything after this"},{"metadata":{"trusted":true},"cell_type":"code","source":"## define your version of mtcnn \nmtcnn = MTCNN(select_largest=False,device=device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## your model\nresnet = torchvision.models.resnet50(False)\nresnet.load_state_dict(torch.load('../input/resnet/resnet.pth')) # set path to .pth file\n_ = resnet.eval().to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"group_transform = mdata.group_transform['val'] # default transform\n\n\n#### in case you want your own transform define it here. uncomment following code and define the transform\n#### it'll receive a (224,224,3) numpy  image and should perform transforms on that.\n# transform = torch_transforms.Compose([\n#     torch_transforms.RandomHorizontalFlip()\n# ])\n## don't change the next line\n# group_transform = lambda x: torch.stack(map(transform, x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_batch(path):\n    frame_count, _ = mvis.vid_info(path)\n    frame_idx = np.linspace(0, frame_count-1, 8, dtype=int)\n    frame_list = list(mvis.get_face_frames(path, frame_idx))\n    return frame_list","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict(path):\n    batch = get_batch(path)\n    batch = group_transform(batch).to(device)\n    \n    with torch.no_grad():\n        pred = resnet(batch)\n    ## I don't use sigmoid in my model. If you use then remove the next line.\n    pred = torch.sigmoid(pred)\n    pred = pred.mean().item()\n    return pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#SPEED TEST\nspeed_test = True\nif speed_test:\n    start = time.perf_counter()\n    for vid in tqdm(test_videos[:10]):\n        print(predict(test_dir+vid))\n    print((time.perf_counter()-start)/10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = time.perf_counter()\npredictions = []\nfor i, vid in enumerate(test_videos):\n    if i%20==19:\n        os.system(f'echo {str(i)} {predictions[-1]:.2f}')\n    \n    try:\n        predictions.append(predict(test_dir+vid))\n    except Exception as e:\n        print(vid+' error:'+str(e))\n        predictions.append(0.5)\n\nprint((time.perf_counter()-start)/len(test_videos))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = pd.DataFrame({\"filename\": test_videos, \"label\": predictions})\nsubmission_df['label'] = submission_df['label'] # use this line for clipping\nsubmission_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Testing code\n\nimport torch.nn.functional as F\nfrom sklearn.metrics import accuracy_score, log_loss\nimport json\n\n\nloss_fn = nn.BCELoss()\nsubmission = pd.read_csv('submission.csv')\nprint(submission.head())\n\nmetadata =  maruti.read_json('../input/filled-metadata/filled_metadata.json')\n\nx = submission['filename']\nypred = submission['label'].to_list()\ny = []\n\nfor i, _ in enumerate(x):\n    y.append(float(metadata[x[i]]['label'] == 'FAKE'))\ny = torch.tensor(y)\nypred = torch.tensor(ypred)\nloss = F.binary_cross_entropy(ypred, y)\nassert loss < 0.65, f'Loss Too High: {loss}'\nprint('loss',F.binary_cross_entropy(ypred, y).item())\nif True:\n    plt.hist(ypred, bins=200, alpha=0.5)\n    plt.hist(y, bins=200, alpha=0.2)\n    plt.show()","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":4}