Image-Face-Swap / app.py
Jonny001's picture
Update app.py
344be82 verified
raw
history blame
2.89 kB
import gradio as gr
import roop.globals
from roop.core import (
start,
decode_execution_providers,
suggest_max_memory,
suggest_execution_threads,
)
from roop.processors.frame.core import get_frame_processors_modules
from roop.utilities import normalize_output_path
from PIL import Image
import io
def process_face_swap(source_image, target_image, apply_face_enhancer):
# Convert images to PIL Image objects and save them to in-memory file-like objects
src_image_bytes = io.BytesIO()
tgt_image_bytes = io.BytesIO()
source_image.save(src_image_bytes, format='JPEG')
target_image.save(tgt_image_bytes, format='JPEG')
src_image_bytes.seek(0)
tgt_image_bytes.seek(0)
src_image_path = "source_image.jpg"
tgt_image_path = "target_image.jpg"
output_path = "result_image.jpg"
with open(src_image_path, 'wb') as f:
f.write(src_image_bytes.getvalue())
with open(tgt_image_path, 'wb') as f:
f.write(tgt_image_bytes.getvalue())
# Set Roop configuration
roop.globals.source_path = src_image_path
roop.globals.target_path = tgt_image_path
roop.globals.output_path = normalize_output_path(
roop.globals.source_path, roop.globals.target_path, output_path
)
roop.globals.frame_processors = ["face_swapper", "face_enhancer"] if apply_face_enhancer else ["face_swapper"]
roop.globals.headless = True
roop.globals.keep_fps = True
roop.globals.keep_audio = True
roop.globals.keep_frames = False
roop.globals.many_faces = False
roop.globals.video_encoder = "libx264"
roop.globals.video_quality = 18
roop.globals.max_memory = suggest_max_memory()
roop.globals.execution_providers = decode_execution_providers(["cuda", "cpu"])
roop.globals.execution_threads = suggest_execution_threads()
# Print paths for debugging
print(f"Starting the process with:")
print(f"Source: {roop.globals.source_path}")
print(f"Target: {roop.globals.target_path}")
print(f"Output: {roop.globals.output_path}")
# Execute face swap process
for processor in get_frame_processors_modules(roop.globals.frame_processors):
if not processor.pre_check():
return
start()
# Load and return the output image
with open(roop.globals.output_path, 'rb') as f:
output_image = f.read()
return output_image
# Create Gradio interface
iface = gr.Interface(
fn=process_face_swap,
inputs=[
gr.Image(type="pil", label="Source Image"),
gr.Image(type="pil", label="Target Image"),
gr.Checkbox(label="Apply Face Enhancer")
],
outputs=gr.Image(type="pil"),
description="Swap faces between two images. Use the face enhancer option to improve the result. Processing may take longer if you use Face Enhancer. Becose this Modle is running using CPU."
)
iface.launch()