onnew commited on
Commit
1dff4c8
·
verified ·
1 Parent(s): edd338a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -316
app.py CHANGED
@@ -1,331 +1,48 @@
1
  import os
2
- import random
3
  import uuid
4
  import gradio as gr
5
- import numpy as np
6
- from PIL import Image
7
- import spaces
8
  import torch
 
9
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
10
- from typing import Tuple
11
-
12
- css = '''
13
- .gradio-container{max-width: 575px !important}
14
- h1{text-align:center}
15
- footer {
16
- visibility: hidden
17
- }
18
- '''
19
-
20
- DESCRIPTIONXX = """## TEXT 2 IMAGE🥠"""
21
-
22
- examples = [
23
-
24
- "A tiny astronaut hatching from an egg on the moon, 4k, planet theme, --style raw5 --v 6.0",
25
- "An anime-style illustration of a delicious, golden-brown wiener schnitzel on a plate, served with fresh lemon slices, parsley --style raw5",
26
- "Cold coffee in a cup bokeh --ar 85:128 --v 6.0 --style raw5, 4K, Photo-Realistic",
27
- "A cat holding a sign that says hello world --ar 85:128 --v 6.0 --style raw"
28
- ]
29
-
30
- MODEL_OPTIONS = {
31
-
32
- "LIGHTNING V5.0": "SG161222/RealVisXL_V5.0_Lightning",
33
- "LIGHTNING V4.0": "SG161222/RealVisXL_V4.0_Lightning",
34
- }
35
-
36
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
37
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
38
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
39
- BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
40
 
41
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
42
 
43
- style_list = [
44
- {
45
- "name": "3840 x 2160",
46
- "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
47
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
48
- },
49
- {
50
- "name": "2560 x 1440",
51
- "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
52
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
53
- },
54
- {
55
- "name": "HD+",
56
- "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
57
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
58
- },
59
- {
60
- "name": "Style Zero",
61
- "prompt": "{prompt}",
62
- "negative_prompt": "",
63
- },
64
- ]
65
 
66
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
67
- DEFAULT_STYLE_NAME = "3840 x 2160"
68
- STYLE_NAMES = list(styles.keys())
69
-
70
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
71
- if style_name in styles:
72
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
73
- else:
74
- p, n = styles[DEFAULT_STYLE_NAME]
75
-
76
- if not negative:
77
- negative = ""
78
- return p.replace("{prompt}", positive), n + negative
79
-
80
- def load_and_prepare_model(model_id):
81
- pipe = StableDiffusionXLPipeline.from_pretrained(
82
- model_id,
83
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
84
- use_safetensors=True,
85
- add_watermarker=False,
86
- ).to(device)
87
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
88
 
89
- if USE_TORCH_COMPILE:
90
- pipe.compile()
91
 
92
- if ENABLE_CPU_OFFLOAD:
93
- pipe.enable_model_cpu_offload()
94
 
95
- return pipe
96
-
97
- # Preload and compile both models
98
- models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
99
-
100
- MAX_SEED = np.iinfo(np.int32).max
101
 
102
- def save_image(img):
103
- unique_name = str(uuid.uuid4()) + ".png"
104
- img.save(unique_name)
105
- return unique_name
106
-
107
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
108
- if randomize_seed:
109
- seed = random.randint(0, MAX_SEED)
110
- return seed
111
-
112
- @spaces.GPU(duration=60, enable_queue=True)
113
- def generate(
114
- model_choice: str,
115
- prompt: str,
116
- negative_prompt: str = "",
117
- use_negative_prompt: bool = False,
118
- style_selection: str = DEFAULT_STYLE_NAME,
119
- seed: int = 1,
120
- width: int = 1024,
121
- height: int = 1024,
122
- guidance_scale: float = 3,
123
- num_inference_steps: int = 25,
124
- randomize_seed: bool = False,
125
- use_resolution_binning: bool = True,
126
- num_images: int = 1,
127
- progress=gr.Progress(track_tqdm=True),
128
- ):
129
- global models
130
- pipe = models[model_choice]
131
 
