prithivMLmods commited on
Commit
85221d2
1 Parent(s): 0a43e8b

Create file.txt

Browse files
Files changed (1) hide show
  1. last-commit/file.txt +274 -0
last-commit/file.txt ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
8
+ import spaces
9
+ import torch
10
+ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
+
12
+ DESCRIPTIONx = """
13
+
14
+ ## TEXT-2-IMG SDXL
15
+
16
+ """
17
+
18
+ css = '''
19
+ .gradio-container{max-width: 690px !important}
20
+ h1{text-align:center}
21
+ footer {
22
+ visibility: hidden
23
+ }
24
+ '''
25
+
26
+
27
+ js_func = """
28
+ function refresh() {
29
+ const url = new URL(window.location);
30
+ if (url.searchParams.get('__theme') !== 'dark') {
31
+ url.searchParams.set('__theme', 'dark');
32
+ window.location.href = url.href;
33
+ }
34
+ }
35
+ """
36
+
37
+
38
+ examples = [
39
+ "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)",
40
+ "Chocolate dripping from a donut against a yellow background, in the style of brocore, hyper-realistic oil --ar 2:3 --q 2 --s 750 --v 5 --ar 2:3 --q 2 --s 750 --v 5",
41
+ "Illustration of A starry night camp in the mountains. Low-angle view, Minimal background, Geometric shapes theme, Pottery, Split-complementary colors, Bicolored light, UHD",
42
+ "Man in brown leather jacket posing for camera, in the style of sleek and stylized, clockpunk, subtle shades, exacting precision, ferrania p30 --ar 67:101 --v 5",
43
+ "Commercial photography, giant burger, white lighting, studio light, 8k octane rendering, high resolution photography, insanely detailed, fine details, on white isolated plain, 8k, commercial photography, stock photo, professional color grading, --v 4 --ar 9:16 "
44
+ ]
45
+
46
+ MODEL_OPTIONS = {
47
+ "Hyper Realism : V4.0_Lightning": "SG161222/RealVisXL_V4.0_Lightning",
48
+ "Deep Realism : RealVisv4_XL": "SG161222/RealVisXL_V4.0",
49
+ }
50
+
51
+ MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
52
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
53
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
54
+ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
55
+
56
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
57
+
58
+ def load_and_prepare_model(model_id):
59
+ pipe = StableDiffusionXLPipeline.from_pretrained(
60
+ model_id,
61
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
62
+ use_safetensors=True,
63
+ add_watermarker=False,
64
+ ).to(device)
65
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
66
+
67
+ if USE_TORCH_COMPILE:
68
+ pipe.compile()
69
+
70
+ if ENABLE_CPU_OFFLOAD:
71
+ pipe.enable_model_cpu_offload()
72
+
73
+ return pipe
74
+
75
+ # Preload and compile both models
76
+ models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
77
+
78
+ MAX_SEED = np.iinfo(np.int32).max
79
+
80
+ def save_image(img):
81
+ unique_name = str(uuid.uuid4()) + ".png"
82
+ img.save(unique_name)
83
+ return unique_name
84
+
85
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
86
+ if randomize_seed:
87
+ seed = random.randint(0, MAX_SEED)
88
+ return seed
89
+
90
+ @spaces.GPU(duration=60, enable_queue=True)
91
+ def generate(
92
+ model_choice: str,
93
+ prompt: str,
94
+ negative_prompt: str = "",
95
+ use_negative_prompt: bool = False,
96
+ seed: int = 1,
97
+ width: int = 1024,
98
+ height: int = 1024,
99
+ guidance_scale: float = 3,
100
+ num_inference_steps: int = 25,
101
+ randomize_seed: bool = False,
102
+ use_resolution_binning: bool = True,
103
+ num_images: int = 1,
104
+ progress=gr.Progress(track_tqdm=True),
105
+ ):
106
+ global models
107
+ pipe = models[model_choice]
108
+
109
+ seed = int(randomize_seed_fn(seed, randomize_seed))
110
+ generator = torch.Generator(device=device).manual_seed(seed)
111
+
112
+ options = {
113
+ "prompt": [prompt] * num_images,
114
+ "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
115
+ "width": width,
116
+ "height": height,
117
+ "guidance_scale": guidance_scale,
118
+ "num_inference_steps": num_inference_steps,
119
+ "generator": generator,
120
+ "output_type": "pil",
121
+ }
122
+
123
+ if use_resolution_binning:
124
+ options["use_resolution_binning"] = True
125
+
126
+ images = []
127
+ for i in range(0, num_images, BATCH_SIZE):
128
+ batch_options = options.copy()
129
+ batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
130
+ if "negative_prompt" in batch_options:
131
+ batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
132
+ images.extend(pipe(**batch_options).images)
133
+
134
+ image_paths = [save_image(img) for img in images]
135
+ return image_paths, seed
136
+
137
+ def load_predefined_images():
138
+ predefined_images = [
139
+ "assets/1.png",
140
+ "assets/2.png",
141
+ "assets/3.png",
142
+ "assets/4.png",
143
+ "assets/5.png",
144
+ "assets/6.png",
145
+ "assets/7.png",
146
+ "assets/8.png",
147
+ "assets/9.png",
148
+ "assets/10.png",
149
+ "assets/11.png",
150
+ "assets/12.png",
151
+ ]
152
+ return predefined_images
153
+
154
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme", js=js_func) as demo:
155
+ gr.Markdown(DESCRIPTIONx)
156
+ with gr.Row():
157
+ prompt = gr.Text(
158
+ label="Prompt",
159
+ show_label=False,
160
+ max_lines=1,
161
+ placeholder="Enter your prompt",
162
+ container=False,
163
+ )
164
+ run_button = gr.Button("Run⚡", scale=0)
165
+ result = gr.Gallery(label="Result", columns=1, show_label=False)
166
+
167
+ with gr.Row():
168
+ model_choice = gr.Dropdown(
169
+ label="Model Selection",
170
+ choices=list(MODEL_OPTIONS.keys()),
171
+ value="Hyper Realism : V4.0_Lightning"
172
+ )
173
+
174
+ with gr.Accordion("Advanced options", open=True):
175
+ num_images = gr.Slider(
176
+ label="Number of Images",
177
+ minimum=1,
178
+ maximum=1,
179
+ step=1,
180
+ value=1,
181
+ )
182
+ with gr.Row():
183
+ with gr.Column(scale=1):
184
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
185
+ negative_prompt = gr.Text(
186
+ label="Negative prompt",
187
+ max_lines=5,
188
+ lines=4,
189
+ placeholder="Enter a negative prompt",
190
+ 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",
191
+ visible=True,
192
+ )
193
+ seed = gr.Slider(
194
+ label="Seed",
195
+ minimum=0,
196
+ maximum=MAX_SEED,
197
+ step=1,
198
+ value=0,
199
+ )
200
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
201
+ with gr.Row():
202
+ width = gr.Slider(
203
+ label="Width",
204
+ minimum=512,
205
+ maximum=MAX_IMAGE_SIZE,
206
+ step=64,
207
+ value=1024,
208
+ )
209
+ height = gr.Slider(
210
+ label="Height",
211
+ minimum=512,
212
+ maximum=MAX_IMAGE_SIZE,
213
+ step=64,
214
+ value=1024,
215
+ )
216
+ with gr.Row():
217
+ guidance_scale = gr.Slider(
218
+ label="Guidance Scale",
219
+ minimum=0.1,
220
+ maximum=6,
221
+ step=0.1,
222
+ value=3.0,
223
+ )
224
+ num_inference_steps = gr.Slider(
225
+ label="Number of inference steps",
226
+ minimum=1,
227
+ maximum=35,
228
+ step=1,
229
+ value=20,
230
+ )
231
+
232
+ gr.Examples(
233
+ examples=examples,
234
+ inputs=prompt,
235
+ cache_examples=False
236
+ )
237
+
238
+ use_negative_prompt.change(
239
+ fn=lambda x: gr.update(visible=x),
240
+ inputs=use_negative_prompt,
241
+ outputs=negative_prompt,
242
+ api_name=False,
243
+ )
244
+
245
+ gr.on(
246
+ triggers=[
247
+ prompt.submit,
248
+ negative_prompt.submit,
249
+ run_button.click,
250
+ ],
251
+ fn=generate,
252
+ inputs=[
253
+ model_choice,
254
+ prompt,
255
+ negative_prompt,
256
+ use_negative_prompt,
257
+ seed,
258
+ width,
259
+ height,
260
+ guidance_scale,
261
+ num_inference_steps,
262
+ randomize_seed,
263
+ num_images
264
+ ],
265
+ outputs=[result, seed],
266
+ api_name="run",
267
+ )
268
+
269
+ with gr.Column(scale=3):
270
+ gr.Markdown("### Image Gallery")
271
+ predefined_gallery = gr.Gallery(label="Image Gallery", columns=4, show_label=False, value=load_predefined_images())
272
+
273
+ if __name__ == "__main__":
274
+ demo.queue(max_size=40).launch(show_api=False)