Fabrice-TIERCELIN commited on
Commit
9f28101
·
verified ·
1 Parent(s): fe612dd
Files changed (4) hide show
  1. CKPT_PTH.py +1 -1
  2. README.md +20 -20
  3. app.py +1058 -1063
  4. requirements.txt +42 -41
CKPT_PTH.py CHANGED
@@ -1,2 +1,2 @@
1
- SDXL_CLIP1_PATH = 'openai/clip-vit-large-patch14'
2
  SDXL_CLIP2_CKPT_PTH = 'laion_CLIP-ViT-bigG-14-laion2B-39B-b160k/open_clip_pytorch_model.bin'
 
1
+ SDXL_CLIP1_PATH = 'openai/clip-vit-large-patch14'
2
  SDXL_CLIP2_CKPT_PTH = 'laion_CLIP-ViT-bigG-14-laion2B-39B-b160k/open_clip_pytorch_model.bin'
README.md CHANGED
@@ -1,21 +1,21 @@
1
- ---
2
- title: SUPIR Image Upscaler
3
- sdk: gradio
4
- emoji: 📷
5
- sdk_version: 4.44.1
6
- app_file: app.py
7
- license: mit
8
- colorFrom: blue
9
- colorTo: pink
10
- tags:
11
- - Upscaling
12
- - Restoring
13
- - Image-to-Image
14
- - Image-2-Image
15
- - Img-to-Img
16
- - Img-2-Img
17
- - language models
18
- - LLMs
19
- short_description: Restore blurred or small images with prompt
20
- suggested_hardware: zero-a10g
21
  ---
 
1
+ ---
2
+ title: SUPIR Image Upscaler
3
+ sdk: gradio
4
+ emoji: 📷
5
+ sdk_version: 5.29.1
6
+ app_file: app.py
7
+ license: mit
8
+ colorFrom: blue
9
+ colorTo: pink
10
+ tags:
11
+ - Upscaling
12
+ - Restoring
13
+ - Image-to-Image
14
+ - Image-2-Image
15
+ - Img-to-Img
16
+ - Img-2-Img
17
+ - language models
18
+ - LLMs
19
+ short_description: Restore blurred or small images with prompt
20
+ suggested_hardware: zero-a10g
21
  ---
