ford442 commited on
Commit
d8b0170
·
1 Parent(s): d6e9c0d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +393 -0
app.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers import AutoTokenizer, AutoModelForCausalLM
19
+
20
+
21
+ css = '''
22
+ .gradio-container{max-width: 570px !important}
23
+ h1{text-align:center}
24
+ footer {
25
+ visibility: hidden
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
+ "REALVISXL V5.0 BF16": "ford442/RealVisXL_V5.0_BF16",
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 = "Style Zero"
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
+ model_dtypes = {
90
+ "SG161222/RealVisXL_V5.0": torch.float32,
91
+ "ford442/RealVisXL_V5.0_BF16": torch.bfloat16,
92
+ }
93
+
94
+ # Get the dtype based on the model_id
95
+ dtype = model_dtypes.get(model_id, torch.float32) # Default to float32 if not found
96
+
97
+ # Load the pipeline with the determined dtype
98
+ pipe = StableDiffusionXLPipeline.from_pretrained(
99
+ model_id,
100
+ torch_dtype=dtype if torch.cuda.is_available() else torch.float32,
101
+ use_safetensors=True,
102
+ add_watermarker=False,
103
+ ).to(device)
104
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
105
+
106
+ if USE_TORCH_COMPILE:
107
+ pipe.compile()
108
+
109
+ if ENABLE_CPU_OFFLOAD:
110
+ pipe.enable_model_cpu_offload()
111
+
112
+ return pipe
113
+
114
+ # Preload and compile both models
115
+ models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
116
+
117
+ MAX_SEED = np.iinfo(np.int32).max
118
+
119
+ def save_image(img):
120
+ unique_name = str(uuid.uuid4()) + ".png"
121
+ img.save(unique_name)
122
+ return unique_name
123
+
124
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
125
+ if randomize_seed:
126
+ seed = random.randint(0, MAX_SEED)
127
+ return seed
128
+
129
+ @spaces.GPU(duration=60, enable_queue=True)
130
+ def generate(
131
+ model_choice: str,
132
+ prompt: str,
133
+ negative_prompt: str = "",
134
+ use_negative_prompt: bool = False,
135
+ style_selection: str = DEFAULT_STYLE_NAME,
136
+ seed: int = 1,
137
+ width: int = 768,
138
+ height: int = 768,
139
+ guidance_scale: float = 3,
140
+ num_inference_steps: int = 100,
141
+ randomize_seed: bool = False,
142
+ use_resolution_binning: bool = True,
143
+ num_images: int = 1,
144
+ progress=gr.Progress(track_tqdm=True),
145
+ ):
146
+ global models
147
+ pipe = models[model_choice]
148
+
149
+ seed = int(randomize_seed_fn(seed, randomize_seed))
150
+ generator = torch.Generator(device=device).manual_seed(seed)
151
+
152
+ prompt, negative_prompt = apply_style(style_selection, prompt, negative_prompt)
153
+
154
+ options = {
155
+ "prompt": [prompt] * num_images,
156
+ "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
157
+ "width": width,
158
+ "height": height,
159
+ "guidance_scale": guidance_scale,
160
+ "num_inference_steps": num_inference_steps,
161
+ "generator": generator,
162
+ "output_type": "pil",
163
+ }
164
+
165
+ if use_resolution_binning:
166
+ options["use_resolution_binning"] = True
167
+
168
+ images = []
169
+ for i in range(0, num_images, BATCH_SIZE):
170
+ batch_options = options.copy()
171
+ batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
172
+ if "negative_prompt" in batch_options:
173
+ batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
174
+ images.extend(pipe(**batch_options).images)
175
+
176
+ image_paths = [save_image(img) for img in images]
177
+ return image_paths, seed
178
+
179
+ def load_predefined_images1():
180
+ predefined_images1 = [
181
+ "assets/7.png",
182
+ "assets/8.png",
183
+ "assets/9.png",
184
+ "assets/1.png",
185
+ "assets/2.png",
186
+ "assets/3.png",
187
+ "assets/4.png",
188
+ "assets/5.png",
189
+ "assets/6.png",
190
+ ]
191
+ return predefined_images1
192
+
193
+
194
+ # def load_predefined_images():
195
+ # predefined_images = [
196
+ # "assets2/11.png",
197
+ # "assets2/22.png",
198
+ # "assets2/33.png",
199
+ # "assets2/44.png",
200
+ # "assets2/55.png",
201
+ # "assets2/66.png",
202
+ # "assets2/77.png",
203
+ # "assets2/88.png",
204
+ # "assets2/99.png",
205
+ # ]
206
+ # return predefined_image
207
+
208
+
209
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
210
+ gr.Markdown(DESCRIPTIONXX)
211
+ with gr.Row():
212
+ prompt = gr.Text(
213
+ label="Prompt",
214
+ show_label=False,
215
+ max_lines=1,
216
+ placeholder="Enter your prompt",
217
+ container=False,
218
+ )
219
+ run_button = gr.Button("Run", scale=0)
220
+ result = gr.Gallery(label="Result", columns=1, show_label=False)
221
+
222
+ with gr.Row():
223
+ model_choice = gr.Dropdown(
224
+ label="Model Selection🔻",
225
+ choices=list(MODEL_OPTIONS.keys()),
226
+ value="REALVISXL V5.0"
227
+ )
228
+
229
+ with gr.Accordion("Advanced options", open=False, visible=True):
230
+ style_selection = gr.Radio(
231
+ show_label=True,
232
+ container=True,
233
+ interactive=True,
234
+ choices=STYLE_NAMES,
235
+ value=DEFAULT_STYLE_NAME,
236
+ label="Quality Style",
237
+ )
238
+ num_images = gr.Slider(
239
+ label="Number of Images",
240
+ minimum=1,
241
+ maximum=5,
242
+ step=1,
243
+ value=1,
244
+ )
245
+ with gr.Row():
246
+ with gr.Column(scale=1):
247
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
248
+ negative_prompt = gr.Text(
249
+ label="Negative prompt",
250
+ max_lines=5,
251
+ lines=4,
252
+ placeholder="Enter a negative prompt",
253
+ 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",
254
+ visible=True,
255
+ )
256
+ seed = gr.Slider(
257
+ label="Seed",
258
+ minimum=0,
259
+ maximum=MAX_SEED,
260
+ step=1,
261
+ value=0,
262
+ )
263
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
264
+ with gr.Row():
265
+ width = gr.Slider(
266
+ label="Width",
267
+ minimum=448,
268
+ maximum=MAX_IMAGE_SIZE,
269
+ step=64,
270
+ value=768,
271
+ )
272
+ height = gr.Slider(
273
+ label="Height",
274
+ minimum=448,
275
+ maximum=MAX_IMAGE_SIZE,
276
+ step=64,
277
+ value=768,
278
+ )
279
+ with gr.Row():
280
+ guidance_scale = gr.Slider(
281
+ label="Guidance Scale",
282
+ minimum=0.1,
283
+ maximum=6,
284
+ step=0.1,
285
+ value=3.0,
286
+ )
287
+ num_inference_steps = gr.Slider(
288
+ label="Number of inference steps",
289
+ minimum=10,
290
+ maximum=200,
291
+ step=10,
292
+ value=100,
293
+ )
294
+
295
+ gr.Examples(
296
+ examples=examples,
297
+ inputs=prompt,
298
+ cache_examples=False
299
+ )
300
+
301
+ use_negative_prompt.change(
302
+ fn=lambda x: gr.update(visible=x),
303
+ inputs=use_negative_prompt,
304
+ outputs=negative_prompt,
305
+ api_name=False,
306
+ )
307
+
308
+ gr.on(
309
+ triggers=[
310
+ prompt.submit,
311
+ negative_prompt.submit,
312
+ run_button.click,
313
+ ],
314
+ fn=generate,
315
+ inputs=[
316
+ model_choice,
317
+ prompt,
318
+ negative_prompt,
319
+ use_negative_prompt,
320
+ style_selection,
321
+ seed,
322
+ width,
323
+ height,
324
+ guidance_scale,
325
+ num_inference_steps,
326
+ randomize_seed,
327
+ num_images,
328
+ ],
329
+ outputs=[result, seed],
330
+ )
331
+
332
+ gr.Markdown("### REALVISXL V5.0")
333
+ predefined_gallery = gr.Gallery(label="REALVISXL V5.0", columns=3, show_label=False, value=load_predefined_images1())
334
+
335
+ #gr.Markdown("### LIGHTNING V5.0")
336
+ #predefined_gallery = gr.Gallery(label="LIGHTNING V5.0", columns=3, show_label=False, value=load_predefined_images())
337
+
338
+ gr.Markdown(
339
+ """
340
+ <div style="text-align: justify;">
341
+ ⚡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.
342
+ </div>
343
+ """)
344
+
345
+ gr.Markdown(
346
+ """
347
+ <div style="text-align: justify;">
348
+ ⚡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.
349
+ <a href='https://huggingface.co/spaces/prithivMLmods/Top-Prompt-Collection' target='_blank'>Try prompts</a>.
350
+ </div>
351
+ """)
352
+
353
+ gr.Markdown(
354
+ """
355
+ <div style="text-align: justify;">
356
+ ⚠️ Users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.
357
+ </div>
358
+ """)
359
+
360
+ tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
361
+ model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
362
+
363
+ def text_generation(input_text, seed):
364
+ full_prompt = f"""
365
+ Create a detailed and descriptive scene setting for an image based on the following prompt: {input_text}
366
+ Your scene:
367
+ """
368
+ input_ids = tokenizer(full_prompt, return_tensors="pt").input_ids
369
+ torch.manual_seed(seed)
370
+ outputs = model.generate(input_ids, do_sample=True, min_length=100, max_length=300)
371
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
372
+ return generated_text
373
+
374
+ title = "Text Generator Demo GPT-Neo"
375
+ description = "Text Generator Application by ecarbo"
376
+
377
+ if __name__ == "__main__":
378
+ demo_interface = demo.queue(max_size=50) # Remove .launch() here
379
+
380
+ text_gen_interface = gr.Interface(
381
+ fn=text_generation,
382
+ inputs=[
383
+ gr.Textbox(lines=1, label="Expand the following prompt to be more detailed and descriptive for image generation: "),
384
+ gr.Number(value=10, label="Enter seed number")
385
+ ],
386
+ outputs=gr.Textbox(label="Text Generated"),
387
+ title=title,
388
+ description=description,
389
+ theme="huggingface"
390
+ )
391
+
392
+ combined_interface = gr.TabbedInterface([demo_interface, text_gen_interface], ["Image Generation", "Text Generation"])
393
+ combined_interface.launch(show_api=False)