{"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"},{"sourceId":9146200,"sourceType":"datasetVersion","datasetId":5524489},{"sourceId":10195730,"sourceType":"datasetVersion","datasetId":6299820},{"sourceId":11868869,"sourceType":"datasetVersion","datasetId":7452820}],"dockerImageVersionId":29845,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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-05-22T08:03:40.194461Z","iopub.execute_input":"2025-05-22T08:03:40.194783Z","iopub.status.idle":"2025-05-22T08:03:42.163770Z","shell.execute_reply.started":"2025-05-22T08:03:40.194723Z","shell.execute_reply":"2025-05-22T08:03:42.163120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"  # Disable GPU for now\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:03:42.165024Z","iopub.execute_input":"2025-05-22T08:03:42.165280Z","iopub.status.idle":"2025-05-22T08:03:42.168820Z","shell.execute_reply.started":"2025-05-22T08:03:42.165225Z","shell.execute_reply":"2025-05-22T08:03:42.167982Z"}},"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-05-22T08:03:42.171476Z","iopub.execute_input":"2025-05-22T08:03:42.171806Z","iopub.status.idle":"2025-05-22T08:03:42.183254Z","shell.execute_reply.started":"2025-05-22T08:03:42.171737Z","shell.execute_reply":"2025-05-22T08:03:42.182600Z"}},"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-05-22T08:03:42.185509Z","iopub.execute_input":"2025-05-22T08:03:42.185775Z","iopub.status.idle":"2025-05-22T08:03:42.346370Z","shell.execute_reply.started":"2025-05-22T08:03:42.185717Z","shell.execute_reply":"2025-05-22T08:03:42.345719Z"}},"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-05-22T08:03:42.347873Z","iopub.execute_input":"2025-05-22T08:03:42.348166Z","iopub.status.idle":"2025-05-22T08:03:42.548674Z","shell.execute_reply.started":"2025-05-22T08:03:42.348109Z","shell.execute_reply":"2025-05-22T08:03:42.547742Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:03:42.550112Z","iopub.execute_input":"2025-05-22T08:03:42.550474Z","iopub.status.idle":"2025-05-22T08:03:42.561258Z","shell.execute_reply.started":"2025-05-22T08:03:42.550414Z","shell.execute_reply":"2025-05-22T08:03:42.559769Z"}},"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-05-22T08:03:42.562856Z","iopub.execute_input":"2025-05-22T08:03:42.563149Z","iopub.status.idle":"2025-05-22T08:03:42.582852Z","shell.execute_reply.started":"2025-05-22T08:03:42.563092Z","shell.execute_reply":"2025-05-22T08:03:42.581243Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def capture_image_from_video(video_path):\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-05-22T08:03:42.584057Z","iopub.execute_input":"2025-05-22T08:03:42.584346Z","iopub.status.idle":"2025-05-22T08:03:42.595332Z","shell.execute_reply.started":"2025-05-22T08:03:42.584291Z","shell.execute_reply":"2025-05-22T08:03:42.594437Z"}},"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-05-22T08:03:42.596893Z","iopub.execute_input":"2025-05-22T08:03:42.597175Z","iopub.status.idle":"2025-05-22T08:03:45.506180Z","shell.execute_reply.started":"2025-05-22T08:03:42.597126Z","shell.execute_reply":"2025-05-22T08:03:45.505393Z"}},"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-05-22T08:03:45.507216Z","iopub.execute_input":"2025-05-22T08:03:45.507439Z","iopub.status.idle":"2025-05-22T08:03:45.514218Z","shell.execute_reply.started":"2025-05-22T08:03:45.507399Z","shell.execute_reply":"2025-05-22T08:03:45.513611Z"}},"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-05-22T08:03:45.515077Z","iopub.execute_input":"2025-05-22T08:03:45.515266Z","iopub.status.idle":"2025-05-22T08:03:48.170939Z","shell.execute_reply.started":"2025-05-22T08:03:45.515231Z","shell.execute_reply":"2025-05-22T08:03:48.169919Z"}},"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-05-22T08:03:48.172581Z","iopub.execute_input":"2025-05-22T08:03:48.173125Z","iopub.status.idle":"2025-05-22T08:03:48.180646Z","shell.execute_reply.started":"2025-05-22T08:03:48.173061Z","shell.execute_reply":"2025-05-22T08:03:48.179692Z"}},"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-05-22T08:03:48.181633Z","iopub.execute_input":"2025-05-22T08:03:48.181966Z","iopub.status.idle":"2025-05-22T08:03:48.249092Z","shell.execute_reply.started":"2025-05-22T08:03:48.181916Z","shell.execute_reply":"2025-05-22T08:03:48.248386Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Modelling**","metadata":{}},{"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-05-22T08:03:48.250453Z","iopub.execute_input":"2025-05-22T08:03:48.250733Z","iopub.status.idle":"2025-05-22T08:03:48.255656Z","shell.execute_reply.started":"2025-05-22T08:03:48.250683Z","shell.execute_reply":"2025-05-22T08:03:48.254770Z"}},"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)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:03:48.256990Z","iopub.execute_input":"2025-05-22T08:03:48.257342Z","iopub.status.idle":"2025-05-22T08:03:48.267017Z","shell.execute_reply.started":"2025-05-22T08:03:48.257162Z","shell.execute_reply":"2025-05-22T08:03:48.266258Z"}},"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-05-22T08:03:48.268266Z","iopub.execute_input":"2025-05-22T08:03:48.268507Z","iopub.status.idle":"2025-05-22T08:03:53.589443Z","shell.execute_reply.started":"2025-05-22T08:03:48.268443Z","shell.execute_reply":"2025-05-22T08:03:53.588689Z"}},"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-05-22T08:03:53.590858Z","iopub.execute_input":"2025-05-22T08:03:53.591110Z","iopub.status.idle":"2025-05-22T08:03:53.599779Z","shell.execute_reply.started":"2025-05-22T08:03:53.591060Z","shell.execute_reply":"2025-05-22T08:03:53.598907Z"}},"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.2,random_state=42,\n                                       stratify=train_sample_metadata['label'])\nprint(Train_set.shape, Test_set.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:03:53.602277Z","iopub.execute_input":"2025-05-22T08:03:53.602556Z","iopub.status.idle":"2025-05-22T08:03:53.899416Z","shell.execute_reply.started":"2025-05-22T08:03:53.602468Z","shell.execute_reply":"2025-05-22T08:03:53.898525Z"}},"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-05-22T08:03:53.900932Z","iopub.execute_input":"2025-05-22T08:03:53.901250Z","iopub.status.idle":"2025-05-22T08:03:53.988321Z","shell.execute_reply.started":"2025-05-22T08:03:53.901190Z","shell.execute_reply":"2025-05-22T08:03:53.987600Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Training(RNN)**","metadata":{}},{"cell_type":"code","source":"from tensorflow import keras\n\n# Define input shape\nframe_features_input = keras.Input((max_seq_length, num_features))\nmask_input = keras.Input((max_seq_length,), dtype=\"bool\")\n\n# Build the model\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)\n\n# Compile the model\nmodel.compile(\n    loss=\"binary_crossentropy\",\n    optimizer=\"adam\",\n    metrics=[\"accuracy\", keras.metrics.Precision()]\n)\n\nmodel.summary()\n\n# Define checkpoint\ncheckpoint = keras.callbacks.ModelCheckpoint(\n    './',\n    save_weights_only=True,\n    save_best_only=True\n)\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],\n    epochs=5,\n    batch_size=64\n)\n\n# Print training and validation metrics after each epoch\nfor epoch in range(len(history.history['loss'])):\n    print(f\"Epoch {epoch+1}\")\n    print(f\" - Training   Loss: {history.history['loss'][epoch]:.4f}, Accuracy: {history.history['accuracy'][epoch]:.4f}, Precision: {history.history['precision'][epoch]:.4f}\")\n    print(f\" - Validation Loss: {history.history['val_loss'][epoch]:.4f}, Accuracy: {history.history['val_accuracy'][epoch]:.4f}, Precision: {history.history['val_precision'][epoch]:.4f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:03:53.989904Z","iopub.execute_input":"2025-05-22T08:03:53.990207Z","iopub.status.idle":"2025-05-22T08:04:01.798236Z","shell.execute_reply.started":"2025-05-22T08:03:53.990147Z","shell.execute_reply":"2025-05-22T08:04:01.797384Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot Accuracy\nplt.figure(figsize=(12, 5))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Val Accuracy')\nplt.title('Model Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plot Loss\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Val Loss')\nplt.title('Model Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:04:01.799265Z","iopub.execute_input":"2025-05-22T08:04:01.799583Z","iopub.status.idle":"2025-05-22T08:04:02.396033Z","shell.execute_reply.started":"2025-05-22T08:04:01.799470Z","shell.execute_reply":"2025-05-22T08:04:02.394878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_videos = '/kaggle/input/deepfake-detection-challenge/test_videos'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T08:04:02.397525Z","iopub.execute_input":"2025-05-22T08:04:02.397886Z","iopub.status.idle":"2025-05-22T08:04:02.406986Z","shell.execute_reply.started":"2025-05-22T08:04:02.397826Z","shell.execute_reply":"2025-05-22T08:04:02.405700Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_FOLDER=\"/kaggle/input/deepfake-detection-challenge\"\nTEST_FOLDER='test_videos'\ntest_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])\ntest_video = np.random.choice(test_videos[\"video\"].values.tolist())\n\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_videos = '/kaggle/input/real-video/fake_video.mp4'\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-05-22T08:04:02.408461Z","iopub.execute_input":"2025-05-22T08:04:02.408849Z","iopub.status.idle":"2025-05-22T08:04:08.534508Z","shell.execute_reply.started":"2025-05-22T08:04:02.408789Z","shell.execute_reply":"2025-05-22T08:04:08.533096Z"}},"outputs":[],"execution_count":null}]}