ssboost commited on
Commit
606ca6a
·
verified ·
1 Parent(s): 02bc931

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -139
app.py CHANGED
@@ -1,159 +1,233 @@
1
- from pathlib import Path
2
- import gradio as gr
3
- import pillow_heif
4
  import spaces
 
 
 
 
 
5
  import torch
6
- from huggingface_hub import hf_hub_download
 
 
 
 
 
7
  from PIL import Image
8
- from refiners.fluxion.utils import manual_seed
9
- from refiners.foundationals.latent_diffusion import Solver, solvers
10
- from enhancer import ESRGANUpscaler, ESRGANUpscalerCheckpoints
11
- import os
12
 
13
- pillow_heif.register_heif_opener()
14
- pillow_heif.register_avif_opener()
15
 
16
- CHECKPOINTS = ESRGANUpscalerCheckpoints(
17
- unet=Path(
18
- hf_hub_download(
19
- repo_id="refiners/juggernaut.reborn.sd1_5.unet",
20
- filename="model.safetensors",
21
- revision="347d14c3c782c4959cc4d1bb1e336d19f7dda4d2",
22
- )
23
- ),
24
- clip_text_encoder=Path(
25
- hf_hub_download(
26
- repo_id="refiners/juggernaut.reborn.sd1_5.text_encoder",
27
- filename="model.safetensors",
28
- revision="744ad6a5c0437ec02ad826df9f6ede102bb27481",
29
- )
30
- ),
31
- lda=Path(
32
- hf_hub_download(
33
- repo_id="refiners/juggernaut.reborn.sd1_5.autoencoder",
34
- filename="model.safetensors",
35
- revision="3c1aae3fc3e03e4a2b7e0fa42b62ebb64f1a4c19",
36
- )
37
- ),
38
- controlnet_tile=Path(
39
- hf_hub_download(
40
- repo_id="refiners/controlnet.sd1_5.tile",
41
- filename="model.safetensors",
42
- revision="48ced6ff8bfa873a8976fa467c3629a240643387",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
44
- ),
45
- esrgan=Path(
46
- hf_hub_download(
47
- repo_id="philz1337x/upscaler",
48
- filename="4x-UltraSharp.pth",
49
- revision="011deacac8270114eb7d2eeff4fe6fa9a837be70",
 
 
50
  )
51
- ),
52
- negative_embedding=Path(
53
- hf_hub_download(
54
- repo_id="philz1337x/embeddings",
55
- filename="JuggernautNegative-neg.pt",
56
- revision="203caa7e9cc2bc225031a4021f6ab1ded283454a",
57
  )
58
- ),
59
- negative_embedding_key="string_to_param.*",
60
- loras={
61
- "more_details": Path(
62
- hf_hub_download(
63
- repo_id="philz1337x/loras",
64
- filename="more_details.safetensors",
65
- revision="a3802c0280c0d00c2ab18d37454a8744c44e474e",
66
- )
67
- ),
68
- "sdxl_render": Path(
69
- hf_hub_download(
70
- repo_id="philz1337x/loras",
71
- filename="SDXLrender_v2.0.safetensors",
72
- revision="a3802c0280c0d00c2ab18d37454a8744c44e474e",
73
- )
74
- ),
75
- },
76
- )
77
-
78
- # initialize the enhancer, on the cpu
79
- DEVICE_CPU = torch.device("cpu")
80
- DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32
81
- enhancer = ESRGANUpscaler(checkpoints=CHECKPOINTS, device=DEVICE_CPU, dtype=DTYPE)
82
-
83
- # "move" the enhancer to the gpu, this is handled by Zero GPU
84
- DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
85
- enhancer.to(device=DEVICE, dtype=DTYPE)
86
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  @spaces.GPU
89
- def process(
90
- input_image: Image.Image,
91
- denoise_strength: float,
92
- ) -> tuple[Image.Image, str]:
93
- # 하드코딩된 옵션
 
 
94
  prompt = "masterpiece, best quality, highres"
95
- negative_prompt = "worst quality, low quality, normal quality"
96
- seed = 42
97
- upscale_factor = 2
98
- controlnet_scale = 0.6
99
- controlnet_decay = 1.0
100
- condition_scale = 6
101
- tile_width = 112
102
- tile_height = 144
103
- num_inference_steps = 18
104
- solver = "DDIM"
105
-
106
- manual_seed(seed)
107
-
108
- solver_type: type[Solver] = getattr(solvers, solver)
109
-
110
- enhanced_image = enhancer.upscale(
111
- image=input_image,
112
- prompt=prompt,
113
- negative_prompt=negative_prompt,
114
- upscale_factor=upscale_factor,
115
- controlnet_scale=controlnet_scale,
116
- controlnet_scale_decay=controlnet_decay,
117
- condition_scale=condition_scale,
118
- tile_size=(tile_height, tile_width),
119
- denoise_strength=denoise_strength,
120
- num_inference_steps=num_inference_steps,
121
- loras_scale={"more_details": 0.5, "sdxl_render": 1.0},
122
- solver_type=solver_type,
123
- )
124
-
125
- # 임시로 이미지를 저장하여 다운로드 가능하게 처리
126
- output_path = "/tmp/enhanced_image.jpg"
127
- enhanced_image.save(output_path, "JPEG")
128
-
129
- return enhanced_image, output_path
130
-
131
 
132
  with gr.Blocks() as demo:
133
-
134
  with gr.Row():
135
  with gr.Column():
136
  input_image = gr.Image(type="pil", label="Input Image")
137
- run_button = gr.Button(value="Enhance Image")
138
  with gr.Column():
139
- output_image = gr.Image(label="Enhanced Image")
140
- download_file = gr.File(label="Download Enhanced Image")
141
-
142
- # 강도 조절을 위한 라디오 버튼 추가 (3단계)
143
- denoise_strength = gr.Radio(
144
- choices=[
145
- ("약하게", 0.3),
146
- ("중간", 0.5),
147
- ("강하게", 0.8)
 
 
 
 
 
 
 
 
 
148
  ],
149
- label="강도 조절",
150
- value=0.3 # 기본값: 3단계
151
- )
152
-
153
- run_button.click(
154
- fn=process,
155
- inputs=[input_image, denoise_strength],
156
- outputs=[output_image, download_file],
157
  )
158
 
159
- demo.launch(share=True)
 
 
 
 
1
  import spaces
2
+
3
+ import os
4
+ import requests
5
+ import time
6
+
7
  import torch
8
+
9
+ from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, DDIMScheduler
10
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
11
+ from diffusers.models import AutoencoderKL
12
+ from diffusers.models.attention_processor import AttnProcessor2_0
13
+
14
  from PIL import Image
15
+ import cv2
16
+ import numpy as np
 
 
17
 
18
+ from RealESRGAN import RealESRGAN
 
19
 
20
+ import gradio as gr
21
+ from gradio_imageslider import ImageSlider
22
+
23
+ from huggingface_hub import hf_hub_download
24
+
25
+ USE_TORCH_COMPILE = False
26
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
27
+
28
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29
+
30
+ def download_models():
31
+ models = {
32
+ "MODEL": ("dantea1118/juggernaut_reborn", "juggernaut_reborn.safetensors", "models/models/Stable-diffusion"),
33
+ "UPSCALER_X2": ("ai-forever/Real-ESRGAN", "RealESRGAN_x2.pth", "models/upscalers/"),
34
+ "UPSCALER_X4": ("ai-forever/Real-ESRGAN", "RealESRGAN_x4.pth", "models/upscalers/"),
35
+ "NEGATIVE_1": ("philz1337x/embeddings", "verybadimagenegative_v1.3.pt", "models/embeddings"),
36
+ "NEGATIVE_2": ("philz1337x/embeddings", "JuggernautNegative-neg.pt", "models/embeddings"),
37
+ "LORA_1": ("philz1337x/loras", "SDXLrender_v2.0.safetensors", "models/Lora"),
38
+ "LORA_2": ("philz1337x/loras", "more_details.safetensors", "models/Lora"),
39
+ "CONTROLNET": ("lllyasviel/ControlNet-v1-1", "control_v11f1e_sd15_tile.pth", "models/ControlNet"),
40
+ "VAE": ("stabilityai/sd-vae-ft-mse-original", "vae-ft-mse-840000-ema-pruned.safetensors", "models/VAE"),
41
+ }
42
+
43
+ for model, (repo_id, filename, local_dir) in models.items():
44
+ hf_hub_download(repo_id=repo_id, filename=filename, local_dir=local_dir)
45
+
46
+ download_models()
47
+
48
+ def timer_func(func):
49
+ def wrapper(*args, **kwargs):
50
+ start_time = time.time()
51
+ result = func(*args, **kwargs)
52
+ end_time = time.time()
53
+ print(f"{func.__name__} took {end_time - start_time:.2f} seconds")
54
+ return result
55
+ return wrapper
56
+
57
+ class LazyLoadPipeline:
58
+ def __init__(self):
59
+ self.pipe = None
60
+
61
+ @timer_func
62
+ def load(self):
63
+ if self.pipe is None:
64
+ print("Starting to load the pipeline...")
65
+ self.pipe = self.setup_pipeline()
66
+ print(f"Moving pipeline to device: {device}")
67
+ self.pipe.to(device)
68
+ if USE_TORCH_COMPILE:
69
+ print("Compiling the model...")
70
+ self.pipe.unet = torch.compile(self.pipe.unet, mode="reduce-overhead", fullgraph=True)
71
+
72
+ @timer_func
73
+ def setup_pipeline(self):
74
+ print("Setting up the pipeline...")
75
+ controlnet = ControlNetModel.from_single_file(
76
+ "models/ControlNet/control_v11f1e_sd15_tile.pth", torch_dtype=torch.float16
77
  )
78
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker")
79
+ model_path = "models/models/Stable-diffusion/juggernaut_reborn.safetensors"
80
+ pipe = StableDiffusionControlNetImg2ImgPipeline.from_single_file(
81
+ model_path,
82
+ controlnet=controlnet,
83
+ torch_dtype=torch.float16,
84
+ use_safetensors=True,
85
+ safety_checker=safety_checker
86
  )
87
+ vae = AutoencoderKL.from_single_file(
88
+ "models/VAE/vae-ft-mse-840000-ema-pruned.safetensors",
89
+ torch_dtype=torch.float16
 
 
 
90
  )
91
+ pipe.vae = vae
92
+ pipe.load_textual_inversion("models/embeddings/verybadimagenegative_v1.3.pt")
93
+ pipe.load_textual_inversion("models/embeddings/JuggernautNegative-neg.pt")
94
+ pipe.load_lora_weights("models/Lora/SDXLrender_v2.0.safetensors")
95
+ pipe.fuse_lora(lora_scale=0.5)
96
+ pipe.load_lora_weights("models/Lora/more_details.safetensors")
97
+ pipe.fuse_lora(lora_scale=1.)
98
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
99
+ pipe.enable_freeu(s1=0.9, s2=0.2, b1=1.3, b2=1.4)
100
+ return pipe
101
+
102
+ def __call__(self, *args, **kwargs):
103
+ return self.pipe(*args, **kwargs)
104
+
105
+ class LazyRealESRGAN:
106
+ def __init__(self, device, scale):
107
+ self.device = device
108
+ self.scale = scale
109
+ self.model = None
110
+
111
+ def load_model(self):
112
+ if self.model is None:
113
+ self.model = RealESRGAN(self.device, scale=self.scale)
114
+ self.model.load_weights(f'models/upscalers/RealESRGAN_x{self.scale}.pth', download=False)
115
+ def predict(self, img):
116
+ self.load_model()
117
+ return self.model.predict(img)
118
+
119
+ lazy_realesrgan_x2 = LazyRealESRGAN(device, scale=2)
120
+ lazy_realesrgan_x4 = LazyRealESRGAN(device, scale=4)
121
+
122
+ @timer_func
123
+ def resize_and_upscale(input_image, resolution):
124
+ scale = 2 if resolution <= 2048 else 4
125
+ input_image = input_image.convert("RGB")
126
+ W, H = input_image.size
127
+ k = float(resolution) / min(H, W)
128
+ H = int(round(H * k / 64.0)) * 64
129
+ W = int(round(W * k / 64.0)) * 64
130
+ img = input_image.resize((W, H), resample=Image.LANCZOS)
131
+ if scale == 2:
132
+ img = lazy_realesrgan_x2.predict(img)
133
+ else:
134
+ img = lazy_realesrgan_x4.predict(img)
135
+ return img
136
+
137
+ @timer_func
138
+ def create_hdr_effect(original_image, hdr):
139
+ if hdr == 0:
140
+ return original_image
141
+ cv_original = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR)
142
+ factors = [1.0 - 0.9 * hdr, 1.0 - 0.7 * hdr, 1.0 - 0.45 * hdr,
143
+ 1.0 - 0.25 * hdr, 1.0, 1.0 + 0.2 * hdr,
144
+ 1.0 + 0.4 * hdr, 1.0 + 0.6 * hdr, 1.0 + 0.8 * hdr]
145
+ images = [cv2.convertScaleAbs(cv_original, alpha=factor) for factor in factors]
146
+ merge_mertens = cv2.createMergeMertens()
147
+ hdr_image = merge_mertens.process(images)
148
+ hdr_image_8bit = np.clip(hdr_image * 255, 0, 255).astype('uint8')
149
+ return Image.fromarray(cv2.cvtColor(hdr_image_8bit, cv2.COLOR_BGR2RGB))
150
+
151
+ lazy_pipe = LazyLoadPipeline()
152
+ lazy_pipe.load()
153
+
154
+ def prepare_image(input_image, resolution, hdr):
155
+ condition_image = resize_and_upscale(input_image, resolution)
156
+ condition_image = create_hdr_effect(condition_image, hdr)
157
+ return condition_image
158
 
