patrickvonplaten commited on
Commit
5af82ca
1 Parent(s): 75eef29
Files changed (6) hide show
  1. README.md +7 -5
  2. app.py +323 -0
  3. nsfw.png +0 -0
  4. requirements.txt +16 -0
  5. style.css +24 -0
  6. utils.py +6 -0
README.md CHANGED
@@ -1,12 +1,14 @@
1
  ---
2
- title: Protogen Web Ui
3
- emoji: 😻
4
- colorFrom: indigo
5
  colorTo: pink
6
  sdk: gradio
7
- sdk_version: 3.16.1
8
  app_file: app.py
9
- pinned: false
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Finetuned Diffusion
3
+ emoji: 🪄🖼️
4
+ colorFrom: red
5
  colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 3.15.0
8
  app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ duplicated_from: anzorq/finetuned_diffusion
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import random
10
+
11
+
12
+ start_time = time.time()
13
+ is_colab = utils.is_google_colab()
14
+ state = None
15
+ current_steps = 25
16
+
17
+ class Model:
18
+ def __init__(self, name, path=""):
19
+ self.name = name
20
+ self.path = path
21
+ self.pipe_t2i = None
22
+ self.pipe_i2i = None
23
+
24
+ models = [
25
+ Model("2.2", "darkstorm2150/Protogen_v2.2_Official_Release"),
26
+ Model("3.4", "darkstorm2150/Protogen_x3.4_Official_Release"),
27
+ Model("5.3", "darkstorm2150/Protogen_v5.3_Official_Release"),
28
+ Model("5.8", "darkstorm2150/Protogen_x5.8_Official_Release"),
29
+ Model("Dragon", "darkstorm2150/Protogen_Dragon_Official_Release"),
30
+ ]
31
+
32
+ custom_model = None
33
+ if is_colab:
34
+ models.insert(0, Model("Custom model"))
35
+ custom_model = models[0]
36
+
37
+ last_mode = "txt2img"
38
+ current_model = models[1] if is_colab else models[0]
39
+ current_model_path = current_model.path
40
+
41
+ if is_colab:
42
+ pipe = StableDiffusionPipeline.from_pretrained(
43
+ current_model.path,
44
+ torch_dtype=torch.float16,
45
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"),
46
+ safety_checker=lambda images, clip_input: (images, False)
47
+ )
48
+
49
+ else:
50
+ pipe = StableDiffusionPipeline.from_pretrained(
51
+ current_model.path,
52
+ torch_dtype=torch.float16,
53
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler")
54
+ )
55
+
56
+ if torch.cuda.is_available():
57
+ pipe = pipe.to("cuda")
58
+ pipe.enable_xformers_memory_efficient_attention()
59
+
60
+ device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
61
+
62
+ def error_str(error, title="Error"):
63
+ return f"""#### {title}
64
+ {error}""" if error else ""
65
+
66
+ def update_state(new_state):
67
+ global state
68
+ state = new_state
69
+
70
+ def update_state_info(old_state):
71
+ if state and state != old_state:
72
+ return gr.update(value=state)
73
+
74
+ def custom_model_changed(path):
75
+ models[0].path = path
76
+ global current_model
77
+ current_model = models[0]
78
+
79
+ def on_model_change(model_name):
80
+
81
+ prefix = "Enter prefix"
82
+
83
+ return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix)
84
+
85
+ def on_steps_change(steps):
86
+ global current_steps
87
+ current_steps = steps
88
+
89
+ def pipe_callback(step: int, timestep: int, latents: torch.FloatTensor):
90
+ update_state(f"{step}/{current_steps} steps")#\nTime left, sec: {timestep/100:.0f}")
91
+
92
+ def inference(model_name, prompt, guidance, steps, n_images=1, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
93
+
94
+ update_state(" ")
95
+
96
+ print(psutil.virtual_memory()) # print memory usage
97
+
98
+ global current_model
99
+ for model in models:
100
+ if model.name == model_name:
101
+ current_model = model
102
+ model_path = current_model.path
103
+
104
+ # generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
105
+ if seed == 0:
106
+ seed = random.randint(0, 2147483647)
107
+
108
+ generator = torch.Generator('cuda').manual_seed(seed)
109
+
110
+ try:
111
+ if img is not None:
112
+ return img_to_img(model_path, prompt, n_images, neg_prompt, img, strength, guidance, steps, width, height, generator, seed), f"Done. Seed: {seed}"
113
+ else:
114
+ return txt_to_img(model_path, prompt, n_images, neg_prompt, guidance, steps, width, height, generator, seed), f"Done. Seed: {seed}"
115
+ except Exception as e:
116
+ return None, error_str(e)
117
+
118
+ def txt_to_img(model_path, prompt, n_images, neg_prompt, guidance, steps, width, height, generator, seed):
119
+
120
+ print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
121
+
122
+ global last_mode
123
+ global pipe
124
+ global current_model_path
125
+ if model_path != current_model_path or last_mode != "txt2img":
126
+ current_model_path = model_path
127
+
128
+ update_state(f"Loading {current_model.name} text-to-image model...")
129
+
130
+ if is_colab or current_model == custom_model:
131
+ pipe = StableDiffusionPipeline.from_pretrained(
132
+ current_model_path,
133
+ torch_dtype=torch.float16,
134
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"),
135
+ safety_checker=lambda images, clip_input: (images, False)
136
+ )
137
+ else:
138
+ pipe = StableDiffusionPipeline.from_pretrained(
139
+ current_model_path,
140
+ torch_dtype=torch.float16,
141
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler")
142
+ )
143
+ # pipe = pipe.to("cpu")
144
+ # pipe = current_model.pipe_t2i
145
+
146
+ if torch.cuda.is_available():
147
+ pipe = pipe.to("cuda")
148
+ pipe.enable_xformers_memory_efficient_attention()
149
+ last_mode = "txt2img"
150
+
151
+ result = pipe(
152
+ prompt,
153
+ negative_prompt = neg_prompt,
154
+ num_images_per_prompt=n_images,
155
+ num_inference_steps = int(steps),
156
+ guidance_scale = guidance,
157
+ width = width,
158
+ height = height,
159
+ generator = generator,
160
+ callback=pipe_callback)
161
+
162
+ # update_state(f"Done. Seed: {seed}")
163
+
164
+ return replace_nsfw_images(result)
165
+
166
+ def img_to_img(model_path, prompt, n_images, neg_prompt, img, strength, guidance, steps, width, height, generator, seed):
167
+
168
+ print(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
169
+
170
+ global last_mode
171
+ global pipe
172
+ global current_model_path
173
+ if model_path != current_model_path or last_mode != "img2img":
174
+ current_model_path = model_path
175
+
176
+ update_state(f"Loading {current_model.name} image-to-image model...")
177
+
178
+ if is_colab or current_model == custom_model:
179
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
180
+ current_model_path,
181
+ torch_dtype=torch.float16,
182
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"),
183
+ safety_checker=lambda images, clip_input: (images, False)
184
+ )
185
+ else:
186
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
187
+ current_model_path,
188
+ torch_dtype=torch.float16,
189
+ scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler")
190
+ )
191
+ # pipe = pipe.to("cpu")
192
+ # pipe = current_model.pipe_i2i
193
+
194
+ if torch.cuda.is_available():
195
+ pipe = pipe.to("cuda")
196
+ pipe.enable_xformers_memory_efficient_attention()
197
+ last_mode = "img2img"
198
+
199
+ ratio = min(height / img.height, width / img.width)
200
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
201
+ result = pipe(
202
+ prompt,
203
+ negative_prompt = neg_prompt,
204
+ num_images_per_prompt=n_images,
205
+ image = img,
206
+ num_inference_steps = int(steps),
207
+ strength = strength,
208
+ guidance_scale = guidance,
209
+ # width = width,
210
+ # height = height,
211
+ generator = generator,
212
+ callback=pipe_callback)
213
+
214
+ # update_state(f"Done. Seed: {seed}")
215
+
216
+ return replace_nsfw_images(result)
217
+
218
+ def replace_nsfw_images(results):
219
+
220
+ if is_colab:
221
+ return results.images
222
+
223
+ for i in range(len(results.images)):
224
+ if results.nsfw_content_detected[i]:
225
+ results.images[i] = Image.open("nsfw.png")
226
+ return results.images
227
+
228
+ # 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}
229
+ # """
230
+ with gr.Blocks(css="style.css") as demo:
231
+ gr.HTML(
232
+ f"""
233
+ <div class="finetuned-diffusion-div">
234
+ <div>
235
+ <h1>Protogen Diffusion</h1>
236
+ </div>
237
+ <p>
238
+ Demo for multiple fine-tuned Protogen Stable Diffusion models + in colab notebook you can load any other Diffusers 🧨 SD model hosted on HuggingFace 🤗.
239
+ </p>
240
+ <p>You can skip the queue and load custom models in the colab: <a href="https://colab.research.google.com/gist/qunash/42112fb104509c24fd3aa6d1c11dd6e0/copy-of-fine-tuned-diffusion-gradio.ipynb"><img data-canonical-src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" src="https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667"></a></p>
241
+ Running on <b>{device}</b>{(" in a <b>Google Colab</b>." if is_colab else "")}
242
+ </p>
243
+ <p>You can also duplicate this space and upgrade to gpu by going to settings:<br>
244
+ <a style="display:inline-block" href="https://huggingface.co/spaces/patrickvonplaten/finetuned_diffusion?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>
245
+ </div>
246
+ """
247
+ )
248
+ with gr.Row():
249
+
250
+ with gr.Column(scale=55):
251
+ with gr.Group():
252
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
253
+ with gr.Box(visible=False) as custom_model_group:
254
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. darkstorm2150/Protogen_x3.4_Official_Release", interactive=True)
255
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
256
+
257
+ with gr.Row():
258
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt.").style(container=False)
259
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
260
+
261
+
262
+ # image_out = gr.Image(height=512)
263
+ gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="auto")
264
+
265
+ state_info = gr.Textbox(label="State", show_label=False, max_lines=2).style(container=False)
266
+ error_output = gr.Markdown()
267
+
268
+ with gr.Column(scale=45):
269
+ with gr.Tab("Options"):
270
+ with gr.Group():
271
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
272
+
273
+ n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
274
+
275
+ with gr.Row():
276
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
277
+ steps = gr.Slider(label="Steps", value=current_steps, minimum=2, maximum=75, step=1)
278
+
279
+ with gr.Row():
280
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
281
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
282
+
283
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
284
+
285
+ with gr.Tab("Image to image"):
286
+ with gr.Group():
287
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
288
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
289
+
290
+ if is_colab:
291
+ model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False)
292
+ custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
293
+ # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
294
+ steps.change(on_steps_change, inputs=[steps], outputs=[], queue=False)
295
+
296
+ inputs = [model_name, prompt, guidance, steps, n_images, width, height, seed, image, strength, neg_prompt]
297
+ outputs = [gallery, error_output]
298
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
299
+ generate.click(inference, inputs=inputs, outputs=outputs)
300
+
301
+ ex = gr.Examples([
302
+ [models[2].name, "Brad Pitt with sunglasses, highly realistic", 7.5, 25],
303
+ [models[1].name, "Johnny Deep with red hair", 7.0, 35],
304
+ [models[0].name, "portrait of a beautiful alyx vance half life", 10, 25],
305
+ ], inputs=[model_name, prompt, guidance, steps], outputs=outputs, fn=inference, cache_examples=False)
306
+
307
+ gr.HTML("""
308
+ <div style="border-top: 1px solid #303030;">
309
+ <br>
310
+ <p>Models by <a href="https://huggingface.co/darkstorm2150">@darkstorm2150</a> and others. ❤️</p>
311
+ <p>This space uses the <a href="https://github.com/LuChengTHU/dpm-solver">DPM-Solver++</a> sampler by <a href="https://arxiv.org/abs/2206.00927">Cheng Lu, et al.</a>.</p>
312
+ <p>Space by: Darkstorm (Victor Espinoza)<br>
313
+ <a href="https://www.instagram.com/officialvictorespinoza/">Instagram</a>
314
+ </div>
315
+ """)
316
+
317
+ demo.load(update_state_info, inputs=state_info, outputs=state_info, every=0.5, show_progress=False)
318
+
319
+ print(f"Space built in {time.time() - start_time:.2f} seconds")
320
+
321
+ # if not is_colab:
322
+ demo.queue(concurrency_count=1)
323
+ demo.launch(debug=is_colab, share=is_colab)
nsfw.png ADDED
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ torchvision==0.13.1+cu113
4
+ #diffusers
5
+ git+https://github.com/huggingface/diffusers.git
6
+ #transformers
7
+ git+https://github.com/huggingface/transformers
8
+ scipy
9
+ ftfy
10
+ psutil
11
+ accelerate==0.12.0
12
+ #OmegaConf
13
+ #pytorch_lightning
14
+ triton==2.0.0.dev20220701
15
+ #https://github.com/apolinario/xformers/releases/download/0.0.3/xformers-0.0.14.dev0-cp38-cp38-linux_x86_64.whl
16
+ https://github.com/camenduru/stable-diffusion-webui-colab/releases/download/0.0.15/xformers-0.0.15.dev0+4c06c79.d20221205-cp38-cp38-linux_x86_64.whl
style.css ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .finetuned-diffusion-div div{
2
+ display:inline-flex;
3
+ align-items:center;
4
+ gap:.8rem;
5
+ font-size:1.75rem
6
+ }
7
+ .finetuned-diffusion-div div h1{
8
+ font-weight:900;
9
+ margin-bottom:7px
10
+ }
11
+ .finetuned-diffusion-div p{
12
+ margin-bottom:10px;
13
+ font-size:94%
14
+ }
15
+ a{
16
+ text-decoration:underline
17
+ }
18
+ .tabs{
19
+ margin-top:0;
20
+ margin-bottom:0
21
+ }
22
+ #gallery{
23
+ min-height:20rem
24
+ }
utils.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def is_google_colab():
2
+ try:
3
+ import google.colab
4
+ return True
5
+ except:
6
+ return False