{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"},{"sourceId":924245,"sourceType":"datasetVersion","datasetId":464091}],"dockerImageVersionId":29844,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\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 read-only \"../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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:18:37.336061Z","iopub.execute_input":"2024-10-19T10:18:37.337233Z","iopub.status.idle":"2024-10-19T10:19:03.282861Z","shell.execute_reply.started":"2024-10-19T10:18:37.337148Z","shell.execute_reply":"2024-10-19T10:19:03.281672Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:27:26.697656Z","iopub.execute_input":"2024-10-19T10:27:26.698215Z","iopub.status.idle":"2024-10-19T10:27:42.132584Z","shell.execute_reply.started":"2024-10-19T10:27:26.698152Z","shell.execute_reply":"2024-10-19T10:27:42.131069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install git+https://github.com/tensorflow/docs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:27:50.074502Z","iopub.execute_input":"2024-10-19T10:27:50.074981Z","iopub.status.idle":"2024-10-19T10:28:09.087663Z","shell.execute_reply.started":"2024-10-19T10:27:50.074936Z","shell.execute_reply":"2024-10-19T10:28:09.08617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow_docs.vis import embed\nfrom tensorflow import keras\n#from imutils import paths\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-10-19T10:28:19.691893Z","iopub.execute_input":"2024-10-19T10:28:19.692348Z","iopub.status.idle":"2024-10-19T10:28:19.699518Z","shell.execute_reply.started":"2024-10-19T10:28:19.692305Z","shell.execute_reply":"2024-10-19T10:28:19.697639Z"}},"outputs":[],"execution_count":null},{"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":"2024-10-19T10:28:24.279479Z","iopub.execute_input":"2024-10-19T10:28:24.279917Z","iopub.status.idle":"2024-10-19T10:28:24.302068Z","shell.execute_reply.started":"2024-10-19T10:28:24.279874Z","shell.execute_reply":"2024-10-19T10:28:24.300696Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_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":"2024-10-19T10:28:44.71881Z","iopub.execute_input":"2024-10-19T10:28:44.719276Z","iopub.status.idle":"2024-10-19T10:28:44.888872Z","shell.execute_reply.started":"2024-10-19T10:28:44.71923Z","shell.execute_reply":"2024-10-19T10:28:44.887619Z"}},"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":"2024-10-19T10:28:52.398151Z","iopub.execute_input":"2024-10-19T10:28:52.399084Z","iopub.status.idle":"2024-10-19T10:28:52.796029Z","shell.execute_reply.started":"2024-10-19T10:28:52.399031Z","shell.execute_reply":"2024-10-19T10:28:52.794396Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:28:57.674726Z","iopub.execute_input":"2024-10-19T10:28:57.675218Z","iopub.status.idle":"2024-10-19T10:28:57.684019Z","shell.execute_reply.started":"2024-10-19T10:28:57.675158Z","shell.execute_reply":"2024-10-19T10:28:57.682483Z"}},"outputs":[],"execution_count":null},{"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":"2024-10-19T10:29:00.599782Z","iopub.execute_input":"2024-10-19T10:29:00.600277Z","iopub.status.idle":"2024-10-19T10:29:00.616246Z","shell.execute_reply.started":"2024-10-19T10:29:00.600229Z","shell.execute_reply":"2024-10-19T10:29:00.614276Z"}},"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":"2024-10-19T10:32:24.925895Z","iopub.execute_input":"2024-10-19T10:32:24.926385Z","iopub.status.idle":"2024-10-19T10:32:24.933727Z","shell.execute_reply.started":"2024-10-19T10:32:24.92634Z","shell.execute_reply":"2024-10-19T10:32:24.932587Z"}},"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":"2024-10-19T10:32:44.083362Z","iopub.execute_input":"2024-10-19T10:32:44.083831Z","iopub.status.idle":"2024-10-19T10:32:47.700042Z","shell.execute_reply.started":"2024-10-19T10:32:44.083778Z","shell.execute_reply":"2024-10-19T10:32:47.698772Z"}},"outputs":[],"execution_count":null},{"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":"2024-10-19T10:33:25.82274Z","iopub.execute_input":"2024-10-19T10:33:25.823897Z","iopub.status.idle":"2024-10-19T10:33:25.836052Z","shell.execute_reply.started":"2024-10-19T10:33:25.823826Z","shell.execute_reply":"2024-10-19T10:33:25.83467Z"}},"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":"2024-10-19T10:33:39.29585Z","iopub.execute_input":"2024-10-19T10:33:39.296336Z","iopub.status.idle":"2024-10-19T10:33:42.249922Z","shell.execute_reply.started":"2024-10-19T10:33:39.296291Z","shell.execute_reply":"2024-10-19T10:33:42.248679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata['original'].value_counts()[0:5]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:34:05.861738Z","iopub.execute_input":"2024-10-19T10:34:05.862859Z","iopub.status.idle":"2024-10-19T10:34:05.877002Z","shell.execute_reply.started":"2024-10-19T10:34:05.862792Z","shell.execute_reply":"2024-10-19T10:34:05.875764Z"}},"outputs":[],"execution_count":null},{"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":"2024-10-19T10:34:22.256077Z","iopub.execute_input":"2024-10-19T10:34:22.256548Z","iopub.status.idle":"2024-10-19T10:34:22.266535Z","shell.execute_reply.started":"2024-10-19T10:34:22.256503Z","shell.execute_reply":"2024-10-19T10:34:22.265202Z"}},"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":"2024-10-19T10:34:39.601928Z","iopub.execute_input":"2024-10-19T10:34:39.603121Z","iopub.status.idle":"2024-10-19T10:34:44.286528Z","shell.execute_reply.started":"2024-10-19T10:34:39.603048Z","shell.execute_reply":"2024-10-19T10:34:44.285269Z"}},"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-10-19T10:38:14.336029Z","iopub.execute_input":"2024-10-19T10:38:14.336508Z","iopub.status.idle":"2024-10-19T10:38:14.343914Z","shell.execute_reply.started":"2024-10-19T10:38:14.336463Z","shell.execute_reply":"2024-10-19T10:38:14.342445Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_videos.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:38:31.531643Z","iopub.execute_input":"2024-10-19T10:38:31.532067Z","iopub.status.idle":"2024-10-19T10:38:31.54352Z","shell.execute_reply.started":"2024-10-19T10:38:31.532025Z","shell.execute_reply":"2024-10-19T10:38:31.54222Z"}},"outputs":[],"execution_count":null},{"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":"2024-10-19T10:38:48.515414Z","iopub.execute_input":"2024-10-19T10:38:48.516018Z","iopub.status.idle":"2024-10-19T10:38:49.613497Z","shell.execute_reply.started":"2024-10-19T10:38:48.51596Z","shell.execute_reply":"2024-10-19T10:38:49.611755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fake_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:41:45.566466Z","iopub.execute_input":"2024-10-19T10:41:45.567664Z","iopub.status.idle":"2024-10-19T10:41:45.574728Z","shell.execute_reply.started":"2024-10-19T10:41:45.567609Z","shell.execute_reply":"2024-10-19T10:41:45.573464Z"}},"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":"2024-10-19T10:41:51.345287Z","iopub.execute_input":"2024-10-19T10:41:51.345704Z","iopub.status.idle":"2024-10-19T10:41:51.709082Z","shell.execute_reply.started":"2024-10-19T10:41:51.345666Z","shell.execute_reply":"2024-10-19T10:41:51.707275Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_SIZE = 224\nBATCH_SIZE = 64\nEPOCHS = 5\n\nMAX_SEQ_LENGTH = 20\nNUM_FEATURES = 2048","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:42:11.677877Z","iopub.execute_input":"2024-10-19T10:42:11.678338Z","iopub.status.idle":"2024-10-19T10:42:11.68455Z","shell.execute_reply.started":"2024-10-19T10:42:11.678294Z","shell.execute_reply":"2024-10-19T10:42:11.683272Z"}},"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\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":"2024-10-19T10:42:23.612626Z","iopub.execute_input":"2024-10-19T10:42:23.613075Z","iopub.status.idle":"2024-10-19T10:42:23.62437Z","shell.execute_reply.started":"2024-10-19T10:42:23.613027Z","shell.execute_reply":"2024-10-19T10:42:23.622625Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def build_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\n\nfeature_extractor = build_feature_extractor()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:42:29.501375Z","iopub.execute_input":"2024-10-19T10:42:29.501836Z","iopub.status.idle":"2024-10-19T10:42:33.065485Z","shell.execute_reply.started":"2024-10-19T10:42:29.501785Z","shell.execute_reply":"2024-10-19T10:42:33.064272Z"}},"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(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":"2024-10-19T10:45:17.922877Z","iopub.execute_input":"2024-10-19T10:45:17.923481Z","iopub.status.idle":"2024-10-19T10:45:17.940532Z","shell.execute_reply.started":"2024-10-19T10:45:17.92342Z","shell.execute_reply":"2024-10-19T10:45:17.938992Z"}},"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,stratify=train_sample_metadata['label'])\n\nprint(Train_set.shape, Test_set.shape )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:45:25.601207Z","iopub.execute_input":"2024-10-19T10:45:25.601637Z","iopub.status.idle":"2024-10-19T10:45:25.614274Z","shell.execute_reply.started":"2024-10-19T10:45:25.601597Z","shell.execute_reply":"2024-10-19T10:45:25.612927Z"}},"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-10-19T10:45:28.814072Z","iopub.execute_input":"2024-10-19T10:45:28.814589Z","iopub.status.idle":"2024-10-19T10:45:28.973435Z","shell.execute_reply.started":"2024-10-19T10:45:28.814544Z","shell.execute_reply":"2024-10-19T10:45:28.97191Z"}},"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\n# Refer to the following tutorial to understand the significance of using `mask`:\n# https://keras.io/api/layers/recurrent_layers/gru/\nx = keras.layers.GRU(16, return_sequences=True)(\n    frame_features_input, mask=mask_input\n)\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)\n\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T10:45:34.463793Z","iopub.execute_input":"2024-10-19T10:45:34.464877Z","iopub.status.idle":"2024-10-19T10:45:34.598663Z","shell.execute_reply.started":"2024-10-19T10:45:34.464823Z","shell.execute_reply":"2024-10-19T10:45:34.5974Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"checkpoint = keras.callbacks.ModelCheckpoint('.weights.h5', 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-10-19T10:46:46.106944Z","iopub.execute_input":"2024-10-19T10:46:46.107442Z","iopub.status.idle":"2024-10-19T10:46:54.989013Z","shell.execute_reply.started":"2024-10-19T10:46:46.107396Z","shell.execute_reply":"2024-10-19T10:46:54.987751Z"}},"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-10-19T10:48:57.651521Z","iopub.execute_input":"2024-10-19T10:48:57.652574Z","iopub.status.idle":"2024-10-19T10:49:03.745679Z","shell.execute_reply.started":"2024-10-19T10:48:57.652524Z","shell.execute_reply":"2024-10-19T10:49:03.743614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}