MultiMatrix commited on
Commit
55aa9a0
·
verified ·
1 Parent(s): 8086127

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +281 -0
app.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import math
3
+ import os
4
+
5
+ import numpy as np
6
+ import torch
7
+ import einops
8
+ import pytorch_lightning as pl
9
+ import gradio as gr
10
+ from PIL import Image
11
+ from omegaconf import OmegaConf
12
+ from openxlab.model import download
13
+ from tqdm import tqdm
14
+
15
+ from model.spaced_sampler import SpacedSampler
16
+ from model.cldm import ControlLDM
17
+ from utils.image import auto_resize, pad
18
+ from utils.common import instantiate_from_config, load_state_dict
19
+ from utils.face_restoration_helper import FaceRestoreHelper
20
+
21
+
22
+ # download models to local directory
23
+ download(model_repo="linxinqi/DiffBIR", model_name="diffbir_general_full_v1")
24
+ download(model_repo="linxinqi/DiffBIR", model_name="diffbir_general_swinir_v1")
25
+ download(model_repo="linxinqi/DiffBIR", model_name="diffbir_face_full_v1")
26
+
27
+ config = "cldm.yaml"
28
+ general_full_ckpt = "general_full_v1.ckpt"
29
+ general_swinir_ckpt = "general_swinir_v1.ckpt"
30
+ face_full_ckpt = "face_full_v1.ckpt"
31
+
32
+ # create general model
33
+ general_model: ControlLDM = instantiate_from_config(OmegaConf.load(config)).cuda()
34
+ load_state_dict(general_model, torch.load(general_full_ckpt, map_location="cuda"), strict=True)
35
+ load_state_dict(general_model.preprocess_model, torch.load(general_swinir_ckpt, map_location="cuda"), strict=True)
36
+ general_model.freeze()
37
+
38
+ # keep a reference of general model's preprocess model and parallel model
39
+ general_preprocess_model = general_model.preprocess_model
40
+ general_control_model = general_model.control_model
41
+
42
+ # create face model
43
+ face_model: ControlLDM = instantiate_from_config(OmegaConf.load(config))
44
+ load_state_dict(face_model, torch.load(face_full_ckpt, map_location="cpu"), strict=True)
45
+ face_model.freeze()
46
+
47
+ # share the pretrained weights with general model
48
+ _tmp = face_model.first_stage_model
49
+ face_model.first_stage_model = general_model.first_stage_model
50
+ del _tmp
51
+
52
+ _tmp = face_model.cond_stage_model
53
+ face_model.cond_stage_model = general_model.cond_stage_model
54
+ del _tmp
55
+
56
+ _tmp = face_model.model
57
+ face_model.model = general_model.model
58
+ del _tmp
59
+
60
+ face_model.cuda()
61
+
62
+ def to_tensor(image, device, bgr2rgb=False):
63
+ if bgr2rgb:
64
+ image = image[:, :, ::-1]
65
+ image_tensor = torch.tensor(image[None] / 255.0, dtype=torch.float32, device=device).clamp_(0, 1)
66
+ image_tensor = einops.rearrange(image_tensor, "n h w c -> n c h w").contiguous()
67
+ return image_tensor
68
+
69
+ def to_array(image):
70
+ image = image.clamp(0, 1)
71
+ image_array = (einops.rearrange(image, "b c h w -> b h w c") * 255).cpu().numpy().clip(0, 255).astype(np.uint8)
72
+ return image_array
73
+
74
+ @torch.no_grad()
75
+ def process(
76
+ control_img: Image.Image,
77
+ use_face_model: bool,
78
+ num_samples: int,
79
+ sr_scale: int,
80
+ disable_preprocess_model: bool,
81
+ strength: float,
82
+ positive_prompt: str,
83
+ negative_prompt: str,
84
+ cfg_scale: float,
85
+ steps: int,
86
+ use_color_fix: bool,
87
+ seed: int,
88
+ tiled: bool,
89
+ tile_size: int,
90
+ tile_stride: int
91
+ # progress = gr.Progress(track_tqdm=True)
92
+ ) -> List[np.ndarray]:
93
+ pl.seed_everything(seed)
94
+
95
+ global general_model
96
+ global face_model
97
+
98
+ model = general_model
99
+ sampler = SpacedSampler(model, var_type="fixed_small")
100
+ model.control_scales = [strength] * 13
101
+ if use_face_model:
102
+ print("use face model")
103
+ sampler_face = SpacedSampler(face_model, var_type="fixed_small")
104
+ face_model.control_scales = [strength] * 13
105
+
106
+ # prepare condition
107
+ if sr_scale != 1:
108
+ control_img = control_img.resize(
109
+ tuple(math.ceil(x * sr_scale) for x in control_img.size),
110
+ Image.BICUBIC
111
+ )
112
+ input_size = control_img.size
113
+ if not tiled:
114
+ control_img = auto_resize(control_img, 512)
115
+ else:
116
+ control_img = auto_resize(control_img, tile_size)
117
+ h, w = control_img.height, control_img.width
118
+ control_img = pad(np.array(control_img), scale=64) # HWC, RGB, [0, 255]
119
+
120
+ if use_face_model:
121
+ # set up FaceRestoreHelper
122
+ face_size = 512
123
+ face_helper = FaceRestoreHelper(device=model.device, upscale_factor=1, face_size=face_size, use_parse=True)
124
+ # read BGR numpy [0, 255]
125
+ face_helper.read_image(np.array(control_img)[:, :, ::-1])
126
+ # detect faces in input lq control image
127
+ face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
128
+ face_helper.align_warp_face()
129
+
130
+ control = to_tensor(control_img, device=model.device)
131
+ if not disable_preprocess_model:
132
+ control = model.preprocess_model(control)
133
+ height, width = control.size(-2), control.size(-1)
134
+
135
+ preds = []
136
+ for _ in tqdm(range(num_samples)):
137
+ shape = (1, 4, height // 8, width // 8)
138
+ x_T = torch.randn(shape, device=model.device, dtype=torch.float32)
139
+ if not tiled:
140
+ samples = sampler.sample(
141
+ steps=steps, shape=shape, cond_img=control,
142
+ positive_prompt=positive_prompt, negative_prompt=negative_prompt, x_T=x_T,
143
+ cfg_scale=cfg_scale, cond_fn=None,
144
+ color_fix_type="wavelet" if use_color_fix else "none"
145
+ )
146
+ else:
147
+ samples = sampler.sample_with_mixdiff(
148
+ tile_size=int(tile_size), tile_stride=int(tile_stride),
149
+ steps=steps, shape=shape, cond_img=control,
150
+ positive_prompt=positive_prompt, negative_prompt=negative_prompt, x_T=x_T,
151
+ cfg_scale=cfg_scale, cond_fn=None,
152
+ color_fix_type="wavelet" if use_color_fix else "none"
153
+ )
154
+ restored_bg = to_array(samples)
155
+
156
+ if use_face_model and len(face_helper.cropped_faces) > 0:
157
+ shape_face = (1, 4, face_size // 8, face_size // 8)
158
+ x_T_face = torch.randn(shape_face, device=model.device, dtype=torch.float32)
159
+ # face detected
160
+ for cropped_face in face_helper.cropped_faces:
161
+ cropped_face = to_tensor(cropped_face, device=model.device, bgr2rgb=True)
162
+ if not disable_preprocess_model:
163
+ cropped_face = face_model.preprocess_model(cropped_face)
164
+ samples_face = sampler_face.sample(
165
+ steps=steps, shape=shape, cond_img=cropped_face,
166
+ positive_prompt=positive_prompt, negative_prompt=negative_prompt, x_T=x_T_face,
167
+ cfg_scale=1.0, cond_fn=None,
168
+ color_fix_type="wavelet" if use_color_fix else "none"
169
+ )
170
+ restored_face = to_array(samples_face)
171
+ face_helper.add_restored_face(restored_face[0])
172
+ face_helper.get_inverse_affine(None)
173
+ # paste each restored face to the input image
174
+ restored_img = face_helper.paste_faces_to_input_image(
175
+ upsample_img=restored_bg[0]
176
+ )
177
+
178
+ # remove padding and resize to input size
179
+ restored_img = Image.fromarray(restored_img[:h, :w, :]).resize(input_size, Image.LANCZOS)
180
+ preds.append(np.array(restored_img))
181
+ return preds
182
+
183
+ MAX_SIZE = int(os.getenv("MAX_SIZE"))
184
+ CONCURRENCY_COUNT = int(os.getenv("CONCURRENCY_COUNT"))
185
+
186
+ print(f"max size = {MAX_SIZE}, concurrency_count = {CONCURRENCY_COUNT}")
187
+
188
+ MARKDOWN = \
189
+ """
190
+ ## DiffBIR: Towards Blind Image Restoration with Generative Diffusion Prior
191
+
192
+ [GitHub](https://github.com/XPixelGroup/DiffBIR) | [Paper](https://arxiv.org/abs/2308.15070) | [Project Page](https://0x3f3f3f3fun.github.io/projects/diffbir/)
193
+
194
+ If DiffBIR is helpful for you, please help star the GitHub Repo. Thanks!
195
+
196
+ ## NOTE
197
+
198
+ 1. This app processes user-uploaded images in sequence, so it may take some time before your image begins to be processed.
199
+ 2. This is a publicly-used app, so please don't upload large images (>= 1024) to avoid taking up too much time.
200
+ """
201
+
202
+ block = gr.Blocks().queue(concurrency_count=CONCURRENCY_COUNT, max_size=MAX_SIZE)
203
+ with block:
204
+ with gr.Row():
205
+ gr.Markdown(MARKDOWN)
206
+ with gr.Row():
207
+ with gr.Column():
208
+ input_image = gr.Image(source="upload", type="pil")
209
+ run_button = gr.Button(label="Run")
210
+ with gr.Accordion("Options", open=True):
211
+ use_face_model = gr.Checkbox(label="Use Face Model", value=False)
212
+ tiled = gr.Checkbox(label="Tiled", value=False)
213
+ tile_size = gr.Slider(label="Tile Size", minimum=512, maximum=1024, value=512, step=256)
214
+ tile_stride = gr.Slider(label="Tile Stride", minimum=256, maximum=512, value=256, step=128)
215
+ num_samples = gr.Slider(label="Number Of Samples", minimum=1, maximum=12, value=1, step=1)
216
+ sr_scale = gr.Number(label="SR Scale", value=1)
217
+ positive_prompt = gr.Textbox(label="Positive Prompt", value="")
218
+ negative_prompt = gr.Textbox(
219
+ label="Negative Prompt",
220
+ value="longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality"
221
+ )
222
+ cfg_scale = gr.Slider(label="Classifier Free Guidance Scale (Set to a value larger than 1 to enable it!)", minimum=0.1, maximum=30.0, value=1.0, step=0.1)
223
+ strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
224
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=50, step=1)
225
+ disable_preprocess_model = gr.Checkbox(label="Disable Preprocess Model", value=False)
226
+ use_color_fix = gr.Checkbox(label="Use Color Correction", value=True)
227
+ seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, value=231)
228
+ with gr.Column():
229
+ result_gallery = gr.Gallery(label="Output", show_label=False, elem_id="gallery").style(height="auto", grid=2)
230
+ # gr.Markdown("## Image Examples")
231
+ gr.Examples(
232
+ examples=[
233
+ ["examples/face/0229.png", True, 1, 1, False, 1.0, "", "", 1.0, 50, True, 231, False, 512, 256],
234
+ ["examples/face/hermione.jpg", True, 1, 2, False, 1.0, "", "", 1.0, 50, True, 231, False, 512, 256],
235
+ ["examples/general/14.jpg", False, 1, 4, False, 1.0, "", "", 1.0, 50, True, 231, False, 512, 256],
236
+ ["examples/general/49.jpg", False, 1, 4, False, 1.0, "", "", 1.0, 50, True, 231, False, 512, 256],
237
+ ["examples/general/53.jpeg", False, 1, 4, False, 1.0, "", "", 1.0, 50, True, 231, False, 512, 256],
238
+ # ["examples/general/bx2vqrcj.png", False, 1, 4, False, 1.0, "", "", 1.0, 50, True, 231, True, 512, 256],
239
+ ],
240
+ inputs=[
241
+ input_image,
242
+ use_face_model,
243
+ num_samples,
244
+ sr_scale,
245
+ disable_preprocess_model,
246
+ strength,
247
+ positive_prompt,
248
+ negative_prompt,
249
+ cfg_scale,
250
+ steps,
251
+ use_color_fix,
252
+ seed,
253
+ tiled,
254
+ tile_size,
255
+ tile_stride
256
+ ],
257
+ outputs=[result_gallery],
258
+ fn=process,
259
+ cache_examples=True,
260
+ )
261
+
262
+ inputs = [
263
+ input_image,
264
+ use_face_model,
265
+ num_samples,
266
+ sr_scale,
267
+ disable_preprocess_model,
268
+ strength,
269
+ positive_prompt,
270
+ negative_prompt,
271
+ cfg_scale,
272
+ steps,
273
+ use_color_fix,
274
+ seed,
275
+ tiled,
276
+ tile_size,
277
+ tile_stride
278
+ ]
279
+ run_button.click(fn=process, inputs=inputs, outputs=[result_gallery])
280
+
281
+ block.launch()