devkunalnaik commited on
Commit
4a9cb39
Β·
1 Parent(s): de1deba

Enhance: CodeFormer ONNX + ESPCN SR + u2net_human_seg + CRF18 unsharp video

Browse files
processors/body_swap.py CHANGED
@@ -31,16 +31,27 @@ class BodySwapper:
31
  Replaces the body in *target_bgr* with the body from *source_bgr*.
32
  """
33
 
34
- # ── Private helpers ───────────────────────────────────────────────────────
35
-
36
- @staticmethod
37
- def _segment(bgr: np.ndarray) -> np.ndarray:
38
- """Return uint8 single-channel person mask via rembg (UΒ²-Net)."""
 
 
 
 
 
 
 
 
 
 
 
39
  from rembg import remove
40
 
41
- pil = Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
42
- result = remove(pil, only_mask=True)
43
- mask = np.array(result)
44
  if mask.ndim == 3:
45
  mask = mask[:, :, 0]
46
  return mask
@@ -147,12 +158,11 @@ class BodySwapper:
147
  # ── Private helpers ───────────────────────────────────────────────────────
148
 
149
  def _segment(self, bgr: np.ndarray) -> np.ndarray:
150
- """Return a uint8 single-channel person mask via rembg."""
151
  from rembg import remove
152
-
153
- pil = Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
154
- result = remove(pil, only_mask=True)
155
- mask = np.array(result)
156
  if mask.ndim == 3:
157
  mask = mask[:, :, 0]
158
  return mask
 
31
  Replaces the body in *target_bgr* with the body from *source_bgr*.
32
  """
33
 
34
+ _rembg_session = None # shared across instances; loaded once
35
+
36
+ @classmethod
37
+ def _get_session(cls):
38
+ """Lazy-load the u2net_human_seg rembg session (better than general u2net)."""
39
+ if cls._rembg_session is None:
40
+ from rembg import new_session
41
+ print("[BodySwapper] Loading u2net_human_seg segmentation model …")
42
+ cls._rembg_session = new_session("u2net_human_seg")
43
+ return cls._rembg_session
44
+
45
+ # ── Private helpers ─────────────────────────────────────────────────
46
+
47
+ @classmethod
48
+ def _segment(cls, bgr: np.ndarray) -> np.ndarray:
49
+ """Return uint8 single-channel person mask via rembg u2net_human_seg."""
50
  from rembg import remove
51
 
52
+ pil = Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
53
+ result = remove(pil, only_mask=True, session=cls._get_session())
54
+ mask = np.array(result)
55
  if mask.ndim == 3:
56
  mask = mask[:, :, 0]
57
  return mask
 
158
  # ── Private helpers ───────────────────────────────────────────────────────
159
 
160
  def _segment(self, bgr: np.ndarray) -> np.ndarray:
161
+ """Return a uint8 single-channel person mask via rembg u2net_human_seg."""
162
  from rembg import remove
