Riccardo Giorato commited on
Commit
9b66f28
1 Parent(s): 9034bd2
Files changed (1) hide show
  1. app.py +118 -128
app.py CHANGED
@@ -6,7 +6,6 @@ import utils
6
 
7
  is_colab = utils.is_google_colab()
8
 
9
-
10
  class Model:
11
  def __init__(self, name, path, prefix):
12
  self.name = name
@@ -15,7 +14,6 @@ class Model:
15
  self.pipe_t2i = None
16
  self.pipe_i2i = None
17
 
18
-
19
  models = [
20
  Model("Beeple", "riccardogiorato/beeple-diffusion", "beeple style "),
21
  Model("Avatar", "riccardogiorato/avatar-diffusion", "avatartwow style "),
@@ -23,8 +21,8 @@ models = [
23
  Model("Poolsuite", "prompthero/poolsuite", "poolsuite style "),
24
  Model("Robo Diffusion", "nousr/robo-diffusion", ""),
25
  Model("Guohua", "Langboat/Guohua-Diffusion", "guohua style ")
26
- ]
27
-
28
  scheduler = DPMSolverMultistepScheduler(
29
  beta_start=0.00085,
30
  beta_end=0.012,
@@ -38,51 +36,53 @@ scheduler = DPMSolverMultistepScheduler(
38
  lower_order_final=True,
39
  )
40
 
 
 
 
 
 
41
  last_mode = "txt2img"
42
- current_model = models[0]
43
  current_model_path = current_model.path
44
 
45
  if is_colab:
46
- pipe = StableDiffusionPipeline.from_pretrained(
47
- current_model.path, torch_dtype=torch.float16, scheduler=scheduler)
48
-
49
- else: # download all models
50
- vae = AutoencoderKL.from_pretrained(
51
- current_model.path, subfolder="vae", torch_dtype=torch.float16)
52
- for model in models:
53
- try:
54
- unet = UNet2DConditionModel.from_pretrained(
55
- model.path, subfolder="unet", torch_dtype=torch.float16)
56
- model.pipe_t2i = StableDiffusionPipeline.from_pretrained(
57
- model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
58
- model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(
59
- model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
60
- except:
61
- models.remove(model)
62
- pipe = models[0].pipe_t2i
63
-
64
  if torch.cuda.is_available():
65
- pipe = pipe.to("cuda")
66
 
67
  device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
68
 
 
 
 
 
69
 
70
  def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
71
 
72
- global current_model
73
- for model in models:
74
- if model.name == model_name:
75
- current_model = model
76
- model_path = current_model.path
77
-
78
- generator = torch.Generator('cuda').manual_seed(
79
- seed) if seed != 0 else None
80
 
81
- if img is not None:
82
- return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator)
83
- else:
84
- return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator)
85
 
 
 
 
 
86
 
87
  def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator=None):
88
 
@@ -92,31 +92,29 @@ def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, g
92
  if model_path != current_model_path or last_mode != "txt2img":
93
  current_model_path = model_path
94
 
95
- if is_colab:
96
- pipe = StableDiffusionPipeline.from_pretrained(
97
- current_model_path, torch_dtype=torch.float16, scheduler=scheduler)
98
  else:
99
- pipe.to("cpu")
100
- pipe = current_model.pipe_t2i
101
 
102
  if torch.cuda.is_available():
103
- pipe = pipe.to("cuda")
104
  last_mode = "txt2img"
105
 
106
- prompt = current_model.prefix + prompt
107
  result = pipe(
108
- prompt,
109
- negative_prompt=neg_prompt,
110
- # num_images_per_prompt=n_images,
111
- num_inference_steps=int(steps),
112
- guidance_scale=guidance,
113
- width=width,
114
- height=height,
115
- generator=generator)
116
-
117
  return replace_nsfw_images(result)
118
 
119
-
120
  def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator=None):
121
 
122
  global last_mode
@@ -125,126 +123,118 @@ def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, w
125
  if model_path != current_model_path or last_mode != "img2img":
126
  current_model_path = model_path
127
 
128
- if is_colab:
129
- pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
130
- current_model_path, torch_dtype=torch.float16, scheduler=scheduler)
131
  else:
132
- pipe.to("cpu")
133
- pipe = current_model.pipe_i2i
134
-
135
  if torch.cuda.is_available():
