Face-Swap / app.py
Rooc's picture
Update app.py
733a7df verified
raw
history blame
6.81 kB
import insightface
import os
import onnxruntime
import cv2
import gfpgan
import tempfile
import time
import gradio as gr
class Predictor:
def __init__(self):
self.setup()
def setup(self):
os.makedirs('models', exist_ok=True)
os.chdir('models')
if not os.path.exists('GFPGANv1.4.pth'):
os.system(
'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth'
)
if not os.path.exists('inswapper_128.onnx'):
os.system(
'wget https://huggingface.co/ashleykleynhans/inswapper/resolve/main/inswapper_128.onnx'
)
os.chdir('..')
"""Load the model into memory to make running multiple predictions efficient"""
self.face_swapper = insightface.model_zoo.get_model('models/inswapper_128.onnx',
providers=onnxruntime.get_available_providers())
self.face_enhancer = gfpgan.GFPGANer(model_path='models/GFPGANv1.4.pth', upscale=1)
self.face_analyser = insightface.app.FaceAnalysis(name='buffalo_l')
self.face_analyser.prepare(ctx_id=0, det_size=(640, 640))
def get_face(self, img_data):
analysed = self.face_analyser.get(img_data)
try:
largest = max(analysed, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))
return largest
except:
print("No face found")
return None
def predict(self, input_image, swap_image):
"""Run a single prediction on the model"""
try:
frame = cv2.imread(input_image.name)
face = self.get_face(frame)
source_face = self.get_face(cv2.imread(swap_image.name))
try:
print(frame.shape, face.shape, source_face.shape)
except:
print("printing shapes failed.")
result = self.face_swapper.get(frame, face, source_face, paste_back=True)
_, _, result = self.face_enhancer.enhance(
result,
paste_back=True
)
out_path = tempfile.mkdtemp() + f"/{str(int(time.time()))}.jpg"
cv2.imwrite(out_path, result)
return out_path
except Exception as e:
print(f"{e}")
return None
# Instantiate the Predictor class
predictor = Predictor()
title = "Swap Faces Using Our Model!!!"
with gr.Blocks() as iface:
gr.Markdown(title)
with gr.Row():
with gr.Column():
input_image = gr.Image(type="file", label="Target Image")
swap_image = gr.Image(type="file", label="Swap Image")
submit_btn = gr.Button("Swap Faces")
with gr.Column():
output_image = gr.Image(type="file", label="Result")
submit_btn.click(
fn=predictor.predict,
inputs=[input_image, swap_image],
outputs=output_image
)
gr.Markdown("""
**Best AI Tools**
[Nude AI](https://nudeai.beauty) • [Uncensored AI](https://uncensoredai.cc) • [AI Hentai Generator](https://aihentaigenerator.fun) • [Stable Diffusion Hentai](https://stable-diffusion-hentai.aihentaigenerator.fun) • [Bing Image Creator](https://bingimagecreator.online) • [NSFW AI Art](https://nsfwaiart.art) • [NSFW AI Chatbot](https://nsfw-ai-chatbot.online) • [NSFW AI World](https://nsfwai.world) • [AI Tools Directory](https://aitoolsdirectory.online) • [Viggle AI](https://viggleai.live) • [TDEE Calculator](https://tdeecalculator.online) • [Calculator App](https://calculatorapp.online) • [Compound Interest Calculator](https://compoundinterestcalculator.site) • [AI Story Generator](https://aistorygenerator.fun) • [Llama AI](https://llamaai.online) • [AI Art Free](https://aiartfree.online) • [Cek Khodam](https://cekkhodam.co) • [AI Detector](https://ai-detector.online) • [AI Cover](https://aicover.fun) • [Flux AI](https://flux-ai.online) • [Brat Generator](https://bratgenerator.org) • [AI Text Generator](https://aitextgenerator.live) • [Black Myth Wukong](https://blackmythwukong.buzz) • [Book Summary](https://booksummary.wiki) • [ChatGPT Gratuit](https://chatgptgratuit.chat) • [ChatGPT Online](https://chatgtponline.com) • [Gau Thai](https://gauthai.pro) • [Best Recipe](https://bestrecipe.pro)
**Games**
[Cookie Clicker Unblocked](https://cookie-clicker-unblocked.pro) • [Freaky Font](https://freakyfont.org) • [Chat Gratuito](https://chatgratuito.online) • [Incredibox Sprunki](https://incrediboxsprunki.pro) • [Moto X3M Unblocked](https://motox3munblocked.pro) • [Parkour Civilization](https://parkourcivilization.pro) • [Sled Rider 3D](https://sledrider3d.com) • [Snow Rider 3D](https://snow-rider-3d.pro) • [Sprunki Game](https://sprunkigame.pro) • [Stickman Hook Unblocked](https://stickmanhookunblocked.pro) • [Escape Road](https://escaperoad.fun) • [Sprunked](https://sprunked.pro) • [Abgerny](https://abgerny.buzz)• [Sprunki Phase](https://sprunki-phase.online) • [Block Blast](https://block-blast.pro) • [Traffic Racer](https://trafficracer.online) • [Football Bros](https://footballbros.online) • [Sprunki Parasite](https://sprunkiparasite.com) • [Sprunki Retake](https://sprunkiretake.online) • [Sprunki Mustard](https://sprunki-mustard.online) • [PVZ Fusion Download](https://pvz-fusion.online) • [My Femboy Roommate](https://myfemboy-roommate.com) • [Homicipher](https://homicipher.fun) • [Anime Reborn Codes](https://animereborncodes.com) • [The Rise of the Golden Idol](https://theriseofthegoldenidol.com/) • [Five Hearts Under One Roof](https://fiveheartsunderoneroof.com) • [Googlies](https://googlies.pro/) • [Discordservers Wiki](https://discordservers.wiki) • [Laundry Store Simulator](https://laundrystoresimulator.com) • [Chill Guy Clicker](https://chillguyclicker.fun) • [Aurelia Game](https://aureliagame.com) • [Kiwi Mod](https://kiwimod.com) • [Doodle Empires](https://doodleempires.org) • [Codes Rob](https://codesrob.com) • [Em Manga](https://emmanga.com) • [Chocolate Factory Sim](https://chocolatefactorysim.com) • [Desktop Mate](https://desktop-mate.com) • [Yellow Mod](https://yellowmod.com) • [PP Novel](https://ppnovel.org) • [Phi4 Chat](https://phi4.chat) • [Streamer Life Simulator 2](https://streamerlifesimulator2.org) • [Ninja Gaiden 2 Black](https://ninjagaiden2black.xyz) • [Dynasty Warriors Origins](https://dynastywarriorsorigins.org) • [Block Breaker](https://block-breaker.online) • [Game Repacks](https://gamerepacks.com) • [Em Manga](https://emmanga.com) • [Amenti Game](https://amentigame.com)
""")
# Launch the Gradio Interface
iface.launch()