1inkusFace commited on
Commit
2662f4d
·
verified ·
1 Parent(s): 67c4653

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +412 -0
app.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import numpy as np
4
+ import random
5
+
6
+ import torch
7
+ from diffusers import StableDiffusion3Pipeline
8
+ #from transformers import CLIPTextModelWithProjection, T5EncoderModel
9
+ from transformers import CLIPTokenizer, T5TokenizerFast
10
+
11
+ import re
12
+ import paramiko
13
+ import urllib
14
+ import time
15
+ import os
16
+ from image_gen_aux import UpscaleWithModel
17
+ from huggingface_hub import hf_hub_download
18
+ import datetime
19
+ import cyper
20
+
21
+ #from diffusers import SD3Transformer2DModel, AutoencoderKL
22
+ #from models.transformer_sd3 import SD3Transformer2DModel
23
+ #from pipeline_stable_diffusion_3_ipa import StableDiffusion3Pipeline
24
+
25
+ from PIL import Image
26
+
27
+ torch.backends.cuda.matmul.allow_tf32 = False
28
+ torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False
29
+ torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
30
+ torch.backends.cudnn.allow_tf32 = False
31
+ torch.backends.cudnn.deterministic = False
32
+ torch.backends.cudnn.benchmark = False
33
+ #torch.backends.cuda.preferred_blas_library="cublas"
34
+ #torch.backends.cuda.preferred_linalg_library="cusolver"
35
+
36
+ hftoken = os.getenv("HF_AUTH_TOKEN")
37
+
38
+ code = r'''
39
+ import torch
40
+ import paramiko
41
+ import os
42
+ FTP_HOST = '1ink.us'
43
+ FTP_USER = 'ford442'
44
+ FTP_PASS = os.getenv("FTP_PASS")
45
+ FTP_DIR = '1ink.us/stable_diff'
46
+
47
+ def upload_to_ftp(filename):
48
+ try:
49
+ transport = paramiko.Transport((FTP_HOST, 22))
50
+ destination_path=FTP_DIR+filename
51
+ transport.connect(username = FTP_USER, password = FTP_PASS)
52
+ sftp = paramiko.SFTPClient.from_transport(transport)
53
+ sftp.put(filename, destination_path)
54
+ sftp.close()
55
+ transport.close()
56
+ print(f"Uploaded {filename} to FTP server")
57
+ except Exception as e:
58
+ print(f"FTP upload error: {e}")
59
+ '''
60
+
61
+ pyx = cyper.inline(code, fast_indexing=True, directives=dict(boundscheck=False, wraparound=False, language_level=3))
62
+
63
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
64
+
65
+ pipe = StableDiffusion3Pipeline.from_pretrained(
66
+ #"stabilityai # stable-diffusion-3.5-large",
67
+ "ford442/stable-diffusion-3.5-large-bf16",
68
+ # vae=AutoencoderKL.from_pretrained("ford442/stable-diffusion-3.5-large-fp32", use_safetensors=True, subfolder='vae',token=True),
69
+ #scheduler = FlowMatchHeunDiscreteScheduler.from_pretrained('ford442/stable-diffusion-3.5-large-bf16', subfolder='scheduler',token=True),
70
+ # text_encoder=CLIPTextModelWithProjection.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", subfolder='text_encoder', token=True),
71
+ # text_encoder_2=CLIPTextModelWithProjection.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", subfolder='text_encoder_2',token=True),
72
+ # text_encoder_3=T5EncoderModel.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", subfolder='text_encoder_3',token=True),
73
+ #tokenizer=CLIPTokenizer.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", add_prefix_space=True, subfolder="tokenizer", token=True),
74
+ #tokenizer_2=CLIPTokenizer.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", add_prefix_space=True, subfolder="tokenizer_2", token=True),
75
+ tokenizer_3=T5TokenizerFast.from_pretrained("ford442/stable-diffusion-3.5-large-bf16", add_prefix_space=False, use_fast=True, subfolder="tokenizer_3", token=True),
76
+ #torch_dtype=torch.bfloat16,
77
+ #use_safetensors=False,
78
+ )
79
+ pipe.load_lora_weights("ford442/sdxl-vae-bf16", weight_name="LoRA/UltraReal.safetensors")
80
+ pipe.to(device=device, dtype=torch.bfloat16)
81
+ #pipe.to(device)
82
+
83
+ upscaler_2 = UpscaleWithModel.from_pretrained("Kim2091/ClearRealityV1").to(torch.device('cpu'))
84
+
85
+ MAX_SEED = np.iinfo(np.int32).max
86
+
87
+ MAX_IMAGE_SIZE = 4096
88
+
89
+ @spaces.GPU(duration=40)
90
+ def infer_30(
91
+ prompt,
92
+ negative_prompt_1,
93
+ negative_prompt_2,
94
+ negative_prompt_3,
95
+ width,
96
+ height,
97
+ guidance_scale,
98
+ num_inference_steps,
99
+ progress=gr.Progress(track_tqdm=True),
100
+ ):
101
+ torch.set_float32_matmul_precision("highest")
102
+ seed = random.randint(0, MAX_SEED)
103
+ generator = torch.Generator(device='cuda').manual_seed(seed)
104
+ print('-- generating image --')
105
+ sd_image = pipe(
106
+ prompt=prompt,
107
+ prompt_2=prompt,
108
+ prompt_3=prompt,
109
+ negative_prompt=negative_prompt_1,
110
+ negative_prompt_2=negative_prompt_2,
111
+ negative_prompt_3=negative_prompt_3,
112
+ guidance_scale=guidance_scale,
113
+ num_inference_steps=num_inference_steps,
114
+ width=width,
115
+ height=height,
116
+ # cross_attention_kwargs={"scale": 0.75},
117
+ generator=generator,
118
+ max_sequence_length=512
119
+ ).images[0]
120
+ print('-- got image --')
121
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
122
+ sd35_path = f"sd35ll_{timestamp}.png"
123
+ sd_image.save(sd35_path,optimize=False,compress_level=0)
124
+ pyx.upload_to_ftp(sd35_path)
125
+ # pipe.unet.to('cpu')
126
+ upscaler_2.to(torch.device('cuda'))
127
+ with torch.no_grad():
128
+ upscale2 = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
129
+ print('-- got upscaled image --')
130
+ downscale2 = upscale2.resize((upscale2.width // 4, upscale2.height // 4),Image.LANCZOS)
131
+ upscale_path = f"sd35ll_upscale_{timestamp}.png"
132
+ downscale2.save(upscale_path,optimize=False,compress_level=0)
133
+ pyx.upload_to_ftp(upscale_path)
134
+ return sd_image, prompt
135
+
136
+ @spaces.GPU(duration=70)
137
+ def infer_60(
138
+ prompt,
139
+ negative_prompt_1,
140
+ negative_prompt_2,
141
+ negative_prompt_3,
142
+ width,
143
+ height,
144
+ guidance_scale,
145
+ num_inference_steps,
146
+ progress=gr.Progress(track_tqdm=True),
147
+ ):
148
+ torch.set_float32_matmul_precision("highest")
149
+ seed = random.randint(0, MAX_SEED)
150
+ generator = torch.Generator(device='cuda').manual_seed(seed)
151
+ print('-- generating image --')
152
+ sd_image = pipe(
153
+ prompt=prompt,
154
+ prompt_2=prompt,
155
+ prompt_3=prompt,
156
+ negative_prompt=negative_prompt_1,
157
+ negative_prompt_2=negative_prompt_2,
158
+ negative_prompt_3=negative_prompt_3,
159
+ guidance_scale=guidance_scale,
160
+ num_inference_steps=num_inference_steps,
161
+ width=width,
162
+ height=height,
163
+ generator=generator,
164
+ max_sequence_length=512
165
+ ).images[0]
166
+ print('-- got image --')
167
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
168
+ sd35_path = f"sd35ll_{timestamp}.png"
169
+ sd_image.save(sd35_path,optimize=False,compress_level=0)
170
+ pyx.upload_to_ftp(sd35_path)
171
+ # pipe.unet.to('cpu')
172
+ upscaler_2.to(torch.device('cuda'))
173
+ with torch.no_grad():
174
+ upscale2 = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
175
+ print('-- got upscaled image --')
176
+ downscale2 = upscale2.resize((upscale2.width // 4, upscale2.height // 4),Image.LANCZOS)
177
+ upscale_path = f"sd35ll_upscale_{timestamp}.png"
178
+ downscale2.save(upscale_path,optimize=False,compress_level=0)
179
+ pyx.upload_to_ftp(upscale_path)
180
+ return sd_image, prompt
181
+
182
+ @spaces.GPU(duration=100)
183
+ def infer_90(
184
+ prompt,
185
+ negative_prompt_1,
186
+ negative_prompt_2,
187
+ negative_prompt_3,
188
+ width,
189
+ height,
190
+ guidance_scale,
191
+ num_inference_steps,
192
+ progress=gr.Progress(track_tqdm=True),
193
+ ):
194
+ torch.set_float32_matmul_precision("highest")
195
+ seed = random.randint(0, MAX_SEED)
196
+ generator = torch.Generator(device='cuda').manual_seed(seed)
197
+ print('-- generating image --')
198
+ sd_image = pipe(
199
+ prompt=prompt,
200
+ prompt_2=prompt,
201
+ prompt_3=prompt,
202
+ negative_prompt=negative_prompt_1,
203
+ negative_prompt_2=negative_prompt_2,
204
+ negative_prompt_3=negative_prompt_3,
205
+ guidance_scale=guidance_scale,
206
+ num_inference_steps=num_inference_steps,
207
+ width=width,
208
+ height=height,
209
+ generator=generator,
210
+ max_sequence_length=512
211
+ ).images[0]
212
+ print('-- got image --')
213
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
214
+ sd35_path = f"sd35ll_{timestamp}.png"
215
+ sd_image.save(sd35_path,optimize=False,compress_level=0)
216
+ pyx.upload_to_ftp(sd35_path)
217
+ # pipe.unet.to('cpu')
218
+ upscaler_2.to(torch.device('cuda'))
219
+ with torch.no_grad():
220
+ upscale2 = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
221
+ print('-- got upscaled image --')
222
+ downscale2 = upscale2.resize((upscale2.width // 4, upscale2.height // 4),Image.LANCZOS)
223
+ upscale_path = f"sd35ll_upscale_{timestamp}.png"
224
+ downscale2.save(upscale_path,optimize=False,compress_level=0)
225
+ pyx.upload_to_ftp(upscale_path)
226
+ return sd_image, prompt
227
+
228
+ @spaces.GPU(duration=110)
229
+ def infer_100(
230
+ prompt,
231
+ negative_prompt_1,
232
+ negative_prompt_2,
233
+ negative_prompt_3,
234
+ width,
235
+ height,
236
+ guidance_scale,
237
+ num_inference_steps,
238
+ progress=gr.Progress(track_tqdm=True),
239
+ ):
240
+ torch.set_float32_matmul_precision("highest")
241
+ seed = random.randint(0, MAX_SEED)
242
+ generator = torch.Generator(device='cuda').manual_seed(seed)
243
+ print('-- generating image --')
244
+ sd_image = pipe(
245
+ prompt=prompt,
246
+ prompt_2=prompt,
247
+ prompt_3=prompt,
248
+ negative_prompt=negative_prompt_1,
249
+ negative_prompt_2=negative_prompt_2,
250
+ negative_prompt_3=negative_prompt_3,
251
+ guidance_scale=guidance_scale,
252
+ num_inference_steps=num_inference_steps,
253
+ width=width,
254
+ height=height,
255
+ generator=generator,
256
+ max_sequence_length=512
257
+ ).images[0]
258
+ print('-- got image --')
259
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
260
+ sd35_path = f"sd35ll_{timestamp}.png"
261
+ sd_image.save(sd35_path,optimize=False,compress_level=0)
262
+ pyx.upload_to_ftp(sd35_path)
263
+ # pipe.unet.to('cpu')
264
+ upscaler_2.to(torch.device('cuda'))
265
+ with torch.no_grad():
266
+ upscale2 = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
267
+ print('-- got upscaled image --')
268
+ downscale2 = upscale2.resize((upscale2.width // 4, upscale2.height // 4),Image.LANCZOS)
269
+ upscale_path = f"sd35ll_upscale_{timestamp}.png"
270
+ downscale2.save(upscale_path,optimize=False,compress_level=0)
271
+ pyx.upload_to_ftp(upscale_path)
272
+ return sd_image, prompt
273
+
274
+ css = """
275
+ #col-container {margin: 0 auto;max-width: 640px;}
276
+ body{background-color: blue;}
277
+ """
278
+
279
+ with gr.Blocks(theme=gr.themes.Origin(),css=css) as demo:
280
+ with gr.Column(elem_id="col-container"):
281
+ gr.Markdown(" # Text-to-Image StableDiffusion 3.5 Large")
282
+ expanded_prompt_output = gr.Textbox(label="Prompt", lines=1) # Add this line
283
+ with gr.Row():
284
+ prompt = gr.Text(
285
+ label="Prompt",
286
+ show_label=False,
287
+ max_lines=1,
288
+ placeholder="Enter your prompt",
289
+ container=False,
290
+ )
291
+ run_button_30 = gr.Button("Run 30", scale=0, variant="primary")
292
+ run_button_60 = gr.Button("Run 60", scale=0, variant="primary")
293
+ run_button_90 = gr.Button("Run 90", scale=0, variant="primary")
294
+ run_button_100 = gr.Button("Run 100", scale=0, variant="primary")
295
+ result = gr.Image(label="Result", show_label=False)
296
+ with gr.Accordion("Advanced Settings", open=True):
297
+ negative_prompt_1 = gr.Text(
298
+ label="Negative prompt 1",
299
+ max_lines=1,
300
+ placeholder="Enter a negative prompt",
301
+ visible=True,
302
+ value="bad anatomy, poorly drawn hands, distorted face, blurry, out of frame, low resolution, grainy, pixelated, disfigured, mutated, extra limbs, bad composition"
303
+ )
304
+ negative_prompt_2 = gr.Text(
305
+ label="Negative prompt 2",
306
+ max_lines=1,
307
+ placeholder="Enter a second negative prompt",
308
+ visible=True,
309
+ value="unrealistic, cartoon, anime, sketch, painting, drawing, illustration, graphic, digital art, render, 3d, blurry, deformed, disfigured, poorly drawn, bad anatomy, mutated, extra limbs, ugly, out of frame, bad composition, low resolution, grainy, pixelated, noisy, oversaturated, undersaturated, (worst quality, low quality:1.3), (bad hands, missing fingers:1.2)"
310
+ )
311
+ negative_prompt_3 = gr.Text(
312
+ label="Negative prompt 3",
313
+ max_lines=1,
314
+ placeholder="Enter a third negative prompt",
315
+ visible=True,
316
+ value="(worst quality, low quality:1.3), (bad anatomy, bad hands, missing fingers, extra digit, fewer digits:1.2), (blurry:1.1), cropped, watermark, text, signature, logo, jpeg artifacts, (ugly, deformed, disfigured:1.2), (poorly drawn:1.2), mutated, extra limbs, (bad proportions, gross proportions:1.2), (malformed limbs, missing arms, missing legs, extra arms, extra legs:1.2), (fused fingers, too many fingers, long neck:1.2), (unnatural body, unnatural pose:1.1), out of frame, (bad composition, poorly composed:1.1), (oversaturated, undersaturated:1.1), (grainy, pixelated:1.1), (low resolution, noisy:1.1), (unrealistic, distorted:1.1), (extra fingers, mutated hands, poorly drawn hands, bad hands:1.3), (missing fingers:1.3)"
317
+ )
318
+ num_iterations = gr.Number(
319
+ value=1000,
320
+ label="Number of Iterations")
321
+ with gr.Row():
322
+ width = gr.Slider(
323
+ label="Width",
324
+ minimum=256,
325
+ maximum=MAX_IMAGE_SIZE,
326
+ step=32,
327
+ value=768,
328
+ )
329
+ height = gr.Slider(
330
+ label="Height",
331
+ minimum=256,
332
+ maximum=MAX_IMAGE_SIZE,
333
+ step=32,
334
+ value=768,
335
+ )
336
+ guidance_scale = gr.Slider(
337
+ label="Guidance scale",
338
+ minimum=0.0,
339
+ maximum=30.0,
340
+ step=0.1,
341
+ value=4.2,
342
+ )
343
+ num_inference_steps = gr.Slider(
344
+ label="Number of inference steps",
345
+ minimum=1,
346
+ maximum=500,
347
+ step=1,
348
+ value=50,
349
+ )
350
+ gr.on(
351
+ triggers=[run_button_30.click, prompt.submit],
352
+ fn=infer_30,
353
+ inputs=[
354
+ prompt,
355
+ negative_prompt_1,
356
+ negative_prompt_2,
357
+ negative_prompt_3,
358
+ width,
359
+ height,
360
+ guidance_scale,
361
+ num_inference_steps,
362
+ ],
363
+ outputs=[result, expanded_prompt_output],
364
+ )
365
+ gr.on(
366
+ triggers=[run_button_60.click, prompt.submit],
367
+ fn=infer_60,
368
+ inputs=[
369
+ prompt,
370
+ negative_prompt_1,
371
+ negative_prompt_2,
372
+ negative_prompt_3,
373
+ width,
374
+ height,
375
+ guidance_scale,
376
+ num_inference_steps,
377
+ ],
378
+ outputs=[result, expanded_prompt_output],
379
+ )
380
+ gr.on(
381
+ triggers=[run_button_90.click, prompt.submit],
382
+ fn=infer_90,
383
+ inputs=[
384
+ prompt,
385
+ negative_prompt_1,
386
+ negative_prompt_2,
387
+ negative_prompt_3,
388
+ width,
389
+ height,
390
+ guidance_scale,
391
+ num_inference_steps,
392
+ ],
393
+ outputs=[result, expanded_prompt_output],
394
+ )
395
+ gr.on(
396
+ triggers=[run_button_100.click, prompt.submit],
397
+ fn=infer_100,
398
+ inputs=[
399
+ prompt,
400
+ negative_prompt_1,
401
+ negative_prompt_2,
402
+ negative_prompt_3,
403
+ width,
404
+ height,
405
+ guidance_scale,
406
+ num_inference_steps,
407
+ ],
408
+ outputs=[result, expanded_prompt_output],
409
+ )
410
+
411
+ if __name__ == "__main__":
412
+ demo.launch()