File size: 37,439 Bytes
81bd15c
 
 
 
 
 
 
 
 
 
 
 
 
 
3e69253
81bd15c
96c7fb7
75a802d
688e85a
 
74dd986
ff20737
 
 
74dd986
81bd15c
 
 
 
 
9381de4
84dd386
81bd15c
c3029a6
aebf4d2
81bd15c
 
 
 
 
 
f8b8c3b
 
 
 
 
 
 
 
 
 
81bd15c
f8b8c3b
 
 
 
 
 
 
 
 
 
81bd15c
f8b8c3b
 
 
 
 
81bd15c
7813cdf
 
96c7fb7
7813cdf
 
8fb74d6
 
 
 
7813cdf
 
 
66c976a
81bd15c
2012398
81bd15c
 
320e40a
81bd15c
56f2c0e
 
 
 
 
 
 
 
 
 
 
 
2012398
320e40a
81bd15c
66c976a
81bd15c
2012398
81bd15c
 
 
 
 
 
 
 
 
 
2012398
81bd15c
 
83a80d8
 
 
 
 
 
 
e887663
22d45a3
83a80d8
 
 
 
 
4fe413f
83a80d8
 
 
 
 
 
 
 
 
 
 
32468cd
da86870
 
7c4ec71
da86870
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
 
 
3142592
da86870
ba43c72
 
 
 
da86870
 
3142592
da86870
 
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
da86870
 
ba43c72
 
7c4ec71
 
ba43c72
 
 
 
 
 
bb54994
7c4ec71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3142592
 
83a80d8
4fe413f
2012398
3142592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bd15c
 
79919d7
3142592
d4b6d48
 
 
 
 
3142592
79919d7
 
 
 
 
 
 
 
 
 
 
 
 
 
83a80d8
22d45a3
 
 
706e01a
81bd15c
 
 
 
 
 
 
 
 
 
d459b6a
81bd15c
 
 
 
d459b6a
81bd15c
 
e887663
81bd15c
93e1d77
 
 
 
 
 
 
 
 
 
 
 
 
 
2299926
0879b61
 
 
 
 
2299926
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3142592
2299926
 
 
bb54994
 
 
 
2299926
 
 
7029aa9
2299926
81bd15c
2012398
a282bf5
 
83a80d8
81bd15c
 
 
 
 
 
 
 
563e3d9
81bd15c
 
 
 
 
 
 
 
 
83a80d8
81bd15c
 
 
83a80d8
81bd15c
 
5353cec
2012398
81bd15c
83a80d8
81bd15c
3142592
 
 
 
79919d7
3142592
7e93de4
 
 
81bd15c
 
 
 
 
 
 
 
 
 
 
 
 
 
15fc37d
 
706e01a
0879b61
81bd15c
427d179
 
3dd58cf
427d179
 
66c976a
3142592
81bd15c
15fc37d
81bd15c
 
 
 
427d179
 
79919d7
7029aa9
 
81bd15c
 
 
 
 
 
911fb02
7813cdf
15fc37d
 
 
7e93de4
15fc37d
 
 
 
320e40a
 
57363eb
427d179
79919d7
 
478d0c1
ba43c72
59dedb4
320e40a
 
ea2ddb8
320e40a
7953a14
320e40a
 
 
 
 
 
 
 
79919d7
 
 
 
 
 
 
320e40a
 
 
 
 
 
 
 
427d179
320e40a
4f1d55c
2012398
320e40a
 
7c4ec71
320e40a
 
4b2a1af
320e40a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fe413f
 
 
 
 
 
 
 
320e40a
 
4fe413f
320e40a
 
478d0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da86870
 
478d0c1
 
 
 
 
 
 
 
 
 
 
79919d7
 
478d0c1
 
 
 
d128830
478d0c1
 
 
 
 
 
 
 
da86870
478d0c1
 
 
 
 
 
 
 
da86870
 
478d0c1
 
 
 
79919d7
 
478d0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da86870
 
478d0c1
 
a14ce71
478d0c1
 
81bd15c
 
8fb74d6
 
 
 
 
 
 
320e40a
 
