SaEdit-MultiAi / face_swap.py
Stiphan's picture
Add AI Face Swap Video feature
8005ca5 verified
import gradio as gr
import requests
import tempfile
import os
# Hugging Face API Config
HF_API_TOKEN = "YOUR_HF_API_KEY" # Apna token lagao
MODEL_URL = "https://api-inference.huggingface.co/models/deepinsight/inswapper"
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}
def swap_face(video_file, face_image):
"""πŸŽ₯ Video + Face β†’ AI Swapped Video"""
if video_file is None or face_image is None:
return None
try:
# Save temp video
temp_vid = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
with open(temp_vid.name, "wb") as f:
f.write(video_file.read())
# Save temp face image
temp_face = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
face_image.save(temp_face.name)
# Send to Hugging Face model (if supports both inputs together)
files = {
"video": open(temp_vid.name, "rb"),
"target_face": open(temp_face.name, "rb")
}
resp = requests.post(MODEL_URL, headers=HEADERS, files=files)
if resp.status_code != 200:
print("Error:", resp.text)
return None
# Save output
temp_output = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
with open(temp_output.name, "wb") as f:
f.write(resp.content)
return temp_output.name
except Exception as e:
print(f"Error: {e}")
return None
# ---------- Gradio UI ----------
with gr.Blocks() as demo:
gr.Markdown("<h2 style='text-align:center'>πŸ€– AI Face Swap Video β€” SaEdit MultiAi</h2>")
vid_input = gr.File(type="file", file_types=[".mp4"], label="πŸŽ₯ Upload Target Video")
face_input = gr.Image(type="pil", label="πŸ–Ό Upload Face Image")
btn = gr.Button("πŸ”„ Swap Face")
output_video = gr.Video(label="🎬 Face Swapped Output")
btn.click(swap_face, inputs=[vid_input, face_input], outputs=output_video)
if __name__ == "__main__":
demo.launch()