aralawrence11 commited on
Commit
ba3e470
·
verified ·
1 Parent(s): edae6f0

Normalize portraits and improve mouth patch alignment

Browse files
Files changed (1) hide show
  1. app.py +55 -8
app.py CHANGED
@@ -20,7 +20,7 @@ from concurrent.futures import ThreadPoolExecutor
20
  from pathlib import Path
21
 
22
  import cv2
23
- from fastapi import FastAPI, Request
24
  from fastapi.responses import FileResponse, JSONResponse
25
  import gradio as gr
26
  import librosa
@@ -46,7 +46,7 @@ BATCH_SIZE = 4
46
  MEL_STEP_SIZE = 16
47
  TARGET_W = 576
48
  TARGET_H = 1024
49
- MAX_SECONDS = 14
50
 
51
  # ---------- Kokoro voices (public, hexgrad/Kokoro-82M) ----------
52
  KOKORO_VOICES = [
@@ -190,6 +190,45 @@ def _mux_audio(video_path: str, audio_path: str) -> str:
190
  return out
191
 
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  def _make_portrait_canvas(img: np.ndarray) -> np.ndarray:
194
  h, w = img.shape[:2]
195
  cover_scale = max(TARGET_W / w, TARGET_H / h)
@@ -358,9 +397,10 @@ def _blend_patch(frame, patch, box):
358
  patch[lower_top:] = matched
359
 
360
  mask = np.zeros((fh, fw), dtype=np.uint8)
361
- cx, cy = fw // 2, int(fh * 0.72)
362
- axes = (int(fw * 0.48), int(fh * 0.33))
363
  cv2.ellipse(mask, (cx, cy), axes, 0, 0, 360, 255, -1)
 
364
  try:
365
  blended = cv2.seamlessClone(patch, roi, mask, (cx, cy), cv2.NORMAL_CLONE)
366
  except cv2.error:
@@ -373,11 +413,18 @@ def _blend_patch(frame, patch, box):
373
 
374
  def _generate_video(image_path: str, audio_path: str) -> str:
375
  wav2lip, scrfd = _ensure_sessions()
376
- img = cv2.imread(image_path)
377
- if img is None:
378
- raise AppError("Could not read the uploaded image.")
 
 
 
 
 
 
 
379
  frame_base = _make_portrait_canvas(img)
380
- face_box = _detect_face(frame_base, scrfd)
381
 
382
  fx1, fy1, fx2, fy2 = face_box
383
  face_crop = frame_base[fy1:fy2, fx1:fx2]
 
20
  from pathlib import Path
21
 
22
  import cv2
23
+ from fastapi import FastAPI, Request, UploadFile
24
  from fastapi.responses import FileResponse, JSONResponse
25
  import gradio as gr
26
  import librosa
 
46
  MEL_STEP_SIZE = 16
47
  TARGET_W = 576
48
  TARGET_H = 1024
49
+ MAX_SECONDS = int(os.environ.get("MAX_SECONDS", "20"))
50
 
51
  # ---------- Kokoro voices (public, hexgrad/Kokoro-82M) ----------
52
  KOKORO_VOICES = [
 
190
  return out
191
 
192
 
193
+
194
+ def _normalize_input_image(img: np.ndarray) -> np.ndarray:
195
+ """Normalize any upload to a sharp RGB-ish frame before detection/rendering."""
196
+ if img is None:
197
+ raise AppError("Could not read the uploaded image.")
198
+ if len(img.shape) == 2:
199
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
200
+ if img.shape[2] == 4:
201
+ img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
202
+ h, w = img.shape[:2]
203
+ if min(h, w) < 720:
204
+ scale = min(2.8, 720 / max(1, min(h, w)))
205
+ img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_CUBIC)
206
+ h, w = img.shape[:2]
207
+ if max(h, w) > 1600:
208
+ scale = 1600 / max(h, w)
209
+ img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
210
+ # Mild contrast normalization helps SCRFD on washed-out or low-light faces.
211
+ lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
212
+ l, a, b = cv2.split(lab)
213
+ l = cv2.createCLAHE(clipLimit=1.6, tileGridSize=(8, 8)).apply(l)
214
+ return cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
215
+
216
+
217
+ def _expand_face_box(box, frame_shape):
218
+ x1, y1, x2, y2 = box
219
+ h, w = frame_shape[:2]
220
+ bw, bh = x2 - x1, y2 - y1
221
+ # Wav2Lip aligns better with a square-ish crop containing chin/mouth, not too much forehead.
222
+ nx1 = int(x1 - bw * 0.12)
223
+ nx2 = int(x2 + bw * 0.12)
224
+ ny1 = int(y1 - bh * 0.08)
225
+ ny2 = int(y2 + bh * 0.24)
226
+ side = max(nx2 - nx1, ny2 - ny1)
227
+ cx, cy = (nx1 + nx2) // 2, int((ny1 + ny2) / 2 + side * 0.04)
228
+ nx1, nx2 = cx - side // 2, cx + side // 2
229
+ ny1, ny2 = cy - side // 2, cy + side // 2
230
+ return (max(0, nx1), max(0, ny1), min(w, nx2), min(h, ny2))
231
+
232
  def _make_portrait_canvas(img: np.ndarray) -> np.ndarray:
233
  h, w = img.shape[:2]
234
  cover_scale = max(TARGET_W / w, TARGET_H / h)
 
397
  patch[lower_top:] = matched
398
 
399
  mask = np.zeros((fh, fw), dtype=np.uint8)
400
+ cx, cy = fw // 2, int(fh * 0.68)
401
+ axes = (int(fw * 0.44), int(fh * 0.28))
402
  cv2.ellipse(mask, (cx, cy), axes, 0, 0, 360, 255, -1)
403
+ mask = cv2.GaussianBlur(mask, (0, 0), max(3, fh / 42))
404
  try:
405
  blended = cv2.seamlessClone(patch, roi, mask, (cx, cy), cv2.NORMAL_CLONE)
406
  except cv2.error:
 
413
 
414
  def _generate_video(image_path: str, audio_path: str) -> str:
415
  wav2lip, scrfd = _ensure_sessions()
416
+ img = _normalize_input_image(cv2.imread(image_path, cv2.IMREAD_UNCHANGED))
417
+ # Detect on the normalized original first; this catches more faces than detecting only after canvas placement.
418
+ try:
419
+ src_box = _detect_face(img, scrfd)
420
+ x1, y1, x2, y2 = _expand_face_box(src_box, img.shape)
421
+ face = img[y1:y2, x1:x2]
422
+ if face.size > 0:
423
+ img = face
424
+ except Exception as exc:
425
+ print(f"[detect] original fallback: {exc}", flush=True)
426
  frame_base = _make_portrait_canvas(img)
427
+ face_box = _expand_face_box(_detect_face(frame_base, scrfd), frame_base.shape)
428
 
429
  fx1, fy1, fx2, fy2 = face_box
430
  face_crop = frame_base[fy1:fy2, fx1:fx2]