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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""controlnet_depth_canny_segmentation.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colab.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1oeKagV0PyeA1ezzMP4h4KnRRHaklw7L1
|
8 |
+
"""
|
9 |
+
|
10 |
+
import os
|
11 |
+
import torch
|
12 |
+
from PIL import Image
|
13 |
+
import numpy as np
|
14 |
+
import cv2
|
15 |
+
import random
|
16 |
+
import gradio as gr
|
17 |
+
|
18 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
19 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, DDPMScheduler
|
20 |
+
from transformers import AutoTokenizer, CLIPTextModel, CLIPFeatureExtractor
|
21 |
+
from transformers import DPTForDepthEstimation, DPTImageProcessor
|
22 |
+
# Imports for Segmentation
|
23 |
+
from transformers import Mask2FormerForUniversalSegmentation, Mask2FormerImageProcessor
|
24 |
+
|
25 |
+
stable_diffusion_base = "runwayml/stable-diffusion-v1-5"
|
26 |
+
|
27 |
+
# Path to your fine-tuned ControlNet Depth model
|
28 |
+
finetune_controlnet_depth_path = "/content/drive/MyDrive/Output_ControlNet_Finetune"
|
29 |
+
|
30 |
+
# Pre-trained ControlNet models for Canny and Segmentation
|
31 |
+
# These are standard models from the lllyasviel collection, optimized for these tasks.
|
32 |
+
controlnet_canny_pretrained_path = "lllyasviel/sd-controlnet-canny"
|
33 |
+
controlnet_seg_pretrained_path = "lllyasviel/sd-controlnet-seg"
|
34 |
+
|
35 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
36 |
+
DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
|
37 |
+
|
38 |
+
# Global pipeline and pre-processor models
|
39 |
+
pipeline = None
|
40 |
+
depth_estimator_model = None
|
41 |
+
depth_estimator_processor = None
|
42 |
+
segmentation_model_preprocessor = None # Renamed to avoid conflict with ControlNet model
|
43 |
+
segmentation_processor_preprocessor = None # Renamed to avoid conflict with ControlNet model
|
44 |
+
|
45 |
+
# Global ControlNet models
|
46 |
+
controlnet_depth_model = None
|
47 |
+
controlnet_canny_model = None
|
48 |
+
controlnet_seg_model = None
|
49 |
+
|
50 |
+
def load_depth_estimator():
|
51 |
+
"""Loads the MiDaS depth estimation model."""
|
52 |
+
global depth_estimator_model, depth_estimator_processor
|
53 |
+
|
54 |
+
if depth_estimator_model is None:
|
55 |
+
|
56 |
+
print("Loading LiheYoung/depth-anything-large-hf depth estimation model...")
|
57 |
+
model_name = "LiheYoung/depth-anything-large-hf"
|
58 |
+
|
59 |
+
depth_estimator_model = DPTForDepthEstimation.from_pretrained(model_name)
|
60 |
+
depth_estimator_processor = DPTImageProcessor.from_pretrained(model_name)
|
61 |
+
depth_estimator_model.to(DEVICE)
|
62 |
+
|
63 |
+
depth_estimator_model.eval()
|
64 |
+
print("MiDaS depth estimation model loaded.")
|
65 |
+
|
66 |
+
|
67 |
+
return depth_estimator_model, depth_estimator_processor
|
68 |
+
|
69 |
+
def load_segmentation_preprocessor_model():
|
70 |
+
"""Loads the Mask2Former segmentation pre-processor model."""
|
71 |
+
global segmentation_model_preprocessor, segmentation_processor_preprocessor
|
72 |
+
|
73 |
+
if segmentation_model_preprocessor is None:
|
74 |
+
print("Loading Mask2Former segmentation pre-processor model...")
|
75 |
+
model_name = "facebook/mask2former-swin-large-ade-semantic"
|
76 |
+
|
77 |
+
segmentation_processor_preprocessor = Mask2FormerImageProcessor.from_pretrained(model_name)
|
78 |
+
segmentation_model_preprocessor = Mask2FormerForUniversalSegmentation.from_pretrained(model_name)
|
79 |
+
segmentation_model_preprocessor.to(DEVICE)
|
80 |
+
|
81 |
+
segmentation_model_preprocessor.eval()
|
82 |
+
print("Mask2Former segmentation pre-processor model loaded.")
|
83 |
+
return segmentation_model_preprocessor, segmentation_processor_preprocessor
|
84 |
+
|
85 |
+
def load_diffusion_pipeline_and_controlnets():
|
86 |
+
"""
|
87 |
+
Loads the base Stable Diffusion pipeline components and all ControlNet models.
|
88 |
+
"""
|
89 |
+
global pipeline, controlnet_depth_model, controlnet_canny_model, controlnet_seg_model
|
90 |
+
|
91 |
+
if pipeline is None:
|
92 |
+
print("Loading base Stable Diffusion pipeline components...")
|
93 |
+
|
94 |
+
try:
|
95 |
+
# Load individual components of the base Stable Diffusion pipeline
|
96 |
+
vae = AutoencoderKL.from_pretrained(stable_diffusion_base, subfolder="vae", torch_dtype=DTYPE)
|
97 |
+
tokenizer = AutoTokenizer.from_pretrained(stable_diffusion_base, subfolder="tokenizer")
|
98 |
+
text_encoder = CLIPTextModel.from_pretrained(stable_diffusion_base, subfolder="text_encoder", torch_dtype=DTYPE)
|
99 |
+
unet = UNet2DConditionModel.from_pretrained(stable_diffusion_base, subfolder="unet", torch_dtype=DTYPE)
|
100 |
+
scheduler = DDPMScheduler.from_pretrained(stable_diffusion_base, subfolder="scheduler")
|
101 |
+
feature_extractor = CLIPFeatureExtractor.from_pretrained(stable_diffusion_base, subfolder="feature_extractor")
|
102 |
+
|
103 |
+
# Load ControlNet models
|
104 |
+
print("Loading ControlNet models (Depth, Canny, Segmentation)...")
|
105 |
+
if not os.path.exists(finetune_controlnet_depth_path):
|
106 |
+
raise FileNotFoundError(f"Fine-tuned ControlNet Depth model not found at: {finetune_controlnet_depth_path}")
|
107 |
+
|
108 |
+
controlnet_depth_model = ControlNetModel.from_pretrained(finetune_controlnet_depth_path, torch_dtype=DTYPE)
|
109 |
+
controlnet_canny_model = ControlNetModel.from_pretrained(controlnet_canny_pretrained_path, torch_dtype=DTYPE)
|
110 |
+
controlnet_seg_model = ControlNetModel.from_pretrained(controlnet_seg_pretrained_path, torch_dtype=DTYPE)
|
111 |
+
print("All ControlNet models loaded.")
|
112 |
+
|
113 |
+
# Create the StableDiffusionControlNetPipeline with a list of ControlNets
|
114 |
+
pipeline = StableDiffusionControlNetPipeline(
|
115 |
+
vae=vae,
|
116 |
+
text_encoder=text_encoder,
|
117 |
+
tokenizer=tokenizer,
|
118 |
+
unet=unet,
|
119 |
+
controlnet=[controlnet_depth_model, controlnet_canny_model, controlnet_seg_model], # Pass list of ControlNets
|
120 |
+
scheduler=scheduler,
|
121 |
+
safety_checker=None,
|
122 |
+
feature_extractor=feature_extractor,
|
123 |
+
image_encoder=None,
|
124 |
+
requires_safety_checker=False,
|
125 |
+
)
|
126 |
+
|
127 |
+
pipeline.to(DEVICE)
|
128 |
+
if torch.cuda.is_available() and hasattr(pipeline, "enable_xformers_memory_efficient_attention"):
|
129 |
+
try:
|
130 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
131 |
+
print("xformers memory efficient attention enabled.")
|
132 |
+
except Exception as e:
|
133 |
+
print(f"Could not enable xformers: {e}")
|
134 |
+
|
135 |
+
# Load all necessary pre-processor models at startup
|
136 |
+
load_depth_estimator()
|
137 |
+
load_segmentation_preprocessor_model()
|
138 |
+
print("Diffusion pipeline and all pre-processor models loaded successfully.")
|
139 |
+
|
140 |
+
except Exception as e:
|
141 |
+
print(f"Error loading pipeline or ControlNets: {e}")
|
142 |
+
pipeline = None
|
143 |
+
raise RuntimeError(f"Failed to load diffusion pipeline or ControlNets: {e}")
|
144 |
+
return pipeline
|
145 |
+
|
146 |
+
def estimate_depth(pil_image: Image.Image) -> Image.Image:
|
147 |
+
"""Estimates depth map from a PIL image."""
|
148 |
+
global depth_estimator_model, depth_estimator_processor
|
149 |
+
|
150 |
+
if depth_estimator_model is None or depth_estimator_processor is None:
|
151 |
+
try:
|
152 |
+
load_depth_estimator()
|
153 |
+
except RuntimeError as e:
|
154 |
+
raise RuntimeError(f"Depth estimator not loaded: {e}")
|
155 |
+
|
156 |
+
inputs = depth_estimator_processor(images=pil_image, return_tensors="pt")
|
157 |
+
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
158 |
+
|
159 |
+
with torch.no_grad():
|
160 |
+
outputs = depth_estimator_model(**inputs)
|
161 |
+
predicted_depth = outputs.predicted_depth
|
162 |
+
|
163 |
+
depth_numpy = predicted_depth.squeeze().cpu().numpy()
|
164 |
+
|
165 |
+
min_depth = depth_numpy.min()
|
166 |
+
max_depth = depth_numpy.max()
|
167 |
+
normalized_depth = (depth_numpy - min_depth) / (max_depth - min_depth)
|
168 |
+
|
169 |
+
inverted_normalized_depth = 1 - normalized_depth
|
170 |
+
|
171 |
+
depth_image_array = (inverted_normalized_depth * 255).astype(np.uint8)
|
172 |
+
depth_pil_image = Image.fromarray(depth_image_array).convert("RGB")
|
173 |
+
return depth_pil_image
|
174 |
+
|
175 |
+
def estimate_canny(pil_image: Image.Image) -> Image.Image:
|
176 |
+
"""Estimates Canny edges from a PIL image."""
|
177 |
+
img = np.array(pil_image)
|
178 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
179 |
+
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
180 |
+
low_threshold = 100
|
181 |
+
high_threshold = 200
|
182 |
+
canny = cv2.Canny(blurred, low_threshold, high_threshold)
|
183 |
+
canny_pil = Image.fromarray(canny).convert("RGB")
|
184 |
+
return canny_pil
|
185 |
+
|
186 |
+
def estimate_segmentation(pil_image: Image.Image) -> Image.Image:
|
187 |
+
"""Estimates segmentation map from a PIL image."""
|
188 |
+
global segmentation_model_preprocessor, segmentation_processor_preprocessor
|
189 |
+
if segmentation_model_preprocessor is None or segmentation_processor_preprocessor is None:
|
190 |
+
try:
|
191 |
+
load_segmentation_preprocessor_model()
|
192 |
+
except RuntimeError as e:
|
193 |
+
raise RuntimeError(f"Segmentation model not loaded: {e}")
|
194 |
+
|
195 |
+
inputs = segmentation_processor_preprocessor(images=pil_image, return_tensors="pt")
|
196 |
+
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
197 |
+
|
198 |
+
with torch.no_grad():
|
199 |
+
outputs = segmentation_model_preprocessor(**inputs)
|
200 |
+
|
201 |
+
# The Mask2FormerForUniversalSegmentation model returns 'sem_seg' for semantic segmentation
|
202 |
+
# I will use the post_process_semantic_segmentation function to get the processed mask
|
203 |
+
target_size = pil_image.size[::-1] # (height, width)
|
204 |
+
segmentation_maps = segmentation_processor_preprocessor.post_process_semantic_segmentation(
|
205 |
+
outputs, target_sizes=[target_size]
|
206 |
+
)
|
207 |
+
# Access the processed segmentation map from the list
|
208 |
+
predicted_mask = segmentation_maps[0].squeeze(0).cpu().numpy()
|
209 |
+
|
210 |
+
|
211 |
+
unique_classes = np.unique(predicted_mask)
|
212 |
+
color_map = {}
|
213 |
+
for class_id in unique_classes:
|
214 |
+
if class_id == 0:
|
215 |
+
color_map[class_id] = (0, 0, 0) # Black for background
|
216 |
+
else:
|
217 |
+
# Generate consistent colors for classes across runs, but still random-ish
|
218 |
+
# Convert class_id to standard integer for random.seed()
|
219 |
+
random.seed(int(class_id))
|
220 |
+
color_map[class_id] = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
|
221 |
+
|
222 |
+
colored_segmentation_array = np.zeros((*predicted_mask.shape, 3), dtype=np.uint8)
|
223 |
+
for y in range(predicted_mask.shape[0]):
|
224 |
+
for x in range(predicted_mask.shape[1]):
|
225 |
+
colored_segmentation_array[y, x] = color_map[predicted_mask[y, x]]
|
226 |
+
|
227 |
+
segmentation_pil_image = Image.fromarray(colored_segmentation_array).convert("RGB")
|
228 |
+
return segmentation_pil_image
|
229 |
+
|
230 |
+
def generate_image_with_all_controls_simultaneous(
|
231 |
+
input_image_raw: Image.Image,
|
232 |
+
prompt: str,
|
233 |
+
negative_prompt: str = "",
|
234 |
+
num_inference_steps: int = 25,
|
235 |
+
guidance_scale: float = 8.0,
|
236 |
+
strength: float = 0.8,
|
237 |
+
seed: int = None,
|
238 |
+
resolution: int = 512
|
239 |
+
) -> tuple[Image.Image, Image.Image, Image.Image, Image.Image]: # Returns generated image + 3 control maps
|
240 |
+
|
241 |
+
global pipeline
|
242 |
+
if pipeline is None:
|
243 |
+
try:
|
244 |
+
load_diffusion_pipeline_and_controlnets()
|
245 |
+
except RuntimeError as e:
|
246 |
+
# Raise a Gradio Error instead of returning it
|
247 |
+
raise gr.Error(f"Model not loaded: {e}")
|
248 |
+
|
249 |
+
# 1. Generate all control maps
|
250 |
+
print("Generating all control maps (Depth, Canny, Segmentation)...")
|
251 |
+
try:
|
252 |
+
depth_map_pil = estimate_depth(input_image_raw)
|
253 |
+
canny_map_pil = estimate_canny(input_image_raw)
|
254 |
+
segmentation_map_pil = estimate_segmentation(input_image_raw)
|
255 |
+
print("All control maps generated.")
|
256 |
+
except Exception as e:
|
257 |
+
# Raise a Gradio Error instead of returning it
|
258 |
+
raise gr.Error(f"Error during control map generation: {e}")
|
259 |
+
|
260 |
+
print(f"Generating image for prompt: '{prompt}' (Negative: '{negative_prompt}', Strength: {strength})")
|
261 |
+
|
262 |
+
# Resize all generated control maps to the desired resolution
|
263 |
+
# IMPORTANT: The order here must match the order of ControlNet models in the pipeline
|
264 |
+
# (depth_model, canny_model, seg_model)
|
265 |
+
control_images_for_pipeline = [
|
266 |
+
depth_map_pil.resize((resolution, resolution), Image.LANCZOS).convert("RGB"),
|
267 |
+
canny_map_pil.resize((resolution, resolution), Image.LANCZOS).convert("RGB"),
|
268 |
+
segmentation_map_pil.resize((resolution, resolution), Image.LANCZOS).convert("RGB")
|
269 |
+
]
|
270 |
+
|
271 |
+
generator = None
|
272 |
+
if seed is None:
|
273 |
+
seed = random.randint(0, 100000)
|
274 |
+
generator = torch.Generator(device=DEVICE).manual_seed(seed)
|
275 |
+
|
276 |
+
with torch.no_grad():
|
277 |
+
generated_images = pipeline(
|
278 |
+
prompt,
|
279 |
+
negative_prompt=negative_prompt,
|
280 |
+
image=control_images_for_pipeline, # Pass the list of control images
|
281 |
+
num_inference_steps=num_inference_steps,
|
282 |
+
guidance_scale=guidance_scale,
|
283 |
+
strength=strength,
|
284 |
+
generator=generator,
|
285 |
+
).images
|
286 |
+
|
287 |
+
print(f"Image generation complete (seed: {seed}).")
|
288 |
+
# Return the generated image and all three control maps for visualization
|
289 |
+
return generated_images[0], depth_map_pil, canny_map_pil, segmentation_map_pil
|
290 |
+
|
291 |
+
# Gradio Interface Setup
|
292 |
+
with gr.Blocks() as iface:
|
293 |
+
gr.Markdown(
|
294 |
+
"""
|
295 |
+
# Stable Diffusion ControlNet Multi-Control (Simultaneous) Demo
|
296 |
+
Upload an input image, and the app will generate its **Depth Map**, **Canny Edges**, and **Segmentation Map**.
|
297 |
+
These three control maps will then be used **simultaneously** with your text prompt to generate a new image.
|
298 |
+
This provides highly detailed structural guidance.
|
299 |
+
|
300 |
+
**⚠️ WARNING: This setup requires significant GPU memory. It may crash on smaller GPUs (e.g., Colab T4).**
|
301 |
+
"""
|
302 |
+
)
|
303 |
+
|
304 |
+
with gr.Row():
|
305 |
+
with gr.Column():
|
306 |
+
input_image_raw = gr.Image(type="pil", label="Input Image")
|
307 |
+
prompt = gr.Textbox(label="Prompt", value="a high-quality photo of a modern interior design, photorealistic, 4k")
|
308 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", value="blurry, low quality, bad anatomy, deformed, ugly, disfigured, watermark, text, signature, error, missing limbs, extra limbs, mutated, out of frame, cropped, noisy, grainy, jpeg artifacts, cartoon, painting, illustration, sketch, drawing, 3d render", placeholder="Enter negative prompt to guide generation away from these features")
|
309 |
+
num_inference_steps = gr.Slider(minimum=10, maximum=100, value=25, step=1, label="Inference Steps")
|
310 |
+
guidance_scale = gr.Slider(minimum=1.0, maximum=20.0, value=8.0, step=0.5, label="Guidance Scale")
|
311 |
+
strength = gr.Slider(minimum=0.0, maximum=1.0, value=0.8, step=0.01, label="Strength (0.0-1.0)")
|
312 |
+
seed = gr.Number(label="Seed (optional, leave blank for random)", value=None)
|
313 |
+
resolution = gr.Number(label="Resolution", value=512, interactive=False)
|
314 |
+
submit_btn = gr.Button("Generate Images")
|
315 |
+
|
316 |
+
with gr.Column():
|
317 |
+
generated_image_output = gr.Image(type="pil", label="Generated Image (Multi-Control)")
|
318 |
+
with gr.Row():
|
319 |
+
depth_map_output = gr.Image(type="pil", label="Generated Depth Map")
|
320 |
+
canny_map_output = gr.Image(type="pil", label="Generated Canny Edges")
|
321 |
+
segmentation_map_output = gr.Image(type="pil", label="Generated Segmentation Map")
|
322 |
+
|
323 |
+
# Define the action for the submit button
|
324 |
+
submit_btn.click(
|
325 |
+
fn=generate_image_with_all_controls_simultaneous,
|
326 |
+
inputs=[
|
327 |
+
input_image_raw,
|
328 |
+
prompt,
|
329 |
+
negative_prompt,
|
330 |
+
num_inference_steps,
|
331 |
+
guidance_scale,
|
332 |
+
strength,
|
333 |
+
seed,
|
334 |
+
resolution
|
335 |
+
],
|
336 |
+
outputs=[
|
337 |
+
generated_image_output,
|
338 |
+
depth_map_output,
|
339 |
+
canny_map_output,
|
340 |
+
segmentation_map_output
|
341 |
+
]
|
342 |
+
)
|
343 |
+
|
344 |
+
# Load the pipeline and pre-processor models when the Gradio app starts
|
345 |
+
load_diffusion_pipeline_and_controlnets()
|
346 |
+
|
347 |
+
if __name__ == "__main__":
|
348 |
+
iface.launch(debug=True, share=True)
|
349 |
+
|
350 |
+
from google.colab import drive
|
351 |
+
drive.mount('/content/drive')
|