akhaliq HF staff commited on
Commit
ea62cc4
1 Parent(s): d2eb062

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +276 -0
app.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import AutoencoderKL, UNet2DConditionModel, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+ import utils
6
+ import datetime
7
+ import time
8
+ import psutil
9
+
10
+ start_time = time.time()
11
+ is_colab = utils.is_google_colab()
12
+
13
+ class Model:
14
+ def __init__(self, name, path="", prefix=""):
15
+ self.name = name
16
+ self.path = path
17
+ self.prefix = prefix
18
+ self.pipe_t2i = None
19
+ self.pipe_i2i = None
20
+
21
+ models = [
22
+ Model("anything v3", "Linaqruf/anything-v3.0", "anything v3 style"),
23
+ ]
24
+ # Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "),
25
+ # Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "),
26
+ # Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "),
27
+ # Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ")
28
+ #Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""),
29
+ #Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""),
30
+ #Model("Robo Diffusion", "nousr/robo-diffusion", ""),
31
+
32
+ scheduler = DPMSolverMultistepScheduler(
33
+ beta_start=0.00085,
34
+ beta_end=0.012,
35
+ beta_schedule="scaled_linear",
36
+ num_train_timesteps=1000,
37
+ trained_betas=None,
38
+ predict_epsilon=True,
39
+ thresholding=False,
40
+ algorithm_type="dpmsolver++",
41
+ solver_type="midpoint",
42
+ lower_order_final=True,
43
+ )
44
+
45
+ custom_model = None
46
+ if is_colab:
47
+ models.insert(0, Model("Custom model"))
48
+ custom_model = models[0]
49
+
50
+ last_mode = "txt2img"
51
+ current_model = models[1] if is_colab else models[0]
52
+ current_model_path = current_model.path
53
+
54
+ if is_colab:
55
+ pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
56
+
57
+ else: # download all models
58
+ print(f"{datetime.datetime.now()} Downloading vae...")
59
+ vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae", torch_dtype=torch.float16)
60
+ for model in models:
61
+ try:
62
+ print(f"{datetime.datetime.now()} Downloading {model.name} model...")
63
+ unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet", torch_dtype=torch.float16)
64
+ model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
65
+ model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
66
+ except Exception as e:
67
+ print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e))
68
+ models.remove(model)
69
+ pipe = models[0].pipe_t2i
70
+
71
+ if torch.cuda.is_available():
72
+ pipe = pipe.to("cuda")
73
+
74
+ device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
75
+
76
+ def error_str(error, title="Error"):
77
+ return f"""#### {title}
78
+ {error}""" if error else ""
79
+
80
+ def custom_model_changed(path):
81
+ models[0].path = path
82
+ global current_model
83
+ current_model = models[0]
84
+
85
+ def on_model_change(model_name):
86
+
87
+ prefix = "Enter prompt. \"" + next((m.prefix for m in models if m.name == model_name), None) + "\" is prefixed automatically" if model_name != models[0].name else "Don't forget to use the custom model prefix in the prompt!"
88
+
89
+ return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix)
90
+
91
+ def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
92
+
93
+ print(psutil.virtual_memory()) # print memory usage
94
+
95
+ global current_model
96
+ for model in models:
97
+ if model.name == model_name:
98
+ current_model = model
99
+ model_path = current_model.path
100
+
101
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
102
+
103
+ try:
104
+ if img is not None:
105
+ return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
106
+ else:
107
+ return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator), None
108
+ except Exception as e:
109
+ return None, error_str(e)
110
+
111
+ def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator):
112
+
113
+ print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
114
+
115
+ global last_mode
116
+ global pipe
117
+ global current_model_path
118
+ if model_path != current_model_path or last_mode != "txt2img":
119
+ current_model_path = model_path
120
+
121
+ if is_colab or current_model == custom_model:
122
+ pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
123
+ else:
124
+ pipe = pipe.to("cpu")
125
+ pipe = current_model.pipe_t2i
126
+
127
+ if torch.cuda.is_available():
128
+ pipe = pipe.to("cuda")
129
+ last_mode = "txt2img"
130
+
131
+ prompt = current_model.prefix + prompt
132
+ result = pipe(
133
+ prompt,
134
+ negative_prompt = neg_prompt,
135
+ # num_images_per_prompt=n_images,
136
+ num_inference_steps = int(steps),
137
+ guidance_scale = guidance,
138
+ width = width,
139
+ height = height,
140
+ generator = generator)
141
+
142
+ return replace_nsfw_images(result)
143
+
144
+ def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
145
+
146
+ print(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
147
+
148
+ global last_mode
149
+ global pipe
150
+ global current_model_path
151
+ if model_path != current_model_path or last_mode != "img2img":
152
+ current_model_path = model_path
153
+
154
+ if is_colab or current_model == custom_model:
155
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
156
+ else:
157
+ pipe = pipe.to("cpu")
158
+ pipe = current_model.pipe_i2i
159
+
160
+ if torch.cuda.is_available():
161
+ pipe = pipe.to("cuda")
162
+ last_mode = "img2img"
163
+
164
+ prompt = current_model.prefix + prompt
165
+ ratio = min(height / img.height, width / img.width)
166
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
167
+ result = pipe(
168
+ prompt,
169
+ negative_prompt = neg_prompt,
170
+ # num_images_per_prompt=n_images,
171
+ init_image = img,
172
+ num_inference_steps = int(steps),
173
+ strength = strength,
174
+ guidance_scale = guidance,
175
+ width = width,
176
+ height = height,
177
+ generator = generator)
178
+
179
+ return replace_nsfw_images(result)
180
+
181
+ def replace_nsfw_images(results):
182
+
183
+ if is_colab:
184
+ return results.images[0]
185
+
186
+ for i in range(len(results.images)):
187
+ if results.nsfw_content_detected[i]:
188
+ results.images[i] = Image.open("nsfw.png")
189
+ return results.images[0]
190
+
191
+ css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
192
+ """
193
+ with gr.Blocks(css=css) as demo:
194
+ gr.HTML(
195
+ f"""
196
+ <div class="finetuned-diffusion-div">
197
+ <div>
198
+ <h1>Anything V3</h1>
199
+ </div>
200
+ <p>
201
+ Demo for Anything V3
202
+ </p>
203
+ <p>You can skip the queue by duplicating this space: <a style="display:inline-block" href="https://huggingface.co/spaces/akhaliq/anything-v3.0?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a> </p>
204
+ </p>
205
+ </div>
206
+ """
207
+ )
208
+ with gr.Row():
209
+
210
+ with gr.Column(scale=55):
211
+ with gr.Group():
212
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
213
+ with gr.Box(visible=False) as custom_model_group:
214
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True)
215
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
216
+
217
+ with gr.Row():
218
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False)
219
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
220
+
221
+
222
+ image_out = gr.Image(height=512)
223
+ # gallery = gr.Gallery(
224
+ # label="Generated images", show_label=False, elem_id="gallery"
225
+ # ).style(grid=[1], height="auto")
226
+ error_output = gr.Markdown()
227
+
228
+ with gr.Column(scale=45):
229
+ with gr.Tab("Options"):
230
+ with gr.Group():
231
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
232
+
233
+ # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
234
+
235
+ with gr.Row():
236
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
237
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
238
+
239
+ with gr.Row():
240
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
241
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
242
+
243
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
244
+
245
+ with gr.Tab("Image to image"):
246
+ with gr.Group():
247
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
248
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
249
+
250
+ if is_colab:
251
+ model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False)
252
+ custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
253
+ # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
254
+
255
+ inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt]
256
+ outputs = [image_out, error_output]
257
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
258
+ generate.click(inference, inputs=inputs, outputs=outputs)
259
+
260
+ ex = gr.Examples([
261
+ [models[0].name, "iron man", 7.5, 50],
262
+
263
+ ], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False)
264
+
265
+ gr.HTML("""
266
+ <div style="border-top: 1px solid #303030;">
267
+ <br>
268
+ <p>Model by Linaqruf</p>
269
+ </div>
270
+ """)
271
+
272
+ print(f"Space built in {time.time() - start_time:.2f} seconds")
273
+
274
+ if not is_colab:
275
+ demo.queue(concurrency_count=1)
276
+ demo.launch(debug=is_colab, share=is_colab)