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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
model_name = '$model_name'
|
| 7 |
+
prefix = '$prefix'
|
| 8 |
+
|
| 9 |
+
scheduler = DPMSolverMultistepScheduler(
|
| 10 |
+
beta_start=0.00085,
|
| 11 |
+
beta_end=0.012,
|
| 12 |
+
beta_schedule="scaled_linear",
|
| 13 |
+
num_train_timesteps=1000,
|
| 14 |
+
trained_betas=None,
|
| 15 |
+
predict_epsilon=True,
|
| 16 |
+
thresholding=False,
|
| 17 |
+
algorithm_type="dpmsolver++",
|
| 18 |
+
solver_type="midpoint",
|
| 19 |
+
lower_order_final=True,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
last_mode = "txt2img"
|
| 23 |
+
|
| 24 |
+
def get_pipe(img2img=False):
|
| 25 |
+
|
| 26 |
+
if img2img:
|
| 27 |
+
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
|
| 28 |
+
model_name,
|
| 29 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else 'auto',
|
| 30 |
+
scheduler=scheduler)
|
| 31 |
+
else:
|
| 32 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 33 |
+
model_name,
|
| 34 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else 'auto',
|
| 35 |
+
scheduler=scheduler)
|
| 36 |
+
|
| 37 |
+
if torch.cuda.is_available():
|
| 38 |
+
pipe = pipe.to("cuda")
|
| 39 |
+
|
| 40 |
+
return pipe
|
| 41 |
+
|
| 42 |
+
pipe = get_pipe()
|
| 43 |
+
|
| 44 |
+
device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
|
| 45 |
+
|
| 46 |
+
def error_str(error, title="Error"):
|
| 47 |
+
return f"""#### {title}
|
| 48 |
+
{error}""" if error else ""
|
| 49 |
+
|
| 50 |
+
def inference(prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt="", auto_prefix=True):
|
| 51 |
+
|
| 52 |
+
generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
|
| 53 |
+
prompt = f"{prefix} {prompt}" if auto_prefix else prompt
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
if img is not None:
|
| 57 |
+
return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
|
| 58 |
+
else:
|
| 59 |
+
return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return None, error_str(e)
|
| 62 |
+
|
| 63 |
+
def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator):
|
| 64 |
+
|
| 65 |
+
global last_mode
|
| 66 |
+
global pipe
|
| 67 |
+
if last_mode != "txt2img":
|
| 68 |
+
|
| 69 |
+
pipe = get_pipe()
|
| 70 |
+
last_mode = "txt2img"
|
| 71 |
+
|
| 72 |
+
prompt = prompt
|
| 73 |
+
result = pipe(
|
| 74 |
+
prompt,
|
| 75 |
+
negative_prompt = neg_prompt,
|
| 76 |
+
num_inference_steps = int(steps),
|
| 77 |
+
guidance_scale = guidance,
|
| 78 |
+
width = width,
|
| 79 |
+
height = height,
|
| 80 |
+
generator = generator)
|
| 81 |
+
|
| 82 |
+
return replace_nsfw_images(result)
|
| 83 |
+
|
| 84 |
+
def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
|
| 85 |
+
|
| 86 |
+
global last_mode
|
| 87 |
+
global pipe
|
| 88 |
+
if last_mode != "img2img":
|
| 89 |
+
|
| 90 |
+
pipe = get_pipe(img2img=True)
|
| 91 |
+
last_mode = "img2img"
|
| 92 |
+
|
| 93 |
+
prompt = prompt
|
| 94 |
+
ratio = min(height / img.height, width / img.width)
|
| 95 |
+
img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
|
| 96 |
+
result = pipe(
|
| 97 |
+
prompt,
|
| 98 |
+
negative_prompt = neg_prompt,
|
| 99 |
+
init_image = img,
|
| 100 |
+
num_inference_steps = int(steps),
|
| 101 |
+
strength = strength,
|
| 102 |
+
guidance_scale = guidance,
|
| 103 |
+
width = width,
|
| 104 |
+
height = height,
|
| 105 |
+
generator = generator)
|
| 106 |
+
|
| 107 |
+
return replace_nsfw_images(result)
|
| 108 |
+
|
| 109 |
+
def replace_nsfw_images(results):
|
| 110 |
+
|
| 111 |
+
for i in range(len(results.images)):
|
| 112 |
+
if results.nsfw_content_detected[i]:
|
| 113 |
+
results.images[i] = Image.open("nsfw.png")
|
| 114 |
+
return results.images[0]
|
| 115 |
+
|
| 116 |
+
css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
|
| 117 |
+
"""
|
| 118 |
+
with gr.Blocks(css=css) as demo:
|
| 119 |
+
gr.HTML(
|
| 120 |
+
f"""
|
| 121 |
+
<div class="main-div">
|
| 122 |
+
<div>
|
| 123 |
+
<h1>$model_name</h1>
|
| 124 |
+
</div>
|
| 125 |
+
<p>
|
| 126 |
+
Demo for the <a href="https://huggingface.co/$model_name">$model_name</a> Stable Diffusion model.<br>
|
| 127 |
+
Add the following tokens to your prompts for the effect: <b>$prefix</b>.
|
| 128 |
+
</p>
|
| 129 |
+
</div>
|
| 130 |
+
"""
|
| 131 |
+
)
|
| 132 |
+
with gr.Row():
|
| 133 |
+
|
| 134 |
+
with gr.Column(scale=55):
|
| 135 |
+
with gr.Group():
|
| 136 |
+
with gr.Row(variant='box'):
|
| 137 |
+
prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False)
|
| 138 |
+
generate = gr.Button(value="Generate")
|
| 139 |
+
|
| 140 |
+
image_out = gr.Image(height=512)
|
| 141 |
+
error_output = gr.Markdown()
|
| 142 |
+
|
| 143 |
+
with gr.Column(scale=45):
|
| 144 |
+
with gr.Tab("Options"):
|
| 145 |
+
with gr.Group():
|
| 146 |
+
neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
|
| 147 |
+
auto_prefix = gr.Checkbox(label="Prefix styling tokens automatically ($prefix)", value=True)
|
| 148 |
+
|
| 149 |
+
with gr.Row():
|
| 150 |
+
guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
|
| 151 |
+
steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
|
| 152 |
+
|
| 153 |
+
with gr.Row():
|
| 154 |
+
width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
|
| 155 |
+
height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
|
| 156 |
+
|
| 157 |
+
seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
|
| 158 |
+
|
| 159 |
+
with gr.Tab("Image to image"):
|
| 160 |
+
with gr.Group():
|
| 161 |
+
image = gr.Image(label="Image", height=256, tool="editor", type="pil")
|
| 162 |
+
strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
|
| 163 |
+
|
| 164 |
+
auto_prefix.change(lambda x: gr.update(placeholder=f"{prefix} [your prompt]" if x else "[Your prompt]"), inputs=auto_prefix, outputs=prompt, queue=False)
|
| 165 |
+
|
| 166 |
+
inputs = [prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, auto_prefix]
|
| 167 |
+
outputs = [image_out, error_output]
|
| 168 |
+
prompt.submit(inference, inputs=inputs, outputs=outputs)
|
| 169 |
+
generate.click(inference, inputs=inputs, outputs=outputs)
|
| 170 |
+
|
| 171 |
+
gr.HTML("""
|
| 172 |
+
<div style="border-top: 1px solid #303030;">
|
| 173 |
+
<br>
|
| 174 |
+
<p>This space was created using <a href="https://huggingface.co/spaces/anzorq/sd-space-creator">SD Space Creator</a>.</p>
|
| 175 |
+
</div>
|
| 176 |
+
""")
|
| 177 |
+
|
| 178 |
+
demo.queue(concurrency_count=1)
|
| 179 |
+
demo.launch()
|