{"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":"markdown","source":"Лабораторна робота № 4: Визначення Deepfake","metadata":{}},{"cell_type":"markdown","source":"Імпорт бібліотек","metadata":{}},{"cell_type":"code","source":"import os\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:02.190865Z","iopub.execute_input":"2024-12-03T12:22:02.191183Z","iopub.status.idle":"2024-12-03T12:22:02.19651Z","shell.execute_reply.started":"2024-12-03T12:22:02.191135Z","shell.execute_reply":"2024-12-03T12:22:02.195511Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Завантаження метаданих","metadata":{}},{"cell_type":"code","source":"metadata_path = '/kaggle/input/deepfake-detection-challenge/train_sample_videos/metadata.json'\n\n# Завантаження метаданих\nwith open(metadata_path, 'r') as f:\n    metadata = json.load(f)\n\n# Конвертація метаданих у DataFrame\nmetadata_df = pd.DataFrame(metadata).T.reset_index().rename(columns={'index': 'video'})\nprint(metadata_df.head())\n\n# Додатковий аналіз\nprint(\"Кількість відео:\", len(metadata_df))\nprint(metadata_df['label'].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:02.19866Z","iopub.execute_input":"2024-12-03T12:22:02.199013Z","iopub.status.idle":"2024-12-03T12:22:02.274403Z","shell.execute_reply.started":"2024-12-03T12:22:02.198951Z","shell.execute_reply":"2024-12-03T12:22:02.273501Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Візуалізація розподілу класів","metadata":{}},{"cell_type":"code","source":"# Розподіл класів\nsns.countplot(x='label', data=metadata_df, palette='viridis')\nplt.title('Розподіл класів (Оригінальні / Підроблені)')\nplt.xlabel('Клас')\nplt.ylabel('Кількість')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:02.276076Z","iopub.execute_input":"2024-12-03T12:22:02.276383Z","iopub.status.idle":"2024-12-03T12:22:02.404921Z","shell.execute_reply.started":"2024-12-03T12:22:02.276315Z","shell.execute_reply":"2024-12-03T12:22:02.403885Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Візуалізація розподілу відео за довжиною","metadata":{}},{"cell_type":"code","source":"# Додавання метаданих у DataFrame\nmetadata_df['video_length'] = metadata_df['video'].apply(lambda x: get_video_length(video_sample_path + x))\n\nplt.figure(figsize=(10, 6))\n\n# Побудова розподілу\nfor label in metadata_df['label'].unique():\n    subset = metadata_df[metadata_df['label'] == label]\n    sns.distplot(subset['video_length'], kde=True, hist=True, label=label)\n\nplt.title('Розподіл довжини відео (кадри)')\nplt.xlabel('Довжина відео (кількість кадрів)')\nplt.ylabel('Кількість відео')\nplt.legend(title='Клас')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:02.406341Z","iopub.execute_input":"2024-12-03T12:22:02.406675Z","iopub.status.idle":"2024-12-03T12:22:10.625137Z","shell.execute_reply.started":"2024-12-03T12:22:02.406618Z","shell.execute_reply":"2024-12-03T12:22:10.624019Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" Зчитування кадрів із відео","metadata":{}},{"cell_type":"code","source":"# Функція для отримання кадру\ndef extract_frame(video_path, save_path, frame_num=30):\n    \n    cap = cv2.VideoCapture(video_path)\n    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)\n    success, frame = cap.read()\n    if success:\n        cv2.imwrite(save_path, frame)\n    cap.release()\n\n# Приклад зчитування одного відео\nvideo_sample_path = '/kaggle/input/deepfake-detection-challenge/train_sample_videos/'\nvideo_name = metadata_df.loc[0, 'video']\nextract_frame(video_sample_path + video_name, f'{video_name}_frame.jpg')\nprint(f\"Кадр збережено для відео {video_name}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:10.628473Z","iopub.execute_input":"2024-12-03T12:22:10.628896Z","iopub.status.idle":"2024-12-03T12:22:10.978974Z","shell.execute_reply.started":"2024-12-03T12:22:10.628817Z","shell.execute_reply":"2024-12-03T12:22:10.978008Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Аналіз та попередня обробка","metadata":{}},{"cell_type":"code","source":"# Додавання нових ознак\nmetadata_df['original_video'] = metadata_df['original'].notnull()\nmetadata_df['is_fake'] = metadata_df['label'] == 'FAKE'\n\n# Розподіл відео за джерелом\nsns.countplot(data=metadata_df, x='original_video', palette='coolwarm')\nplt.title('Відео оригінальні/згенеровані')\nplt.xlabel('Чи є це оригінальне відео?')\nplt.ylabel('Кількість')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:10.981218Z","iopub.execute_input":"2024-12-03T12:22:10.981616Z","iopub.status.idle":"2024-12-03T12:22:11.215287Z","shell.execute_reply.started":"2024-12-03T12:22:10.981546Z","shell.execute_reply":"2024-12-03T12:22:11.21391Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Створення набору даних для навчання","metadata":{}},{"cell_type":"code","source":"train, test = train_test_split(metadata_df, test_size=0.2, random_state=42, stratify=metadata_df['label'])\n\nprint(\"Розмір тренувального набору:\", len(train))\nprint(\"Розмір тестового набору:\", len(test))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:11.217223Z","iopub.execute_input":"2024-12-03T12:22:11.217683Z","iopub.status.idle":"2024-12-03T12:22:11.238284Z","shell.execute_reply.started":"2024-12-03T12:22:11.217611Z","shell.execute_reply":"2024-12-03T12:22:11.237072Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Попередній аналіз кадрів","metadata":{}},{"cell_type":"code","source":"# Кількість прикладів для кожного класу\nnum_examples = 7\n\n# Фільтрація відео для кожної категорії\nreal_videos = metadata_df[metadata_df['label'] == 'REAL'].head(num_examples)['video']\nfake_videos = metadata_df[metadata_df['label'] == 'FAKE'].head(num_examples)['video']\n\n# Створення підсюжетів\nfig, axes = plt.subplots(2, num_examples, figsize=(15, 8))\n\n# Оригінальні відео\nfor i, video in enumerate(real_videos):\n    video_path = video_sample_path + video\n    cap = cv2.VideoCapture(video_path)\n    success, frame = cap.read()\n    cap.release()\n    if success:\n        axes[0, i].imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n        axes[0, i].set_title(f'Оригінал\\n{video}', fontsize=12)\n    else:\n        axes[0, i].text(0.5, 0.5, 'Не вдалося завантажити', ha='center', va='center', fontsize=12)\n    axes[0, i].axis('off')\n\n# Підроблені відео\nfor i, video in enumerate(fake_videos):\n    video_path = video_sample_path + video\n    cap = cv2.VideoCapture(video_path)\n    success, frame = cap.read()\n    cap.release()\n    if success:\n        axes[1, i].imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n        axes[1, i].set_title(f'Підробка\\n{video}', fontsize=12)\n    else:\n        axes[1, i].text(0.5, 0.5, 'Не вдалося завантажити', ha='center', va='center', fontsize=12)\n    axes[1, i].axis('off')\n\n# Додаткові налаштування сюжету\nplt.suptitle('Візуалізація оригінальних і підроблених відео', fontsize=17)\nplt.tight_layout(rect=[0, 0, 1, 0.96])\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T12:22:11.240133Z","iopub.execute_input":"2024-12-03T12:22:11.240572Z","iopub.status.idle":"2024-12-03T12:22:14.651476Z","shell.execute_reply.started":"2024-12-03T12:22:11.240504Z","shell.execute_reply":"2024-12-03T12:22:14.650553Z"}},"outputs":[],"execution_count":null}]}