Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import torch
|
4 |
+
from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, DDIMScheduler
|
5 |
+
from diffusers.models import AutoencoderKL
|
6 |
+
from PIL import Image
|
7 |
+
import cv2
|
8 |
+
import numpy as np
|
9 |
+
import gradio as gr
|
10 |
+
from gradio_imageslider import ImageSlider
|
11 |
+
from huggingface_hub import hf_hub_download
|
12 |
+
import subprocess
|
13 |
+
|
14 |
+
# Install Real-ESRGAN with dependencies
|
15 |
+
subprocess.run("pip install git+https://github.com/inference-sh/Real-ESRGAN.git basicsr opencv-python-headless", shell=True)
|
16 |
+
|
17 |
+
from RealESRGAN import RealESRGAN
|
18 |
+
|
19 |
+
# Force CPU usage
|
20 |
+
device = torch.device("cpu")
|
21 |
+
ENABLE_CPU_OFFLOAD = True # Enable CPU offloading to manage memory
|
22 |
+
USE_TORCH_COMPILE = False # Disable torch.compile for CPU compatibility
|
23 |
+
|
24 |
+
# Create model directories
|
25 |
+
os.makedirs("models/Stable-diffusion", exist_ok=True)
|
26 |
+
os.makedirs("models/ControlNet", exist_ok=True)
|
27 |
+
os.makedirs("models/VAE", exist_ok=True)
|
28 |
+
os.makedirs("models/upscalers", exist_ok=True)
|
29 |
+
|
30 |
+
# Download essential models (reduced set to save storage)
|
31 |
+
def download_models():
|
32 |
+
models = {
|
33 |
+
"MODEL": ("dantea1118/juggernaut_reborn", "juggernaut_reborn.safetensors", "models/Stable-diffusion"),
|
34 |
+
"CONTROLNET": ("lllyasviel/ControlNet-v1-1", "control_v11f1e_sd15_tile.pth", "models/ControlNet"),
|
35 |
+
"VAE": ("stabilityai/sd-vae-ft-mse-original", "vae-ft-mse-840000-ema-pruned.safetensors", "models/VAE"),
|
36 |
+
"UPSCALER_X2": ("ai-forever/Real-ESRGAN", "RealESRGAN_x2.pth", "models/upscalers"),
|
37 |
+
}
|
38 |
+
for model, (repo_id, filename, local_dir) in models.items():
|
39 |
+
print(f"Downloading {model}...")
|
40 |
+
hf_hub_download(repo_id=repo_id, filename=filename, local_dir=local_dir)
|
41 |
+
|
42 |
+
download_models()
|
43 |
+
|
44 |
+
# Timer decorator for performance tracking
|
45 |
+
def timer_func(func):
|
46 |
+
def wrapper(*args, **kwargs):
|
47 |
+
start_time = time.time()
|
48 |
+
result = func(*args, **kwargs)
|
49 |
+
print(f"{func.__name__} took {time.time() - start_time:.2f} seconds")
|
50 |
+
return result
|
51 |
+
return wrapper
|
52 |
+
|
53 |
+
# Lazy pipeline for memory efficiency
|
54 |
+
class LazyLoadPipeline:
|
55 |
+
def __init__(self):
|
56 |
+
self.pipe = None
|
57 |
+
|
58 |
+
@timer_func
|
59 |
+
def load(self):
|
60 |
+
if self.pipe is None:
|
61 |
+
print("Setting up pipeline...")
|
62 |
+
controlnet = ControlNetModel.from_single_file(
|
63 |
+
"models/ControlNet/control_v11f1e_sd15_tile.pth", torch_dtype=torch.float16
|
64 |
+
)
|
65 |
+
model_path = "models/Stable-diffusion/juggernaut_reborn.safetensors"
|
66 |
+
pipe = StableDiffusionControlNetImg2ImgPipeline.from_single_file(
|
67 |
+
model_path,
|
68 |
+
controlnet=controlnet,
|
69 |
+
torch_dtype=torch.float16,
|
70 |
+
use_safetensors=True,
|
71 |
+
)
|
72 |
+
vae = AutoencoderKL.from_single_file(
|
73 |
+
"models/VAE/vae-ft-mse-840000-ema-pruned.safetensors",
|
74 |
+
torch_dtype=torch.float16
|
75 |
+
)
|
76 |
+
pipe.vae = vae
|
77 |
+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
78 |
+
pipe.to(device)
|
79 |
+
if ENABLE_CPU_OFFLOAD:
|
80 |
+
print("Enabling CPU offloading...")
|
81 |
+
pipe.enable_model_cpu_offload()
|
82 |
+
return pipe
|
83 |
+
return self.pipe
|
84 |
+
|
85 |
+
def __call__(self, *args, **kwargs):
|
86 |
+
if self.pipe is None:
|
87 |
+
self.pipe = self.load()
|
88 |
+
return self.pipe(*args, **kwargs)
|
89 |
+
|
90 |
+
# Lazy Real-ESRGAN upscaler
|
91 |
+
class LazyRealESRGAN:
|
92 |
+
def __init__(self, device, scale):
|
93 |
+
self.device = device
|
94 |
+
self.scale = scale
|
95 |
+
self.model = None
|
96 |
+
|
97 |
+
def load_model(self):
|
98 |
+
if self.model is None:
|
99 |
+
self.model = RealESRGAN(self.device, scale=self.scale)
|
100 |
+
self.model.load_weights(f'models/upscalers/RealESRGAN_x{self.scale}.pth', download=False)
|
101 |
+
|
102 |
+
def predict(self, img):
|
103 |
+
self.load_model()
|
104 |
+
return self.model.predict(img)
|
105 |
+
|
106 |
+
lazy_realesrgan_x2 = LazyRealESRGAN(device, scale=2)
|
107 |
+
|
108 |
+
@timer_func
|
109 |
+
def resize_and_upscale(input_image, resolution):
|
110 |
+
input_image = input_image.convert("RGB")
|
111 |
+
W, H = input_image.size
|
112 |
+
k = float(resolution) / min(H, W)
|
113 |
+
H = int(round(H * k / 64.0)) * 64
|
114 |
+
W = int(round(W * k / 64.0)) * 64
|
115 |
+
img = input_image.resize((W, H), resample=Image.LANCZOS)
|
116 |
+
img = lazy_realesrgan_x2.predict(img)
|
117 |
+
return img
|
118 |
+
|
119 |
+
@timer_func
|
120 |
+
def create_hdr_effect(original_image, hdr):
|
121 |
+
if hdr == 0:
|
122 |
+
return original_image
|
123 |
+
cv_original = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR)
|
124 |
+
factors = [1.0 - 0.9 * hdr, 1.0 - 0.7 * hdr, 1.0, 1.0 + 0.2 * hdr]
|
125 |
+
images = [cv2.convertScaleAbs(cv_original, alpha=factor) for factor in factors]
|
126 |
+
merge_mertens = cv2.createMergeMertens()
|
127 |
+
hdr_image = merge_mertens.process(images)
|
128 |
+
hdr_image_8bit = np.clip(hdr_image * 255, 0, 255).astype('uint8')
|
129 |
+
return Image.fromarray(cv2.cvtColor(hdr_image_8bit, cv2.COLOR_BGR2RGB))
|
130 |
+
|
131 |
+
lazy_pipe = LazyLoadPipeline()
|
132 |
+
|
133 |
+
@timer_func
|
134 |
+
def gradio_process_image(input_image, resolution, num_inference_steps, strength, hdr, guidance_scale):
|
135 |
+
print("Starting image processing...")
|
136 |
+
condition_image = resize_and_upscale(input_image, resolution)
|
137 |
+
condition_image = create_hdr_effect(condition_image, hdr)
|
138 |
+
|
139 |
+
prompt = "masterpiece, best quality, highres"
|
140 |
+
negative_prompt = "low quality, normal quality, blurry, lowres"
|
141 |
+
|
142 |
+
options = {
|
143 |
+
"prompt": prompt,
|
144 |
+
"negative_prompt": negative_prompt,
|
145 |
+
"image": condition_image,
|
146 |
+
"control_image": condition_image,
|
147 |
+
"width": condition_image.size[0],
|
148 |
+
"height": condition_image.size[1],
|
149 |
+
"strength": strength,
|
150 |
+
"num_inference_steps": num_inference_steps,
|
151 |
+
"guidance_scale": guidance_scale,
|
152 |
+
"generator": torch.Generator(device=device).manual_seed(0),
|
153 |
+
}
|
154 |
+
|
155 |
+
print("Running inference...")
|
156 |
+
result = lazy_pipe(**options).images[0]
|
157 |
+
print("Image processing completed successfully")
|
158 |
+
|
159 |
+
return [np.array(input_image), np.array(result)]
|
160 |
+
|
161 |
+
# Gradio interface
|
162 |
+
title = """<h1 align="center">Image Upscaler with Tile ControlNet</h1>
|
163 |
+
<p align="center">CPU-optimized version for Hugging Face Spaces</p>"""
|
164 |
+
|
165 |
+
with gr.Blocks() as demo:
|
166 |
+
gr.HTML(title)
|
167 |
+
with gr.Row():
|
168 |
+
with gr.Column():
|
169 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
170 |
+
run_button = gr.Button("Enhance Image")
|
171 |
+
with gr.Column():
|
172 |
+
output_slider = ImageSlider(label="Before / After", type="numpy")
|
173 |
+
with gr.Accordion("Advanced Options", open=False):
|
174 |
+
resolution = gr.Slider(minimum=256, maximum=1024, value=512, step=64, label="Resolution")
|
175 |
+
num_inference_steps = gr.Slider(minimum=1, maximum=20, value=10, step=1, label="Inference Steps")
|
176 |
+
strength = gr.Slider(minimum=0, maximum=1, value=0.4, step=0.01, label="Strength")
|
177 |
+
hdr = gr.Slider(minimum=0, maximum=1, value=0, step=0.1, label="HDR Effect")
|
178 |
+
guidance_scale = gr.Slider(minimum=0, maximum=10, value=3, step=0.5, label="Guidance Scale")
|
179 |
+
|
180 |
+
run_button.click(fn=gradio_process_image,
|
181 |
+
inputs=[input_image, resolution, num_inference_steps, strength, hdr, guidance_scale],
|
182 |
+
outputs=output_slider)
|
183 |
+
|
184 |
+
# Launch the app
|
185 |
+
demo.launch()
|