File size: 1,905 Bytes
452fa15
 
 
 
 
bb766be
 
452fa15
 
 
 
 
 
 
 
 
bb766be
 
 
 
 
 
 
dd4f721
cbeba36
452fa15
8c613a3
 
452fa15
461df35
452fa15
 
 
 
 
 
 
 
 
 
408a47f
 
452fa15
 
 
bb766be
dd4f721
452fa15
 
 
 
dd4f721
 
 
 
 
452fa15
 
 
 
 
15e42f0
452fa15
97cab1f
 
 
 
a2089cc
97cab1f
 
 
 
3f97b64
97cab1f
 
 
 
 
bb766be
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import gradio as gr
from PIL import Image
import sys
import tempfile
from facefusion import core
from moviepy.editor import VideoFileClip


def run_cli(cli_args):
  old_argv = sys.argv
  try:
    sys.argv = ['run.py', *cli_args]
    core.cli()
  finally:
    sys.argv = old_argv


def get_video_duration(video_path):
    video = VideoFileClip(video_path)
    duration = video.duration  # duration in seconds
    return duration


def swap_faces(source_image_path, target_image_path, enhance_face=True, enhance_frame=True):
  provider = 'cuda'

  target_ext = target_image_path.split('.')[-1]
  output_image_file = tempfile.NamedTemporaryFile(suffix=f'.{target_ext}')
  output_image_path = output_image_file.name
  duration = int(get_video_duration(target_image_path))
  print(source_image_path)
  print(target_image_path)
  print(output_image_path)

  cli_args = [
    '--headless',
    '-s', source_image_path,
    '-t', target_image_path,
    '-o', output_image_path,
    '--execution-providers', provider,
    # '--face-detector-model', 'yunet',
    '--face-analyser-order', 'large-small',
  ]

  cli_args += [ '--frame-processors', 'face_swapper' ]
  cli_args += ['--trim-frame-end',str(duration)]
  if enhance_face:
    cli_args += [
      'face_enhancer',
    ]

  if enhance_frame:
    cli_args += [
      'frame_enhancer',
    ]

  from facefusion.processors.frame.core import clear_frame_processors_modules
  clear_frame_processors_modules()

  run_cli(cli_args)

  return output_image_path

demo = gr.Interface(
  fn=swap_faces,
  inputs=[
      gr.Image(type="filepath"),
      gr.Video(),
      gr.Checkbox(label="Enhance Face", value=True),
      gr.Checkbox(label="Enhance Frame", value=True),
  ],
  outputs=[
      gr.Video()
  ],
  title="Swap Faces",
  allow_flagging="never"
)

if __name__ == "__main__":    
    demo.queue(api_open=True)
    demo.launch(show_error=True, show_api=True)