{"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"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"* **Title** \n\n    using RNN's & CNN's to deal with Deepfake video","metadata":{}},{"cell_type":"markdown","source":"* **Problem** \n\n    深偽技術(Deepfake)是基於人工智慧中的圖像合成技巧所衍伸出來的技術,通過換臉達到偽造身分的目的,進而融合生成式對抗網路(GAN)的技巧,產生人臉再進行替換.","metadata":{}},{"cell_type":"markdown","source":"* **Purpose** \n    \n    訓練模型以辨認影像中的物體是否為Deepfake所產生的結果(REAL/FAKE)","metadata":{}},{"cell_type":"markdown","source":"* **Dataset** \n\n    1. 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    2. sample_submission.csv - a sample submission file in the correct format.\n    3. test_videos.zip - a zip file containing a small set of videos to be used as a public validation set.","metadata":{}},{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"execution":{"iopub.status.busy":"2023-09-11T00:26:39.070303Z","iopub.execute_input":"2023-09-11T00:26:39.070661Z","iopub.status.idle":"2023-09-11T00:28:10.160392Z","shell.execute_reply.started":"2023-09-11T00:26:39.070561Z","shell.execute_reply":"2023-09-11T00:28:10.155352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#導入相關套件\nfrom 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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:10.167695Z","iopub.execute_input":"2023-09-11T00:28:10.168434Z","iopub.status.idle":"2023-09-11T00:28:15.185865Z","shell.execute_reply.started":"2023-09-11T00:28:10.168326Z","shell.execute_reply":"2023-09-11T00:28:15.184276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#導入資料/查看資料大小\nDATA_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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:15.188688Z","iopub.execute_input":"2023-09-11T00:28:15.189500Z","iopub.status.idle":"2023-09-11T00:28:15.435044Z","shell.execute_reply.started":"2023-09-11T00:28:15.189422Z","shell.execute_reply":"2023-09-11T00:28:15.434057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:15.436995Z","iopub.execute_input":"2023-09-11T00:28:15.437531Z","iopub.status.idle":"2023-09-11T00:28:17.182487Z","shell.execute_reply.started":"2023-09-11T00:28:15.437467Z","shell.execute_reply":"2023-09-11T00:28:17.181702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:17.186825Z","iopub.execute_input":"2023-09-11T00:28:17.187631Z","iopub.status.idle":"2023-09-11T00:28:17.402961Z","shell.execute_reply.started":"2023-09-11T00:28:17.187514Z","shell.execute_reply":"2023-09-11T00:28:17.401744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#檢查檔案維度\ntrain_sample_metadata.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-11T00:28:17.405645Z","iopub.execute_input":"2023-09-11T00:28:17.405949Z","iopub.status.idle":"2023-09-11T00:28:18.329378Z","shell.execute_reply.started":"2023-09-11T00:28:17.405890Z","shell.execute_reply":"2023-09-11T00:28:18.328515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* **擷取影像** \n\n    將影像擷取成圖片處理(分成FAKE/REAL兩部分)","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:18.331798Z","iopub.execute_input":"2023-09-11T00:28:18.332223Z","iopub.status.idle":"2023-09-11T00:28:18.418749Z","shell.execute_reply.started":"2023-09-11T00:28:18.332160Z","shell.execute_reply":"2023-09-11T00:28:18.417302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:18.420738Z","iopub.execute_input":"2023-09-11T00:28:18.421346Z","iopub.status.idle":"2023-09-11T00:28:18.514040Z","shell.execute_reply.started":"2023-09-11T00:28:18.421260Z","shell.execute_reply":"2023-09-11T00:28:18.512882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:18.515362Z","iopub.execute_input":"2023-09-11T00:28:18.515831Z","iopub.status.idle":"2023-09-11T00:28:21.798106Z","shell.execute_reply.started":"2023-09-11T00:28:18.515766Z","shell.execute_reply":"2023-09-11T00:28:21.796654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:21.799737Z","iopub.execute_input":"2023-09-11T00:28:21.800031Z","iopub.status.idle":"2023-09-11T00:28:21.814065Z","shell.execute_reply.started":"2023-09-11T00:28:21.799980Z","shell.execute_reply":"2023-09-11T00:28:21.813384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:21.815925Z","iopub.execute_input":"2023-09-11T00:28:21.816520Z","iopub.status.idle":"2023-09-11T00:28:26.688666Z","shell.execute_reply.started":"2023-09-11T00:28:21.816459Z","shell.execute_reply":"2023-09-11T00:28:26.687912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* **檢視FAKE** \n\n    想從中找出fake跟real的分辨方式,訂定之後model的構築方向","metadata":{}},{"cell_type":"code","source":"f_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)","metadata":{"execution":{"iopub.status.busy":"2023-09-11T00:28:26.689921Z","iopub.execute_input":"2023-09-11T00:28:26.690369Z","iopub.status.idle":"2023-09-11T00:28:26.698514Z","shell.execute_reply.started":"2023-09-11T00:28:26.690327Z","shell.execute_reply":"2023-09-11T00:28:26.697798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:26.699835Z","iopub.execute_input":"2023-09-11T00:28:26.700204Z","iopub.status.idle":"2023-09-11T00:28:26.842916Z","shell.execute_reply.started":"2023-09-11T00:28:26.700163Z","shell.execute_reply":"2023-09-11T00:28:26.841985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"經過多個影片的測試,有些很容易看出是fake,但有些卻完全難以靠肉眼分辨是否為fake","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:26.843998Z","iopub.execute_input":"2023-09-11T00:28:26.844504Z","iopub.status.idle":"2023-09-11T00:28:26.850213Z","shell.execute_reply.started":"2023-09-11T00:28:26.844431Z","shell.execute_reply":"2023-09-11T00:28:26.849208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:26.852025Z","iopub.execute_input":"2023-09-11T00:28:26.852329Z","iopub.status.idle":"2023-09-11T00:28:26.871323Z","shell.execute_reply.started":"2023-09-11T00:28:26.852267Z","shell.execute_reply":"2023-09-11T00:28:26.870217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:26.872975Z","iopub.execute_input":"2023-09-11T00:28:26.873569Z","iopub.status.idle":"2023-09-11T00:28:33.527925Z","shell.execute_reply.started":"2023-09-11T00:28:26.873498Z","shell.execute_reply":"2023-09-11T00:28:33.526801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_all_videos(df, root_dir): #df是train_sample_metadata->json的split\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\") #array=360*20\n    frame_features = np.zeros(\n        shape=(num_samples, max_seq_length, num_features), dtype=\"float32\" #array=360*20*2048\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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:33.529792Z","iopub.execute_input":"2023-09-11T00:28:33.530133Z","iopub.status.idle":"2023-09-11T00:28:33.544407Z","shell.execute_reply.started":"2023-09-11T00:28:33.530068Z","shell.execute_reply":"2023-09-11T00:28:33.542967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nTrain_set , Test_set = train_test_split(train_sample_metadata, test_size=0.1,random_state=42,\n                                       stratify=train_sample_metadata['label'])\nprint(Train_set.shape, Test_set.shape)","metadata":{"execution":{"iopub.status.busy":"2023-09-11T00:28:33.546396Z","iopub.execute_input":"2023-09-11T00:28:33.546787Z","iopub.status.idle":"2023-09-11T00:28:34.714446Z","shell.execute_reply.started":"2023-09-11T00:28:33.546721Z","shell.execute_reply":"2023-09-11T00:28:34.713068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:34.715893Z","iopub.execute_input":"2023-09-11T00:28:34.716152Z","iopub.status.idle":"2023-09-11T00:28:34.841257Z","shell.execute_reply.started":"2023-09-11T00:28:34.716101Z","shell.execute_reply":"2023-09-11T00:28:34.840091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Training(RNN)**","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:34.842563Z","iopub.execute_input":"2023-09-11T00:28:34.842967Z","iopub.status.idle":"2023-09-11T00:28:36.432603Z","shell.execute_reply.started":"2023-09-11T00:28:34.842913Z","shell.execute_reply":"2023-09-11T00:28:36.431611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:36.434288Z","iopub.execute_input":"2023-09-11T00:28:36.434881Z","iopub.status.idle":"2023-09-11T00:28:56.624385Z","shell.execute_reply.started":"2023-09-11T00:28:36.434802Z","shell.execute_reply":"2023-09-11T00:28:56.622921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Inference**","metadata":{}},{"cell_type":"code","source":"test_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])","metadata":{"execution":{"iopub.status.busy":"2023-09-11T00:28:56.626052Z","iopub.execute_input":"2023-09-11T00:28:56.626332Z","iopub.status.idle":"2023-09-11T00:28:56.637026Z","shell.execute_reply.started":"2023-09-11T00:28:56.626278Z","shell.execute_reply":"2023-09-11T00:28:56.635222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-11T00:28:56.638670Z","iopub.execute_input":"2023-09-11T00:28:56.639017Z","iopub.status.idle":"2023-09-11T00:29:04.613169Z","shell.execute_reply.started":"2023-09-11T00:28:56.638952Z","shell.execute_reply":"2023-09-11T00:29:04.612081Z"},"trusted":true},"execution_count":null,"outputs":[]}],"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}}