8fb74d6
 
 
 
 
 
 
 
 
 
 
 
 
7813cdf
 
 
 
 
 
8fb74d6
ef92c97
7813cdf
 
 
8fb74d6
83a80d8
8fb74d6
 
 
 
e887663
22d45a3
8fb74d6
 
 
 
 
4fe413f
8fb74d6
 
 
 
 
 
 
 
 
 
 
32468cd
7e93de4
 
8fb74d6
15fc37d
8fb74d6
320e40a
7813cdf
3142592
 
 
8fb74d6
7e93de4
 
8fb74d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83a80d8
 
8fb74d6
 
 
 
 
 
 
 
 
911fb02
66c976a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
import os

import gradio as gr
from gradio_imageslider import ImageSlider
import argparse
from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype
import numpy as np
import torch
from SUPIR.util import create_SUPIR_model, load_QF_ckpt
from PIL import Image
from llava.llava_agent import LLavaAgent
from CKPT_PTH import LLAVA_MODEL_PATH
import einops
import copy
import math
import time
import random
import spaces
from huggingface_hub import hf_hub_download

hf_hub_download(repo_id="laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", filename="open_clip_pytorch_model.bin", local_dir="laion_CLIP-ViT-bigG-14-laion2B-39B-b160k")
hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")

parser = argparse.ArgumentParser()
parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
parser.add_argument("--ip", type=str, default='127.0.0.1')
parser.add_argument("--port", type=int, default='6688')
parser.add_argument("--no_llava", action='store_true', default=True)#False
parser.add_argument("--use_image_slider", action='store_true', default=False)#False
parser.add_argument("--log_history", action='store_true', default=False)
parser.add_argument("--loading_half_params", action='store_true', default=False)#False
parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
parser.add_argument("--encoder_tile_size", type=int, default=512)
parser.add_argument("--decoder_tile_size", type=int, default=64)
parser.add_argument("--load_8bit_llava", action='store_true', default=False)
args = parser.parse_args()
use_llava = not args.no_llava

if torch.cuda.device_count() > 0:
    if torch.cuda.device_count() >= 2:
        SUPIR_device = 'cuda:0'
        LLaVA_device = 'cuda:1'
    elif torch.cuda.device_count() == 1:
        SUPIR_device = 'cuda:0'
        LLaVA_device = 'cuda:0'
    else:
        SUPIR_device = 'cpu'
        LLaVA_device = 'cpu'

    # load SUPIR
    model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
    if args.loading_half_params:
        model = model.half()
    if args.use_tile_vae:
        model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
    model = model.to(SUPIR_device)
    model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
    model.current_model = 'v0-Q'
    ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)

    # load LLaVA
    if use_llava:
        llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)
    else:
        llava_agent = None

def update_seed(is_randomize_seed, seed):
    if is_randomize_seed:
        return random.randint(0, 2147483647)
    return seed

def check(input_image):
    if input_image is None:
        raise gr.Error("Please provide an image to restore.")

def reset_feedback():
    return 3, ''

@spaces.GPU(duration=540)
def stage1_process(input_image, gamma_correction):
    print('stage1_process ==>>')
    if torch.cuda.device_count() == 0:
        gr.Warning('Set this space to GPU config to make it work.')
        return None, None
    torch.cuda.set_device(SUPIR_device)
    LQ = HWC3(input_image)
    LQ = fix_resize(LQ, 512)
    # stage1
    LQ = np.array(LQ) / 255 * 2 - 1
    LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
    LQ = model.batchify_denoise(LQ, is_stage1=True)
    LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
    # gamma correction
    LQ = LQ / 255.0
    LQ = np.power(LQ, gamma_correction)
    LQ *= 255.0
    LQ = LQ.round().clip(0, 255).astype(np.uint8)
    print('<<== stage1_process')
    return LQ, gr.update(visible = True)

