{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm_notebook\n%matplotlib inline \nimport cv2 as cv\n# https://www.kaggle.com/gpreda/deepfake-starter-kit","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"DATA_FOLDER = '../input/deepfake-detection-challenge'\nTRAIN_SAMPLE_FOLDER = 'train_sample_videos'\nTEST_FOLDER = 'test_videos'\n\nprint(f\"Train samples:{len(os.listdir(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER)))}\")\nprint(f\"Test samples: {len(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER)))}\")\n\nFACE_DETECTION_FOLDER = '../input/haar-cascades-for-face-detection'\nprint(f\"Face detection resources: {os.listdir(FACE_DETECTION_FOLDER)}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check files type\ntrain_list = list(os.listdir(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER)))\next_list = []\nfor file in train_list:\n    file_ext = file.split('.')[1]\n    if (file_ext not in ext_list):\n        ext_list.append(file_ext)\nprint(f\"Extensions: {ext_list}\")\n\n# count how many files with each extensions there are\nfor file_ext in ext_list:\n    print('No. of', file_ext, ':', len([file for file in train_list if file.endswith(file_ext)]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_list = list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER)))\next_list = []\nfor file in test_list:\n    file_ext = file.split('.')[1]\n    if (file_ext not in ext_list):\n        ext_list.append(file_ext)\nprint(f\"Extensions: {ext_list}\")\n\nfor file_ext in ext_list:\n    print('No. of', file_ext, ':', len([file for file in test_list if file.endswith(file_ext)]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"json_file = [file for file in train_list if file.endswith('json')][0]\nprint(f\"json file: {json_file}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# There is a json file(metadata.json) & we will explore this file\ndef get_meta_from_json(path):\n    df = pd.read_json(os.path.join(DATA_FOLDER, path, json_file))\n    # rows and cols are diffult to see so apply transpose\n    df = df.T\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"meta_train_df = get_meta_from_json(TRAIN_SAMPLE_FOLDER)\nmeta_train_df.head()\n# the index has the .mp4 file names","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Missing data\ndef missing_data(data):\n    total = data.isnull().sum()\n    percent = (total/data.isnull().count()*100)\n    tp = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n    \n    types = []\n    for col in data.columns:\n        dtype = str(data[col].dtype)\n        types.append(dtype)\n    tp['Types'] = types\n    \n    return tp\n\nmissing_data(meta_train_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"missing_data(meta_train_df.loc[meta_train_df.label=='REAL'])\n# all missing original data are the one associated with REAL label\n# missing_data(meta_train_df.loc[meta_train_df.label=='FAKE'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Unique vals\ndef unique_values(data):\n    total = data.count()\n    t = pd.DataFrame(total)\n    t.columns = ['Total']\n    \n    uniques = []\n    for col in data.columns:\n        unique = data[col].nunique()\n        uniques.append(unique)\n    t['Uniques'] = uniques\n    \n    return t\n    \nunique_values(meta_train_df)\n# We observe that original label has the same pattern for uniques values. \n# We know that we have 77 missing data (that's why total is only 323) \n# and we observe that we do have 209 unique examples.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Most frequent originals\ndef most_frequent_values(data):\n    total = data.count()\n    t = pd.DataFrame(total)\n    t.columns = ['Total']\n    \n    items = []\n    vals = []\n    for col in data.columns:\n        # count unique rows -> value_counts(), taking 1st index as it's val is greater so more occurence/frequent\n        itm = data[col].value_counts().index[0]\n        val = data[col].value_counts().values[0]\n        items.append(itm)\n        vals.append(val)\n    t['Most frequent item'] = items\n    t['Frequence'] = vals\n    t['Percent from total'] = np.round(vals / total * 100, 3)\n    return t\n  \nmost_frequent_values(meta_train_df)\n# We see that most frequent label is FAKE (80.75%), \n# meawmsgiti.mp4 is the most frequent original (6 samples).","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_count(feature, title, df):\n    f, ax = plt.subplots(1, 1, figsize=(4, 4))\n    total = float(len(df))\n    g = sns.countplot(x=feature, data=df, order=df[feature].value_counts().index[:20], palette='Set3')\n    g.set_title(\"No. and percentage of {}\".format(title))\n    \n    for p in ax.patches:\n        height = p.get_height()\n        ax.text(p.get_x() + p.get_width()/2, height, '{:1.2f}%'.format((height/total)*100), ha=\"center\")\n    plt.show()\n    \nplot_count('split', 'split (train)', meta_train_df)\nplot_count('label', 'label (train)', meta_train_df)\n# print(meta_train_df['label'].value_counts().index[:2])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Video data exploration\n# Missing video (or meta) data\nmeta = np.array(list(meta_train_df.index))\nstorage = np.array([file for file in train_list if file.endswith('mp4')])\nprint(f\"Metadata: {meta.shape[0]}, Folder: {storage.shape[0]}\")\nprint(f\"Files in metadata and not in folder: {np.setdiff1d(meta,storage,assume_unique=False).shape[0]}\")\nprint(f\"Files in folder and not in metadata: {np.setdiff1d(storage,meta,assume_unique=False).shape[0]}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Few fake videos(the index contains the .mp4 file names so .index gives the .mp4 file names)\nfake_train_sample_video = list(meta_train_df.loc[meta_train_df.label=='FAKE'].sample(3).index)\nfake_train_sample_video","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_image_from_video(video_path):\n    cap_img = cv.VideoCapture(video_path)\n    ret, frame = cap_img.read()\n    fig = plt.figure(figsize=(10, 10))\n    ax = fig.add_subplot(111)\n    frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n    ax.imshow(frame)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for video_file in fake_train_sample_video:\n    display_image_from_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, video_file))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Few real videos\nreal_train_sample_video = list(meta_train_df.loc[meta_train_df.label=='REAL'].sample(3).index)\nreal_train_sample_video","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for video_file in real_train_sample_video:\n    display_image_from_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, video_file))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Videos with same original\nmeta_train_df['original'].value_counts()[0:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_image_from_video_list(video_path_list, video_folder=TRAIN_SAMPLE_FOLDER):\n    plt.figure()\n    fig, ax = plt.subplots(2,3,figsize=(16,8))\n    # we only show images extracted from the first 6 videos\n    for i, video_file in enumerate(video_path_list[0:6]):\n        video_path = os.path.join(DATA_FOLDER, video_folder,video_file)\n        capture_image = cv.VideoCapture(video_path) \n        ret, frame = capture_image.read()\n        frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n        ax[i//3, i%3].imshow(frame)\n        ax[i//3, i%3].set_title(f\"Video: {video_file}\")\n        ax[i//3, i%3].axis('on')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"same_original_fake_train_sample_video = list(meta_train_df.loc[meta_train_df.original=='meawmsgiti.mp4'].index)\ndisplay_image_from_video_list(same_original_fake_train_sample_video)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"same_original_fake_train_sample_video = list(meta_train_df.loc[meta_train_df.original=='qeumxirsme.mp4'].index)\ndisplay_image_from_video_list(same_original_fake_train_sample_video)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"same_original_fake_train_sample_video = list(meta_train_df.loc[meta_train_df.original=='kgbkktcjxf.mp4'].index)\ndisplay_image_from_video_list(same_original_fake_train_sample_video)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Test video files(provide a col name, since no col name is there)\ntest_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])\ntest_videos.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# show one of test\ndisplay_image_from_video_list(test_videos.sample(6).video, TEST_FOLDER)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Face detection\nclass ObjectDetector():\n    \n    def __init__(self, object_cascade_path):\n        self.objectCascade = cv.CascadeClassifier(object_cascade_path)\n        \n    def detect(self, image, scale_factor=1.3, min_neighbors=5, min_size=(20, 20)):\n        rects = self.objectCascade.detectMultiScale(image, \n                                                    scaleFactor=scale_factor,\n                                                    minNeighbors=min_neighbors,\n                                                    minSize=min_size)\n        return rects","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"frontal_cascade_path = os.path.join(FACE_DETECTION_FOLDER, 'haarcascade_frontalface_default.xml')\neye_cascade_path= os.path.join(FACE_DETECTION_FOLDER,'haarcascade_eye.xml')\nprofile_cascade_path= os.path.join(FACE_DETECTION_FOLDER,'haarcascade_profileface.xml')\nsmile_cascade_path= os.path.join(FACE_DETECTION_FOLDER,'haarcascade_smile.xml')\n\nfd = ObjectDetector(frontal_cascade_path)\ned = ObjectDetector(eye_cascade_path)\npd = ObjectDetector(profile_cascade_path)\nsd = ObjectDetector(smile_cascade_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def detect_objects(image, scale_factor, min_neighbors, min_size):\n    \n    image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n    \n    eyes = ed.detect(image_gray, scale_factor=scale_factor, min_neighbors=min_neighbors, min_size=(int(min_size[0]/2), int(min_size[1]/2)))\n    \n    for x, y, w, h in eyes:\n        cv.circle(image, (int(x+w/2), int(y+h/2)), (int((w + h)/4)), (0, 0, 255), 3)\n    \n    profiles = pd.detect(image_gray, scale_factor=scale_factor, min_neighbors=min_neighbors, min_size=min_size)\n    \n    for x, y, w, h in profiles:\n        cv.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 3)\n    \n    faces = fd.detect(image_gray, scale_factor=scale_factor, min_neighbors=min_neighbors, min_size=min_size)\n\n    for x, y, w, h in faces:\n        cv.rectangle(image,(x, y),(x+w, y+h),(0, 255, 0), 3)\n    \n    fig = plt.figure(figsize=(10, 10))\n    ax = fig.add_subplot(111)\n    image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n    ax.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def extract_image_objects(video_file, video_set_folder=TRAIN_SAMPLE_FOLDER):\n    \n    video_path = os.path.join(DATA_FOLDER, video_set_folder, video_file)\n    cap_image = cv.VideoCapture(video_path)\n    ret, frame = cap_image.read()\n    \n    detect_objects(image=frame, scale_factor=1.3, min_neighbors=5, min_size=(50, 50))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"same_original_fake_train_sample_video = list(meta_train_df.loc[meta_train_df.original=='kgbkktcjxf.mp4'].index)\nfor video_file in same_original_fake_train_sample_video[1:4]:\n    print(video_file)\n    extract_image_objects(video_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fake_videos = list(meta_train_df.loc[meta_train_df.label == 'FAKE'].index)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from IPython.display import HTML\nfrom base64 import b64encode\n\ndef play_video(video_file, subset=TRAIN_SAMPLE_FOLDER):\n    video_url = open(os.path.join(DATA_FOLDER, subset, video_file),'rb').read()\n    data_url = \"data:video/mp4;base64,\" + b64encode(video_url).decode()\n    return HTML(\"\"\"<video width=500 controls><source src=\"%s\" type=\"video/mp4\"></video>\"\"\" % data_url)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"play_video(fake_videos[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install /kaggle/input/facenet-pytorch-vggface2/facenet_pytorch-2.0.0-py3-none-any.whl\n\nfrom facenet_pytorch.models.inception_resnet_v1 import get_torch_home\ntorch_home = get_torch_home()\n\n# Copy model checkpoints to torch cache so they are loaded automatically by the package\n!mkdir -p $torch_home/checkpoints/\n!cp /kaggle/input/facenet-pytorch-vggface2/20180402-114759-vggface2-logits.pth $torch_home/checkpoints/vggface2_DG3kwML46X.pt\n!cp /kaggle/input/facenet-pytorch-vggface2/20180402-114759-vggface2-features.pth $torch_home/checkpoints/vggface2_G5aNV2VSMn.pt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport glob\nimport time\nimport torch\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom tqdm.notebook import tqdm\n\n# See github.com/timesler/facenet-pytorch:\nfrom facenet_pytorch import MTCNN, InceptionResnetV1, extract_face\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(margin=14, keep_all=True, factor=0.5, device=device).eval()\n\n# Load facial recognition model\nresnet = InceptionResnetV1(pretrained='vggface2', device=device).eval()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class DetectionPipeline:\n    \"\"\"Pipeline class for detecting faces in the frames of a video file.\"\"\"\n    \n    def __init__(self, detector, n_frames=None, batch_size=60, resize=None):\n        \"\"\"Constructor for DetectionPipeline class.\n        \n        Keyword Arguments:\n            n_frames {int} -- Total number of frames to load. These will be evenly spaced\n                throughout the video. If not specified (i.e., None), all frames will be loaded.\n                (default: {None})\n            batch_size {int} -- Batch size to use with MTCNN face detector. (default: {32})\n            resize {float} -- Fraction by which to resize frames from original prior to face\n                detection. A value less than 1 results in downsampling and a value greater than\n                1 result in upsampling. (default: {None})\n        \"\"\"\n        self.detector = detector\n        self.n_frames = n_frames\n        self.batch_size = batch_size\n        self.resize = resize\n    \n    def __call__(self, filename):\n        \"\"\"Load frames from an MP4 video and detect faces.\n\n        Arguments:\n            filename {str} -- Path to video.\n        \"\"\"\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        if self.n_frames is None:\n            sample = np.arange(0, v_len)\n        else:\n            sample = np.linspace(0, v_len - 1, self.n_frames).astype(int)\n\n        # Loop through frames\n        faces = []\n        frames = []\n        for j in range(v_len):\n            success = v_cap.grab()\n            if j in sample:\n                # Load frame\n                success, frame = v_cap.retrieve()\n                if not success:\n                    continue\n                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n                frame = Image.fromarray(frame)\n                \n                # Resize frame to desired size\n                if self.resize is not None:\n                    frame = frame.resize([int(d * self.resize) for d in frame.size])\n                frames.append(frame)\n\n                # When batch is full, detect faces and reset frame list\n                if len(frames) % self.batch_size == 0 or j == sample[-1]:\n                    faces.extend(self.detector(frames))\n                    frames = []\n\n        v_cap.release()\n\n        return faces    \n\n\ndef process_faces(faces, resnet):\n    # Filter out frames without faces\n    faces = [f for f in faces if f is not None]\n    faces = torch.cat(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 = (embeddings - centroid).norm(dim=1).cpu().numpy()\n    \n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define face detection pipeline\ndetection_pipeline = DetectionPipeline(detector=mtcnn, batch_size=60, resize=0.25)\n\n# Get all test videos\nfilenames = glob.glob('/kaggle/input/deepfake-detection-challenge/test_videos/*.mp4')\n\nX = []\nstart = time.time()\nn_processed = 0\nwith torch.no_grad():\n    for i, filename in tqdm(enumerate(filenames), total=len(filenames)):\n        try:\n            # Load frames and find faces\n            faces = detection_pipeline(filename)\n            \n            # Calculate embeddings\n            X.append(process_faces(faces, resnet))\n\n        except KeyboardInterrupt:\n            print('\\nStopped.')\n            break\n\n        except Exception as e:\n            print(e)\n            X.append(None)\n        \n        n_processed += len(faces)\n        print(f'Frames per second (load+detect+embed): {n_processed / (time.time() - start):6.3}\\r', end='')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bias = -0.2942\nweight = 0.68235746\n\nsubmission = []\nfor filename, x_i in zip(filenames, X):\n    if x_i is not None:\n        prob = 1 / (1 + np.exp(-(bias + (weight * x_i).mean())))\n    else:\n        prob = 0.5\n    submission.append([os.path.basename(filename), prob])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(submission, columns=['filename', 'label'])\nsubmission.sort_values('filename').to_csv('submission.csv', index=False)\n\nplt.hist(submission.label, 20)\nplt.show()","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":4}