sandhyasinha655 commited on
Commit
9692264
·
verified ·
1 Parent(s): 82b1bd2

Update run.py

Browse files
Files changed (1) hide show
  1. run.py +12 -1
run.py CHANGED
@@ -1,10 +1,12 @@
1
  import os
 
2
  from moviepy.editor import VideoFileClip
3
  from PIL import Image
4
  import insightface
5
  import cv2
6
  import numpy as np
7
 
 
8
  model = insightface.app.FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
9
  model.prepare(ctx_id=0)
10
 
@@ -25,6 +27,7 @@ def swap_face(source_path, target_path, output_path):
25
  source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
26
  source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
27
  cv2.imwrite(output_path, target_img)
 
28
  else:
29
  clip = VideoFileClip(target_path)
30
  def process_frame(frame):
@@ -36,10 +39,18 @@ def swap_face(source_path, target_path, output_path):
36
  source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
37
  source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
38
  return cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
 
39
  new_clip = clip.fl_image(process_frame)
40
  new_clip.write_videofile(output_path, audio=True)
41
 
42
  def run_faceswap(source_path, target_path):
43
  output_path = "result.jpg" if target_path.endswith(".jpg") else "result.mp4"
44
  swap_face(source_path, target_path, output_path)
45
- return output_path
 
 
 
 
 
 
 
 
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 once
10
  model = insightface.app.FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
11
  model.prepare(ctx_id=0)
12
 
 
27
  source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
28
  source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
29
  cv2.imwrite(output_path, target_img)
30
+
31
  else:
32
  clip = VideoFileClip(target_path)
33
  def process_frame(frame):
 
39
  source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
40
  source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
41
  return cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
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.")