Fabrice-TIERCELIN commited on
Commit
81bd15c
1 Parent(s): 923a6ff

Warning when running on CPU

Browse files
Files changed (1) hide show
  1. gradio_demo.py +332 -314
gradio_demo.py CHANGED
@@ -1,314 +1,332 @@
1
- import os
2
-
3
- import gradio as gr
4
- from gradio_imageslider import ImageSlider
5
- import argparse
6
- from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype
7
- import numpy as np
8
- import torch
9
- from SUPIR.util import create_SUPIR_model, load_QF_ckpt
10
- from PIL import Image
11
- from llava.llava_agent import LLavaAgent
12
- from CKPT_PTH import LLAVA_MODEL_PATH
13
- import einops
14
- import copy
15
- import time
16
-
17
- parser = argparse.ArgumentParser()
18
- parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
19
- parser.add_argument("--ip", type=str, default='127.0.0.1')
20
- parser.add_argument("--port", type=int, default='6688')
21
- parser.add_argument("--no_llava", action='store_true', default=False)
22
- parser.add_argument("--use_image_slider", action='store_true', default=False)
23
- parser.add_argument("--log_history", action='store_true', default=False)
24
- parser.add_argument("--loading_half_params", action='store_true', default=False)
25
- parser.add_argument("--use_tile_vae", action='store_true', default=False)
26
- parser.add_argument("--encoder_tile_size", type=int, default=512)
27
- parser.add_argument("--decoder_tile_size", type=int, default=64)
28
- parser.add_argument("--load_8bit_llava", action='store_true', default=False)
29
- args = parser.parse_args()
30
- server_ip = args.ip
31
- server_port = args.port
32
- use_llava = not args.no_llava
33
-
34
- if torch.cuda.device_count() >= 2:
35
- SUPIR_device = 'cuda:0'
36
- LLaVA_device = 'cuda:1'
37
- elif torch.cuda.device_count() == 1:
38
- SUPIR_device = 'cuda:0'
39
- LLaVA_device = 'cuda:0'
40
- else:
41
- raise ValueError('Currently support CUDA only.')
42
-
43
- # load SUPIR
44
- model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
45
- if args.loading_half_params:
46
- model = model.half()
47
- if args.use_tile_vae:
48
- model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
49
- model = model.to(SUPIR_device)
50
- model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
51
- model.current_model = 'v0-Q'
52
- ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
53
-
54
- # load LLaVA
55
- if use_llava:
56
- llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)
57
- else:
58
- llava_agent = None
59
-
60
- def stage1_process(input_image, gamma_correction):
61
- torch.cuda.set_device(SUPIR_device)
62
- LQ = HWC3(input_image)
63
- LQ = fix_resize(LQ, 512)
64
- # stage1
65
- LQ = np.array(LQ) / 255 * 2 - 1
66
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
67
- LQ = model.batchify_denoise(LQ, is_stage1=True)
68
- LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
69
- # gamma correction
70
- LQ = LQ / 255.0
71
- LQ = np.power(LQ, gamma_correction)
72
- LQ *= 255.0
73
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
74
- return LQ
75
-
76
- def llave_process(input_image, temperature, top_p, qs=None):
77
- torch.cuda.set_device(LLaVA_device)
78
- if use_llava:
79
- LQ = HWC3(input_image)
80
- LQ = Image.fromarray(LQ.astype('uint8'))
81
- captions = llava_agent.gen_image_caption([LQ], temperature=temperature, top_p=top_p, qs=qs)
82
- else:
83
- captions = ['LLaVA is not available. Please add text manually.']
84
- return captions[0]
85
-
86
- def stage2_process(input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2,
87
- s_cfg, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction,
88
- linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select):
89
- torch.cuda.set_device(SUPIR_device)
90
- event_id = str(time.time_ns())
91
- event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt,
92
- 'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps,
93
- 's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn,
94
- 's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype,
95
- 'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2,
96
- 'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2,
97
- 'model_select': model_select}
98
-
99
- if model_select != model.current_model:
100
- if model_select == 'v0-Q':
101
- print('load v0-Q')
102
- model.load_state_dict(ckpt_Q, strict=False)
103
- model.current_model = 'v0-Q'
104
- elif model_select == 'v0-F':
105
- print('load v0-F')
106
- model.load_state_dict(ckpt_F, strict=False)
107
- model.current_model = 'v0-F'
108
- input_image = HWC3(input_image)
109
- input_image = upscale_image(input_image, upscale, unit_resolution=32,
110
- min_size=1024)
111
-
112
- LQ = np.array(input_image) / 255.0
113
- LQ = np.power(LQ, gamma_correction)
114
- LQ *= 255.0
115
- LQ = LQ.round().clip(0, 255).astype(np.uint8)
116
- LQ = LQ / 255 * 2 - 1
117
- LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
118
- if use_llava:
119
- captions = [prompt]
120
- else:
121
- captions = ['']
122
-
123
- model.ae_dtype = convert_dtype(ae_dtype)
124
- model.model.dtype = convert_dtype(diff_dtype)
125
-
126
- samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
127
- s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
128
- num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
129
- use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
130
- cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
131
-
132
- x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
133
- 0, 255).astype(np.uint8)
134
- results = [x_samples[i] for i in range(num_samples)]
135
-
136
- if args.log_history:
137
- os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True)
138
- with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
139
- f.write(str(event_dict))
140
- f.close()
141
- Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png')
142
- for i, result in enumerate(results):
143
- Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png')
144
- return [input_image] + results, event_id, 3, ''
145
-
146
-
147
- def load_and_reset(param_setting):
148
- edm_steps = default_setting.edm_steps
149
- s_stage2 = 1.0
150
- s_stage1 = -1.0
151
- s_churn = 5
152
- s_noise = 1.003
153
- a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
154
- 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
155
- 'detailing, hyper sharpness, perfect without deformations.'
156
- n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, oil painting, cartoon, CG Style, ' \
157
- '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
158
- 'signature, jpeg artifacts, deformed, lowres, over-smooth'
159
- color_fix_type = 'Wavelet'
160
- spt_linear_s_stage2 = 0.0
161
- linear_s_stage2 = False
162
- linear_CFG = True
163
- if param_setting == "Quality":
164
- s_cfg = default_setting.s_cfg_Quality
165
- spt_linear_CFG = default_setting.spt_linear_CFG_Quality
166
- elif param_setting == "Fidelity":
167
- s_cfg = default_setting.s_cfg_Fidelity
168
- spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
169
- else:
170
- raise NotImplementedError
171
- return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
172
- linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2
173
-
174
-
175
- def submit_feedback(event_id, fb_score, fb_text):
176
- if args.log_history:
177
- with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f:
178
- event_dict = eval(f.read())
179
- f.close()
180
- event_dict['feedback'] = {'score': fb_score, 'text': fb_text}
181
- with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
182
- f.write(str(event_dict))
183
- f.close()
184
- return 'Submit successfully, thank you for your comments!'
185
- else:
186
- return 'Submit failed, the server is not set to log history.'
187
-
188
-
189
- title_md = """
190
- # **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
191
-
192
- ⚠️SUPIR is still a research project under tested and is not yet a stable commercial product.
193
-
194
- [[Paper](https://arxiv.org/abs/2401.13627)]   [[Project Page](http://supir.xpixel.group/)]   [[How to play](https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png)]
195
- """
196
-
197
-
198
- claim_md = """
199
- ## **Terms of use**
200
-
201
- 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.
202
-
203
- ## **License**
204
-
205
- 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.
206
- """
207
-
208
-
209
- block = gr.Blocks(title='SUPIR').queue()
210
- with block:
211
- with gr.Row():
212
- gr.Markdown(title_md)
213
- with gr.Row():
214
- with gr.Column():
215
- with gr.Row(equal_height=True):
216
- with gr.Column():
217
- gr.Markdown("<center>Input</center>")
218
- input_image = gr.Image(type="numpy", elem_id="image-input", height=400, width=400)
219
- with gr.Column():
220
- gr.Markdown("<center>Stage1 Output</center>")
221
- denoise_image = gr.Image(type="numpy", elem_id="image-s1", height=400, width=400)
222
- prompt = gr.Textbox(label="Prompt", value="")
223
- with gr.Accordion("Stage1 options", open=False):
224
- gamma_correction = gr.Slider(label="Gamma Correction", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
225
- with gr.Accordion("LLaVA options", open=False):
226
- temperature = gr.Slider(label="Temperature", minimum=0., maximum=1.0, value=0.2, step=0.1)
227
- top_p = gr.Slider(label="Top P", minimum=0., maximum=1.0, value=0.7, step=0.1)
228
- qs = gr.Textbox(label="Question", value="Describe this image and its style in a very detailed manner. "
229
- "The image is a realistic photography, not an art painting.")
230
- with gr.Accordion("Stage2 options", open=False):
231
- num_samples = gr.Slider(label="Num Samples", minimum=1, maximum=4 if not args.use_image_slider else 1
232
- , value=1, step=1)
233
- upscale = gr.Slider(label="Upscale", minimum=1, maximum=8, value=1, step=1)
234
- edm_steps = gr.Slider(label="Steps", minimum=1, maximum=200, value=default_setting.edm_steps, step=1)
235
- s_cfg = gr.Slider(label="Text Guidance Scale", minimum=1.0, maximum=15.0,
236
- value=default_setting.s_cfg_Quality, step=0.1)
237
- s_stage2 = gr.Slider(label="Stage2 Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
238
- s_stage1 = gr.Slider(label="Stage1 Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
239
- seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
240
- s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
241
- s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
242
- a_prompt = gr.Textbox(label="Default Positive Prompt",
243
- value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
244
- 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
245
- 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, '
246
- 'hyper sharpness, perfect without deformations.')
247
- n_prompt = gr.Textbox(label="Default Negative Prompt",
248
- value='painting, oil painting, illustration, drawing, art, sketch, oil painting, '
249
- 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, '
250
- 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
251
- 'deformed, lowres, over-smooth')
252
- with gr.Row():
253
- with gr.Column():
254
- linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
255
- spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
256
- maximum=9.0, value=default_setting.spt_linear_CFG_Quality, step=0.5)
257
- with gr.Column():
258
- linear_s_stage2 = gr.Checkbox(label="Linear Stage2 Guidance", value=False)
259
- spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
260
- maximum=1., value=0., step=0.05)
261
- with gr.Row():
262
- with gr.Column():
263
- diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16",
264
- interactive=True)
265
- with gr.Column():
266
- ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16",
267
- interactive=True)
268
- with gr.Column():
269
- color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", value="Wavelet",
270
- interactive=True)
271
- with gr.Column():
272
- model_select = gr.Radio(["v0-Q", "v0-F"], label="Model Selection", value="v0-Q",
273
- interactive=True)
274
-
275
- with gr.Column():
276
- gr.Markdown("<center>Stage2 Output</center>")
277
- if not args.use_image_slider:
278
- result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery1")
279
- else:
280
- result_gallery = ImageSlider(label='Output', show_label=False, elem_id="gallery1")
281
- with gr.Row():
282
- with gr.Column():
283
- denoise_button = gr.Button(value="Stage1 Run")
284
- with gr.Column():
285
- llave_button = gr.Button(value="LlaVa Run")
286
- with gr.Column():
287
- diffusion_button = gr.Button(value="Stage2 Run")
288
- with gr.Row():
289
- with gr.Column():
290
- param_setting = gr.Dropdown(["Quality", "Fidelity"], interactive=True, label="Param Setting",
291
- value="Quality")
292
- with gr.Column():
293
- restart_button = gr.Button(value="Reset Param", scale=2)
294
- with gr.Accordion("Feedback", open=True):
295
- fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1,
296
- interactive=True)
297
- fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.')
298
- submit_button = gr.Button(value="Submit Feedback")
299
- with gr.Row():
300
- gr.Markdown(claim_md)
301
- event_id = gr.Textbox(label="Event ID", value="", visible=False)
302
-
303
- llave_button.click(fn=llave_process, inputs=[denoise_image, temperature, top_p, qs], outputs=[prompt])
304
- denoise_button.click(fn=stage1_process, inputs=[input_image, gamma_correction],
305
- outputs=[denoise_image])
306
- stage2_ips = [input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2,
307
- s_cfg, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction,
308
- linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select]
309
- diffusion_button.click(fn=stage2_process, inputs=stage2_ips, outputs=[result_gallery, event_id, fb_score, fb_text])
310
- restart_button.click(fn=load_and_reset, inputs=[param_setting],
311
- outputs=[edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt,
312
- color_fix_type, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2])
313
- submit_button.click(fn=submit_feedback, inputs=[event_id, fb_score, fb_text], outputs=[fb_text])
314
- block.launch(server_name=server_ip, server_port=server_port)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from gradio_imageslider import ImageSlider
5
+ import argparse
6
+ from SUPIR.util import HWC3, upscale_image, fix_resize, convert_dtype
7
+ import numpy as np
8
+ import torch
9
+ from SUPIR.util import create_SUPIR_model, load_QF_ckpt
10
+ from PIL import Image
11
+ from llava.llava_agent import LLavaAgent
12
+ from CKPT_PTH import LLAVA_MODEL_PATH
13
+ import einops
14
+ import copy
15
+ import time
16
+
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument("--opt", type=str, default='options/SUPIR_v0.yaml')
19
+ parser.add_argument("--ip", type=str, default='127.0.0.1')
20
+ parser.add_argument("--port", type=int, default='6688')
21
+ parser.add_argument("--no_llava", action='store_true', default=False)
22
+ parser.add_argument("--use_image_slider", action='store_true', default=False)
23
+ parser.add_argument("--log_history", action='store_true', default=False)
24
+ parser.add_argument("--loading_half_params", action='store_true', default=False)
25
+ parser.add_argument("--use_tile_vae", action='store_true', default=False)
26
+ parser.add_argument("--encoder_tile_size", type=int, default=512)
27
+ parser.add_argument("--decoder_tile_size", type=int, default=64)
28
+ parser.add_argument("--load_8bit_llava", action='store_true', default=False)
29
+ args = parser.parse_args()
30
+ server_ip = args.ip
31
+ server_port = args.port
32
+ use_llava = not args.no_llava
33
+
34
+ if torch.cuda.device_count() >= 2:
35
+ SUPIR_device = 'cuda:0'
36
+ LLaVA_device = 'cuda:1'
37
+ elif torch.cuda.device_count() == 1:
38
+ SUPIR_device = 'cuda:0'
39
+ LLaVA_device = 'cuda:0'
40
+ else:
41
+ SUPIR_device = 'cpu'
42
+ LLaVA_device = 'cpu'
43
+
44
+ # load SUPIR
45
+ model, default_setting = create_SUPIR_model(args.opt, SUPIR_sign='Q', load_default_setting=True)
46
+ if args.loading_half_params:
47
+ model = model.half()
48
+ if args.use_tile_vae:
49
+ model.init_tile_vae(encoder_tile_size=args.encoder_tile_size, decoder_tile_size=args.decoder_tile_size)
50
+ model = model.to(SUPIR_device)
51
+ model.first_stage_model.denoise_encoder_s1 = copy.deepcopy(model.first_stage_model.denoise_encoder)
52
+ model.current_model = 'v0-Q'
53
+ ckpt_Q, ckpt_F = load_QF_ckpt(args.opt)
54
+
55
+ # load LLaVA
56
+ if use_llava:
57
+ llava_agent = LLavaAgent(LLAVA_MODEL_PATH, device=LLaVA_device, load_8bit=args.load_8bit_llava, load_4bit=False)
58
+ else:
59
+ llava_agent = None
60
+
61
+ def stage1_process(input_image, gamma_correction):
62
+ if torch.cuda.device_count() == 0:
63
+ gr.Warning('Set this space to GPU config to make it work.')
64
+ return None
65
+ torch.cuda.set_device(SUPIR_device)
66
+ LQ = HWC3(input_image)
67
+ LQ = fix_resize(LQ, 512)
68
+ # stage1
69
+ LQ = np.array(LQ) / 255 * 2 - 1
70
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
71
+ LQ = model.batchify_denoise(LQ, is_stage1=True)
72
+ LQ = (LQ[0].permute(1, 2, 0) * 127.5 + 127.5).cpu().numpy().round().clip(0, 255).astype(np.uint8)
73
+ # gamma correction
74
+ LQ = LQ / 255.0
75
+ LQ = np.power(LQ, gamma_correction)
76
+ LQ *= 255.0
77
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
78
+ return LQ
79
+
80
+ def llave_process(input_image, temperature, top_p, qs=None):
81
+ if torch.cuda.device_count() == 0:
82
+ gr.Warning('Set this space to GPU config to make it work.')
83
+ return 'Set this space to GPU config to make it work.'
84
+ torch.cuda.set_device(LLaVA_device)
85
+ if use_llava:
86
+ LQ = HWC3(input_image)
87
+ LQ = Image.fromarray(LQ.astype('uint8'))
88
+ captions = llava_agent.gen_image_caption([LQ], temperature=temperature, top_p=top_p, qs=qs)
89
+ else:
90
+ captions = ['LLaVA is not available. Please add text manually.']
91
+ return captions[0]
92
+
93
+ def stage2_process(input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2,
94
+ s_cfg, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction,
95
+ linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select):
96
+ if torch.cuda.device_count() == 0:
97
+ gr.Warning('Set this space to GPU config to make it work.')
98
+ return None, None, None, None
99
+ torch.cuda.set_device(SUPIR_device)
100
+ event_id = str(time.time_ns())
101
+ event_dict = {'event_id': event_id, 'localtime': time.ctime(), 'prompt': prompt, 'a_prompt': a_prompt,
102
+ 'n_prompt': n_prompt, 'num_samples': num_samples, 'upscale': upscale, 'edm_steps': edm_steps,
103
+ 's_stage1': s_stage1, 's_stage2': s_stage2, 's_cfg': s_cfg, 'seed': seed, 's_churn': s_churn,
104
+ 's_noise': s_noise, 'color_fix_type': color_fix_type, 'diff_dtype': diff_dtype, 'ae_dtype': ae_dtype,
105
+ 'gamma_correction': gamma_correction, 'linear_CFG': linear_CFG, 'linear_s_stage2': linear_s_stage2,
106
+ 'spt_linear_CFG': spt_linear_CFG, 'spt_linear_s_stage2': spt_linear_s_stage2,
107
+ 'model_select': model_select}
108
+
109
+ if model_select != model.current_model:
110
+ if model_select == 'v0-Q':
111
+ print('load v0-Q')
112
+ model.load_state_dict(ckpt_Q, strict=False)
113
+ model.current_model = 'v0-Q'
114
+ elif model_select == 'v0-F':
115
+ print('load v0-F')
116
+ model.load_state_dict(ckpt_F, strict=False)
117
+ model.current_model = 'v0-F'
118
+ input_image = HWC3(input_image)
119
+ input_image = upscale_image(input_image, upscale, unit_resolution=32,
120
+ min_size=1024)
121
+
122
+ LQ = np.array(input_image) / 255.0
123
+ LQ = np.power(LQ, gamma_correction)
124
+ LQ *= 255.0
125
+ LQ = LQ.round().clip(0, 255).astype(np.uint8)
126
+ LQ = LQ / 255 * 2 - 1
127
+ LQ = torch.tensor(LQ, dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(SUPIR_device)[:, :3, :, :]
128
+ if use_llava:
129
+ captions = [prompt]
130
+ else:
131
+ captions = ['']
132
+
133
+ model.ae_dtype = convert_dtype(ae_dtype)
134
+ model.model.dtype = convert_dtype(diff_dtype)
135
+
136
+ samples = model.batchify_sample(LQ, captions, num_steps=edm_steps, restoration_scale=s_stage1, s_churn=s_churn,
137
+ s_noise=s_noise, cfg_scale=s_cfg, control_scale=s_stage2, seed=seed,
138
+ num_samples=num_samples, p_p=a_prompt, n_p=n_prompt, color_fix_type=color_fix_type,
139
+ use_linear_CFG=linear_CFG, use_linear_control_scale=linear_s_stage2,
140
+ cfg_scale_start=spt_linear_CFG, control_scale_start=spt_linear_s_stage2)
141
+
142
+ x_samples = (einops.rearrange(samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().round().clip(
143
+ 0, 255).astype(np.uint8)
144
+ results = [x_samples[i] for i in range(num_samples)]
145
+
146
+ if args.log_history:
147
+ os.makedirs(f'./history/{event_id[:5]}/{event_id[5:]}', exist_ok=True)
148
+ with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
149
+ f.write(str(event_dict))
150
+ f.close()
151
+ Image.fromarray(input_image).save(f'./history/{event_id[:5]}/{event_id[5:]}/LQ.png')
152
+ for i, result in enumerate(results):
153
+ Image.fromarray(result).save(f'./history/{event_id[:5]}/{event_id[5:]}/HQ_{i}.png')
154
+ return [input_image] + results, event_id, 3, ''
155
+
156
+
157
+ def load_and_reset(param_setting):
158
+ edm_steps = default_setting.edm_steps
159
+ s_stage2 = 1.0
160
+ s_stage1 = -1.0
161
+ s_churn = 5
162
+ s_noise = 1.003
163
+ a_prompt = 'Cinematic, High Contrast, highly detailed, taken using a Canon EOS R camera, hyper detailed photo - ' \
164
+ 'realistic maximum detail, 32k, Color Grading, ultra HD, extreme meticulous detailing, skin pore ' \
165
+ 'detailing, hyper sharpness, perfect without deformations.'
166
+ n_prompt = 'painting, oil painting, illustration, drawing, art, sketch, oil painting, cartoon, CG Style, ' \
167
+ '3D render, unreal engine, blurring, dirty, messy, worst quality, low quality, frames, watermark, ' \
168
+ 'signature, jpeg artifacts, deformed, lowres, over-smooth'
169
+ color_fix_type = 'Wavelet'
170
+ spt_linear_s_stage2 = 0.0
171
+ linear_s_stage2 = False
172
+ linear_CFG = True
173
+ if param_setting == "Quality":
174
+ s_cfg = default_setting.s_cfg_Quality
175
+ spt_linear_CFG = default_setting.spt_linear_CFG_Quality
176
+ elif param_setting == "Fidelity":
177
+ s_cfg = default_setting.s_cfg_Fidelity
178
+ spt_linear_CFG = default_setting.spt_linear_CFG_Fidelity
179
+ else:
180
+ raise NotImplementedError
181
+ return edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt, color_fix_type, linear_CFG, \
182
+ linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2
183
+
184
+
185
+ def submit_feedback(event_id, fb_score, fb_text):
186
+ if args.log_history:
187
+ with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'r') as f:
188
+ event_dict = eval(f.read())
189
+ f.close()
190
+ event_dict['feedback'] = {'score': fb_score, 'text': fb_text}
191
+ with open(f'./history/{event_id[:5]}/{event_id[5:]}/logs.txt', 'w') as f:
192
+ f.write(str(event_dict))
193
+ f.close()
194
+ return 'Submit successfully, thank you for your comments!'
195
+ else:
196
+ return 'Submit failed, the server is not set to log history.'
197
+
198
+ if torch.cuda.device_count() == 0:
199
+ title_md = """
200
+ # **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
201
+
202
+ ⚠️To use SUPIR, [Duplicate this space](https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true) and set a **GPU**.
203
+
204
+ You can't use SUPIR directly here as this space runs on a CPU, which not enough for SUPIR. This is a template space. Please provide feedback if you have issues.
205
+ """
206
+ else:
207
+ title_md = """
208
+ # **SUPIR: Practicing Model Scaling for Photo-Realistic Image Restoration**
209
+
210
+ ⚠️SUPIR is still a research project under tested and is not yet a stable commercial product.
211
+
212
+ [[Paper](https://arxiv.org/abs/2401.13627)] &emsp; [[Project Page](http://supir.xpixel.group/)] &emsp; [[How to play](https://github.com/Fanghua-Yu/SUPIR/blob/master/assets/DemoGuide.png)]
213
+ """
214
+
215
+
216
+ claim_md = """
217
+ ## **Terms of use**
218
+
219
+ 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.
220
+
221
+ ## **License**
222
+
223
+ 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.
224
+ """
225
+
226
+
227
+ block = gr.Blocks(title='SUPIR').queue()
228
+ with block:
229
+ with gr.Row():
230
+ gr.Markdown(title_md)
231
+ with gr.Row():
232
+ with gr.Column():
233
+ with gr.Row(equal_height=True):
234
+ with gr.Column():
235
+ gr.Markdown("<center>Input</center>")
236
+ input_image = gr.Image(type="numpy", elem_id="image-input", height=400, width=400)
237
+ with gr.Column():
238
+ gr.Markdown("<center>Stage1 Output</center>")
239
+ denoise_image = gr.Image(type="numpy", elem_id="image-s1", height=400, width=400)
240
+ prompt = gr.Textbox(label="Prompt", value="")
241
+ with gr.Accordion("Stage1 options", open=False):
242
+ gamma_correction = gr.Slider(label="Gamma Correction", minimum=0.1, maximum=2.0, value=1.0, step=0.1)
243
+ with gr.Accordion("LLaVA options", open=False):
244
+ temperature = gr.Slider(label="Temperature", minimum=0., maximum=1.0, value=0.2, step=0.1)
245
+ top_p = gr.Slider(label="Top P", minimum=0., maximum=1.0, value=0.7, step=0.1)
246
+ qs = gr.Textbox(label="Question", value="Describe this image and its style in a very detailed manner. "
247
+ "The image is a realistic photography, not an art painting.")
248
+ with gr.Accordion("Stage2 options", open=False):
249
+ num_samples = gr.Slider(label="Num Samples", minimum=1, maximum=4 if not args.use_image_slider else 1
250
+ , value=1, step=1)
251
+ upscale = gr.Slider(label="Upscale", minimum=1, maximum=8, value=1, step=1)
252
+ edm_steps = gr.Slider(label="Steps", minimum=1, maximum=200, value=default_setting.edm_steps, step=1)
253
+ s_cfg = gr.Slider(label="Text Guidance Scale", minimum=1.0, maximum=15.0,
254
+ value=default_setting.s_cfg_Quality, step=0.1)
255
+ s_stage2 = gr.Slider(label="Stage2 Guidance Strength", minimum=0., maximum=1., value=1., step=0.05)
256
+ s_stage1 = gr.Slider(label="Stage1 Guidance Strength", minimum=-1.0, maximum=6.0, value=-1.0, step=1.0)
257
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
258
+ s_churn = gr.Slider(label="S-Churn", minimum=0, maximum=40, value=5, step=1)
259
+ s_noise = gr.Slider(label="S-Noise", minimum=1.0, maximum=1.1, value=1.003, step=0.001)
260
+ a_prompt = gr.Textbox(label="Default Positive Prompt",
261
+ value='Cinematic, High Contrast, highly detailed, taken using a Canon EOS R '
262
+ 'camera, hyper detailed photo - realistic maximum detail, 32k, Color '
263
+ 'Grading, ultra HD, extreme meticulous detailing, skin pore detailing, '
264
+ 'hyper sharpness, perfect without deformations.')
265
+ n_prompt = gr.Textbox(label="Default Negative Prompt",
266
+ value='painting, oil painting, illustration, drawing, art, sketch, oil painting, '
267
+ 'cartoon, CG Style, 3D render, unreal engine, blurring, dirty, messy, '
268
+ 'worst quality, low quality, frames, watermark, signature, jpeg artifacts, '
269
+ 'deformed, lowres, over-smooth')
270
+ with gr.Row():
271
+ with gr.Column():
272
+ linear_CFG = gr.Checkbox(label="Linear CFG", value=True)
273
+ spt_linear_CFG = gr.Slider(label="CFG Start", minimum=1.0,
274
+ maximum=9.0, value=default_setting.spt_linear_CFG_Quality, step=0.5)
275
+ with gr.Column():
276
+ linear_s_stage2 = gr.Checkbox(label="Linear Stage2 Guidance", value=False)
277
+ spt_linear_s_stage2 = gr.Slider(label="Guidance Start", minimum=0.,
278
+ maximum=1., value=0., step=0.05)
279
+ with gr.Row():
280
+ with gr.Column():
281
+ diff_dtype = gr.Radio(['fp32', 'fp16', 'bf16'], label="Diffusion Data Type", value="fp16",
282
+ interactive=True)
283
+ with gr.Column():
284
+ ae_dtype = gr.Radio(['fp32', 'bf16'], label="Auto-Encoder Data Type", value="bf16",
285
+ interactive=True)
286
+ with gr.Column():
287
+ color_fix_type = gr.Radio(["None", "AdaIn", "Wavelet"], label="Color-Fix Type", value="Wavelet",
288
+ interactive=True)
289
+ with gr.Column():
290
+ model_select = gr.Radio(["v0-Q", "v0-F"], label="Model Selection", value="v0-Q",
291
+ interactive=True)
292
+
293
+ with gr.Column():
294
+ gr.Markdown("<center>Stage2 Output</center>")
295
+ if not args.use_image_slider:
296
+ result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery1")
297
+ else:
298
+ result_gallery = ImageSlider(label='Output', show_label=False, elem_id="gallery1")
299
+ with gr.Row():
300
+ with gr.Column():
301
+ denoise_button = gr.Button(value="Stage1 Run")
302
+ with gr.Column():
303
+ llave_button = gr.Button(value="LlaVa Run")
304
+ with gr.Column():
305
+ diffusion_button = gr.Button(value="Stage2 Run")
306
+ with gr.Row():
307
+ with gr.Column():
308
+ param_setting = gr.Dropdown(["Quality", "Fidelity"], interactive=True, label="Param Setting",
309
+ value="Quality")
310
+ with gr.Column():
311
+ restart_button = gr.Button(value="Reset Param", scale=2)
312
+ with gr.Accordion("Feedback", open=True):
313
+ fb_score = gr.Slider(label="Feedback Score", minimum=1, maximum=5, value=3, step=1,
314
+ interactive=True)
315
+ fb_text = gr.Textbox(label="Feedback Text", value="", placeholder='Please enter your feedback here.')
316
+ submit_button = gr.Button(value="Submit Feedback")
317
+ with gr.Row():
318
+ gr.Markdown(claim_md)
319
+ event_id = gr.Textbox(label="Event ID", value="", visible=False)
320
+
321
+ llave_button.click(fn=llave_process, inputs=[denoise_image, temperature, top_p, qs], outputs=[prompt])
322
+ denoise_button.click(fn=stage1_process, inputs=[input_image, gamma_correction],
323
+ outputs=[denoise_image])
324
+ stage2_ips = [input_image, prompt, a_prompt, n_prompt, num_samples, upscale, edm_steps, s_stage1, s_stage2,
325
+ s_cfg, seed, s_churn, s_noise, color_fix_type, diff_dtype, ae_dtype, gamma_correction,
326
+ linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2, model_select]
327
+ diffusion_button.click(fn=stage2_process, inputs=stage2_ips, outputs=[result_gallery, event_id, fb_score, fb_text])
328
+ restart_button.click(fn=load_and_reset, inputs=[param_setting],
329
+ outputs=[edm_steps, s_cfg, s_stage2, s_stage1, s_churn, s_noise, a_prompt, n_prompt,
330
+ color_fix_type, linear_CFG, linear_s_stage2, spt_linear_CFG, spt_linear_s_stage2])
331
+ submit_button.click(fn=submit_feedback, inputs=[event_id, fb_score, fb_text], outputs=[fb_text])
332
+ block.launch(server_name=server_ip, server_port=server_port)