Fabrice-TIERCELIN commited on
Commit
60f71f8
1 Parent(s): 5c3932c

Delete gradio_demo_face.py

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