163
+ pil = Image.fromarray(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
164
+ result = remove(pil, only_mask=True, session=self._get_session())
165
+ mask = np.array(result)
 
166
  if mask.ndim == 3:
167
  mask = mask[:, :, 0]
168
  return mask
processors/face_swap.py CHANGED
@@ -17,7 +17,9 @@ from pathlib import Path
17
  MODELS_DIR = Path(__file__).parent.parent / "models"
18
  MODELS_DIR.mkdir(exist_ok=True)
19
 
20
- INSWAPPER_PATH = MODELS_DIR / "inswapper_128.onnx"
 
 
21
 
22
  # Public mirrors β€” tried in order until one succeeds
23
  _INSWAPPER_URLS = [
@@ -81,18 +83,69 @@ def _download_inswapper() -> None:
81
  )
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # ── Main class ────────────────────────────────────────────────────────────────
85
 
86
  class FaceSwapper:
87
  """
88
  Swaps the dominant face from a source image onto every detected face in
89
- the target image. Optionally runs GFPGAN to restore/enhance face quality.
 
90
  """
91
 
92
  def __init__(self):
93
- self._app = None # InsightFace FaceAnalysis
94
- self._swapper = None # inswapper ONNX model
95
- self._ready = False
 
 
96
 
97
  # ── Lazy initialisation ───────────────────────────────────────────────────
98
 
@@ -174,6 +227,125 @@ class FaceSwapper:
174
 
175
  return result
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  # ── Public API ────────────────────────────────────────────────────────────
178
 
179
  def swap(
@@ -221,9 +393,9 @@ class FaceSwapper:
221
  result, tgt_face, source_face, paste_back=True
222
  )
223
 
224
- # Always apply OpenCV enhancement β€” no extra deps needed
225
  if enhance:
226
- result = self._enhance_opencv(result, target_faces)
227
 
228
  # If we downscaled, upscale back to original resolution with Lanczos
229
  if scale_down < 1.0:
@@ -294,7 +466,7 @@ class FaceSwapper:
294
  result = self._swapper.get(result, tgt_face, source_face, paste_back=True)
295
 
296
  if enhance:
297
- result = self._enhance_opencv(result, target_faces)
298
 
299
  # Scale back up to original frame size
300
  if scale_down < 1.0:
 
17
  MODELS_DIR = Path(__file__).parent.parent / "models"
18
  MODELS_DIR.mkdir(exist_ok=True)
19
 
20
+ INSWAPPER_PATH = MODELS_DIR / "inswapper_128.onnx"
21
+ CODEFORMER_PATH = MODELS_DIR / "codeformer.onnx"
22
+ ESPCN_PATH = MODELS_DIR / "ESPCN_x2.pb"
23
 
24
  # Public mirrors β€” tried in order until one succeeds
25
  _INSWAPPER_URLS = [
 
83
  )
84
 
85
 
86
+ def _download_codeformer() -> None:
87
+ """Download CodeFormer ONNX model (~56 MB)."""
88
+ if CODEFORMER_PATH.exists() and CODEFORMER_PATH.stat().st_size > 50_000_000:
89
+ return
90
+ urls = [
91
+ "https://github.com/facefusion/facefusion-assets/releases/download/models/codeformer.onnx",
92
+ ]
93
+ for url in urls:
94
+ try:
95
+ print(f"[FaceSwapper] Downloading CodeFormer from {url} …")
96
+ resp = requests.get(url, stream=True, timeout=300)
97
+ resp.raise_for_status()
98
+ with open(CODEFORMER_PATH, "wb") as f:
99
+ for chunk in resp.iter_content(65536):
100
+ f.write(chunk)
101
+ if CODEFORMER_PATH.stat().st_size > 50_000_000:
102
+ print("[FaceSwapper] CodeFormer ready.")
103
+ return
104
+ CODEFORMER_PATH.unlink(missing_ok=True)
105
+ except Exception as e:
106
+ print(f"[FaceSwapper] CodeFormer download failed: {e}")
107
+ CODEFORMER_PATH.unlink(missing_ok=True)
108
+ print("[FaceSwapper] CodeFormer unavailable β€” falling back to OpenCV enhancement.")
109
+
110
+
111
+ def _download_espcn() -> None:
112
+ """Download ESPCN x2 super-resolution model (~100 KB)."""
113
+ if ESPCN_PATH.exists() and ESPCN_PATH.stat().st_size > 50_000:
114
+ return
115
+ urls = [
116
+ "https://github.com/fannymonori/TF-ESPCN/raw/master/export/ESPCN_x2.pb",
117
+ ]
118
+ for url in urls:
119
+ try:
120
+ print(f"[FaceSwapper] Downloading ESPCN SR model from {url} …")
121
+ resp = requests.get(url, timeout=60)
122
+ resp.raise_for_status()
123
+ ESPCN_PATH.write_bytes(resp.content)
124
+ if ESPCN_PATH.stat().st_size > 50_000:
125
+ print("[FaceSwapper] ESPCN SR model ready.")
126
+ return
127
+ ESPCN_PATH.unlink(missing_ok=True)
128
+ except Exception as e:
129
+ print(f"[FaceSwapper] ESPCN download failed: {e}")
130
+ ESPCN_PATH.unlink(missing_ok=True)
131
+ print("[FaceSwapper] ESPCN unavailable β€” skipping super-resolution step.")
132
+
133
+
134
  # ── Main class ────────────────────────────────────────────────────────────────
135
 
136
  class FaceSwapper:
137
  """
138
  Swaps the dominant face from a source image onto every detected face in
139
+ the target image. Optionally runs CodeFormer (ONNX) + ESPCN super-res
140
+ for ultra-realistic high-definition output.
141
  """
142
 
143
  def __init__(self):
144
+ self._app = None # InsightFace FaceAnalysis
145
+ self._swapper = None # inswapper ONNX model
146
+ self._codeformer = None # CodeFormer ONNX session
147
+ self._sr = None # ESPCN DNN super-res (opencv-contrib)
148
+ self._ready = False
149
 
150
  # ── Lazy initialisation ───────────────────────────────────────────────────
151
 
 
227
 
228
  return result
229
 
230
+ # ── CodeFormer ONNX enhancement ───────────────────────────────────────────
231
+
232
+ def _load_codeformer(self):
233
+ """Lazy-load CodeFormer ONNX session. Returns None if unavailable."""
234
+ if self._codeformer is not None:
235
+ return self._codeformer
236
+ try:
237
+ _download_codeformer()
238
+ if not CODEFORMER_PATH.exists():
239
+ return None
240
+ import onnxruntime as ort
241
+ self._codeformer = ort.InferenceSession(
242
+ str(CODEFORMER_PATH),
243
+ providers=["CPUExecutionProvider"],
244
+ )
245
+ print("[FaceSwapper] CodeFormer ONNX loaded.")
246
+ except Exception as e:
247
+ print(f"[FaceSwapper] CodeFormer load failed: {e}")
248
+ self._codeformer = None
249
+ return self._codeformer
250
+
251
+ def _load_sr(self):
252
+ """Lazy-load ESPCN x2 DNN super-res (needs opencv-contrib). Returns None if unavailable."""
253
+ if self._sr is not None:
254
+ return self._sr
255
+ try:
256
+ _download_espcn()
257
+ if not ESPCN_PATH.exists():
258
+ return None
259
+ sr = cv2.dnn_superres.DnnSuperResImpl_create()
260
+ sr.readModel(str(ESPCN_PATH))
261
+ sr.setModel("espcn", 2)
262
+ self._sr = sr
263
+ print("[FaceSwapper] ESPCN 2Γ— super-res loaded.")
264
+ except Exception as e:
265
+ print(f"[FaceSwapper] ESPCN load failed ({e}) β€” super-res disabled.")
266
+ self._sr = None
267
+ return self._sr
268
+
269
+ def _enhance_codeformer(self, image: np.ndarray, faces) -> np.ndarray:
270
+ """
271
+ For each detected face:
272
+ 1. CodeFormer ONNX β€” neural face restoration at 512Γ—512
273
+ 2. ESPCN 2Γ— super-res β€” upscales small faces for HD output
274
+ 3. CLAHE β€” local contrast refinement
275
+ Falls back to OpenCV enhancement if CodeFormer is unavailable.
276
+ """
277
+ sess = self._load_codeformer()
278
+ if sess is None:
279
+ return self._enhance_opencv(image, faces)
280
+
281
+ sr = self._load_sr() # may be None β€” applied only when available
282
+ result = image.copy()
283
+ input_names = [i.name for i in sess.get_inputs()]
284
+
285
+ for face in faces:
286
+ box = face.bbox.astype(int)
287
+ # Expand bbox 20% for realistic context padding
288
+ bx1, by1, bx2, by2 = (
289
+ max(box[0], 0), max(box[1], 0),
290
+ min(box[2], image.shape[1]), min(box[3], image.shape[0]),
291
+ )
292
+ pad = int(min(bx2 - bx1, by2 - by1) * 0.15)
293
+ x1 = max(0, bx1 - pad); y1 = max(0, by1 - pad)
294
+ x2 = min(image.shape[1], bx2 + pad); y2 = min(image.shape[0], by2 + pad)
295
+ if x2 <= x1 or y2 <= y1:
296
+ continue
297
+
298
+ roi = result[y1:y2, x1:x2].copy()
299
+ orig = roi.copy()
300
+ h, w = roi.shape[:2]
301
+
302
+ # ── 1. CodeFormer: BGRβ†’RGB, resize to 512, normalize [-1, 1] ─────
303
+ face_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
304
+ face_512 = cv2.resize(face_rgb, (512, 512), interpolation=cv2.INTER_LANCZOS4)
305
+ inp = (face_512.astype(np.float32) / 127.5) - 1.0 # [-1, 1]
306
+ inp = np.transpose(inp, (2, 0, 1))[np.newaxis] # [1,3,512,512]
307
+
308
+ try:
309
+ out = sess.run(None, {input_names[0]: inp})[0] # [1,3,512,512]
310
+ except Exception as e:
311
+ print(f"[FaceSwapper] CodeFormer inference failed: {e}")
312
+ continue
313
+
314
+ # Postprocess: [-1,1] β†’ [0,255] β†’ BGR
315
+ out_rgb = np.squeeze(out) # [3,512,512]
316
+ out_rgb = np.transpose(out_rgb, (1, 2, 0)) # [512,512,3]
317
+ out_rgb = ((out_rgb + 1.0) * 127.5).clip(0, 255).astype(np.uint8)
318
+ out_bgr = cv2.cvtColor(out_rgb, cv2.COLOR_RGB2BGR)
319
+
320
+ # ── 2. ESPCN 2Γ— super-res on small faces (<= 128 px) ─────────────
321
+ if sr is not None and min(w, h) <= 128:
322
+ try:
323
+ out_bgr = sr.upsample(out_bgr)
324
+ # Resize back to face region size (x2 upsample β†’ scale back down)
325
+ out_bgr = cv2.resize(out_bgr, (w, h), interpolation=cv2.INTER_LANCZOS4)
326
+ except Exception:
327
+ out_bgr = cv2.resize(out_bgr, (w, h), interpolation=cv2.INTER_LANCZOS4)
328
+ else:
329
+ out_bgr = cv2.resize(out_bgr, (w, h), interpolation=cv2.INTER_LANCZOS4)
330
+
331
+ # ── 3. CLAHE on L channel for final contrast refinement ───────────
332
+ lab = cv2.cvtColor(out_bgr, cv2.COLOR_BGR2LAB)
333
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
334
+ lab[:, :, 0] = clahe.apply(lab[:, :, 0])
335
+ out_bgr = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
336
+
337
+ # ── 4. Feather-blend onto result ──────────────────────────────────
338
+ msk = np.zeros((h, w), dtype=np.float32)
339
+ p = max(4, min(h, w) // 10)
340
+ msk[p:-p, p:-p] = 1.0
341
+ msk = cv2.GaussianBlur(msk, (0, 0), p // 2 or 1)
342
+ msk = msk[:, :, np.newaxis]
343
+ result[y1:y2, x1:x2] = (
344
+ out_bgr.astype(np.float32) * msk + orig.astype(np.float32) * (1 - msk)
345
+ ).astype(np.uint8)
346
+
347
+ return result
348
+
349
  # ── Public API ────────────────────────────────────────────────────────────
350
 
351
  def swap(
 
393
  result, tgt_face, source_face, paste_back=True
394
  )
395
 
396
+ # CodeFormer ONNX + ESPCN super-res + CLAHE (falls back to OpenCV if unavailable)
397
  if enhance:
398
+ result = self._enhance_codeformer(result, target_faces)
399
 
400
  # If we downscaled, upscale back to original resolution with Lanczos
401
  if scale_down < 1.0:
 
466
  result = self._swapper.get(result, tgt_face, source_face, paste_back=True)
467
 
468
  if enhance:
469
+ result = self._enhance_codeformer(result, target_faces)
470
 
471
  # Scale back up to original frame size
472
  if scale_down < 1.0:
processors/video_processor.py CHANGED
@@ -265,9 +265,10 @@ class VideoProcessor:
265
 
266
  out_kwargs = dict(
267
  vcodec="libx264",
268
- crf=23,
269
  preset="fast",
270
  pix_fmt="yuv420p", # widest player compatibility
 
271
  )
272
  if has_audio:
273
  out_kwargs.update(acodec="aac", audio_bitrate="192k")
 
265
 
266
  out_kwargs = dict(
267
  vcodec="libx264",
268
+ crf=18, # 18 = visually lossless (was 23)
269
  preset="fast",
270
  pix_fmt="yuv420p", # widest player compatibility
271
+ **{"vf": "unsharp=5:5:1.0:5:5:0.0"}, # mild luma sharpening
272
  )
273
  if has_audio:
274
  out_kwargs.update(acodec="aac", audio_bitrate="192k")
requirements.txt CHANGED
@@ -18,7 +18,7 @@ rembg>=2.0.50
18
  # Pose Estimation β€” removed (mediapipe 0.10.14+ drops solutions API on Py3.13)
19
 
20
  # Image / Video Processing
21
- opencv-python-headless>=4.8.0
22
  Pillow>=10.0.0
23
  numpy>=1.24.0
24
  scikit-image>=0.21.0
 
18
  # Pose Estimation β€” removed (mediapipe 0.10.14+ drops solutions API on Py3.13)
19
 
20
  # Image / Video Processing
21
+ opencv-contrib-python-headless>=4.8.0
22
  Pillow>=10.0.0
23
  numpy>=1.24.0
24
  scikit-image>=0.21.0