|
import gradio as gr |
|
from gradio_client import Client |
|
import os |
|
import random |
|
from io import BytesIO |
|
from PIL import Image |
|
import base64 |
|
|
|
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") |
|
|
|
|
|
source_b64 = gr.encode_pil_to_base64(source_img) |
|
target_b64 = gr.encode_pil_to_base64(target_img) |
|
|
|
result = client.predict( |
|
source_file=source_b64, |
|
target_file=target_b64, |
|
doFaceEnhancer=doFaceEnhancer, |
|
api_name="/predict", |
|
api_key=api_key |
|
) |
|
print(result) |
|
|
|
|
|
result_decoded = base64.b64decode(result) |
|
output_image = Image.open(BytesIO(result_decoded)) |
|
return output_image |
|
|
|
except Exception as e: |
|
print(f"Ошибка при вызове API: {e}") |
|
return None |
|
|
|
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() |
|
|