Spaces:
Sleeping

File size: 6,851 Bytes
cc54add
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9424c581",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✔ YOLOv8-face model loaded!\n"
     ]
    }
   ],
   "source": [
    "from ultralytics import YOLO\n",
    "import cv2\n",
    "import numpy as np\n",
    "import os\n",
    "from tqdm import tqdm\n",
    "\n",
    "model = YOLO(\"yolov8n-face.pt\")  \n",
    "print(\"✔ YOLOv8-face model loaded!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7e391706",
   "metadata": {},
   "outputs": [],
   "source": [
    "def crop_face_yolo(frame, expand=1.3):\n",
    "    results = model(frame, verbose=False)[0] \n",
    "    if len(results.boxes) == 0:\n",
    "        return None\n",
    "\n",
    "    box = results.boxes.xyxy[0].cpu().numpy().astype(int)\n",
    "    x1, y1, x2, y2 = box\n",
    "\n",
    "    h, w = frame.shape[:2]\n",
    "\n",
    "    bw, bh = x2-x1, y2-y1\n",
    "    pad_w = int((expand - 1) * bw / 2)\n",
    "    pad_h = int((expand - 1) * bh / 2)\n",
    "\n",
    "    x1 = max(0, x1 - pad_w)\n",
    "    y1 = max(0, y1 - pad_h)\n",
    "    x2 = min(w, x2 + pad_w)\n",
    "    y2 = min(h, y2 + pad_h)\n",
    "\n",
    "    return frame[y1:y2, x1:x2]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9118fd00",
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_video_full(video_path, out_dir, sample_frames=20, batch_size=8):\n",
    "    os.makedirs(out_dir, exist_ok=True)\n",
    "    cap = cv2.VideoCapture(video_path)\n",
    "    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
    "    idxs = np.linspace(0, total-1, sample_frames).astype(int)\n",
    "    idx_set = set(idxs)\n",
    "    i = 0\n",
    "    saved = 0\n",
    "    frames = []\n",
    "    frame_indices = []\n",
    "    while True:\n",
    "        ret, frame = cap.read()\n",
    "        if not ret:\n",
    "            break\n",
    "        if i in idx_set:\n",
    "            frames.append(frame)\n",
    "            frame_indices.append(i)\n",
    "            if len(frames) == batch_size:\n",
    "                results = model(frames, verbose=False)\n",
    "                for j, res in enumerate(results):\n",
    "                    if len(res.boxes) == 0:\n",
    "                        continue\n",
    "                    box = res.boxes.xyxy[0].cpu().numpy().astype(int)\n",
    "                    x1, y1, x2, y2 = box\n",
    "                    h, w = res.orig_img.shape[:2]\n",
    "                    bw, bh = x2-x1, y2-y1\n",
    "                    pad_w = int((1.3 - 1) * bw / 2)\n",
    "                    pad_h = int((1.3 - 1) * bh / 2)\n",
    "                    x1 = max(0, x1 - pad_w)\n",
    "                    y1 = max(0, y1 - pad_h)\n",
    "                    x2 = min(w, x2 + pad_w)\n",
    "                    y2 = min(h, y2 + pad_h)\n",
    "                    crop = res.orig_img[y1:y2, x1:x2]\n",
    "                    crop = cv2.resize(crop, (299, 299))\n",
    "                    cv2.imwrite(f\"{out_dir}/frame_{saved:03d}.png\", crop)\n",
    "                    saved += 1\n",
    "                frames = []\n",
    "                frame_indices = []\n",
    "        i += 1\n",
    "    # Process any remaining frames\n",
    "    if frames:\n",
    "        results = model(frames, verbose=False)\n",
    "        for j, res in enumerate(results):\n",
    "            if len(res.boxes) == 0:\n",
    "                continue\n",
    "            box = res.boxes.xyxy[0].cpu().numpy().astype(int)\n",
    "            x1, y1, x2, y2 = box\n",
    "            h, w = res.orig_img.shape[:2]\n",
    "            bw, bh = x2-x1, y2-y1\n",
    "            pad_w = int((1.3 - 1) * bw / 2)\n",
    "            pad_h = int((1.3 - 1) * bh / 2)\n",
    "            x1 = max(0, x1 - pad_w)\n",
    "            y1 = max(0, y1 - pad_h)\n",
    "            x2 = min(w, x2 + pad_w)\n",
    "            y2 = min(h, y2 + pad_h)\n",
    "            crop = res.orig_img[y1:y2, x1:x2]\n",
    "            crop = cv2.resize(crop, (299, 299))\n",
    "            cv2.imwrite(f\"{out_dir}/frame_{saved:03d}.png\", crop)\n",
    "            saved += 1\n",
    "    cap.release()\n",
    "    return saved\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13a800c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing original (parallel):  15%|█▍        | 147/1000 [01:16<05:38,  2.52it/s]"
     ]
    }
   ],
   "source": [
    "import concurrent.futures\n",
    "ROOT = r\"FaceForensics++_C23\"     # <- change this\n",
    "OUT  = r\"FFprocessed\"              # <- change this\n",
    "\n",
    "folders = [\n",
    "    \"original\",\n",
    "    \"Deepfakes\",\n",
    "    \"FaceSwap\",\n",
    "    \"Face2Face\",\n",
    "    \"NeuralTextures\",\n",
    "    \"FaceShifter\",\n",
    "    \"DeepFakeDetection\"\n",
    "]\n",
    "\n",
    "N_FRAMES = 20  # recommended\n",
    "BATCH_SIZE = 64 # You can increase this if you have more GPU memory\n",
    "\n",
    "def process_one_video(args):\n",
    "    video_path, save_dir, n_frames, batch_size = args\n",
    "    os.makedirs(save_dir, exist_ok=True)\n",
    "    return process_video_full(video_path, save_dir, n_frames, batch_size=batch_size)\n",
    "\n",
    "for folder in folders:\n",
    "    in_folder = os.path.join(ROOT, folder)\n",
    "    out_folder = os.path.join(OUT, folder)\n",
    "    os.makedirs(out_folder, exist_ok=True)\n",
    "\n",
    "    videos = [v for v in os.listdir(in_folder) if v.endswith(\".mp4\")]\n",
    "    video_args = []\n",
    "    for vid in videos:\n",
    "        video_path = os.path.join(in_folder, vid)\n",
    "        save_dir = os.path.join(out_folder, vid.replace(\".mp4\", \"\"))\n",
    "        video_args.append((video_path, save_dir, N_FRAMES, BATCH_SIZE))\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        list(tqdm(executor.map(process_one_video, video_args), total=len(video_args), desc=f\"Processing {folder} (parallel)\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08e94f56",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dl_env (3.11.0)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}