pulkitbuilds007 commited on
Commit
886d291
·
verified ·
1 Parent(s): a0cea18

Delete face_swap_pro.ipynb

Browse files
Files changed (1) hide show
  1. face_swap_pro.ipynb +0 -713
face_swap_pro.ipynb DELETED
@@ -1,713 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "id": "1225004c",
6
- "metadata": {},
7
- "source": [
8
- "# Face swap Pro: enhancer, better blend mask, colour matching, feathered 512px blend\n",
9
- "\n",
10
- "Upgrade of `face_swap_fixed.ipynb`. For every face in every frame it now does this:\n",
11
- "\n",
12
- "1. **Swap** with `inswapper_128` (128px), then re-map the result into a **512px** face crop.\n",
13
- "2. **Better blend mask** = feathered box x **occlusion mask** (XSeg: keeps hands, mics, glasses in front) x **face parser** (BiSeNet: swaps only skin, eyes, nose, mouth, not hair, hats or ears).\n",
14
- "3. **Colour matching**: moves the swapped face's LAB colour and brightness toward the original face.\n",
15
- "4. **Face enhancer** (GFPGAN 1.4) at 512px, blended with the raw swap by `ENHANCE_BLEND`.\n",
16
- "5. **Feathered, enlarged blend**: the 512px result is warped back and alpha-blended with a soft edge.\n",
17
- "6. Frames go straight into ffmpeg (NVENC, else x264), so there is no lossy temp file.\n",
18
- "\n",
19
- "**Run order:** cell 1 once (then restart the kernel), cell 2 once, cell 3, cell 4, cell 5 (preview one frame and tune), cell 6 (full video).\n",
20
- "\n",
21
- "**Tuning (cell 3):** blurry face -> raise `ENHANCE_BLEND`; plastic or off-likeness -> lower it; visible seam -> raise `FEATHER`; skin tone off -> raise `COLOR_STRENGTH`; slow -> turn off `USE_PARSER`, then `USE_OCCLUDER`. Use `MAX_FRAMES` to test on a short clip.\n",
22
- "\n",
23
- "**Licences and consent:** `inswapper_128`, `buffalo_l` and GFPGAN 1.4 are for non-commercial research use as far as I know, so check each model's licence before using output commercially. Only swap faces of people who have consented."
24
- ]
25
- },
26
- {
27
- "cell_type": "code",
28
- "execution_count": 1,
29
- "id": "6cfd6ee4",
30
- "metadata": {},
31
- "outputs": [
32
- {
33
- "name": "stdout",
34
- "output_type": "stream",
35
- "text": [
36
- "Requirement already satisfied: insightface in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (2.1)\n",
37
- "Requirement already satisfied: opencv-python in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (5.0.0.93)\n",
38
- "Requirement already satisfied: numpy in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (2.4.6)\n",
39
- "Requirement already satisfied: tqdm in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (4.68.2)\n",
40
- "Requirement already satisfied: huggingface_hub in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (2.3.0)\n",
41
- "Requirement already satisfied: onnx>=1.13 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from insightface) (1.23.2)\n",
42
- "Requirement already satisfied: onnxruntime in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from insightface) (1.31.1)\n",
43
- "Requirement already satisfied: requests in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from insightface) (2.34.2)\n",
44
- "Requirement already satisfied: scipy in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from insightface) (1.18.0)\n",
45
- "Requirement already satisfied: scikit-image in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from insightface) (0.26.0)\n",
46
- "Requirement already satisfied: colorama in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from tqdm) (0.4.6)\n",
47
- "Requirement already satisfied: click<9.0.0,>=8.4.2 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (8.5.0)\n",
48
- "Requirement already satisfied: filelock>=3.10.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (3.29.4)\n",
49
- "Requirement already satisfied: fsspec>=2023.5.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (2026.4.0)\n",
50
- "Requirement already satisfied: hf-xet<2.0.0,>=1.6.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (1.7.0)\n",
51
- "Requirement already satisfied: httpx2<3,>=2.0.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (2.16.0)\n",
52
- "Requirement already satisfied: packaging>=20.9 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (26.0)\n",
53
- "Requirement already satisfied: pyyaml>=5.1 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (6.0.3)\n",
54
- "Requirement already satisfied: typing-extensions>=4.1.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from huggingface_hub) (4.16.0)\n",
55
- "Requirement already satisfied: anyio>=4.10 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from httpx2<3,>=2.0.0->huggingface_hub) (4.12.1)\n",
56
- "Requirement already satisfied: httpcore2==2.16.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from httpx2<3,>=2.0.0->huggingface_hub) (2.16.0)\n",
57
- "Requirement already satisfied: idna>=3.18 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from httpx2<3,>=2.0.0->huggingface_hub) (3.18)\n",
58
- "Requirement already satisfied: truststore>=0.10 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from httpx2<3,>=2.0.0->huggingface_hub) (0.10.4)\n",
59
- "Requirement already satisfied: h11>=0.16 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from httpcore2==2.16.0->httpx2<3,>=2.0.0->huggingface_hub) (0.16.0)\n",
60
- "Requirement already satisfied: protobuf>=6.31.1 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnx>=1.13->insightface) (6.33.5)\n",
61
- "Requirement already satisfied: ml_dtypes>=0.5.4 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnx>=1.13->insightface) (0.6.0)\n",
62
- "Requirement already satisfied: flatbuffers in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime->insightface) (25.12.19)\n",
63
- "Requirement already satisfied: charset_normalizer<4,>=2 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from requests->insightface) (3.4.7)\n",
64
- "Requirement already satisfied: urllib3<3,>=1.26 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from requests->insightface) (2.7.0)\n",
65
- "Requirement already satisfied: certifi>=2023.5.7 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from requests->insightface) (2026.7.22)\n",
66
- "Requirement already satisfied: networkx>=3.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from scikit-image->insightface) (3.6.1)\n",
67
- "Requirement already satisfied: pillow>=10.1 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from scikit-image->insightface) (12.3.0)\n",
68
- "Requirement already satisfied: imageio!=2.35.0,>=2.33 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from scikit-image->insightface) (2.37.3)\n",
69
- "Requirement already satisfied: tifffile>=2022.8.12 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from scikit-image->insightface) (2026.6.1)\n",
70
- "Requirement already satisfied: lazy-loader>=0.4 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from scikit-image->insightface) (0.5)\n",
71
- "Requirement already satisfied: onnxruntime-gpu[cuda,cudnn] in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (1.31.1)\n",
72
- "Requirement already satisfied: flatbuffers in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (25.12.19)\n",
73
- "Requirement already satisfied: numpy>=1.21.6 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (2.4.6)\n",
74
- "Requirement already satisfied: packaging in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (26.0)\n",
75
- "Requirement already satisfied: protobuf>=4.25.8 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (6.33.5)\n",
76
- "Requirement already satisfied: nvidia-cuda-nvrtc~=13.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (13.4.92)\n",
77
- "Requirement already satisfied: nvidia-cuda-runtime~=13.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (13.4.92)\n",
78
- "Requirement already satisfied: nvidia-cufft~=12.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (12.4.0.43)\n",
79
- "Requirement already satisfied: nvidia-curand~=10.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (10.4.4.72)\n",
80
- "Requirement already satisfied: nvidia-cudnn-cu13~=9.0 in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from onnxruntime-gpu[cuda,cudnn]) (9.27.0.42)\n",
81
- "Requirement already satisfied: nvidia-cublas in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from nvidia-cudnn-cu13~=9.0->onnxruntime-gpu[cuda,cudnn]) (13.8.0.4)\n",
82
- "Requirement already satisfied: nvidia-nvjitlink in c:\\Users\\pulki\\anaconda3\\Lib\\site-packages (from nvidia-cufft~=12.0->onnxruntime-gpu[cuda,cudnn]) (13.4.92)\n"
83
- ]
84
- }
85
- ],
86
- "source": [
87
- "# ---- CELL 1: one-time setup (run once, then RESTART the kernel) ----\n",
88
- "import sys\n",
89
- "!{sys.executable} -m pip install insightface opencv-python numpy tqdm huggingface_hub\n",
90
- "!{sys.executable} -m pip install \"onnxruntime-gpu[cuda,cudnn]\"\n",
91
- "# Also needs ffmpeg installed and on PATH (check with: ffmpeg -version)\n",
92
- "# No PyTorch needed: the enhancer and mask models run on onnxruntime too.\n"
93
- ]
94
- },
95
- {
96
- "cell_type": "code",
97
- "execution_count": 2,
98
- "id": "fcc99ce4",
99
- "metadata": {},
100
- "outputs": [
101
- {
102
- "data": {
103
- "application/vnd.jupyter.widget-view+json": {
104
- "model_id": "dfb785b6b0b44f2491cb99c675840719",
105
- "version_major": 2,
106
- "version_minor": 0
107
- },
108
- "text/plain": [
109
- "gfpgan_1.4.onnx: 0.00B [00:00, ?B/s]"
110
- ]
111
- },
112
- "metadata": {},
113
- "output_type": "display_data"
114
- },
115
- {
116
- "name": "stdout",
117
- "output_type": "stream",
118
- "text": [
119
- "OK: gfpgan_1.4.onnx\n"
120
- ]
121
- },
122
- {
123
- "data": {
124
- "application/vnd.jupyter.widget-view+json": {
125
- "model_id": "75cf20b20a644aa495bb20ad2b6e1b3e",
126
- "version_major": 2,
127
- "version_minor": 0
128
- },
129
- "text/plain": [
130
- "xseg_1.onnx: 0.00B [00:00, ?B/s]"
131
- ]
132
- },
133
- "metadata": {},
134
- "output_type": "display_data"
135
- },
136
- {
137
- "name": "stdout",
138
- "output_type": "stream",
139
- "text": [
140
- "OK: xseg_1.onnx\n"
141
- ]
142
- },
143
- {
144
- "data": {
145
- "application/vnd.jupyter.widget-view+json": {
146
- "model_id": "7af4265aecaa4d9f9c62316ff690e40c",
147
- "version_major": 2,
148
- "version_minor": 0
149
- },
150
- "text/plain": [
151
- "bisenet_resnet_34.onnx: 0.00B [00:00, ?B/s]"
152
- ]
153
- },
154
- "metadata": {},
155
- "output_type": "display_data"
156
- },
157
- {
158
- "name": "stdout",
159
- "output_type": "stream",
160
- "text": [
161
- "OK: bisenet_resnet_34.onnx\n"
162
- ]
163
- }
164
- ],
165
- "source": [
166
- "# ---- CELL 2: download all models (skips files that already exist) ----\n",
167
- "import os, urllib.request\n",
168
- "from tqdm.auto import tqdm\n",
169
- "from huggingface_hub import hf_hub_download\n",
170
- "\n",
171
- "ROOT = r\"D:\\vid\"\n",
172
- "MODELS_DIR = os.path.join(ROOT, \"models\")\n",
173
- "os.makedirs(MODELS_DIR, exist_ok=True)\n",
174
- "\n",
175
- "# 1) face swapper (same source as before)\n",
176
- "SWAP_MODEL = os.path.join(MODELS_DIR, \"inswapper_128.onnx\")\n",
177
- "if not os.path.exists(SWAP_MODEL):\n",
178
- " hf_hub_download(repo_id=\"ezioruan/inswapper_128.onnx\",\n",
179
- " filename=\"inswapper_128.onnx\", local_dir=MODELS_DIR)\n",
180
- "\n",
181
- "# 2) enhancer + mask models (ONNX, hosted by the FaceFusion project; each tries GitHub, then Hugging Face)\n",
182
- "GH = \"https://github.com/facefusion/facefusion-assets/releases/download\"\n",
183
- "HF = \"https://huggingface.co/facefusion\"\n",
184
- "EXTRA = { # file name -> release/repo tag\n",
185
- " \"gfpgan_1.4.onnx\": \"models-3.0.0\", # face enhancer\n",
186
- " \"xseg_1.onnx\": \"models-3.1.0\", # occlusion mask (hands, mics, glasses...)\n",
187
- " \"bisenet_resnet_34.onnx\": \"models-3.0.0\", # face-region parser (skin/eyes/mouth vs hair/hat)\n",
188
- "}\n",
189
- "\n",
190
- "def download(name, tag):\n",
191
- " dest = os.path.join(MODELS_DIR, name)\n",
192
- " if os.path.exists(dest) and os.path.getsize(dest) > 1_000_000:\n",
193
- " print(\"OK (exists):\", name); return True\n",
194
- " for url in (f\"{GH}/{tag}/{name}\", f\"{HF}/{tag}/resolve/main/{name}\"):\n",
195
- " try:\n",
196
- " tmp = dest + \".part\"\n",
197
- " with tqdm(unit=\"B\", unit_scale=True, desc=name) as bar:\n",
198
- " def hook(blocks, bsize, total):\n",
199
- " if total > 0: bar.total = total\n",
200
- " bar.update(blocks * bsize - bar.n)\n",
201
- " urllib.request.urlretrieve(url, tmp, hook)\n",
202
- " if os.path.getsize(tmp) < 1_000_000:\n",
203
- " raise IOError(\"downloaded file too small\")\n",
204
- " os.replace(tmp, dest); print(\"OK:\", name); return True\n",
205
- " except Exception as e:\n",
206
- " print(f\" failed {url}: {e}\")\n",
207
- " print(f\"!! Could not download {name}. The pipeline will run without that feature.\")\n",
208
- " return False\n",
209
- "\n",
210
- "for n, t in EXTRA.items():\n",
211
- " download(n, t)\n"
212
- ]
213
- },
214
- {
215
- "cell_type": "code",
216
- "execution_count": 3,
217
- "id": "6999bfc2",
218
- "metadata": {},
219
- "outputs": [
220
- {
221
- "name": "stdout",
222
- "output_type": "stream",
223
- "text": [
224
- "inswapper-shape: [1, 3, 128, 128]\n",
225
- "Running on: GPU (CUDA)\n",
226
- " [on] face enhancer (GFPGAN 1.4)\n",
227
- " [on] occlusion mask (XSeg)\n",
228
- " [on] face parser (BiSeNet)\n",
229
- "Setup complete.\n"
230
- ]
231
- }
232
- ],
233
- "source": [
234
- "# ---- CELL 3: config + load models (GPU if it really works, else CPU) ----\n",
235
- "import os, sys, glob, shutil, subprocess, sysconfig\n",
236
- "\n",
237
- "# ---------------- CONFIG ----------------\n",
238
- "ROOT = r\"D:\\vid\"\n",
239
- "SRC_IMG = os.path.join(ROOT, \"source.jpeg\") # face to paste INTO the video\n",
240
- "IN_VID = os.path.join(ROOT, \"input.mp4\")\n",
241
- "OUT_VID = os.path.join(ROOT, \"output_pro.mp4\")\n",
242
- "MODELS_DIR = os.path.join(ROOT, \"models\")\n",
243
- "SWAP_MODEL = os.path.join(MODELS_DIR, \"inswapper_128.onnx\")\n",
244
- "ENH_MODEL = os.path.join(MODELS_DIR, \"gfpgan_1.4.onnx\")\n",
245
- "OCC_MODEL = os.path.join(MODELS_DIR, \"xseg_1.onnx\")\n",
246
- "PARSE_MODEL = os.path.join(MODELS_DIR, \"bisenet_resnet_34.onnx\")\n",
247
- "\n",
248
- "TARGET_IMG = None # optional: photo of the ONE person to replace (None = every face)\n",
249
- "SIM_THRESH = 0.4 # face-match threshold when TARGET_IMG is used\n",
250
- "SMOOTH = 0.6 # landmark smoothing: 0 = off, higher = steadier but laggier\n",
251
- "DET_SIZE = (640, 640)\n",
252
- "\n",
253
- "# ---- quality options ----\n",
254
- "USE_ENHANCER = True # GFPGAN face restoration at 512px\n",
255
- "ENHANCE_BLEND = 0.8 # 1.0 = fully restored face, lower keeps more of the raw swap\n",
256
- "USE_COLOR_MATCH = True # match swapped skin tone / brightness to the original face\n",
257
- "COLOR_STRENGTH = 0.8 # 0 = off, 1 = full match\n",
258
- "USE_OCCLUDER = True # keep hands, mics, glasses etc. in front of the face\n",
259
- "USE_PARSER = True # restrict the swap to skin/eyes/nose/mouth (not hair, hat, ears)\n",
260
- "FEATHER = 0.3 # edge softness of the blend (0.1 = sharp seam, 0.5 = very soft)\n",
261
- "BOX_INSET = 0.10 # fraction of the swap crop trimmed from each edge before feathering\n",
262
- "\n",
263
- "MAX_FRAMES = None # e.g. 150 to process only the first 150 frames while tuning\n",
264
- "# ----------------------------------------\n",
265
- "\n",
266
- "# 1) Make pip-installed NVIDIA DLLs (CUDA / cuDNN) visible to Windows BEFORE importing onnxruntime\n",
267
- "if os.name == \"nt\":\n",
268
- " nv_root = os.path.join(sysconfig.get_paths()[\"purelib\"], \"nvidia\")\n",
269
- " bins = {os.path.dirname(p) for p in glob.glob(os.path.join(nv_root, \"**\", \"*.dll\"), recursive=True)}\n",
270
- " for b in sorted(bins):\n",
271
- " os.environ[\"PATH\"] = b + os.pathsep + os.environ[\"PATH\"]\n",
272
- " try:\n",
273
- " os.add_dll_directory(b)\n",
274
- " except (OSError, AttributeError):\n",
275
- " pass\n",
276
- "\n",
277
- "import warnings\n",
278
- "warnings.filterwarnings(\"ignore\", category=FutureWarning) # harmless scikit-image notice from insightface\n",
279
- "\n",
280
- "import cv2\n",
281
- "import numpy as np\n",
282
- "import onnxruntime as ort\n",
283
- "import insightface\n",
284
- "from insightface.app import FaceAnalysis\n",
285
- "from tqdm import tqdm\n",
286
- "\n",
287
- "if hasattr(ort, \"preload_dlls\"):\n",
288
- " try:\n",
289
- " ort.preload_dlls()\n",
290
- " except Exception as e:\n",
291
- " print(\"preload_dlls warning:\", e)\n",
292
- "\n",
293
- "# 2) Input checks\n",
294
- "for p in [SRC_IMG, IN_VID, SWAP_MODEL] + ([TARGET_IMG] if TARGET_IMG else []):\n",
295
- " assert os.path.exists(p), f\"File not found: {p}\"\n",
296
- "assert shutil.which(\"ffmpeg\"), \"ffmpeg not found in PATH.\"\n",
297
- "\n",
298
- "# 3) Build face detector + swapper; use the GPU if it really works, otherwise fall back to CPU\n",
299
- "def build(providers):\n",
300
- " app = FaceAnalysis(name=\"buffalo_l\", providers=providers,\n",
301
- " allowed_modules=[\"detection\", \"recognition\"])\n",
302
- " app.prepare(ctx_id=0 if providers[0] != \"CPUExecutionProvider\" else -1, det_size=DET_SIZE)\n",
303
- " swapper = insightface.model_zoo.get_model(SWAP_MODEL, providers=providers)\n",
304
- " return app, swapper\n",
305
- "\n",
306
- "def selftest(app, swapper):\n",
307
- " \"\"\"Run one dummy inference per model; raises if CUDA/cuDNN can't actually load.\"\"\"\n",
308
- " app.det_model.detect(np.zeros((640, 640, 3), dtype=np.uint8), max_num=1)\n",
309
- " feeds = {}\n",
310
- " for inp in swapper.session.get_inputs():\n",
311
- " shape = [d if isinstance(d, int) else 1 for d in inp.shape]\n",
312
- " feeds[inp.name] = np.zeros(shape, dtype=np.float32)\n",
313
- " swapper.session.run(None, feeds)\n",
314
- "\n",
315
- "USING_GPU = False\n",
316
- "if \"CUDAExecutionProvider\" in ort.get_available_providers():\n",
317
- " try:\n",
318
- " app, swapper = build([\"CUDAExecutionProvider\", \"CPUExecutionProvider\"])\n",
319
- " selftest(app, swapper)\n",
320
- " USING_GPU = True\n",
321
- " except Exception as e:\n",
322
- " print(\"GPU failed -> falling back to CPU.\\nReason:\", str(e).splitlines()[-1][:300])\n",
323
- "if not USING_GPU:\n",
324
- " app, swapper = build([\"CPUExecutionProvider\"])\n",
325
- "ACTIVE_PROVIDERS = ([\"CUDAExecutionProvider\", \"CPUExecutionProvider\"] if USING_GPU\n",
326
- " else [\"CPUExecutionProvider\"])\n",
327
- "print(\"Running on:\", \"GPU (CUDA)\" if USING_GPU else \"CPU (slow)\")\n",
328
- "\n",
329
- "# 4) Optional models: enhancer, occlusion mask, face parser (a missing file just disables that feature)\n",
330
- "def load_optional(enabled, path, label):\n",
331
- " if not enabled:\n",
332
- " return None\n",
333
- " if not os.path.exists(path):\n",
334
- " print(f\" [off] {label}: model not found ({os.path.basename(path)}). Run cell 2 to download it.\")\n",
335
- " return None\n",
336
- " so = ort.SessionOptions()\n",
337
- " so.log_severity_level = 3\n",
338
- " sess = ort.InferenceSession(path, sess_options=so, providers=ACTIVE_PROVIDERS)\n",
339
- " print(f\" [on] {label}\")\n",
340
- " return sess\n",
341
- "\n",
342
- "enh_sess = load_optional(USE_ENHANCER, ENH_MODEL, \"face enhancer (GFPGAN 1.4)\")\n",
343
- "occ_sess = load_optional(USE_OCCLUDER, OCC_MODEL, \"occlusion mask (XSeg)\")\n",
344
- "parse_sess = load_optional(USE_PARSER, PARSE_MODEL, \"face parser (BiSeNet)\")\n",
345
- "\n",
346
- "# 5) Source / target identity\n",
347
- "def load_img(path):\n",
348
- " img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)\n",
349
- " assert img is not None, f\"Could not read image: {path}\"\n",
350
- " return img\n",
351
- "\n",
352
- "def largest_face(img, name):\n",
353
- " faces = app.get(img)\n",
354
- " assert len(faces) > 0, f\"No face detected in {name}. Use a clear, front-facing photo.\"\n",
355
- " return max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))\n",
356
- "\n",
357
- "src_face = largest_face(load_img(SRC_IMG), \"source image\")\n",
358
- "target_emb = largest_face(load_img(TARGET_IMG), \"target image\").normed_embedding if TARGET_IMG else None\n",
359
- "print(\"Setup complete.\")\n"
360
- ]
361
- },
362
- {
363
- "cell_type": "code",
364
- "execution_count": 4,
365
- "id": "6ce4551e",
366
- "metadata": {},
367
- "outputs": [
368
- {
369
- "name": "stdout",
370
- "output_type": "stream",
371
- "text": [
372
- "Pipeline ready.\n"
373
- ]
374
- }
375
- ],
376
- "source": [
377
- "# ---- CELL 4: the upgraded face pipeline (run once; no output) ----\n",
378
- "CROP = 512 # working resolution for enhancement and blending\n",
379
- "\n",
380
- "# Standard 5-point face template used by GFPGAN (512x512): eyes, nose, mouth corners\n",
381
- "FFHQ_512 = np.array([[192.98138, 239.94708], [318.90277, 240.19360], [256.63416, 314.01935],\n",
382
- " [201.26117, 371.41043], [313.08905, 371.15118]], dtype=np.float32)\n",
383
- "PARSE_KEEP = [1, 2, 3, 4, 5, 6, 10, 11, 12, 13] # skin, brows, eyes, glasses, nose, mouth, lips\n",
384
- "_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)\n",
385
- "_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)\n",
386
- "\n",
387
- "def _to3(M):\n",
388
- " return np.vstack([M, [0, 0, 1]]).astype(np.float64)\n",
389
- "\n",
390
- "def ffhq_matrix(kps):\n",
391
- " \"\"\"Similarity transform: frame coordinates -> 512x512 enhancer crop.\"\"\"\n",
392
- " M, _ = cv2.estimateAffinePartial2D(kps.astype(np.float32), FFHQ_512, method=cv2.LMEDS)\n",
393
- " return M\n",
394
- "\n",
395
- "# ---------- models ----------\n",
396
- "def enhance_face(img512):\n",
397
- " x = img512[:, :, ::-1].astype(np.float32) / 255.0 # BGR -> RGB\n",
398
- " x = ((x - 0.5) / 0.5).transpose(2, 0, 1)[None]\n",
399
- " y = enh_sess.run(None, {enh_sess.get_inputs()[0].name: x})[0][0]\n",
400
- " y = (np.clip(y, -1, 1) + 1) / 2\n",
401
- " return (y.transpose(1, 2, 0) * 255.0).round().astype(np.uint8)[:, :, ::-1]\n",
402
- "\n",
403
- "def _soft(m):\n",
404
- " return (cv2.GaussianBlur(m.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2\n",
405
- "\n",
406
- "def occlusion_mask(crop512):\n",
407
- " \"\"\"1 = visible face, 0 = something (hand, mic, glasses frame...) is in front of it.\"\"\"\n",
408
- " x = cv2.resize(crop512, (256, 256))[None].astype(np.float32) / 255.0 # NHWC\n",
409
- " m = occ_sess.run(None, {occ_sess.get_inputs()[0].name: x})[0][0, :, :, 0]\n",
410
- " return _soft(cv2.resize(m, (CROP, CROP)))\n",
411
- "\n",
412
- "def parser_mask(crop512):\n",
413
- " \"\"\"1 = skin / eyes / brows / nose / mouth, 0 = hair, hat, ears, neck, background.\"\"\"\n",
414
- " x = cv2.resize(crop512, (512, 512))[:, :, ::-1].astype(np.float32) / 255.0\n",
415
- " x = ((x - _MEAN) / _STD).transpose(2, 0, 1)[None].astype(np.float32)\n",
416
- " out = parse_sess.run(None, {parse_sess.get_inputs()[0].name: x})[0][0] # (19, H, W)\n",
417
- " m = np.isin(out.argmax(0), PARSE_KEEP).astype(np.float32)\n",
418
- " return _soft(cv2.resize(m, (CROP, CROP)))\n",
419
- "\n",
420
- "def box_mask(T):\n",
421
- " \"\"\"Feathered box covering the area the swapper actually generated, mapped into the 512 crop.\"\"\"\n",
422
- " inset = max(int(128 * BOX_INSET), 1)\n",
423
- " m = np.zeros((128, 128), np.float32)\n",
424
- " m[inset:-inset, inset:-inset] = 1.0\n",
425
- " m = cv2.warpAffine(m, T, (CROP, CROP), flags=cv2.INTER_LINEAR)\n",
426
- " return cv2.GaussianBlur(m, (0, 0), max(CROP * 0.5 * FEATHER * 0.25, 0.5))\n",
427
- "\n",
428
- "# ---------- colour matching ----------\n",
429
- "def color_match(swapped, original, mask):\n",
430
- " \"\"\"Move the swapped face's LAB mean/std toward the original face's (inside the mask).\"\"\"\n",
431
- " reg = mask > 0.5\n",
432
- " if reg.sum() < 2000:\n",
433
- " return swapped\n",
434
- " s = cv2.cvtColor(swapped.astype(np.float32) / 255.0, cv2.COLOR_BGR2LAB)\n",
435
- " o = cv2.cvtColor(original.astype(np.float32) / 255.0, cv2.COLOR_BGR2LAB)\n",
436
- " out = s.copy()\n",
437
- " for c in range(3):\n",
438
- " sm, ss = s[..., c][reg].mean(), s[..., c][reg].std() + 1e-6\n",
439
- " om, os_ = o[..., c][reg].mean(), o[..., c][reg].std() + 1e-6\n",
440
- " out[..., c] = (s[..., c] - sm) * np.clip(os_ / ss, 0.75, 1.25) + om\n",
441
- " out = s + COLOR_STRENGTH * (out - s)\n",
442
- " return np.clip(cv2.cvtColor(out, cv2.COLOR_LAB2BGR) * 255.0, 0, 255).astype(np.uint8)\n",
443
- "\n",
444
- "# ---------- paste back ----------\n",
445
- "def paste(frame, face512, mask512, M):\n",
446
- " \"\"\"Warp the 512 result and its mask back into the frame and alpha-blend (ROI only, for speed).\"\"\"\n",
447
- " H, W = frame.shape[:2]\n",
448
- " IM = cv2.invertAffineTransform(M)\n",
449
- " scale = float(np.sqrt(abs(np.linalg.det(IM[:, :2]))))\n",
450
- " if scale < 0.7: # small face in a big frame: downsample first to avoid aliasing\n",
451
- " n = max(int(round(CROP * scale * 1.5)), 64)\n",
452
- " face512 = cv2.resize(face512, (n, n), interpolation=cv2.INTER_AREA)\n",
453
- " mask512 = cv2.resize(mask512, (n, n), interpolation=cv2.INTER_AREA)\n",
454
- " IM = (_to3(IM) @ np.diag([CROP / n, CROP / n, 1.0]))[:2]\n",
455
- " n = face512.shape[0]\n",
456
- " corners = np.array([[0, 0], [n, 0], [n, n], [0, n]], np.float32)\n",
457
- " pts = cv2.transform(corners[None], IM)[0]\n",
458
- " x0, y0 = np.floor(pts.min(0)).astype(int)\n",
459
- " x1, y1 = np.ceil(pts.max(0)).astype(int)\n",
460
- " x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, W), min(y1, H)\n",
461
- " if x1 - x0 < 2 or y1 - y0 < 2:\n",
462
- " return frame\n",
463
- " IMr = IM.copy()\n",
464
- " IMr[0, 2] -= x0\n",
465
- " IMr[1, 2] -= y0\n",
466
- " size = (x1 - x0, y1 - y0)\n",
467
- " f = cv2.warpAffine(face512, IMr, size, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)\n",
468
- " m = cv2.warpAffine(mask512, IMr, size, flags=cv2.INTER_LINEAR)[..., None]\n",
469
- " roi = frame[y0:y1, x0:x1].astype(np.float32)\n",
470
- " frame[y0:y1, x0:x1] = (roi * (1 - m) + f.astype(np.float32) * m).round().astype(np.uint8)\n",
471
- " return frame\n",
472
- "\n",
473
- "# ---------- one face ----------\n",
474
- "def swap_one(src_frame, out, face):\n",
475
- " bgr_fake, M_arc = swapper.get(src_frame, face, src_face, paste_back=False) # raw 128px swap\n",
476
- " M = ffhq_matrix(face.kps)\n",
477
- " if M is None:\n",
478
- " return out\n",
479
- " T = (_to3(M) @ np.linalg.inv(_to3(M_arc)))[:2] # 128 swap crop -> 512 crop\n",
480
- " orig512 = cv2.warpAffine(src_frame, M, (CROP, CROP), flags=cv2.INTER_CUBIC,\n",
481
- " borderMode=cv2.BORDER_REPLICATE)\n",
482
- " swap512 = cv2.warpAffine(bgr_fake, T, (CROP, CROP), flags=cv2.INTER_CUBIC,\n",
483
- " borderMode=cv2.BORDER_REPLICATE)\n",
484
- " mask = box_mask(T)\n",
485
- " if occ_sess is not None:\n",
486
- " mask = np.minimum(mask, occlusion_mask(orig512))\n",
487
- " if parse_sess is not None:\n",
488
- " mask = np.minimum(mask, parser_mask(orig512))\n",
489
- " if USE_COLOR_MATCH and COLOR_STRENGTH > 0:\n",
490
- " swap512 = color_match(swap512, orig512, mask)\n",
491
- " if enh_sess is not None:\n",
492
- " enh = enhance_face(swap512)\n",
493
- " swap512 = cv2.addWeighted(enh, ENHANCE_BLEND, swap512, 1 - ENHANCE_BLEND, 0)\n",
494
- " return paste(out, swap512, mask, M)\n",
495
- "\n",
496
- "# ---------- one frame ----------\n",
497
- "prev_kps = []\n",
498
- "\n",
499
- "def smooth_kps(face, prev, new_prev, max_dim):\n",
500
- " c = face.kps.mean(axis=0)\n",
501
- " best, best_d = None, 1e9\n",
502
- " for pk in prev:\n",
503
- " d = np.linalg.norm(pk.mean(axis=0) - c)\n",
504
- " if d < best_d:\n",
505
- " best, best_d = pk, d\n",
506
- " if best is not None and best_d < 0.15 * max_dim:\n",
507
- " face.kps = SMOOTH * best + (1 - SMOOTH) * face.kps\n",
508
- " new_prev.append(face.kps.copy())\n",
509
- "\n",
510
- "def process_frame(frame):\n",
511
- " global prev_kps\n",
512
- " out, new_prev, n = frame.copy(), [], 0\n",
513
- " for face in app.get(frame):\n",
514
- " if target_emb is not None and float(np.dot(face.normed_embedding, target_emb)) < SIM_THRESH:\n",
515
- " continue\n",
516
- " if SMOOTH > 0:\n",
517
- " smooth_kps(face, prev_kps, new_prev, max(frame.shape[:2]))\n",
518
- " out = swap_one(frame, out, face) # every face is cut from the ORIGINAL frame\n",
519
- " n += 1\n",
520
- " prev_kps = new_prev\n",
521
- " return out, n\n",
522
- "print(\"Pipeline ready.\")\n"
523
- ]
524
- },
525
- {
526
- "cell_type": "code",
527
- "execution_count": 6,
528
- "id": "f678bfbb",
529
- "metadata": {},
530
- "outputs": [
531
- {
532
- "name": "stdout",
533
- "output_type": "stream",
534
- "text": [
535
- "Using frame 280 (1 face(s))\n"
536
- ]
537
- },
538
- ],
539
- "source": [
540
- "# ---- CELL 5: quick preview on ONE frame (tune the settings here before the full video) ----\n",
541
- "from IPython.display import display, Image as IPyImage\n",
542
- "\n",
543
- "PREVIEW_FRAME = 30 # which frame of the video to test\n",
544
- "\n",
545
- "def make_preview(frame):\n",
546
- " global prev_kps\n",
547
- " prev_kps = []\n",
548
- " faces = [f for f in app.get(frame)\n",
549
- " if target_emb is None or float(np.dot(f.normed_embedding, target_emb)) >= SIM_THRESH]\n",
550
- " assert faces, \"No face found in this frame. Try another PREVIEW_FRAME.\"\n",
551
- " face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))\n",
552
- " base = swapper.get(frame.copy(), face, src_face, paste_back=True) # the old, basic result\n",
553
- " new, _ = process_frame(frame) # the upgraded result\n",
554
- " x0, y0, x1, y1 = face.bbox.astype(int)\n",
555
- " cx, cy, half = (x0 + x1) // 2, (y0 + y1) // 2, int(max(x1 - x0, y1 - y0) * 0.9)\n",
556
- " H, W = frame.shape[:2]\n",
557
- " a, b, c, d = max(cy - half, 0), min(cy + half, H), max(cx - half, 0), min(cx + half, W)\n",
558
- " panels = [cv2.resize(im[a:b, c:d], (480, 480), interpolation=cv2.INTER_CUBIC) for im in (frame, base, new)]\n",
559
- " for p, t in zip(panels, [\"original\", \"basic swap\", \"upgraded\"]):\n",
560
- " cv2.putText(p, t, (12, 32), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 4, cv2.LINE_AA)\n",
561
- " cv2.putText(p, t, (12, 32), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 2, cv2.LINE_AA)\n",
562
- " return np.hstack(panels)\n",
563
- "\n",
564
- "def find_preview_frame(start=0, step=5, max_tries=300):\n",
565
- " cap = cv2.VideoCapture(IN_VID)\n",
566
- " total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
567
- " seen_any, idx = 0, start\n",
568
- " for _ in range(max_tries):\n",
569
- " if total > 0 and idx >= total:\n",
570
- " break\n",
571
- " cap.set(cv2.CAP_PROP_POS_FRAMES, idx)\n",
572
- " ok, fr = cap.read()\n",
573
- " if not ok:\n",
574
- " break\n",
575
- " faces = app.get(fr)\n",
576
- " seen_any += len(faces)\n",
577
- " keep = [f for f in faces\n",
578
- " if target_emb is None or float(np.dot(f.normed_embedding, target_emb)) >= SIM_THRESH]\n",
579
- " if keep:\n",
580
- " cap.release()\n",
581
- " print(f\"Using frame {idx} ({len(keep)} face(s))\")\n",
582
- " return fr\n",
583
- " idx += step\n",
584
- " cap.release()\n",
585
- " print(f\"No usable face found. Frames in video: {total}, faces detected at all: {seen_any}\")\n",
586
- " if seen_any > 0 and target_emb is not None:\n",
587
- " print(\"Faces exist but none match TARGET_IMG. Lower SIM_THRESH (try 0.25) or set TARGET_IMG = None.\")\n",
588
- " elif seen_any == 0:\n",
589
- " print(\"The detector sees no faces. Try DET_SIZE = (1024, 1024) in cell 3, and check the video isn't sideways or too dark.\")\n",
590
- " return None\n",
591
- "\n",
592
- "test_frame = find_preview_frame(start=PREVIEW_FRAME)\n",
593
- "assert test_frame is not None, \"No frame to preview. See the messages above.\"\n",
594
- "panel = make_preview(test_frame)\n",
595
- "cv2.imwrite(os.path.join(ROOT, \"preview.jpg\"), panel)\n",
596
- "display(IPyImage(data=cv2.imencode(\".jpg\", panel)[1].tobytes()))\n"
597
- ]
598
- },
599
- {
600
- "cell_type": "code",
601
- "execution_count": 7,
602
- "id": "c251acd6",
603
- "metadata": {},
604
- "outputs": [
605
- {
606
- "name": "stdout",
607
- "output_type": "stream",
608
- "text": [
609
- "Encoding with NVENC\n"
610
- ]
611
- },
612
- {
613
- "name": "stderr",
614
- "output_type": "stream",
615
- "text": [
616
- "Swapping + enhancing: 100%|██████████| 23890/23890 [1:52:13<00:00, 3.55it/s] \n"
617
- ]
618
- },
619
- {
620
- "name": "stdout",
621
- "output_type": "stream",
622
- "text": [
623
- "Frames: 23890, faces swapped: 21432\n",
624
- "Saved: D:\\vid\\output_pro.mp4\n"
625
- ]
626
- }
627
- ],
628
- "source": [
629
- "# ---- CELL 6: process the whole video (frames are piped straight into ffmpeg; no temp file) ----\n",
630
- "def pick_encoder():\n",
631
- " \"\"\"NVENC if this machine can really use it, otherwise CPU x264.\"\"\"\n",
632
- " r = subprocess.run([\"ffmpeg\", \"-v\", \"error\", \"-f\", \"lavfi\", \"-i\", \"color=c=black:s=256x256:d=0.1\",\n",
633
- " \"-c:v\", \"h264_nvenc\", \"-f\", \"null\", \"-\"], capture_output=True)\n",
634
- " if r.returncode == 0:\n",
635
- " return [\"-c:v\", \"h264_nvenc\", \"-preset\", \"p5\", \"-rc\", \"vbr\", \"-cq\", \"18\", \"-b:v\", \"0\"], \"NVENC\"\n",
636
- " return [\"-c:v\", \"libx264\", \"-preset\", \"medium\", \"-crf\", \"17\"], \"x264 (CPU)\"\n",
637
- "\n",
638
- "cap = cv2.VideoCapture(IN_VID)\n",
639
- "assert cap.isOpened(), f\"Could not open video: {IN_VID}\"\n",
640
- "fps = cap.get(cv2.CAP_PROP_FPS) or 25\n",
641
- "total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
642
- "ok, frame = cap.read()\n",
643
- "assert ok, \"Could not read the first frame.\"\n",
644
- "h, w = frame.shape[:2] # real size after any rotation metadata\n",
645
- "if MAX_FRAMES:\n",
646
- " total = min(total, MAX_FRAMES) if total > 0 else MAX_FRAMES\n",
647
- "\n",
648
- "venc, enc_name = pick_encoder()\n",
649
- "log_path = os.path.join(ROOT, \"ffmpeg_log.txt\")\n",
650
- "enc_cmd = [\"ffmpeg\", \"-y\", \"-v\", \"error\",\n",
651
- " \"-f\", \"rawvideo\", \"-pix_fmt\", \"bgr24\", \"-s\", f\"{w}x{h}\", \"-framerate\", f\"{fps:.6f}\", \"-i\", \"-\",\n",
652
- " \"-i\", IN_VID, \"-map\", \"0:v:0\", \"-map\", \"1:a:0?\",\n",
653
- " \"-vf\", \"pad=ceil(iw/2)*2:ceil(ih/2)*2\",\n",
654
- " *venc, \"-pix_fmt\", \"yuv420p\", \"-c:a\", \"aac\", \"-b:a\", \"192k\", \"-shortest\", OUT_VID]\n",
655
- "enc = subprocess.Popen(enc_cmd, stdin=subprocess.PIPE, stderr=open(log_path, \"wb\"))\n",
656
- "print(f\"Encoding with {enc_name}\")\n",
657
- "\n",
658
- "prev_kps = []\n",
659
- "n_frames = n_swapped = 0\n",
660
- "try:\n",
661
- " pbar = tqdm(total=total if total > 0 else None, desc=\"Swapping + enhancing\")\n",
662
- " while True:\n",
663
- " out, n = process_frame(frame)\n",
664
- " enc.stdin.write(np.ascontiguousarray(out).tobytes())\n",
665
- " n_swapped += n\n",
666
- " n_frames += 1\n",
667
- " pbar.update(1)\n",
668
- " if MAX_FRAMES and n_frames >= MAX_FRAMES:\n",
669
- " break\n",
670
- " ok, frame = cap.read()\n",
671
- " if not ok:\n",
672
- " break\n",
673
- " pbar.close()\n",
674
- "except BrokenPipeError:\n",
675
- " print(\"ffmpeg stopped early. Log:\\n\", open(log_path, errors=\"ignore\").read()[-1500:])\n",
676
- "finally:\n",
677
- " cap.release()\n",
678
- " try:\n",
679
- " enc.stdin.close()\n",
680
- " except Exception:\n",
681
- " pass\n",
682
- " enc.wait()\n",
683
- "\n",
684
- "print(f\"Frames: {n_frames}, faces swapped: {n_swapped}\")\n",
685
- "if enc.returncode == 0:\n",
686
- " print(\"Saved:\", OUT_VID)\n",
687
- "else:\n",
688
- " print(\"ffmpeg error:\\n\", open(log_path, errors=\"ignore\").read()[-1500:])\n"
689
- ]
690
- }
691
- ],
692
- "metadata": {
693
- "kernelspec": {
694
- "display_name": "base",
695
- "language": "python",
696
- "name": "python3"
697
- },
698
- "language_info": {
699
- "codemirror_mode": {
700
- "name": "ipython",
701
- "version": 3
702
- },
703
- "file_extension": ".py",
704
- "mimetype": "text/x-python",
705
- "name": "python",
706
- "nbconvert_exporter": "python",
707
- "pygments_lexer": "ipython3",
708
- "version": "3.14.6"
709
- }
710
- },
711
- "nbformat": 4,
712
- "nbformat_minor": 5
713
- }