{"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":"2025-04-03T10:29:50.193779Z","iopub.execute_input":"2025-04-03T10:29:50.194054Z","iopub.status.idle":"2025-04-03T10:29:55.362687Z","shell.execute_reply.started":"2025-04-03T10:29:50.194013Z","shell.execute_reply":"2025-04-03T10:29:55.361635Z"}},"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":"2025-04-03T10:29:55.364895Z","iopub.execute_input":"2025-04-03T10:29:55.365217Z","iopub.status.idle":"2025-04-03T10:29:55.370696Z","shell.execute_reply.started":"2025-04-03T10:29:55.365156Z","shell.execute_reply":"2025-04-03T10:29:55.369944Z"}},"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":"2025-04-03T10:29:55.372257Z","iopub.execute_input":"2025-04-03T10:29:55.372558Z","iopub.status.idle":"2025-04-03T10:29:55.386601Z","shell.execute_reply.started":"2025-04-03T10:29:55.372504Z","shell.execute_reply":"2025-04-03T10:29:55.386016Z"}},"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.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-03T10:29:55.387744Z","iopub.execute_input":"2025-04-03T10:29:55.387923Z","iopub.status.idle":"2025-04-03T10:29:55.510313Z","shell.execute_reply.started":"2025-04-03T10:29:55.387890Z","shell.execute_reply":"2025-04-03T10:29:55.509620Z"}},"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":"2025-04-03T10:29:55.513610Z","iopub.execute_input":"2025-04-03T10:29:55.513909Z","iopub.status.idle":"2025-04-03T10:29:55.725856Z","shell.execute_reply.started":"2025-04-03T10:29:55.513854Z","shell.execute_reply":"2025-04-03T10:29:55.724698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-03T10:29:55.729281Z","iopub.execute_input":"2025-04-03T10:29:55.730232Z","iopub.status.idle":"2025-04-03T10:29:55.737653Z","shell.execute_reply.started":"2025-04-03T10:29:55.730160Z","shell.execute_reply":"2025-04-03T10:29:55.736644Z"}},"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":"2025-04-03T10:29:55.739764Z","iopub.execute_input":"2025-04-03T10:29:55.740159Z","iopub.status.idle":"2025-04-03T10:29:55.757279Z","shell.execute_reply.started":"2025-04-03T10:29:55.740100Z","shell.execute_reply":"2025-04-03T10:29:55.755988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def capture_image_from_video(video_path):\n    capture_image = cv2.VideoCapture(video_path)\n    \n    # Check if the video was successfully opened\n    if not capture_image.isOpened():\n        print(f\"Error: Could not open video {video_path}\")\n        return\n    \n    # Read the first frame\n    ret, frame = capture_image.read()\n    \n    # Check if frame is read correctly\n    if not ret:\n        print(f\"Error: Could not read frame from {video_path}\")\n        return\n    \n    # Convert the frame from BGR to RGB (OpenCV uses BGR by default)\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    \n    # Display the image using Matplotlib\n    plt.figure(figsize=(4, 4))\n    plt.imshow(frame)\n    plt.axis('off')  # Hide axes for a cleaner view\n    plt.show()\n\n    # Release the video capture object\n    capture_image.release()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-03T10:32:38.523412Z","iopub.execute_input":"2025-04-03T10:32:38.523729Z","iopub.status.idle":"2025-04-03T10:32:38.529768Z","shell.execute_reply.started":"2025-04-03T10:32:38.523683Z","shell.execute_reply":"2025-04-03T10:32:38.528819Z"}},"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":"2025-04-03T10:32:45.647740Z","iopub.execute_input":"2025-04-03T10:32:45.648047Z","iopub.status.idle":"2025-04-03T10:32:46.827179Z","shell.execute_reply.started":"2025-04-03T10:32:45.647985Z","shell.execute_reply":"2025-04-03T10:32:46.826304Z"}},"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":"2025-04-03T10:32:55.112186Z","iopub.execute_input":"2025-04-03T10:32:55.112442Z","iopub.status.idle":"2025-04-03T10:32:55.119322Z","shell.execute_reply.started":"2025-04-03T10:32:55.112404Z","shell.execute_reply":"2025-04-03T10:32:55.118674Z"}},"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":"2025-04-03T10:32:58.792662Z","iopub.execute_input":"2025-04-03T10:32:58.792917Z","iopub.status.idle":"2025-04-03T10:33:00.081179Z","shell.execute_reply.started":"2025-04-03T10:32:58.792879Z","shell.execute_reply":"2025-04-03T10:33:00.079813Z"}},"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":"2025-04-03T10:33:04.087611Z","iopub.execute_input":"2025-04-03T10:33:04.087988Z","iopub.status.idle":"2025-04-03T10:33:04.093279Z","shell.execute_reply.started":"2025-04-03T10:33:04.087916Z","shell.execute_reply":"2025-04-03T10:33:04.092445Z"}},"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":"2025-04-03T10:33:08.646972Z","iopub.execute_input":"2025-04-03T10:33:08.647231Z","iopub.status.idle":"2025-04-03T10:33:08.767916Z","shell.execute_reply.started":"2025-04-03T10:33:08.647193Z","shell.execute_reply":"2025-04-03T10:33:08.766659Z"}},"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":"2025-04-03T10:33:30.872620Z","iopub.execute_input":"2025-04-03T10:33:30.872877Z","iopub.status.idle":"2025-04-03T10:33:30.876904Z","shell.execute_reply.started":"2025-04-03T10:33:30.872840Z","shell.execute_reply":"2025-04-03T10:33:30.876009Z"}},"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":"2025-04-03T10:33:37.188288Z","iopub.execute_input":"2025-04-03T10:33:37.188600Z","iopub.status.idle":"2025-04-03T10:33:37.196551Z","shell.execute_reply.started":"2025-04-03T10:33:37.188549Z","shell.execute_reply":"2025-04-03T10:33:37.195389Z"}},"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":"2025-04-03T10:33:45.438250Z","iopub.execute_input":"2025-04-03T10:33:45.438576Z","iopub.status.idle":"2025-04-03T10:33:51.794516Z","shell.execute_reply.started":"2025-04-03T10:33:45.438518Z","shell.execute_reply":"2025-04-03T10:33:51.793792Z"}},"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":"2025-04-03T10:34:03.048440Z","iopub.execute_input":"2025-04-03T10:34:03.048806Z","iopub.status.idle":"2025-04-03T10:34:03.058282Z","shell.execute_reply.started":"2025-04-03T10:34:03.048746Z","shell.execute_reply":"2025-04-03T10:34:03.057346Z"}},"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":"2025-04-03T10:34:11.353731Z","iopub.execute_input":"2025-04-03T10:34:11.354007Z","iopub.status.idle":"2025-04-03T10:34:12.049807Z","shell.execute_reply.started":"2025-04-03T10:34:11.353968Z","shell.execute_reply":"2025-04-03T10:34:12.048973Z"}},"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":"2025-04-03T10:34:14.712090Z","iopub.execute_input":"2025-04-03T10:34:14.712353Z","iopub.status.idle":"2025-04-03T10:34:14.801145Z","shell.execute_reply.started":"2025-04-03T10:34:14.712313Z","shell.execute_reply":"2025-04-03T10:34:14.800415Z"}},"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":"2025-04-03T10:34:19.712057Z","iopub.execute_input":"2025-04-03T10:34:19.712325Z","iopub.status.idle":"2025-04-03T10:34:21.022360Z","shell.execute_reply.started":"2025-04-03T10:34:19.712286Z","shell.execute_reply":"2025-04-03T10:34:21.021697Z"}},"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":"2025-04-03T10:34:30.233241Z","iopub.execute_input":"2025-04-03T10:34:30.233517Z","iopub.status.idle":"2025-04-03T10:34:47.318515Z","shell.execute_reply.started":"2025-04-03T10:34:30.233465Z","shell.execute_reply":"2025-04-03T10:34:47.317844Z"}},"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":"2025-04-03T10:34:51.357078Z","iopub.execute_input":"2025-04-03T10:34:51.357338Z","iopub.status.idle":"2025-04-03T10:34:51.363758Z","shell.execute_reply.started":"2025-04-03T10:34:51.357297Z","shell.execute_reply":"2025-04-03T10:34:51.362988Z"}},"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":"2025-04-03T10:35:00.928901Z","iopub.execute_input":"2025-04-03T10:35:00.929183Z","iopub.status.idle":"2025-04-03T10:35:07.861773Z","shell.execute_reply.started":"2025-04-03T10:35:00.929143Z","shell.execute_reply":"2025-04-03T10:35:07.860456Z"}},"outputs":[],"execution_count":null}]}