136
- pipe = pipe.to("cuda")
137
  last_mode = "img2img"
138
 
139
  prompt = current_model.prefix + prompt
140
  ratio = min(height / img.height, width / img.width)
141
- img = img.resize(
142
- (int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
143
  result = pipe(
144
  prompt,
145
- negative_prompt=neg_prompt,
146
  # num_images_per_prompt=n_images,
147
- init_image=img,
148
- num_inference_steps=int(steps),
149
- strength=strength,
150
- guidance_scale=guidance,
151
- width=width,
152
- height=height,
153
- generator=generator)
154
-
155
  return replace_nsfw_images(result)
156
 
157
-
158
  def replace_nsfw_images(results):
159
  for i in range(len(results.images)):
160
- if results.nsfw_content_detected[i]:
161
- results.images[i] = Image.open("nsfw.png")
162
  return results.images[0]
163
 
164
-
165
- css = """.playground-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.playground-diffusion-div div h1{font-weight:900;margin-bottom:7px}.playground-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
166
  """
167
  with gr.Blocks(css=css) as demo:
168
  gr.HTML(
169
  f"""
170
- <div class="playground-diffusion-div">
171
  <div>
172
  <h1>Playground Diffusion</h1>
173
  </div>
174
  <p>
175
  Demo for multiple fine-tuned Stable Diffusion models, trained on different styles: <br>
176
- <a href="https://huggingface.co/riccardogiorato/avatar-diffusion">Avatar</a>,<br/>
177
  <a href="https://huggingface.co/riccardogiorato/beeple-diffusion">Beeple</a>,<br/>
178
  <a href="https://huggingface.co/s3nh/beksinski-style-stable-diffusion">Beksinski</a>,<br/>
179
  Diffusers 🧨 SD model hosted on HuggingFace 🤗.
180
- </p>
181
  Running on <b>{device}</b>{(" in a <b>Google Colab</b>." if is_colab else "")}
182
  </p>
183
  </div>
184
  """
185
  )
186
  with gr.Row():
187
-
188
  with gr.Column(scale=55):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  with gr.Group():
190
- model_name = gr.Dropdown(label="Model", choices=[
191
- m.name for m in models], value=current_model.name)
192
 
193
- with gr.Row():
194
- prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,
195
- placeholder="Enter prompt. Style applied automatically").style(container=False)
196
- generate = gr.Button(value="Generate").style(
197
- rounded=(False, True, True, False))
198
 
199
- image_out = gr.Image(height=512)
200
- # gallery = gr.Gallery(
201
- # label="Generated images", show_label=False, elem_id="gallery"
202
- # ).style(grid=[1], height="auto")
203
 
204
- with gr.Column(scale=45):
205
- with gr.Tab("Options"):
206
- with gr.Group():
207
- neg_prompt = gr.Textbox(
208
- label="Negative prompt", placeholder="What to exclude from the image")
209
-
210
- # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
211
-
212
- with gr.Row():
213
- guidance = gr.Slider(
214
- label="Guidance scale", value=7.5, maximum=15)
215
- steps = gr.Slider(
216
- label="Steps", value=25, minimum=2, maximum=75, step=1)
217
-
218
- with gr.Row():
219
- width = gr.Slider(
220
- label="Width", value=512, minimum=64, maximum=1024, step=8)
221
- height = gr.Slider(
222
- label="Height", value=512, minimum=64, maximum=1024, step=8)
223
-
224
- seed = gr.Slider(
225
- 0, 2147483647, label='Seed (0 = random)', value=0, step=1)
226
-
227
- with gr.Tab("Image to image"):
228
- with gr.Group():
229
- image = gr.Image(label="Image", height=256,
230
- tool="editor", type="pil")
231
- strength = gr.Slider(
232
- label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
233
-
234
- inputs = [model_name, prompt, guidance, steps,
235
- width, height, seed, image, strength, neg_prompt]
236
  prompt.submit(inference, inputs=inputs, outputs=image_out)
237
  generate.click(inference, inputs=inputs, outputs=image_out)
238
 
239
  ex = gr.Examples([
240
- [models[0].name, "Neon techno-magic robot with spear pierces an ancient beast, hyperrealism, no blur, 4k resolution, ultra detailed", 7.5, 50],
241
- [models[0].name, "halfturn portrait of a big crystal face of a beautiful abstract ancient Egyptian elderly shaman woman, made of iridescent golden crystals, half - turn, bottom view, ominous, intricate, studio, art by anthony macbain and greg rutkowski and alphonse mucha, concept art, 4k, sharp focus", 7.5, 25],
242
  ], [model_name, prompt, guidance, steps, seed], image_out, inference, cache_examples=False)
243
 
244
  gr.HTML("""
245
- <p>Models by <a href="https://huggingface.co/riccardogiorato">@riccardogiorato</a><br></p>
246
  """)
247
 
248
  if not is_colab:
249
- demo.queue(concurrency_count=1)
250
- demo.launch(debug=is_colab, share=is_colab)
 
6
 
7
  is_colab = utils.is_google_colab()
8
 
 
9
  class Model:
10
  def __init__(self, name, path, prefix):
11
  self.name = name
 
14
  self.pipe_t2i = None
15
  self.pipe_i2i = None
16
 
 
17
  models = [
18
  Model("Beeple", "riccardogiorato/beeple-diffusion", "beeple style "),
19
  Model("Avatar", "riccardogiorato/avatar-diffusion", "avatartwow style "),
 
21
  Model("Poolsuite", "prompthero/poolsuite", "poolsuite style "),
22
  Model("Robo Diffusion", "nousr/robo-diffusion", ""),
23
  Model("Guohua", "Langboat/Guohua-Diffusion", "guohua style ")
24
+ ]
25
+
26
  scheduler = DPMSolverMultistepScheduler(
27
  beta_start=0.00085,
28
  beta_end=0.012,
 
36
  lower_order_final=True,
37
  )
38
 
39
+ custom_model = None
40
+ if is_colab:
41
+ models.insert(0, Model("Custom model", "", ""))
42
+ custom_model = models[0]
43
+
44
  last_mode = "txt2img"
45
+ current_model = models[1] if is_colab else models[0]
46
  current_model_path = current_model.path
47
 
48
  if is_colab:
49
+ pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16, scheduler=scheduler)
50
+
51
+ else: # download all models
52
+ vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae", torch_dtype=torch.float16)
53
+ for model in models:
54
+ try:
55
+ unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet", torch_dtype=torch.float16)
56
+ model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
57
+ model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
58
+ except:
59
+ models.remove(model)
60
+ pipe = models[0].pipe_t2i
61
+
 
 
 
 
 
62
  if torch.cuda.is_available():
63
+ pipe = pipe.to("cuda")
64
 
65
  device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
66
 
67
+ def custom_model_changed(path):
68
+ models[0].path = path
69
+ global current_model
70
+ current_model = models[0]
71
 
72
  def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
73
 
74
+ global current_model
75
+ for model in models:
76
+ if model.name == model_name:
77
+ current_model = model
78
+ model_path = current_model.path
 
 
 
79
 
80
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
 
 
 
81
 
82
+ if img is not None:
83
+ return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator)
84
+ else:
85
+ return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator)
86
 
