TobDeBer commited on
Commit
1fee954
·
1 Parent(s): 9bc9904

RealVis Refiner based on V5

Browse files
app.py CHANGED
@@ -1,352 +1,82 @@
1
- #!/usr/bin/env python
2
- # Permission is hereby granted, free of charge, to any person obtaining a copy
3
- # of this software and associated documentation files (the "Software"), to deal
4
- # in the Software without restriction, including without limitation the rights
5
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6
- # copies of the Software, and to permit persons to whom the Software is
7
-
8
- import os
9
- import random
10
- import uuid
11
- import gradio as gr
12
- import numpy as np
13
  from PIL import Image
14
- import spaces
 
15
  import torch
16
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
17
- from typing import Tuple
18
 
 
 
19
 
20
- css = '''
21
- .gradio-container{max-width: 575px !important}
22
- h1{text-align:center}
23
- footer {
24
- visibility: hidden
25
  }
26
- '''
27
-
28
-
29
- DESCRIPTIONXX = """
30
- ## REALVISXL V5.0 ⚡
31
- """
32
-
33
- examples = [
34
-
35
- "Many apples splashed with drops of water within a fancy bowl 4k, hdr --v 6.0 --style raw",
36
- "A profile photo of a dog, brown background, shot on Leica M6 --ar 128:85 --v 6.0 --style raw",
37
- ]
38
-
39
- MODEL_OPTIONS = {
40
- "REALVISXL V5.0": "SG161222/RealVisXL_V5.0",
41
- "LIGHTNING V5.0": "SG161222/RealVisXL_V5.0_Lightning",
42
  }
 
43
 
44
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
45
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
46
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
47
- BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
48
-
49
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
50
-
51
- style_list = [
52
- {
53
- "name": "3840 x 2160",
54
- "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
55
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
56
- },
57
- {
58
- "name": "2560 x 1440",
59
- "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
60
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
61
- },
62
- {
63
- "name": "HD+",
64
- "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
65
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
66
- },
67
- {
68
- "name": "Style Zero",
69
- "prompt": "{prompt}",
70
- "negative_prompt": "",
71
- },
72
- ]
73
-
74
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
75
- DEFAULT_STYLE_NAME = "3840 x 2160"
76
- STYLE_NAMES = list(styles.keys())
77
-
78
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
79
- if style_name in styles:
80
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
81
- else:
82
- p, n = styles[DEFAULT_STYLE_NAME]
83
-
84
- if not negative:
85
- negative = ""
86
- return p.replace("{prompt}", positive), n + negative
87
-
88
- def load_and_prepare_model(model_id):
89
- pipe = StableDiffusionXLPipeline.from_pretrained(
90
- model_id,
91
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
92
  use_safetensors=True,
93
  add_watermarker=False,
94
  ).to(device)
95
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
96
-
97
- if USE_TORCH_COMPILE:
98
- pipe.compile()
99
-
100
- if ENABLE_CPU_OFFLOAD:
101
- pipe.enable_model_cpu_offload()
102
-
103
- return pipe
104
-
105
- # Preload and compile both models
106
- models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
107
-
108
- MAX_SEED = np.iinfo(np.int32).max
109
-
110
- def save_image(img):
111
- unique_name = str(uuid.uuid4()) + ".png"
112
- img.save(unique_name)
113
- return unique_name
114
-
115
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
116
- if randomize_seed:
117
- seed = random.randint(0, MAX_SEED)
118
- return seed
119
-
120
- @spaces.GPU(duration=60, enable_queue=True)
121
- def generate(
122
- model_choice: str,
123
- prompt: str,
124
- negative_prompt: str = "",
125
- use_negative_prompt: bool = False,
126
- style_selection: str = DEFAULT_STYLE_NAME,
127
- seed: int = 1,
128
- width: int = 1024,
129
- height: int = 1024,
130
- guidance_scale: float = 3,
131
- num_inference_steps: int = 25,
132
- randomize_seed: bool = False,
133
- use_resolution_binning: bool = True,
134
- num_images: int = 1,
135
- progress=gr.Progress(track_tqdm=True),
136
- ):
137
- global models
138
- pipe = models[model_choice]
139
-
140
- seed = int(randomize_seed_fn(seed, randomize_seed))
141
- generator = torch.Generator(device=device).manual_seed(seed)
142
-
143
- prompt, negative_prompt = apply_style(style_selection, prompt, negative_prompt)
144
-
145
- options = {
146
- "prompt": [prompt] * num_images,
147
- "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
148
- "width": width,
149
- "height": height,
150
- "guidance_scale": guidance_scale,
151
- "num_inference_steps": num_inference_steps,
152
- "generator": generator,
153
- "output_type": "pil",
154
- }
155
-
156
- if use_resolution_binning:
157
- options["use_resolution_binning"] = True
158
-
159
- images = []
160
- for i in range(0, num_images, BATCH_SIZE):
161
- batch_options = options.copy()
162
- batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
163
- if "negative_prompt" in batch_options:
164
- batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
165
- images.extend(pipe(**batch_options).images)
166
-
167
- image_paths = [save_image(img) for img in images]
168
- return image_paths, seed
169
-
170
- def load_predefined_images1():
171
- predefined_images1 = [
172
- "assets/7.png",
173
- "assets/8.png",
174
- "assets/9.png",
175
- "assets/1.png",
176
- "assets/2.png",
177
- "assets/3.png",
178
- "assets/4.png",
179
- "assets/5.png",
180
- "assets/6.png",
181
- ]
182
- return predefined_images1
183
-
184
-
185
- def load_predefined_images():
186
- predefined_images = [
187
- "assets2/11.png",
188
- "assets2/22.png",
189
- "assets2/33.png",
190
- "assets2/44.png",
191
- "assets2/55.png",
192
- "assets2/66.png",
193
- "assets2/77.png",
194
- "assets2/88.png",
195
- "assets2/99.png",
196
- ]
197
- return predefined_images
198
-
199
-
200
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
201
- gr.Markdown(DESCRIPTIONXX)
202
- with gr.Row():
203
- prompt = gr.Text(
204
- label="Prompt",
205
- show_label=False,
206
- max_lines=1,
207
- placeholder="Enter your prompt",
208
- container=False,
209
- )
210
- run_button = gr.Button("Run", scale=0)
211
- result = gr.Gallery(label="Result", columns=1, show_label=False)
212
 
