prithivMLmods commited on
Commit
e100e3d
1 Parent(s): af16bbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -74
app.py CHANGED
@@ -1,91 +1,182 @@
 
 
1
  import os
2
  import random
3
  import uuid
4
- import json
5
 
6
  import gradio as gr
7
  import numpy as np
8
  from PIL import Image
9
  import spaces
 
10
  import torch
11
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  if not torch.cuda.is_available():
14
- DESCRIPTION += "\n<p>Running on CPU, This may not work on CPU.</p>"
15
 
16
  MAX_SEED = np.iinfo(np.int32).max
17
- CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "1") == "1"
18
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
19
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
20
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
21
 
22
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
 
23
 
24
  if torch.cuda.is_available():
25
  pipe = StableDiffusionXLPipeline.from_pretrained(
26
  "stabilityai/stable-diffusion-xl-base-1.0",
27
  torch_dtype=torch.float16,
28
  use_safetensors=True,
29
- add_watermarker=False
30
  )
31
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
 
 
32
  pipe.to("cuda")
33
 
34
 
35
- def save_image(img):
36
- unique_name = str(uuid.uuid4()) + ".png"
37
- img.save(unique_name)
38
- return unique_name
 
 
 
39
 
40
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
41
- if randomize_seed:
42
- seed = random.randint(0, MAX_SEED)
43
- return seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- @spaces.GPU(duration=30, queue=False)
46
- def dalle4k(
 
 
 
 
 
 
47
  prompt: str,
48
  negative_prompt: str = "",
 
49
  use_negative_prompt: bool = False,
50
- seed: int = 1,
 
 
51
  width: int = 1024,
52
  height: int = 1024,
53
  guidance_scale: float = 3,
54
- num_inference_steps: int = 30,
55
  randomize_seed: bool = False,
56
- use_resolution_binning: bool = True,
57
  progress=gr.Progress(track_tqdm=True),
58
  ):
59
- pipe.to(device)
60
- seed = int(randomize_seed_fn(seed, randomize_seed))
61
- generator = torch.Generator().manual_seed(seed)
62
-
63
- options = {
64
- "prompt":prompt,
65
- "negative_prompt":negative_prompt,
66
- "width":width,
67
- "height":height,
68
- "guidance_scale":guidance_scale,
69
- "num_inference_steps":num_inference_steps,
70
- "generator":generator,
71
- "use_resolution_binning":use_resolution_binning,
72
- "output_type":"pil",
73
-
74
- }
75
 
76
- images = pipe(**options).images
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  image_paths = [save_image(img) for img in images]
 
79
  return image_paths, seed
80
 
81
-
82
  examples = [
83
- "a cat eating a piece of cheese",
84
- "a ROBOT riding a BLUE horse on Mars, photorealistic, 4k",
85
- "Ironman VS Hulk, ultrarealistic",
86
- "Astronaut in a jungle, cold color palette, oil pastel, detailed, 8k",
87
- "An alien holding sign board contain word 'Flash', futuristic, neonpunk",
88
- "Kids going to school, Anime style"
89
  ]
90
 
91
  css = '''
@@ -96,8 +187,13 @@ footer {
96
  }
97
  '''
98
  with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
99
- gr.Markdown("""# SDXL Flash
100
- ### First Image processing takes time then images generate faster.""")
 
 
 
 
 
101
  with gr.Group():
102
  with gr.Row():
103
  prompt = gr.Text(
@@ -107,64 +203,81 @@ with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
107
  placeholder="Enter your prompt",
108
  container=False,
109
  )
110
- run_button = gr.Button("Run", scale=0)
111
- result = gr.Gallery(label="Result", columns=1)
112
  with gr.Accordion("Advanced options", open=False):
