{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"}],"dockerImageVersionId":29845,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:23:54.691605Z","iopub.execute_input":"2024-12-07T07:23:54.691929Z","iopub.status.idle":"2024-12-07T07:25:14.721840Z","shell.execute_reply.started":"2024-12-07T07:23:54.691861Z","shell.execute_reply":"2024-12-07T07:25:14.721142Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport imageio\nimport cv2\nimport os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:14.724350Z","iopub.execute_input":"2024-12-07T07:25:14.724570Z","iopub.status.idle":"2024-12-07T07:25:17.799782Z","shell.execute_reply.started":"2024-12-07T07:25:14.724533Z","shell.execute_reply":"2024-12-07T07:25:17.799237Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_FOLDER = '/kaggle/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)))}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:17.800880Z","iopub.execute_input":"2024-12-07T07:25:17.801075Z","iopub.status.idle":"2024-12-07T07:25:17.840956Z","shell.execute_reply.started":"2024-12-07T07:25:17.801041Z","shell.execute_reply":"2024-12-07T07:25:17.840342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata = pd.read_json('/kaggle/input/deepfake-detection-challenge/train_sample_videos/metadata.json').T\ntrain_sample_metadata.tail()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:17.842376Z","iopub.execute_input":"2024-12-07T07:25:17.842657Z","iopub.status.idle":"2024-12-07T07:25:18.376186Z","shell.execute_reply.started":"2024-12-07T07:25:17.842604Z","shell.execute_reply":"2024-12-07T07:25:18.375527Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.groupby('label')['label'].count().plot(figsize=(5,5),kind='bar',title='The Label in the Training Set')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:18.378455Z","iopub.execute_input":"2024-12-07T07:25:18.378677Z","iopub.status.idle":"2024-12-07T07:25:18.588392Z","shell.execute_reply.started":"2024-12-07T07:25:18.378635Z","shell.execute_reply":"2024-12-07T07:25:18.587316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:18.591901Z","iopub.execute_input":"2024-12-07T07:25:18.592326Z","iopub.status.idle":"2024-12-07T07:25:18.599172Z","shell.execute_reply.started":"2024-12-07T07:25:18.592260Z","shell.execute_reply":"2024-12-07T07:25:18.598238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].sample(5).index)\nf_train_sample_video","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:18.600486Z","iopub.execute_input":"2024-12-07T07:25:18.600822Z","iopub.status.idle":"2024-12-07T07:25:18.616790Z","shell.execute_reply.started":"2024-12-07T07:25:18.600771Z","shell.execute_reply":"2024-12-07T07:25:18.615576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def capture_image_from_video(video_path):\n    # Capture video\n    capture_image = cv2.VideoCapture(video_path)\n    ret, frame = capture_image.read()\n    \n    if not ret:\n        print(f\"Could not read frame from {video_path}\")\n        return\n    \n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    fig = plt.figure(figsize=(4, 4))\n    ax = fig.add_subplot(111)  \n    ax.imshow(frame)\n    plt.show()\n    capture_image.release()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:18.618290Z","iopub.execute_input":"2024-12-07T07:25:18.618728Z","iopub.status.idle":"2024-12-07T07:25:18.630509Z","shell.execute_reply.started":"2024-12-07T07:25:18.618567Z","shell.execute_reply":"2024-12-07T07:25:18.629434Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for video_file in f_train_sample_video:\n    capture_image_from_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, video_file))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:18.631805Z","iopub.execute_input":"2024-12-07T07:25:18.632151Z","iopub.status.idle":"2024-12-07T07:25:20.261547Z","shell.execute_reply.started":"2024-12-07T07:25:18.632098Z","shell.execute_reply":"2024-12-07T07:25:20.260718Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"r_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='REAL'].sample(5).index)\nr_train_sample_video","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:20.263008Z","iopub.execute_input":"2024-12-07T07:25:20.263323Z","iopub.status.idle":"2024-12-07T07:25:20.270821Z","shell.execute_reply.started":"2024-12-07T07:25:20.263272Z","shell.execute_reply":"2024-12-07T07:25:20.269951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for video_file in r_train_sample_video:\n    capture_image_from_video(os.path.join(DATA_FOLDER,TRAIN_SAMPLE_FOLDER,video_file))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:20.272075Z","iopub.execute_input":"2024-12-07T07:25:20.272399Z","iopub.status.idle":"2024-12-07T07:25:22.288181Z","shell.execute_reply.started":"2024-12-07T07:25:20.272352Z","shell.execute_reply":"2024-12-07T07:25:22.284515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:22.289523Z","iopub.execute_input":"2024-12-07T07:25:22.289849Z","iopub.status.idle":"2024-12-07T07:25:22.310322Z","shell.execute_reply.started":"2024-12-07T07:25:22.289796Z","shell.execute_reply":"2024-12-07T07:25:22.307830Z"}},"outputs":[],"execution_count":null},{"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)\nplay_video(f_videos[5])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:22.311804Z","iopub.execute_input":"2024-12-07T07:25:22.312139Z","iopub.status.idle":"2024-12-07T07:25:26.790084Z","shell.execute_reply.started":"2024-12-07T07:25:22.312084Z","shell.execute_reply":"2024-12-07T07:25:26.789331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_size = 224\nbatch_size = 64\nepochs = 15\n\nmax_seq_length = 20\nnum_features = 2048","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:26.791459Z","iopub.execute_input":"2024-12-07T07:25:26.791713Z","iopub.status.idle":"2024-12-07T07:25:27.132975Z","shell.execute_reply.started":"2024-12-07T07:25:26.791662Z","shell.execute_reply":"2024-12-07T07:25:27.132164Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def crop_center_square(frame):\n    y,x = frame.shape[0:2]\n    min_dim = min(y, x)\n    start_x = (x // 2) - (min_dim // 2)\n    start_y = (y // 2) - (min_dim // 2)\n    return frame[start_y :start_y + min_dim, start_x : start_x + min_dim]\n\ndef load_video(path, max_frames=0, resize=(img_size, img_size)):\n    cap = cv2.VideoCapture(path)\n    frames = []\n    try:\n        while 1:\n            ret, frame = cap.read()\n            if not ret:\n                break\n            frame = crop_center_square(frame)\n            frame = cv2.resize(frame, resize)\n            frame = frame[:, :, [2, 1, 0]]\n            frames.append(frame)\n            \n            if len(frames) == max_frames:\n                break\n    finally:\n        cap.release()\n    return np.array(frames)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:27.134295Z","iopub.execute_input":"2024-12-07T07:25:27.134506Z","iopub.status.idle":"2024-12-07T07:25:27.144488Z","shell.execute_reply.started":"2024-12-07T07:25:27.134470Z","shell.execute_reply":"2024-12-07T07:25:27.143834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def pretrain_feature_extractor():\n    feature_extractor = keras.applications.InceptionV3(\n    weights = \"imagenet\",\n    include_top=False,\n    pooling=\"avg\",\n    input_shape = (img_size,img_size,3)\n    )\n    preprocess_input = keras.applications.inception_v3.preprocess_input\n    \n    inputs = keras.Input((img_size,img_size,3))\n    preprocessed = preprocess_input(inputs)\n    \n    outputs = feature_extractor(preprocessed)\n    return keras.Model(inputs, outputs, name=\"feature_extractor\")\n\nfeature_extractor = pretrain_feature_extractor()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:27.145537Z","iopub.execute_input":"2024-12-07T07:25:27.145724Z","iopub.status.idle":"2024-12-07T07:25:30.135926Z","shell.execute_reply.started":"2024-12-07T07:25:27.145692Z","shell.execute_reply":"2024-12-07T07:25:30.135217Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def prepare_all_videos(df, root_dir):\n    num_samples = len(df)\n    video_paths = list(df.index)\n    labels = df[\"label\"].values\n    labels = np.array(labels=='FAKE').astype(np.int)\n    \n    frame_masks = np.zeros(shape=(num_samples, max_seq_length), dtype=\"bool\")\n    frame_features = np.zeros(\n        shape=(num_samples, max_seq_length, num_features), dtype=\"float32\" \n    )\n    \n    for idx, path in enumerate(video_paths):\n        frames = load_video(os.path.join(root_dir, path))\n        frames = frames[None, ...]\n        \n        temp_frame_mask = np.zeros(shape=(1, max_seq_length,), dtype=\"bool\")\n        temp_frame_features = np.zeros(shape=(1, max_seq_length, num_features), dtype=\"float32\")\n        \n        for i, batch in enumerate(frames):\n            video_length = batch.shape[0] \n            length = min(max_seq_length, video_length) #if length is over 20s ,only cut 20s\n            for j in range(length):\n                temp_frame_features[i, j, :] =feature_extractor.predict(batch[None, j, :])\n            temp_frame_mask[i, :length] =1 # 1 = not masked, 0 = masked ->give 1 when there are images ,otherwise 0 for padding\n        \n        frame_features[idx,] =temp_frame_features.squeeze() #squeeze array for training\n        frame_masks[idx,] =temp_frame_mask.squeeze()\n    \n    return (frame_features, frame_masks), labels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:30.137088Z","iopub.execute_input":"2024-12-07T07:25:30.137366Z","iopub.status.idle":"2024-12-07T07:25:30.145972Z","shell.execute_reply.started":"2024-12-07T07:25:30.137319Z","shell.execute_reply":"2024-12-07T07:25:30.145032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nTrain_set , Test_set = train_test_split(train_sample_metadata, test_size=0.1,random_state=42,\n                                       stratify=train_sample_metadata['label'])\nprint(Train_set.shape, Test_set.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:30.147127Z","iopub.execute_input":"2024-12-07T07:25:30.147476Z","iopub.status.idle":"2024-12-07T07:25:30.840584Z","shell.execute_reply.started":"2024-12-07T07:25:30.147427Z","shell.execute_reply":"2024-12-07T07:25:30.839917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data, train_labels = prepare_all_videos(Train_set, \"train\")\ntest_data, test_labels = prepare_all_videos(Test_set, \"test\")\n\nprint(f\"Frame features in train set:{train_data[0].shape}\")\nprint(f\"Frame masks in train set:{train_data[1].shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:30.841897Z","iopub.execute_input":"2024-12-07T07:25:30.842209Z","iopub.status.idle":"2024-12-07T07:25:30.928783Z","shell.execute_reply.started":"2024-12-07T07:25:30.842137Z","shell.execute_reply":"2024-12-07T07:25:30.927970Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"frame_features_input = keras.Input((max_seq_length, num_features))\nmask_input = keras.Input((max_seq_length,),dtype=\"bool\")\n\nx = keras.layers.GRU(16, return_sequences=True)(frame_features_input, mask = mask_input)\nx = keras.layers.GRU(8)(x)\nx = keras.layers.Dropout(0.4)(x)\nx = keras.layers.Dense(8, activation=\"relu\")(x)\noutput = keras.layers.Dense(1, activation=\"sigmoid\")(x)\n\nmodel = keras.Model([frame_features_input, mask_input], output)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:30.930107Z","iopub.execute_input":"2024-12-07T07:25:30.930463Z","iopub.status.idle":"2024-12-07T07:25:32.411502Z","shell.execute_reply.started":"2024-12-07T07:25:30.930408Z","shell.execute_reply":"2024-12-07T07:25:32.410824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"checkpoint = keras.callbacks.ModelCheckpoint('./', save_weights_only=True, save_best_only=True)\nhistory = model.fit(\n        [train_data[0], train_data[1]],\n        train_labels,\n        validation_data=([test_data[0], test_data[1]], test_labels),\n        callbacks=[checkpoint],\n        epochs=epochs,\n        batch_size=8\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:32.412556Z","iopub.execute_input":"2024-12-07T07:25:32.412752Z","iopub.status.idle":"2024-12-07T07:25:49.656932Z","shell.execute_reply.started":"2024-12-07T07:25:32.412718Z","shell.execute_reply":"2024-12-07T07:25:49.656364Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:49.658300Z","iopub.execute_input":"2024-12-07T07:25:49.658527Z","iopub.status.idle":"2024-12-07T07:25:49.662922Z","shell.execute_reply.started":"2024-12-07T07:25:49.658482Z","shell.execute_reply":"2024-12-07T07:25:49.662394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def prepare_single_video(frames):\n    frames = frames[None, ...]\n    frame_mask = np.zeros(shape=(1, max_seq_length,), dtype=\"bool\")\n    frame_features = np.zeros(shape=(1, max_seq_length, num_features), dtype=\"float32\")\n\n    for i, batch in enumerate(frames):\n        video_length = batch.shape[0]\n        length = min(max_seq_length, video_length)\n        for j in range(length):\n            frame_features[i, j, :] = feature_extractor.predict(batch[None, j, :])\n        frame_mask[i, :length] = 1  # 1 = not masked, 0 = masked\n\n    return frame_features, frame_mask\n\ndef sequence_prediction(path):\n    frames = load_video(os.path.join(DATA_FOLDER, TEST_FOLDER,path))\n    frame_features, frame_mask = prepare_single_video(frames)\n    return model.predict([frame_features, frame_mask])[0]\n    \n# This utility is for visualization.\n# Referenced from:\n# https://www.tensorflow.org/hub/tutorials/action_recognition_with_tf_hub\ndef to_gif(images):\n    converted_images = images.astype(np.uint8)\n    imageio.mimsave(\"animation.gif\", converted_images, fps=10)\n    return embed.embed_file(\"animation.gif\")\n\n\ntest_video = np.random.choice(test_videos[\"video\"].values.tolist())\nprint(f\"Test video path: {test_video}\")\n\nif(sequence_prediction(test_video)>=0.5):\n    print(f'The predicted class of the video is FAKE')\nelse:\n    print(f'The predicted class of the video is REAL')\n\nplay_video(test_video,TEST_FOLDER)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:25:49.663982Z","iopub.execute_input":"2024-12-07T07:25:49.664284Z","iopub.status.idle":"2024-12-07T07:25:56.135933Z","shell.execute_reply.started":"2024-12-07T07:25:49.664228Z","shell.execute_reply":"2024-12-07T07:25:56.134735Z"}},"outputs":[],"execution_count":null}]}