213
- with gr.Row():
214
- model_choice = gr.Dropdown(
215
- label="Model Selection🔻",
216
- choices=list(MODEL_OPTIONS.keys()),
217
- value="LIGHTNING V5.0"
218
- )
219
 
220
- with gr.Accordion("Advanced options", open=False, visible=False):
221
- style_selection = gr.Radio(
222
- show_label=True,
223
- container=True,
224
- interactive=True,
225
- choices=STYLE_NAMES,
226
- value=DEFAULT_STYLE_NAME,
227
- label="Quality Style",
228
- )
229
- num_images = gr.Slider(
230
- label="Number of Images",
231
- minimum=1,
232
- maximum=5,
233
- step=1,
234
- value=1,
235
- )
236
- with gr.Row():
237
- with gr.Column(scale=1):
238
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
239
- negative_prompt = gr.Text(
240
- label="Negative prompt",
241
- max_lines=5,
242
- lines=4,
243
- placeholder="Enter a negative prompt",
244
- 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",
245
- visible=True,
246
- )
247
- seed = gr.Slider(
248
- label="Seed",
249
- minimum=0,
250
- maximum=MAX_SEED,
251
- step=1,
252
- value=0,
253
- )
254
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
255
  with gr.Row():
256
- width = gr.Slider(
257
- label="Width",
258
- minimum=512,
259
- maximum=MAX_IMAGE_SIZE,
260
- step=64,
261
- value=1024,
262
- )
263
- height = gr.Slider(
264
- label="Height",
265
- minimum=512,
266
- maximum=MAX_IMAGE_SIZE,
267
- step=64,
268
- value=1024,
269
- )
270
- with gr.Row():
271
- guidance_scale = gr.Slider(
272
- label="Guidance Scale",
273
- minimum=0.1,
274
- maximum=6,
275
- step=0.1,
276
- value=3.0,
277
- )
278
- num_inference_steps = gr.Slider(
279
- label="Number of inference steps",
280
- minimum=1,
281
- maximum=60,
282
- step=1,
283
- value=28,
284
- )
285
-
286
- gr.Examples(
287
- examples=examples,
288
- inputs=prompt,
289
- cache_examples=False
290
- )
291
-
292
- use_negative_prompt.change(
293
- fn=lambda x: gr.update(visible=x),
294
- inputs=use_negative_prompt,
295
- outputs=negative_prompt,
296
- api_name=False,
297
- )
298
-
299
- gr.on(
300
- triggers=[
301
- prompt.submit,
302
- negative_prompt.submit,
303
- run_button.click,
304
- ],
305
- fn=generate,
306
- inputs=[
307
- model_choice,
308
- prompt,
309
- negative_prompt,
310
- use_negative_prompt,
311
- style_selection,
312
- seed,
313
- width,
314
- height,
315
- guidance_scale,
316
- num_inference_steps,
317
- randomize_seed,
318
- num_images,
319
- ],
320
- outputs=[result, seed],
321
- )
322
-
323
- gr.Markdown("### LIGHTNING V5.0")
324
- predefined_gallery = gr.Gallery(label="LIGHTNING V5.0", columns=3, show_label=False, value=load_predefined_images())
325
-
326
- gr.Markdown("### REALVISXL V5.0")
327
- predefined_gallery = gr.Gallery(label="REALVISXL V5.0", columns=3, show_label=False, value=load_predefined_images1())
328
-
329
- gr.Markdown(
330
- """
331
- <div style="text-align: justify;">
332
- ⚡Models used in the playground <a href="https://huggingface.co/SG161222/RealVisXL_V5.0">[REALVISXL V5.0]</a>, <a href="https://huggingface.co/SG161222/RealVisXL_V5.0_Lightning">[REALVISXL V5.0 LIGHTNING]</a> for image generation. Stable Diffusion XL piped (SDXL) model HF. This is the demo space for generating images using the Stable Diffusion XL models, with multiple different variants available.
333
- </div>
334
- """)
335
-
336
- gr.Markdown(
337
- """
338
- <div style="text-align: justify;">
339
- ⚡This is the demo space for generating images using Stable Diffusion XL with quality styles, different models, and types. Try the sample prompts to generate higher quality images. Try the sample prompts for generating higher quality images.
340
- <a href='https://huggingface.co/spaces/prithivMLmods/Top-Prompt-Collection' target='_blank'>Try prompts</a>.
341
- </div>
342
- """)
343
-
344
- gr.Markdown(
345
- """
346
- <div style="text-align: justify;">
347
- ⚠️ Users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.
348
- </div>
349
- """)
350
 