app.py CHANGED
@@ -1,1063 +1,1058 @@
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
-
12
- try:
13
- import spaces
14
- except:
15
- class spaces():
16
- def GPU(*args, **kwargs):
17
- def decorator(function):
18
- return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
19
- return decorator
20
-
21
- import re
22
- import uuid
23
-
24
- from gradio_imageslider import ImageSlider
25
- from PIL import Image
26
- from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
27
- from huggingface_hub import hf_hub_download
28
- import pillow_heif
29
-
30
- pillow_heif.register_heif_opener()
31
-
32
- max_64_bit_int = np.iinfo(np.int32).max
33
-
34
- 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")
35
- hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
36
- hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
37
- hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
38
- hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
39
-
40
- parser = argparse.ArgumentParser()
41
- parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
42
- parser.add_argument("--ip", type=str, default='127.0.0.1')
43
- parser.add_argument("--port", type=int, default='6688')
44
- parser.add_argument("--no_llava", action='store_true', default=True)#False
45
- parser.add_argument("--use_image_slider", action='store_true', default=False)#False
46
- parser.add_argument("--log_history", action='store_true', default=False)
47
- parser.add_argument("--loading_half_params", action='store_true', default=False)#False
48
- parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
49
- parser.add_argument("--encoder_tile_size", type=int, default=512)
50
- parser.add_argument("--decoder_tile_size", type=int, default=64)
51
- parser.add_argument("--load_8bit_llava", action='store_true', default=False)
52
- args = parser.parse_args()
53
-
54
- if torch.cuda.device_count() > 0:
55
- SUPIR_device = 'cuda:0'
56
-
57
- # Load SUPIR
58
- model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
59
- if args.loading_half_params:
60
- model = model.half()
61
- if args.use_tile_vae:
62
- model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
63
- model = model.to(SUPIR_device)
64
- model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
65
- model.current_model = 'v0-Q'
66
- ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
67
-
68
- def check_upload(input_image):
69
- if input_image is None:
70
- raise gr.Error("Please provide an image to restore.")
71
- return gr.update(visible = True)
72
-
73
- def update_seed(is_randomize_seed, seed):
74
- if is_randomize_seed:
75
- return random.randint(0, max_64_bit_int)
76
- return seed
77
-
78
- def reset():
79
- return [
80
- None,
81
- 0,
82
- None,
83
- None,
84
- "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.",
85
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
86
- 1,
87
- 1024,
88
- 1,
89
- 2,
90
- 50,
91
- -1.0,
92
- 1.,
93
- default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0,
94
- True,
95
- random.randint(0, max_64_bit_int),
96
- 5,
97
- 1.003,
98
- "Wavelet",
99
- "fp32",
100
- "fp32",
101
- 1.0,
102
- True,
103
- False,
104
- default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0,
105
- 0.,
106
- "v0-Q",
107
- "input",
108
- 179
109
- ]
110
-
111
- def check_and_update(input_image):
112
- if input_image is None:
113
- raise gr.Error("Please provide an image to restore.")
114
- return [gr.update(visible = True), gr.update(interactive = True)]
115
-
116
- @spaces.GPU(duration=180)
117
- def stage1_process(
118
- input_image,
119
- gamma_correction,
120
- diff_dtype,
121
- ae_dtype
122
- ):
123
- print('stage1_process ==>>')
124
- if torch.cuda.device_count() == 0:
125
- gr.Warning('Set this space to GPU config to make it work.')
126
- return None, None, gr.update(interactive = False)
127
- torch.cuda.set_device(SUPIR_device)
128
- LQ = HWC3(np.array(Image.open(input_image)))
129
- LQ = fix_resize(LQ, 512)
130
- # stage1
131
- LQ = np.array(LQ) / 255 * 2 - 1
132
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
133
-
134
- model.ae_dtype = convert_dtype(ae_dtype)
135
- model.model.dtype = convert_dtype(diff_dtype)
136
-
137
- LQ = model.batchify_denoise(LQ, is_stage1=True)
138
- LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
139
- # gamma correction
140
- LQ = LQ / 255.0
141
- LQ = np.power(LQ, gamma_correction)
142
- LQ *= 255.0
143
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
144
- print('<<== stage1_process')
145
- return LQ, gr.update(visible = True)
146
-
147
- def stage2_process_example(*args, **kwargs):
148
- [result_slider, result_gallery, restore_information, reset_btn, dummy_button] = restore_in_Xmin(*args, **kwargs)
149
- return [gr.update(visible = True, value=result_slider[1]), restore_information, reset_btn, dummy_button]
150
-
151
- def stage2_process(*args, **kwargs):
152
- try:
153
- return restore_in_Xmin(*args, **kwargs)
154
- except Exception as e:
155
- # NO_GPU_MESSAGE_INQUEUE
156
- print("gradio.exceptions.Error 'No GPU is currently available for you after 60s'")
157
- print('str(type(e)): ' + str(type(e))) # <class 'gradio.exceptions.Error'>
158
- print('str(e): ' + str(e)) # You have exceeded your GPU quota...
159
- try:
160
- print('e.message: ' + e.message) # No GPU is currently available for you after 60s
161
- except Exception as e2:
162
- print('Failure')
163
- if str(e).startswith("No GPU is currently available for you after 60s"):
164
- print('Exception identified!!!')
165
- #if str(type(e)) == "<class 'gradio.exceptions.Error'>":
166
- #print('Exception of name ' + type(e).__name__)
167
- raise e
168
-
169
- def restore_in_Xmin(
170
- noisy_image,
171
- rotation,
172
- denoise_image,
173
- prompt,
174
- a_prompt,
175
- n_prompt,
176
- num_samples,
177
- min_size,
178
- downscale,
179
- upscale,
180
- edm_steps,
181
- s_stage1,
182
- s_stage2,
183
- s_cfg,
184
- randomize_seed,
185
- seed,
186
- s_churn,
187
- s_noise,
188
- color_fix_type,
189
- diff_dtype,
190
- ae_dtype,
191
- gamma_correction,
192
- linear_CFG,
193
- linear_s_stage2,
194
- spt_linear_CFG,
195
- spt_linear_s_stage2,
196
- model_select,
197
- output_format,
198
- allocation
199
- ):
200
- print("noisy_image:\n" + str(noisy_image))
201
- print("denoise_image:\n" + str(denoise_image))
202
- print("rotation: " + str(rotation))
203
- print("prompt: " + str(prompt))
204
- print("a_prompt: " + str(a_prompt))
205
- print("n_prompt: " + str(n_prompt))
206
- print("num_samples: " + str(num_samples))
207
- print("min_size: " + str(min_size))
208
- print("downscale: " + str(downscale))
209
- print("upscale: " + str(upscale))
210
- print("edm_steps: " + str(edm_steps))
211
- print("s_stage1: " + str(s_stage1))
212
- print("s_stage2: " + str(s_stage2))
213
- print("s_cfg: " + str(s_cfg))
214
- print("randomize_seed: " + str(randomize_seed))
215
- print("seed: " + str(seed))
216
- print("s_churn: " + str(s_churn))
217
- print("s_noise: " + str(s_noise))
218
- print("color_fix_type: " + str(color_fix_type))
219
- print("diff_dtype: " + str(diff_dtype))
220
- print("ae_dtype: " + str(ae_dtype))
221
- print("gamma_correction: " + str(gamma_correction))
222
- print("linear_CFG: " + str(linear_CFG))
223
- print("linear_s_stage2: " + str(linear_s_stage2))
224
- print("spt_linear_CFG: " + str(spt_linear_CFG))
225
- print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
226
- print("model_select: " + str(model_select))
227
- print("GPU time allocation: " + str(allocation) + " min")
228
- print("output_format: " + str(output_format))
229
-
230
- input_format = re.sub(r"^.*\.([^\.]+)$", r"\1", noisy_image)
231
-
232
- if input_format not in ['png', 'webp', 'jpg', 'jpeg', 'gif', 'bmp', 'avif']:
233
- gr.Warning('Invalid image format. Please first convert into *.png, *.webp, *.jpg, *.jpeg, *.gif, *.bmp, *.heic or *.avif.')
234
- return None, None, None, None, None, gr.update(interactive = False)
235
-
236
- if output_format == "input":
237
- if noisy_image is None:
238
- output_format = "png"
239
- else:
240
- output_format = input_format
241
- print("final output_format: " + str(output_format))
242
-
243
- if prompt is None:
244
- prompt = ""
245
-
246
- if a_prompt is None:
247
- a_prompt = ""
248
-
249
- if n_prompt is None:
250
- n_prompt = ""
251
-
252
- if prompt != "" and a_prompt != "":
253
- a_prompt = prompt + ", " + a_prompt
254
- else:
255
- a_prompt = prompt + a_prompt
256
- print("Final prompt: " + str(a_prompt))
257
-
258
- denoise_image = np.array(Image.open(noisy_image if denoise_image is None else denoise_image))
259
-
260
- if rotation == 90:
261
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
262
- elif rotation == 180:
263
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
264
- denoise_image = np.array(list(zip(*denoise_image[::-1])))
265
- elif rotation == -90:
266
- denoise_image = np.array(list(zip(*denoise_image))[::-1])
267
-
268
- if 1 < downscale:
269
- input_height, input_width, input_channel = denoise_image.shape
270
- denoise_image = np.array(Image.fromarray(denoise_image).resize((input_width // downscale, input_height // downscale), Image.LANCZOS))
271
-
272
- denoise_image = HWC3(denoise_image)
273
-
274
- if torch.cuda.device_count() == 0:
275
- gr.Warning('Set this space to GPU config to make it work.')
276
- return [noisy_image, denoise_image], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = [denoise_image]), None, gr.update(visible=True)
277
-
278
- if model_select != model.current_model:
279
- print('load ' + model_select)
280
- if model_select == 'v0-Q':
281
- model.load_state_dict(ckpt_Q, strict=False)
282
- elif model_select == 'v0-F':
283
- model.load_state_dict(ckpt_F, strict=False)
284
- model.current_model = model_select
285
-
286
- model.ae_dtype = convert_dtype(ae_dtype)
287
- model.model.dtype = convert_dtype(diff_dtype)
288
-
289
- return restore_on_gpu(
290
- 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
291
- )
292
-
293
- def get_duration(
294
- noisy_image,
295
- input_image,
296
- prompt,
297
- a_prompt,
298
- n_prompt,
299
- num_samples,
300
- min_size,
301
- downscale,
302
- upscale,
303
- edm_steps,
304
- s_stage1,
305
- s_stage2,
306
- s_cfg,
307
- randomize_seed,
308
- seed,
309
- s_churn,
310
- s_noise,
311
- color_fix_type,
312
- diff_dtype,
313
- ae_dtype,
314
- gamma_correction,
315
- linear_CFG,
316
- linear_s_stage2,
317
- spt_linear_CFG,
318
- spt_linear_s_stage2,
319
- model_select,
320
- output_format,
321
- allocation
322
- ):
323
- return allocation
324
-
325
- @spaces.GPU(duration=get_duration)
326
- def restore_on_gpu(
327
- noisy_image,
328
- input_image,
329
- prompt,
330
- a_prompt,
331
- n_prompt,
332
- num_samples,
333
- min_size,
334
- downscale,
335
- upscale,
336
- edm_steps,
337
- s_stage1,
338
- s_stage2,
339
- s_cfg,
340
- randomize_seed,
341
- seed,
342
- s_churn,
343
- s_noise,
344
- color_fix_type,
345
- diff_dtype,
346
- ae_dtype,
347
- gamma_correction,
348
- linear_CFG,
349
- linear_s_stage2,
350
- spt_linear_CFG,
351
- spt_linear_s_stage2,
352
- model_select,
353
- output_format,
354
- allocation
355
- ):
356
- start = time.time()
357
- print('restore ==>>')
358
-
359
- torch.cuda.set_device(SUPIR_device)
360
-
361
- with torch.no_grad():
362
- input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=min_size)
363
- LQ = np.array(input_image) / 255.0
364
- LQ = np.power(LQ, gamma_correction)
365
- LQ *= 255.0
366
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
367
- LQ = LQ / 255 * 2 - 1
368
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
369
- captions = ['']
370
-
371
- samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
372
- s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
373
- num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
374
- use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
375
- cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
376
-
377
- x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
378
- 0, 255).astype(np.uint8)
379
- results = [x_samples[i] for i in range(num_samples)]
380
- torch.cuda.empty_cache()
381
-
382
- # All the results have the same size
383
- input_height, input_width, input_channel = np.array(input_image).shape
384
- result_height, result_width, result_channel = np.array(results[0]).shape
385
-
386
- print('<<== restore')
387
- end = time.time()
388
- secondes = int(end - start)
389
- minutes = math.floor(secondes / 60)
390
- secondes = secondes - (minutes * 60)
391
- hours = math.floor(minutes / 60)
392
- minutes = minutes - (hours * 60)
393
- information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
394
- "If you don't get the image you wanted, add more details in the « Image description ». " + \
395
- "The image" + (" has" if len(results) == 1 else "s have") + " been generated in " + \
396
- ((str(hours) + " h, ") if hours != 0 else "") + \
397
- ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
398
- str(secondes) + " sec. " + \
399
- "The new image resolution is " + str(result_width) + \
400
- " pixels large and " + str(result_height) + \
401
- " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
402
- print(information)
403
- try:
404
- print("Initial resolution: " + f'{input_width * input_height:,}')
405
- print("Final resolution: " + f'{result_width * result_height:,}')
406
- print("edm_steps: " + str(edm_steps))
407
- print("num_samples: " + str(num_samples))
408
- print("downscale: " + str(downscale))
409
- print("Estimated minutes: " + f'{(((result_width * result_height**(1/1.75)) * input_width * input_height * (edm_steps**(1/2)) * (num_samples**(1/2.5)))**(1/2.5)) / 25000:,}')
410
- except Exception as e:
411
- print('Exception of Estimation')
412
-
413
- # Only one image can be shown in the slider
414
- 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), gr.update(visible=False), gr.update(interactive = False)
415
-
416
- def load_and_reset(param_setting):
417
- print('load_and_reset ==>>')
418
- if torch.cuda.device_count() == 0:
419
- gr.Warning('Set this space to GPU config to make it work.')
420
- return None, None, None, None, None, None, None, None, None, None, None, None, None, None
421
- edm_steps = default_setting.edm_steps
422
- s_stage2 = 1.0
423
- s_stage1 = -1.0
424
- s_churn = 5
425
- s_noise = 1.003
426
- a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
427
- 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
428
- 'detailing, hyper sharpness, perfect without deformations.'
429
- n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
430
- '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
431
- 'signature, jpeg artifacts, deformed, lowres, over-smooth'
432
- color_fix_type = 'Wavelet'
433
- spt_linear_s_stage2 = 0.0
434
- linear_s_stage2 = False
435
- linear_CFG = True
436
- if param_setting == "Quality":
437
- s_cfg = default_setting.s_cfg_Quality
438
- spt_linear_CFG = default_setting.spt_linear_CFG_Quality
439
- model_select = "v0-Q"
440
- elif param_setting == "Fidelity":
441
- s_cfg = default_setting.s_cfg_Fidelity
442
- spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
443
- model_select = "v0-F"
444
- else:
445
- raise NotImplementedError
446
- gr.Info('The parameters are reset.')
447
- print('<<== load_and_reset')
448
- return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
449
- linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select
450
-
451
- def log_information(result_gallery):
452
- print('log_information')
453
- if result_gallery is not None:
454
- for i, result in enumerate(result_gallery):
455
- print(result[0])
456
-
457
- def on_select_result(result_slider, result_gallery, evt: gr.SelectData):
458
- print('on_select_result')
459
- if result_gallery is not None:
460
- for i, result in enumerate(result_gallery):
461
- print(result[0])
462
- return [result_slider[0], result_gallery[evt.index][0]]
463
-
464
- title_html = """
465
- <h1><center>SUPIR</center></h1>
466
- <big><center>Upscale your images up to x10 freely, without account, without watermark and download it</center></big>
467
- <center><big><big>🤸<big><big><big><big><big><big>🤸</big></big></big></big></big></big></big></big></center>
468
-
469
- <p>This is an online demo of SUPIR, a practicing model scaling for photo-realistic image restoration.
470
- The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
471
- SUPIR is for beauty and illustration only.
472
- Most of the processes last few minutes.
473
- If you want to upscale AI-generated images, be noticed that <i>PixArt Sigma</i> space can directly generate 5984x5984 images.
474
- Due to Gradio issues, the generated image is slightly less satured than the original.
475
- Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">message in discussion</a> if you encounter issues.
476
- You can also use <a href="https://huggingface.co/spaces/gokaygokay/AuraSR">AuraSR</a> to upscale x4.
477
-
478
- <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>
479
- <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>
480
- """
481
-
482
-
483
- claim_md = """
484
- ## **Piracy**
485
- The images are not stored but the logs are saved during a month.
486
- ## **How to get SUPIR**
487
- You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
488
- You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
489
- You can install _Pinokio_ on your computer and then install _SUPIR_ into it. It should be quite easy if you have an Nvidia GPU.
490
- ## **Terms of use**
491
- 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.
492
- ## **License**
493
- 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.
494
- """
495
-
496
- js = """
497
- function createGradioAnimation() {
498
- window.addEventListener("beforeunload", function(e) {
499
- if (document.getElementById('dummy_button_id') && !document.getElementById('dummy_button_id').disabled) {
500
- var confirmationMessage = 'A process is still running. '
501
- + 'If you leave before saving, your changes will be lost.';
502
-
503
- (e || window.event).returnValue = confirmationMessage;
504
- }
505
- return confirmationMessage;
506
- });
507
- return 'Animation created';
508
- }
509
- """
510
-
511
- # Gradio interface
512
- with gr.Blocks(js=js) as interface:
513
- if torch.cuda.device_count() == 0:
514
- with gr.Row():
515
- gr.HTML("""
516
- <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>
517
-
518
- 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.
519
- </big></big></big></p>
520
- """)
521
- gr.HTML(title_html)
522
-
523
- input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.jpg, *.gif, *.bmp, *.avif)", show_label=True, type="filepath", height=600, elem_id="image-input")
524
- 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, visible=False)
525
- with gr.Group():
526
- 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)
527
- prompt_hint = gr.HTML("You can use a <a href='"'https://huggingface.co/spaces/badayvedat/LLaVA'"'>LlaVa space</a> to auto-generate the description of your image.")
528
- 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)
529
- 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")
530
- allocation = gr.Slider(label="GPU allocation time (in seconds)", info='lower=May abort run, higher=Quota penalty for next runs; only useful for ZeroGPU; for instance set to 88 when you have the message "You have exceeded your GPU quota (180s requested vs. 89s left)."', value=180, minimum=60, maximum=320, step=1)
531
-
532
- with gr.Accordion("Pre-denoising (optional)", open=False):
533
- gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
534
- denoise_button = gr.Button(value="Pre-denoise")
535
- denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], interactive = False, height=600, elem_id="image-s1")
536
- denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)
537
-
538
- with gr.Accordion("Advanced options", open=False):
539
- a_prompt = gr.Textbox(label="Additional image description",
540
- info="Completes the main image description",
541
- value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
542
- 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
543
- 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, clothing fabric detailing, '
544
- 'hyper sharpness, perfect without deformations.',
545
- lines=3)
546
- n_prompt = gr.Textbox(label="Negative image description",
547
- info="Disambiguate by listing what the image does NOT represent",
548
- value='painting, oil painting, illustration, drawing, art, sketch, anime, '
549
- 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, '
550
- 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
551
- 'deformed, lowres, over-smooth',
552
- lines=3)
553
- edm_steps = gr.Slider(label="Steps", info="lower=faster, higher=more details; too many steps create a checker effect", minimum=1, maximum=200, value=default_setting.edm_steps if torch.cuda.device_count() > 0 else 1, step=1)
554
- num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
555
- , value=1, step=1)
556
- min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
557
- 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)
558
- with gr.Row():
559
- with gr.Column():
560
- model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q")
561
- with gr.Column():
562
- 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="AdaIn")
563
- s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
564
- value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
565
- s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
566
- s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
567
- s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
568
- s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
569
- with gr.Row():
570
- with gr.Column():
571
- linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
572
- spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
573
- maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
574
- with gr.Column():
575
- linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
576
- spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
577
- maximum=1., value=0., step=0.05)
578
- with gr.Column():
579
- diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp32")
580
- with gr.Column():
581
- ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32")
582
- randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
583
- seed = gr.Slider(label="Seed", minimum=0, maximum=max_64_bit_int, step=1, randomize=True)
584
- with gr.Group():
585
- param_setting = gr.Radio(["Quality", "Fidelity"], label="Presetting", value = "Quality")
586
- restart_button = gr.Button(value="Apply presetting")
587
-
588
- with gr.Column():
589
- diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id = "process_button")
590
- reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
591
- dummy_button = gr.Button(elem_id = "dummy_button_id", visible = False, interactive = False)
592
-
593
- warning = gr.HTML(elem_id="warning", value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
594
- restore_information = gr.HTML(value = "Restart the process to get another result.", visible = False)
595
- result_slider = ImageSlider(label = 'Comparator', show_label = False, interactive = False, elem_id = "slider1", show_download_button = False)
596
- result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
597
- result_example = gr.Image(label="Example Image", visible = False, interactive = False)
598
-
599
- with gr.Row(elem_id="examples", visible=False):
600
- gr.Examples(
601
- examples = [
602
- [
603
- "./Examples/Example2.jpeg",
604
- 0,
605
- None,
606
- "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
607
- "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.",
608
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
609
- 1,
610
- 1024,
611
- 1,
612
- 1,
613
- 200,
614
- -1,
615
- 1,
616
- 7.5,
617
- False,
618
- 42,
619
- 5,
620
- 1.003,
621
- "Wavelet",
622
- "fp16",
623
- "bf16",
624
- 1.0,
625
- True,
626
- 4,
627
- False,
628
- 0.,
629
- "v0-Q",
630
- "input",
631
- 50
632
- ],
633
- [
634
- "./Examples/Example1.png",
635
- 0,
636
- None,
637
- "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
638
- "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.",
639
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
640
- 2,
641
- 1024,
642
- 1,
643
- 8,
644
- 100,
645
- -1,
646
- 1,
647
- 7.5,
648
- False,
649
- 42,
650
- 5,
651
- 1.003,
652
- "AdaIn",
653
- "fp16",
654
- "bf16",
655
- 1.0,
656
- True,
657
- 4,
658
- False,
659
- 0.,
660
- "v0-Q",
661
- "input",
662
- 180
663
- ],
664
- [
665
- "./Examples/Example3.webp",
666
- 0,
667
- None,
668
- "A red apple",
669
- "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.",
670
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
671
- 1,
672
- 1024,
673
- 1,
674
- 1,
675
- 200,
676
- -1,
677
- 1,
678
- 7.5,
679
- False,
680
- 42,
681
- 5,
682
- 1.003,
683
- "Wavelet",
684
- "fp16",
685
- "bf16",
686
- 1.0,
687
- True,
688
- 4,
689
- False,
690
- 0.,
691
- "v0-Q",
692
- "input",
693
- 180
694
- ],
695
- [
696
- "./Examples/Example3.webp",
697
- 0,
698
- None,
699
- "A red marble",
700
- "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.",
701
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
702
- 1,
703
- 1024,
704
- 1,
705
- 1,
706
- 200,
707
- -1,
708
- 1,
709
- 7.5,
710
- False,
711
- 42,
712
- 5,
713
- 1.003,
714
- "Wavelet",
715
- "fp16",
716
- "bf16",
717
- 1.0,
718
- True,
719
- 4,
720
- False,
721
- 0.,
722
- "v0-Q",
723
- "input",
724
- 180
725
- ],
726
- ],
727
- run_on_click = True,
728
- fn = stage2_process_example,
729
- inputs = [
730
- input_image,
731
- rotation,
732
- denoise_image,
733
- prompt,
734
- a_prompt,
735
- n_prompt,
736
- num_samples,
737
- min_size,
738
- downscale,
739
- upscale,
740
- edm_steps,
741
- s_stage1,
742
- s_stage2,
743
- s_cfg,
744
- randomize_seed,
745
- seed,
746
- s_churn,
747
- s_noise,
748
- color_fix_type,
749
- diff_dtype,
750
- ae_dtype,
751
- gamma_correction,
752
- linear_CFG,
753
- linear_s_stage2,
754
- spt_linear_CFG,
755
- spt_linear_s_stage2,
756
- model_select,
757
- output_format,
758
- allocation
759
- ],
760
- outputs = [
761
- result_example,
762
- restore_information,
763
- reset_btn
764
- ],
765
- cache_examples = "lazy",
766
- )
767
-
768
- gr.Examples(
769
- label = "Examples for demo",
770
- examples = [
771
- [
772
- "./Examples/Example1.png",
773
- 0,
774
- "./Examples/Example1.png",
775
- "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
776
- "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.",
777
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
778
- 2,
779
- 1024,
780
- 1,
781
- 8,
782
- 100,
783
- -1,
784
- 1,
785
- 7.5,
786
- False,
787
- 42,
788
- 5,
789
- 1.003,
790
- "AdaIn",
791
- "fp16",
792
- "bf16",
793
- 1.0,
794
- True,
795
- 4,
796
- False,
797
- 0.,
798
- "v0-Q",
799
- "input",
800
- 180
801
- ],
802
- [
803
- "./Examples/Example2.jpeg",
804
- 0,
805
- "./Examples/Example2.jpeg",
806
- "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
807
- "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.",
808
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
809
- 1,
810
- 1024,
811
- 1,
812
- 1,
813
- 100,
814
- -1,
815
- 1,
816
- 7.5,
817
- False,
818
- 42,
819
- 5,
820
- 1.003,
821
- "Wavelet",
822
- "fp16",
823
- "bf16",
824
- 1.0,
825
- True,
826
- 4,
827
- False,
828
- 0.,
829
- "v0-Q",
830
- "input",
831
- 50
832
- ],
833
- [
834
- "./Examples/Example3.webp",
835
- 0,
836
- "./Examples/Example3.webp",
837
- "A red apple",
838
- "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.",
839
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
840
- 1,
841
- 1024,
842
- 1,
843
- 1,
844
- 200,
845
- -1,
846
- 1,
847
- 7.5,
848
- False,
849
- 42,
850
- 5,
851
- 1.003,
852
- "Wavelet",
853
- "fp16",
854
- "bf16",
855
- 1.0,
856
- True,
857
- 4,
858
- False,
859
- 0.,
860
- "v0-Q",
861
- "input",
862
- 180
863
- ],
864
- [
865
- "./Examples/Example3.webp",
866
- 0,
867
- "./Examples/Example3.webp",
868
- "A red marble",
869
- "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.",
870
- "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
871
- 1,
872
- 1024,
873
- 1,
874
- 1,
875
- 200,
876
- -1,
877
- 1,
878
- 7.5,
879
- False,
880
- 42,
881
- 5,
882
- 1.003,
883
- "Wavelet",
884
- "fp16",
885
- "bf16",
886
- 1.0,
887
- True,
888
- 4,
889
- False,
890
- 0.,
891
- "v0-Q",
892
- "input",
893
- 180
894
- ],
895
- ],
896
- run_on_click = True,
897
- fn = stage2_process,
898
- inputs = [
899
- input_image,
900
- rotation,
901
- denoise_image,
902
- prompt,
903
- a_prompt,
904
- n_prompt,
905
- num_samples,
906
- min_size,
907
- downscale,
908
- upscale,
909
- edm_steps,
910
- s_stage1,
911
- s_stage2,
912
- s_cfg,
913
- randomize_seed,
914
- seed,
915
- s_churn,
916
- s_noise,
917
- color_fix_type,
918
- diff_dtype,
919
- ae_dtype,
920
- gamma_correction,
921
- linear_CFG,
922
- linear_s_stage2,
923
- spt_linear_CFG,
924
- spt_linear_s_stage2,
925
- model_select,
926
- output_format,
927
- allocation
928
- ],
929
- outputs = [
930
- result_slider,
931
- result_gallery,
932
- restore_information,
933
- reset_btn,
934
- dummy_button
935
- ],
936
- cache_examples = False,
937
- )
938
-
939
- with gr.Row():
940
- gr.Markdown(claim_md)
941
-
942
- input_image.upload(fn = check_upload, inputs = [
943
- input_image
944
- ], outputs = [
945
- rotation
946
- ], queue = False, show_progress = False)
947
-
948
- denoise_button.click(fn = check_and_update, inputs = [
949
- input_image
950
- ], outputs = [warning, dummy_button], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
951
- input_image,
952
- gamma_correction,
953
- diff_dtype,
954
- ae_dtype
955
- ], outputs=[
956
- denoise_image,
957
- denoise_information,
958
- dummy_button
959
- ])
960
-
961
- diffusion_button.click(fn = update_seed, inputs = [
962
- randomize_seed,
963
- seed
964
- ], outputs = [
965
- seed
966
- ], queue = False, show_progress = False).then(fn = check_and_update, inputs = [
967
- input_image
968
- ], outputs = [warning, dummy_button], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
969
- input_image,
970
- rotation,
971
- denoise_image,
972
- prompt,
973
- a_prompt,
974
- n_prompt,
975
- num_samples,
976
- min_size,
977
- downscale,
978
- upscale,
979
- edm_steps,
980
- s_stage1,
981
- s_stage2,
982
- s_cfg,
983
- randomize_seed,
984
- seed,
985
- s_churn,
986
- s_noise,
987
- color_fix_type,
988
- diff_dtype,
989
- ae_dtype,
990
- gamma_correction,
991
- linear_CFG,
992
- linear_s_stage2,
993
- spt_linear_CFG,
994
- spt_linear_s_stage2,
995
- model_select,
996
- output_format,
997
- allocation
998
- ], outputs = [
999
- result_slider,
1000
- result_gallery,
1001
- restore_information,
1002
- reset_btn,
1003
- warning,
1004
- dummy_button
1005
- ]).success(fn = log_information, inputs = [
1006
- result_gallery
1007
- ], outputs = [], queue = False, show_progress = False)
1008
-
1009
- result_gallery.change(on_select_result, [result_slider, result_gallery], result_slider)
1010
- result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider)
1011
-
1012
- restart_button.click(fn = load_and_reset, inputs = [
1013
- param_setting
1014
- ], outputs = [
1015
- edm_steps,
1016
- s_cfg,
1017
- s_stage2,
1018
- s_stage1,
1019
- s_churn,
1020
- s_noise,
1021
- a_prompt,
1022
- n_prompt,
1023
- color_fix_type,
1024
- linear_CFG,
1025
- linear_s_stage2,
1026
- spt_linear_CFG,
1027
- spt_linear_s_stage2,
1028
- model_select
1029
- ])
1030
-
1031
- reset_btn.click(fn = reset, inputs = [], outputs = [
1032
- input_image,
1033
- rotation,
1034
- denoise_image,
1035
- prompt,
1036
- a_prompt,
1037
- n_prompt,
1038
- num_samples,
1039
- min_size,
1040
- downscale,
1041
- upscale,
1042
- edm_steps,
1043
- s_stage1,
1044
- s_stage2,
1045
- s_cfg,
1046
- randomize_seed,
1047
- seed,
1048
- s_churn,
1049
- s_noise,
1050
- color_fix_type,
1051
- diff_dtype,
1052
- ae_dtype,
1053
- gamma_correction,
1054
- linear_CFG,
1055
- linear_s_stage2,
1056
- spt_linear_CFG,
1057
- spt_linear_s_stage2,
1058
- model_select,
1059
- output_format,
1060
- allocation
1061
- ], queue = False, show_progress = False)
1062
-
1063
- 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
+ from datetime import datetime
12
+
13
+ try:
14
+ import spaces
15
+ except:
16
+ class spaces():
17
+ def GPU(*args, **kwargs):
18
+ def decorator(function):
19
+ return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
20
+ return decorator
21
+
22
+ import re
23
+ import uuid
24
+
25
+ from gradio_imageslider import ImageSlider
26
+ from PIL import Image
27
+ import imageio.v3 as iio
28
+ from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype, create_SUPIR_model, load_QF_ckpt
29
+ from huggingface_hub import hf_hub_download
30
+ import pillow_heif
31
+
32
+ pillow_heif.register_heif_opener()
33
+
34
+ max_64_bit_int = np.iinfo(np.int32).max
35
+
36
+ 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")
37
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="sd_xl_base_1.0_0.9vae.safetensors", local_dir="yushan777_SUPIR")
38
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0F.ckpt", local_dir="yushan777_SUPIR")
39
+ hf_hub_download(repo_id="camenduru/SUPIR", filename="SUPIR-v0Q.ckpt", local_dir="yushan777_SUPIR")
40
+ hf_hub_download(repo_id="RunDiffusion/Juggernaut-XL-Lightning", filename="Juggernaut_RunDiffusionPhoto2_Lightning_4Steps.safetensors", local_dir="RunDiffusion_Juggernaut-XL-Lightning")
41
+
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
44
+ parser.add_argument("--ip", type=str, default='127.0.0.1')
45
+ parser.add_argument("--port", type=int, default='6688')
46
+ parser.add_argument("--no_llava", action='store_true', default=True)#False
47
+ parser.add_argument("--use_image_slider", action='store_true', default=False)#False
48
+ parser.add_argument("--log_history", action='store_true', default=False)
49
+ parser.add_argument("--loading_half_params", action='store_true', default=False)#False
50
+ parser.add_argument("--use_tile_vae", action='store_true', default=True)#False
51
+ parser.add_argument("--encoder_tile_size", type=int, default=512)
52
+ parser.add_argument("--decoder_tile_size", type=int, default=64)
53
+ parser.add_argument("--load_8bit_llava", action='store_true', default=False)
54
+ args = parser.parse_args()
55
+
56
+ input_image_debug_value = [None]
57
+ prompt_debug_value = [None]
58
+ upscale_debug_value = [None]
59
+
60
+ if torch.cuda.device_count() > 0:
61
+ SUPIR_device = 'cuda:0'
62
+
63
+ # Load SUPIR
64
+ model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
65
+ if args.loading_half_params:
66
+ model = model.half()
67
+ if args.use_tile_vae:
68
+ model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
69
+ model = model.to(SUPIR_device)
70
+ model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
71
+ model.current_model = 'v0-Q'
72
+ ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
73
+
74
+ def check_upload(input_image):
75
+ if input_image is None:
76
+ raise gr.Error("Please provide an image to restore.")
77
+ return gr.update(visible = True)
78
+
79
+ def update_seed(is_randomize_seed, seed):
80
+ if is_randomize_seed:
81
+ return random.randint(0, max_64_bit_int)
82
+ return seed
83
+
84
+ def reset():
85
+ return [
86
+ None,
87
+ 0,
88
+ None,
89
+ None,
90
+ "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.",
91
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
92
+ 1,
93
+ 1024,
94
+ 1,
95
+ 2,
96
+ 50,
97
+ -1.0,
98
+ 1.,
99
+ default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0,
100
+ True,
101
+ random.randint(0, max_64_bit_int),
102
+ 5,
103
+ 1.003,
104
+ "Wavelet",
105
+ "fp32",
106
+ "fp32",
107
+ 1.0,
108
+ True,
109
+ default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0,
110
+ False,
111
+ 0.,
112
+ "v0-Q",
113
+ "input",
114
+ 179
115
+ ]
116
+
117
+ def check_and_update(input_image):
118
+ if input_image is None:
119
+ raise gr.Error("Please provide an image to restore.")
120
+ return [gr.update(visible = True), gr.update(interactive = True)]
121
+
122
+ @spaces.GPU(duration=180)
123
+ def stage1_process(
124
+ input_image,
125
+ gamma_correction,
126
+ diff_dtype,
127
+ ae_dtype
128
+ ):
129
+ print('stage1_process ==>>')
130
+ if torch.cuda.device_count() == 0:
131
+ gr.Warning('Set this space to GPU config to make it work.')
132
+ return None, None, gr.update(interactive = False)
133
+ torch.cuda.set_device(SUPIR_device)
134
+ LQ = HWC3(np.array(Image.open(input_image)))
135
+ LQ = fix_resize(LQ, 512)
136
+ # stage1
137
+ LQ = np.array(LQ) / 255 * 2 - 1
138
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
139
+
140
+ model.ae_dtype = convert_dtype(ae_dtype)
141
+ model.model.dtype = convert_dtype(diff_dtype)
142
+
143
+ LQ = model.batchify_denoise(LQ, is_stage1=True)
144
+ LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
145
+ # gamma correction
146
+ LQ = LQ / 255.0
147
+ LQ = np.power(LQ, gamma_correction)
148
+ LQ *= 255.0
149
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
150
+ print('<<== stage1_process')
151
+ return LQ, gr.update(visible = True)
152
+
153
+ def stage2_process_example(*args, **kwargs):
154
+ [result_slider, result_gallery, restore_information, reset_btn, warning, dummy_button] = restore_in_Xmin(*args, **kwargs)
155
+ #outputs_folder = './outputs/'
156
+ outputs_folder = './tmp/'
157
+ os.makedirs(outputs_folder, exist_ok=True)
158
+ output_filename = os.path.join(outputs_folder, datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + '.png')
159
+ print(output_filename)
160
+ iio.imwrite(output_filename, result_slider[1], format="png")
161
+ return [gr.update(visible = True, value=output_filename), warning, dummy_button, gr.skip()]
162
+
163
+ def stage2_process(*args, **kwargs):
164
+ try:
165
+ return restore_in_Xmin(*args, **kwargs)
166
+ except Exception as e:
167
+ # NO_GPU_MESSAGE_INQUEUE
168
+ print("gradio.exceptions.Error 'No GPU is currently available for you after 60s'")
169
+ print('str(type(e)): ' + str(type(e))) # <class 'gradio.exceptions.Error'>
170
+ print('str(e): ' + str(e)) # You have exceeded your GPU quota...
171
+ try:
172
+ print('e.message: ' + e.message) # No GPU is currently available for you after 60s
173
+ except Exception as e2:
174
+ print('Failure')
175
+ if str(e).startswith("No GPU is currently available for you after 60s"):
176
+ print('Exception identified!!!')
177
+ #if str(type(e)) == "<class 'gradio.exceptions.Error'>":
178
+ #print('Exception of name ' + type(e).__name__)
179
+ raise e
180
+
181
+ def restore_in_Xmin(
182
+ noisy_image,
183
+ rotation,
184
+ denoise_image,
185
+ prompt,
186
+ a_prompt,
187
+ n_prompt,
188
+ num_samples,
189
+ min_size,
190
+ downscale,
191
+ upscale,
192
+ edm_steps,
193
+ s_stage1,
194
+ s_stage2,
195
+ s_cfg,
196
+ randomize_seed,
197
+ seed,
198
+ s_churn,
199
+ s_noise,
200
+ color_fix_type,
201
+ diff_dtype,
202
+ ae_dtype,
203
+ gamma_correction,
204
+ linear_CFG,
205
+ spt_linear_CFG,
206
+ linear_s_stage2,
207
+ spt_linear_s_stage2,
208
+ model_select,
209
+ output_format,
210
+ allocation
211
+ ):
212
+ print("noisy_image:\n" + str(noisy_image))
213
+ print("denoise_image:\n" + str(denoise_image))
214
+ print("rotation: " + str(rotation))
215
+ print("prompt: " + str(prompt))
216
+ print("a_prompt: " + str(a_prompt))
217
+ print("n_prompt: " + str(n_prompt))
218
+ print("num_samples: " + str(num_samples))
219
+ print("min_size: " + str(min_size))
220
+ print("downscale: " + str(downscale))
221
+ print("upscale: " + str(upscale))
222
+ print("edm_steps: " + str(edm_steps))
223
+ print("s_stage1: " + str(s_stage1))
224
+ print("s_stage2: " + str(s_stage2))
225
+ print("s_cfg: " + str(s_cfg))
226
+ print("randomize_seed: " + str(randomize_seed))
227
+ print("seed: " + str(seed))
228
+ print("s_churn: " + str(s_churn))
229
+ print("s_noise: " + str(s_noise))
230
+ print("color_fix_type: " + str(color_fix_type))
231
+ print("diff_dtype: " + str(diff_dtype))
232
+ print("ae_dtype: " + str(ae_dtype))
233
+ print("gamma_correction: " + str(gamma_correction))
234
+ print("linear_CFG: " + str(linear_CFG))
235
+ print("linear_s_stage2: " + str(linear_s_stage2))
236
+ print("spt_linear_CFG: " + str(spt_linear_CFG))
237
+ print("spt_linear_s_stage2: " + str(spt_linear_s_stage2))
238
+ print("model_select: " + str(model_select))
239
+ print("GPU time allocation: " + str(allocation) + " min")
240
+ print("output_format: " + str(output_format))
241
+
242
+ if input_image_debug_value[0] is not None or prompt_debug_value[0] is not None or upscale_debug_value[0] is not None:
243
+ denoise_image = noisy_image = input_image_debug_value[0]
244
+ a_prompt = prompt_debug_value[0]
245
+ upscale = upscale_debug_value[0]
246
+ allocation = min(allocation * 60 * 100, 600)
247
+ seed = random.randint(0, max_64_bit_int)
248
+
249
+ input_format = re.sub(r"^.*\.([^\.]+)$", r"\1", noisy_image)
250
+
251
+ if input_format not in ['png', 'webp', 'jpg', 'jpeg', 'gif', 'bmp', 'avif']:
252
+ gr.Warning('Invalid image format. Please first convert into *.png, *.webp, *.jpg, *.jpeg, *.gif, *.bmp, *.heic or *.avif.')
253
+ return None, None, None, None, None, gr.update(interactive = False)
254
+
255
+ if output_format == "input":
256
+ if noisy_image is None:
257
+ output_format = "png"
258
+ else:
259
+ output_format = input_format
260
+ print("final output_format: " + str(output_format))
261
+
262
+ if prompt is None:
263
+ prompt = ""
264
+
265
+ if a_prompt is None:
266
+ a_prompt = ""
267
+
268
+ if n_prompt is None:
269
+ n_prompt = ""
270
+
271
+ if prompt != "" and a_prompt != "":
272
+ a_prompt = prompt + ", " + a_prompt
273
+ else:
274
+ a_prompt = prompt + a_prompt
275
+ print("Final prompt: " + str(a_prompt))
276
+
277
+ denoise_image = np.array(Image.open(noisy_image if denoise_image is None else denoise_image))
278
+
279
+ if rotation == 90:
280
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
281
+ elif rotation == 180:
282
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
283
+ denoise_image = np.array(list(zip(*denoise_image[::-1])))
284
+ elif rotation == -90:
285
+ denoise_image = np.array(list(zip(*denoise_image))[::-1])
286
+
287
+ if 1 < downscale:
288
+ input_height, input_width, input_channel = denoise_image.shape
289
+ denoise_image = np.array(Image.fromarray(denoise_image).resize((input_width // downscale, input_height // downscale), Image.LANCZOS))
290
+
291
+ denoise_image = HWC3(denoise_image)
292
+
293
+ if torch.cuda.device_count() == 0:
294
+ gr.Warning('Set this space to GPU config to make it work.')
295
+ return [noisy_image, denoise_image], gr.update(label="Downloadable results in *." + output_format + " format", format = output_format, value = [denoise_image]), None, gr.update(visible=True)
296
+
297
+ if model_select != model.current_model:
298
+ print('load ' + model_select)
299
+ if model_select == 'v0-Q':
300
+ model.load_state_dict(ckpt_Q, strict=False)
301
+ elif model_select == 'v0-F':
302
+ model.load_state_dict(ckpt_F, strict=False)
303
+ model.current_model = model_select
304
+
305
+ model.ae_dtype = convert_dtype(ae_dtype)
306
+ model.model.dtype = convert_dtype(diff_dtype)
307
+
308
+ return restore_on_gpu(
309
+ 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
310
+ )
311
+
312
+ def get_duration(
313
+ noisy_image,
314
+ input_image,
315
+ prompt,
316
+ a_prompt,
317
+ n_prompt,
318
+ num_samples,
319
+ min_size,
320
+ downscale,
321
+ upscale,
322
+ edm_steps,
323
+ s_stage1,
324
+ s_stage2,
325
+ s_cfg,
326
+ randomize_seed,
327
+ seed,
328
+ s_churn,
329
+ s_noise,
330
+ color_fix_type,
331
+ diff_dtype,
332
+ ae_dtype,
333
+ gamma_correction,
334
+ linear_CFG,
335
+ spt_linear_CFG,
336
+ linear_s_stage2,
337
+ spt_linear_s_stage2,
338
+ model_select,
339
+ output_format,
340
+ allocation
341
+ ):
342
+ return allocation
343
+
344
+ @spaces.GPU(duration=get_duration)
345
+ def restore_on_gpu(
346
+ noisy_image,
347
+ input_image,
348
+ prompt,
349
+ a_prompt,
350
+ n_prompt,
351
+ num_samples,
352
+ min_size,
353
+ downscale,
354
+ upscale,
355
+ edm_steps,
356
+ s_stage1,
357
+ s_stage2,
358
+ s_cfg,
359
+ randomize_seed,
360
+ seed,
361
+ s_churn,
362
+ s_noise,
363
+ color_fix_type,
364
+ diff_dtype,
365
+ ae_dtype,
366
+ gamma_correction,
367
+ linear_CFG,
368
+ spt_linear_CFG,
369
+ linear_s_stage2,
370
+ spt_linear_s_stage2,
371
+ model_select,
372
+ output_format,
373
+ allocation
374
+ ):
375
+ start = time.time()
376
+ print('restore ==>>')
377
+
378
+ torch.cuda.set_device(SUPIR_device)
379
+
380
+ with torch.no_grad():
381
+ input_image = upscale_image(input_image, upscale, unit_resolution=32, min_size=min_size)
382
+ LQ = np.array(input_image) / 255.0
383
+ LQ = np.power(LQ, gamma_correction)
384
+ LQ *= 255.0
385
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
386
+ LQ = LQ / 255 * 2 - 1
387
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
388
+ captions = ['']
389
+
390
+ samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
391
+ s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
392
+ num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
393
+ use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
394
+ cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
395
+
396
+ x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
397
+ 0, 255).astype(np.uint8)
398
+ results = [x_samples[i] for i in range(num_samples)]
399
+ torch.cuda.empty_cache()
400
+
401
+ # All the results have the same size
402
+ input_height, input_width, input_channel = np.array(input_image).shape
403
+ result_height, result_width, result_channel = np.array(results[0]).shape
404
+
405
+ print('<<== restore')
406
+ end = time.time()
407
+ secondes = int(end - start)
408
+ minutes = math.floor(secondes / 60)
409
+ secondes = secondes - (minutes * 60)
410
+ hours = math.floor(minutes / 60)
411
+ minutes = minutes - (hours * 60)
412
+ information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
413
+ "If you don't get the image you wanted, add more details in the « Image description ». " + \
414
+ "The image" + (" has" if len(results) == 1 else "s have") + " been generated in " + \
415
+ ((str(hours) + " h, ") if hours != 0 else "") + \
416
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
417
+ str(secondes) + " sec. " + \
418
+ "The new image resolution is " + str(result_width) + \
419
+ " pixels large and " + str(result_height) + \
420
+ " pixels high, so a resolution of " + f'{result_width * result_height:,}' + " pixels."
421
+ print(information)
422
+ try:
423
+ print("Initial resolution: " + f'{input_width * input_height:,}')
424
+ print("Final resolution: " + f'{result_width * result_height:,}')
425
+ print("edm_steps: " + str(edm_steps))
426
+ print("num_samples: " + str(num_samples))
427
+ print("downscale: " + str(downscale))
428
+ print("Estimated minutes: " + f'{(((result_width * result_height**(1/1.75)) * input_width * input_height * (edm_steps**(1/2)) * (num_samples**(1/2.5)))**(1/2.5)) / 25000:,}')
429
+ except Exception as e:
430
+ print('Exception of Estimation')
431
+
432
+ # Only one image can be shown in the slider
433
+ 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), gr.update(visible=False), gr.update(interactive = False)
434
+
435
+ def load_and_reset(param_setting):
436
+ print('load_and_reset ==>>')
437
+ if torch.cuda.device_count() == 0:
438
+ gr.Warning('Set this space to GPU config to make it work.')
439
+ return None, None, None, None, None, None, None, None, None, None, None, None, None, None
440
+ edm_steps = default_setting.edm_steps
441
+ s_stage2 = 1.0
442
+ s_stage1 = -1.0
443
+ s_churn = 5
444
+ s_noise = 1.003
445
+ a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
446
+ 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
447
+ 'detailing, hyper sharpness, perfect without deformations.'
448
+ n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, ' \
449
+ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
450
+ 'signature, jpeg artifacts, deformed, lowres, over-smooth'
451
+ color_fix_type = 'Wavelet'
452
+ spt_linear_s_stage2 = 0.0
453
+ linear_s_stage2 = False
454
+ linear_CFG = True
455
+ if param_setting == "Quality":
456
+ s_cfg = default_setting.s_cfg_Quality
457
+ spt_linear_CFG = default_setting.spt_linear_CFG_Quality
458
+ model_select = "v0-Q"
459
+ elif param_setting == "Fidelity":
460
+ s_cfg = default_setting.s_cfg_Fidelity
461
+ spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
462
+ model_select = "v0-F"
463
+ else:
464
+ raise NotImplementedError
465
+ gr.Info('The parameters are reset.')
466
+ print('<<== load_and_reset')
467
+ return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
468
+ spt_linear_CFG, linear_s_stage2, spt_linear_s_stage2, model_select
469
+
470
+ def log_information(result_gallery):
471
+ print('log_information')
472
+ if result_gallery is not None:
473
+ for i, result in enumerate(result_gallery):
474
+ print(result[0])
475
+
476
+ def on_select_result(result_slider, result_gallery, evt: gr.SelectData):
477
+ print('on_select_result')
478
+ if result_gallery is not None:
479
+ for i, result in enumerate(result_gallery):
480
+ print(result[0])
481
+ return [result_slider[0], result_gallery[evt.index][0]]
482
+
483
+ def on_render_image_example(result_example):
484
+ print('on_render_image_example')
485
+ return gr.update(value = result_example, visible = True)
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
+ The content added by SUPIR is <b><u>imagination, not real-world information</u></b>.
494
+ SUPIR is for beauty and illustration only.
495
+ Most of the processes last few minutes.
496
+ If you want to upscale AI-generated images, be noticed that <i>PixArt Sigma</i> space can directly generate 5984x5984 images.
497
+ Due to Gradio issues, the generated image is slightly less satured than the original.
498
+ Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">message in discussion</a> if you encounter issues.
499
+ You can also use <a href="https://huggingface.co/spaces/gokaygokay/AuraSR">AuraSR</a> to upscale x4.
500
+
501
+ <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>
502
+ <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>
503
+ """
504
+
505
+
506
+ claim_md = """
507
+ ## **Piracy**
508
+ The images are not stored but the logs are saved during a month.
509
+ ## **How to get SUPIR**
510
+ You can get SUPIR on HuggingFace by [duplicating this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set GPU.
511
+ You can also install SUPIR on your computer following [this tutorial](https://huggingface.co/blog/MonsterMMORPG/supir-sota-image-upscale-better-than-magnific-ai).
512
+ You can install _Pinokio_ on your computer and then install _SUPIR_ into it. It should be quite easy if you have an Nvidia GPU.
513
+ ## **Terms of use**
514
+ 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.
515
+ ## **License**
516
+ 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.
517
+ """
518
+
519
+ js = """
520
+ function createGradioAnimation() {
521
+ window.addEventListener("beforeunload", function(e) {
522
+ if (document.getElementById('dummy_button_id') && !document.getElementById('dummy_button_id').disabled) {
523
+ var confirmationMessage = 'A process is still running. '
524
+ + 'If you leave before saving, your changes will be lost.';
525
+
526
+ (e || window.event).returnValue = confirmationMessage;
527
+ }
528
+ return confirmationMessage;
529
+ });
530
+ return 'Animation created';
531
+ }
532
+ """
533
+
534
+ # Gradio interface
535
+ with gr.Blocks(js=js) as interface:
536
+ if torch.cuda.device_count() == 0:
537
+ with gr.Row():
538
+ gr.HTML("""
539
+ <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>
540
+
541
+ 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.
542
+ </big></big></big></p>
543
+ """)
544
+ gr.HTML(title_html)
545
+
546
+ input_image = gr.Image(label="Input (*.png, *.webp, *.jpeg, *.jpg, *.gif, *.bmp, *.avif)", show_label=True, type="filepath", height=600, elem_id="image-input")
547
+ 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, visible=False)
548
+ with gr.Group():
549
+ 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)
550
+ prompt_hint = gr.HTML("You can use a <a href='"'https://huggingface.co/spaces/badayvedat/LLaVA'"'>LlaVa space</a> to auto-generate the description of your image.")
551
+ 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)
552
+ 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")
553
+ allocation = gr.Slider(label="GPU allocation time (in seconds)", info='lower=May abort run, higher=Quota penalty for next runs; only useful for ZeroGPU; for instance set to 88 when you have the message "You have exceeded your GPU quota (180s requested vs. 89s left)."', value=180, minimum=60, maximum=320, step=1)
554
+
555
+ with gr.Accordion("Pre-denoising (optional)", open=False):
556
+ gamma_correction = gr.Slider(label="Gamma Correction", info = "lower=lighter, higher=darker", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
557
+ denoise_button = gr.Button(value="Pre-denoise")
558
+ denoise_image = gr.Image(label="Denoised image", show_label=True, type="filepath", sources=[], interactive = False, height=600, elem_id="image-s1")
559
+ denoise_information = gr.HTML(value="If present, the denoised image will be used for the restoration instead of the input image.", visible=False)
560
+
561
+ with gr.Accordion("Advanced options", open=False):
562
+ a_prompt = gr.Textbox(label="Additional image description",
563
+ info="Completes the main image description",
564
+ value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
565
+ 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
566
+ 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, clothing fabric detailing, '
567
+ 'hyper sharpness, perfect without deformations.',
568
+ lines=3)
569
+ n_prompt = gr.Textbox(label="Negative image description",
570
+ info="Disambiguate by listing what the image does NOT represent",
571
+ value='painting, oil painting, illustration, drawing, art, sketch, anime, '
572
+ 'cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, '
573
+ 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
574
+ 'deformed, lowres, over-smooth',
575
+ lines=3)
576
+ edm_steps = gr.Slider(label="Steps", info="lower=faster, higher=more details; too many steps create a checker effect", minimum=1, maximum=200, value=default_setting.edm_steps if torch.cuda.device_count() > 0 else 1, step=1)
577
+ num_samples = gr.Slider(label="Num Samples", info="Number of generated results", minimum=1, maximum=4 if not args.use_image_slider else 1
578
+ , value=1, step=1)
579
+ min_size = gr.Slider(label="Minimum size", info="Minimum height, minimum width of the result", minimum=32, maximum=4096, value=1024, step=32)
580
+ 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)
581
+ with gr.Row():
582
+ with gr.Column():
583
+ model_select = gr.Radio([["💃 Quality (v0-Q)", "v0-Q"], ["🎯 Fidelity (v0-F)", "v0-F"]], label="Model Selection", info="Pretrained model", value="v0-Q")
584
+ with gr.Column():
585
+ 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="AdaIn")
586
+ s_cfg = gr.Slider(label="Text Guidance Scale", info="lower=follow the image, higher=follow the prompt", minimum=1.0, maximum=15.0,
587
+ value=default_setting.s_cfg_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.1)
588
+ s_stage2 = gr.Slider(label="Restoring Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
589
+ s_stage1 = gr.Slider(label="Pre-denoising Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
590
+ s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
591
+ s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
592
+ with gr.Row():
593
+ with gr.Column():
594
+ linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
595
+ spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
596
+ maximum=9.0, value=default_setting.spt_linear_CFG_Quality if torch.cuda.device_count() > 0 else 1.0, step=0.5)
597
+ with gr.Column():
598
+ linear_s_stage2 = gr.Checkbox(label="Linear Restoring Guidance", value=False)
599
+ spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
600
+ maximum=1., value=0., step=0.05)
601
+ with gr.Column():
602
+ diff_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["fp16 (medium)", "fp16"], ["bf16 (speed)", "bf16"]], label="Diffusion Data Type", value="fp32")
603
+ with gr.Column():
604
+ ae_dtype = gr.Radio([["fp32 (precision)", "fp32"], ["bf16 (speed)", "bf16"]], label="Auto-Encoder Data Type", value="fp32")
605
+ randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
606
+ seed = gr.Slider(label="Seed", minimum=0, maximum=max_64_bit_int, step=1, randomize=True)
607
+ with gr.Group():
608
+ param_setting = gr.Radio(["Quality", "Fidelity"], label="Presetting", value = "Quality")
609
+ restart_button = gr.Button(value="Apply presetting")
610
+
611
+ with gr.Accordion("Debug", open=False):
612
+ input_image_debug = gr.Image(label="Image Debug", type="filepath")
613
+ prompt_debug = gr.Textbox(label="Prompt Debug", value='')
614
+ upscale_debug = 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 Debug", info="Resolution x1 to x10", value=2)
615
+
616
+ with gr.Column():
617
+ diffusion_button = gr.Button(value="🚀 Upscale/Restore", variant = "primary", elem_id = "process_button")
618
+ reset_btn = gr.Button(value="🧹 Reinit page", variant="stop", elem_id="reset_button", visible = False)
619
+ dummy_button = gr.Button(elem_id = "dummy_button_id", visible = False, interactive = False)
620
+
621
+ warning = gr.HTML(elem_id="warning", value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
622
+ restore_information = gr.HTML(value = "Restart the process to get another result.", visible = False)
623
+ result_slider = ImageSlider(label = 'Comparator', show_label = False, interactive = False, elem_id = "slider1", show_download_button = False, visible = False)
624
+ result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
625
+ result_example = gr.HTML(elem_id="result_example", visible = False)
626
+ result_image_example = gr.Image(label="Example Image", visible = False)
627
+
628
+ with gr.Row(elem_id="examples", visible = False):
629
+ gr.Examples(
630
+ label = "Examples for cache",
631
+ examples = [
632
+ [
633
+ "./Examples/Example2.jpeg",
634
+ 0,
635
+ "./Examples/Example2.jpeg",
636
+ "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
637
+ "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.",
638
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
639
+ 1, # num_samples
640
+ 32, # min_size
641
+ 1, # downscale
642
+ 1, # upscale
643
+ 100, # edm_steps
644
+ -1, # s_stage1
645
+ 1, # s_stage2
646
+ 7.5, # s_cfg
647
+ True, # randomize_seed
648
+ 42, # seed
649
+ 5, # s_churn
650
+ 1.003, # s_noise
651
+ "Wavelet", # color_fix_type
652
+ "fp16", # diff_dtype
653
+ "bf16", # ae_dtype
654
+ 1.0, # gamma_correction
655
+ True, # linear_CFG
656
+ 4, # spt_linear_CFG
657
+ False, # linear_s_stage2
658
+ 0., # spt_linear_s_stage2
659
+ "v0-Q", # model_select
660
+ "input", # output_format
661
+ 60 # allocation
662
+ ],
663
+ [
664
+ "./Examples/Example2.jpeg",
665
+ 0,
666
+ "./Examples/Example2.jpeg",
667
+ "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
668
+ "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.",
669
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
670
+ 4, # num_samples
671
+ 32, # min_size
672
+ 1, # downscale
673
+ 1, # upscale
674
+ 100, # edm_steps
675
+ -1, # s_stage1
676
+ 1, # s_stage2
677
+ 7.5, # s_cfg
678
+ True, # randomize_seed
679
+ 42, # seed
680
+ 5, # s_churn
681
+ 1.003, # s_noise
682
+ "Wavelet", # color_fix_type
683
+ "fp16", # diff_dtype
684
+ "bf16", # ae_dtype
685
+ 1.0, # gamma_correction
686
+ True, # linear_CFG
687
+ 4, # spt_linear_CFG
688
+ False, # linear_s_stage2
689
+ 0., # spt_linear_s_stage2
690
+ "v0-Q", # model_select
691
+ "input", # output_format
692
+ 60 # allocation
693
+ ]
694
+ ],
695
+ run_on_click = True,
696
+ fn = stage2_process_example,
697
+ inputs = [
698
+ input_image,
699
+ rotation,
700
+ denoise_image,
701
+ prompt,
702
+ a_prompt,
703
+ n_prompt,
704
+ num_samples,
705
+ min_size,
706
+ downscale,
707
+ upscale,
708
+ edm_steps,
709
+ s_stage1,
710
+ s_stage2,
711
+ s_cfg,
712
+ randomize_seed,
713
+ seed,
714
+ s_churn,
715
+ s_noise,
716
+ color_fix_type,
717
+ diff_dtype,
718
+ ae_dtype,
719
+ gamma_correction,
720
+ linear_CFG,
721
+ spt_linear_CFG,
722
+ linear_s_stage2,
723
+ spt_linear_s_stage2,
724
+ model_select,
725
+ output_format,
726
+ allocation
727
+ ],
728
+ outputs = [
729
+ result_example,
730
+ warning,
731
+ dummy_button,
732
+ prompt_hint
733
+ ],
734
+ cache_examples = True,
735
+ )
736
+
737
+ gr.Examples(
738
+ label = "Examples for demo",
739
+ examples = [
740
+ [
741
+ "./Examples/Example1.png",
742
+ 0,
743
+ "./Examples/Example1.png",
744
+ "Group of people, walking, happy, in the street, photorealistic, 8k, extremely detailled",
745
+ "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.",
746
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
747
+ 2, # num_samples
748
+ 1024, # min_size
749
+ 1, # downscale
750
+ 8, # upscale
751
+ 100, # edm_steps
752
+ -1, # s_stage1
753
+ 1, # s_stage2
754
+ 7.5, # s_cfg
755
+ False, # randomize_seed
756
+ 42, # seed
757
+ 5, # s_churn
758
+ 1.003, # s_noise
759
+ "AdaIn", # color_fix_type
760
+ "fp16", # diff_dtype
761
+ "bf16", # ae_dtype
762
+ 1.0, # gamma_correction
763
+ True, # linear_CFG
764
+ 4, # spt_linear_CFG
765
+ False, # linear_s_stage2
766
+ 0., # spt_linear_s_stage2
767
+ "v0-Q", # model_select
768
+ "input", # output_format
769
+ 180 # allocation
770
+ ],
771
+ [
772
+ "./Examples/Example2.jpeg",
773
+ 0,
774
+ "./Examples/Example2.jpeg",
775
+ "La cabeza de un gato atigrado, en una casa, fotorrealista, 8k, extremadamente detallada",
776
+ "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.",
777
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
778
+ 1, # num_samples
779
+ 1024, # min_size
780
+ 1, # downscale
781
+ 1, # upscale
782
+ 100, # edm_steps
783
+ -1, # s_stage1
784
+ 1, # s_stage2
785
+ 7.5, # s_cfg
786
+ False, # randomize_seed
787
+ 42, # seed
788
+ 5, # s_churn
789
+ 1.003, # s_noise
790
+ "Wavelet", # color_fix_type
791
+ "fp16", # diff_dtype
792
+ "bf16", # ae_dtype
793
+ 1.0, # gamma_correction
794
+ True, # linear_CFG
795
+ 4, # spt_linear_CFG
796
+ False, # linear_s_stage2
797
+ 0., # spt_linear_s_stage2
798
+ "v0-Q", # model_select
799
+ "input", # output_format
800
+ 60 # allocation
801
+ ],
802
+ [
803
+ "./Examples/Example3.webp",
804
+ 0,
805
+ "./Examples/Example3.webp",
806
+ "A red apple",
807
+ "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.",
808
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
809
+ 1, # num_samples
810
+ 1024, # min_size
811
+ 1, # downscale
812
+ 1, # upscale
813
+ 200, # edm_steps
814
+ -1, # s_stage1
815
+ 1, # s_stage2
816
+ 7.5, # s_cfg
817
+ False, # randomize_seed
818
+ 42, # seed
819
+ 5, # s_churn
820
+ 1.003, # s_noise
821
+ "Wavelet", # color_fix_type
822
+ "fp16", # diff_dtype
823
+ "bf16", # ae_dtype
824
+ 1.0, # gamma_correction
825
+ True, # linear_CFG
826
+ 4, # spt_linear_CFG
827
+ False, # linear_s_stage2
828
+ 0., # spt_linear_s_stage2
829
+ "v0-Q", # model_select
830
+ "input", # output_format
831
+ 180 # allocation
832
+ ],
833
+ [
834
+ "./Examples/Example3.webp",
835
+ 0,
836
+ "./Examples/Example3.webp",
837
+ "A red marble",
838
+ "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.",
839
+ "painting, oil painting, illustration, drawing, art, sketch, anime, cartoon, CG Style, 3D render, unreal engine, blurring, aliasing, pixel, unsharp, weird textures, ugly, dirty, messy, worst quality, low quality, frames, watermark, signature, jpeg artifacts, deformed, lowres, over-smooth",
840
+ 1, # num_samples
841
+ 1024, # min_size
842
+ 1, # downscale
843
+ 1, # upscale
844
+ 200, # edm_steps
845
+ -1, # s_stage1
846
+ 1, # s_stage2
847
+ 7.5, # s_cfg
848
+ False, # randomize_seed
849
+ 42, # seed
850
+ 5, # s_churn
851
+ 1.003, # s_noise
852
+ "Wavelet", # color_fix_type
853
+ "fp16", # diff_dtype
854
+ "bf16", # ae_dtype
855
+ 1.0, # gamma_correction
856
+ True, # linear_CFG
857
+ 4, # spt_linear_CFG
858
+ False, # linear_s_stage2
859
+ 0., # spt_linear_s_stage2
860
+ "v0-Q", # model_select
861
+ "input", # output_format
862
+ 180 # allocation
863
+ ],
864
+ ],
865
+ run_on_click = True,
866
+ fn = stage2_process,
867
+ inputs = [
868
+ input_image,
869
+ rotation,
870
+ denoise_image,
871
+ prompt,
872
+ a_prompt,
873
+ n_prompt,
874
+ num_samples,
875
+ min_size,
876
+ downscale,
877
+ upscale,
878
+ edm_steps,
879
+ s_stage1,
880
+ s_stage2,
881
+ s_cfg,
882
+ randomize_seed,
883
+ seed,
884
+ s_churn,
885
+ s_noise,
886
+ color_fix_type,
887
+ diff_dtype,
888
+ ae_dtype,
889
+ gamma_correction,
890
+ linear_CFG,
891
+ spt_linear_CFG,
892
+ linear_s_stage2,
893
+ spt_linear_s_stage2,
894
+ model_select,
895
+ output_format,
896
+ allocation
897
+ ],
898
+ outputs = [
899
+ result_slider,
900
+ result_gallery,
901
+ restore_information,
902
+ reset_btn,
903
+ warning,
904
+ dummy_button
905
+ ],
906
+ cache_examples = False,
907
+ )
908
+
909
+ with gr.Row():
910
+ gr.Markdown(claim_md)
911
+
912
+ input_image.upload(fn = check_upload, inputs = [
913
+ input_image
914
+ ], outputs = [
915
+ rotation
916
+ ], queue = False, show_progress = False)
917
+
918
+ denoise_button.click(fn = check_and_update, inputs = [
919
+ input_image
920
+ ], outputs = [warning, dummy_button], queue = False, show_progress = False).success(fn = stage1_process, inputs = [
921
+ input_image,
922
+ gamma_correction,
923
+ diff_dtype,
924
+ ae_dtype
925
+ ], outputs=[
926
+ denoise_image,
927
+ denoise_information,
928
+ dummy_button
929
+ ])
930
+
931
+ diffusion_button.click(fn = update_seed, inputs = [
932
+ randomize_seed,
933
+ seed
934
+ ], outputs = [
935
+ seed
936
+ ], queue = False, show_progress = False).then(fn = check_and_update, inputs = [
937
+ input_image
938
+ ], outputs = [warning, dummy_button], queue = False, show_progress = False).success(fn=stage2_process, inputs = [
939
+ input_image,
940
+ rotation,
941
+ denoise_image,
942
+ prompt,
943
+ a_prompt,
944
+ n_prompt,
945
+ num_samples,
946
+ min_size,
947
+ downscale,
948
+ upscale,
949
+ edm_steps,
950
+ s_stage1,
951
+ s_stage2,
952
+ s_cfg,
953
+ randomize_seed,
954
+ seed,
955
+ s_churn,
956
+ s_noise,
957
+ color_fix_type,
958
+ diff_dtype,
959
+ ae_dtype,
960
+ gamma_correction,
961
+ linear_CFG,
962
+ spt_linear_CFG,
963
+ linear_s_stage2,
964
+ spt_linear_s_stage2,
965
+ model_select,
966
+ output_format,
967
+ allocation
968
+ ], outputs = [
969
+ result_slider,
970
+ result_gallery,
971
+ restore_information,
972
+ reset_btn,
973
+ warning,
974
+ dummy_button
975
+ ]).success(fn = log_information, inputs = [
976
+ result_gallery
977
+ ], outputs = [], queue = False, show_progress = False)
978
+
979
+ result_gallery.change(on_select_result, [result_slider, result_gallery], result_slider)
980
+ result_gallery.select(on_select_result, [result_slider, result_gallery], result_slider)
981
+ result_example.change(on_render_image_example, result_example, result_image_example)
982
+
983
+ restart_button.click(fn = load_and_reset, inputs = [
984
+ param_setting
985
+ ], outputs = [
986
+ edm_steps,
987
+ s_cfg,
988
+ s_stage2,
989
+ s_stage1,
990
+ s_churn,
991
+ s_noise,
992
+ a_prompt,
993
+ n_prompt,
994
+ color_fix_type,
995
+ linear_CFG,
996
+ spt_linear_CFG,
997
+ linear_s_stage2,
998
+ spt_linear_s_stage2,
999
+ model_select
1000
+ ])
1001
+
1002
+ reset_btn.click(fn = reset, inputs = [], outputs = [
1003
+ input_image,
1004
+ rotation,
1005
+ denoise_image,
1006
+ prompt,
1007
+ a_prompt,
1008
+ n_prompt,
1009
+ num_samples,
1010
+ min_size,
1011
+ downscale,
1012
+ upscale,
1013
+ edm_steps,
1014
+ s_stage1,
1015
+ s_stage2,
1016
+ s_cfg,
1017
+ randomize_seed,
1018
+ seed,
1019
+ s_churn,
1020
+ s_noise,
1021
+ color_fix_type,
1022
+ diff_dtype,
1023
+ ae_dtype,
1024
+ gamma_correction,
1025
+ linear_CFG,
1026
+ spt_linear_CFG,
1027
+ linear_s_stage2,
1028
+ spt_linear_s_stage2,
1029
+ model_select,
1030
+ output_format,
1031
+ allocation
1032
+ ], queue = False, show_progress = False)
1033
+
1034
+ def handle_field_debug_change(input_image_debug_data, prompt_debug_data, upscale_debug_data):
1035
+ input_image_debug_value[0] = input_image_debug_data
1036
+ prompt_debug_value[0] = prompt_debug_data
1037
+ upscale_debug_value[0] = upscale_debug_data
1038
+ return []
1039
+
1040
+ input_image_debug.upload(
1041
+ fn=handle_field_debug_change,
1042
+ inputs=[input_image_debug, prompt_debug, upscale_debug],
1043
+ outputs=[]
1044
+ )
1045
+
1046
+ prompt_debug.change(
1047
+ fn=handle_field_debug_change,
1048
+ inputs=[input_image_debug, prompt_debug, upscale_debug],
1049
+ outputs=[]
1050
+ )
1051
+
1052
+ upscale_debug.change(
1053
+ fn=handle_field_debug_change,
1054
+ inputs=[input_image_debug, prompt_debug, upscale_debug],
1055
+ outputs=[]
1056
+ )
1057
+
1058
+ interface.queue(10).launch(mcp_server=True, ssr_mode=False)
 
 
 
 
 
requirements.txt CHANGED
@@ -1,42 +1,43 @@
1
- pydantic==2.10.6 # To avoid the message "No API found" or "Internal server error"
2
-
3
- fastapi==0.115.13
4
- gradio_imageslider==0.0.20
5
- gradio_client==1.10.3
6
- numpy==1.26.4
7
- requests==2.32.4
8
- sentencepiece==0.2.0
9
- tokenizers==0.19.1
10
- torchvision==0.22.0
11
- uvicorn==0.34.3
12
- wandb==0.20.1
13
- httpx==0.28.1
14
- transformers==4.43.0
15
- accelerate==1.8.0
16
- scikit-learn==1.7.0
17
- einops==0.8.1
18
- einops-exts==0.0.4
19
- timm==1.0.15
20
- openai-clip==1.0.1
21
- fsspec==2025.5.1
22
- kornia==0.8.1
23
- matplotlib==3.10.3
24
- ninja==1.11.1.4
25
- omegaconf==2.3.0
26
- opencv-python==4.11.0.86
27
- pandas==2.3.0
28
- pillow==11.2.1
29
- pytorch-lightning==2.5.1.post0
30
- PyYAML==6.0.2
31
- scipy==1.15.3
32
- tqdm==4.67.1
33
- triton==3.3.0
34
- urllib3==2.4.0
35
- webdataset==0.2.111
36
- xformers==0.0.30
37
- facexlib==0.3.0
38
- k-diffusion==0.1.1.post1
39
- diffusers==0.33.1
40
- pillow-heif==0.22.0
41
-
 
42
  open-clip-torch==2.24.0
 
1
+ pydantic==2.10.6 # To avoid the message "No API found" or "Internal server error"
2
+
3
+ fastapi==0.115.13
4
+ gradio_imageslider==0.0.20
5
+ gradio_client==1.10.3
6
+ numpy==1.26.4
7
+ requests==2.32.4
8
+ sentencepiece==0.2.0
9
+ tokenizers==0.19.1
10
+ torchvision==0.22.0
11
+ uvicorn==0.34.3
12
+ wandb==0.20.1
13
+ httpx==0.28.1
14
+ transformers==4.43.0
15
+ accelerate==1.8.0
16
+ scikit-learn==1.7.0
17
+ einops==0.8.1
18
+ einops-exts==0.0.4
19
+ timm==1.0.15
20
+ openai-clip==1.0.1
21
+ fsspec==2025.5.1
22
+ kornia==0.8.1
23
+ matplotlib==3.10.3
24
+ ninja==1.11.1.4
25
+ omegaconf==2.3.0
26
+ opencv-python==4.11.0.86
27
+ pandas==2.3.0
28
+ pillow==11.2.1
29
+ pytorch-lightning==2.5.1.post0
30
+ PyYAML==6.0.2
31
+ scipy==1.15.3
32
+ tqdm==4.67.1
33
+ triton==3.3.0
34
+ urllib3==2.4.0
35
+ webdataset==0.2.111
36
+ xformers==0.0.30
37
+ facexlib==0.3.0
38
+ k-diffusion==0.1.1.post1
39
+ diffusers==0.33.1
40
+ imageio==2.37.0
41
+ pillow-heif==0.22.0
42
+
43
  open-clip-torch==2.24.0