{"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"},{"sourceId":10184005,"sourceType":"datasetVersion","datasetId":6291240},{"sourceId":10184017,"sourceType":"datasetVersion","datasetId":6291250}],"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 in \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 \"../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# Any results you write to the current directory are saved as output.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:06:22.918262Z","iopub.execute_input":"2024-12-12T18:06:22.918645Z","iopub.status.idle":"2024-12-12T18:06:25.855656Z","shell.execute_reply.started":"2024-12-12T18:06:22.918577Z","shell.execute_reply":"2024-12-12T18:06:25.854805Z"},"_kg_hide-input":true,"_kg_hide-output":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Importing the required libraries\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport glob\nimport sys\n%matplotlib inline\nimport pickle\nimport shutil\nimport time\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.preprocessing import image as im\nfrom keras.applications.inception_v3 import preprocess_input,decode_predictions\nfrom keras.models import load_model","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:07:26.338637Z","iopub.execute_input":"2024-12-12T18:07:26.338991Z","iopub.status.idle":"2024-12-12T18:07:26.349112Z","shell.execute_reply.started":"2024-12-12T18:07:26.338940Z","shell.execute_reply":"2024-12-12T18:07:26.347971Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import keras\nprint('Keras version:', keras.__version__)\nprint('OpenCV version:', cv2.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:07:34.618943Z","iopub.execute_input":"2024-12-12T18:07:34.619282Z","iopub.status.idle":"2024-12-12T18:07:34.625771Z","shell.execute_reply.started":"2024-12-12T18:07:34.619226Z","shell.execute_reply":"2024-12-12T18:07:34.624238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initializing the paths\ninput_path = '/kaggle/input/deepfake-detection-challenge/'\noutput_path = '/kaggle/working/'\ntrain_dir = glob.glob(input_path + 'train_sample_videos/*.mp4')\ntest_dir = glob.glob(input_path + 'test_videos/*.mp4')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:07:42.437361Z","iopub.execute_input":"2024-12-12T18:07:42.437735Z","iopub.status.idle":"2024-12-12T18:07:42.447576Z","shell.execute_reply.started":"2024-12-12T18:07:42.437665Z","shell.execute_reply":"2024-12-12T18:07:42.446722Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Reading the labels of training data\n\ndf_train = pd.read_json(input_path + 'train_sample_videos/metadata.json').transpose()\ndf_train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:07:47.721453Z","iopub.execute_input":"2024-12-12T18:07:47.721832Z","iopub.status.idle":"2024-12-12T18:07:48.165108Z","shell.execute_reply.started":"2024-12-12T18:07:47.721773Z","shell.execute_reply":"2024-12-12T18:07:48.164095Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plotting the count of labels\n\ndf_train.label.value_counts().plot.bar()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:07:54.423229Z","iopub.execute_input":"2024-12-12T18:07:54.423575Z","iopub.status.idle":"2024-12-12T18:07:54.594158Z","shell.execute_reply.started":"2024-12-12T18:07:54.423523Z","shell.execute_reply":"2024-12-12T18:07:54.592968Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating the dicrectory which would contain the video frames\n\n# shutil.rmtree(output_path + 'train_frames')\nos.mkdir(output_path + 'train_frames')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:08:15.713829Z","iopub.execute_input":"2024-12-12T18:08:15.714212Z","iopub.status.idle":"2024-12-12T18:08:15.718906Z","shell.execute_reply.started":"2024-12-12T18:08:15.714148Z","shell.execute_reply":"2024-12-12T18:08:15.717906Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating frames of all the videos\ntrain_dir = [train_dir[0]]\nt = time.time()\ncount1 = 0\nfor v in train_dir:\n    t1 = time.time()\n    v_name = v.split(\"/\")[-1]\n    if not os.path.exists(output_path + \"train_frames/\" + v_name.split(\".\")[0]):\n        os.mkdir(output_path + \"train_frames/\" + v_name.split(\".\")[0])\n    count = 0\n    cap = cv2.VideoCapture(v)\n    while count < 100:\n        cap.set(cv2.CAP_PROP_POS_MSEC,(count * 100))   \n        ret,frame = cap.read()\n        image = frame\n        count = count + 1\n        cv2.imwrite(\"train_frames/\" + v_name.split(\".\")[0] + \"/frame\" + str(count) + \".jpg\",image)\n    count1 += 1\n    print('Elapsed: ', time.time() - t1, ' | ', count1, '/', len(train_dir), ' | ', v)\nprint('Total elapsed: ', time.time() - t)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:08:18.915728Z","iopub.execute_input":"2024-12-12T18:08:18.916068Z","iopub.status.idle":"2024-12-12T18:09:17.149978Z","shell.execute_reply.started":"2024-12-12T18:08:18.916018Z","shell.execute_reply":"2024-12-12T18:09:17.149068Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(type(image))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:10:11.168811Z","iopub.execute_input":"2024-12-12T18:10:11.169134Z","iopub.status.idle":"2024-12-12T18:10:11.174693Z","shell.execute_reply.started":"2024-12-12T18:10:11.169085Z","shell.execute_reply":"2024-12-12T18:10:11.173665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Taking the base model as Inception V3 and initializing it's weight with imagenet\n\n# Enable internet on kernel settings\ninput_tensor = Input(shape = (229, 229, 3))\ncnn_model = InceptionV3(input_tensor = input_tensor, weights = 'imagenet', include_top = False, pooling = 'avg')\ncnn_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:10:15.146152Z","iopub.execute_input":"2024-12-12T18:10:15.146459Z","iopub.status.idle":"2024-12-12T18:10:23.339792Z","shell.execute_reply.started":"2024-12-12T18:10:15.146411Z","shell.execute_reply":"2024-12-12T18:10:23.338756Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Defining the frame files\n\nframe_files = glob.glob(\"train_frames/*/*.jpg\")\nprint('Total frames captured: ', len(frame_files))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:10:30.650551Z","iopub.execute_input":"2024-12-12T18:10:30.650913Z","iopub.status.idle":"2024-12-12T18:10:30.657803Z","shell.execute_reply.started":"2024-12-12T18:10:30.650857Z","shell.execute_reply":"2024-12-12T18:10:30.656651Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Finding out the feature for each and every frame of all the videos\n\ncnn_output = {}\nt = time.time()\nfor name in frame_files:\n    t1 = time.time()\n    img = im.load_img(name, target_size = (229, 229, 3))\n    x = im.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = preprocess_input(x)\n    folder_name = name.split(\"/\")[1]\n    if folder_name not in cnn_output.keys():\n        cnn_output[folder_name] = []\n    result = cnn_model.predict(x)\n    cnn_output[folder_name].append(result)\nprint('Elapsed: ', time.time() - t)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:10:38.354433Z","iopub.execute_input":"2024-12-12T18:10:38.354881Z","iopub.status.idle":"2024-12-12T18:10:53.302660Z","shell.execute_reply.started":"2024-12-12T18:10:38.354801Z","shell.execute_reply":"2024-12-12T18:10:53.301649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Example of CNN output\n print(len(cnn_output['eivxffliio']), 'frames captured from eivxffliio.mp4')\n cnn_output['eivxffliio']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:52:46.201715Z","iopub.execute_input":"2024-12-12T18:52:46.202044Z","iopub.status.idle":"2024-12-12T18:52:46.245227Z","shell.execute_reply.started":"2024-12-12T18:52:46.201993Z","shell.execute_reply":"2024-12-12T18:52:46.244060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_file_path = output_path + 'cnn_output.txt'\n\n# فتح الملف وحفظ البيانات\nwith open(output_file_path, 'wb') as f:\n    pickle.dump(cnn_output, f)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:54:04.984902Z","iopub.execute_input":"2024-12-12T18:54:04.985238Z","iopub.status.idle":"2024-12-12T18:54:04.992131Z","shell.execute_reply.started":"2024-12-12T18:54:04.985178Z","shell.execute_reply":"2024-12-12T18:54:04.991145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Retrieving the cnn_output\n\nwith open(output_path + 'cnn_output.txt', 'rb') as f:\n    cnn_output = pickle.load(f)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T18:54:07.140591Z","iopub.execute_input":"2024-12-12T18:54:07.140957Z","iopub.status.idle":"2024-12-12T18:54:07.147341Z","shell.execute_reply.started":"2024-12-12T18:54:07.140872Z","shell.execute_reply":"2024-12-12T18:54:07.146459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport time\nfrom keras.preprocessing import image as im\nfrom keras.applications.inception_v3 import preprocess_input\n\n# cnn_output \ncnn_output = {}\nt = time.time()\n\nfor name in frame_files:\n    t1 = time.time()\n    \n    img = im.load_img(name, target_size=(229, 229))  \n    x = im.img_to_array(img)\n    x = np.expand_dims(x, axis=0)  \n    x = preprocess_input(x)  \n\n    folder_name = name.split(\"/\")[1]\n    if folder_name not in cnn_output.keys():\n        cnn_output[folder_name] = []\n    \n    result = cnn_model.predict(x)\n    cnn_output[folder_name].append(result)\n    \n    print(f\"Processed {name} in {time.time() - t1} seconds\")\n\nprint('Elapsed: ', time.time() - t)\n\n\npredictions = []\n\nfor folder, results in cnn_output.items():\n    for result in results:\n        predictions.append((folder, result))\n\nfor prediction in predictions:\n    folder, result = prediction\n    result_value = result[0][0]  \n    if result_value > 0.5:\n        print(f\"Video in {folder} is Fake\")\n    else:\n        print(f\"Video in {folder} is Real\")\n\nimport pickle\nwith open('cnn_output.pkl', 'wb') as f:\n    pickle.dump(cnn_output, f)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:00:01.346628Z","iopub.execute_input":"2024-12-12T19:00:01.347025Z","iopub.status.idle":"2024-12-12T19:00:12.381109Z","shell.execute_reply.started":"2024-12-12T19:00:01.346969Z","shell.execute_reply":"2024-12-12T19:00:12.380048Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"real_count = 0\nfake_count = 0\ntotal_count = 0\n\nfor prediction in predictions:\n    folder, result = prediction\n    result_value = result[0][0]  \n    if result_value > 0.5:\n        fake_count += 1 \n    else:\n        real_count += 1  \n    total_count += 1  \n\nreal_percentage = (real_count / total_count) * 100\nfake_percentage = (fake_count / total_count) * 100\n\nprint(f\"Percentage of Real videos: {real_percentage:.2f}%\")\nprint(f\"Percentage of Fake videos: {fake_percentage:.2f}%\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:01:05.573380Z","iopub.execute_input":"2024-12-12T19:01:05.573932Z","iopub.status.idle":"2024-12-12T19:01:05.584124Z","shell.execute_reply.started":"2024-12-12T19:01:05.573683Z","shell.execute_reply":"2024-12-12T19:01:05.581656Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"new_video_path = \"/kaggle/input/216525254/1111111.mp4\"  \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:13:09.190541Z","iopub.execute_input":"2024-12-12T19:13:09.190992Z","iopub.status.idle":"2024-12-12T19:13:09.195529Z","shell.execute_reply.started":"2024-12-12T19:13:09.190916Z","shell.execute_reply":"2024-12-12T19:13:09.194530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_video_frames = \"train_frames/new_video_frames\"  \nos.makedirs(output_video_frames, exist_ok=True)\n\ncap = cv2.VideoCapture(new_video_path)\nframe_count = 0\nwhile frame_count < 100:  \n    cap.set(cv2.CAP_PROP_POS_MSEC, (frame_count * 100))   \n    ret, frame = cap.read()\n    if ret:\n        image = frame\n        cv2.imwrite(f\"{output_video_frames}/frame{frame_count + 1}.jpg\", image)\n    frame_count += 1\ncap.release()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:13:11.340421Z","iopub.execute_input":"2024-12-12T19:13:11.340816Z","iopub.status.idle":"2024-12-12T19:13:30.133363Z","shell.execute_reply.started":"2024-12-12T19:13:11.340760Z","shell.execute_reply":"2024-12-12T19:13:30.132270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cnn_output_new_video = {}\nframe_files_new_video = glob.glob(output_video_frames + \"/*.jpg\")\n\nfor name in frame_files_new_video:\n    t1 = time.time()\n    \n    img = im.load_img(name, target_size=(229, 229))   \n    x = im.img_to_array(img)\n    x = np.expand_dims(x, axis=0) \n    x = preprocess_input(x)  \n\n    folder_name = name.split(\"/\")[1]\n    if folder_name not in cnn_output_new_video.keys():\n        cnn_output_new_video[folder_name] = []\n    \n    result = cnn_model.predict(x)\n    cnn_output_new_video[folder_name].append(result)\n    \n    print(f\"Processed {name} in {time.time() - t1} seconds\")\n\nprint('Elapsed: ', time.time() - t)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:13:34.214570Z","iopub.execute_input":"2024-12-12T19:13:34.214920Z","iopub.status.idle":"2024-12-12T19:13:45.024993Z","shell.execute_reply.started":"2024-12-12T19:13:34.214860Z","shell.execute_reply":"2024-12-12T19:13:45.024096Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions_new_video = []\n\nfor folder, results in cnn_output_new_video.items():\n    for result in results:\n        predictions_new_video.append((folder, result))\n\nfor prediction in predictions_new_video:\n    folder, result = prediction\n    result_value = result[0][0] \n    if result_value > 0.5:\n        print(f\"Video in {folder} is Fake\")\n    else:\n        print(f\"Video in {folder} is Real\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:13:47.793314Z","iopub.execute_input":"2024-12-12T19:13:47.793699Z","iopub.status.idle":"2024-12-12T19:13:47.807015Z","shell.execute_reply.started":"2024-12-12T19:13:47.793620Z","shell.execute_reply":"2024-12-12T19:13:47.805670Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open('cnn_output_new_video.pkl', 'wb') as f:\n    pickle.dump(cnn_output_new_video, f)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:10:56.620108Z","iopub.execute_input":"2024-12-12T19:10:56.620438Z","iopub.status.idle":"2024-12-12T19:10:56.627778Z","shell.execute_reply.started":"2024-12-12T19:10:56.620384Z","shell.execute_reply":"2024-12-12T19:10:56.626878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"real_count = 0\nfake_count = 0\ntotal_count = 0\n\nfor prediction in predictions_new_video:\n    folder, result = prediction\n    result_value = result[0][0] \n    if result_value > 0.5:\n        fake_count += 1  \n    else:\n        real_count += 1 \n    total_count += 1  \n\nreal_percentage = (real_count / total_count) * 100\nfake_percentage = (fake_count / total_count) * 100\n\nprint(f\"Percentage of Real videos: {real_percentage:.2f}%\")\nprint(f\"Percentage of Fake videos: {fake_percentage:.2f}%\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T19:14:52.954476Z","iopub.execute_input":"2024-12-12T19:14:52.954833Z","iopub.status.idle":"2024-12-12T19:14:52.962400Z","shell.execute_reply.started":"2024-12-12T19:14:52.954780Z","shell.execute_reply":"2024-12-12T19:14:52.961612Z"}},"outputs":[],"execution_count":null}]}