132
- seed = int(randomize_seed_fn(seed, randomize_seed))
133
- generator = torch.Generator(device=device).manual_seed(seed)
134
-
135
- prompt, negative_prompt = apply_style(style_selection, prompt, negative_prompt)
136
-
137
- options = {
138
- "prompt": [prompt] * num_images,
139
- "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
140
- "width": width,
141
- "height": height,
142
- "guidance_scale": guidance_scale,
143
- "num_inference_steps": num_inference_steps,
144
- "generator": generator,
145
- "output_type": "pil",
146
- }
147
-
148
- if use_resolution_binning:
149
- options["use_resolution_binning"] = True
150
-
151
- images = []
152
- for i in range(0, num_images, BATCH_SIZE):
153
- batch_options = options.copy()
154
- batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
155
- if "negative_prompt" in batch_options:
156
- batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
157
- images.extend(pipe(**batch_options).images)
158
-
159
- image_paths = [save_image(img) for img in images]
160
- return image_paths, seed
161
-
162
- #def load_predefined_images():
163
- # predefined_images = [
164
- # "assets/1.png",
165
- # "assets/2.png",
166
- # "assets/3.png",
167
- # "assets/4.png",
168
- # "assets/5.png",
169
- # "assets/6.png",
170
- # "assets/7.png",
171
- # "assets/8.png",
172
- # "assets/9.png",
173
- # "assets/10.png",
174
- # "assets/11.png",
175
- # "assets/12.png",
176
- # ]
177
- # return predefined_images
178
-
179
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
180
- gr.Markdown(DESCRIPTIONXX)
181
  with gr.Row():
182
- prompt = gr.Text(
183
- label="Prompt",
184
- show_label=False,
185
- max_lines=1,
186
- placeholder="Enter your prompt",
187
- container=False,
188
- )
189
- run_button = gr.Button("Run", scale=0)
190
- result = gr.Gallery(label="Result", columns=1, show_label=False)
191
-
192
- with gr.Row():
193
- model_choice = gr.Dropdown(
194
- label="Model Selection⬇️",
195
- choices=list(MODEL_OPTIONS.keys()),
196
- value="LIGHTNING V5.0"
197
- )
198
-
199
- with gr.Accordion("Advanced options", open=False, visible=False):
200
- style_selection = gr.Radio(
201
- show_label=True,
202
- container=True,
203
- interactive=True,
204
- choices=STYLE_NAMES,
205
- value=DEFAULT_STYLE_NAME,
206
- label="Quality Style",
207
- )
208
- num_images = gr.Slider(
209
- label="Number of Images",
210
- minimum=1,
211
- maximum=5,
212
- step=1,
213
- value=1,
214
- )
215
- with gr.Row():
216
- with gr.Column(scale=1):
217
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
218
- negative_prompt = gr.Text(
219
- label="Negative prompt",
220
- max_lines=5,
221
- lines=4,
222
- placeholder="Enter a negative prompt",
223
- 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",
224
- visible=True,
225
- )
226
- seed = gr.Slider(
227
- label="Seed",
228
- minimum=0,
229
- maximum=MAX_SEED,
230
- step=1,
231
- value=0,
232
- )
233
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
234
- with gr.Row():
235
- width = gr.Slider(
236
- label="Width",
237
- minimum=512,
238
- maximum=MAX_IMAGE_SIZE,
239
- step=8,
240
- value=1024,
241
- )
242
- height = gr.Slider(
243
- label="Height",
244
- minimum=512,
245
- maximum=MAX_IMAGE_SIZE,
246
- step=8,
247
- value=1024,
248
- )
249
- with gr.Row():
250
- guidance_scale = gr.Slider(
251
- label="Guidance Scale",
252
- minimum=0.1,
253
- maximum=6,
254
- step=0.1,
255
- value=3.0,
256
- )
257
- num_inference_steps = gr.Slider(
258
- label="Number of inference steps",
259
- minimum=1,
260
- maximum=60,
261
- step=1,
262
- value=28,
263
- )
264
-
265
- gr.Examples(
266
- examples=examples,
267
- inputs=prompt,
268
- cache_examples=False
269
- )
270
-
271
- use_negative_prompt.change(
272
- fn=lambda x: gr.update(visible=x),
273
- inputs=use_negative_prompt,
274
- outputs=negative_prompt,
275
- api_name=False,
276
- )
277
-
278
- gr.on(
279
- triggers=[
280
- prompt.submit,
281
- negative_prompt.submit,
282
- run_button.click,
283
- ],
284
- fn=generate,
285
- inputs=[
286
- model_choice,
287
- prompt,
288
- negative_prompt,
289
- use_negative_prompt,
290
- style_selection,
291
- seed,
292
- width,
293
- height,
294
- guidance_scale,
295
- num_inference_steps,
296
- randomize_seed,
297
- num_images,
298
- ],
299
- outputs=[result, seed],
300
- )
301
-
302
-
303
- #gr.Markdown("### Image Gallery")
304
- #predefined_gallery = gr.Gallery(label="Image Gallery", columns=3, show_label=False, value=load_predefined_images())
305
-
306
- gr.Markdown(
307
- """
308
- <div style="text-align: justify;">
309
- 🥠Models used in the playground: <a href="https://huggingface.co/SG161222/RealVisXL_V5.0_Lightning">[LIGHTNING V5.0]</a>, <a href="https://huggingface.co/SG161222/RealVisXL_V4.0_Lightning">[LIGHTNING V4.0]</a>
310
- 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.
311
- </div>
312
- """
313
- )
314
-
315
- gr.Markdown(
316
- """
317
- <div style="text-align: justify;">
318
- 🥠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.
319
- <a href='https://huggingface.co/spaces/prithivMLmods/Top-Prompt-Collection' target='_blank'>Try prompts</a>.
320
- </div>
321
- """)
322
-
323
- gr.Markdown(
324
- """
325
- <div style="text-align: justify;">
326
- ⚠️ Users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.
327
- </div>
328
- """)
329
-
330
  if __name__ == "__main__":
