Fabrice-TIERCELIN commited on
Commit
1444618
·
verified ·
1 Parent(s): f3602ba

Upload 4 files

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