Fabrice-TIERCELIN commited on
Commit
fae2f45
1 Parent(s): a08a8ca

Image format for result

Browse files
Files changed (1) hide show
  1. app.py +899 -899
app.py CHANGED
@@ -1,900 +1,900 @@
1
- import os
2
- import gradio as gr
3
- import argparse
4
- import numpy as np
5
- import torch
6
- import einops
7
- import copy
8
- import math
9
- import time
10
- import random
11
- import spaces
12
- import re
13
- import uuid
14
-
15
- from gradio_imageslider import ImageSlider
16
- from PIL import Image
17
- from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
18
- from huggingface_hub import hf_hub_download
19
- from pillow_heif import register_heif_opener
20
-
21
- register_heif_opener()
22
-
23
- max_64_bit_int = 2**32 - 1
24
-
25
- 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")
26
- hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
27
- hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
28
- hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
29
- hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
30
-
31
- parser = argparse.ArgumentParser()
32
- parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
33
- parser.add_argument("--ip", type=str, default='127.0.0.1')
34
- parser.add_argument("--port", type=int, default='6688')
35
- parser.add_argument("--no_llava", action='store_true', default=True)#False
36
- parser.add_argument("--use_image_slider", action='store_true', default=False)#False
37
- parser.add_argument("--log_history", action='store_true', default=False)
38
- parser.add_argument("--loading_half_params", action='store_true', default=False)#False
39
- parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
40
- parser.add_argument("--encoder_tile_size", type=int, default=512)
41
- parser.add_argument("--decoder_tile_size", type=int, default=64)
42
- parser.add_argument("--load_8bit_llava", action='store_true', default=False)
43
- args = parser.parse_args()
44
-
45
- if torch.cuda.device_count() > 0:
46
- SUPIR_device = 'cuda:0'
47
-
48
- # Load SUPIR
49
- model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
50
- if args.loading_half_params:
51
- model = model.half()
52
- if args.use_tile_vae:
53
- model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
54
- model = model.to(SUPIR_device)
55
- model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
56
- model.current_model = 'v0-Q'
57
- ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
58
-
59
- def check_upload(input_image):
60
- if input_image is None:
61
- raise gr.Error("Please provide an image to restore.")
62
- return gr.update(visible = True)
63
-
64
- def update_seed(is_randomize_seed, seed):
65
- if is_randomize_seed:
66
- return random.randint(0, max_64_bit_int)
67
- return seed
68
-
69
- def reset():
70
- return [
71
- None,
72
- 0,
73
- None,
74
- None,
75
- "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.",
76
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
77
- 1,
78
- 1024,
79
- 1,
80
- 2,
81
- 50,
82
- -1.0,
83
- 1.,
84
- default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0,
85
- True,
86
- random.randint(0, max_64_bit_int),
87
- 5,
88
- 1.003,
89
- "Wavelet",
90
- "fp32",
91
- "fp32",
92
- 1.0,
93
- True,
94
- False,
95
- default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0,
96
- 0.,
97
- "v0-Q",
98
- "input",
99
- 6
100
- ]
101
-
102
- def check(input_image):
103
- if input_image is None:
104
- raise gr.Error("Please provide an image to restore.")
105
-
106
- @spaces.GPU(duration=420)
107
- def stage1_process(
108
- input_image,
109
- gamma_correction,
110
- diff_dtype,
111
- ae_dtype
112
- ):
113
- print('stage1_process ==>>')
114
- if torch.cuda.device_count() == 0:
115
- gr.Warning('Set this space to GPU config to make it work.')
116
- return None, None
117
- torch.cuda.set_device(SUPIR_device)
118
- LQ = HWC3(np.array(Image.open(input_image)))
119
- LQ = fix_resize(LQ, 512)
120
- # stage1
121
- LQ = np.array(LQ) / 255 * 2 - 1
122
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
123
-
124
- model.ae_dtype = convert_dtype(ae_dtype)
125
- model.model.dtype = convert_dtype(diff_dtype)
126
-
127
- LQ = model.batchify_denoise(LQ, is_stage1=True)
128
- LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
129
- # gamma correction
130
- LQ = LQ / 255.0
131
- LQ = np.power(LQ, gamma_correction)
132
- LQ *= 255.0
133
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
134
- print('<<== stage1_process')
135
- return LQ, gr.update(visible = True)
136
-
137
- def stage2_process(*args, **kwargs):
138
- try:
139
- return restore_in_Xmin(*args, **kwargs)
140
- except Exception as e:
141
- print('Exception of type ' + str(type(e)))
142
- if type(e).__name__ == "<class 'gradio.exceptions.Error'>":
143
- print('Exception of name ' + type(e).__name__)
144
- raise e
145
-
146
- def restore_in_Xmin(
147
- noisy_image,
148
- rotation,
149
- denoise_image,
150
- prompt,
151
- a_prompt,
152
- n_prompt,
153
- num_samples,
154
- min_size,
155
- downscale,
156
- upscale,
157
- edm_steps,
158
- s_stage1,
159
- s_stage2,
160
- s_cfg,
161
- randomize_seed,
162
- seed,
163
- s_churn,
164
- s_noise,
165
- color_fix_type,
166
- diff_dtype,
167
- ae_dtype,
168
- gamma_correction,
169
- linear_CFG,
170
- linear_s_stage2,
171
- spt_linear_CFG,
172
- spt_linear_s_stage2,
173
- model_select,
174
- output_format,
175
- allocation
176
- ):
177
- print("noisy_image:\n" + str(noisy_image))
178
- print("denoise_image:\n" + str(denoise_image))
179
- print("rotation: " + str(rotation))
180
- print("prompt: " + str(prompt))
181
- print("a_prompt: " + str(a_prompt))
182
- print("n_prompt: " + str(n_prompt))
183
- print("num_samples: " + str(num_samples))
184
- print("min_size: " + str(min_size))
185
- print("downscale: " + str(downscale))
186
- print("upscale: " + str(upscale))
187
- print("edm_steps: " + str(edm_steps))
188
- print("s_stage1: " + str(s_stage1))
189
- print("s_stage2: " + str(s_stage2))
190
- print("s_cfg: " + str(s_cfg))
191
- print("randomize_seed: " + str(randomize_seed))
192
- print("seed: " + str(seed))
193
- print("s_churn: " + str(s_churn))
194
- print("s_noise: " + str(s_noise))
195
- print("color_fix_type: " + str(color_fix_type))
196
- print("diff_dtype: " + str(diff_dtype))
197
- print("ae_dtype: " + str(ae_dtype))
198
- print("gamma_correction: " + str(gamma_correction))
199
- print("linear_CFG: " + str(linear_CFG))
200
- print("linear_s_stage2: " + str(linear_s_stage2))
201
- print("spt_linear_CFG: " + str(spt_linear_CFG))
202
- print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
203
- print("model_select: " + str(model_select))
204
- print("GPU time allocation: " + str(allocation) + " min")
205
- print("output_format: " + str(output_format))
206
-
207
- input_format = re.sub(r"^.*\.([^\.]+)$", r"\1", noisy_image)
208
-
209
- if input_format not in ['png', 'webp', 'jpg', 'jpeg', 'gif', 'bmp', 'heic']:
210
- gr.Warning('Invalid image format. Please first convert into *.png, *.webp, *.jpg, *.jpeg, *.gif, *.bmp or *.heic.')
211
- return None, None, None, None
212
-
213
- if output_format == "input":
214
- if noisy_image is None:
215
- output_format = "png"
216
- else:
217
- output_format = input_format
218
- print("final output_format: " + str(output_format))
219
-
220
- if prompt is None:
221
- prompt = ""
222
-
223
- if a_prompt is None:
224
- a_prompt = ""
225
-
226
- if n_prompt is None:
227
- n_prompt = ""
228
-
229
- if prompt != "" and a_prompt != "":
230
- a_prompt = prompt + ", " + a_prompt
231
- else:
232
- a_prompt = prompt + a_prompt
233
- print("Final prompt: " + str(a_prompt))
234
-
235
- denoise_image = np.array(Image.open(noisy_image if denoise_image is None else denoise_image))
236
-
237
- if rotation == 90:
238
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
239
- elif rotation == 180:
240
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
241
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
242
- elif rotation == -90:
243
- denoise_image = np.array(list(zip(*denoise_image))[::-1])
244
-
245
- if 1 < downscale:
246
- input_height, input_width, input_channel = denoise_image.shape
247
- denoise_image = np.array(Image.fromarray(denoise_image).resize((input_width // downscale, input_height // downscale), Image.LANCZOS))
248
-
249
- denoise_image = HWC3(denoise_image)
250
-
251
- if torch.cuda.device_count() == 0:
252
- gr.Warning('Set this space to GPU config to make it work.')
253
- return [noisy_image, denoise_image], [denoise_image], None, gr.update(visible=True)
254
-
255
- if model_select != model.current_model:
256
- print('load ' + model_select)
257
- if model_select == 'v0-Q':
258
- model.load_state_dict(ckpt_Q, strict=False)
259
- elif model_select == 'v0-F':
260
- model.load_state_dict(ckpt_F, strict=False)
261
- model.current_model = model_select
262
-
263
- model.ae_dtype = convert_dtype(ae_dtype)
264
- model.model.dtype = convert_dtype(diff_dtype)
265
-
266
- # Allocation
267
- if allocation == 1:
268
- return restore_in_1min(
269
- 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
270
- )
271
- if allocation == 2:
272
- return restore_in_2min(
273
- 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
274
- )
275
- if allocation == 3:
276
- return restore_in_3min(
277
- 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
278
- )
279
- if allocation == 4:
280
- return restore_in_4min(
281
- 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
282
- )
283
- if allocation == 5:
284
- return restore_in_5min(
285
- 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
286
- )
287
- if allocation == 7:
288
- return restore_in_7min(
289
- 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
290
- )
291
- if allocation == 8:
292
- return restore_in_8min(
293
- 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
294
- )
295
- if allocation == 9:
296
- return restore_in_9min(
297
- 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
298
- )
299
- if allocation == 10:
300
- return restore_in_10min(
301
- 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
302
- )
303
- else:
304
- return restore_in_6min(
305
- 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
306
- )
307
-
308
- @spaces.GPU(duration=59)
309
- def restore_in_1min(*args, **kwargs):
310
- return restore_on_gpu(*args, **kwargs)
311
-
312
- @spaces.GPU(duration=119)
313
- def restore_in_2min(*args, **kwargs):
314
- return restore_on_gpu(*args, **kwargs)
315
-
316
- @spaces.GPU(duration=179)
317
- def restore_in_3min(*args, **kwargs):
318
- return restore_on_gpu(*args, **kwargs)
319
-
320
- @spaces.GPU(duration=239)
321
- def restore_in_4min(*args, **kwargs):
322
- return restore_on_gpu(*args, **kwargs)
323
-
324
- @spaces.GPU(duration=299)
325
- def restore_in_5min(*args, **kwargs):
326
- return restore_on_gpu(*args, **kwargs)
327
-
328
- @spaces.GPU(duration=359)
329
- def restore_in_6min(*args, **kwargs):
330
- return restore_on_gpu(*args, **kwargs)
331
-
332
- @spaces.GPU(duration=419)
333
- def restore_in_7min(*args, **kwargs):
334
- return restore_on_gpu(*args, **kwargs)
335
-
336
- @spaces.GPU(duration=479)
337
- def restore_in_8min(*args, **kwargs):
338
- return restore_on_gpu(*args, **kwargs)
339
-
340
- @spaces.GPU(duration=539)
341
- def restore_in_9min(*args, **kwargs):
342
- return restore_on_gpu(*args, **kwargs)
343
-
344
- @spaces.GPU(duration=599)
345
- def restore_in_10min(*args, **kwargs):
346
- return restore_on_gpu(*args, **kwargs)
347
-
348
- def restore_on_gpu(
349
- noisy_image,
350
- input_image,
351
- prompt,
352
- a_prompt,
353
- n_prompt,
354
- num_samples,
355
- min_size,
356
- downscale,
357
- upscale,
358
- edm_steps,
359
- s_stage1,
360
- s_stage2,
361
- s_cfg,
362
- randomize_seed,
363
- seed,
364
- s_churn,
365
- s_noise,
366
- color_fix_type,
367
- diff_dtype,
368
- ae_dtype,
369
- gamma_correction,
370
- linear_CFG,
371
- linear_s_stage2,
372
- spt_linear_CFG,
373
- spt_linear_s_stage2,
374
- model_select,
375
- output_format,
376
- allocation
377
- ):
378
- start = time.time()
379
- print('restore ==>>')
380
-
381
- torch.cuda.set_device(SUPIR_device)
382
-
383
- with torch.no_grad():
384
- input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=min_size)
385
- LQ = np.array(input_image) / 255.0
386
- LQ = np.power(LQ, gamma_correction)
387
- LQ *= 255.0
388
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
389
- LQ = LQ / 255 * 2 - 1
390
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
391
- captions = ['']
392
-
393
- samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
394
- s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
395
- num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
396
- use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
397
- cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
398
-
399
- x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
400
- 0, 255).astype(np.uint8)
401
- results = [x_samples[i] for i in range(num_samples)]
402
- torch.cuda.empty_cache()
403
-
404
- # All the results have the same size
405
- input_height, input_width, input_channel = np.array(input_image).shape
406
- result_height, result_width, result_channel = np.array(results[0]).shape
407
-
408
- print('<<== restore')
409
- end = time.time()
410
- secondes = int(end - start)
411
- minutes = math.floor(secondes / 60)
412
- secondes = secondes - (minutes * 60)
413
- hours = math.floor(minutes / 60)
414
- minutes = minutes - (hours * 60)
415
- information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
416
- "If you don't get the image you wanted, add more details in the « Image description ». " + \
417
- "Wait " + str(allocation) + " min before a new run to avoid quota penalty or use another computer. " + \
418
- "The image" + (" has" if len(results) == 1 else "s have") + " been generated in " + \
419
- ((str(hours) + " h, ") if hours != 0 else "") + \
420
- ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
421
- str(secondes) + " sec. " + \
422
- "The new image resolution is " + str(result_width) + \
423
- " pixels large and " + str(result_height) + \
424
- " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
425
- print(information)
426
- try:
427
- print("Initial resolution: " + f'{input_width * input_height:,}')
428
- print("Final resolution: " + f'{result_width * result_height:,}')
429
- print("edm_steps: " + str(edm_steps))
430
- print("num_samples: " + str(num_samples))
431
- print("downscale: " + str(downscale))
432
- print("Estimated minutes: " + f'{(((result_width * result_height**(1/1.5)) * input_width * input_height * (edm_steps**(1/2)) * (num_samples**(1/2.5)))**(1/2.5)) / 25000:,}')
433
- except Exception as e:
434
- print('Exception of Estimation')
435
-
436
- # Only one image can be shown in the slider
437
- return [noisy_image] + [results[0]], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = results), gr.update(value = information, visible = True), gr.update(visible=True)
438
-
439
- def load_and_reset(param_setting):
440
- print('load_and_reset ==>>')
441
- if torch.cuda.device_count() == 0:
442
- gr.Warning('Set this space to GPU config to make it work.')
443
- return None, None, None, None, None, None, None, None, None, None, None, None, None, None
444
- edm_steps = default_setting.edm_steps
445
- s_stage2 = 1.0
446
- s_stage1 = -1.0
447
- s_churn = 5
448
- s_noise = 1.003
449
- a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
450
- 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
451
- 'detailing, hyper sharpness, perfect without deformations.'
452
- n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
453
- '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
454
- 'signature, jpeg artifacts, deformed, lowres, over-smooth'
455
- color_fix_type = 'Wavelet'
456
- spt_linear_s_stage2 = 0.0
457
- linear_s_stage2 = False
458
- linear_CFG = True
459
- if param_setting == "Quality":
460
- s_cfg = default_setting.s_cfg_Quality
461
- spt_linear_CFG = default_setting.spt_linear_CFG_Quality
462
- model_select = "v0-Q"
463
- elif param_setting == "Fidelity":
464
- s_cfg = default_setting.s_cfg_Fidelity
465
- spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
466
- model_select = "v0-F"
467
- else:
468
- raise NotImplementedError
469
- gr.Info('The parameters are reset.')
470
- print('<<== load_and_reset')
471
- return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
472
- linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select
473
-
474
- def log_information(result_gallery):
475
- print('log_information')
476
- if result_gallery is not None:
477
- for i, result in enumerate(result_gallery):
478
- print(result[0])
479
-
480
- def on_select_result(result_slider, result_gallery, evt: gr.SelectData):
481
- print('on_select_result')
482
- if result_gallery is not None:
483
- for i, result in enumerate(result_gallery):
484
- print(result[0])
485
- return [result_slider[0], result_gallery[evt.index][0]]
486
-
487
- title_html = """
488
- <h1><center>SUPIR</center></h1>
489
- <big><center>Upscale your images up to x10 freely, without account, without watermark and download it</center></big>
490
- <center><big><big>🤸<big><big><big><big><big><big>🤸</big></big></big></big></big></big></big></big></center>
491
-
492
- <p>This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
493
- It is still a research project under tested and is not yet a stable commercial product.
494
- The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
495
- SUPIR is for beauty and illustration only.
496
- Most of the processes only last few minutes.
497
- The process will be aborted if it lasts more than 10 min.
498
- If you want to upscale AI-generated images, be noticed that <i>PixArt Sigma</i> space can directly generate 5984x5984 images.
499
- Due to Gradio issues, the generated image is slightly less satured than the original.
500
- Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">message in discussion</a> if you encounter issues.
501
- You can also use <a href="https://huggingface.co/spaces/gokaygokay/AuraSR">AuraSR</a> to upscale x4.
502
-
503
- <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://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai">Local Install Guide</a></center></p>
504
- <p><center><a style="display:inline-block" href='https://github.com/Fanghua-Yu/SUPIR'><img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Fanghua-Yu/SUPIR?style=social"></a></center></p>
505
- """
506
-
507
-
508
- claim_md = """
509
- ## **Piracy**
510
- The images are not stored but the logs are saved during a month.
511
- ## **How to get SUPIR**
512
- You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
513
- You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
514
- You can install _Pinokio_ on your computer and then install _SUPIR_ into it. It should be quite easy if you have an Nvidia GPU.
515
- ## **Terms of use**
516
- 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.
517
- ## **License**
518
- 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.
519
- """
520
-
521
- # Gradio interface
522
- with gr.Blocks() as interface:
523
- if torch.cuda.device_count() == 0:
524
- with gr.Row():
525
- gr.HTML("""
526
- <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>
527
-
528
- You can't use SUPIR directly here because this space runs on a CPU, which is not enough for SUPIR. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
529
- </big></big></big></p>
530
- """)
531
- gr.HTML(title_html)
532
-
533
- input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.jpg, *.gif, *.bmp, *.heic)", show_label=True, type="filepath", height=600, elem_id="image-input")
534
- rotation = gr.Radio([["No rotation", 0], ["⤵ Rotate +90°", 90], ["↩ Return 180°", 180], ["⤴ Rotate -90°", -90]], label="Orientation correction", info="Will apply the following rotation before restoring the image; the AI needs a good orientation to understand the content", value=0, interactive=True, visible=False)
535
- with gr.Group():
536
- prompt = gr.Textbox(label="Image description", info="Help the AI understand what the image represents; describe as much as possible, especially the details we can't see on the original image; you can write in any language", value="", placeholder="A 33 years old man, walking, in the street, Santiago, morning, Summer, photorealistic", lines=3)
537
- 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.")
538
- upscale = gr.Radio([["x1", 1], ["x2", 2], ["x3", 3], ["x4", 4], ["x5", 5], ["x6", 6], ["x7", 7], ["x8", 8], ["x9", 9], ["x10", 10]], label="Upscale factor", info="Resolution x1 to x10", value=2, interactive=True)
539
- 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 (discouraged)", 8], ["9 min (discouraged)", 9], ["10 min (discouraged)", 10]], label="GPU allocation time", info="lower=May abort run, higher=Quota penalty for next runs", value=7, interactive=True)
540
- output_format = gr.Radio([["As input", "input"], ["*.png", "png"], ["*.webp", "webp"], ["*.jpeg", "jpeg"], ["*.gif", "gif"], ["*.bmp", "bmp"], ["*.heic", "heic"]], label="Image format for result", info="File extention", value="input", interactive=True)
541
-
542
- with gr.Accordion("Pre-denoising (optional)", open=False):
543
- gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
544
- denoise_button = gr.Button(value="Pre-denoise")
545
- denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], interactive = False, height=600, elem_id="image-s1")
546
- denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)
547
-
548
- with gr.Accordion("Advanced options", open=False):
549
- a_prompt = gr.Textbox(label="Additional image description",
550
- info="Completes the main image description",
551
- value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
552
- 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
553
- 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, '
554
- 'hyper sharpness, perfect without deformations.',
555
- lines=3)
556
- n_prompt = gr.Textbox(label="Negative image description",
557
- info="Disambiguate by listing what the image does NOT represent",
558
- value='painting, oil painting, illustration, drawing, art, sketch, anime, '
559
- 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, '
560
- 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
561
- 'deformed, lowres, over-smooth',
562
- lines=3)
563
- 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)
564
- num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
565
- , value=1, step=1)
566
- min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
567
- downscale = gr.Radio([["/1", 1], ["/2", 2], ["/3", 3], ["/4", 4], ["/5", 5], ["/6", 6], ["/7", 7], ["/8", 8], ["/9", 9], ["/10", 10]], label="Pre-downscale factor", info="Reducing blurred image reduce the process time", value=1, interactive=True)
568
- with gr.Row():
569
- with gr.Column():
570
- model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q",
571
- interactive=True)
572
- with gr.Column():
573
- color_fix_type = gr.Radio([["None", "None"], ["AdaIn (improve as a photo)", "AdaIn"], ["Wavelet (for JPEG artifacts)", "Wavelet"]], label="Color-Fix Type", info="AdaIn=Improve following a style, Wavelet=For JPEG artifacts", value="Wavelet",
574
- interactive=True)
575
- s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
576
- value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
577
- s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
578
- s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
579
- s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
580
- s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
581
- with gr.Row():
582
- with gr.Column():
583
- linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
584
- spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
585
- maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
586
- with gr.Column():
587
- linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
588
- spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
589
- maximum=1., value=0., step=0.05)
590
- with gr.Column():
591
- diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp32",
592
- interactive=True)
593
- with gr.Column():
594
- ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32",
595
- interactive=True)
596
- randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
597
- seed = gr.Slider(label="Seed", minimum=0, maximum=max_64_bit_int, step=1, randomize=True)
598
- with gr.Group():
599
- param_setting = gr.Radio(["Quality", "Fidelity"], interactive=True, label="Presetting", value = "Quality")
600
- restart_button = gr.Button(value="Apply presetting")
601
-
602
- with gr.Column():
603
- diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id = "process_button")
604
- reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
605
-
606
- restore_information = gr.HTML(value = "Restart the process to get another result.", visible = False)
607
- result_slider = ImageSlider(label = 'Comparator', show_label = False, interactive = False, elem_id = "slider1", show_download_button = False)
608
- result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
609
-
610
- gr.Examples(
611
- examples = [
612
- [
613
- "./Examples/Example1.png",
614
- 0,
615
- None,
616
- "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
617
- "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.",
618
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
619
- 2,
620
- 1024,
621
- 1,
622
- 8,
623
- 200,
624
- -1,
625
- 1,
626
- 7.5,
627
- False,
628
- 42,
629
- 5,
630
- 1.003,
631
- "AdaIn",
632
- "fp16",
633
- "bf16",
634
- 1.0,
635
- True,
636
- 4,
637
- False,
638
- 0.,
639
- "v0-Q",
640
- "input",
641
- 5
642
- ],
643
- [
644
- "./Examples/Example2.jpeg",
645
- 0,
646
- None,
647
- "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
648
- "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.",
649
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
650
- 1,
651
- 1024,
652
- 1,
653
- 1,
654
- 200,
655
- -1,
656
- 1,
657
- 7.5,
658
- False,
659
- 42,
660
- 5,
661
- 1.003,
662
- "Wavelet",
663
- "fp16",
664
- "bf16",
665
- 1.0,
666
- True,
667
- 4,
668
- False,
669
- 0.,
670
- "v0-Q",
671
- "input",
672
- 4
673
- ],
674
- [
675
- "./Examples/Example3.webp",
676
- 0,
677
- None,
678
- "A red apple",
679
- "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.",
680
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
681
- 1,
682
- 1024,
683
- 1,
684
- 1,
685
- 200,
686
- -1,
687
- 1,
688
- 7.5,
689
- False,
690
- 42,
691
- 5,
692
- 1.003,
693
- "Wavelet",
694
- "fp16",
695
- "bf16",
696
- 1.0,
697
- True,
698
- 4,
699
- False,
700
- 0.,
701
- "v0-Q",
702
- "input",
703
- 4
704
- ],
705
- [
706
- "./Examples/Example3.webp",
707
- 0,
708
- None,
709
- "A red marble",
710
- "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.",
711
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
712
- 1,
713
- 1024,
714
- 1,
715
- 1,
716
- 200,
717
- -1,
718
- 1,
719
- 7.5,
720
- False,
721
- 42,
722
- 5,
723
- 1.003,
724
- "Wavelet",
725
- "fp16",
726
- "bf16",
727
- 1.0,
728
- True,
729
- 4,
730
- False,
731
- 0.,
732
- "v0-Q",
733
- "input",
734
- 4
735
- ],
736
- ],
737
- run_on_click = True,
738
- fn = stage2_process,
739
- inputs = [
740
- input_image,
741
- rotation,
742
- denoise_image,
743
- prompt,
744
- a_prompt,
745
- n_prompt,
746
- num_samples,
747
- min_size,
748
- downscale,
749
- upscale,
750
- edm_steps,
751
- s_stage1,
752
- s_stage2,
753
- s_cfg,
754
- randomize_seed,
755
- seed,
756
- s_churn,
757
- s_noise,
758
- color_fix_type,
759
- diff_dtype,
760
- ae_dtype,
761
- gamma_correction,
762
- linear_CFG,
763
- linear_s_stage2,
764
- spt_linear_CFG,
765
- spt_linear_s_stage2,
766
- model_select,
767
- output_format,
768
- allocation
769
- ],
770
- outputs = [
771
- result_slider,
772
- result_gallery,
773
- restore_information,
774
- reset_btn
775
- ],
776
- cache_examples = False,
777
- )
778
-
779
- with gr.Row():
780
- gr.Markdown(claim_md)
781
-
782
- input_image.upload(fn = check_upload, inputs = [
783
- input_image
784
- ], outputs = [
785
- rotation
786
- ], queue = False, show_progress = False)
787
-
788
- denoise_button.click(fn = check, inputs = [
789
- input_image
790
- ], outputs = [], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
791
- input_image,
792
- gamma_correction,
793
- diff_dtype,
794
- ae_dtype
795
- ], outputs=[
796
- denoise_image,
797
- denoise_information
798
- ])
799
-
800
- diffusion_button.click(fn = update_seed, inputs = [
801
- randomize_seed,
802
- seed
803
- ], outputs = [
804
- seed
805
- ], queue = False, show_progress = False).then(fn = check, inputs = [
806
- input_image
807
- ], outputs = [], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
808
- input_image,
809
- rotation,
810
- denoise_image,
811
- prompt,
812
- a_prompt,
813
- n_prompt,
814
- num_samples,
815
- min_size,
816
- downscale,
817
- upscale,
818
- edm_steps,
819
- s_stage1,
820
- s_stage2,
821
- s_cfg,
822
- randomize_seed,
823
- seed,
824
- s_churn,
825
- s_noise,
826
- color_fix_type,
827
- diff_dtype,
828
- ae_dtype,
829
- gamma_correction,
830
- linear_CFG,
831
- linear_s_stage2,
832
- spt_linear_CFG,
833
- spt_linear_s_stage2,
834
- model_select,
835
- output_format,
836
- allocation
837
- ], outputs = [
838
- result_slider,
839
- result_gallery,
840
- restore_information,
841
- reset_btn
842
- ]).success(fn = log_information, inputs = [
843
- result_gallery
844
- ], outputs = [], queue = False, show_progress = False)
845
-
846
- result_gallery.change(on_select_result, [result_slider, result_gallery], result_slider)
847
- result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider)
848
-
849
- restart_button.click(fn = load_and_reset, inputs = [
850
- param_setting
851
- ], outputs = [
852
- edm_steps,
853
- s_cfg,
854
- s_stage2,
855
- s_stage1,
856
- s_churn,
857
- s_noise,
858
- a_prompt,
859
- n_prompt,
860
- color_fix_type,
861
- linear_CFG,
862
- linear_s_stage2,
863
- spt_linear_CFG,
864
- spt_linear_s_stage2,
865
- model_select
866
- ])
867
-
868
- reset_btn.click(fn = reset, inputs = [], outputs = [
869
- input_image,
870
- rotation,
871
- denoise_image,
872
- prompt,
873
- a_prompt,
874
- n_prompt,
875
- num_samples,
876
- min_size,
877
- downscale,
878
- upscale,
879
- edm_steps,
880
- s_stage1,
881
- s_stage2,
882
- s_cfg,
883
- randomize_seed,
884
- seed,
885
- s_churn,
886
- s_noise,
887
- color_fix_type,
888
- diff_dtype,
889
- ae_dtype,
890
- gamma_correction,
891
- linear_CFG,
892
- linear_s_stage2,
893
- spt_linear_CFG,
894
- spt_linear_s_stage2,
895
- model_select,
896
- output_format,
897
- allocation
898
- ], queue = False, show_progress = False)
899
-
900
  interface.queue(10).launch()
 