331
- demo.queue(max_size=50).launch(show_api=True)
 
1
  import os
 
2
  import uuid
3
  import gradio as gr
 
 
 
4
  import torch
5
+ from PIL import Image
6
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Configuração do modelo e pipeline
9
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
10
 
11
+ # Carrega o pipeline do modelo
12
+ scheduler = EulerAncestralDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
13
+ pipe = StableDiffusionXLPipeline.from_pretrained(model_id, scheduler=scheduler, torch_dtype=torch.float16)
14
+ pipe.to("cuda") # Usa GPU para acelerar o processamento
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # Função para geração de imagens
17
+ def generate_image(prompt: str, height: int = 576, width: int = 1024, seed: int = None) -> Image.Image:
18
+ if not seed:
19
+ seed = random.randint(0, 99999)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Configurar seed para reprodutibilidade
22
+ generator = torch.manual_seed(seed)
23
 
24
+ # Gerar a imagem
25
+ image = pipe(prompt, height=height, width=width, num_inference_steps=50, guidance_scale=7.5, generator=generator).images[0]
26
 
27
+ # Retorna a imagem gerada
28
+ return image
 
 
 
 
29
 
30
+ # Interface Gradio
31
+ with gr.Blocks() as demo:
32
+ gr.Markdown("## Gerador de Imagens com Stable Diffusion XL")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  with gr.Row():
35
+ with gr.Column():
36
+ prompt = gr.Textbox(label="Texto (Prompt)", placeholder="Descreva a imagem que deseja gerar...")
37
+ seed = gr.Number(label="Seed (opcional)", value=None)
38
+ generate_button = gr.Button("Gerar Imagem")
39
+
40
+ with gr.Column():
41
+ output_image = gr.Image(label="Imagem Gerada", type="pil")
42
+
43
+ # Conectar botão à função
44
+ generate_button.click(fn=generate_image, inputs=[prompt, gr.Number(value=576), gr.Number(value=1024), seed], outputs=output_image)
45
+
46
+ # Executar o app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  if __name__ == "__main__":
48
+ demo.launch(server_name="0.0.0.0", server_port=7860)