159
  @spaces.GPU
160
+ @timer_func
161
+ def gradio_process_image(input_image, resolution, num_inference_steps, strength, hdr, guidance_scale):
162
+ print("Starting image processing...")
163
+ torch.cuda.empty_cache()
164
+
165
+ condition_image = prepare_image(input_image, resolution, hdr)
166
+
167
  prompt = "masterpiece, best quality, highres"
168
+ negative_prompt = "low quality, normal quality, ugly, blurry, blur, lowres, bad anatomy, bad hands, cropped, worst quality, verybadimagenegative_v1.3, JuggernautNegative-neg"
169
+
170
+ options = {
171
+ "prompt": prompt,
172
+ "negative_prompt": negative_prompt,
173
+ "image": condition_image,
174
+ "control_image": condition_image,
175
+ "width": condition_image.size[0],
176
+ "height": condition_image.size[1],
177
+ "strength": strength,
178
+ "num_inference_steps": num_inference_steps,
179
+ "guidance_scale": guidance_scale,
180
+ "generator": torch.Generator(device=device).manual_seed(0),
181
+ }
182
+
183
+ print("Running inference...")
184
+ result = lazy_pipe(**options).images[0]
185
+ print("Image processing completed successfully")
186
+
187
+ # Convert input_image and result to numpy arrays
188
+ input_array = np.array(input_image)
189
+ result_array = np.array(result)
190
+
191
+ return [input_array, result_array]
192
+
193
+ title = """<h1 align="center">Image Upscaler with Tile Controlnet</h1>
194
+ <p align="center">The main ideas come from</p>
195
+ <p><center>
196
+ <a href="https://github.com/philz1337x/clarity-upscaler" target="_blank">[philz1337x]</a>
197
+ <a href="https://github.com/BatouResearch/controlnet-tile-upscale" target="_blank">[Pau-Lozano]</a>
198
+ </center></p>
199
+ """
 
 
 
 
200
 
