gokaygokay commited on
Commit
9632f25
1 Parent(s): 82a71e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -82
app.py CHANGED
@@ -1,8 +1,7 @@
1
- import spaces
2
  import os
3
  import requests
4
  import torch
5
- from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler
6
  from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
7
  from diffusers.models import AutoencoderKL
8
  from PIL import Image
@@ -11,15 +10,13 @@ import cv2
11
  import numpy as np
12
  from diffusers.models.attention_processor import AttnProcessor2_0
13
  import gradio as gr
 
14
 
15
- USE_TORCH_COMPILE = 0
16
- ENABLE_CPU_OFFLOAD = 0
17
 
18
- # Set up the device
19
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
 
21
-
22
- # Function to download files (from the example)
23
  def download_file(url, folder_path, filename):
24
  if not os.path.exists(folder_path):
25
  os.makedirs(folder_path)
@@ -37,7 +34,6 @@ def download_file(url, folder_path, filename):
37
  else:
38
  print(f"Error downloading the file. Status code: {response.status_code}")
39
 
40
- # Download necessary models and files
41
  def download_models():
42
  models = {
43
  "MODEL": ("https://huggingface.co/dantea1118/juggernaut_reborn/resolve/main/juggernaut_reborn.safetensors?download=true", "models/models/Stable-diffusion", "juggernaut_reborn.safetensors"),
@@ -56,9 +52,6 @@ def download_models():
56
 
57
  download_models()
58
 
59
-
60
-
61
-
62
  class LazyRealESRGAN:
63
  def __init__(self, device, scale):
64
  self.device = device
@@ -74,72 +67,49 @@ class LazyRealESRGAN:
74
  self.load_model()
75
  return self.model.predict(img)
76
 
77
- # Initialize the lazy models
78
  lazy_realesrgan_x2 = LazyRealESRGAN(device, scale=2)
79
  lazy_realesrgan_x4 = LazyRealESRGAN(device, scale=4)
80
 
81
  def resize_and_upscale(input_image, resolution):
82
- scale = 2
83
- if resolution == 2048:
84
- init_w = 1024
85
- elif resolution == 2560:
86
- init_w = 1280
87
- elif resolution == 3072:
88
- init_w = 1536
89
- else:
90
- init_w = 1024
91
- scale = 4
92
-
93
  input_image = input_image.convert("RGB")
94
  W, H = input_image.size
95
- k = float(init_w) / min(H, W)
96
- H *= k
97
- W *= k
98
- H = int(round(H / 64.0)) * 64
99
- W = int(round(W / 64.0)) * 64
100
  img = input_image.resize((W, H), resample=Image.LANCZOS)
101
- model = RealESRGAN(device, scale=scale)
102
- model.load_weights(f'models/upscalers/RealESRGAN_x{scale}.pth', download=False)
103
- img = model.predict(img)
104
  if scale == 2:
105
  img = lazy_realesrgan_x2.predict(img)
106
  else:
107
  img = lazy_realesrgan_x4.predict(img)
108
  return img
109
 
110
- def calculate_brightness_factors(hdr_intensity):
111
- factors = [1.0] * 9
112
- if hdr_intensity > 0:
113
- factors = [1.0 - 0.9 * hdr_intensity, 1.0 - 0.7 * hdr_intensity, 1.0 - 0.45 * hdr_intensity,
114
- 1.0 - 0.25 * hdr_intensity, 1.0, 1.0 + 0.2 * hdr_intensity,
115
- 1.0 + 0.4 * hdr_intensity, 1.0 + 0.6 * hdr_intensity, 1.0 + 0.8 * hdr_intensity]
116
- return factors
117
-
118
- def pil_to_cv(pil_image):
119
- return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
120
-
121
- def adjust_brightness(cv_image, factor):
122
- hsv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
123
- h, s, v = cv2.split(hsv_image)
124
- v = np.clip(v * factor, 0, 255).astype('uint8')
125
- adjusted_hsv = cv2.merge([h, s, v])
126
- return cv2.cvtColor(adjusted_hsv, cv2.COLOR_HSV2BGR)
127
-
128
  def create_hdr_effect(original_image, hdr):
129
- cv_original = pil_to_cv(original_image)
130
- brightness_factors = calculate_brightness_factors(hdr)
131
- images = [adjust_brightness(cv_original, factor) for factor in brightness_factors]
132
-
 
 
 
133
  merge_mertens = cv2.createMergeMertens()
134
  hdr_image = merge_mertens.process(images)
135
  hdr_image_8bit = np.clip(hdr_image * 255, 0, 255).astype('uint8')
136
- hdr_image_pil = Image.fromarray(cv2.cvtColor(hdr_image_8bit, cv2.COLOR_BGR2RGB))
137
-
138
- return hdr_image_pil
139
 
140
- class ImageProcessor:
141
  def __init__(self):
142
- self.pipe = self.setup_pipeline()
 
 
 
 
 
 
 
 
 
 
143
 
144
  def setup_pipeline(self):
145
  controlnet = ControlNetModel.from_single_file(
@@ -172,35 +142,38 @@ class ImageProcessor:
172
 
173
  return pipe
174
 
175
- def process_image(self, input_image, prompt, negative_prompt, resolution=2048, num_inference_steps=50, guidance_scale=3, strength=0.35, hdr=0):
176
- condition_image = resize_and_upscale(input_image, resolution)
177
- condition_image = create_hdr_effect(condition_image, hdr)
178
 
179
- result = self.pipe(
180
- prompt=prompt,
181
- negative_prompt=negative_prompt,
182
- image=condition_image,
183
- control_image=condition_image,
184
- width=condition_image.size[0],
185
- height=condition_image.size[1],
186
- strength=strength,
187
- num_inference_steps=num_inference_steps,
188
- guidance_scale=guidance_scale,
189
- generator=torch.manual_seed(0),
190
- ).images[0]
191
-
192
- return result
193
-
194
-
195
- image_processor = ImageProcessor()
196
 
197
  @spaces.GPU
198
  def gradio_process_image(input_image, resolution, num_inference_steps, strength, hdr, guidance_scale):
199
- image_processor.pipe = image_processor.pipe.to(device)
200
- image_processor.pipe.unet.set_attn_processor(AttnProcessor2_0())
 
 
 
 
 
201
  prompt = "masterpiece, best quality, highres"
202
  negative_prompt = "low quality, normal quality, ugly, blurry, blur, lowres, bad anatomy, bad hands, cropped, worst quality, verybadimagenegative_v1.3, JuggernautNegative-neg"
203
- result = image_processor.process_image(input_image, prompt, negative_prompt, resolution, num_inference_steps, guidance_scale, strength, hdr)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  return result
205
 
206
  # Gradio interface
@@ -214,7 +187,7 @@ with gr.Blocks() as demo:
214
  output_image = gr.Image(type="pil", label="Enhanced Image")
215
  with gr.Accordion("Advanced Options", open=False):
216
  resolution = gr.Slider(minimum=512, maximum=2048, value=1024, step=64, label="Resolution")
217
- num_inference_steps = gr.Slider(minimum=1, maximum=100, value=50, step=1, label="Number of Inference Steps")
218
  strength = gr.Slider(minimum=0, maximum=1, value=0.35, step=0.05, label="Strength")
219
  hdr = gr.Slider(minimum=0, maximum=1, value=0, step=0.1, label="HDR Effect")
220
  guidance_scale = gr.Slider(minimum=0, maximum=20, value=3, step=0.5, label="Guidance Scale")
 
 
1
  import os
2
  import requests
3
  import torch
4
+ from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, DDIMScheduler
5
  from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
6
  from diffusers.models import AutoencoderKL
7
  from PIL import Image
 
10
  import numpy as np
11
  from diffusers.models.attention_processor import AttnProcessor2_0
12
  import gradio as gr
13
+ import spaces
14
 
15
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
16
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
17
 
 
18
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
 
 
 
20
  def download_file(url, folder_path, filename):
21
  if not os.path.exists(folder_path):
22
  os.makedirs(folder_path)
 
34
  else:
35
  print(f"Error downloading the file. Status code: {response.status_code}")
36
 
 
37
  def download_models():
38
  models = {
39
  "MODEL": ("https://huggingface.co/dantea1118/juggernaut_reborn/resolve/main/juggernaut_reborn.safetensors?download=true", "models/models/Stable-diffusion", "juggernaut_reborn.safetensors"),
 
52
 
53
  download_models()
54
 
 
 
 
55
  class LazyRealESRGAN:
56
  def __init__(self, device, scale):
57
  self.device = device
 
67
  self.load_model()
68
  return self.model.predict(img)
69
 
 
70
  lazy_realesrgan_x2 = LazyRealESRGAN(device, scale=2)
71
  lazy_realesrgan_x4 = LazyRealESRGAN(device, scale=4)
72
 
73
  def resize_and_upscale(input_image, resolution):
74
+ scale = 2 if resolution <= 2048 else 4
 
 
 
 
 
 
 
 
 
 
75
  input_image = input_image.convert("RGB")
76
  W, H = input_image.size
77
+ k = float(resolution) / min(H, W)
78
+ H = int(round(H * k / 64.0)) * 64
79
+ W = int(round(W * k / 64.0)) * 64
 
 
80
  img = input_image.resize((W, H), resample=Image.LANCZOS)
 
 
 
81
  if scale == 2:
82
  img = lazy_realesrgan_x2.predict(img)
83
  else:
84
  img = lazy_realesrgan_x4.predict(img)
85
  return img
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def create_hdr_effect(original_image, hdr):
88
+ if hdr == 0:
89
+ return original_image
90
+ cv_original = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR)
91
+ factors = [1.0 - 0.9 * hdr, 1.0 - 0.7 * hdr, 1.0 - 0.45 * hdr,
92
+ 1.0 - 0.25 * hdr, 1.0, 1.0 + 0.2 * hdr,
93
+ 1.0 + 0.4 * hdr, 1.0 + 0.6 * hdr, 1.0 + 0.8 * hdr]
94
+ images = [cv2.convertScaleAbs(cv_original, alpha=factor) for factor in factors]
95
  merge_mertens = cv2.createMergeMertens()
96
  hdr_image = merge_mertens.process(images)
97
  hdr_image_8bit = np.clip(hdr_image * 255, 0, 255).astype('uint8')
98
+ return Image.fromarray(cv2.cvtColor(hdr_image_8bit, cv2.COLOR_BGR2RGB))
 
 
99
 
100
+ class LazyLoadPipeline:
101
  def __init__(self):
102
+ self.pipe = None
103
+
104
+ def load(self):
105
+ if self.pipe is None:
106
+ self.pipe = self.setup_pipeline()
107
+ if ENABLE_CPU_OFFLOAD:
108
+ self.pipe.enable_model_cpu_offload()
109
+ else:
110
+ self.pipe.to(device)
111
+ if USE_TORCH_COMPILE:
112
+ self.pipe.unet = torch.compile(self.pipe.unet, mode="reduce-overhead", fullgraph=True)
113
 
114
  def setup_pipeline(self):
115
  controlnet = ControlNetModel.from_single_file(
 
142
 
143
  return pipe
144
 
145
+ def __call__(self, *args, **kwargs):
146
+ self.load()
147
+ return self.pipe(*args, **kwargs)
148
 
149
+ lazy_pipe = LazyLoadPipeline()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  @spaces.GPU
152
  def gradio_process_image(input_image, resolution, num_inference_steps, strength, hdr, guidance_scale):
153
+ torch.cuda.empty_cache()
154
+ lazy_pipe.load()
155
+ lazy_pipe.pipe.unet.set_attn_processor(AttnProcessor2_0())
156
+
157
+ condition_image = resize_and_upscale(input_image, resolution)
158
+ condition_image = create_hdr_effect(condition_image, hdr)
159
+
160
  prompt = "masterpiece, best quality, highres"
161
  negative_prompt = "low quality, normal quality, ugly, blurry, blur, lowres, bad anatomy, bad hands, cropped, worst quality, verybadimagenegative_v1.3, JuggernautNegative-neg"
162
+
163
+ options = {
164
+ "prompt": prompt,
165
+ "negative_prompt": negative_prompt,
166
+ "image": condition_image,
167
+ "control_image": condition_image,
168
+ "width": condition_image.size[0],
169
+ "height": condition_image.size[1],
170
+ "strength": strength,
171
+ "num_inference_steps": num_inference_steps,
172
+ "guidance_scale": guidance_scale,
173
+ "generator": torch.Generator(device=device).manual_seed(0),
174
+ }
175
+
176
+ result = lazy_pipe(**options).images[0]
177
  return result
178
 
179
  # Gradio interface
 
187
  output_image = gr.Image(type="pil", label="Enhanced Image")
188
  with gr.Accordion("Advanced Options", open=False):
189
  resolution = gr.Slider(minimum=512, maximum=2048, value=1024, step=64, label="Resolution")
190
+ num_inference_steps = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Number of Inference Steps")
191
  strength = gr.Slider(minimum=0, maximum=1, value=0.35, step=0.05, label="Strength")
192
  hdr = gr.Slider(minimum=0, maximum=1, value=0, step=0.1, label="HDR Effect")
193
  guidance_scale = gr.Slider(minimum=0, maximum=20, value=3, step=0.5, label="Guidance Scale")