@spaces.GPU(duration=540)
def llave_process(input_image, temperature, top_p, qs=None):
    print('llave_process ==>>')
    if torch.cuda.device_count() == 0:
        gr.Warning('Set this space to GPU config to make it work.')
        return 'Set this space to GPU config to make it work.'
    torch.cuda.set_device(LLaVA_device)
    if use_llava:
        LQ = HWC3(input_image)
        LQ = Image.fromarray(LQ.astype('uint8'))
        captions = llava_agent.gen_image_caption([LQ], temperature=temperature, top_p=top_p, qs=qs)
    else:
        captions = ['LLaVA is not available. Please add text manually.']
    print('<<== llave_process')
    return captions[0]

def stage2_process(
    noisy_image,
    denoise_image,
    prompt,
    a_prompt,
    n_prompt,
    num_samples,
    min_size,
    downscale,
    upscale,
    edm_steps,
    s_stage1,
    s_stage2,
    s_cfg,
    randomize_seed,
    seed,
    s_churn,
    s_noise,
    color_fix_type,
    diff_dtype,
    ae_dtype,
    gamma_correction,
    linear_CFG,
    linear_s_stage2,
    spt_linear_CFG,
    spt_linear_s_stage2,
    model_select,
    output_format,
    allocation
):
    if allocation == 1:
        return restore_in_1min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 2:
        return restore_in_2min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 3:
        return restore_in_3min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 4:
        return restore_in_4min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 5:
        return restore_in_5min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 7:
        return restore_in_7min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 8:
        return restore_in_8min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 9:
        return restore_in_9min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    if allocation == 10:
        return restore_in_10min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )
    else:
        return restore_in_6min(
            noisy_image, denoise_image, prompt, a_prompt, n_prompt, num_samples, min_size, downscale, upscale, edm_steps, s_stage1, s_stage2, s_cfg, randomize_seed, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select, output_format, allocation
        )

@spaces.GPU(duration=60)
def restore_in_1min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=120)
def restore_in_2min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=180)
def restore_in_3min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=240)
def restore_in_4min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=300)
def restore_in_5min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=360)
def restore_in_6min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=420)
def restore_in_7min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=480)
def restore_in_8min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=540)
def restore_in_9min(*args, **kwargs):
    return restore(*args, **kwargs)

@spaces.GPU(duration=599)
def restore_in_10min(*args, **kwargs):
    return restore(*args, **kwargs)

