FaceSwap / app.py
Rooni's picture
Update app.py
0ffaf55 verified
raw
history blame
1.81 kB
import gradio as gr
from gradio_client import Client, handle_file
import os
import random
from io import BytesIO
from PIL import Image
KEYS = os.getenv("KEYS").split(",")
def get_random_api_key():
return random.choice(KEYS)
def swap_face_api(source_img, target_img, doFaceEnhancer):
try:
api_key = get_random_api_key()
client = Client("tuan2308/face-swap")
# Конвертируем PIL изображения в байты
source_bytes = BytesIO()
source_img.save(source_bytes, format="JPEG") # или PNG, в зависимости от формата
source_bytes.seek(0)
target_bytes = BytesIO()
target_img.save(target_bytes, format="JPEG") # или PNG, в зависимости от формата
target_bytes.seek(0)
result = client.predict(
source_file=handle_file(source_bytes.read(), filename="source.jpg"), # Добавляем имя файла
target_file=handle_file(target_bytes.read(), filename="target.jpg"), # Добавляем имя файла
doFaceEnhancer=doFaceEnhancer,
api_name="/predict",
api_key=api_key
)
# Конвертируем результат из байтов обратно в PIL Image
output_image = Image.open(BytesIO(result))
return output_image
except Exception as e:
print(f"Ошибка при вызове API: {e}")
return None
iface = gr.Interface(
fn=swap_face_api,
inputs=[
gr.Image(type="pil", label="Source Image"),
gr.Image(type="pil", label="Target Image"),
gr.Checkbox(label="Face Enhancer?")
],
outputs=gr.Image(type="pil", label="Output Image"),
title="Face Swap via API"
)
iface.launch()