Update run.py
Browse files
run.py
CHANGED
@@ -1,12 +1,9 @@
|
|
1 |
import os
|
2 |
-
import time
|
3 |
from moviepy.editor import VideoFileClip
|
4 |
-
from PIL import Image
|
5 |
import insightface
|
6 |
import cv2
|
7 |
-
import numpy as np
|
8 |
|
9 |
-
# Load model
|
10 |
model = insightface.app.FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
|
11 |
model.prepare(ctx_id=0)
|
12 |
|
@@ -22,35 +19,28 @@ def swap_face(source_path, target_path, output_path):
|
|
22 |
faces = model.get(target_img)
|
23 |
if len(faces) == 0:
|
24 |
raise Exception("No face found in target.")
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
cv2.imwrite(output_path, target_img)
|
30 |
|
31 |
else:
|
32 |
clip = VideoFileClip(target_path)
|
|
|
33 |
def process_frame(frame):
|
34 |
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
35 |
faces = model.get(frame_bgr)
|
36 |
if len(faces) > 0:
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
new_clip = clip.fl_image(process_frame)
|
44 |
-
new_clip.write_videofile(output_path, audio=True)
|
45 |
-
|
46 |
-
def run_faceswap(source_path, target_path):
|
47 |
-
output_path = "result.jpg" if target_path.endswith(".jpg") else "result.mp4"
|
48 |
-
swap_face(source_path, target_path, output_path)
|
49 |
-
|
50 |
-
# ✅ Safety check – wait for output file to be created
|
51 |
-
for _ in range(5):
|
52 |
-
if os.path.exists(output_path):
|
53 |
-
return output_path
|
54 |
-
time.sleep(1)
|
55 |
-
|
56 |
-
raise Exception("Output file not generated.")
|
|
|
1 |
import os
|
|
|
2 |
from moviepy.editor import VideoFileClip
|
|
|
3 |
import insightface
|
4 |
import cv2
|
|
|
5 |
|
6 |
+
# Load InsightFace model
|
7 |
model = insightface.app.FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
|
8 |
model.prepare(ctx_id=0)
|
9 |
|
|
|
19 |
faces = model.get(target_img)
|
20 |
if len(faces) == 0:
|
21 |
raise Exception("No face found in target.")
|
22 |
+
|
23 |
+
# Crop and resize source face
|
24 |
+
sx1, sy1, sx2, sy2 = source_face.bbox.astype(int)
|
25 |
+
source_crop = source_img[sy1:sy2, sx1:sx2]
|
26 |
+
|
27 |
+
tx1, ty1, tx2, ty2 = faces[0].bbox.astype(int)
|
28 |
+
target_w, target_h = tx2 - tx1, ty2 - ty1
|
29 |
+
source_resized = cv2.resize(source_crop, (target_w, target_h))
|
30 |
+
|
31 |
+
# Paste on target
|
32 |
+
target_img[ty1:ty2, tx1:tx2] = source_resized
|
33 |
cv2.imwrite(output_path, target_img)
|
34 |
|
35 |
else:
|
36 |
clip = VideoFileClip(target_path)
|
37 |
+
|
38 |
def process_frame(frame):
|
39 |
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
40 |
faces = model.get(frame_bgr)
|
41 |
if len(faces) > 0:
|
42 |
+
tx1, ty1, tx2, ty2 = faces[0].bbox.astype(int)
|
43 |
+
target_w, target_h = tx2 - tx1, ty2 - ty1
|
44 |
+
|
45 |
+
sx1, sy1, sx2, sy2 = source_face.bbox.astype(int)
|
46 |
+
source_crop = source_img
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|