prithivMLmods commited on
Commit
e89bce5
·
verified ·
1 Parent(s): af94c6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -58
app.py CHANGED
@@ -1,7 +1,7 @@
 
1
  import os
2
  import random
3
  import uuid
4
- import json
5
  import gradio as gr
6
  import numpy as np
7
  from PIL import Image
@@ -9,45 +9,55 @@ import spaces
9
  import torch
10
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
 
12
- DESCRIPTIONx = """## REALVISXL V5 🤗
13
- """
14
-
15
  css = '''
16
- .gradio-container{max-width: 560px !important}
17
  h1{text-align:center}
18
  footer {
19
  visibility: hidden
20
  }
21
  '''
22
 
 
 
 
23
  examples = [
24
- "3d image, cute girl, in the style of Pixar --ar 1:2 --stylize 750, 4K resolution highlights, Sharp focus, octane render, ray tracing, Ultra-High-Definition, 8k, UHD, HDR, (Masterpiece:1.5), (best quality:1.5)",
25
- "Cold coffee in a cup bokeh --ar 85:128 --v 6.0 --style raw5, 4K",
 
26
  ]
27
 
28
- MODEL_ID = os.getenv("MODEL_VAL_PATH", "SG161222/RealVisXL_V4.0")
 
 
 
 
 
29
  MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
30
  USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
31
  ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
32
- BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # Allow generating multiple images at once
33
 
34
- #Load model outside of function
35
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
36
- pipe = StableDiffusionXLPipeline.from_pretrained(
37
- MODEL_ID,
38
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
39
- use_safetensors=True,
40
- add_watermarker=False,
41
- ).to(device)
42
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
43
-
44
- # <compile speedup >
45
- if USE_TORCH_COMPILE:
46
- pipe.compile()
47
-
48
- # Offloading capacity (RAM)
49
- if ENABLE_CPU_OFFLOAD:
50
- pipe.enable_model_cpu_offload()
 
 
 
 
 
51
 
52
  MAX_SEED = np.iinfo(np.int32).max
53
 
@@ -63,6 +73,7 @@ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
63
 
64
  @spaces.GPU(duration=60, enable_queue=True)
