nightfury/Stable_Diffusion
1
1import gradio as gr2#import torch3#from torch import autocast // only for GPU4 5from PIL import Image6import numpy as np7from io import BytesIO8import os9MY_SECRET_TOKEN=os.environ.get('HF_TOKEN_SD')10 11from diffusers import StableDiffusionImg2ImgPipeline12 13print("hello sylvain")14 15YOUR_TOKEN=MY_SECRET_TOKEN16 17device="cpu"18 19#prompt_pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=YOUR_TOKEN)20#prompt_pipe.to(device)21 22img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=YOUR_TOKEN)23img_pipe.to(device)24 25source_img = gr.Image(source="upload", type="filepath", label="init_img | 512*512 px")26gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="auto")27 28def resize(value,img):29 #baseheight = value30 img = Image.open(img)31 #hpercent = (baseheight/float(img.size[1]))32 #wsize = int((float(img.size[0])*float(hpercent)))33 #img = img.resize((wsize,baseheight), Image.Resampling.LANCZOS)34 img = img.resize((value,value), Image.Resampling.LANCZOS)35 return img36 37 38def infer(prompt, source_img): 39 40 source_image = resize(512, source_img)41 source_image.save('source.png')42 images_list = img_pipe([prompt] * 2, init_image=source_image, strength=0.75)43 images = []44 safe_image = Image.open(r"unsafe.png")45 for i, image in enumerate(images_list["sample"]):46 if(images_list["nsfw_content_detected"][i]):47 images.append(safe_image)48 else:49 images.append(image) 50 return images51 52print("Great sylvain ! Everything is working fine !")53 54title="Img2Img Stable Diffusion CPU"55description="Img2Img Stable Diffusion example using CPU and HF token. <br />Warning: Slow process... ~5/10 min inference time. <b>NSFW filter enabled.</b>" 56 57gr.Interface(fn=infer, inputs=["text", source_img], outputs=gallery,title=title,description=description).queue(max_size=100).launch(enable_queue=True)