Spaces:
Runtime error
Runtime error
face-detect-crop (#7)
Browse files- update (fafb3f65f4a4bc8c3b20993ea51eb5e4b0b2d868)
- face_processing.py +518 -0
- processing.py +41 -7
- requirements.txt +4 -0
- video_processing.py +8 -0
face_processing.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Face detection and region extraction for lipsync optimization"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import math
|
| 5 |
+
import logging
|
| 6 |
+
from typing import List, Dict, Tuple, Optional
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import mediapipe as mp
|
| 10 |
+
import numpy as np
|
| 11 |
+
import subprocess
|
| 12 |
+
|
| 13 |
+
from video_processing import get_video_info
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class FaceDetectionError(Exception):
|
| 19 |
+
"""Custom exception for face detection errors"""
|
| 20 |
+
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sample_frames_from_video(
|
| 25 |
+
video_path: str, output_dir: str, sample_count: int = 20
|
| 26 |
+
) -> List[Tuple[int, str]]:
|
| 27 |
+
"""Extract uniform sample frames from video
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
video_path: Path to video
|
| 31 |
+
output_dir: Directory to save extracted frames
|
| 32 |
+
sample_count: Number of frames to sample
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
List of (frame_index, frame_path) tuples
|
| 36 |
+
"""
|
| 37 |
+
video_info = get_video_info(video_path)
|
| 38 |
+
fps = video_info["fps"]
|
| 39 |
+
duration = video_info["duration"]
|
| 40 |
+
total_frames = int(duration * fps)
|
| 41 |
+
|
| 42 |
+
frames_dir = os.path.join(output_dir, "sampled_frames")
|
| 43 |
+
os.makedirs(frames_dir, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
if total_frames <= sample_count:
|
| 46 |
+
frame_indices = list(range(total_frames))
|
| 47 |
+
else:
|
| 48 |
+
frame_indices = [
|
| 49 |
+
int(i * total_frames / sample_count) for i in range(sample_count)
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
extracted_frames = []
|
| 53 |
+
for idx, frame_idx in enumerate(frame_indices):
|
| 54 |
+
frame_path = os.path.join(frames_dir, f"frame_{idx:04d}.jpg")
|
| 55 |
+
|
| 56 |
+
cmd = [
|
| 57 |
+
"ffmpeg",
|
| 58 |
+
"-loglevel",
|
| 59 |
+
"error",
|
| 60 |
+
"-y",
|
| 61 |
+
"-hwaccel",
|
| 62 |
+
"cuda",
|
| 63 |
+
"-i",
|
| 64 |
+
video_path,
|
| 65 |
+
"-vframes",
|
| 66 |
+
"1",
|
| 67 |
+
"-ss",
|
| 68 |
+
f"{frame_idx / fps:.3f}",
|
| 69 |
+
frame_path,
|
| 70 |
+
]
|
| 71 |
+
subprocess.run(cmd, check=True)
|
| 72 |
+
|
| 73 |
+
extracted_frames.append((frame_idx, frame_path))
|
| 74 |
+
|
| 75 |
+
logger.info(f"Extracted {len(extracted_frames)} frames from {video_path}")
|
| 76 |
+
return extracted_frames
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def detect_faces_in_frames(
|
| 80 |
+
extracted_frames: List[Tuple[int, str]],
|
| 81 |
+
min_confidence: float = 0.5,
|
| 82 |
+
min_face_pixels: int = 100,
|
| 83 |
+
) -> List[Dict]:
|
| 84 |
+
"""Detect faces in all sampled frames using MediaPipe
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
extracted_frames: List of (frame_index, frame_path) tuples
|
| 88 |
+
min_confidence: Minimum detection confidence (0-1)
|
| 89 |
+
min_face_pixels: Minimum face size in pixels
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
List of detections: [{"frame_idx", "confidence", "bbox": (x, y, w, h)}]
|
| 93 |
+
"""
|
| 94 |
+
mp_face_detection = mp.solutions.face_detection
|
| 95 |
+
detections = []
|
| 96 |
+
|
| 97 |
+
with mp_face_detection.FaceDetection(
|
| 98 |
+
model_selection=0, min_detection_confidence=min_confidence
|
| 99 |
+
) as face_detector:
|
| 100 |
+
for frame_idx, frame_path in extracted_frames:
|
| 101 |
+
frame = cv2.imread(frame_path)
|
| 102 |
+
if frame is None:
|
| 103 |
+
logger.warning(f"Failed to read frame: {frame_path}")
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
h, w = frame.shape[:2]
|
| 107 |
+
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 108 |
+
|
| 109 |
+
results = face_detector.process(rgb_frame)
|
| 110 |
+
|
| 111 |
+
if results.detections:
|
| 112 |
+
for detection in results.detections:
|
| 113 |
+
bbox = detection.location_data.relative_bounding_box
|
| 114 |
+
|
| 115 |
+
abs_x = int(bbox.xmin * w)
|
| 116 |
+
abs_y = int(bbox.ymin * h)
|
| 117 |
+
abs_w = int(bbox.width * w)
|
| 118 |
+
abs_h = int(bbox.height * h)
|
| 119 |
+
|
| 120 |
+
if abs_w >= min_face_pixels and abs_h >= min_face_pixels:
|
| 121 |
+
detections.append(
|
| 122 |
+
{
|
| 123 |
+
"frame_idx": frame_idx,
|
| 124 |
+
"confidence": float(detection.score[0]),
|
| 125 |
+
"bbox": (abs_x, abs_y, abs_w, abs_h),
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
logger.info(f"Detected {len(detections)} faces in {len(extracted_frames)} faces")
|
| 130 |
+
return detections
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def cluster_face_detections(
|
| 134 |
+
detections: List[Dict], max_distance: int = 100
|
| 135 |
+
) -> List[List[Dict]]:
|
| 136 |
+
"""Group face detections belonging to the same person using clustering
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
detections: List of face detections
|
| 140 |
+
max_distance: Maximum distance (pixels) to consider detections as same person
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
List of clusters (each cluster is a list of detections)
|
| 144 |
+
"""
|
| 145 |
+
if not detections:
|
| 146 |
+
return []
|
| 147 |
+
|
| 148 |
+
clusters = []
|
| 149 |
+
visited = set()
|
| 150 |
+
|
| 151 |
+
for i, det_i in enumerate(detections):
|
| 152 |
+
if i in visited:
|
| 153 |
+
continue
|
| 154 |
+
|
| 155 |
+
x_i, y_i, w_i, h_i = det_i["bbox"]
|
| 156 |
+
center_i = (x_i + w_i / 2, y_i + h_i / 2)
|
| 157 |
+
|
| 158 |
+
cluster = [det_i]
|
| 159 |
+
visited.add(i)
|
| 160 |
+
|
| 161 |
+
for j, det_j in enumerate(detections):
|
| 162 |
+
if j in visited:
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
x_j, y_j, w_j, h_j = det_j["bbox"]
|
| 166 |
+
center_j = (x_j + w_j / 2, y_j + h_j / 2)
|
| 167 |
+
|
| 168 |
+
distance = math.sqrt(
|
| 169 |
+
(center_i[0] - center_j[0]) ** 2 + (center_i[1] - center_j[1]) ** 2
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if distance < max_distance:
|
| 173 |
+
cluster.append(det_j)
|
| 174 |
+
visited.add(j)
|
| 175 |
+
|
| 176 |
+
clusters.append(cluster)
|
| 177 |
+
|
| 178 |
+
logger.info(f"Clustered {len(detections)} detections into {len(clusters)} clusters")
|
| 179 |
+
return clusters
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def select_best_cluster(clusters: List[List[Dict]]) -> List[Dict] | None:
|
| 183 |
+
"""Select the best face cluster (highest frequency)
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
clusters: List of clusters
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
Best cluster (most frequent) or None
|
| 190 |
+
"""
|
| 191 |
+
if not clusters:
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
scored_clusters = [(len(cluster), cluster) for cluster in clusters]
|
| 195 |
+
scored_clusters.sort(key=lambda x: x[0], reverse=True)
|
| 196 |
+
|
| 197 |
+
best_cluster = scored_clusters[0][1]
|
| 198 |
+
logger.info(f"Selected best cluster with {len(best_cluster)} detections")
|
| 199 |
+
return best_cluster
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def verify_face_stability(
|
| 203 |
+
cluster: List[Dict], max_movement_percent: float = 0.3
|
| 204 |
+
) -> bool:
|
| 205 |
+
"""Verify face doesn't move too much between frames
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
cluster: Face detections for the same person
|
| 209 |
+
max_movement_percent: Max movement as percentage of average face size
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
True if face is stable, False otherwise
|
| 213 |
+
"""
|
| 214 |
+
if len(cluster) < 2:
|
| 215 |
+
return True
|
| 216 |
+
|
| 217 |
+
centers = []
|
| 218 |
+
sizes = []
|
| 219 |
+
|
| 220 |
+
for det in cluster:
|
| 221 |
+
x, y, w, h = det["bbox"]
|
| 222 |
+
centers.append((x + w / 2, y + h / 2))
|
| 223 |
+
sizes.append(w * h)
|
| 224 |
+
|
| 225 |
+
avg_size = sum(sizes) / len(sizes)
|
| 226 |
+
avg_face_dim = math.sqrt(avg_size)
|
| 227 |
+
max_allowed_movement = avg_face_dim * max_movement_percent
|
| 228 |
+
|
| 229 |
+
for i in range(len(centers) - 1):
|
| 230 |
+
dx = abs(centers[i + 1][0] - centers[i][0])
|
| 231 |
+
dy = abs(centers[i + 1][1] - centers[i][1])
|
| 232 |
+
movement = math.sqrt(dx**2 + dy**2)
|
| 233 |
+
|
| 234 |
+
if movement > max_allowed_movement:
|
| 235 |
+
logger.warning(
|
| 236 |
+
f"Face movement {movement:.1f}px > {max_allowed_movement:.1f}px"
|
| 237 |
+
)
|
| 238 |
+
return False
|
| 239 |
+
|
| 240 |
+
return True
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def calculate_face_bbox_from_cluster(cluster: List[Dict]) -> Dict:
|
| 244 |
+
"""Calculate average face bounding box from cluster
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
cluster: Face detections for the same person
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
Dict: {"x", "y", "width", "height"}
|
| 251 |
+
"""
|
| 252 |
+
weighted_x = 0
|
| 253 |
+
weighted_y = 0
|
| 254 |
+
weighted_w = 0
|
| 255 |
+
weighted_h = 0
|
| 256 |
+
total_weight = 0
|
| 257 |
+
|
| 258 |
+
for det in cluster:
|
| 259 |
+
x, y, w, h = det["bbox"]
|
| 260 |
+
weight = det["confidence"]
|
| 261 |
+
weighted_x += x * weight
|
| 262 |
+
weighted_y += y * weight
|
| 263 |
+
weighted_w += w * weight
|
| 264 |
+
weighted_h += h * weight
|
| 265 |
+
total_weight += weight
|
| 266 |
+
|
| 267 |
+
avg_bbox = {
|
| 268 |
+
"x": int(weighted_x / total_weight),
|
| 269 |
+
"y": int(weighted_y / total_weight),
|
| 270 |
+
"width": int(weighted_w / total_weight),
|
| 271 |
+
"height": int(weighted_h / total_weight),
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
return avg_bbox
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def calculate_safe_crop_512x512(
|
| 278 |
+
face_bbox: Dict, video_width: int, video_height: int
|
| 279 |
+
) -> Dict:
|
| 280 |
+
"""Calculate safe 512x512 crop region ensuring face is inside
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
face_bbox: Face bounding box {"x", "y", "width", "height"}
|
| 284 |
+
video_width: Video width
|
| 285 |
+
video_height: Video height
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
Dict: {"x", "y", "width": 512, "height": 512}
|
| 289 |
+
"""
|
| 290 |
+
crop_size = 512
|
| 291 |
+
crop_half = crop_size // 2
|
| 292 |
+
|
| 293 |
+
face_center_x = face_bbox["x"] + face_bbox["width"] / 2
|
| 294 |
+
face_center_y = face_bbox["y"] + face_bbox["height"] / 2
|
| 295 |
+
|
| 296 |
+
crop_x = int(face_center_x - crop_half)
|
| 297 |
+
crop_y = int(face_center_y - crop_half)
|
| 298 |
+
|
| 299 |
+
crop_x = max(0, crop_x)
|
| 300 |
+
crop_y = max(0, crop_y)
|
| 301 |
+
crop_x = min(video_width - crop_size, crop_x)
|
| 302 |
+
crop_y = min(video_height - crop_size, crop_y)
|
| 303 |
+
|
| 304 |
+
face_right = face_bbox["x"] + face_bbox["width"]
|
| 305 |
+
face_bottom = face_bbox["y"] + face_bbox["height"]
|
| 306 |
+
crop_right = crop_x + crop_size
|
| 307 |
+
crop_bottom = crop_y + crop_size
|
| 308 |
+
|
| 309 |
+
if (
|
| 310 |
+
face_bbox["x"] < crop_x
|
| 311 |
+
or face_bbox["y"] < crop_y
|
| 312 |
+
or face_right > crop_right
|
| 313 |
+
or face_bottom > crop_bottom
|
| 314 |
+
):
|
| 315 |
+
if face_bbox["x"] < crop_x:
|
| 316 |
+
crop_x = face_bbox["x"]
|
| 317 |
+
elif face_right > crop_right:
|
| 318 |
+
crop_x = face_right - crop_size
|
| 319 |
+
|
| 320 |
+
if face_bbox["y"] < crop_y:
|
| 321 |
+
crop_y = face_bbox["y"]
|
| 322 |
+
elif face_bottom > crop_bottom:
|
| 323 |
+
crop_y = face_bottom - crop_size
|
| 324 |
+
|
| 325 |
+
crop_x = max(0, crop_x)
|
| 326 |
+
crop_y = max(0, crop_y)
|
| 327 |
+
crop_x = min(video_width - crop_size, crop_x)
|
| 328 |
+
crop_y = min(video_height - crop_size, crop_y)
|
| 329 |
+
|
| 330 |
+
return {"x": crop_x, "y": crop_y, "width": crop_size, "height": crop_size}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def detect_face_region(
|
| 334 |
+
video_path: str,
|
| 335 |
+
output_dir: str,
|
| 336 |
+
sample_count: int = 20,
|
| 337 |
+
min_confidence: float = 0.5,
|
| 338 |
+
min_face_pixels: int = 100,
|
| 339 |
+
max_face_movement_percent: float = 0.3,
|
| 340 |
+
) -> Dict:
|
| 341 |
+
"""Main function: Detect face and calculate safe 512x512 crop
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
video_path: Path to video
|
| 345 |
+
output_dir: Directory for temporary files
|
| 346 |
+
sample_count: Number of frames to sample (default: 20)
|
| 347 |
+
min_confidence: Minimum detection confidence
|
| 348 |
+
min_face_pixels: Minimum face size in pixels
|
| 349 |
+
max_face_movement_percent: Max allowed face movement
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
Dict: {"x", "y", "width": 512, "height": 512, "face_bbox"}
|
| 353 |
+
|
| 354 |
+
Raises:
|
| 355 |
+
FaceDetectionError: If face detection fails
|
| 356 |
+
"""
|
| 357 |
+
try:
|
| 358 |
+
video_info = get_video_info(video_path)
|
| 359 |
+
video_w, video_h = video_info["width"], video_info["height"]
|
| 360 |
+
|
| 361 |
+
if video_w < 512 or video_h < 512:
|
| 362 |
+
raise FaceDetectionError(
|
| 363 |
+
f"Video resolution {video_w}x{video_h} < 512x512. "
|
| 364 |
+
f"Please upload higher resolution video."
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
extracted_frames = sample_frames_from_video(
|
| 368 |
+
video_path, output_dir, sample_count
|
| 369 |
+
)
|
| 370 |
+
detections = detect_faces_in_frames(
|
| 371 |
+
extracted_frames, min_confidence, min_face_pixels
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
if not detections:
|
| 375 |
+
raise FaceDetectionError(
|
| 376 |
+
f"No face detected in {sample_count} sampled frames. "
|
| 377 |
+
f"Please upload a video with a visible face."
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
frames_with_face = len(set(d["frame_idx"] for d in detections))
|
| 381 |
+
face_coverage = frames_with_face / len(extracted_frames)
|
| 382 |
+
|
| 383 |
+
if face_coverage < 0.5:
|
| 384 |
+
raise FaceDetectionError(
|
| 385 |
+
f"Face detected in only {frames_with_face}/{len(extracted_frames)} frames "
|
| 386 |
+
f"({face_coverage * 100:.1f}%). "
|
| 387 |
+
f"Please upload a video with a visible face."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
clusters = cluster_face_detections(detections)
|
| 391 |
+
best_cluster = select_best_cluster(clusters)
|
| 392 |
+
|
| 393 |
+
if best_cluster is None:
|
| 394 |
+
raise FaceDetectionError(
|
| 395 |
+
f"Failed to identify main face in video. "
|
| 396 |
+
f"Please upload a video with a clear, visible face."
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
if not verify_face_stability(best_cluster, max_face_movement_percent):
|
| 400 |
+
raise FaceDetectionError(
|
| 401 |
+
f"Face moves too much between frames. "
|
| 402 |
+
f"Please upload a video with a stable face position."
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
face_bbox = calculate_face_bbox_from_cluster(best_cluster)
|
| 406 |
+
crop_bbox = calculate_safe_crop_512x512(face_bbox, video_w, video_h)
|
| 407 |
+
|
| 408 |
+
crop_bbox["face_bbox"] = face_bbox
|
| 409 |
+
|
| 410 |
+
logger.info(
|
| 411 |
+
f"Face detected at ({face_bbox['x']}, {face_bbox['y']}) "
|
| 412 |
+
f"size {face_bbox['width']}x{face_bbox['height']}, "
|
| 413 |
+
f"crop at ({crop_bbox['x']}, {crop_bbox['y']})"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
return crop_bbox
|
| 417 |
+
|
| 418 |
+
except FaceDetectionError:
|
| 419 |
+
raise
|
| 420 |
+
except Exception as e:
|
| 421 |
+
logger.error(f"Face detection failed: {e}")
|
| 422 |
+
raise FaceDetectionError(f"Face detection failed: {str(e)}")
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def crop_video_to_512x512(video_path: str, crop_bbox: Dict, output_dir: str) -> str:
|
| 426 |
+
"""Crop video to 512x512 using calculated bbox
|
| 427 |
+
|
| 428 |
+
Args:
|
| 429 |
+
video_path: Path to input video
|
| 430 |
+
crop_bbox: Crop region {"x", "y", "width", "height"}
|
| 431 |
+
output_dir: Directory to save output
|
| 432 |
+
|
| 433 |
+
Returns:
|
| 434 |
+
Path to cropped video
|
| 435 |
+
"""
|
| 436 |
+
output_path = os.path.join(output_dir, "face_cropped_512x512.mp4")
|
| 437 |
+
|
| 438 |
+
cmd = [
|
| 439 |
+
"ffmpeg",
|
| 440 |
+
"-loglevel",
|
| 441 |
+
"error",
|
| 442 |
+
"-y",
|
| 443 |
+
"-hwaccel",
|
| 444 |
+
"cuda",
|
| 445 |
+
"-i",
|
| 446 |
+
video_path,
|
| 447 |
+
"-vf",
|
| 448 |
+
f"crop={crop_bbox['width']}:{crop_bbox['height']}:{crop_bbox['x']}:{crop_bbox['y']}",
|
| 449 |
+
"-c:v",
|
| 450 |
+
"h264_nvenc",
|
| 451 |
+
"-preset",
|
| 452 |
+
"p6",
|
| 453 |
+
"-cq",
|
| 454 |
+
"18",
|
| 455 |
+
"-c:a",
|
| 456 |
+
"copy",
|
| 457 |
+
output_path,
|
| 458 |
+
]
|
| 459 |
+
|
| 460 |
+
subprocess.run(cmd, check=True)
|
| 461 |
+
logger.info(f"Cropped video to 512x512: {output_path}")
|
| 462 |
+
return output_path
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def blend_face_into_original(
|
| 466 |
+
original_video: str,
|
| 467 |
+
face_video: str,
|
| 468 |
+
crop_bbox: Dict,
|
| 469 |
+
output_dir: str,
|
| 470 |
+
feather: int = 10,
|
| 471 |
+
) -> str:
|
| 472 |
+
"""Blend face video back into original video
|
| 473 |
+
|
| 474 |
+
Args:
|
| 475 |
+
original_video: Path to original video
|
| 476 |
+
face_video: Path to face-cropped lipsynced video
|
| 477 |
+
crop_bbox: Crop region {"x", "y", "width", "height"}
|
| 478 |
+
output_dir: Directory to save output
|
| 479 |
+
feather: Feather radius for smooth blending
|
| 480 |
+
|
| 481 |
+
Returns:
|
| 482 |
+
Path to blended video
|
| 483 |
+
"""
|
| 484 |
+
output_path = os.path.join(output_dir, "face_blended.mp4")
|
| 485 |
+
|
| 486 |
+
cmd = [
|
| 487 |
+
"ffmpeg",
|
| 488 |
+
"-loglevel",
|
| 489 |
+
"error",
|
| 490 |
+
"-y",
|
| 491 |
+
"-hwaccel",
|
| 492 |
+
"cuda",
|
| 493 |
+
"-hwaccel_output_format",
|
| 494 |
+
"cuda",
|
| 495 |
+
"-i",
|
| 496 |
+
original_video,
|
| 497 |
+
"-i",
|
| 498 |
+
face_video,
|
| 499 |
+
"-filter_complex",
|
| 500 |
+
(
|
| 501 |
+
f"[1:v]format=rgba,split[A][B];"
|
| 502 |
+
f"[A]colorchannelmixer=aa=0.8[B];"
|
| 503 |
+
f"[0:v][1:v]overlay={crop_bbox['x']}:{crop_bbox['y']}"
|
| 504 |
+
),
|
| 505 |
+
"-c:v",
|
| 506 |
+
"h264_nvenc",
|
| 507 |
+
"-preset",
|
| 508 |
+
"p6",
|
| 509 |
+
"-cq",
|
| 510 |
+
"18",
|
| 511 |
+
"-c:a",
|
| 512 |
+
"copy",
|
| 513 |
+
output_path,
|
| 514 |
+
]
|
| 515 |
+
|
| 516 |
+
subprocess.run(cmd, check=True)
|
| 517 |
+
logger.info(f"Blended face into original: {output_path}")
|
| 518 |
+
return output_path
|
processing.py
CHANGED
|
@@ -12,6 +12,12 @@ import torch
|
|
| 12 |
|
| 13 |
from audio_processing import get_audio_duration, prepare_target_audio
|
| 14 |
from config import PROCESSED_RESULTS_DIR
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from lipsync_processing import apply_lipsync_to_video
|
| 16 |
from time_util import timer
|
| 17 |
from utils import setup_output_dir
|
|
@@ -97,7 +103,27 @@ def process_lipsync_with_audio_target(
|
|
| 97 |
gc.collect()
|
| 98 |
logger.info(f"Memory after video loop: {get_memory_usage()}")
|
| 99 |
|
| 100 |
-
progress(0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
logger.info(f"Memory before audio prep: {get_memory_usage()}")
|
| 102 |
|
| 103 |
with timer("Preparing target audio"):
|
|
@@ -106,17 +132,17 @@ def process_lipsync_with_audio_target(
|
|
| 106 |
gc.collect()
|
| 107 |
logger.info(f"Memory after audio prep: {get_memory_usage()}")
|
| 108 |
|
| 109 |
-
progress(0.
|
| 110 |
|
| 111 |
logger.info(
|
| 112 |
-
f"Starting lipsync: video={
|
| 113 |
)
|
| 114 |
logger.info(f"Memory before lipsync: {get_memory_usage()}")
|
| 115 |
|
| 116 |
with timer("Applying lipsync"):
|
| 117 |
try:
|
| 118 |
-
|
| 119 |
-
|
| 120 |
)
|
| 121 |
except Exception as e:
|
| 122 |
logger.error(f"Lipsync failed with error: {type(e).__name__}: {e}")
|
|
@@ -127,9 +153,17 @@ def process_lipsync_with_audio_target(
|
|
| 127 |
gc.collect()
|
| 128 |
logger.info(f"Memory after lipsync: {get_memory_usage()}")
|
| 129 |
|
| 130 |
-
progress(0.8, desc="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
progress(1.0, desc="✅ Hoàn tất!")
|
| 135 |
logger.info(f"Memory at end: {get_memory_usage()}")
|
|
|
|
| 12 |
|
| 13 |
from audio_processing import get_audio_duration, prepare_target_audio
|
| 14 |
from config import PROCESSED_RESULTS_DIR
|
| 15 |
+
from face_processing import (
|
| 16 |
+
blend_face_into_original,
|
| 17 |
+
crop_video_to_512x512,
|
| 18 |
+
detect_face_region,
|
| 19 |
+
FaceDetectionError,
|
| 20 |
+
)
|
| 21 |
from lipsync_processing import apply_lipsync_to_video
|
| 22 |
from time_util import timer
|
| 23 |
from utils import setup_output_dir
|
|
|
|
| 103 |
gc.collect()
|
| 104 |
logger.info(f"Memory after video loop: {get_memory_usage()}")
|
| 105 |
|
| 106 |
+
progress(0.2, desc="👤 Đang phát hiện khuôn mặt...")
|
| 107 |
+
with timer("Detecting face"):
|
| 108 |
+
try:
|
| 109 |
+
face_bbox = detect_face_region(video_looped, output_dir)
|
| 110 |
+
except FaceDetectionError as e:
|
| 111 |
+
logger.error(f"Face detection failed: {e}")
|
| 112 |
+
raise gr.Error(str(e))
|
| 113 |
+
|
| 114 |
+
gc.collect()
|
| 115 |
+
logger.info(f"Memory after face detection: {get_memory_usage()}")
|
| 116 |
+
|
| 117 |
+
progress(0.3, desc="✂️ Đang crop video 512x512...")
|
| 118 |
+
with timer("Cropping video to 512x512"):
|
| 119 |
+
face_cropped_512 = crop_video_to_512x512(
|
| 120 |
+
video_looped, face_bbox, output_dir
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
gc.collect()
|
| 124 |
+
logger.info(f"Memory after crop: {get_memory_usage()}")
|
| 125 |
+
|
| 126 |
+
progress(0.4, desc="🎵 Đang xử lý audio...")
|
| 127 |
logger.info(f"Memory before audio prep: {get_memory_usage()}")
|
| 128 |
|
| 129 |
with timer("Preparing target audio"):
|
|
|
|
| 132 |
gc.collect()
|
| 133 |
logger.info(f"Memory after audio prep: {get_memory_usage()}")
|
| 134 |
|
| 135 |
+
progress(0.6, desc="👄 Đang lipsync...")
|
| 136 |
|
| 137 |
logger.info(
|
| 138 |
+
f"Starting lipsync: video={face_cropped_512}, audio_16k={audio_16k}, output={output_dir}"
|
| 139 |
)
|
| 140 |
logger.info(f"Memory before lipsync: {get_memory_usage()}")
|
| 141 |
|
| 142 |
with timer("Applying lipsync"):
|
| 143 |
try:
|
| 144 |
+
lipsynced_face = apply_lipsync_to_video(
|
| 145 |
+
face_cropped_512, audio_16k, output_dir
|
| 146 |
)
|
| 147 |
except Exception as e:
|
| 148 |
logger.error(f"Lipsync failed with error: {type(e).__name__}: {e}")
|
|
|
|
| 153 |
gc.collect()
|
| 154 |
logger.info(f"Memory after lipsync: {get_memory_usage()}")
|
| 155 |
|
| 156 |
+
progress(0.8, desc="🔀 Đang ghép video...")
|
| 157 |
+
with timer("Blending face into original"):
|
| 158 |
+
lipsynced_full = blend_face_into_original(
|
| 159 |
+
video_looped, lipsynced_face, face_bbox, output_dir
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
gc.collect()
|
| 163 |
+
logger.info(f"Memory after blend: {get_memory_usage()}")
|
| 164 |
|
| 165 |
+
progress(0.9, desc="🔗 Đang ghép audio...")
|
| 166 |
+
final_video = merge_audio_video(lipsynced_full, audio_upsampled, output_dir)
|
| 167 |
|
| 168 |
progress(1.0, desc="✅ Hoàn tất!")
|
| 169 |
logger.info(f"Memory at end: {get_memory_usage()}")
|
requirements.txt
CHANGED
|
@@ -21,3 +21,7 @@ git+https://github.com/techio-dev/LatentSync-batch.git
|
|
| 21 |
|
| 22 |
# --- Flash Attention (HuggingFace Spaces) ---
|
| 23 |
https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# --- Flash Attention (HuggingFace Spaces) ---
|
| 23 |
https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
|
| 24 |
+
|
| 25 |
+
# --- Face Detection ---
|
| 26 |
+
mediapipe>=0.10.0
|
| 27 |
+
opencv-python>=4.8.0
|
video_processing.py
CHANGED
|
@@ -23,6 +23,8 @@ def crop_video_duration(video_path: str, duration: int, output_dir: str) -> str:
|
|
| 23 |
"-loglevel",
|
| 24 |
"error",
|
| 25 |
"-y",
|
|
|
|
|
|
|
| 26 |
"-i",
|
| 27 |
video_path,
|
| 28 |
"-t",
|
|
@@ -52,6 +54,8 @@ def merge_audio_video(video_path: str, audio_path: str, output_dir: str) -> str:
|
|
| 52 |
"-loglevel",
|
| 53 |
"error",
|
| 54 |
"-y",
|
|
|
|
|
|
|
| 55 |
"-i",
|
| 56 |
video_path,
|
| 57 |
"-i",
|
|
@@ -127,6 +131,8 @@ def loop_video_to_match_audio(
|
|
| 127 |
"-loglevel",
|
| 128 |
"error",
|
| 129 |
"-y",
|
|
|
|
|
|
|
| 130 |
"-i",
|
| 131 |
video_path,
|
| 132 |
"-t",
|
|
@@ -142,6 +148,8 @@ def loop_video_to_match_audio(
|
|
| 142 |
"-loglevel",
|
| 143 |
"error",
|
| 144 |
"-y",
|
|
|
|
|
|
|
| 145 |
"-stream_loop",
|
| 146 |
f"{loop_count}",
|
| 147 |
"-i",
|
|
|
|
| 23 |
"-loglevel",
|
| 24 |
"error",
|
| 25 |
"-y",
|
| 26 |
+
"-hwaccel",
|
| 27 |
+
"cuda",
|
| 28 |
"-i",
|
| 29 |
video_path,
|
| 30 |
"-t",
|
|
|
|
| 54 |
"-loglevel",
|
| 55 |
"error",
|
| 56 |
"-y",
|
| 57 |
+
"-hwaccel",
|
| 58 |
+
"cuda",
|
| 59 |
"-i",
|
| 60 |
video_path,
|
| 61 |
"-i",
|
|
|
|
| 131 |
"-loglevel",
|
| 132 |
"error",
|
| 133 |
"-y",
|
| 134 |
+
"-hwaccel",
|
| 135 |
+
"cuda",
|
| 136 |
"-i",
|
| 137 |
video_path,
|
| 138 |
"-t",
|
|
|
|
| 148 |
"-loglevel",
|
| 149 |
"error",
|
| 150 |
"-y",
|
| 151 |
+
"-hwaccel",
|
| 152 |
+
"cuda",
|
| 153 |
"-stream_loop",
|
| 154 |
f"{loop_count}",
|
| 155 |
"-i",
|