201
  with gr.Blocks() as demo:
202
+ gr.HTML(title)
203
  with gr.Row():
204
  with gr.Column():
205
  input_image = gr.Image(type="pil", label="Input Image")
206
+ run_button = gr.Button("Enhance Image")
207
  with gr.Column():
208
+ output_slider = ImageSlider(label="Before / After", type="numpy")
209
+ with gr.Accordion("Advanced Options", open=False):
210
+ resolution = gr.Slider(minimum=256, maximum=2048, value=512, step=256, label="Resolution")
211
+ num_inference_steps = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Number of Inference Steps")
212
+ strength = gr.Slider(minimum=0, maximum=1, value=0.4, step=0.01, label="Strength")
213
+ hdr = gr.Slider(minimum=0, maximum=1, value=0, step=0.1, label="HDR Effect")
214
+ guidance_scale = gr.Slider(minimum=0, maximum=20, value=3, step=0.5, label="Guidance Scale")
215
+
216
+ run_button.click(fn=gradio_process_image,
217
+ inputs=[input_image, resolution, num_inference_steps, strength, hdr, guidance_scale],
218
+ outputs=output_slider)
219
+
220
+ # Add examples with all required inputs
221
+ gr.Examples(
222
+ examples=[
223
+ ["image1.jpg", 512, 20, 0.4, 0, 3],
224
+ ["image2.png", 512, 20, 0.4, 0, 3],
225
+ ["image3.png", 512, 20, 0.4, 0, 3],
226
  ],
227
+ inputs=[input_image, resolution, num_inference_steps, strength, hdr, guidance_scale],
228
+ outputs=output_slider,
229
+ fn=gradio_process_image,
230
+ cache_examples=True,
 
 
 
 
231
  )
232
 
233
+ demo.launch(share=True)