65
  def generate(
 
66
  prompt: str,
67
  negative_prompt: str = "",
68
  use_negative_prompt: bool = False,
@@ -73,13 +84,15 @@ def generate(
73
  num_inference_steps: int = 25,
74
  randomize_seed: bool = False,
75
  use_resolution_binning: bool = True,
76
- num_images: int = 1, # Number of images to generate
77
  progress=gr.Progress(track_tqdm=True),
78
  ):
 
 
 
79
  seed = int(randomize_seed_fn(seed, randomize_seed))
80
  generator = torch.Generator(device=device).manual_seed(seed)
81
 
82
- #Options
83
  options = {
84
  "prompt": [prompt] * num_images,
85
  "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
@@ -91,11 +104,9 @@ def generate(
91
  "output_type": "pil",
92
  }
93
 
94
- #VRAM usage Lesser
95
  if use_resolution_binning:
96
  options["use_resolution_binning"] = True
97
 
98
- #Images potential batches
99
  images = []
100
  for i in range(0, num_images, BATCH_SIZE):
101
  batch_options = options.copy()
@@ -106,39 +117,63 @@ def generate(
106
 
107
  image_paths = [save_image(img) for img in images]
108
  return image_paths, seed
109
- #Main gr.Block
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
111
- gr.Markdown(DESCRIPTIONx)
 
 
 
 
 
 
 
 
 
 
112
 
113
- with gr.Group():
114
- with gr.Row():
115
- prompt = gr.Text(
116
- label="Prompt",
117
- show_label=False,
118
- max_lines=1,
119
- placeholder="Enter your prompt",
120
- container=False,
121
- )
122
- run_button = gr.Button("Run", scale=0)
123
- result = gr.Gallery(label="Result", columns=1, show_label=False)
124
- with gr.Accordion("Advanced options", open=False, visible=True):
125
  num_images = gr.Slider(
126
  label="Number of Images",
127
  minimum=1,
128
- maximum=4,
129
  step=1,
130
  value=1,
131
  )
132
  with gr.Row():
133
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
134
- negative_prompt = gr.Text(
135
- label="Negative prompt",
136
- max_lines=5,
137
- lines=4,
138
- placeholder="Enter a negative prompt",
139
- value="bad hands, bad anatomy, ugly, deformed, (face asymmetry, eyes asymmetry, deformed eyes, deformed mouth, open mouth)",
140
- visible=True,
141
- )
 
142
  seed = gr.Slider(
143
  label="Seed",
144
  minimum=0,
@@ -147,7 +182,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
147
  value=0,
148
  )
149
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
150
- with gr.Row(visible=True):
151
  width = gr.Slider(
152
  label="Width",
153
  minimum=512,
@@ -173,7 +208,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
173
  num_inference_steps = gr.Slider(
174
  label="Number of inference steps",
175
  minimum=1,
176
- maximum=25,
177
  step=1,
178
  value=23,
179
  )
@@ -190,6 +225,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
190
  outputs=negative_prompt,
191
  api_name=False,
192
  )
 
193
  gr.on(
194
  triggers=[
195
  prompt.submit,
@@ -198,6 +234,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
198
  ],
199
  fn=generate,
200
  inputs=[
 
201
  prompt,
202
  negative_prompt,
203
  use_negative_prompt,
@@ -211,7 +248,14 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
211
  ],
212
  outputs=[result, seed],
213
  api_name="run",
214
- )
215
-
 
 
 
 
 
 
 
216
  if __name__ == "__main__":
217
- demo.queue(max_size=40).launch()
 
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
 
9
  import torch
10
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
 
 
 
 
12
  css = '''
13
+ .gradio-container{max-width: 570px !important}
14
  h1{text-align:center}
15
  footer {
16
  visibility: hidden
17
  }
18
  '''
19
 
20
+ DESCRIPTIONXX = """
21
+ ## REALVISXL V5 + V5 LIGHTNING ⚡
22
+ """
23
  examples = [
24
+
25
+ "Illustration of A starry night camp in the mountains, 4k, cinematic --ar 85:128 --v 6.0 --style raw",
26
+ "A delicious ceviche cheesecake slice, 4k, octane render, ray tracing, Ultra-High-Definition"
27
  ]
28
 
29
+ MODEL_OPTIONS = {
30
+ "REALVISXL V5.0": "SG161222/RealVisXL_V4.0_Lightning",
31
+ "V5.0 LIGHTNING": "SG161222/RealVisXL_V3.0_Turbo",
32
+
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
+ def load_and_prepare_model(model_id):
43
+ pipe = StableDiffusionXLPipeline.from_pretrained(
44
+ model_id,
45
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
46
+ use_safetensors=True,
47
+ add_watermarker=False,
48
+ ).to(device)
49
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
50
+
51
+ if USE_TORCH_COMPILE:
52
+ pipe.compile()
53
+
54
+ if ENABLE_CPU_OFFLOAD:
55
+ pipe.enable_model_cpu_offload()
56
+
57
+ return pipe
58
+
59
+ # Preload and compile both models
60
+ models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
61
 
62
  MAX_SEED = np.iinfo(np.int32).max
63
 
 
73
 
74
  @spaces.GPU(duration=60, enable_queue=True)
75
  def generate(
76
+ model_choice: str,
77
  prompt: str,
78
  negative_prompt: str = "",
79
  use_negative_prompt: bool = False,
 
84
  num_inference_steps: int = 25,
85
  randomize_seed: bool = False,
86
  use_resolution_binning: bool = True,
87
+ num_images: int = 1,
88
  progress=gr.Progress(track_tqdm=True),
89
  ):
90
+ global models
91
+ pipe = models[model_choice]
92
+
93
  seed = int(randomize_seed_fn(seed, randomize_seed))
94
  generator = torch.Generator(device=device).manual_seed(seed)
95
 
 
96
  options = {
97
  "prompt": [prompt] * num_images,
98
  "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
 
104
  "output_type": "pil",
105
  }
106
 
 
107
  if use_resolution_binning:
108
  options["use_resolution_binning"] = True
109
 
 
110
  images = []
111
  for i in range(0, num_images, BATCH_SIZE):
112
  batch_options = options.copy()
 
117
 
118
  image_paths = [save_image(img) for img in images]
119
  return image_paths, seed
120
+
121
+ #def load_predefined_images():
122
+ # predefined_images = [
123
+ # "assets/1.png",
124
+ # "assets/2.png",
125
+ # "assets/3.png",
126
+ # "assets/4.png",
127
+ # "assets/5.png",
128
+ # "assets/6.png",
129
+ # "assets/7.png",
130
+ #"assets/8.png",
131
+ #"assets/9.png",
132
+ #"assets/10.png",
133
+ #"assets/11.png",
134
+ #"assets/12.png",
135
+ #]
136
+ #return predefined_images
137
+
138
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
139
+ gr.Markdown(DESCRIPTIONXX)
140
+ with gr.Row():
141
+ prompt = gr.Text(
142
+ label="Prompt",
143
+ show_label=False,
144
+ max_lines=1,
145
+ placeholder="Enter your prompt",
146
+ container=False,
147
+ )
148
+ run_button = gr.Button("Run⚡", scale=0)
149
+ result = gr.Gallery(label="Result", columns=1, show_label=False)
150
 
151
+ with gr.Row():
152
+ model_choice = gr.Dropdown(
153
+ label="Model Selection",
154
+ choices=list(MODEL_OPTIONS.keys()),
155
+ value="Lightning"
156
+ )
157
+
158
+ with gr.Accordion("Advanced options", open=False, visible==True):
 
 
 
 
159
  num_images = gr.Slider(
160
  label="Number of Images",
161
  minimum=1,
162
+ maximum=1,
163
  step=1,
164
  value=1,
165
  )
166
  with gr.Row():
167
+ with gr.Column(scale=1):
168
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
169
+ negative_prompt = gr.Text(
170
+ label="Negative prompt",
171
+ max_lines=5,
172
+ lines=4,
173
+ placeholder="Enter a negative prompt",
174
+ value="(octane render, render, drawing, anime, bad photo, bad photography:1.3), (worst quality, low quality, blurry:1.2), (bad teeth, deformed teeth, deformed lips), (bad anatomy, bad proportions:1.1), (deformed iris, deformed pupils), (deformed eyes, bad eyes), (deformed face, ugly face, bad face), (deformed hands, bad hands, fused fingers), morbid, mutilated, mutation, disfigured",
175
+ visible=True,
176
+ )
177
  seed = gr.Slider(
178
  label="Seed",
179
  minimum=0,
 
182
  value=0,
183
  )
184
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
185
+ with gr.Row():
186
  width = gr.Slider(
187
  label="Width",
188
  minimum=512,
 
208
  num_inference_steps = gr.Slider(
209
  label="Number of inference steps",
210
  minimum=1,
211
+ maximum=40,
212
  step=1,
213
  value=23,
214
  )
 
225
  outputs=negative_prompt,
226
  api_name=False,
227
  )
228
+
229
  gr.on(
230
  triggers=[
231
  prompt.submit,
 
234
  ],
235
  fn=generate,
236
  inputs=[
237
+ model_choice,
238
  prompt,
239
  negative_prompt,
240
  use_negative_prompt,
 
248
  ],
249
  outputs=[result, seed],
250
  api_name="run",
251
+ )
252
+ gr.Markdown("🥠Models used in the playground [[REALVISXL V5.0]](https://huggingface.co/SG161222/RealVisXL_V5.0), [[REALVISXL V5.0 LIGHTNING]](https://huggingface.co/SG161222/RealVisXL_V5.0_Lightning) 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 multi different variants available.")
253
+ gr.Markdown("🥠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.<a href='https://huggingface.co/spaces/prithivMLmods/Top-Prompt-Collection' target='_blank'>Try prompts</a>.")
254
+ gr.Markdown("⚠️ users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.")
255
+
256
+ # with gr.Column(scale=3):
257
+ # gr.Markdown("### Image Gallery")
258
+ # predefined_gallery = gr.Gallery(label="Image Gallery", columns=3, show_label=False, value=load_predefined_images())
259
+
260
  if __name__ == "__main__":
261
+ demo.queue(max_size=20).launch(show_api=False)