87
  def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator=None):
88
 
 
92
  if model_path != current_model_path or last_mode != "txt2img":
93
  current_model_path = model_path
94
 
95
+ if is_colab or current_model == custom_model:
96
+ pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler)
 
97
  else:
98
+ pipe.to("cpu")
99
+ pipe = current_model.pipe_t2i
100
 
101
  if torch.cuda.is_available():
102
+ pipe = pipe.to("cuda")
103
  last_mode = "txt2img"
104
 
105
+ prompt = current_model.prefix + prompt
106
  result = pipe(
107
+ prompt,
108
+ negative_prompt = neg_prompt,
109
+ # num_images_per_prompt=n_images,
110
+ num_inference_steps = int(steps),
111
+ guidance_scale = guidance,
112
+ width = width,
113
+ height = height,
114
+ generator = generator)
115
+
116
  return replace_nsfw_images(result)
117
 
 
118
  def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator=None):
119
 
120
  global last_mode
 
123
  if model_path != current_model_path or last_mode != "img2img":
124
  current_model_path = model_path
125
 
126
+ if is_colab or current_model == custom_model:
127
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler)
 
128
  else:
129
+ pipe.to("cpu")
130
+ pipe = current_model.pipe_i2i
131
+
132
  if torch.cuda.is_available():
