Fabrice-TIERCELIN commited on
Commit
f33459e
1 Parent(s): be04fa8

Delete gradio_demo_tiled.py

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