def restore(
    noisy_image,
    denoise_image,
    prompt,
    a_prompt,
    n_prompt,
    num_samples,
    min_size,
    downscale,
    upscale,
    edm_steps,
    s_stage1,
    s_stage2,
    s_cfg,
    randomize_seed,
    seed,
    s_churn,
    s_noise,
    color_fix_type,
    diff_dtype,
    ae_dtype,
    gamma_correction,
    linear_CFG,
    linear_s_stage2,
    spt_linear_CFG,
    spt_linear_s_stage2,
    model_select,
    output_format,
    allocation
):
    start = time.time()
    print('stage2_process ==>>')
    print("noisy_image: " + str(noisy_image))
    print("denoise_image: " + str(denoise_image))
    print("prompt: " + str(prompt))
    print("a_prompt: " + str(a_prompt))
    print("n_prompt: " + str(n_prompt))
    print("num_samples: " + str(num_samples))
    print("min_size: " + str(min_size))
    print("downscale: " + str(downscale))
    print("upscale: " + str(upscale))
    print("edm_steps: " + str(edm_steps))
    print("s_stage1: " + str(s_stage1))
    print("s_stage2: " + str(s_stage2))
    print("s_cfg: " + str(s_cfg))
    print("randomize_seed: " + str(randomize_seed))
    print("seed: " + str(seed))
    print("s_churn: " + str(s_churn))
    print("s_noise: " + str(s_noise))
    print("color_fix_type: " + str(color_fix_type))
    print("diff_dtype: " + str(diff_dtype))
    print("ae_dtype: " + str(ae_dtype))
    print("gamma_correction: " + str(gamma_correction))
    print("linear_CFG: " + str(linear_CFG))
    print("linear_s_stage2: " + str(linear_s_stage2))
    print("spt_linear_CFG: " + str(spt_linear_CFG))
    print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
    print("model_select: " + str(model_select))
    print("output_format: " + str(output_format))
    print("GPU time allocation: " + str(allocation) + " min")

    if torch.cuda.device_count() == 0:
        gr.Warning('Set this space to GPU config to make it work.')
        return [noisy_image] * 2, [noisy_image] * 2, None, None

    if output_format == "input":
        if noisy_image is None:
            output_format = "png"
        else:
            output_format = noisy_image.format

    if prompt is None:
        prompt = ""

    if a_prompt is None:
        a_prompt = ""

    if n_prompt is None:
        n_prompt = ""

    if prompt != "" and a_prompt != "":
        a_prompt = prompt + ", " + a_prompt
    else:
        a_prompt = prompt + a_prompt
    print("Final prompt: " + str(a_prompt))
    input_image = noisy_image if denoise_image is None else denoise_image
    if 1 < downscale:
        input_height, input_width, input_channel = np.array(input_image).shape
        input_image = input_image.resize((input_width // downscale, input_height // downscale), Image.LANCZOS)
    torch.cuda.set_device(SUPIR_device)
    event_id = str(time.time_ns())
    event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt,
                  'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps,
                  's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn,
                  's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype,
                  'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2,
                  'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2,
                  'model_select': model_select}

    if model_select != model.current_model:
        print('load ' + model_select)
        if model_select == 'v0-Q':
            model.load_state_dict(ckpt_Q, strict=False)
        elif model_select == 'v0-F':
            model.load_state_dict(ckpt_F, strict=False)
        model.current_model = model_select
    input_image = HWC3(input_image)
    input_image = upscale_image(input_image, upscale, unit_resolution=32,
                                min_size=min_size)

    LQ = np.array(input_image) / 255.0
    LQ = np.power(LQ, gamma_correction)
    LQ *= 255.0
    LQ = LQ.round().clip(0, 255).astype(np.uint8)
    LQ = LQ / 255 * 2 - 1
    LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
    if use_llava:
        captions = [prompt]
    else:
        captions = ['']

    model.ae_dtype = convert_dtype(ae_dtype)
    model.model.dtype = convert_dtype(diff_dtype)

    samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
                                    s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
                                    num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
                                    use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
                                    cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)

    x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
        0, 255).astype(np.uint8)
    results = [x_samples[i] for i in range(num_samples)]

    if args.log_history:
        os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True)
        with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
            f.write(str(event_dict))
        f.close()
        Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png')
        for i, result in enumerate(results):
            Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png')

    # All the results have the same size
    result_height, result_width, result_channel = np.array(results[0]).shape

    print('<<== stage2_process')
    end = time.time()
    secondes = int(end - start)
    minutes = math.floor(secondes / 60)
    secondes = secondes - (minutes * 60)
    hours = math.floor(minutes / 60)
    minutes = minutes - (hours * 60)
    information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
    "Wait " + str(allocation) + " min before a new run to avoid time penalty. " + \
    "The image(s) has(ve) been generated in " + \
    ((str(hours) + " h, ") if hours != 0 else "") + \
    ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
    str(secondes) + " sec. " + \
    "The new image resolution is " + str(result_width) + \
    " pixels large and " + str(result_height) + \
    " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
    print(information)

    # Only one image can be shown in the slider
    return [noisy_image] + [results[0]], gr.update(format = output_format, value = [noisy_image] + results), gr.update(value = information, visible = True), event_id

def load_and_reset(param_setting):
    print('load_and_reset ==>>')
    if torch.cuda.device_count() == 0:
        gr.Warning('Set this space to GPU config to make it work.')
        return None, None, None, None, None, None, None, None, None, None, None, None, None, None
    edm_steps = default_setting.edm_steps
    s_stage2 = 1.0
    s_stage1 = -1.0
    s_churn = 5
    s_noise = 1.003
    a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
               'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
               'detailing, hyper sharpness, perfect without deformations.'
    n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
               '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
               'signature, jpeg artifacts, deformed, lowres, over-smooth'
    color_fix_type = 'Wavelet'
    spt_linear_s_stage2 = 0.0
    linear_s_stage2 = False
    linear_CFG = True
    if param_setting == "Quality":
        s_cfg = default_setting.s_cfg_Quality
        spt_linear_CFG = default_setting.spt_linear_CFG_Quality
        model_select = "v0-Q"
    elif param_setting == "Fidelity":
        s_cfg = default_setting.s_cfg_Fidelity
        spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
        model_select = "v0-F"
    else:
        raise NotImplementedError
    gr.Info('The parameters are reset.')
    print('<<== load_and_reset')
    return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
        linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select

