Deeev2005 commited on
Commit
752b61f
·
verified ·
1 Parent(s): 142af9a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, cv2, tempfile
2
+ import gradio as gr
3
+ from moviepy.editor import ImageSequenceClip
4
+ from insightface.app import FaceAnalysis
5
+ from insightface.model_zoo import get_model
6
+
7
+ os.environ["XDG_RUNTIME_DIR"] = "/tmp/runtime-dir"
8
+
9
+ # Load InsightFace models once at startup
10
+ app = FaceAnalysis(name="buffalo_l", providers=["CUDAExecutionProvider","CPUExecutionProvider"])
11
+ app.prepare(ctx_id=0, det_size=(1024,1024))
12
+
13
+ onnx_model_path = "./inswapper_128.onnx" # <-- put model in Space files or download
14
+ swap_model = get_model(onnx_model_path,
15
+ providers=["CUDAExecutionProvider","CPUExecutionProvider"])
16
+
17
+ def face_swap_api(source_image, target_video):
18
+ src_img = cv2.imread(source_image)
19
+ src_faces = app.get(src_img)
20
+ if len(src_faces) == 0:
21
+ return None
22
+ src_face = src_faces[0]
23
+
24
+ frames_dir = tempfile.mkdtemp()
25
+ cap = cv2.VideoCapture(target_video)
26
+ fps = cap.get(cv2.CAP_PROP_FPS)
27
+ frames = []
28
+ idx = 0
29
+ while cap.isOpened():
30
+ ret, frame = cap.read()
31
+ if not ret: break
32
+ frame_path = os.path.join(frames_dir, f"frame_{idx:04d}.png")
33
+ cv2.imwrite(frame_path, frame)
34
+ frames.append(frame_path)
35
+ idx += 1
36
+ cap.release()
37
+
38
+ swapped_frames = []
39
+ for fpath in frames:
40
+ frame = cv2.imread(fpath)
41
+ faces = app.get(frame)
42
+ for face in faces:
43
+ frame = swap_model.get(frame, face, src_face, paste_back=True)
44
+ swapped_frames.append(frame)
45
+
46
+ out_path = os.path.join(tempfile.gettempdir(), "swapped_output.mp4")
47
+ clip = ImageSequenceClip(
48
+ [cv2.cvtColor(f, cv2.COLOR_BGR2RGB) for f in swapped_frames], fps=fps
49
+ )
50
+ clip.write_videofile(out_path, codec="libx264", audio=False, verbose=False)
51
+ return out_path
52
+
53
+ demo = gr.Interface(
54
+ fn=face_swap_api,
55
+ inputs=[gr.Image(type="filepath", label="Source Face"),
56
+ gr.Video(label="Target Video")],
57
+ outputs=gr.Video(label="Swapped Output Video"),
58
+ title="Face Swap API",
59
+ description="Upload a face photo and a video. Returns a face-swapped MP4."
60
+ )
61
+
62
+ if __name__ == "__main__":
63
+ demo.launch()