351
- if __name__ == "__main__":
352
- demo.queue(max_size=50).launch(show_api=False)
 
1
+ from diffusers import EulerAncestralDiscreteScheduler, StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
 
 
 
 
 
 
 
 
 
 
 
2
  from PIL import Image
3
+ import gradio as gr
4
+ import random
5
  import torch
6
+ import math
 
7
 
8
+ device = "cuda"
9
+ negative_prompt = "deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime, text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck"
10
 
11
+ css = """
12
+ .btn-green {
13
+ background-image: linear-gradient(to bottom right, #6dd178, #00a613) !important;
14
+ border-color: #22c55e !important;
15
+ color: #166534 !important;
16
  }
17
+ .btn-green:hover {
18
+ background-image: linear-gradient(to bottom right, #6dd178, #6dd178) !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  }
20
+ """
21
 
22
+ def generate(prompt, samp_steps, seed, progress=gr.Progress(track_tqdm=True)):
23
+ print("prompt = ", prompt)
24
+ turbo_steps=5 # use sweet spot
25
+ if seed < 0:
26
+ seed = random.randint(1,999999)
27
+ image = txt2img(
28
+ prompt=prompt,
29
+ negative_prompt=negative_prompt,
30
+ num_inference_steps=turbo_steps,
31
+ guidance_scale=2,
32
+ seed=seed,
33
+ ).images[0]
34
+ upscaled_image = image.resize((1024,1024), 1)
35
+ final_image = img2img(
36
+ prompt=prompt,
37
+ negative_prompt=negative_prompt,
38
+ image=upscaled_image,
39
+ num_inference_steps=max(1,samp_steps-turbo_steps*2), # always discount lightning at 2x efficiency
40
+ guidance_scale=5,
41
+ strength=1,
42
+ seed=seed,
43
+ ).images[0]
44
+ return [final_image], seed
45
+
46
+
47
+ def set_base_models():
48
+ txt2img = StableDiffusionXLPipeline.from_pretrained(
49
+ "SG161222/RealVisXL_V5.0_Lightning",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
51
  use_safetensors=True,
52
  add_watermarker=False,
53
  ).to(device)
