{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"},{"sourceId":845111,"sourceType":"datasetVersion","datasetId":446509}],"dockerImageVersionId":29845,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-24T08:42:24.869269Z","iopub.execute_input":"2024-08-24T08:42:24.869510Z","iopub.status.idle":"2024-08-24T08:42:27.261141Z","shell.execute_reply.started":"2024-08-24T08:42:24.869468Z","shell.execute_reply":"2024-08-24T08:42:27.260256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install '/kaggle/input/dlibpkg/dlib-19.19.0'","metadata":{"execution":{"iopub.status.busy":"2024-08-24T08:42:27.263080Z","iopub.execute_input":"2024-08-24T08:42:27.263415Z","iopub.status.idle":"2024-08-24T08:48:23.522977Z","shell.execute_reply.started":"2024-08-24T08:42:27.263357Z","shell.execute_reply":"2024-08-24T08:48:23.522087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import dlib\nimport cv2\nimport os\nimport re\nimport json\nfrom pylab import *\nfrom PIL import Image, ImageChops, ImageEnhance","metadata":{"execution":{"iopub.status.busy":"2024-08-24T08:48:23.524738Z","iopub.execute_input":"2024-08-24T08:48:23.525074Z","iopub.status.idle":"2024-08-24T08:48:24.595739Z","shell.execute_reply.started":"2024-08-24T08:48:23.525010Z","shell.execute_reply":"2024-08-24T08:48:24.594867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_folder(path):\n    \"\"\"\n    Creates folder\n\n    Makes a new directory as path\n\n    \n    \"\"\"\n    if os.path.exists(path):\n        print(\"{} already exists. Passing!\".format(path))\n        pass\n    else:\n        os.makedirs(path)\n        print(\"{} created!\".format(path))","metadata":{"execution":{"iopub.status.busy":"2024-08-24T08:48:24.597430Z","iopub.execute_input":"2024-08-24T08:48:24.597711Z","iopub.status.idle":"2024-08-24T08:48:24.603399Z","shell.execute_reply.started":"2024-08-24T08:48:24.597659Z","shell.execute_reply":"2024-08-24T08:48:24.602646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_frame_folder = '/kaggle/input/deepfake-detection-challenge/train_sample_videos'\ndataset = 'dataset'\nreal = 'dataset/real'\nfake = 'dataset/fake'\ncreate_folder(dataset)\ncreate_folder(real)\ncreate_folder(fake)","metadata":{"execution":{"iopub.status.busy":"2024-08-24T08:48:24.605954Z","iopub.execute_input":"2024-08-24T08:48:24.606301Z","iopub.status.idle":"2024-08-24T08:48:24.617569Z","shell.execute_reply.started":"2024-08-24T08:48:24.606240Z","shell.execute_reply":"2024-08-24T08:48:24.616887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(os.path.join(train_frame_folder, 'metadata.json'), 'r') as file:\n    data = json.load(file)\nlist_of_train_data = [f for f in os.listdir(train_frame_folder) if f.endswith('.mp4')]\ndetector = dlib.get_frontal_face_detector()\nfor vid in list_of_train_data:\n    count = 0\n    cap = cv2.VideoCapture(os.path.join(train_frame_folder, vid))\n    frameRate = cap.get(5)\n    while cap.isOpened():\n        frameId = cap.get(1)\n        ret, frame = cap.read()\n        if ret != True:\n            break\n        if frameId % ((int(frameRate)+1)*1) == 0:\n            face_rects, scores, idx = detector.run(frame, 0)\n            for i, d in enumerate(face_rects):\n                x1 = d.left()\n                y1 = d.top()\n                x2 = d.right()\n                y2 = d.bottom()\n                crop_img = frame[y1:y2, x1:x2]\n                if data[vid]['label'] == 'REAL':\n                    cv2.imwrite('dataset/real/'+vid.split('.')[0]+'_'+str(count)+'.png', cv2.resize(crop_img, (128, 128)))\n                elif data[vid]['label'] == 'FAKE':\n                    cv2.imwrite('dataset/fake/'+vid.split('.')[0]+'_'+str(count)+'.png', cv2.resize(crop_img, (128, 128)))\n                count+=1","metadata":{"execution":{"iopub.status.busy":"2024-08-24T08:48:24.619233Z","iopub.execute_input":"2024-08-24T08:48:24.619489Z","iopub.status.idle":"2024-08-24T09:19:25.039694Z","shell.execute_reply.started":"2024-08-24T08:48:24.619441Z","shell.execute_reply":"2024-08-24T09:19:25.038820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n# Check if the directory exists\nfake_images_directory = '/kaggle/working/dataset/fake'\n\nif os.path.exists(fake_images_directory):\n    # Count the number of image files in the directory\n    fake_images_count = len([file for file in os.listdir(fake_images_directory) if file.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff'))])\n    print(f\"The number of images in the 'fake' directory: {fake_images_count}\")\nelse:\n    print(\"The directory does not exist. Please check the path.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-08-24T09:20:16.140915Z","iopub.execute_input":"2024-08-24T09:20:16.141256Z","iopub.status.idle":"2024-08-24T09:20:16.150352Z","shell.execute_reply.started":"2024-08-24T09:20:16.141187Z","shell.execute_reply":"2024-08-24T09:20:16.149416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n# Check if the directory exists\nfake_images_directory = '/kaggle/working/dataset/real'\n\nif os.path.exists(fake_images_directory):\n    # Count the number of image files in the directory\n    fake_images_count = len([file for file in os.listdir(fake_images_directory) if file.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff'))])\n    print(f\"The number of images in the 'fake' directory: {fake_images_count}\")\nelse:\n    print(\"The directory does not exist. Please check the path.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-08-24T09:20:17.126102Z","iopub.execute_input":"2024-08-24T09:20:17.126432Z","iopub.status.idle":"2024-08-24T09:20:17.133919Z","shell.execute_reply.started":"2024-08-24T09:20:17.126383Z","shell.execute_reply":"2024-08-24T09:20:17.133118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport random\nimport matplotlib.pyplot as plt\nimport cv2\n\n# Directory path\nfake_images_directory = '/kaggle/working/dataset/fake'\n\n# Check if the directory exists and list all image files\nif os.path.exists(fake_images_directory):\n    image_files = [file for file in os.listdir(fake_images_directory) if file.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff'))]\n    \n    # If there are at least 4 images, visualize them\n    if len(image_files) >= 4:\n        # Select 4 random images\n        random_images = random.sample(image_files, 4)\n\n        # Plotting the images\n        plt.figure(figsize=(10, 10))\n        for i, img_file in enumerate(random_images):\n            img_path = os.path.join(fake_images_directory, img_file)\n            img = cv2.imread(img_path)\n            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert BGR to RGB\n            plt.subplot(2, 2, i + 1)\n            plt.imshow(img_rgb)\n            plt.title(img_file)\n            plt.axis('off')\n\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"Not enough images in the directory to display.\")\nelse:\n    print(\"The directory does not exist. Please check the path.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-08-24T09:19:25.072855Z","iopub.execute_input":"2024-08-24T09:19:25.073211Z","iopub.status.idle":"2024-08-24T09:19:25.855571Z","shell.execute_reply.started":"2024-08-24T09:19:25.073145Z","shell.execute_reply":"2024-08-24T09:19:25.854848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\n# Define the path to your dataset directory\ndataset_directory = '/kaggle/working/dataset'\n\n# Define the output zip file path\noutput_zip_file = '/kaggle/working/dataset.zip'\n\n# Create a zip archive from the directory\nshutil.make_archive(output_zip_file.replace('.zip', ''), 'zip', dataset_directory)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-24T09:20:32.673051Z","iopub.execute_input":"2024-08-24T09:20:32.673511Z","iopub.status.idle":"2024-08-24T09:20:36.086616Z","shell.execute_reply.started":"2024-08-24T09:20:32.673433Z","shell.execute_reply":"2024-08-24T09:20:36.085809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}