Fabrice-TIERCELIN commited on
Commit
3a6b630
1 Parent(s): a0c090f

Delete gradio_demo.py

Browse files
Files changed (1) hide show
  1. gradio_demo.py +0 -314
gradio_demo.py DELETED
@@ -1,314 +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
-
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)