prithivMLmods commited on
Commit
dddc860
·
verified ·
1 Parent(s): 4cf566d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -293
app.py CHANGED
@@ -1,295 +1,3 @@
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 StableCascadeDecoderPipeline, StableCascadePriorPipeline
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 may not work on CPU.</p>"
31
-
32
- USE_TORCH_COMPILE = 0
33
- ENABLE_CPU_OFFLOAD = 1 # Enable CPU offloading to reduce GPU memory usage
34
-
35
- style_list = [
36
- {
37
- "name": "3840 x 2160",
38
- "prompt": "hyper-realistic 8K image of {prompt} . ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
39
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
40
- },
41
- {
42
- "name": "2560 × 1440",
43
- "prompt": "hyper-realistic 4K image of {prompt} . ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
44
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
45
- },
46
- {
47
- "name": "HDR",
48
- "prompt": "HDR photo of {prompt} . high dynamic range, vivid colors, sharp contrast, realistic, detailed, high resolution, professional",
49
- "negative_prompt": "dull, low contrast, blurry, unrealistic, cartoonish, ugly, deformed",
50
- },
51
- {
52
- "name": "Cinematic",
53
- "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
54
- "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
55
- },
56
- {
57
- "name": "Photo",
58
- "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
59
- "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
60
- },
61
- {
62
- "name": "Anime",
63
- "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed",
64
- "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
65
- },
66
- {
67
- "name": "Manga",
68
- "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style",
69
- "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style",
70
- },
71
- {
72
- "name": "Digital",
73
- "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed",
74
- "negative_prompt": "photo, photorealistic, realism, ugly",
75
- },
76
- {
77
- "name": "3D Model",
78
- "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting",
79
- "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
80
- },
81
- {
82
- "name": "(No style)",
83
- "prompt": "{prompt}",
84
- "negative_prompt": "",
85
- },
86
- ]
87
-
88
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
89
- STYLE_NAMES = list(styles.keys())
90
- DEFAULT_STYLE_NAME = "3840 x 2160"
91
-
92
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
93
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
94
- return p.replace("{prompt}", positive), n + negative
95
-
96
- # Initialize models once during setup
97
- prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", variant="bf16", torch_dtype=torch.bfloat16)
98
- decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", variant="bf16", torch_dtype=torch.float16)
99
-
100
- if ENABLE_CPU_OFFLOAD:
101
- prior.enable_model_cpu_offload()
102
- decoder.enable_model_cpu_offload()
103
- else:
104
- device = "cuda" if torch.cuda.is_available() else "cpu"
105
- prior.to(device)
106
- decoder.to(device)
107
- print("Loaded on Device!")
108
-
109
- @spaces.GPU(enable_queue=True)
110
- def stab(
111
- prompt: str,
112
- negative_prompt: str = "",
113
- style: str = DEFAULT_STYLE_NAME,
114
- use_negative_prompt: bool = False,
115
- num_inference_steps: int = 40,
116
- num_images_per_prompt: int = 2,
117
- seed: int = 0,
118
- width: int = 1024,
119
- height: int = 1024,
120
- guidance_scale: float = 6,
121
- randomize_seed: bool = False,
122
- progress=gr.Progress(track_tqdm=True),
123
- ):
124
- seed = int(randomize_seed_fn(seed, randomize_seed))
125
-
126
- if not use_negative_prompt:
127
- negative_prompt = ""
128
- prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
129
-
130
- prior_output = prior(
131
- prompt=prompt,
132
- height=height,
133
- width=width,
134
- negative_prompt=negative_prompt,
135
- guidance_scale=guidance_scale,
136
- num_images_per_prompt=num_images_per_prompt,
137
- num_inference_steps=num_inference_steps
138
- )
139
-
140
- images = decoder(
141
- image_embeddings=prior_output.image_embeddings.to(torch.float16),
142
- prompt=prompt,
143
- negative_prompt=negative_prompt,
144
- guidance_scale=0.0,
145
- output_type="pil",
146
- num_inference_steps=10
147
- ).images
148
-
149
- image_paths = [save_image(img) for img in images]
150
- print(image_paths)
151
- return image_paths, seed
152
-
153
- examples = [
154
- "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)",
155
- "(Pirate ship sailing into a bioluminescence sea with a galaxy in the sky), epic, 4k, ultra, the space scene with planets and stars, in the style of ethereal escapism, richly colored skies, vibrant worlds --ar 8:5",
156
- "Thin burger, realistic photo (without tomato or any other ingredient), smoky flavor, 4K resolution highlights every texture, providing an incredible and appetizing visual experience",
157
- "A galaxy with blue water, a red star and many planets in one view, in the style of digital fantasy nebulae and cosmos, light black and violet, realistic nebulae paintings, james paick, steve henderson, ue5, cosmic horror --ar 8:5",
158
- "A dark night sky with thick, dense clouds and stars in the background. The main focus is on one of these large cloud formations that has been stylized to resemble an ancient dragon. There's no moon or other celestial bodies visible in the sky. This scene conveys mystery and magic, with the dark blue glow from distant galaxies adding depth and contrast to the night landscape. --ar 8:5 --v 5.2 --style raw"
159
- ]
160
-
161
- css = '''
162
- .gradio-container{max-width: 560px !important}
163
- h1{text-align:center}
164
- footer {
165
- visibility: hidden
166
- }
167
- '''
168
-
169
- with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") as demo:
170
- gr.Markdown(DESCRIPTION)
171
- gr.DuplicateButton(
172
- value="Duplicate Space for private use",
173
- elem_id="duplicate-button",
174
- visible=False,
175
- )
176
-
177
- with gr.Group():
178
- with gr.Row():
179
- prompt = gr.Textbox(
180
- label="Prompt",
181
- show_label=False,
182
- max_lines=1,
183
- placeholder="Enter your prompt",
184
- container=False,
185
- )
186
- run_button = gr.Button("Run")
187
- result = gr.Gallery(label="Result", columns=1, preview=True)
188
- with gr.Accordion("Advanced options", open=False):
189
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True, visible=True)
190
- negative_prompt = gr.Textbox(
191
- label="Negative prompt",
192
- max_lines=1,
193
- placeholder="Enter a negative prompt",
194
- 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",
195
- visible=True,
196
- )
197
- with gr.Row():
198
- num_inference_steps = gr.Slider(
199
- label="Steps",
200
- minimum=10,
201
- maximum=60,
202
- step=1,
203
- value=40,
204
- )
205
- with gr.Row():
206
- num_images_per_prompt = gr.Slider(
207
- label="Images",
208
- minimum=1,
209
- maximum=5,
210
- step=1,
211
- value=2,
212
- )
213
- seed = gr.Slider(
214
- label="Seed",
215
- minimum=0,
216
- maximum=MAX_SEED,
217
- step=1,
218
- value=0,
219
- visible=True
220
- )
221
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
222
- with gr.Row(visible=True):
223
- width = gr.Slider(
224
- label="Width",
225
- minimum=512,
226
- maximum=2048,
227
- step=8,
228
- value=1024,
229
- )
230
- height = gr.Slider(
231
- label="Height",
232
- minimum=512,
233
- maximum=2048,
234
- step=8,
235
- value=1024,
236
- )
237
- with gr.Row():
238
- guidance_scale = gr.Slider(
239
- label="Guidance Scale",
240
- minimum=0.1,
241
- maximum=20.0,
242
- step=0.1,
243
- value=6,
244
- )
245
- with gr.Row(visible=True):
246
- style_selection = gr.Radio(
247
- show_label=True,
248
- container=True,
249
- interactive=True,
250
- choices=STYLE_NAMES,
251
- value=DEFAULT_STYLE_NAME,
252
- label="Styler",
253
- )
254
-
255
- gr.Examples(
256
- examples=examples,
257
- inputs=prompt,
258
- outputs=[result, seed],
259
- fn=stab,
260
- cache_examples=False,
261
- )
262
-
263
- use_negative_prompt.change(
264
- fn=lambda x: gr.update(visible=x),
265
- inputs=use_negative_prompt,
266
- outputs=negative_prompt,
267
- api_name=False,
268
- )
269
-
270
- gr.on(
271
- triggers=[
272
- prompt.submit,
273
- negative_prompt.submit,
274
- run_button.click,
275
- ],
276
- fn=stab,
277
- inputs=[
278
- prompt,
279
- negative_prompt,
280
- style_selection,
281
- use_negative_prompt,
282
- num_inference_steps,
283
- num_images_per_prompt,
284
- seed,
285
- width,
286
- height,
287
- guidance_scale,
288
- randomize_seed,
289
- ],
290
- outputs=[result, seed],
291
- api_name="run",
292
- )
293
 
294
- if __name__ == "__main__":
295
- demo.queue(max_size=20).launch(show_api=False, debug=False, share=True)
 
 
 
1
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ exec(os.environ.get('dalle-like-stabilityai-model'))