def log_information(result_gallery):
    print('log_information')
    if result_gallery is not None:
        for i, result in enumerate(result_gallery):
            print(result[0])

def on_select_result(result_gallery, evt: gr.SelectData):
    print('on_select_result')
    return [result_gallery[0][0], result_gallery[evt.index][0]]

def submit_feedback(event_id, fb_score, fb_text):
    if args.log_history:
        with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f:
            event_dict = eval(f.read())
        f.close()
        event_dict['feedback'] = {'score': fb_score, 'text': fb_text}
        with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
            f.write(str(event_dict))
        f.close()
        return 'Submit successfully, thank you for your comments!'
    else:
        return 'Submit failed, the server is not set to log history.'

title_html = """
    <h1><center>SUPIR</center></h1>
    <big><center>Upscale your images up to x8 freely, without account, without watermark and download it</center></big>
    <center><big><big>🤸<big><big><big><big><big><big>🤸</big></big></big></big></big></big></big></big></center>
    
    <p>This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
    It is still a research project under tested and is not yet a stable commercial product.
    The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
    The aim of SUPIR is the beauty and the illustration.
    Most of the processes only last few minutes.
    This demo can handle huge images but the process will be aborted if it lasts more than 9 min.
    Please leave a message in discussion if you encounter issues.
    
    <p><center><a href="https://arxiv.org/abs/2401.13627">Paper</a> &emsp; <a href="http://supir.xpixel.group/">Project Page</a> &emsp; <a href="https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png">How to play</a> &emsp; <a href="https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai">Local Install Guide</a></center></p>
    """


claim_md = """
## **Piracy**
The images are not stored but the logs are saved during a month.
## **How to get SUPIR**
You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
## **Terms of use**
By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please submit a feedback to us if you get any inappropriate answer! We will collect those to keep improving our models. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
## **License**
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/Fanghua-Yu/SUPIR) of SUPIR.
"""