1
+ import os
2
+ import gradio as gr
3
+ import argparse
4
+ import numpy as np
5
+ import torch
6
+ import einops
7
+ import copy
8
+ import math
9
+ import time
10
+ import random
11
+ import spaces
12
+ import re
13
+ import uuid
14
+
15
+ from gradio_imageslider import ImageSlider
16
+ from PIL import Image
17
+ from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
18
+ from huggingface_hub import hf_hub_download
19
+ from pillow_heif import register_heif_opener
20
+
21
+ register_heif_opener()
22
+
23
+ max_64_bit_int = 2**32 - 1
24
+
25
+ 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")
26
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
27
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
28
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
29
+ hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
30
+
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
33
+ parser.add_argument("--ip", type=str, default='127.0.0.1')
34
+ parser.add_argument("--port", type=int, default='6688')
35
+ parser.add_argument("--no_llava", action='store_true', default=True)#False
36
+ parser.add_argument("--use_image_slider", action='store_true', default=False)#False
37
+ parser.add_argument("--log_history", action='store_true', default=False)
38
+ parser.add_argument("--loading_half_params", action='store_true', default=False)#False
39
+ parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
40
+ parser.add_argument("--encoder_tile_size", type=int, default=512)
41
+ parser.add_argument("--decoder_tile_size", type=int, default=64)
42
+ parser.add_argument("--load_8bit_llava", action='store_true', default=False)
43
+ args = parser.parse_args()
44
+
45
+ if torch.cuda.device_count() > 0:
46
+ SUPIR_device = 'cuda:0'
47
+
48
+ # Load SUPIR
49
+ model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
50
+ if args.loading_half_params:
51
+ model = model.half()
52
+ if args.use_tile_vae:
53
+ model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
54
+ model = model.to(SUPIR_device)
55
+ model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
56
+ model.current_model = 'v0-Q'
57
+ ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
58
+
59
+ def check_upload(input_image):
60
+ if input_image is None:
61
+ raise gr.Error("Please provide an image to restore.")
62
+ return gr.update(visible = True)
63
+
64
+ def update_seed(is_randomize_seed, seed):
65
+ if is_randomize_seed:
66
+ return random.randint(0, max_64_bit_int)
67
+ return seed
68
+
69
+ def reset():
70
+ return [
71
+ None,
72
+ 0,
73
+ None,
74
+ None,
75
+ "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.",
76
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
77
+ 1,
78
+ 1024,
79
+ 1,
80
+ 2,
81
+ 50,
82
+ -1.0,
83
+ 1.,
84
+ default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0,
85
+ True,
86
+ random.randint(0, max_64_bit_int),
87
+ 5,
88
+ 1.003,
89
+ "Wavelet",
90
+ "fp32",
91
+ "fp32",
92
+ 1.0,
93
+ True,
94
+ False,
95
+ default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0,
96
+ 0.,
97
+ "v0-Q",
98
+ "input",
99
+ 6
100
+ ]
101
+
102
+ def check(input_image):
103
+ if input_image is None:
104
+ raise gr.Error("Please provide an image to restore.")
105
+
106
+ @spaces.GPU(duration=420)
107
+ def stage1_process(
108
+ input_image,
109
+ gamma_correction,
110
+ diff_dtype,
111
+ ae_dtype
112
+ ):
113
+ print('stage1_process ==>>')
114
+ if torch.cuda.device_count() == 0:
115
+ gr.Warning('Set this space to GPU config to make it work.')
116
+ return None, None
117
+ torch.cuda.set_device(SUPIR_device)
118
+ LQ = HWC3(np.array(Image.open(input_image)))
119
+ LQ = fix_resize(LQ, 512)
120
+ # stage1
121
+ LQ = np.array(LQ) / 255 * 2 - 1
122
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
123
+
124
+ model.ae_dtype = convert_dtype(ae_dtype)
125
+ model.model.dtype = convert_dtype(diff_dtype)
126
+
127
+ LQ = model.batchify_denoise(LQ, is_stage1=True)
128
+ LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
129
+ # gamma correction
130
+ LQ = LQ / 255.0
131
+ LQ = np.power(LQ, gamma_correction)
132
+ LQ *= 255.0
133
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
134
+ print('<<== stage1_process')
135
+ return LQ, gr.update(visible = True)
136
+
137
+ def stage2_process(*args, **kwargs):
138
+ try:
139
+ return restore_in_Xmin(*args, **kwargs)
140
+ except Exception as e:
141
+ print('Exception of type ' + str(type(e)))
142
+ if type(e).__name__ == "<class 'gradio.exceptions.Error'>":
143
+ print('Exception of name ' + type(e).__name__)
144
+ raise e
145
+
146
+ def restore_in_Xmin(
147
+ noisy_image,
148
+ rotation,
149
+ denoise_image,
150
+ prompt,
151
+ a_prompt,
152
+ n_prompt,
153
+ num_samples,
154
+ min_size,
155
+ downscale,
156
+ upscale,
157
+ edm_steps,
158
+ s_stage1,
159
+ s_stage2,
160
+ s_cfg,
161
+ randomize_seed,
162
+ seed,
163
+ s_churn,
164
+ s_noise,
165
+ color_fix_type,
166
+ diff_dtype,
167
+ ae_dtype,
168
+ gamma_correction,
169
+ linear_CFG,
170
+ linear_s_stage2,
171
+ spt_linear_CFG,
172
+ spt_linear_s_stage2,
173
+ model_select,
174
+ output_format,
175
+ allocation
176
+ ):
177
+ print("noisy_image:\n" + str(noisy_image))
178
+ print("denoise_image:\n" + str(denoise_image))
179
+ print("rotation: " + str(rotation))
180
+ print("prompt: " + str(prompt))
181
+ print("a_prompt: " + str(a_prompt))
182
+ print("n_prompt: " + str(n_prompt))
183
+ print("num_samples: " + str(num_samples))
184
+ print("min_size: " + str(min_size))
185
+ print("downscale: " + str(downscale))
186
+ print("upscale: " + str(upscale))
187
+ print("edm_steps: " + str(edm_steps))
188
+ print("s_stage1: " + str(s_stage1))
189
+ print("s_stage2: " + str(s_stage2))
190
+ print("s_cfg: " + str(s_cfg))
191
+ print("randomize_seed: " + str(randomize_seed))
192
+ print("seed: " + str(seed))
193
+ print("s_churn: " + str(s_churn))
194
+ print("s_noise: " + str(s_noise))
195
+ print("color_fix_type: " + str(color_fix_type))
196
+ print("diff_dtype: " + str(diff_dtype))
197
+ print("ae_dtype: " + str(ae_dtype))
198
+ print("gamma_correction: " + str(gamma_correction))
199
+ print("linear_CFG: " + str(linear_CFG))
200
+ print("linear_s_stage2: " + str(linear_s_stage2))
201
+ print("spt_linear_CFG: " + str(spt_linear_CFG))
202
+ print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
203
+ print("model_select: " + str(model_select))
204
+ print("GPU time allocation: " + str(allocation) + " min")
205
+ print("output_format: " + str(output_format))
206
+
207
+ input_format = re.sub(r"^.*\.([^\.]+)$", r"\1", noisy_image)
208
+
209
+ if input_format not in ['png', 'webp', 'jpg', 'jpeg', 'gif', 'bmp', 'heic']:
210
+ gr.Warning('Invalid image format. Please first convert into *.png, *.webp, *.jpg, *.jpeg, *.gif, *.bmp or *.heic.')
211
+ return None, None, None, None
212
+
213
+ if output_format == "input":
214
+ if noisy_image is None:
215
+ output_format = "png"
216
+ else:
217
+ output_format = input_format
218
+ print("final output_format: " + str(output_format))
219
+
220
+ if prompt is None:
221
+ prompt = ""
222
+
223
+ if a_prompt is None:
224
+ a_prompt = ""
225
+
226
+ if n_prompt is None:
227
+ n_prompt = ""
228
+
229
+ if prompt != "" and a_prompt != "":
230
+ a_prompt = prompt + ", " + a_prompt
231
+ else:
232
+ a_prompt = prompt + a_prompt
233
+ print("Final prompt: " + str(a_prompt))
234
+
235
+ denoise_image = np.array(Image.open(noisy_image if denoise_image is None else denoise_image))
236
+
237
+ if rotation == 90:
238
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
239
+ elif rotation == 180:
240
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
241
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
242
+ elif rotation == -90:
243
+ denoise_image = np.array(list(zip(*denoise_image))[::-1])
244
+
245
+ if 1 < downscale:
246
+ input_height, input_width, input_channel = denoise_image.shape
247
+ denoise_image = np.array(Image.fromarray(denoise_image).resize((input_width // downscale, input_height // downscale), Image.LANCZOS))
248
+
249
+ denoise_image = HWC3(denoise_image)
250
+
251
+ if torch.cuda.device_count() == 0:
252
+ gr.Warning('Set this space to GPU config to make it work.')
253
+ return [noisy_image, denoise_image], [denoise_image], None, gr.update(visible=True)
254
+
255
+ if model_select != model.current_model:
256
+ print('load ' + model_select)
257
+ if model_select == 'v0-Q':
258
+ model.load_state_dict(ckpt_Q, strict=False)
259
+ elif model_select == 'v0-F':
260
+ model.load_state_dict(ckpt_F, strict=False)
261
+ model.current_model = model_select
262
+
263
+ model.ae_dtype = convert_dtype(ae_dtype)
264
+ model.model.dtype = convert_dtype(diff_dtype)
265
+
266
+ # Allocation
267
+ if allocation == 1:
268
+ return restore_in_1min(
269
+ 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
270
+ )
271
+ if allocation == 2:
272
+ return restore_in_2min(
273
+ 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
274
+ )
275
+ if allocation == 3:
276
+ return restore_in_3min(
277
+ 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
278
+ )
279
+ if allocation == 4:
280
+ return restore_in_4min(
281
+ 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
282
+ )
283
+ if allocation == 5:
284
+ return restore_in_5min(
285
+ 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
286
+ )
287
+ if allocation == 7:
288
+ return restore_in_7min(
289
+ 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
290
+ )
291
+ if allocation == 8:
292
+ return restore_in_8min(
293
+ 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
294
+ )
295
+ if allocation == 9:
296
+ return restore_in_9min(
297
+ 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
298
+ )
299
+ if allocation == 10:
300
+ return restore_in_10min(
301
+ 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
302
+ )
303
+ else:
304
+ return restore_in_6min(
305
+ 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
306
+ )
307
+
308
+ @spaces.GPU(duration=59)
309
+ def restore_in_1min(*args, **kwargs):
310
+ return restore_on_gpu(*args, **kwargs)
311
+
312
+ @spaces.GPU(duration=119)
313
+ def restore_in_2min(*args, **kwargs):
314
+ return restore_on_gpu(*args, **kwargs)
315
+
316
+ @spaces.GPU(duration=179)
317
+ def restore_in_3min(*args, **kwargs):
318
+ return restore_on_gpu(*args, **kwargs)
319
+
320
+ @spaces.GPU(duration=239)
321
+ def restore_in_4min(*args, **kwargs):
322
+ return restore_on_gpu(*args, **kwargs)
323
+
324
+ @spaces.GPU(duration=299)
325
+ def restore_in_5min(*args, **kwargs):
326
+ return restore_on_gpu(*args, **kwargs)
327
+
328
+ @spaces.GPU(duration=359)
329
+ def restore_in_6min(*args, **kwargs):
330
+ return restore_on_gpu(*args, **kwargs)
331
+
332
+ @spaces.GPU(duration=419)
333
+ def restore_in_7min(*args, **kwargs):
334
+ return restore_on_gpu(*args, **kwargs)
335
+
336
+ @spaces.GPU(duration=479)
337
+ def restore_in_8min(*args, **kwargs):
338
+ return restore_on_gpu(*args, **kwargs)
339
+
340
+ @spaces.GPU(duration=539)
341
+ def restore_in_9min(*args, **kwargs):
342
+ return restore_on_gpu(*args, **kwargs)
343
+
344
+ @spaces.GPU(duration=599)
345
+ def restore_in_10min(*args, **kwargs):
346
+ return restore_on_gpu(*args, **kwargs)
347
+
348
+ def restore_on_gpu(
349
+ noisy_image,
350
+ input_image,
351
+ prompt,
352
+ a_prompt,
353
+ n_prompt,
354
+ num_samples,
355
+ min_size,
356
+ downscale,
357
+ upscale,
358
+ edm_steps,
359
+ s_stage1,
360
+ s_stage2,
361
+ s_cfg,
362
+ randomize_seed,
363
+ seed,
364
+ s_churn,
365
+ s_noise,
366
+ color_fix_type,
367
+ diff_dtype,
368
+ ae_dtype,
369
+ gamma_correction,
370
+ linear_CFG,
371
+ linear_s_stage2,
372
+ spt_linear_CFG,
373
+ spt_linear_s_stage2,
374
+ model_select,
375
+ output_format,
376
+ allocation
377
+ ):
378
+ start = time.time()
379
+ print('restore ==>>')
380
+
381
+ torch.cuda.set_device(SUPIR_device)
382
+
383
+ with torch.no_grad():
384
+ input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=min_size)
385
+ LQ = np.array(input_image) / 255.0
386
+ LQ = np.power(LQ, gamma_correction)
387
+ LQ *= 255.0
388
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
389
+ LQ = LQ / 255 * 2 - 1
390
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
391
+ captions = ['']
392
+
393
+ samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
394
+ s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
395
+ num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
396
+ use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
397
+ cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
398
+
399
+ x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
400
+ 0, 255).astype(np.uint8)
401
+ results = [x_samples[i] for i in range(num_samples)]
402
+ torch.cuda.empty_cache()
403
+
404
+ # All the results have the same size
405
+ input_height, input_width, input_channel = np.array(input_image).shape
406
+ result_height, result_width, result_channel = np.array(results[0]).shape
407
+
408
+ print('<<== restore')
409
+ end = time.time()
410
+ secondes = int(end - start)
411
+ minutes = math.floor(secondes / 60)
412
+ secondes = secondes - (minutes * 60)
413
+ hours = math.floor(minutes / 60)
414
+ minutes = minutes - (hours * 60)
415
+ information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
416
+ "If you don't get the image you wanted, add more details in the « Image description ». " + \
417
+ "Wait " + str(allocation) + " min before a new run to avoid quota penalty or use another computer. " + \
418
+ "The image" + (" has" if len(results) == 1 else "s have") + " been generated in " + \
419
+ ((str(hours) + " h, ") if hours != 0 else "") + \
420
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
421
+ str(secondes) + " sec. " + \
422
+ "The new image resolution is " + str(result_width) + \
423
+ " pixels large and " + str(result_height) + \
424
+ " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
425
+ print(information)
426
+ try:
427
+ print("Initial resolution: " + f'{input_width * input_height:,}')
428
+ print("Final resolution: " + f'{result_width * result_height:,}')
429
+ print("edm_steps: " + str(edm_steps))
430
+ print("num_samples: " + str(num_samples))
431
+ print("downscale: " + str(downscale))
432
+ print("Estimated minutes: " + f'{(((result_width * result_height**(1/1.5)) * input_width * input_height * (edm_steps**(1/2)) * (num_samples**(1/2.5)))**(1/2.5)) / 25000:,}')
433
+ except Exception as e:
434
+ print('Exception of Estimation')
435
+
436
+ # Only one image can be shown in the slider
437
+ return [noisy_image] + [results[0]], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = results), gr.update(value = information, visible = True), gr.update(visible=True)
438
+
439
+ def load_and_reset(param_setting):
440
+ print('load_and_reset ==>>')
441
+ if torch.cuda.device_count() == 0:
442
+ gr.Warning('Set this space to GPU config to make it work.')
443
+ return None, None, None, None, None, None, None, None, None, None, None, None, None, None
444
+ edm_steps = default_setting.edm_steps
445
+ s_stage2 = 1.0
446
+ s_stage1 = -1.0
447
+ s_churn = 5
448
+ s_noise = 1.003
449
+ a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
450
+ 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
451
+ 'detailing, hyper sharpness, perfect without deformations.'
452
+ n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
453
+ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
454
+ 'signature, jpeg artifacts, deformed, lowres, over-smooth'
455
+ color_fix_type = 'Wavelet'
456
+ spt_linear_s_stage2 = 0.0
457
+ linear_s_stage2 = False
458
+ linear_CFG = True
459
+ if param_setting == "Quality":
460
+ s_cfg = default_setting.s_cfg_Quality
461
+ spt_linear_CFG = default_setting.spt_linear_CFG_Quality
462
+ model_select = "v0-Q"
463
+ elif param_setting == "Fidelity":
464
+ s_cfg = default_setting.s_cfg_Fidelity
465
+ spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
466
+ model_select = "v0-F"
467
+ else:
468
+ raise NotImplementedError
469
+ gr.Info('The parameters are reset.')
470
+ print('<<== load_and_reset')
471
+ return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
472
+ linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select
473
+
474
+ def log_information(result_gallery):
475
+ print('log_information')
476
+ if result_gallery is not None:
477
+ for i, result in enumerate(result_gallery):
478
+ print(result[0])
479
+
480
+ def on_select_result(result_slider, result_gallery, evt: gr.SelectData):
481
+ print('on_select_result')
482
+ if result_gallery is not None:
483
+ for i, result in enumerate(result_gallery):
484
+ print(result[0])
485
+ return [result_slider[0], result_gallery[evt.index][0]]
486
+
487
+ title_html = """
488
+ <h1><center>SUPIR</center></h1>
489
+ <big><center>Upscale your images up to x10 freely, without account, without watermark and download it</center></big>
490
+ <center><big><big>🤸<big><big><big><big><big><big>🤸</big></big></big></big></big></big></big></big></center>
491
+
492
+ <p>This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
493
+ It is still a research project under tested and is not yet a stable commercial product.
494
+ The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
495
+ SUPIR is for beauty and illustration only.
496
+ Most of the processes only last few minutes.
497
+ The process will be aborted if it lasts more than 10 min.
498
+ If you want to upscale AI-generated images, be noticed that <i>PixArt Sigma</i> space can directly generate 5984x5984 images.
499
+ Due to Gradio issues, the generated image is slightly less satured than the original.
500
+ Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">message in discussion</a> if you encounter issues.
501
+ You can also use <a href="https://huggingface.co/spaces/gokaygokay/AuraSR">AuraSR</a> to upscale x4.
502
+
503
+ <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://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai">Local Install Guide</a></center></p>
504
+ <p><center><a style="display:inline-block" href='https://github.com/Fanghua-Yu/SUPIR'><img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Fanghua-Yu/SUPIR?style=social"></a></center></p>
505
+ """
506
+
507
+
508
+ claim_md = """
509
+ ## **Piracy**
510
+ The images are not stored but the logs are saved during a month.
511
+ ## **How to get SUPIR**
512
+ You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
513
+ You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
514
+ You can install _Pinokio_ on your computer and then install _SUPIR_ into it. It should be quite easy if you have an Nvidia GPU.
515
+ ## **Terms of use**
516
+ 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.
517
+ ## **License**
518
+ 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.
519
+ """
520
+
521
+ # Gradio interface
522
+ with gr.Blocks() as interface:
523
+ if torch.cuda.device_count() == 0:
524
+ with gr.Row():
525
+ gr.HTML("""
526
+ <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>
527
+
528
+ You can't use SUPIR directly here because this space runs on a CPU, which is not enough for SUPIR. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
529
+ </big></big></big></p>
530
+ """)
531
+ gr.HTML(title_html)
532
+
533
+ input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.jpg, *.gif, *.bmp, *.heic)", show_label=True, type="filepath", height=600, elem_id="image-input")
534
+ rotation = gr.Radio([["No rotation", 0], ["⤵ Rotate +90°", 90], ["↩ Return 180°", 180], ["⤴ Rotate -90°", -90]], label="Orientation correction", info="Will apply the following rotation before restoring the image; the AI needs a good orientation to understand the content", value=0, interactive=True, visible=False)
535
+ with gr.Group():
536
+ prompt = gr.Textbox(label="Image description", info="Help the AI understand what the image represents; describe as much as possible, especially the details we can't see on the original image; you can write in any language", value="", placeholder="A 33 years old man, walking, in the street, Santiago, morning, Summer, photorealistic", lines=3)
537
+ 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.")
538
+ upscale = gr.Radio([["x1", 1], ["x2", 2], ["x3", 3], ["x4", 4], ["x5", 5], ["x6", 6], ["x7", 7], ["x8", 8], ["x9", 9], ["x10", 10]], label="Upscale factor", info="Resolution x1 to x10", value=2, interactive=True)
539
+ 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 (discouraged)", 8], ["9 min (discouraged)", 9], ["10 min (discouraged)", 10]], label="GPU allocation time", info="lower=May abort run, higher=Quota penalty for next runs", value=7, interactive=True)
540
+ output_format = gr.Radio([["As input", "input"], ["*.png", "png"], ["*.webp", "webp"], ["*.jpeg", "jpeg"], ["*.gif", "gif"], ["*.bmp", "bmp"]], label="Image format for result", info="File extention", value="input", interactive=True)
541
+
542
+ with gr.Accordion("Pre-denoising (optional)", open=False):
543
+ gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
544
+ denoise_button = gr.Button(value="Pre-denoise")
545
+ denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], interactive = False, height=600, elem_id="image-s1")
546
+ denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)
547
+
548
+ with gr.Accordion("Advanced options", open=False):
549
+ a_prompt = gr.Textbox(label="Additional image description",
550
+ info="Completes the main image description",
551
+ value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
552
+ 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
553
+ 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, '
554
+ 'hyper sharpness, perfect without deformations.',
555
+ lines=3)
556
+ n_prompt = gr.Textbox(label="Negative image description",
557
+ info="Disambiguate by listing what the image does NOT represent",
558
+ value='painting, oil painting, illustration, drawing, art, sketch, anime, '
559
+ 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, '
560
+ 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
561
+ 'deformed, lowres, over-smooth',
562
+ lines=3)
563
+ 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)
564
+ num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
565
+ , value=1, step=1)
566
+ min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
567
+ downscale = gr.Radio([["/1", 1], ["/2", 2], ["/3", 3], ["/4", 4], ["/5", 5], ["/6", 6], ["/7", 7], ["/8", 8], ["/9", 9], ["/10", 10]], label="Pre-downscale factor", info="Reducing blurred image reduce the process time", value=1, interactive=True)
568
+ with gr.Row():
569
+ with gr.Column():
570
+ model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q",
571
+ interactive=True)
572
+ with gr.Column():
573
+ color_fix_type = gr.Radio([["None", "None"], ["AdaIn (improve as a photo)", "AdaIn"], ["Wavelet (for JPEG artifacts)", "Wavelet"]], label="Color-Fix Type", info="AdaIn=Improve following a style, Wavelet=For JPEG artifacts", value="Wavelet",
574
+ interactive=True)
575
+ s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
576
+ value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
577
+ s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
578
+ s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
579
+ s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
580
+ s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
581
+ with gr.Row():
582
+ with gr.Column():
583
+ linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
584
+ spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
585
+ maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
586
+ with gr.Column():
587
+ linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
588
+ spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
589
+ maximum=1., value=0., step=0.05)
590
+ with gr.Column():
591
+ diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp32",
592
+ interactive=True)
593
+ with gr.Column():
594
+ ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32",
595
+ interactive=True)
596
+ randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
597
+ seed = gr.Slider(label="Seed", minimum=0, maximum=max_64_bit_int, step=1, randomize=True)
598
+ with gr.Group():
599
+ param_setting = gr.Radio(["Quality", "Fidelity"], interactive=True, label="Presetting", value = "Quality")
600
+ restart_button = gr.Button(value="Apply presetting")
601
+
602
+ with gr.Column():
603
+ diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id = "process_button")
604
+ reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
605
+
606
+ restore_information = gr.HTML(value = "Restart the process to get another result.", visible = False)
607
+ result_slider = ImageSlider(label = 'Comparator', show_label = False, interactive = False, elem_id = "slider1", show_download_button = False)
608
+ result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
609
+
610
+ gr.Examples(
611
+ examples = [
612
+ [
613
+ "./Examples/Example1.png",
614
+ 0,
615
+ None,
616
+ "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
617
+ "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.",
618
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
619
+ 2,
620
+ 1024,
621
+ 1,
622
+ 8,
623
+ 200,
624
+ -1,
625
+ 1,
626
+ 7.5,
627
+ False,
628
+ 42,
629
+ 5,
630
+ 1.003,
631
+ "AdaIn",
632
+ "fp16",
633
+ "bf16",
634
+ 1.0,
635
+ True,
636
+ 4,
637
+ False,
638
+ 0.,
639
+ "v0-Q",
640
+ "input",
641
+ 5
642
+ ],
643
+ [
644
+ "./Examples/Example2.jpeg",
645
+ 0,
646
+ None,
647
+ "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
648
+ "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.",
649
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
650
+ 1,
651
+ 1024,
652
+ 1,
653
+ 1,
654
+ 200,
655
+ -1,
656
+ 1,
657
+ 7.5,
658
+ False,
659
+ 42,
660
+ 5,
661
+ 1.003,
662
+ "Wavelet",
663
+ "fp16",
664
+ "bf16",
665
+ 1.0,
666
+ True,
667
+ 4,
668
+ False,
669
+ 0.,
670
+ "v0-Q",
671
+ "input",
672
+ 4
673
+ ],
674
+ [
675
+ "./Examples/Example3.webp",
676
+ 0,
677
+ None,
678
+ "A red apple",
679
+ "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.",
680
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
681
+ 1,
682
+ 1024,
683
+ 1,
684
+ 1,
685
+ 200,
686
+ -1,
687
+ 1,
688
+ 7.5,
689
+ False,
690
+ 42,
691
+ 5,
692
+ 1.003,
693
+ "Wavelet",
694
+ "fp16",
695
+ "bf16",
696
+ 1.0,
697
+ True,
698
+ 4,
699
+ False,
700
+ 0.,
701
+ "v0-Q",
702
+ "input",
703
+ 4
704
+ ],
705
+ [
706
+ "./Examples/Example3.webp",
707
+ 0,
708
+ None,
709
+ "A red marble",
710
+ "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.",
711
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
712
+ 1,
713
+ 1024,
714
+ 1,
715
+ 1,
716
+ 200,
717
+ -1,
718
+ 1,
719
+ 7.5,
720
+ False,
721
+ 42,
722
+ 5,
723
+ 1.003,
724
+ "Wavelet",
725
+ "fp16",
726
+ "bf16",
727
+ 1.0,
728
+ True,
729
+ 4,
730
+ False,
731
+ 0.,
732
+ "v0-Q",
733
+ "input",
734
+ 4
735
+ ],
736
+ ],
737
+ run_on_click = True,
738
+ fn = stage2_process,
739
+ inputs = [
740
+ input_image,
741
+ rotation,
742
+ denoise_image,
743
+ prompt,
744
+ a_prompt,
745
+ n_prompt,
746
+ num_samples,
747
+ min_size,
748
+ downscale,
749
+ upscale,
750
+ edm_steps,
751
+ s_stage1,
752
+ s_stage2,
753
+ s_cfg,
754
+ randomize_seed,
755
+ seed,
756
+ s_churn,
757
+ s_noise,
758
+ color_fix_type,
759
+ diff_dtype,
760
+ ae_dtype,
761
+ gamma_correction,
762
+ linear_CFG,
763
+ linear_s_stage2,
764
+ spt_linear_CFG,
765
+ spt_linear_s_stage2,
766
+ model_select,
767
+ output_format,
768
+ allocation
769
+ ],
770
+ outputs = [
771
+ result_slider,
772
+ result_gallery,
773
+ restore_information,
774
+ reset_btn
775
+ ],
776
+ cache_examples = False,
777
+ )
778
+
779
+ with gr.Row():
780
+ gr.Markdown(claim_md)
781
+
782
+ input_image.upload(fn = check_upload, inputs = [
783
+ input_image
784
+ ], outputs = [
785
+ rotation
786
+ ], queue = False, show_progress = False)
787
+
788
+ denoise_button.click(fn = check, inputs = [
789
+ input_image
790
+ ], outputs = [], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
791
+ input_image,
792
+ gamma_correction,
793
+ diff_dtype,
794
+ ae_dtype
795
+ ], outputs=[
796
+ denoise_image,
797
+ denoise_information
798
+ ])
799
+
800
+ diffusion_button.click(fn = update_seed, inputs = [
801
+ randomize_seed,
802
+ seed
803
+ ], outputs = [
804
+ seed
805
+ ], queue = False, show_progress = False).then(fn = check, inputs = [
806
+ input_image
807
+ ], outputs = [], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
808
+ input_image,
809
+ rotation,
810
+ denoise_image,
811
+ prompt,
812
+ a_prompt,
813
+ n_prompt,
814
+ num_samples,
815
+ min_size,
816
+ downscale,
817
+ upscale,
818
+ edm_steps,
819
+ s_stage1,
820
+ s_stage2,
821
+ s_cfg,
822
+ randomize_seed,
823
+ seed,
824
+ s_churn,
825
+ s_noise,
826
+ color_fix_type,
827
+ diff_dtype,
828
+ ae_dtype,
829
+ gamma_correction,
830
+ linear_CFG,
831
+ linear_s_stage2,
832
+ spt_linear_CFG,
833
+ spt_linear_s_stage2,
834
+ model_select,
835
+ output_format,
836
+ allocation
837
+ ], outputs = [
838
+ result_slider,
839
+ result_gallery,
840
+ restore_information,
841
+ reset_btn
842
+ ]).success(fn = log_information, inputs = [
843
+ result_gallery
844
+ ], outputs = [], queue = False, show_progress = False)
845
+
846
+ result_gallery.change(on_select_result, [result_slider, result_gallery], result_slider)
847
+ result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider)
848
+
849
+ restart_button.click(fn = load_and_reset, inputs = [
850
+ param_setting
851
+ ], outputs = [
852
+ edm_steps,
853
+ s_cfg,
854
+ s_stage2,
855
+ s_stage1,
856
+ s_churn,
857
+ s_noise,
858
+ a_prompt,
859
+ n_prompt,
860
+ color_fix_type,
861
+ linear_CFG,
862
+ linear_s_stage2,
863
+ spt_linear_CFG,
864
+ spt_linear_s_stage2,
865
+ model_select
866
+ ])
867
+
868
+ reset_btn.click(fn = reset, inputs = [], outputs = [
869
+ input_image,
870
+ rotation,
871
+ denoise_image,
872
+ prompt,
873
+ a_prompt,
874
+ n_prompt,
875
+ num_samples,
876
+ min_size,
877
+ downscale,
878
+ upscale,
879
+ edm_steps,
880
+ s_stage1,
881
+ s_stage2,
882
+ s_cfg,
883
+ randomize_seed,
884
+ seed,
885
+ s_churn,
886
+ s_noise,
887
+ color_fix_type,
888
+ diff_dtype,
889
+ ae_dtype,
890
+ gamma_correction,
891
+ linear_CFG,
892
+ linear_s_stage2,
893
+ spt_linear_CFG,
894
+ spt_linear_s_stage2,
895
+ model_select,
896
+ output_format,
897
+ allocation
898
+ ], queue = False, show_progress = False)
899
+
900
  interface.queue(10).launch()