{"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":"none","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"}],"dockerImageVersionId":29844,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-03-16T16:02:23.833535Z","iopub.execute_input":"2025-03-16T16:02:23.833767Z","iopub.status.idle":"2025-03-16T16:04:01.035986Z","shell.execute_reply.started":"2025-03-16T16:02:23.833722Z","shell.execute_reply":"2025-03-16T16:04:01.034914Z"}},"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-03-16T16:04:06.100349Z","iopub.execute_input":"2025-03-16T16:04:06.100737Z","iopub.status.idle":"2025-03-16T16:04:10.815658Z","shell.execute_reply.started":"2025-03-16T16:04:06.100654Z","shell.execute_reply":"2025-03-16T16:04:10.814419Z"}},"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-03-16T16:04:22.412434Z","iopub.execute_input":"2025-03-16T16:04:22.414011Z","iopub.status.idle":"2025-03-16T16:04:22.467709Z","shell.execute_reply.started":"2025-03-16T16:04:22.413838Z","shell.execute_reply":"2025-03-16T16:04:22.465225Z"}},"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-03-16T16:04:33.468175Z","iopub.execute_input":"2025-03-16T16:04:33.468532Z","iopub.status.idle":"2025-03-16T16:04:33.821297Z","shell.execute_reply.started":"2025-03-16T16:04:33.468483Z","shell.execute_reply":"2025-03-16T16:04:33.820179Z"}},"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-03-16T16:04:43.392600Z","iopub.execute_input":"2025-03-16T16:04:43.393007Z","iopub.status.idle":"2025-03-16T16:04:43.655645Z","shell.execute_reply.started":"2025-03-16T16:04:43.392941Z","shell.execute_reply":"2025-03-16T16:04:43.654500Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-16T16:04:53.743552Z","iopub.execute_input":"2025-03-16T16:04:53.743929Z","iopub.status.idle":"2025-03-16T16:04:53.751172Z","shell.execute_reply.started":"2025-03-16T16:04:53.743865Z","shell.execute_reply":"2025-03-16T16:04:53.749901Z"}},"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-03-16T16:05:28.682903Z","iopub.execute_input":"2025-03-16T16:05:28.683231Z","iopub.status.idle":"2025-03-16T16:05:28.692628Z","shell.execute_reply.started":"2025-03-16T16:05:28.683183Z","shell.execute_reply":"2025-03-16T16:05:28.691353Z"}},"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":"2025-03-16T16:05:30.775653Z","iopub.execute_input":"2025-03-16T16:05:30.776006Z","iopub.status.idle":"2025-03-16T16:05:30.783221Z","shell.execute_reply.started":"2025-03-16T16:05:30.775953Z","shell.execute_reply":"2025-03-16T16:05:30.781999Z"}},"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-03-16T16:05:41.119101Z","iopub.execute_input":"2025-03-16T16:05:41.119464Z","iopub.status.idle":"2025-03-16T16:05:43.002812Z","shell.execute_reply.started":"2025-03-16T16:05:41.119404Z","shell.execute_reply":"2025-03-16T16:05:43.001965Z"}},"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-03-16T16:05:53.033182Z","iopub.execute_input":"2025-03-16T16:05:53.033528Z","iopub.status.idle":"2025-03-16T16:05:53.043202Z","shell.execute_reply.started":"2025-03-16T16:05:53.033472Z","shell.execute_reply":"2025-03-16T16:05:53.042009Z"}},"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-03-16T16:06:02.267291Z","iopub.execute_input":"2025-03-16T16:06:02.267599Z","iopub.status.idle":"2025-03-16T16:06:04.270776Z","shell.execute_reply.started":"2025-03-16T16:06:02.267544Z","shell.execute_reply":"2025-03-16T16:06:04.269709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)\nfrom 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-03-16T16:06:16.367942Z","iopub.execute_input":"2025-03-16T16:06:16.368286Z","iopub.status.idle":"2025-03-16T16:06:16.489031Z","shell.execute_reply.started":"2025-03-16T16:06:16.368233Z","shell.execute_reply":"2025-03-16T16:06:16.488178Z"}},"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-03-16T16:06:55.936389Z","iopub.execute_input":"2025-03-16T16:06:55.936789Z","iopub.status.idle":"2025-03-16T16:06:55.942126Z","shell.execute_reply.started":"2025-03-16T16:06:55.936725Z","shell.execute_reply":"2025-03-16T16:06:55.940725Z"}},"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-03-16T16:07:09.730205Z","iopub.execute_input":"2025-03-16T16:07:09.730551Z","iopub.status.idle":"2025-03-16T16:07:09.740305Z","shell.execute_reply.started":"2025-03-16T16:07:09.730503Z","shell.execute_reply":"2025-03-16T16:07:09.739252Z"}},"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-03-16T16:07:20.753701Z","iopub.execute_input":"2025-03-16T16:07:20.754069Z","iopub.status.idle":"2025-03-16T16:07:24.981834Z","shell.execute_reply.started":"2025-03-16T16:07:20.754016Z","shell.execute_reply":"2025-03-16T16:07:24.980773Z"}},"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-03-16T16:07:34.717735Z","iopub.execute_input":"2025-03-16T16:07:34.718058Z","iopub.status.idle":"2025-03-16T16:07:34.730027Z","shell.execute_reply.started":"2025-03-16T16:07:34.718009Z","shell.execute_reply":"2025-03-16T16:07:34.728319Z"}},"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.3,random_state=42,\n                                       stratify=train_sample_metadata['label'])\nprint(Train_set.shape, Test_set.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-16T16:07:55.451647Z","iopub.execute_input":"2025-03-16T16:07:55.451997Z","iopub.status.idle":"2025-03-16T16:07:55.468474Z","shell.execute_reply.started":"2025-03-16T16:07:55.451942Z","shell.execute_reply":"2025-03-16T16:07:55.467480Z"}},"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-16T16:07:57.627442Z","iopub.execute_input":"2025-03-16T16:07:57.627782Z","iopub.status.idle":"2025-03-16T16:07:57.814402Z","shell.execute_reply.started":"2025-03-16T16:07:57.627726Z","shell.execute_reply":"2025-03-16T16:07:57.813515Z"}},"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-03-16T16:08:07.600544Z","iopub.execute_input":"2025-03-16T16:08:07.600882Z","iopub.status.idle":"2025-03-16T16:08:09.481868Z","shell.execute_reply.started":"2025-03-16T16:08:07.600828Z","shell.execute_reply":"2025-03-16T16:08:09.480601Z"}},"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-03-16T16:08:21.322291Z","iopub.execute_input":"2025-03-16T16:08:21.322603Z","iopub.status.idle":"2025-03-16T16:08:44.151037Z","shell.execute_reply.started":"2025-03-16T16:08:21.322555Z","shell.execute_reply":"2025-03-16T16:08:44.149862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"/kaggle/working/fake_video_detection_model.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-16T16:10:36.073248Z","iopub.execute_input":"2025-03-16T16:10:36.073624Z","iopub.status.idle":"2025-03-16T16:10:36.114654Z","shell.execute_reply.started":"2025-03-16T16:10:36.073571Z","shell.execute_reply":"2025-03-16T16:10:36.113576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"/kaggle/working\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-16T16:10:57.448349Z","iopub.execute_input":"2025-03-16T16:10:57.448770Z","iopub.status.idle":"2025-03-16T16:10:57.455949Z","shell.execute_reply.started":"2025-03-16T16:10:57.448706Z","shell.execute_reply":"2025-03-16T16:10:57.454728Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])\ndef 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-16T16:12:18.987698Z","iopub.execute_input":"2025-03-16T16:12:18.988062Z","iopub.status.idle":"2025-03-16T16:12:24.386204Z","shell.execute_reply.started":"2025-03-16T16:12:18.988010Z","shell.execute_reply":"2025-03-16T16:12:24.385029Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport os\nimport cv2\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom IPython.display import HTML\nimport base64\n\n# Load the trained model\nmodel = keras.models.load_model(\"/kaggle/working/fake_video_detection_model.h5\")\n\n# Define constants\nmax_seq_length = 20  # Should be the same as in training\nnum_features = 2048   # Adjust according to feature extractor\n\n# Load the feature extractor (same one used in training)\nfeature_extractor = keras.applications.InceptionV3(include_top=False, pooling=\"avg\", input_shape=(224, 224, 3))\n\ndef load_video(video_path, max_frames=max_seq_length, frame_size=(224, 224)):\n    \"\"\"Loads video frames and resizes them to the required shape.\"\"\"\n    cap = cv2.VideoCapture(video_path)\n    frames = []\n    frame_count = 0\n\n    while cap.isOpened():\n        ret, frame = cap.read()\n        if not ret or frame_count >= max_frames:\n            break\n        frame = cv2.resize(frame, frame_size)  # Resize to match feature extractor\n        frame = frame / 255.0  # Normalize\n        frames.append(frame)\n        frame_count += 1\n\n    cap.release()\n    \n    if len(frames) < max_frames:\n        # Pad with zeros if less frames\n        frames += [np.zeros((224, 224, 3))] * (max_frames - len(frames))\n    \n    return np.array(frames)\n\ndef preprocess_video(video_path):\n    \"\"\"Preprocesses a video and extracts features for prediction.\"\"\"\n    frames = load_video(video_path)\n    frames = frames[None, ...]  # Add batch dimension\n    \n    frame_mask = np.zeros((1, max_seq_length), dtype=\"bool\")\n    frame_features = np.zeros((1, max_seq_length, num_features), dtype=\"float32\")\n\n    video_length = frames.shape[1]\n    length = min(max_seq_length, video_length)\n\n    for i in range(length):\n        frame_features[0, i, :] = feature_extractor.predict(frames[:, i, :, :, :])\n    frame_mask[0, :length] = 1\n\n    return [frame_features, frame_mask]\n\n# Path to the test video\nvideo_path = \"/kaggle/input/deepfake-detection-challenge/test_videos/bwdmzwhdnw.mp4\"\n\n# Preprocess the video\nvideo_data = preprocess_video(video_path)\n\n# Make prediction\nprediction = model.predict(video_data)\npredicted_label = \"FAKE\" if prediction[0][0] > 0.5 else \"REAL\"\n\nprint(f\"Prediction: {predicted_label} (Confidence: {prediction[0][0]:.4f})\")\n\n# Function to display the video in a Kaggle Notebook\ndef display_video(video_path):\n    \"\"\"Encodes and displays video in a Kaggle Notebook\"\"\"\n    video_encoded = base64.b64encode(open(video_path, \"rb\").read()).decode('utf-8')\n    video_tag = f'''\n    <video width=\"600\" controls>\n        <source src=\"data:video/mp4;base64,{video_encoded}\" type=\"video/mp4\">\n    </video>\n    '''\n    return HTML(video_tag)\n\n# Display the video\ndisplay_video(video_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-16T16:18:41.581560Z","iopub.execute_input":"2025-03-16T16:18:41.582025Z","iopub.status.idle":"2025-03-16T16:18:52.796286Z","shell.execute_reply.started":"2025-03-16T16:18:41.581942Z","shell.execute_reply":"2025-03-16T16:18:52.794919Z"}},"outputs":[],"execution_count":null}]}