# Gradio interface
with gr.Blocks(title="SUPIR") as interface:
    if torch.cuda.device_count() == 0:
        with gr.Row():
            gr.HTML("""
    <p style="background-color: red;"><big><big><big><b>⚠️To use SUPIR, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
    
    You can't use SUPIR directly here because this space runs on a CPU, which is not enough for SUPIR. This is a template space. Please provide feedback if you have issues.
    </big></big></big></p>
    """)
    gr.HTML(title_html)

    input_image = gr.Image(label="Input", show_label=True, type="numpy", height=600, elem_id="image-input")
    with gr.Group():
        prompt = gr.Textbox(label="Image description", info="Help the AI understand what the image represents; describe as much as possible; I advise you to write in English as other languages may not be handled", value="", placeholder="A person, walking, in a town, Summer, photorealistic", lines=3)
        prompt_hint = gr.HTML("You can use a <a href='"'https://huggingface.co/spaces/MaziyarPanahi/llava-llama-3-8b'"'>LlaVa space</a> to auto-generate the description of your image.")
        upscale = gr.Radio([["x1", 1], ["x2", 2], ["x3", 3], ["x4", 4], ["x5", 5], ["x6", 6], ["x7", 7], ["x8", 8]], label="Upscale factor", info="Resolution x1 to x8", value=2, interactive=True)
        allocation = gr.Radio([["1 min", 1], ["2 min", 2], ["3 min", 3], ["4 min", 4], ["5 min", 5], ["6 min", 6], ["7 min", 7], ["8 min", 8], ["9 min", 9], ["10 min (may fail)", 10]], label="GPU allocation time", info="lower=May abort run, higher=Time penalty for next runs", value=6, interactive=True)
        output_format = gr.Radio([["*.png", "png"], ["*.webp", "webp"], ["*.jpeg", "jpeg"], ["*.gif", "gif"], ["*.bmp", "bmp"]], label="Image format for result", info="File extention", value="png", interactive=True)

    with gr.Accordion("Pre-denoising (optional)", open=False):
        gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
        denoise_button = gr.Button(value="Pre-denoise")
        denoise_image = gr.Image(label="Denoised image", show_label=True, type="numpy", sources=[], height=600, elem_id="image-s1")
        denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)

    with gr.Accordion("LLaVA options", open=False, visible=False):
        temperature = gr.Slider(label="Temperature", info = "lower=Always similar, higher=More creative", minimum=0., maximum=1.0, value=0.2, step=0.1)
        top_p = gr.Slider(label="Top P", info = "Percent of tokens shortlisted", minimum=0., maximum=1.0, value=0.7, step=0.1)
        qs = gr.Textbox(label="Question", info="Ask LLaVa what description you want", value="Describe the image and its style in a very detailed manner. The image is a realistic photography, not an art painting.", lines=3)

    with gr.Accordion("Advanced options", open=False):
        a_prompt = gr.Textbox(label="Additional image description",
                              info="Completes the main image description",
                              value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
                                    'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
                                    'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, '
                                    'hyper sharpness, perfect without deformations.',
                              lines=3)
        n_prompt = gr.Textbox(label="Anti image description",
                              info="Disambiguate by listing what the image does NOT represent",
                              value='painting, oil painting, illustration, drawing, art, sketch, anime, '
                                    'cartoon, CG Style, 3D render, unreal engine, blurring, bokeh, ugly, dirty, messy, '
                                    'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
                                    'deformed, lowres, over-smooth',
                              lines=3)
        edm_steps = gr.Slider(label="Steps", info="lower=faster, higher=more details", minimum=1, maximum=200, value=default_setting.edm_steps if torch.cuda.device_count() > 0 else 1, step=1)
        num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
                                , value=1, step=1)
        min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
        downscale = gr.Radio([["/1", 1], ["/2", 2], ["/3", 3], ["/4", 4], ["/5", 5], ["/6", 6], ["/7", 7], ["/8", 8]], label="Pre-downscale factor", info="Reducing blurred image reduce the process time", value=1, interactive=True)
        with gr.Row():
            with gr.Column():
                model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q",
                                        interactive=True)
            with gr.Column():
                color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", info="AdaIn=Improve following a style, Wavelet=For JPEG artifacts", value="Wavelet",
                                          interactive=True)
        s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
                          value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
        s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
        s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
        s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
        s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
        with gr.Row():
            with gr.Column():
                linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
                spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
                                                maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
            with gr.Column():
                linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
                spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
                                                maximum=1., value=0., step=0.05)
            with gr.Column():
                diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16",
                                      interactive=True)
            with gr.Column():
                ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16",
                                    interactive=True)
        randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
        seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, randomize=True)
        with gr.Group():
            param_setting = gr.Radio(["Quality", "Fidelity"], interactive=True, label="Presetting", value="Quality")
            restart_button = gr.Button(value="Apply presetting")

    with gr.Group():
        llave_button = gr.Button(value="Generate description by LlaVa (disabled)", visible=False)

        diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id="process_button")

        restore_information = gr.HTML(value="Restart the process to get another result.", visible=False)
        result_slider = ImageSlider(label='Output', show_label=True, elem_id="slider1")
        result_gallery = gr.Gallery(label='Output', show_label=True, elem_id="gallery1")

    with gr.Accordion("Feedback", open=True, visible=False):
        fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1, interactive=True)
        fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.')
        submit_button = gr.Button(value="Submit Feedback")
        event_id = gr.Textbox(label="Event ID", value="", visible=False)

    gr.Examples(
        fn = stage2_process,
	    inputs = [
            input_image,
            denoise_image,
            prompt,
            a_prompt,
            n_prompt,
            num_samples,
            min_size,
            downscale,
            upscale,
            edm_steps,
            s_stage1,
            s_stage2,
            s_cfg,
            randomize_seed,
            seed,
            s_churn,
            s_noise,
            color_fix_type,
            diff_dtype,
            ae_dtype,
            gamma_correction,
            linear_CFG,
            linear_s_stage2,
            spt_linear_CFG,
            spt_linear_s_stage2,
            model_select,
            output_format,
            allocation
        ],
	    outputs = [
            result_slider,
            result_gallery,
            restore_information,
            event_id
        ],
        examples = [
                [
                    "./Examples/Example1.png",
                    None,
                    "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
                    "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.",
                    "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
                    1,
                    1024,
                    1,
                    8,
                    200,
                    -1,
                    1,
                    7.5,
                    False,
                    42,
                    5,
                    1.003,
                    "AdaIn",
                    "fp16",
                    "bf16",
                    1.0,
                    True,
                    4,
                    False,
                    0.,
                    "v0-Q",
                    "png",
                    6
                ],
                [
                    "./Examples/Example2.jpeg",
                    None,
                    "The head of a tabby cat, in a house, photorealistic, 8k, extremely detailled",
                    "Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore detailing, hyper sharpness, perfect without deformations.",
                    "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, bokeh, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
                    1,
                    1024,
                    1,
                    1,
                    200,
                    -1,
                    1,
                    7.5,
                    False,
                    42,
                    5,
                    1.003,
                    "Wavelet",
                    "fp16",
                    "bf16",
                    1.0,
                    True,
                    4,
                    False,
                    0.,
                    "v0-Q",
                    "png",
                    6
                ],
            ],
        cache_examples = False,
    )

    with gr.Row():
        gr.Markdown(claim_md)
    
    denoise_button.click(fn = check, inputs = [
        input_image
    ], outputs = [], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
        input_image,
        gamma_correction
    ], outputs=[
        denoise_image,
        denoise_information
    ])

    llave_button.click(fn = check, inputs = [
        denoise_image
    ], outputs = [], queue = False, show_progress = False).success(fn = llave_process, inputs = [
        denoise_image,
        temperature,
        top_p,
        qs
    ], outputs = [
        prompt
    ])

    diffusion_button.click(fn = update_seed, inputs = [
        randomize_seed,
        seed
    ], outputs = [
        seed
    ], queue = False, show_progress = False).then(fn = check, inputs = [
        input_image
    ], outputs = [], queue = False, show_progress = False).success(fn = reset_feedback, inputs = [], outputs = [
        fb_score,
        fb_text
    ], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
        input_image,
        denoise_image,
        prompt,
        a_prompt,
        n_prompt,
        num_samples,
        min_size,
        downscale,
        upscale,
        edm_steps,
        s_stage1,
        s_stage2,
        s_cfg,
        randomize_seed,
        seed,
        s_churn,
        s_noise,
        color_fix_type,
        diff_dtype,
        ae_dtype,
        gamma_correction,
        linear_CFG,
        linear_s_stage2,
        spt_linear_CFG,
        spt_linear_s_stage2,
        model_select,
        output_format,
        allocation
    ], outputs = [
        result_slider,
        result_gallery,
        restore_information,
        event_id
    ]).success(fn = log_information, inputs = [
        result_gallery
    ], outputs = [], queue = False, show_progress = False)

    result_gallery.select(on_select_result, result_gallery, result_slider)

    restart_button.click(fn = load_and_reset, inputs = [
        param_setting
    ], outputs = [
        edm_steps,
        s_cfg,
        s_stage2,
        s_stage1,
        s_churn,
        s_noise,
        a_prompt,
        n_prompt,
        color_fix_type,
        linear_CFG,
        linear_s_stage2,
        spt_linear_CFG,
        spt_linear_s_stage2,
        model_select
    ])

    submit_button.click(fn = submit_feedback, inputs = [
        event_id,
        fb_score,
        fb_text
    ], outputs = [
        fb_text
    ])
        
    interface.queue(10).launch()