113
- with gr.Row(visible=False):
114
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
115
- negative_prompt = gr.Text(
116
  label="Negative prompt",
117
- max_lines=5,
118
- lines=4,
119
  placeholder="Enter a negative prompt",
120
- value="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, NSFW",
121
  visible=True,
122
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  seed = gr.Slider(
124
  label="Seed",
125
  minimum=0,
126
  maximum=MAX_SEED,
127
  step=1,
128
  value=0,
 
129
  )
130
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
131
  with gr.Row(visible=True):
132
  width = gr.Slider(
133
  label="Width",
134
  minimum=512,
135
- maximum=MAX_IMAGE_SIZE,
136
- step=64,
137
  value=1024,
138
  )
139
  height = gr.Slider(
140
  label="Height",
141
  minimum=512,
142
- maximum=MAX_IMAGE_SIZE,
143
- step=64,
144
  value=1024,
145
  )
146
  with gr.Row():
147
  guidance_scale = gr.Slider(
148
  label="Guidance Scale",
149
  minimum=0.1,
150
- maximum=6,
151
  step=0.1,
152
- value=3.0,
153
  )
154
- num_inference_steps = gr.Slider(
155
- label="Number of inference steps",
156
- minimum=1,
157
- maximum=30,
158
- step=1,
159
- value=30,
 
 
160
  )
 
161
 
162
  gr.Examples(
163
  examples=examples,
164
  inputs=prompt,
165
  outputs=[result, seed],
166
- fn=dalle4k,
167
- cache_examples=CACHE_EXAMPLES,
168
  )
169
 
170
  use_negative_prompt.change(
@@ -173,6 +286,7 @@ with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
173
  outputs=negative_prompt,
174
  api_name=False,
175
  )
 
176
 
177
  gr.on(
178
  triggers=[
@@ -180,21 +294,23 @@ with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
180
  negative_prompt.submit,
181
  run_button.click,
182
  ],
183
- fn=dalle4k,
184
  inputs=[
185
  prompt,
186
  negative_prompt,
 
187
  use_negative_prompt,
 
 
188
  seed,
189
  width,
190
  height,
191
  guidance_scale,
192
- num_inference_steps,
193
  randomize_seed,
194
  ],
195
  outputs=[result, seed],
196
  api_name="run",
197
  )
198
-
199
  if __name__ == "__main__":
200
- demo.queue(max_size=20).launch()
 
1
+ #!/usr/bin/env python
2
+
3
  import os
4
  import random
5
  import uuid
 
6
 
7
  import gradio as gr
8
  import numpy as np
9
  from PIL import Image
10
  import spaces
11
+ from typing import Tuple
12
  import torch
13
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
14
 
15
+ DESCRIPTION = """ """
16
+
17
+ def save_image(img):
18
+ unique_name = str(uuid.uuid4()) + ".png"
19
+ img.save(unique_name)
20
+ return unique_name
21
+
22
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
23
+ if randomize_seed:
24
+ seed = random.randint(0, MAX_SEED)
25
+ return seed
26
+
27
+ MAX_SEED = np.iinfo(np.int32).max
28
+
29
  if not torch.cuda.is_available():
30
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"
31
 
32
  MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
33
 
34
+ USE_TORCH_COMPILE = 0
35
+ ENABLE_CPU_OFFLOAD = 0
36
+
37
 
38
  if torch.cuda.is_available():
39
  pipe = StableDiffusionXLPipeline.from_pretrained(
40
  "stabilityai/stable-diffusion-xl-base-1.0",
41
  torch_dtype=torch.float16,
42
  use_safetensors=True,
 
43
  )
44
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
45
+ pipe.load_lora_weights("ByteDance/Hyper-SD", weight_name="Hyper-SDXL-8steps-lora.safetensors", adapter_name="dalle")
46
+ pipe.set_adapters("dalle")
47
  pipe.to("cuda")
48
 
49
 
50
+
51
+ style_list = [
52
+ {
53
+ "name": "(No style)",
54
+ "prompt": "{prompt}",
55
+ "negative_prompt": "",
56
+ },
57
 
58
+ {
59
+ "name": "8K",
60
+ "prompt": "hyper-realistic 8K image of {prompt} . ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
61
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
62
+ },
63
+
64
+ {
65
+ "name": "4K",
66
+ "prompt": "hyper-realistic 4K image of {prompt} . ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
67
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
68
+ },
69
+
70
+ {
71
+ "name": "HDR Photography",
72
+ "prompt": "HDR photo of {prompt} . high dynamic range, vivid colors, sharp contrast, realistic, detailed, high resolution, professional",
73
+ "negative_prompt": "dull, low contrast, blurry, unrealistic, cartoonish, ugly, deformed",
74
+ },
75
+
76
+
77
+ {
78
+ "name": "Cinematic",
79
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
80
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
81
+ },
82
+ {
83
+ "name": "Photographic",
84
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
85
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
86
+ },
87
+ {
88
+ "name": "Anime",
89
+ "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed",
90
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
91
+ },
92
+ {
93
+ "name": "Manga",
94
+ "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style",
95
+ "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style",
96
+ },
97
+ {
98
+ "name": "Digital Art",
99
+ "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed",
100
+ "negative_prompt": "photo, photorealistic, realism, ugly",
101
+ },
102
+ {
103
+ "name": "Pixel art",
104
+ "prompt": "pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics",
105
+ "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic",
106
+ },
107
+ {
108
+ "name": "Fantasy art",
109
+ "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy",
110
+ "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white",
111
+ },
112
+ {
113
+ "name": "Neonpunk",
114
+ "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional",
115
+ "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured",
116
+ },
117
+ {
118
+ "name": "3D Model",
119
+ "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting",
120
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
121
+ },
122
+
123
+
124
+ ]
125
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
126
+ STYLE_NAMES = list(styles.keys())
127
+ DEFAULT_STYLE_NAME = "(No style)"
128
 
129
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
130
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
131
+ if not negative:
132
+ negative = ""
133
+ return p.replace("{prompt}", positive), n + negative
134
+
135
+ @spaces.GPU(enable_queue=True)
136
+ def generate(
137
  prompt: str,
138
  negative_prompt: str = "",
139
+ style: str = DEFAULT_STYLE_NAME,
140
  use_negative_prompt: bool = False,
141
+ num_inference_steps: int = 30,
142
+ num_images_per_prompt: int = 2,
143
+ seed: int = 0,
144
  width: int = 1024,
145
  height: int = 1024,
146
  guidance_scale: float = 3,
 
147
  randomize_seed: bool = False,
 
148
  progress=gr.Progress(track_tqdm=True),
149
  ):
150
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+ seed = int(randomize_seed_fn(seed, randomize_seed))
153
 
154
+ if not use_negative_prompt:
155
+ negative_prompt = "" # type: ignore
156
+ prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
157
+
158
+ images = pipe(
159
+ prompt=prompt,
160
+ negative_prompt=negative_prompt,
161
+ width=width,
162
+ height=height,
163
+ guidance_scale=guidance_scale,
164
+ num_inference_steps=num_inference_steps,
165
+ num_images_per_prompt=num_images_per_prompt,
166
+ cross_attention_kwargs={"scale": 0.65},
167
+ output_type="pil",
168
+ ).images
169
  image_paths = [save_image(img) for img in images]
170
+ print(image_paths)
171
  return image_paths, seed
172
 
 
173
  examples = [
174
+ "a time traveler meeting their past self in a Victorian-era street",
175
+ "a carnival at night with colorful lights and whimsical rides",
176
+ "a Viking ship sailing through a storm with lightning in the background",
177
+ "a cyberpunk street market with neon lights and holographic signs",
178
+ "a space station orbiting a distant planet, serving as a hub for intergalactic travelers",
179
+ "a surreal landscape with floating islands and waterfalls cascading into the void"
180
  ]
181
 
182
  css = '''
 
187
  }
188
  '''
189
  with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
190
+ gr.Markdown(DESCRIPTION)
191
+ gr.DuplicateButton(
192
+ value="Duplicate Space for private use",
193
+ elem_id="duplicate-button",
194
+ visible=False,
195
+ )
196
+
197
  with gr.Group():
198
  with gr.Row():
199
  prompt = gr.Text(
 
203
  placeholder="Enter your prompt",
204
  container=False,
205
  )
206
+ run_button = gr.Button("Run")
207
+ result = gr.Gallery(label="Result", columns=1, preview=True)
208
  with gr.Accordion("Advanced options", open=False):
209
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=False, visible=True)
210
+ negative_prompt = gr.Text(
 
211
  label="Negative prompt",
212
+ max_lines=1,
 
213
  placeholder="Enter a negative prompt",
 
214
  visible=True,
215
  )
