SunderAli17 commited on
Commit
be52250
1 Parent(s): 50c5efb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -0
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
4
+
5
+ import torch
6
+ import numpy as np
7
+ import gradio as gr
8
+ import spaces
9
+ from PIL import Image
10
+
11
+ from diffusers import DDPMScheduler
12
+ from pipelines.lcm_single_step_scheduler import LCMSingleStepScheduler
13
+
14
+ from module.ip_adapter.utils import load_adapter_to_pipe
15
+ from pipelines.sdxl_SAKBIR import SAKBIRPipeline
16
+
17
+ def resize_img(input_image, max_side=1280, min_side=1024, size=None,
18
+ pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64):
19
+
20
+ w, h = input_image.size
21
+ if size is not None:
22
+ w_resize_new, h_resize_new = size
23
+ else:
24
+ # ratio = min_side / min(h, w)
25
+ # w, h = round(ratio*w), round(ratio*h)
26
+ ratio = max_side / max(h, w)
27
+ input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode)
28
+ w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number
29
+ h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number
30
+ input_image = input_image.resize([w_resize_new, h_resize_new], mode)
31
+
32
+ if pad_to_max_side:
33
+ res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255
34
+ offset_x = (max_side - w_resize_new) // 2
35
+ offset_y = (max_side - h_resize_new) // 2
36
+ res[offset_y:offset_y+h_resize_new, offset_x:offset_x+w_resize_new] = np.array(input_image)
37
+ input_image = Image.fromarray(res)
38
+ return input_image
39
+
40
+ from huggingface_hub import hf_hub_download
41
+
42
+ hf_hub_download(repo_id="SunderAli17/SAKBIR", filename="models/adapter.pt", local_dir=".")
43
+ hf_hub_download(repo_id="SunderAli17/SAKBIR", filename="models/aggregator.pt", local_dir=".")
44
+ hf_hub_download(repo_id="SunderAli17/SAKBIR", filename="models/previewer_lora_weights.bin", local_dir=".")
45
+
46
+ SAKBIR_path = f'./models'
47
+
48
+ device = "cuda" if torch.cuda.is_available() else "cpu"
49
+ sdxl_repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
50
+ dinov2_repo_id = "facebook/dinov2-large"
51
+ lcm_repo_id = "latent-consistency/lcm-lora-sdxl"
52
+
53
+ if torch.cuda.is_available():
54
+ torch_dtype = torch.float16
55
+ else:
56
+ torch_dtype = torch.float32
57
+
58
+ # Load pretrained models.
59
+ print("Initializing pipeline...")
60
+ pipe = SAKBIRPipeline.from_pretrained(
61
+ sdxl_repo_id,
62
+ torch_dtype=torch_dtype,
63
+ )
64
+
65
+ # Image prompt projector.
66
+ print("Loading LQ-Adapter...")
67
+ load_adapter_to_pipe(
68
+ pipe,
69
+ f"{SAKBIR_path}/adapter.pt",
70
+ dinov2_repo_id,
71
+ )
72
+
73
+ # Prepare previewer
74
+ lora_alpha = pipe.prepare_previewers(SAKBIR_path)
75
+ print(f"use lora alpha {lora_alpha}")
76
+ lora_alpha = pipe.prepare_previewers(lcm_repo_id, use_lcm=True)
77
+ print(f"use lora alpha {lora_alpha}")
78
+ pipe.to(device=device, dtype=torch_dtype)
79
+ pipe.scheduler = DDPMScheduler.from_pretrained(sdxl_repo_id, subfolder="scheduler")
80
+ lcm_scheduler = LCMSingleStepScheduler.from_config(pipe.scheduler.config)
81
+
82
+ # Load weights.
83
+ print("Loading checkpoint...")
84
+ aggregator_state_dict = torch.load(
85
+ f"{SAKBIR_path}/aggregator.pt",
86
+ map_location="cpu"
87
+ )
88
+ pipe.aggregator.load_state_dict(aggregator_state_dict, strict=True)
89
+ pipe.aggregator.to(device=device, dtype=torch_dtype)
90
+
91
+ MAX_SEED = np.iinfo(np.int32).max
92
+ MAX_IMAGE_SIZE = 1024
93
+
94
+ PROMPT = "Photorealistic, highly detailed, hyper detailed photo - realistic maximum detail, 32k, \
95
+ ultra HD, extreme meticulous detailing, skin pore detailing, \
96
+ hyper sharpness, perfect without deformations, \
97
+ taken using a Canon EOS R camera, Cinematic, High Contrast, Color Grading. "
98
+
99
+ NEG_PROMPT = "blurry, out of focus, unclear, depth of field, over-smooth, \
100
+ sketch, oil painting, cartoon, CG Style, 3D render, unreal engine, \
101
+ dirty, messy, worst quality, low quality, frames, painting, illustration, drawing, art, \
102
+ watermark, signature, jpeg artifacts, deformed, lowres"
103
+
104
+ def unpack_pipe_out(preview_row, index):
105
+ return preview_row[index][0]
106
+
107
+ def dynamic_preview_slider(sampling_steps):
108
+ print(sampling_steps)
109
+ return gr.Slider(label="Restoration Previews", value=sampling_steps-1, minimum=0, maximum=sampling_steps-1, step=1)
110
+
111
+ def dynamic_guidance_slider(sampling_steps):
112
+ return gr.Slider(label="Start Free Rendering", value=sampling_steps, minimum=0, maximum=sampling_steps, step=1)
113
+
114
+ def show_final_preview(preview_row):
115
+ return preview_row[-1][0]
116
+
117
+ @spaces.GPU(duration=70) #[uncomment to use ZeroGPU]
118
+ @torch.no_grad()
119
+ def SAKBIR_restore(
120
+ lq, prompt="", steps=30, cfg_scale=7.0, guidance_end=1.0,
121
+ creative_restoration=False, seed=3407, height=1024, width=1024, preview_start=0.0, progress=gr.Progress(track_tqdm=True)):
122
+ if creative_restoration:
123
+ if "lcm" not in pipe.unet.active_adapters():
124
+ pipe.unet.set_adapter('lcm')
125
+ else:
126
+ if "previewer" not in pipe.unet.active_adapters():
127
+ pipe.unet.set_adapter('previewer')
128
+
129
+ if isinstance(guidance_end, int):
130
+ guidance_end = guidance_end / steps
131
+ elif guidance_end > 1.0:
132
+ guidance_end = guidance_end / steps
133
+ if isinstance(preview_start, int):
134
+ preview_start = preview_start / steps
135
+ elif preview_start > 1.0:
136
+ preview_start = preview_start / steps
137
+
138
+ w, h = lq.size
139
+ if w == h :
140
+ lq = [resize_img(lq.convert("RGB"), size=(width, height))]
141
+ else:
142
+ lq = [resize_img(lq.convert("RGB"), size=None)]
143
+
144
+ generator = torch.Generator(device=device).manual_seed(seed)
145
+ timesteps = [
146
+ i * (1000//steps) + pipe.scheduler.config.steps_offset for i in range(0, steps)
147
+ ]
148
+ timesteps = timesteps[::-1]
149
+
150
+ prompt = PROMPT if len(prompt)==0 else prompt
151
+ neg_prompt = NEG_PROMPT
152
+
153
+ out = pipe(
154
+ prompt=[prompt]*len(lq),
155
+ image=lq,
156
+ num_inference_steps=steps,
157
+ generator=generator,
158
+ timesteps=timesteps,
159
+ negative_prompt=[neg_prompt]*len(lq),
160
+ guidance_scale=cfg_scale,
161
+ control_guidance_end=guidance_end,
162
+ preview_start=preview_start,
163
+ previewer_scheduler=lcm_scheduler,
164
+ return_dict=False,
165
+ save_preview_row=True,
166
+ )
167
+ for i, preview_img in enumerate(out[1]):
168
+ preview_img.append(f"preview_{i}")
169
+ return out[0][0], out[1]
170
+
171
+ examples = [
172
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
173
+ "An astronaut riding a green horse",
174
+ "A delicious ceviche cheesecake slice",
175
+ ]
176
+
177
+ css="""
178
+ #col-container {
179
+ margin: 0 auto;
180
+ max-width: 640px;
181
+ }
182
+ """
183
+
184
+ with gr.Blocks() as SAK:
185
+ gr.Markdown(
186
+ """
187
+ # SAKBIR: Blind Image Restoration using Generative Networks.
188
+ ### **SAKBIR can restore your degraded image as well as modify it through the imaginative prompts being provided by the user. You can refer to the advance usage details for more information.**
189
+ ## Basic usage: Image Restoration
190
+ 1. Upload the image that you want to restore;
191
+ 2. Optionally, tune the `Steps` `CFG Scale` parameters. Typically higher steps lead to better results, but less than 50 is recommended for efficiency;
192
+ 3. Click `SAKBIR!`.
193
+ """)
194
+ with gr.Row():
195
+ with gr.Column():
196
+ lq_img = gr.Image(label="Low-quality image", type="pil")
197
+
198
+ with gr.Row():
199
+ steps = gr.Number(label="Steps", value=30, step=1)
200
+ cfg_scale = gr.Number(label="CFG Scale", value=7.0, step=0.1)
201
+
202
+ with gr.Row():
203
+ height = gr.Number(label="Height", value=1024, step=1, visible=False)
204
+ width = gr.Number(label="Width", value=1024, step=1, visible=False)
205
+ seed = gr.Number(label="Seed", value=42, step=1)
206
+ # guidance_start = gr.Slider(label="Guidance Start", value=1.0, minimum=0.0, maximum=1.0, step=0.05)
207
+ guidance_end = gr.Slider(label="Start Free Rendering", value=30, minimum=0, maximum=30, step=1)
208
+ preview_start = gr.Slider(label="Preview Start", value=0, minimum=0, maximum=30, step=1)
209
+ prompt = gr.Textbox(label="Restoration prompts (Optional)", placeholder="")
210
+ mode = gr.Checkbox(label="Creative Restoration", value=False)
211
+
212
+ with gr.Row():
213
+ restore_btn = gr.Button("SAKBIR processing!")
214
+ clear_btn = gr.ClearButton()
215
+ gr.Examples(
216
+ examples = ["example_images/lady.png", "example_images/man.png", "example_images/dog.png", "example_images/panda.png", "example_images/sculpture.png", "example_images/cottage.png", "example_images/Naruto.png", "example_images/Konan.png"],
217
+ inputs = [lq_img]
218
+ )
219
+ with gr.Column():
220
+ output = gr.Image(label="Image restored using SAKBIR", type="pil")
221
+ index = gr.Slider(label="Preview Restoration", value=29, minimum=0, maximum=29, step=1)
222
+ preview = gr.Image(label="Preview", type="pil")
223
+
224
+ pipe_out = gr.Gallery(visible=False)
225
+ clear_btn.add([lq_img, output, preview])
226
+ restore_btn.click(
227
+ SAKBIR_restore, inputs=[
228
+ lq_img, prompt, steps, cfg_scale, guidance_end,
229
+ mode, seed, height, width, preview_start,
230
+ ],
231
+ outputs=[output, pipe_out], api_name="SAKBIR"
232
+ )
233
+ steps.change(dynamic_guidance_slider, inputs=steps, outputs=guidance_end)
234
+ output.change(dynamic_preview_slider, inputs=steps, outputs=index)
235
+ index.release(unpack_pipe_out, inputs=[pipe_out, index], outputs=preview)
236
+ output.change(show_final_preview, inputs=pipe_out, outputs=preview)
237
+ gr.Markdown(
238
+ """
239
+ ## Advance usage:
240
+ ### Browse restoration variants:
241
+ 1. You can explore other in-progress versions while dragging the "Preview Restoration" at the completion of SAKBIR Processing.
242
+ 2. You can get a more refined result by setting the "Start Free Rendering" for the output that you like.
243
+ ### Creative restoration:
244
+ 1. You can also opt for the `Creative Restoration` option;
245
+ 2. Input the prompt in the textbox for "Restoration using prompts";
246
+ 3. Set the value of the slider for "Start Free Rendering" to a medium value for SAKBIR creation.
247
+ """)
248
+
249
+ SAK.queue().launch()