File size: 3,743 Bytes
8b9f861
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7157f11
8b9f861
7157f11
 
 
 
8b9f861
 
 
 
 
7157f11
 
8b9f861
 
 
 
 
 
7157f11
 
 
 
 
7e981ff
7157f11
 
 
 
 
 
8b9f861
 
 
 
 
 
 
 
 
 
7157f11
 
8b9f861
7157f11
8b9f861
 
7157f11
 
8b9f861
 
 
 
 
 
7157f11
8b9f861
 
7157f11
8b9f861
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import gradio as gr
from refacer import Refacer
import argparse
import os
import requests

# Hugging Face URL to download the model
model_url = "https://huggingface.co/ofter/4x-UltraSharp/resolve/main/inswapper_128.onnx"
model_path = "./inswapper_128.onnx"

# Function to download the model
def download_model():
    if not os.path.exists(model_path):
        print("Downloading inswapper_128.onnx...")
        response = requests.get(model_url)
        if response.status_code == 200:
            with open(model_path, 'wb') as f:
                f.write(response.content)
            print("Model downloaded successfully!")
        else:
            raise Exception(f"Failed to download the model. Status code: {response.status_code}")
    else:
        print("Model already exists.")

# Download the model when the script runs
download_model()

# Argument parser
parser = argparse.ArgumentParser(description='Refacer')
parser.add_argument("--max_num_faces", type=int, help="Max number of faces on UI", default=5)
parser.add_argument("--force_cpu", help="Force CPU mode", default=False, action="store_true")
parser.add_argument("--share_gradio", help="Share Gradio", default=False, action="store_true")
parser.add_argument("--server_name", type=str, help="Server IP address", default="127.0.0.1")
parser.add_argument("--server_port", type=int, help="Server port", default=7860)
parser.add_argument("--colab_performance", help="Use in colab for better performance", default=False, action="store_true")
args = parser.parse_args()

# Initialize the Refacer class
refacer = Refacer(force_cpu=args.force_cpu, colab_performance=args.colab_performance)
num_faces = args.max_num_faces

# Function to process refacing
def run(*vars):
    video_path = vars[0]  # Original video path
    if not video_path:
        raise ValueError("Video file not found. Please upload a valid video.")
    
    origins = vars[1:(num_faces+1)]
    destinations = vars[(num_faces+1):(num_faces*2)+1]
    thresholds = vars[(num_faces*2)+1:]

    faces = []
    for k in range(num_faces):
        if origins[k] and destinations[k]:
            faces.append({
                'origin': origins[k],
                'destination': destinations[k],
                'threshold': thresholds[k]
            })

    try:
        # Call refacer to process video and return bytes
        refaced_video_path = refacer.reface(video_path, faces)
        with open(refaced_video_path, "rb") as f:
            video_bytes = f.read()

        # Cleanup temporary file
        os.remove(refaced_video_path)
        return video_bytes
    except Exception as e:
        print(f"Error during refacing: {e}")
        raise RuntimeError("Video refacing failed. Check logs.")

# Prepare Gradio components
origin = []
destination = []
thresholds = []

with gr.Blocks() as demo:
    with gr.Row():
        gr.Markdown("# Refacer")
    with gr.Row():
        video = gr.Video(label="Original Video", format="mp4")
        video2 = gr.Video(label="Refaced Video", interactive=False, format="mp4")

    for i in range(num_faces):
        with gr.Tab(f"Face #{i+1}"):
            with gr.Row():
                origin.append(gr.Image(label="Face to Replace"))
                destination.append(gr.Image(label="Destination Face"))
            with gr.Row():
                thresholds.append(gr.Slider(label="Threshold", minimum=0.0, maximum=1.0, value=0.2))
    
    with gr.Row():
        button = gr.Button("Reface", variant="primary")

    # Configure button click
    button.click(fn=run, inputs=[video] + origin + destination + thresholds, outputs=[video2])

# Launch Gradio app
demo.queue().launch(show_error=True, share=args.share_gradio, server_name="0.0.0.0", server_port=args.server_port)