216
+ with gr.Row():
217
+ num_inference_steps = gr.Slider(
218
+ label="Steps",
219
+ minimum=10,
220
+ maximum=60,
221
+ step=1,
222
+ value=30,
223
+ )
224
+ with gr.Row():
225
+ num_images_per_prompt = gr.Slider(
226
+ label="Images",
227
+ minimum=1,
228
+ maximum=5,
229
+ step=1,
230
+ value=2,
231
+ )
232
  seed = gr.Slider(
233
  label="Seed",
234
  minimum=0,
235
  maximum=MAX_SEED,
236
  step=1,
237
  value=0,
238
+ visible=True
239
  )
240
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
241
  with gr.Row(visible=True):
242
  width = gr.Slider(
243
  label="Width",
244
  minimum=512,
245
+ maximum=2048,
246
+ step=8,
247
  value=1024,
248
  )
249
  height = gr.Slider(
250
  label="Height",
251
  minimum=512,
252
+ maximum=2048,
253
+ step=8,
254
  value=1024,
255
  )
256
  with gr.Row():
257
  guidance_scale = gr.Slider(
258
  label="Guidance Scale",
259
  minimum=0.1,
260
+ maximum=20.0,
261
  step=0.1,
262
+ value=6,
263
  )
264
+ with gr.Row(visible=True):
265
+ style_selection = gr.Radio(
266
+ show_label=True,
267
+ container=True,
268
+ interactive=True,
269
+ choices=STYLE_NAMES,
270
+ value=DEFAULT_STYLE_NAME,
271
+ label="Image Style",
272
  )
273
+
274
 
275
  gr.Examples(
276
  examples=examples,
277
  inputs=prompt,
278
  outputs=[result, seed],
279
+ fn=generate,
280
+ cache_examples=False,
281
  )
282
 
283
  use_negative_prompt.change(
 
286
  outputs=negative_prompt,
287
  api_name=False,
288
  )
289
+
290
 
291
  gr.on(
292
  triggers=[
 
294
  negative_prompt.submit,
295
  run_button.click,
296
  ],
297
+ fn=generate,
298
  inputs=[
299
  prompt,
300
  negative_prompt,
301
+ style_selection,
302
  use_negative_prompt,
303
+ num_inference_steps,
304
+ num_images_per_prompt,
305
  seed,
306
  width,
307
  height,
308
  guidance_scale,
 
309
  randomize_seed,
310
  ],
311
  outputs=[result, seed],
312
  api_name="run",
313
  )
314
+
315
  if __name__ == "__main__":
316
+ demo.queue(max_size=20).launch(show_api=False, debug=False)