133
+ pipe = pipe.to("cuda")
134
  last_mode = "img2img"
135
 
136
  prompt = current_model.prefix + prompt
137
  ratio = min(height / img.height, width / img.width)
138
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
 
139
  result = pipe(
140
  prompt,
141
+ negative_prompt = neg_prompt,
142
  # num_images_per_prompt=n_images,
143
+ init_image = img,
144
+ num_inference_steps = int(steps),
145
+ strength = strength,
146
+ guidance_scale = guidance,
147
+ width = width,
148
+ height = height,
149
+ generator = generator)
150
+
151
  return replace_nsfw_images(result)
152
 
 
153
  def replace_nsfw_images(results):
154
  for i in range(len(results.images)):
155
+ if results.nsfw_content_detected[i]:
156
+ results.images[i] = Image.open("nsfw.png")
157
  return results.images[0]
158
 
159
+ 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}
 
160
  """
161
  with gr.Blocks(css=css) as demo:
162
  gr.HTML(
163
  f"""
164
+ <div class="finetuned-diffusion-div">
165
  <div>
166
  <h1>Playground Diffusion</h1>
167
  </div>
168
  <p>
169
  Demo for multiple fine-tuned Stable Diffusion models, trained on different styles: <br>
170
+ <a href="https://huggingface.co/riccardogiorato/avatar-diffusion">Avatar</a>,<br/>
171
  <a href="https://huggingface.co/riccardogiorato/beeple-diffusion">Beeple</a>,<br/>
172
  <a href="https://huggingface.co/s3nh/beksinski-style-stable-diffusion">Beksinski</a>,<br/>
173
  Diffusers 🧨 SD model hosted on HuggingFace 🤗.
 
174
  Running on <b>{device}</b>{(" in a <b>Google Colab</b>." if is_colab else "")}
175
  </p>
176
  </div>
177
  """
178
  )
179
  with gr.Row():
180
+
181
  with gr.Column(scale=55):
182
+ with gr.Group():
183
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
184
+ with gr.Box(visible=False) as custom_model_group:
185
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True)
186
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
187
+
188
+ with gr.Row():
189
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False)
190
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
191
+
192
+
193
+ image_out = gr.Image(height=512)
194
+ # gallery = gr.Gallery(
195
+ # label="Generated images", show_label=False, elem_id="gallery"
196
+ # ).style(grid=[1], height="auto")
197
+
198
+ with gr.Column(scale=45):
199
+ with gr.Tab("Options"):
200
  with gr.Group():
201
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
 
202
 
203
+ # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
 
 
 
 
204
 
205
+ with gr.Row():
206
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
207
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
 
208
 
209
+ with gr.Row():
210
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
211
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
212
+
213
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
214
+
215
+ with gr.Tab("Image to image"):
216
+ with gr.Group():
217
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
218
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
219
+
220
+ if is_colab:
221
+ model_name.change(lambda x: gr.update(visible = x == models[0].name), inputs=model_name, outputs=custom_model_group)
222
+ custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
223
+ # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
224
+
225
+ inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  prompt.submit(inference, inputs=inputs, outputs=image_out)
227
  generate.click(inference, inputs=inputs, outputs=image_out)
228
 
229
  ex = gr.Examples([
230
+ [models[1].name, "Neon techno-magic robot with spear pierces an ancient beast, hyperrealism, no blur, 4k resolution, ultra detailed", 7.5, 50],
231
+ [models[1].name, "halfturn portrait of a big crystal face of a beautiful abstract ancient Egyptian elderly shaman woman, made of iridescent golden crystals, half - turn, bottom view, ominous, intricate, studio, art by anthony macbain and greg rutkowski and alphonse mucha, concept art, 4k, sharp focus", 7.5, 25],
232
  ], [model_name, prompt, guidance, steps, seed], image_out, inference, cache_examples=False)
233
 
234
  gr.HTML("""
235
+ <p>Models by <a href="https://huggingface.co/riccardogiorato">@riccardogiorato</a><br></p>
236
  """)
237
 
238
  if not is_colab:
239
+ demo.queue(concurrency_count=1)
240
+ demo.launch(debug=is_colab, share=is_colab)