face_swap_api / app.py
navonapp's picture
Update app.py
5aa8d2e verified
import gradio as gr
import subprocess
import uuid
import os
def swap_faces(source_file, target_file, mode):
output_ext = "jpg" if mode in ["image_to_image", "selfie_to_selfie"] else "mp4"
output_path = f"/tmp/output_{uuid.uuid4().hex}.{output_ext}"
tmp_source = f"/tmp/source_{uuid.uuid4().hex}.jpg"
tmp_target = f"/tmp/target_{uuid.uuid4().hex}"
if mode == "image_to_video":
tmp_target += ".mp4"
else:
tmp_target += ".jpg"
with open(tmp_source, "wb") as f:
f.write(source_file)
with open(tmp_target, "wb") as f:
f.write(target_file)
command = [
"python3", "facefusion.py", "run",
"--source-paths", tmp_source,
"--target-path", tmp_target,
"--output-path", output_path,
"--processors", "face_swapper",
"--log-level", "debug"
]
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("=== STDOUT ===")
print(result.stdout.decode())
print("=== STDERR ===")
print(result.stderr.decode())
if result.returncode != 0:
raise Exception(f"Processing failed:\n{result.stderr.decode()}")
# โœ… ื‘ื“ื™ืงื” ืื ื”ืงื•ื‘ืฅ ื ื•ืฆืจ ื‘ืืžืช
if not os.path.exists(output_path):
raise Exception("โŒ ื”ืงื•ื‘ืฅ ืœื ื ื•ืฆืจ โ€“ ื›ื ืจืื” ืฉื”ืชื”ืœื™ืš ื ื›ืฉืœ ืคื ื™ืžื™ืช ื‘ืœื™ ืœื”ื—ื–ื™ืจ ืฉื’ื™ืื”.")
return output_path
iface = gr.Interface(
fn=swap_faces,
inputs=[
gr.File(label="ื‘ื—ืจ ืชืžื•ื ืช ืžืงื•ืจ (Selfie)", type="binary"),
gr.File(label="ื‘ื—ืจ ื™ืขื“ (ืชืžื•ื ื” ืžื”ื’ืœืจื™ื” ืื• ื•ื™ื“ืื•)", type="binary"),
gr.Radio(
choices=[
("ื”ื—ืœืคืช ืคื ื™ื ืœืชืžื•ื ื” ืžื”ื’ืœืจื™ื”", "image_to_image"),
("ืฉื ื™ ืื ืฉื™ื ืžื—ืœื™ืคื™ื ืคื ื™ื", "selfie_to_selfie"),
("ื”ื—ืœืคืช ืคื ื™ื ืขืœ ื•ื™ื“ืื•", "image_to_video")
],
label="ื‘ื—ืจ ืžืฆื‘ ืคืขื•ืœื”",
value="image_to_image"
)
],
outputs=gr.File(label="ืงื•ื‘ืฅ ืชื•ืฆืื”"),
title="๐ŸŽญ FaceFusion API - ื”ืขืœืืช ืงื‘ืฆื™ื",
description="ื”ืขืœื” ืฉื ื™ ืงื‘ืฆื™ื (ืชืžื•ื ื•ืช ืื• ื•ื™ื“ืื•), ื•ื‘ื—ืจ ืืช ืกื•ื’ ื”ื”ืžืจื” ืฉืชืจืฆื” ืœื‘ืฆืข"
)
iface.launch()