54
+ txt2img.scheduler = EulerAncestralDiscreteScheduler.from_config(txt2img.scheduler.config)
55
+
56
+ img2img = StableDiffusionXLImg2ImgPipeline.from_pretrained(
57
+ "SG161222/RealVisXL_V5.0",
58
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32,
59
+ use_safetensors=True,
60
+ add_watermarker=False,
61
+ ).to(device)
62
+ img2img.scheduler = EulerAncestralDiscreteScheduler.from_config(img2img.scheduler.config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ return txt2img, img2img
 
 
 
 
 
65
 
66
+ with gr.Blocks(css=css) as demo:
67
+ with gr.Column():
68
+ prompt = gr.Textbox(label="Prompt for RealVisXL_V5")
69
+ submit_btn = gr.Button("Generate", elem_classes="btn-green")
70
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  with gr.Row():
72
+ turbo_steps = gr.Slider(5, 5, value=5, step=1, label="Turbo steps (fixed at 5)")
73
+ sampling_steps = gr.Slider(15, 50, value=25, step=1, label="Effective steps")
74
+ seed = gr.Number(label="Seed", value=-1, minimum=-1, precision=0)
75
+ lastSeed = gr.Number(label="Last Seed", value=-1, interactive=False)
76
+
77
+ gallery = gr.Gallery(show_label=False, preview=True, container=False, height=1100)
78
+
79
+ submit_btn.click(generate, [prompt, sampling_steps, seed], [gallery, lastSeed], queue=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ txt2img, img2img = set_base_models()
82
+ demo.launch(debug=True, share=True)
assets/1.png DELETED

Git LFS Details

  • SHA256: 70782d518ca6cc50c076a6ba1953e53c3ec94df3f91a76e9653fee22ba46b8aa
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
assets/2.png DELETED

Git LFS Details

  • SHA256: d412bbd5dd6682a03bbfd12ddbd04bbf743e02ae7f9000a322dfa8369b790c38
  • Pointer size: 132 Bytes
  • Size of remote file: 1.45 MB
assets/3.png DELETED

Git LFS Details

  • SHA256: 1e19171bf11f7a7c16ede7c779b6a33e07371a656c63240b2ae038f33ef72a62
  • Pointer size: 132 Bytes
  • Size of remote file: 1.39 MB
assets/4.png DELETED

Git LFS Details

  • SHA256: d7d3857eb047b907694d90ae4c09706866a3ffd82b77a4ac191b54a6cd52ccef
  • Pointer size: 132 Bytes
  • Size of remote file: 1.52 MB
assets/5.png DELETED

Git LFS Details

  • SHA256: 7f71714ab1df1d2c5ae6ce3615bdd3c6fa70b4e7aaec47570ad913918d92c39f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.7 MB
assets/6.png DELETED

Git LFS Details

  • SHA256: 50f52b5f4ecf44e1b986083e9831adeff33e5712bd5ea56096dc9280e65a69cf
  • Pointer size: 132 Bytes
  • Size of remote file: 1.6 MB
assets/7.png DELETED

Git LFS Details

  • SHA256: 04ad5ca448c3d0e64baae8dc7820354fc915a50c55637c0012963b909b2755e2
  • Pointer size: 132 Bytes
  • Size of remote file: 1.65 MB
assets/8.png DELETED

Git LFS Details

  • SHA256: 162f929907be3a59d532dd990276fcd51b42c3d6f96e2f0171ef7d82789df9fc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.64 MB
assets/9.png DELETED

Git LFS Details

  • SHA256: e79ea4bfb0e03b2accdafa6225565ca6c8eeb673802655e503c6983d150e5336
  • Pointer size: 132 Bytes
  • Size of remote file: 1.39 MB
assets/demo.txt DELETED
File without changes
assets2/11.png DELETED

Git LFS Details

  • SHA256: 5a41dfa62733c27f657128fe33fd1e48dca2a09c89c04fb8523591bdb19c0ffd
  • Pointer size: 132 Bytes
  • Size of remote file: 1.45 MB
assets2/22.png DELETED

Git LFS Details

  • SHA256: 01e0f2a09d88ae8a7527f24c38de3fd27b596923ac44e58f1b0b0e1e80fde9bb
  • Pointer size: 132 Bytes
  • Size of remote file: 1.32 MB
assets2/33.png DELETED

Git LFS Details

  • SHA256: 336f95b3c3085ee582d53b0dded5209d0dd3b7e36df8ce4e567a3a6e57c4e769
  • Pointer size: 132 Bytes
  • Size of remote file: 1.38 MB
assets2/44.png DELETED

Git LFS Details

  • SHA256: 5613623febd83852e664dce5f089a8ec3ea13b98e5dcf5bb39ee3880d13a8f88
  • Pointer size: 132 Bytes
  • Size of remote file: 1.56 MB
assets2/55.png DELETED

Git LFS Details

  • SHA256: 96b55e256afa031926d712c4fce657e432bac9e9fd094eb600dbf6343544cee4
  • Pointer size: 132 Bytes
  • Size of remote file: 1.68 MB
assets2/66.png DELETED

Git LFS Details

  • SHA256: 6b38f33f586cb55f66f9c3b53d098661bff57937ea1a65190b1556055abfee50
  • Pointer size: 132 Bytes
  • Size of remote file: 1.68 MB
assets2/77.png DELETED

Git LFS Details

  • SHA256: 38f0cffe5c5dd2150dfdf6b2eadfacc72c9dfdb69cfb369bbdf1b12e012db0b5
  • Pointer size: 132 Bytes
  • Size of remote file: 1.99 MB
assets2/88.png DELETED

Git LFS Details

  • SHA256: 2ff4deeccb4bc5046ba7240356c95a3d003961388408926a9bbeebfafa2ec581
  • Pointer size: 132 Bytes
  • Size of remote file: 1.59 MB
assets2/99.png DELETED

Git LFS Details

  • SHA256: 0cbff01753ffa850be8b774aaf0f40d09ee4461897b08837bdd1dc4851bab821
  • Pointer size: 132 Bytes
  • Size of remote file: 1.29 MB
files/demo.txt DELETED
@@ -1,285 +0,0 @@
1
- #!/usr/bin/env python
2
- import os
3
- import random
4
- import uuid
5
- import gradio as gr
6
- import numpy as np
7
- from PIL import Image
8
- import spaces
9
- import torch
10
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
- from typing import Tuple
12
-
13
- css = '''
14
- .gradio-container{max-width: 570px !important}
15
- h1{text-align:center}
16
- footer {
17
- visibility: hidden
18
- }
19
- '''
20
-
21
- DESCRIPTIONXX = """
22
- ## REALVISXL V5 + LIGHTNING ⚡
23
- """
24
-
25
- examples = [
26
- "Illustration of A starry night camp in the mountains, 4k, cinematic --ar 85:128 --v 6.0 --style raw",
27
- "A delicious ceviche cheesecake slice, 4k, octane render, ray tracing, Ultra-High-Definition"
28
- ]
29
-
30
- MODEL_OPTIONS = {
31
- "REALVISXL V5.0": "SG161222/RealVisXL_V5.0",
32
- # "LIGHTNING V5.0": "SG161222/RealVisXL_V5.0_Lightning",
33
- }
34
-
35
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
36
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
37
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
38
- BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
39
-
40
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
41
-
42
- style_list = [
43
- {
44
- "name": "3840 x 2160",
45
- "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
46
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
47
- },
48
- {
49
- "name": "2560 x 1440",
50
- "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
51
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
52
- },
53
- {
54
- "name": "HD+",
55
- "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
56
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
57
- },
58
- {
59
- "name": "Style Zero",
60
- "prompt": "{prompt}",
61
- "negative_prompt": "",
62
- },
63
- ]
64
-
65
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
66
- DEFAULT_STYLE_NAME = "3840 x 2160"
67
- STYLE_NAMES = list(styles.keys())
68
-
69
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
70
- if style_name in styles:
71
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
72
- else:
73
- p, n = styles[DEFAULT_STYLE_NAME]
74
-
75
- if not negative:
76
- negative = ""
77
- return p.replace("{prompt}", positive), n + negative
78
-
79
- def load_and_prepare_model(model_id):
80
- pipe = StableDiffusionXLPipeline.from_pretrained(
81
- model_id,
82
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
83
- use_safetensors=True,
84
- add_watermarker=False,
85
- ).to(device)
86
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
87
-
88
- if USE_TORCH_COMPILE:
89
- pipe.compile()
90
-
91
- if ENABLE_CPU_OFFLOAD:
92
- pipe.enable_model_cpu_offload()
93
-
94
- return pipe
95
-
96
- # Preload and compile both models
97
- models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
98
-
99
- MAX_SEED = np.iinfo(np.int32).max
100
-
101
- def save_image(img):
102
- unique_name = str(uuid.uuid4()) + ".png"
103
- img.save(unique_name)
104
- return unique_name
105
-
106
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
107
- if randomize_seed:
108
- seed = random.randint(0, MAX_SEED)
109
- return seed
110
-
111
- @spaces.GPU(duration=60, enable_queue=True)
112
- def generate(
113
- model_choice: str,
114
- prompt: str,
115
- negative_prompt: str = "",
116
- use_negative_prompt: bool = False,
117
- style_selection: str = DEFAULT_STYLE_NAME,
118
- seed: int = 1,
119
- width: int = 1024,
120
- height: int = 1024,
121
- guidance_scale: float = 3,
122
- num_inference_steps: int = 25,
123
- randomize_seed: bool = False,
124
- use_resolution_binning: bool = True,
125
- num_images: int = 1,
126
- progress=gr.Progress(track_tqdm=True),
127
- ):
128
- global models
129
- pipe = models[model_choice]
130
-
131
- seed = int(randomize_seed_fn(seed, randomize_seed))
132
- generator = torch.Generator(device=device).manual_seed(seed)
133
-
134
- prompt, negative_prompt = apply_style(style_selection, prompt, negative_prompt)
135
-
136
- options = {
137
- "prompt": [prompt] * num_images,
138
- "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
139
- "width": width,
140
- "height": height,
141
- "guidance_scale": guidance_scale,
142
- "num_inference_steps": num_inference_steps,
143
- "generator": generator,
144
- "output_type": "pil",
145
- }
146
-
147
- if use_resolution_binning:
148
- options["use_resolution_binning"] = True
149
-
150
- images = []
151
- for i in range(0, num_images, BATCH_SIZE):
152
- batch_options = options.copy()
153
- batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
154
- if "negative_prompt" in batch_options:
155
- batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
156
- images.extend(pipe(**batch_options).images)
157
-
158
- image_paths = [save_image(img) for img in images]
159
- return image_paths, seed
160
-
161
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
162
- gr.Markdown(DESCRIPTIONXX)
163
- with gr.Row():
164
- prompt = gr.Text(
165
- label="Prompt",
166
- show_label=False,
167
- max_lines=1,
168
- placeholder="Enter your prompt",
169
- container=False,
170
- )
171
- run_button = gr.Button("Run", scale=0)
172
- result = gr.Gallery(label="Result", columns=1, show_label=False)
173
-
174
- with gr.Row():
175
- model_choice = gr.Dropdown(
176
- label="Model Selection🔻",
177
- choices=list(MODEL_OPTIONS.keys()),
178
- value="REALVISXL V5.0"
179
- )
180
-
181
- with gr.Accordion("Advanced options", open=False, visible=True):
182
- style_selection = gr.Radio(
183
- show_label=True,
184
- container=True,
185
- interactive=True,
186
- choices=STYLE_NAMES,
187
- value=DEFAULT_STYLE_NAME,
188
- label="Quality Style",
189
- )
190
- num_images = gr.Slider(
191
- label="Number of Images",
192
- minimum=1,
193
- maximum=5,
194
- step=1,
195
- value=1,
196
- )
197
- with gr.Row():
198
- with gr.Column(scale=1):
199
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
200
- negative_prompt = gr.Text(
201
- label="Negative prompt",
202
- max_lines=5,
203
- lines=4,
204
- placeholder="Enter a negative prompt",
205
- 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",
206
- visible=True,
207
- )
208
- seed = gr.Slider(
209
- label="Seed",
210
- minimum=0,
211
- maximum=MAX_SEED,
212
- step=1,
213
- value=0,
214
- )
215
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
216
- with gr.Row():
217
- width = gr.Slider(
218
- label="Width",
219
- minimum=512,
220
- maximum=MAX_IMAGE_SIZE,
221
- step=64,
222
- value=1024,
223
- )
224
- height = gr.Slider(
225
- label="Height",
226
- minimum=512,
227
- maximum=MAX_IMAGE_SIZE,
228
- step=64,
229
- value=1024,
230
- )
231
- with gr.Row():
232
- guidance_scale = gr.Slider(
233
- label="Guidance Scale",
234
- minimum=0.1,
235
- maximum=6,
236
- step=0.1,
237
- value=3.0,
238
- )
239
- num_inference_steps = gr.Slider(
240
- label="Number of inference steps",
241
- minimum=1,
242
- maximum=60,
243
- step=1,
244
- value=32,
245
- )
246
-
247
- gr.Examples(
248
- examples=examples,
249
- inputs=prompt,
250
- cache_examples=False
251
- )
252
-
253
- use_negative_prompt.change(
254
- fn=lambda x: gr.update(visible=x),
255
- inputs=use_negative_prompt,
256
- outputs=negative_prompt,
257
- api_name=False,
258
- )
259
-
260
- gr.on(
261
- triggers=[
262
- prompt.submit,
263
- negative_prompt.submit,
264
- run_button.click,
265
- ],
266
- fn=generate,
267
- inputs=[
268
- model_choice,
269
- prompt,
270
- negative_prompt,
271
- use_negative_prompt,
272
- style_selection,
273
- seed,
274
- width,
275
- height,
276
- guidance_scale,
277
- num_inference_steps,
278
- randomize_seed,
279
- gr.State(value=True),
280
- num_images,
281
- ],
282
- outputs=[result, seed],
283
- )
284
-
285
- demo.queue(concurrency_count=3).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
files/original-file.txt DELETED
@@ -1,300 +0,0 @@
1
- #!/usr/bin/env python
2
- # Permission is hereby granted, free of charge, to any person obtaining a copy
3
- # of this software and associated documentation files (the "Software"), to deal
4
- # in the Software without restriction, including without limitation the rights
5
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6
- # copies of the Software, and to permit persons to whom the Software is
7
-
8
- import os
9
- import random
10
- import uuid
11
- import gradio as gr
12
- import numpy as np
13
- from PIL import Image
14
- import spaces
15
- import torch
16
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
17
-
18
- css = '''
19
- .gradio-container{max-width: 570px !important}
20
- h1{text-align:center}
21
- footer {
22
- visibility: hidden
23
- }
24
- '''
25
-
26
- DESCRIPTIONXX = """
27
- ## REALVISXL V5 + LIGHTNING ⚡
28
- """
29
- examples = [
30
-
31
- "Illustration of A starry night camp in the mountains, 4k, cinematic --ar 85:128 --v 6.0 --style raw",
32
- "A delicious ceviche cheesecake slice, 4k, octane render, ray tracing, Ultra-High-Definition"
33
- ]
34
-
35
- MODEL_OPTIONS = {
36
- "REALVISXL V5.0": "SG161222/RealVisXL_V5.0",
37
- #"LIGHTNING V5.0": "SG161222/RealVisXL_V5.0_Lightning",
38
- }
39
-
40
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
41
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
42
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
43
- BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
44
-
45
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
46
-
47
- def load_and_prepare_model(model_id):
48
- pipe = StableDiffusionXLPipeline.from_pretrained(
49
- model_id,
50
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
51
- use_safetensors=True,
52
- add_watermarker=False,
53
- ).to(device)
54
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
55
-
56
- if USE_TORCH_COMPILE:
57
- pipe.compile()
58
-
59
- if ENABLE_CPU_OFFLOAD:
60
- pipe.enable_model_cpu_offload()
61
-
62
- return pipe
63
-
64
- # Preload and compile both models
65
- models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
66
-
67
- MAX_SEED = np.iinfo(np.int32).max
68
-
69
- def save_image(img):
70
- unique_name = str(uuid.uuid4()) + ".png"
71
- img.save(unique_name)
72
- return unique_name
73
-
74
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
75
- if randomize_seed:
76
- seed = random.randint(0, MAX_SEED)
77
- return seed
78
-
79
- @spaces.GPU(duration=60, enable_queue=True)
80
- def generate(
81
- model_choice: str,
82
- prompt: str,
83
- negative_prompt: str = "",
84
- use_negative_prompt: bool = False,
85
- seed: int = 1,
86
- width: int = 1024,
87
- height: int = 1024,
88
- guidance_scale: float = 3,
89
- num_inference_steps: int = 25,
90
- randomize_seed: bool = False,
91
- use_resolution_binning: bool = True,
92
- num_images: int = 1,
93
- progress=gr.Progress(track_tqdm=True),
94
- ):
95
- global models
96
- pipe = models[model_choice]
97
-
98
- seed = int(randomize_seed_fn(seed, randomize_seed))
99
- generator = torch.Generator(device=device).manual_seed(seed)
100
-
101
- options = {
102
- "prompt": [prompt] * num_images,
103
- "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
104
- "width": width,
105
- "height": height,
106
- "guidance_scale": guidance_scale,
107
- "num_inference_steps": num_inference_steps,
108
- "generator": generator,
109
- "output_type": "pil",
110
- }
111
-
112
- if use_resolution_binning:
113
- options["use_resolution_binning"] = True
114
-
115
- images = []
116
- for i in range(0, num_images, BATCH_SIZE):
117
- batch_options = options.copy()
118
- batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
119
- if "negative_prompt" in batch_options:
120
- batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
121
- images.extend(pipe(**batch_options).images)
122
-
123
- image_paths = [save_image(img) for img in images]
124
- return image_paths, seed
125
-
126
- #def load_predefined_images():
127
- # predefined_images = [
128
- # "assets/1.png",
129
- # "assets/2.png",
130
- # "assets/3.png",
131
- # "assets/4.png",
132
- # "assets/5.png",
133
- # "assets/6.png",
134
- # "assets/7.png",
135
- #"assets/8.png",
136
- #"assets/9.png",
137
- #]
138
- #return predefined_images
139
-
140
-
141
- # def load_predefined_images():
142
- # predefined_images = [
143
- # "assets2/11.png",
144
- # "assets2/22.png",
145
- # "assets2/33.png",
146
- # "assets2/44.png",
147
- # "assets2/55.png",
148
- # "assets2/66.png",
149
- # "assets2/77.png",
150
- # "assets2/88.png",
151
- # "assets2/99.png",
152
- # ]
153
- # return predefined_images
154
-
155
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
156
- gr.Markdown(DESCRIPTIONXX)
157
- with gr.Row():
158
- prompt = gr.Text(
159
- label="Prompt",
160
- show_label=False,
161
- max_lines=1,
162
- placeholder="Enter your prompt",
163
- container=False,
164
- )
165
- run_button = gr.Button("Run", scale=0)
166
- result = gr.Gallery(label="Result", columns=1, show_label=False)
167
-
168
- with gr.Row():
169
- model_choice = gr.Dropdown(
170
- label="Model Selection🔻",
171
- choices=list(MODEL_OPTIONS.keys()),
172
- value="REALVISXL V5.0"
173
- )
174
-
175
- with gr.Accordion("Advanced options", open=False, visible=True):
176
- num_images = gr.Slider(
177
- label="Number of Images",
178
- minimum=1,
179
- maximum=5,
180
- step=1,
181
- value=1,
182
- )
183
- with gr.Row():
184
- with gr.Column(scale=1):
185
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
186
- negative_prompt = gr.Text(
187
- label="Negative prompt",
188
- max_lines=5,
189
- lines=4,
190
- placeholder="Enter a negative prompt",
191
- 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",
192
- visible=True,
193
- )
194
- seed = gr.Slider(
195
- label="Seed",
196
- minimum=0,
197
- maximum=MAX_SEED,
198
- step=1,
199
- value=0,
200
- )
201
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
202
- with gr.Row():
203
- width = gr.Slider(
204
- label="Width",
205
- minimum=512,
206
- maximum=MAX_IMAGE_SIZE,
207
- step=64,
208
- value=1024,
209
- )
210
- height = gr.Slider(
211
- label="Height",
212
- minimum=512,
213
- maximum=MAX_IMAGE_SIZE,
214
- step=64,
215
- value=1024,
216
- )
217
- with gr.Row():
218
- guidance_scale = gr.Slider(
219
- label="Guidance Scale",
220
- minimum=0.1,
221
- maximum=6,
222
- step=0.1,
223
- value=3.0,
224
- )
225
- num_inference_steps = gr.Slider(
226
- label="Number of inference steps",
227
- minimum=1,
228
- maximum=60,
229
- step=1,
230
- value=32,
231
- )
232
-
233
- gr.Examples(
234
- examples=examples,
235
- inputs=prompt,
236
- cache_examples=False
237
- )
238
-
239
- use_negative_prompt.change(
240
- fn=lambda x: gr.update(visible=x),
241
- inputs=use_negative_prompt,
242
- outputs=negative_prompt,
243
- api_name=False,
244
- )
245
-
246
- gr.on(
247
- triggers=[
248
- prompt.submit,
249
- negative_prompt.submit,
250
- run_button.click,
251
- ],
252
- fn=generate,
253
- inputs=[
254
- model_choice,
255
- prompt,
256
- negative_prompt,
257
- use_negative_prompt,
258
- seed,
259
- width,
260
- height,
261
- guidance_scale,
262
- num_inference_steps,
263
- randomize_seed,
264
- num_images
265
- ],
266
- outputs=[result, seed],
267
- api_name="run",
268
- )
269
-
270
-
271
- #gr.Markdown("### REALVISXL V5.0")
272
- #predefined_gallery = gr.Gallery(label="REALVISXL V5.0", columns=3, show_label=False, value=load_predefined_images1())
273
-
274
- #gr.Markdown("### LIGHTNING V5.0")
275
- #predefined_gallery = gr.Gallery(label="LIGHTNING V5.0", columns=3, show_label=False, value=load_predefined_images())
276
-
277
- gr.Markdown(
278
- """
279
- <div style="text-align: justify;">
280
- ⚡Models used in the playground <a href="https://huggingface.co/SG161222/RealVisXL_V5.0">[REALVISXL V5.0]</a>, <a href="https://huggingface.co/SG161222/RealVisXL_V5.0_Lightning">[REALVISXL V5.0 LIGHTNING]</a> for image generation. Stable Diffusion XL piped (SDXL) model HF. This is the demo space for generating images using the Stable Diffusion XL models, with multiple different variants available.
281
- </div>
282
- """)
283
-
284
- gr.Markdown(
285
- """
286
- <div style="text-align: justify;">
287
- ⚡This is the demo space for generating images using Stable Diffusion XL with quality styles, different models, and types. Try the sample prompts to generate higher quality images. Try the sample prompts for generating higher quality images.
288
- <a href='https://huggingface.co/spaces/prithivMLmods/Top-Prompt-Collection' target='_blank'>Try prompts</a>.
289
- </div>
290
- """)
291
-
292
- gr.Markdown(
293
- """
294
- <div style="text-align: justify;">
295
- ⚠️ Users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.
296
- </div>
297
- """)
298
-
299
- if __name__ == "__main__":
300
- demo.queue(max_size=50).launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,10 +1,30 @@
1
- diffusers
2
  torch
3
  torchvision
 
4
  pipeline
5
  transformers
6
  accelerate
7
  safetensors
 
8
  spaces
 
 
9
  peft
10
- gradio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ git+https://github.com/huggingface/diffusers.git
2
  torch
3
  torchvision
4
+ xformers
5
  pipeline
6
  transformers
7
  accelerate
8
  safetensors
9
+ sentencepiece
10
  spaces
11
+ beautifulsoup4
12
+ ftfy
13
  peft
14
+ protobuf
15
+ invisible_watermark
16
+
17
+ huggingface_hub
18
+ pyyaml
19
+ packaging
20
+ numpy
21
+ Pillow
22
+ pytz
23
+ python-dateutil
24
+ click
25
+ rich
26
+
27
+ modin[all]
28
+ optimum-intel
29
+ openvino
30
+ onnx