prithivMLmods commited on
Commit
687ac39
·
verified ·
1 Parent(s): 2759bfd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +255 -0
app.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import uuid
4
+ from typing import Tuple
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
+
12
+ DESCRIPTIONz= """## LoRA SD 🙀
13
+ """
14
+
15
+ def save_image(img):
16
+ unique_name = str(uuid.uuid4()) + ".png"
17
+ img.save(unique_name)
18
+ return unique_name
19
+
20
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
21
+ if randomize_seed:
22
+ seed = random.randint(0, MAX_SEED)
23
+ return seed
24
+
25
+ MAX_SEED = np.iinfo(np.int32).max
26
+
27
+ if not torch.cuda.is_available():
28
+ DESCRIPTIONz += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
29
+
30
+ USE_TORCH_COMPILE = 0
31
+ ENABLE_CPU_OFFLOAD = 0
32
+
33
+ if torch.cuda.is_available():
34
+ pipe = StableDiffusionXLPipeline.from_pretrained(
35
+ "SG161222/RealVisXL_V4.0_Lightning",
36
+ torch_dtype=torch.float16,
37
+ use_safetensors=True,
38
+ )
39
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
40
+
41
+ LORA_OPTIONS = {
42
+ "Realism": ("prithivMLmods/Canopus-Realism-LoRA", "Canopus-Realism-LoRA.safetensors", "rlms"),
43
+ "PIXAR": ("prithivMLmods/Canopus-Pixar-Art", "Canopus-Pixar-Art.safetensors", "pixar"),
44
+ "PhotoShoot": ("prithivMLmods/Canopus-Photo-Shoot-Mini-LoRA", "Canopus-Photo-Shoot-Mini-LoRA.safetensors", "photo"),
45
+ "Interior Architecture": ("prithivMLmods/Canopus-Interior-Architecture-0.1", "Canopus-Interior-Architecture-0.1δ.safetensors", "arch"),
46
+ "Fashion Product": ("prithivMLmods/Canopus-Fashion-Product-Dilation", "Canopus-Fashion-Product-Dilation.safetensors", "fashion"),
47
+ }
48
+
49
+ for model_name, weight_name, adapter_name in LORA_OPTIONS.values():
50
+ pipe.load_lora_weights(model_name, weight_name=weight_name, adapter_name=adapter_name)
51
+ pipe.to("cuda")
52
+
53
+ style_list = [
54
+ {
55
+ "name": "3840 x 2160",
56
+ "prompt": "hyper-realistic 8K 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": "2560 x 1440",
61
+ "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
62
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
63
+ },
64
+ {
65
+ "name": "HD+",
66
+ "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
67
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
68
+ },
69
+ {
70
+ "name": "Style Zero",
71
+ "prompt": "{prompt}",
72
+ "negative_prompt": "",
73
+ },
74
+ ]
75
+
76
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
77
+
78
+ DEFAULT_STYLE_NAME = "3840 x 2160"
79
+ STYLE_NAMES = list(styles.keys())
80
+
81
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
82
+ if style_name in styles:
83
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
84
+ else:
85
+ p, n = styles[DEFAULT_STYLE_NAME]
86
+
87
+ if not negative:
88
+ negative = ""
89
+ return p.replace("{prompt}", positive), n + negative
90
+
91
+ @spaces.GPU(duration=60, enable_queue=True)
92
+ def generate(
93
+ prompt: str,
94
+ negative_prompt: str = "",
95
+ use_negative_prompt: bool = False,
96
+ seed: int = 0,
97
+ width: int = 1024,
98
+ height: int = 1024,
99
+ guidance_scale: float = 3,
100
+ randomize_seed: bool = False,
101
+ style_name: str = DEFAULT_STYLE_NAME,
102
+ lora_model: str = "Realism",
103
+ progress=gr.Progress(track_tqdm=True),
104
+ ):
105
+ seed = int(randomize_seed_fn(seed, randomize_seed))
106
+
107
+ positive_prompt, effective_negative_prompt = apply_style(style_name, prompt, negative_prompt)
108
+
109
+ if not use_negative_prompt:
110
+ effective_negative_prompt = "" # type: ignore
111
+
112
+ model_name, weight_name, adapter_name = LORA_OPTIONS[lora_model]
113
+ pipe.set_adapters(adapter_name)
114
+
115
+ images = pipe(
116
+ prompt=positive_prompt,
117
+ negative_prompt=effective_negative_prompt,
118
+ width=width,
119
+ height=height,
120
+ guidance_scale=guidance_scale,
121
+ num_inference_steps=20,
122
+ num_images_per_prompt=1,
123
+ cross_attention_kwargs={"scale": 0.65},
124
+ output_type="pil",
125
+ ).images
126
+ image_paths = [save_image(img) for img in images]
127
+ return image_paths, seed
128
+
129
+ examples = [
130
+ "A man in ski mask, in the style of smokey background, androgynous, imaginative prison scenes, light indigo and black, close-up, michelangelo, street-savvy --ar 125:187 --v 5.1 --style raw",
131
+ "Photography, front view, dynamic range, female model, upper-body, black T-shirt, dark khaki cargo pants, urban backdrop, dusk, dramatic sunlights, bokeh, cityscape, photorealism, natural, UHD --ar 9:16 --stylize 300"
132
+ ]
133
+
134
+ css = '''
135
+ .gradio-container{max-width: 545px !important}
136
+ h1{text-align:center}
137
+ footer {
138
+ visibility: hidden
139
+ }
140
+ '''
141
+
142
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
143
+ gr.Markdown(DESCRIPTIONz)
144
+ with gr.Group():
145
+ with gr.Row():
146
+ prompt = gr.Text(
147
+ label="Prompt",
148
+ show_label=False,
149
+ max_lines=1,
150
+ placeholder="Enter your prompt with realism tag!",
151
+ container=False,
152
+ )
153
+ run_button = gr.Button("Run", scale=0)
154
+ result = gr.Gallery(label="Result", columns=1, preview=True, show_label=False)
155
+
156
+ with gr.Accordion("Advanced options", open=False, visible=False):
157
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
158
+ negative_prompt = gr.Text(
159
+ label="Negative prompt",
160
+ lines=4,
161
+ max_lines=6,
162
+ 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",
163
+ placeholder="Enter a negative prompt",
164
+ visible=True,
165
+ )
166
+ seed = gr.Slider(
167
+ label="Seed",
168
+ minimum=0,
169
+ maximum=MAX_SEED,
170
+ step=1,
171
+ value=0,
172
+ visible=True
173
+ )
174
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
175
+
176
+ with gr.Row(visible=True):
177
+ width = gr.Slider(
178
+ label="Width",
179
+ minimum=512,
180
+ maximum=2048,
181
+ step=8,
182
+ value=1024,
183
+ )
184
+ height = gr.Slider(
185
+ label="Height",
186
+ minimum=512,
187
+ maximum=2048,
188
+ step=8,
189
+ value=1024,
190
+ )
191
+
192
+ with gr.Row():
193
+ guidance_scale = gr.Slider(
194
+ label="Guidance Scale",
195
+ minimum=0.1,
196
+ maximum=20.0,
197
+ step=0.1,
198
+ value=3.0,
199
+ )
200
+
201
+ style_selection = gr.Radio(
202
+ show_label=True,
203
+ container=True,
204
+ interactive=True,
205
+ choices=STYLE_NAMES,
206
+ value=DEFAULT_STYLE_NAME,
207
+ label="Quality Style",
208
+ )
209
+
210
+ model_choice = gr.Dropdown(
211
+ label="LoRA Selection",
212
+ choices=list(LORA_OPTIONS.keys()),
213
+ value="Realism"
214
+ )
215
+
216
+ gr.Examples(
217
+ examples=examples,
218
+ inputs=prompt,
219
+ outputs=[result, seed],
220
+ fn=generate,
221
+ cache_examples=False,
222
+ )
223
+
224
+ use_negative_prompt.change(
225
+ fn=lambda x: gr.update(visible=x),
226
+ inputs=use_negative_prompt,
227
+ outputs=negative_prompt,
228
+ api_name=False,
229
+ )
230
+
231
+ gr.on(
232
+ triggers=[
233
+ prompt.submit,
234
+ negative_prompt.submit,
235
+ run_button.click,
236
+ ],
237
+ fn=generate,
238
+ inputs=[
239
+ prompt,
240
+ negative_prompt,
241
+ use_negative_prompt,
242
+ seed,
243
+ width,
244
+ height,
245
+ guidance_scale,
246
+ randomize_seed,
247
+ style_selection,
248
+ model_choice,
249
+ ],
250
+ outputs=[result, seed],
251
+ api_name="run",
252
+ )
253
+
254
+ if __name__ == "__main__":
255
+ demo.queue(max_size=30).launch()