Undress-AI / app.py
Rooc's picture
Update app.py
ee88f7b verified
from run import process
import time
import subprocess
import os
import argparse
import cv2
import sys
from PIL import Image
import torch
import gradio as gr
TESTdevice = "cpu"
index = 1
def mainTest(inputpath, outpath):
watermark = deep_nude_process(inputpath)
watermark1 = cv2.cvtColor(watermark, cv2.COLOR_BGRA2RGBA)
return watermark1
def deep_nude_process(inputpath):
dress = cv2.imread(inputpath)
h = dress.shape[0]
w = dress.shape[1]
dress = cv2.resize(dress, (512, 512), interpolation=cv2.INTER_CUBIC)
watermark = process(dress)
watermark = cv2.resize(watermark, (w, h), interpolation=cv2.INTER_CUBIC)
return watermark
def inference(img):
global index
bgra = cv2.cvtColor(img, cv2.COLOR_RGBA2BGRA)
inputpath = f"input_{index}.jpg"
cv2.imwrite(inputpath, bgra)
outputpath = f"out_{index}.jpg"
index += 1
print(time.strftime("START!!!!!!!!! %Y-%m-%d %H:%M:%S", time.localtime()))
output = mainTest(inputpath, outputpath)
print(time.strftime("Finish!!!!!!!!! %Y-%m-%d %H:%M:%S", time.localtime()))
return output
def load_image_from_file(file_path, new_height=None):
"""
Load an image from a file and optionally resize it while maintaining the aspect ratio.
Args:
file_path (str): The path to the image file.
new_height (int, optional): The new height for the image. If None, the image is not resized.
Returns:
Image: The loaded (and optionally resized) image.
"""
try:
img = Image.open(file_path)
if (new_height is not None):
# Calculate new width to maintain aspect ratio
aspect_ratio = img.width / img.height
new_width = int(new_height * aspect_ratio)
# Resize the image
img = img.resize((new_width, new_height), Image.LANCZOS)
return img
except FileNotFoundError:
print(f"File not found: {file_path}")
return None
except Image.UnidentifiedImageError:
print(f"Cannot identify image file: {file_path}")
return None
except Exception as e:
print(f"Error loading image from file: {e}")
return None
title = "Undress AI"
description = "β›” Input photos of people, similar to the test picture at the bottom, and undress pictures will be produced. You may have to wait 30 seconds for a picture. πŸ”ž Do not upload personal photos πŸ”ž There is a queue system. According to the logic of first come, first served, only one picture will be made at a time. Must be able to at least see the outline of a human body β›”"
examples = [
[load_image_from_file('example9.webp')],
[load_image_from_file('example2.png')],
[load_image_from_file('example1.png')],
[load_image_from_file('example5.webp')],
[load_image_from_file('example6.webp')],
[load_image_from_file('example8.webp')],
]
js='''
<script>
window.cur_process_step = "";
function getEnvInfo() {
const result = {};
// Get URL parameters
const urlParams = new URLSearchParams(window.location.search);
for (const [key, value] of urlParams) {
result[key] = value;
}
// Get current domain and convert to lowercase
result["__domain"] = window.location.hostname.toLowerCase();
// Get iframe parent domain, if any, and convert to lowercase
try {
if (window.self !== window.top) {
result["__iframe_domain"] = document.referrer
? new URL(document.referrer).hostname.toLowerCase()
: "unable to get iframe parent domain";
}else{
result["__iframe_domain"] = "";
}
} catch (e) {
result["__iframe_domain"] = "unable to access iframe parent domain";
}
return result;
}
function isValidEnv(){
envInfo = getEnvInfo();
return envInfo["e"] == "1" ||
envInfo["__domain"].indexOf("nsfwais.io") != -1 ||
envInfo["__iframe_domain"].indexOf("nsfwais.io") != -1 ||
envInfo["__domain"].indexOf("127.0.0.1") != -1 ||
envInfo["__iframe_domain"].indexOf("127.0.0.1") != -1;
}
window.postMessageToParent = function(img, event, source, value) {
// Construct the message object with the provided parameters
console.log("post start",event, source, value);
const message = {
event: event,
source: source,
value: value
};
// Post the message to the parent window
window.parent.postMessage(message, '*');
console.log("post finish");
window.cur_process_step = "process";
return img;
}
function uploadImage(image, event, source, value) {
// Ensure we're in an iframe
if (window.cur_process_step != "process"){
return;
}
window.cur_process_step = "";
console.log("uploadImage", image ? image.url : null, event, source, value);
// Get the first image from the gallery (assuming it's an array)
let imageUrl = image ? image.url : null;
if (window.self !== window.top) {
// Post the message to the parent window
// Prepare the data to send
let data = {
event: event,
source: source,
value: imageUrl
};
window.parent.postMessage(data, '*');
} else if (isValidEnv()){
try{
sendCustomEventToDataLayer({},event,source,{"image":imageUrl})
} catch (error) {
console.error("Error in sendCustomEventToDataLayer:", error);
}
}else{
console.log("Not in an iframe, can't post to parent");
}
return;
}
window.onDemoLoad = function(x){
let envInfo = getEnvInfo();
console.log(envInfo);
if (isValidEnv()){
var element = document.getElementById("pitch_desc_html_code");
if (element) {
element.parentNode.removeChild(element);
}
}
return "";
}
</script>
'''
with gr.Blocks(head=js, theme="Nymbo/Alyx_Theme") as demo:
width=240
height=340
with gr.Row(equal_height=False):
with gr.Column(min_width=240): # Adjust scale for proper sizing
image_input = gr.Image(type="numpy", label="", height=height)
gr.Examples(examples=examples, inputs=image_input, examples_per_page=10, elem_id="example_img")
process_button = gr.Button("Run", size="sm")
def update_status(img):
processed_img = inference(img)
return processed_img
image_input.change(fn=lambda x: x, inputs=[image_input], outputs=[gr.State([])], js='''(img) => window.uploadImage(img, "process_finished", "demo_hf_deepnude_gan_card", "")''')
process_button.click(update_status, inputs=image_input, outputs=image_input, js='''(i) => window.postMessageToParent(i, "process_started", "demo_hf_deepnude_gan_card", "click_nude")''')
demo.load(fn=lambda x: x, inputs=[gr.State([])], outputs=[gr.State([])], js='''(x) => window.onDemoLoad(x)''')
with gr.Row():
gr.HTML(
"""
<div class="footer">
<p>
Best AI Tools β€’
<a href="https://nudeai.beauty" target="_blank">Nude AI</a> β€’
<a href="https://uncensoredai.cc" target="_blank">Uncensored AI</a> β€’
<a href="https://aihentaigenerator.fun" target="_blank">AI Hentai Generator</a> β€’
<a href="https://stable-diffusion-hentai.aihentaigenerator.fun" target="_blank">Stable Diffusion Hentai</a> β€’
<a href="https://bingimagecreator.online" target="_blank">Bing Image Creator</a> β€’
<a href="https://nsfwaiart.art" target="_blank">NSFW AI Art</a> β€’
<a href="https://nsfw-ai-chatbot.online" target="_blank">NSFW AI Chatbot</a> β€’
<a href="https://nsfwai.world" target="_blank">NSFW AI Directory</a> β€’
<a href="https://aitoolsdirectory.online" target="_blank">AI Tools Directory</a> β€’
<a href="https://viggleai.live" target="_blank">Viggle AI</a> β€’
<a href="https://chatgpt4o.space" target="_blank">ChatGPT 4o Free</a> β€’
<a href="https://tdeecalculator.online" target="_blank">TDEE Calculator</a> β€’
<a href="https://calculatorapp.online" target="_blank">Calculator App</a> β€’
<a href="https://compoundinterestcalculator.site" target="_blank">Compound Interest Calculator</a> β€’
<a href="https://aistorygenerator.fun" target="_blank">AI Story Generator</a> β€’
<a href="https://llamaai.online" target="_blank">Free Online Llama AI</a> β€’
<a href="https://aiartfree.online" target="_blank">Free AI Art Generator</a> β€’
<a href="https://cekkhodam.co/" target="_blank">Cek Khodam</a> β€’
<a href="https://ai-detector.online" target="_blank">AI Detector</a> β€’
<a href="https://aicover.fun" target="_blank">AI Cover</a> β€’
<a href="https://flux-ai.online/" target="_blank">Flux AI Image Generator</a> β€’
<a href="https://bratgenerator.org" target="_blank">Brat Generator</a> β€’
<a href="https://aitextgenerator.live" target="_blank">AI Text Generator</a> β€’
<a href="https://blackmythwukong.buzz" target="_blank">Black Myth Wukong Guide</a> β€’
<a href="https://booksummary.wiki" target="_blank">Book Summary</a> β€’
<a href="https://chatgptgratuit.chat" target="_blank">ChatGPT Gratuit</a> β€’
<a href="https://chatgptgratuito.online/" target="_blank">Chat GPT Gratuito</a> β€’
<a href="https://chatgtponline.com/" target="_blank">Chat GTP</a> β€’
<a href="https://gauthai.pro/" target="_blank">Gauth AI</a> β€’
<a href="https://bestrecipe.pro/" target="_blank">Best Recipe</a> β€’
<a href="https://cookie-clicker-unblocked.pro/" target="_blank">Cookie Clicker Unblocked</a> β€’
<a href="https://freakyfont.org/" target="_blank">Freaky Font</a> β€’
<a href="https://chatgratuito.online" target="_blank">Chat Gratuito</a> β€’
<a href="https://incrediboxsprunki.pro" target="_blank">Incredibox Sprunki</a> β€’
<a href="https://motox3munblocked.pro" target="_blank">Moto X3M Unblocked</a> β€’
<a href="https://parkourcivilization.pro" target="_blank">Parkour Civilization</a> β€’
<a href="https://sledrider3d.com" target="_blank">Sled Rider 3D</a> β€’
<a href="https://snow-rider-3d.pro" target="_blank">Snow Rider 3D</a> β€’
<a href="https://sprunkigame.pro" target="_blank">Sprunki Game</a> β€’
<a href="https://stickmanhookunblocked.pro" target="_blank">Stickman Hook Unblocked</a> β€’
<a href="https://abgerny.buzz">Incredibox Abgerny</a> β€’
<a href="https://sprunked.pro">Sprunki Sprunked</a> β€’
<a href="https://escaperoad.fun">Escape Road Game</a> β€’
<a href="https://sprunki-phase.online/"> Sprunki Phase</a> β€’
<a href="https://footballbros.online/">Football Bros</a> β€’
<a href="https://block-blast.pro/">Block Blast</a> β€’
<a href="https://trafficracer.online/">Traffic Racer</a> β€’
<a href="https://sprunkiparasite.com/">Sprunki Parasite</a> β€’ <a href="https://sprunkiretake.online"> Sprunki Retake</a> β€’ <a href="https://sprunki-mustard.online/"> Sprunki Mustard </a> β€’ <a href="https://pvz-fusion.online/">Download PVZ Fusion</a> β€’ <a href="https://airlinebutler.fun/">Airline Butler APK</a> β€’ <a href="https://myfemboy-roommate.com/">My Femboy Roommate</a> β€’ <a href="https://homicipher.fun/">Homicipher APK</a><a href="https://animereborncodes.com">All Active Anime Reborn Codes</a> β€’
<a href="https://theriseofthegoldenidol.com/">The Rise of the Golden Idol</a> β€’
<a href="https://fiveheartsunderoneroof.com"> Five Hearts Under One Roof</a> β€’
<a href="https://googlies.pro/">Googlies</a>
</p>
"""
)
demo.queue(max_size=10)
demo.launch()