{"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":"gpu","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":"markdown","source":"# Title","metadata":{"id":"Q6tasuafvT2O"}},{"cell_type":"markdown","source":"Deep Video Detection using CNN's and RNN's","metadata":{"id":"LvJBeHv3vfE_"}},{"cell_type":"markdown","source":"## About the dataset","metadata":{}},{"cell_type":"markdown","source":"Files\n\n* train_sample_videos.zip - a ZIP file containing a sample set of training videos and a metadata.json with labels. the full set of training videos is available through the links provided above.\n* sample_submission.csv - a sample submission file in the correct format.\n* test_videos.zip - a zip file containing a small set of videos to be used as a public validation set. To understand the datasets available for this competition, review the Getting Started information.\n\nMetadata Columns\n\n* filename - the filename of the video\n* label - whether the video is REAL or FAKE\n* original - in the case that a train set video is FAKE, the original video is listed here\n* split - this is always equal to \"train\".","metadata":{}},{"cell_type":"markdown","source":"## Importing required libraries","metadata":{}},{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:07:09.274284Z","iopub.execute_input":"2025-03-05T13:07:09.274579Z","iopub.status.idle":"2025-03-05T13:08:31.027720Z","shell.execute_reply.started":"2025-03-05T13:07:09.274526Z","shell.execute_reply":"2025-03-05T13:08:31.027063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:31.029925Z","iopub.execute_input":"2025-03-05T13:08:31.030265Z","iopub.status.idle":"2025-03-05T13:08:31.034153Z","shell.execute_reply.started":"2025-03-05T13:08:31.030211Z","shell.execute_reply":"2025-03-05T13:08:31.033454Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport imageio\nimport cv2\nimport os\n\nprint(\"All modules imported successfully!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:31.035547Z","iopub.execute_input":"2025-03-05T13:08:31.035817Z","iopub.status.idle":"2025-03-05T13:08:34.187146Z","shell.execute_reply.started":"2025-03-05T13:08:31.035769Z","shell.execute_reply":"2025-03-05T13:08:34.186261Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Data Visualisation","metadata":{}},{"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)))}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:34.188474Z","iopub.execute_input":"2025-03-05T13:08:34.188765Z","iopub.status.idle":"2025-03-05T13:08:34.233394Z","shell.execute_reply.started":"2025-03-05T13:08:34.188703Z","shell.execute_reply":"2025-03-05T13:08:34.232308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\ntrain_sample_metadata = pd.read_json('../input/deepfake-detection-challenge/train_sample_videos/metadata.json').T\ntrain_sample_metadata.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:34.235264Z","iopub.execute_input":"2025-03-05T13:08:34.235584Z","iopub.status.idle":"2025-03-05T13:08:37.618677Z","shell.execute_reply.started":"2025-03-05T13:08:34.235534Z","shell.execute_reply":"2025-03-05T13:08:37.617978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.groupby('label')['label'].count().plot(figsize=(15, 5), kind='bar', title='Distribution of Labels in the Training Set')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:37.621383Z","iopub.execute_input":"2025-03-05T13:08:37.621629Z","iopub.status.idle":"2025-03-05T13:08:38.730643Z","shell.execute_reply.started":"2025-03-05T13:08:37.621583Z","shell.execute_reply":"2025-03-05T13:08:38.729609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:38.737971Z","iopub.execute_input":"2025-03-05T13:08:38.738689Z","iopub.status.idle":"2025-03-05T13:08:38.793519Z","shell.execute_reply.started":"2025-03-05T13:08:38.738613Z","shell.execute_reply":"2025-03-05T13:08:38.792335Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Let's visualize now the data.\n\nWe select first a list of fake videos.","metadata":{}},{"cell_type":"markdown","source":"### Few fake videos","metadata":{}},{"cell_type":"code","source":"fake_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].sample(3).index)\nfake_train_sample_video","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:38.794671Z","iopub.execute_input":"2025-03-05T13:08:38.794916Z","iopub.status.idle":"2025-03-05T13:08:38.805196Z","shell.execute_reply.started":"2025-03-05T13:08:38.794876Z","shell.execute_reply":"2025-03-05T13:08:38.804563Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_image_from_video(video_path):\n    '''\n    input: video_path - path for video\n    process:\n    1. perform a video capture from the video\n    2. read the image\n    3. display the image\n    '''\n    capture_image = cv2.VideoCapture(video_path) \n    ret, frame = capture_image.read()\n    fig = plt.figure(figsize=(10,10))\n    ax = fig.add_subplot(111)\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    ax.imshow(frame)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:38.806206Z","iopub.execute_input":"2025-03-05T13:08:38.806422Z","iopub.status.idle":"2025-03-05T13:08:38.817755Z","shell.execute_reply.started":"2025-03-05T13:08:38.806377Z","shell.execute_reply":"2025-03-05T13:08:38.817224Z"}},"outputs":[],"execution_count":null},{"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:38.818779Z","iopub.execute_input":"2025-03-05T13:08:38.818954Z","iopub.status.idle":"2025-03-05T13:08:40.685368Z","shell.execute_reply.started":"2025-03-05T13:08:38.818922Z","shell.execute_reply":"2025-03-05T13:08:40.684653Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Let's try now the same for few of the images that are real.","metadata":{}},{"cell_type":"markdown","source":"### Few Real Videos","metadata":{}},{"cell_type":"code","source":"real_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='REAL'].sample(3).index)\nreal_train_sample_video","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:40.686571Z","iopub.execute_input":"2025-03-05T13:08:40.686826Z","iopub.status.idle":"2025-03-05T13:08:40.693724Z","shell.execute_reply.started":"2025-03-05T13:08:40.686777Z","shell.execute_reply":"2025-03-05T13:08:40.692765Z"}},"outputs":[],"execution_count":null},{"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:40.694959Z","iopub.execute_input":"2025-03-05T13:08:40.695264Z","iopub.status.idle":"2025-03-05T13:08:41.818993Z","shell.execute_reply.started":"2025-03-05T13:08:40.695208Z","shell.execute_reply":"2025-03-05T13:08:41.818157Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Videos with same original","metadata":{}},{"cell_type":"markdown","source":"Let's look now to set of samples with the same original.","metadata":{}},{"cell_type":"code","source":"train_sample_metadata['original'].value_counts()[0:5]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:41.820176Z","iopub.execute_input":"2025-03-05T13:08:41.820442Z","iopub.status.idle":"2025-03-05T13:08:41.830053Z","shell.execute_reply.started":"2025-03-05T13:08:41.820401Z","shell.execute_reply":"2025-03-05T13:08:41.829316Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We pick one of the originals with largest number of samples.\n\nWe also modify our visualization function to work with multiple images.","metadata":{}},{"cell_type":"code","source":"def display_image_from_video_list(video_path_list, video_folder=TRAIN_SAMPLE_FOLDER):\n    '''\n    input: video_path_list - path for video\n    process:\n    0. for each video in the video path list\n        1. perform a video capture from the video\n        2. read the image\n        3. display the image\n    '''\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 = cv2.VideoCapture(video_path) \n        ret, frame = capture_image.read()\n        frame = cv2.cvtColor(frame, cv2.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')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:41.831203Z","iopub.execute_input":"2025-03-05T13:08:41.831758Z","iopub.status.idle":"2025-03-05T13:08:41.843987Z","shell.execute_reply.started":"2025-03-05T13:08:41.831708Z","shell.execute_reply":"2025-03-05T13:08:41.843242Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"same_original_fake_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.original=='atvmxvwyns.mp4'].index)\ndisplay_image_from_video_list(same_original_fake_train_sample_video)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:41.845406Z","iopub.execute_input":"2025-03-05T13:08:41.845681Z","iopub.status.idle":"2025-03-05T13:08:43.665732Z","shell.execute_reply.started":"2025-03-05T13:08:41.845636Z","shell.execute_reply":"2025-03-05T13:08:43.665121Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Test video files","metadata":{}},{"cell_type":"markdown","source":"Let's also look to few of the test data files.","metadata":{}},{"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-03-05T13:08:43.666824Z","iopub.execute_input":"2025-03-05T13:08:43.667036Z","iopub.status.idle":"2025-03-05T13:08:43.672412Z","shell.execute_reply.started":"2025-03-05T13:08:43.666988Z","shell.execute_reply":"2025-03-05T13:08:43.671738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_videos.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:43.673917Z","iopub.execute_input":"2025-03-05T13:08:43.674402Z","iopub.status.idle":"2025-03-05T13:08:43.688008Z","shell.execute_reply.started":"2025-03-05T13:08:43.674208Z","shell.execute_reply":"2025-03-05T13:08:43.687353Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Let's visualize now one of the videos.","metadata":{}},{"cell_type":"code","source":"display_image_from_video(os.path.join(DATA_FOLDER, TEST_FOLDER, test_videos.iloc[2].video))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:43.689355Z","iopub.execute_input":"2025-03-05T13:08:43.689627Z","iopub.status.idle":"2025-03-05T13:08:44.203326Z","shell.execute_reply.started":"2025-03-05T13:08:43.689575Z","shell.execute_reply":"2025-03-05T13:08:44.202615Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Play video files","metadata":{}},{"cell_type":"markdown","source":"Let's look to few fake videos.","metadata":{}},{"cell_type":"code","source":"fake_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:44.204785Z","iopub.execute_input":"2025-03-05T13:08:44.205305Z","iopub.status.idle":"2025-03-05T13:08:44.211084Z","shell.execute_reply.started":"2025-03-05T13:08:44.205134Z","shell.execute_reply":"2025-03-05T13:08:44.210168Z"}},"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    '''\n    Display video\n    param: video_file - the name of the video file to display\n    param: subset - the folder where the video file is located (can be TRAIN_SAMPLE_FOLDER or TEST_Folder)\n    '''\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)\n\nplay_video(fake_videos[10])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:44.212216Z","iopub.execute_input":"2025-03-05T13:08:44.212463Z","iopub.status.idle":"2025-03-05T13:08:44.610793Z","shell.execute_reply.started":"2025-03-05T13:08:44.212419Z","shell.execute_reply":"2025-03-05T13:08:44.609474Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"From visual inspection of these fakes videos, in some cases is very easy to spot the anomalies created when engineering the deep fake, in some cases is more difficult.","metadata":{}},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"cell_type":"markdown","source":"### A CNN-RNN Architecture","metadata":{}},{"cell_type":"code","source":"IMG_SIZE = 224\nBATCH_SIZE = 32\nEPOCHS = 10\n\nMAX_SEQ_LENGTH = 20\nNUM_FEATURES = 2048","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:08:44.612493Z","iopub.execute_input":"2025-03-05T13:08:44.612863Z","iopub.status.idle":"2025-03-05T13:08:44.618523Z","shell.execute_reply.started":"2025-03-05T13:08:44.612801Z","shell.execute_reply":"2025-03-05T13:08:44.617653Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" In this example we will do the following:\n\n* Capture the frames of a video.\n* Extract frames from the videos until a maximum frame count is reached.\n* In the case, where a video's frame count is lesser than the maximum frame count we will pad the video with zeros.","metadata":{}},{"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\n\ndef load_video(path, max_frames=0, resize=(IMG_SIZE, IMG_SIZE)):\n    cap = cv2.VideoCapture(path)\n    frames = []\n    try:\n        while True:\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-03-05T13:08:44.620096Z","iopub.execute_input":"2025-03-05T13:08:44.620432Z","iopub.status.idle":"2025-03-05T13:08:44.641772Z","shell.execute_reply.started":"2025-03-05T13:08:44.620368Z","shell.execute_reply":"2025-03-05T13:08:44.641096Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We can use a pre-trained network to extract meaningful features from the extracted frames. The Keras Applications module provides a number of state-of-the-art models pre-trained on the ImageNet-1k dataset. We will be using the InceptionV3 model for this purpose.","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import applications\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model\n\nIMG_SIZE = 224  # Set the image size\n\ndef build_feature_extractor():\n    feature_extractor = applications.InceptionV3(\n        weights=\"imagenet\",\n        include_top=False,\n        pooling=\"avg\",\n        input_shape=(IMG_SIZE, IMG_SIZE, 3),\n    )\n    \n    preprocess_input = applications.inception_v3.preprocess_input\n\n    inputs = layers.Input((IMG_SIZE, IMG_SIZE, 3))\n    preprocessed = preprocess_input(inputs)\n\n    outputs = feature_extractor(preprocessed)\n    return Model(inputs, outputs, name=\"feature_extractor\")\n\n# Build the feature extractor\nfeature_extractor = build_feature_extractor()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:10:02.028513Z","iopub.execute_input":"2025-03-05T13:10:02.028820Z","iopub.status.idle":"2025-03-05T13:10:05.265462Z","shell.execute_reply.started":"2025-03-05T13:10:02.028770Z","shell.execute_reply":"2025-03-05T13:10:05.264853Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Finally, we can put all the pieces together to create our data processing utility.","metadata":{}},{"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` and `frame_features` are what we will feed to our sequence model.\n    # `frame_masks` will contain a bunch of booleans denoting if a timestep is\n    # masked with padding or not.\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 each video.\n    for idx, path in enumerate(video_paths):\n        # Gather all its frames and add a batch dimension.\n        frames = load_video(os.path.join(root_dir, path))\n        frames = frames[None, ...]\n\n        # Initialize placeholders to store the masks and features of the current video.\n        temp_frame_mask = np.zeros(shape=(1, MAX_SEQ_LENGTH,), dtype=\"bool\")\n        temp_frame_features = np.zeros(\n            shape=(1, MAX_SEQ_LENGTH, NUM_FEATURES), dtype=\"float32\"\n        )\n\n        # Extract features from the frames of the current video.\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                temp_frame_features[i, j, :] = feature_extractor.predict(\n                    batch[None, j, :]\n                )\n            temp_frame_mask[i, :length] = 1  # 1 = not masked, 0 = masked\n\n        frame_features[idx,] = temp_frame_features.squeeze()\n        frame_masks[idx,] = temp_frame_mask.squeeze()\n\n    return (frame_features, frame_masks), labels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:10:10.102466Z","iopub.execute_input":"2025-03-05T13:10:10.102794Z","iopub.status.idle":"2025-03-05T13:10:10.112422Z","shell.execute_reply.started":"2025-03-05T13:10:10.102734Z","shell.execute_reply":"2025-03-05T13:10:10.111558Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Since we don't have test labels we split the training data to find its performance in unseen data","metadata":{}},{"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,stratify=train_sample_metadata['label'])\n\nprint(Train_set.shape, Test_set.shape )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:10:15.347629Z","iopub.execute_input":"2025-03-05T13:10:15.347945Z","iopub.status.idle":"2025-03-05T13:10:16.119910Z","shell.execute_reply.started":"2025-03-05T13:10:15.347890Z","shell.execute_reply":"2025-03-05T13:10:16.119269Z"}},"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-03-05T13:10:17.262819Z","iopub.execute_input":"2025-03-05T13:10:17.263085Z","iopub.status.idle":"2025-03-05T13:10:17.354555Z","shell.execute_reply.started":"2025-03-05T13:10:17.263047Z","shell.execute_reply":"2025-03-05T13:10:17.353694Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## The sequence model","metadata":{}},{"cell_type":"markdown","source":"Now, we can feed this data to a sequence model consisting of recurrent layers like GRU.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\n\n# Define input layers\nframe_features_input = keras.Input((MAX_SEQ_LENGTH, NUM_FEATURES))\nmask_input = keras.Input((MAX_SEQ_LENGTH,), dtype=\"bool\")\n\n# Define GRU layers with Batch Normalization\nx = keras.layers.GRU(64, return_sequences=True)(frame_features_input, mask=mask_input)\nx = keras.layers.BatchNormalization()(x)\nx = keras.layers.GRU(32, return_sequences=True)(x)\nx = keras.layers.BatchNormalization()(x)\nx = keras.layers.GRU(16)(x)\nx = keras.layers.Dropout(0.5)(x)\n\n# Fully connected layers\nx = keras.layers.Dense(32, activation=\"relu\")(x)\nx = keras.layers.Dropout(0.5)(x)\noutput = keras.layers.Dense(1, activation=\"sigmoid\")(x)\n\n# Create and compile the model\nmodel = keras.Model([frame_features_input, mask_input], output)\noptimizer = keras.optimizers.Adam(learning_rate=1e-4)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])\nmodel.summary()\n\n# Define callbacks\nearly_stopping = keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=5, restore_best_weights=True)\ncheckpoint = keras.callbacks.ModelCheckpoint(\"./\", save_weights_only=True, save_best_only=True)\n\n# Train the model\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, early_stopping],\n    epochs=EPOCHS,\n    batch_size=16\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:10:25.002744Z","iopub.execute_input":"2025-03-05T13:10:25.003057Z","iopub.status.idle":"2025-03-05T13:10:50.404174Z","shell.execute_reply.started":"2025-03-05T13:10:25.002996Z","shell.execute_reply":"2025-03-05T13:10:50.403453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"video.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:14:21.822374Z","iopub.execute_input":"2025-03-05T13:14:21.822667Z","iopub.status.idle":"2025-03-05T13:14:21.869450Z","shell.execute_reply.started":"2025-03-05T13:14:21.822627Z","shell.execute_reply":"2025-03-05T13:14:21.868876Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Inference","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\naccuracy = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs =range(1, len(accuracy)+1)\n\nplt.figure(figsize=(14,5))\n\nplt.subplot()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-05T13:10:54.781985Z","iopub.execute_input":"2025-03-05T13:10:54.782256Z","iopub.status.idle":"2025-03-05T13:10:55.056340Z","shell.execute_reply.started":"2025-03-05T13:10:54.782224Z","shell.execute_reply":"2025-03-05T13:10:55.055165Z"}},"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-03-05T13:11:00.942961Z","iopub.execute_input":"2025-03-05T13:11:00.943233Z","iopub.status.idle":"2025-03-05T13:11:08.847608Z","shell.execute_reply.started":"2025-03-05T13:11:00.943194Z","shell.execute_reply":"2025-03-05T13:11:08.846290Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Here we used simple RNN model feel free to try some complex Attention based and Transformer based models","metadata":{}},{"cell_type":"markdown","source":"# Conclusion","metadata":{}},{"cell_type":"markdown","source":"The deep  deep fake video classifier model gave a generalisation error of around 80%","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}