Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,53 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
from PIL import Image
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation, AutoModelForDepthEstimation
|
| 6 |
from colors import ade_palette
|
| 7 |
from utils import map_colors_rgb
|
| 8 |
from diffusers import StableDiffusionXLPipeline
|
| 9 |
import gradio as gr
|
|
|
|
| 10 |
|
| 11 |
device = "cuda"
|
| 12 |
dtype = torch.float16
|
| 13 |
-
import spaces
|
| 14 |
-
|
| 15 |
|
|
|
|
| 16 |
css = """
|
| 17 |
#img-display-container {
|
| 18 |
max-height: 50vh;
|
| 19 |
-
}
|
| 20 |
#img-display-input {
|
| 21 |
max-height: 40vh;
|
| 22 |
-
}
|
| 23 |
#img-display-output {
|
| 24 |
max-height: 40vh;
|
| 25 |
-
}
|
| 26 |
"""
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
filtered_colors = []
|
| 30 |
filtered_items = []
|
| 31 |
for color, item in zip(colors_list, items_list):
|
|
@@ -34,19 +56,47 @@ def filter_items(colors_list, items_list, items_to_remove):
|
|
| 34 |
filtered_items.append(item)
|
| 35 |
return filtered_colors, filtered_items
|
| 36 |
|
| 37 |
-
def get_segmentation_pipeline(
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
return image_processor, image_segmentor
|
| 41 |
|
|
|
|
| 42 |
@torch.inference_mode()
|
| 43 |
@spaces.GPU
|
| 44 |
-
def segment_image(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
pixel_values = image_processor(image, return_tensors="pt").pixel_values
|
| 46 |
with torch.no_grad():
|
| 47 |
outputs = image_segmentor(pixel_values)
|
| 48 |
|
| 49 |
-
seg = image_processor.post_process_semantic_segmentation(
|
|
|
|
| 50 |
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
|
| 51 |
palette = np.array(ade_palette())
|
| 52 |
for label, color in enumerate(palette):
|
|
@@ -55,14 +105,22 @@ def segment_image(image, image_processor, image_segmentor):
|
|
| 55 |
seg_image = Image.fromarray(color_seg).convert('RGB')
|
| 56 |
return seg_image
|
| 57 |
|
|
|
|
| 58 |
def get_depth_pipeline():
|
| 59 |
-
feature_extractor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-large-hf",
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
return feature_extractor, depth_estimator
|
| 62 |
|
|
|
|
| 63 |
@torch.inference_mode()
|
| 64 |
@spaces.GPU
|
| 65 |
-
def get_depth_image(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
image_to_depth = feature_extractor(images=image, return_tensors="pt").to(device)
|
| 67 |
with torch.no_grad():
|
| 68 |
depth_map = depth_estimator(**image_to_depth).predicted_depth
|
|
@@ -77,36 +135,59 @@ def get_depth_image(image, feature_extractor, depth_estimator):
|
|
| 77 |
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 78 |
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 79 |
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
|
|
|
|
|
|
| 80 |
image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
| 81 |
image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
| 82 |
return image
|
| 83 |
|
|
|
|
| 84 |
def resize_dimensions(dimensions, target_size):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
width, height = dimensions
|
| 86 |
|
|
|
|
| 87 |
if width < target_size and height < target_size:
|
| 88 |
return dimensions
|
| 89 |
|
|
|
|
| 90 |
if width > height:
|
|
|
|
| 91 |
aspect_ratio = height / width
|
|
|
|
| 92 |
return (target_size, int(target_size * aspect_ratio))
|
| 93 |
else:
|
|
|
|
| 94 |
aspect_ratio = width / height
|
|
|
|
| 95 |
return (int(target_size * aspect_ratio), target_size)
|
| 96 |
|
|
|
|
| 97 |
def flush():
|
| 98 |
gc.collect()
|
| 99 |
torch.cuda.empty_cache()
|
| 100 |
-
|
|
|
|
| 101 |
class ControlNetDepthDesignModelMulti:
|
|
|
|
|
|
|
| 102 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
| 103 |
self.seed = 323*111
|
| 104 |
self.neg_prompt = "window, door, low resolution, banner, logo, watermark, text, deformed, blurry, out of focus, surreal, ugly, beginner"
|
| 105 |
self.control_items = ["windowpane;window", "door;double;door"]
|
| 106 |
self.additional_quality_suffix = "interior design, 4K, high resolution, photorealistic"
|
| 107 |
-
|
| 108 |
@spaces.GPU
|
| 109 |
-
def generate_design(self, empty_room_image, prompt, guidance_scale=10, num_steps=50, strength=0.9, img_size=640) -> Image:
|
|
|
|
|
|
|
|
|
|
| 110 |
print(prompt)
|
| 111 |
flush()
|
| 112 |
self.generator = torch.Generator(device=device).manual_seed(self.seed)
|
|
@@ -116,11 +197,17 @@ class ControlNetDepthDesignModelMulti:
|
|
| 116 |
orig_w, orig_h = empty_room_image.size
|
| 117 |
new_width, new_height = resize_dimensions(empty_room_image.size, img_size)
|
| 118 |
input_image = empty_room_image.resize((new_width, new_height))
|
| 119 |
-
real_seg = np.array(segment_image(input_image,
|
|
|
|
|
|
|
| 120 |
unique_colors = np.unique(real_seg.reshape(-1, real_seg.shape[2]), axis=0)
|
| 121 |
unique_colors = [tuple(color) for color in unique_colors]
|
| 122 |
segment_items = [map_colors_rgb(i) for i in unique_colors]
|
| 123 |
-
chosen_colors, segment_items = filter_items(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
mask = np.zeros_like(real_seg)
|
| 125 |
for color in chosen_colors:
|
| 126 |
color_matches = (real_seg == color).all(axis=2)
|
|
@@ -137,16 +224,36 @@ class ControlNetDepthDesignModelMulti:
|
|
| 137 |
flush()
|
| 138 |
new_width_ip = int(new_width / 8) * 8
|
| 139 |
new_height_ip = int(new_height / 8) * 8
|
| 140 |
-
ip_image = guide_pipe(pos_prompt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
flush()
|
| 143 |
-
generated_image = pipe(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
flush()
|
| 146 |
-
design_image = generated_image.resize(
|
|
|
|
|
|
|
| 147 |
|
| 148 |
return design_image
|
| 149 |
|
|
|
|
| 150 |
def create_demo(model):
|
| 151 |
gr.Markdown("### Stable Design demo")
|
| 152 |
with gr.Row():
|
|
@@ -154,13 +261,38 @@ def create_demo(model):
|
|
| 154 |
input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
|
| 155 |
input_text = gr.Textbox(label='Prompt', placeholder='Please upload your image first', lines=2)
|
| 156 |
with gr.Accordion('Advanced options', open=False):
|
| 157 |
-
num_steps = gr.Slider(label='Steps',
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
submit = gr.Button("Submit")
|
| 165 |
|
| 166 |
with gr.Column():
|
|
@@ -178,21 +310,32 @@ def create_demo(model):
|
|
| 178 |
return out_img
|
| 179 |
|
| 180 |
submit.click(on_submit, inputs=[input_image, input_text, num_steps, guidance_scale, seed, strength, a_prompt, n_prompt, img_size], outputs=design_image)
|
| 181 |
-
examples = gr.Examples(examples=[["bedroom_1.jpg", "An elegantly appointed bedroom in the Art Deco style, featuring a grand king-size bed with geometric bedding, a luxurious velvet armchair, and a mirrored nightstand that reflects the room's opulence. Art Deco-inspired artwork adds a touch of glamour"], ["bedroom_2.jpg", "A bedroom that exudes French country charm with a soft upholstered bed, walls adorned with floral wallpaper, and a vintage wooden wardrobe. A crystal chandelier casts a warm, inviting glow over the space"], ["dinning_room_1.jpg", "A cozy dining room that captures the essence of rustic charm with a solid wooden farmhouse table at its core, surrounded by an eclectic mix of mismatched chairs. An antique sideboard serves as a statement piece, and the ambiance is warmly lit by a series of quaint Edison bulbs dangling from the ceiling"], ["dinning_room_3.jpg", "A dining room that epitomizes contemporary elegance, anchored by a sleek, minimalist dining table paired with stylish modern chairs. Artistic lighting fixtures create a focal point above, while the surrounding minimalist decor ensures the space feels open, airy, and utterly modern"], ["image_1.jpg", "A glamorous master bedroom in Hollywood Regency style, boasting a plush tufted headboard, mirrored furniture reflecting elegance, luxurious fabrics in rich textures, and opulent gold accents for a touch of luxury."], ["image_2.jpg", "A vibrant living room with a tropical theme, complete with comfortable rattan furniture, large leafy plants bringing the outdoors in, bright cushions adding pops of color, and bamboo blinds for natural light control."], ["living_room_1.jpg", "A stylish living room embracing mid-century modern aesthetics, featuring a vintage teak coffee table at its center, complemented by a classic sunburst clock on the wall and a cozy shag rug underfoot, creating a warm and inviting atmosphere"]],
|
| 182 |
inputs=[input_image, input_text], cache_examples=False)
|
| 183 |
|
| 184 |
|
| 185 |
-
controlnet_depth
|
| 186 |
-
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
pipe.set_ip_adapter_scale(0.4)
|
| 191 |
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 192 |
pipe = pipe.to(device)
|
| 193 |
-
guide_pipe = StableDiffusionXLPipeline.from_pretrained("segmind/SSD-1B",
|
|
|
|
| 194 |
guide_pipe = guide_pipe.to(device)
|
| 195 |
-
|
| 196 |
seg_image_processor, image_segmentor = get_segmentation_pipeline()
|
| 197 |
depth_feature_extractor, depth_estimator = get_depth_pipeline()
|
| 198 |
depth_estimator = depth_estimator.to(device)
|
|
@@ -212,4 +355,8 @@ def main():
|
|
| 212 |
|
| 213 |
create_demo(model)
|
| 214 |
|
| 215 |
-
demo.queue().launch(share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
from typing import Tuple, Union, List
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
import numpy as np
|
| 6 |
from PIL import Image
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from diffusers.pipelines.controlnet import StableDiffusionControlNetInpaintPipeline
|
| 10 |
+
from diffusers import ControlNetModel, UniPCMultistepScheduler, AutoPipelineForText2Image
|
| 11 |
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation, AutoModelForDepthEstimation
|
| 12 |
from colors import ade_palette
|
| 13 |
from utils import map_colors_rgb
|
| 14 |
from diffusers import StableDiffusionXLPipeline
|
| 15 |
import gradio as gr
|
| 16 |
+
import gc
|
| 17 |
|
| 18 |
device = "cuda"
|
| 19 |
dtype = torch.float16
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
|
| 22 |
css = """
|
| 23 |
#img-display-container {
|
| 24 |
max-height: 50vh;
|
| 25 |
+
}
|
| 26 |
#img-display-input {
|
| 27 |
max-height: 40vh;
|
| 28 |
+
}
|
| 29 |
#img-display-output {
|
| 30 |
max-height: 40vh;
|
| 31 |
+
}
|
| 32 |
"""
|
| 33 |
|
| 34 |
+
|
| 35 |
+
def filter_items(
|
| 36 |
+
colors_list: Union[List, np.ndarray],
|
| 37 |
+
items_list: Union[List, np.ndarray],
|
| 38 |
+
items_to_remove: Union[List, np.ndarray]
|
| 39 |
+
) -> Tuple[Union[List, np.ndarray], Union[List, np.ndarray]]:
|
| 40 |
+
"""
|
| 41 |
+
Filters items and their corresponding colors from given lists, excluding
|
| 42 |
+
specified items.
|
| 43 |
+
Args:
|
| 44 |
+
colors_list: A list or numpy array of colors corresponding to items.
|
| 45 |
+
items_list: A list or numpy array of items.
|
| 46 |
+
items_to_remove: A list or numpy array of items to be removed.
|
| 47 |
+
Returns:
|
| 48 |
+
A tuple of two lists or numpy arrays: filtered colors and filtered
|
| 49 |
+
items.
|
| 50 |
+
"""
|
| 51 |
filtered_colors = []
|
| 52 |
filtered_items = []
|
| 53 |
for color, item in zip(colors_list, items_list):
|
|
|
|
| 56 |
filtered_items.append(item)
|
| 57 |
return filtered_colors, filtered_items
|
| 58 |
|
| 59 |
+
def get_segmentation_pipeline(
|
| 60 |
+
) -> Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]:
|
| 61 |
+
"""Method to load the segmentation pipeline
|
| 62 |
+
Returns:
|
| 63 |
+
Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]: segmentation pipeline
|
| 64 |
+
"""
|
| 65 |
+
image_processor = AutoImageProcessor.from_pretrained(
|
| 66 |
+
"openmmlab/upernet-convnext-small"
|
| 67 |
+
)
|
| 68 |
+
image_segmentor = UperNetForSemanticSegmentation.from_pretrained(
|
| 69 |
+
"openmmlab/upernet-convnext-small"
|
| 70 |
+
)
|
| 71 |
return image_processor, image_segmentor
|
| 72 |
|
| 73 |
+
|
| 74 |
@torch.inference_mode()
|
| 75 |
@spaces.GPU
|
| 76 |
+
def segment_image(
|
| 77 |
+
image: Image,
|
| 78 |
+
image_processor: AutoImageProcessor,
|
| 79 |
+
image_segmentor: UperNetForSemanticSegmentation
|
| 80 |
+
) -> Image:
|
| 81 |
+
"""
|
| 82 |
+
Segments an image using a semantic segmentation model.
|
| 83 |
+
Args:
|
| 84 |
+
image (Image): The input image to be segmented.
|
| 85 |
+
image_processor (AutoImageProcessor): The processor to prepare the
|
| 86 |
+
image for segmentation.
|
| 87 |
+
image_segmentor (UperNetForSemanticSegmentation): The semantic
|
| 88 |
+
segmentation model used to identify different segments in the image.
|
| 89 |
+
Returns:
|
| 90 |
+
Image: The segmented image with each segment colored differently based
|
| 91 |
+
on its identified class.
|
| 92 |
+
"""
|
| 93 |
+
# image_processor, image_segmentor = get_segmentation_pipeline()
|
| 94 |
pixel_values = image_processor(image, return_tensors="pt").pixel_values
|
| 95 |
with torch.no_grad():
|
| 96 |
outputs = image_segmentor(pixel_values)
|
| 97 |
|
| 98 |
+
seg = image_processor.post_process_semantic_segmentation(
|
| 99 |
+
outputs, target_sizes=[image.size[::-1]])[0]
|
| 100 |
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
|
| 101 |
palette = np.array(ade_palette())
|
| 102 |
for label, color in enumerate(palette):
|
|
|
|
| 105 |
seg_image = Image.fromarray(color_seg).convert('RGB')
|
| 106 |
return seg_image
|
| 107 |
|
| 108 |
+
|
| 109 |
def get_depth_pipeline():
|
| 110 |
+
feature_extractor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-large-hf",
|
| 111 |
+
torch_dtype=dtype)
|
| 112 |
+
depth_estimator = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-large-hf",
|
| 113 |
+
torch_dtype=dtype)
|
| 114 |
return feature_extractor, depth_estimator
|
| 115 |
|
| 116 |
+
|
| 117 |
@torch.inference_mode()
|
| 118 |
@spaces.GPU
|
| 119 |
+
def get_depth_image(
|
| 120 |
+
image: Image,
|
| 121 |
+
feature_extractor: AutoImageProcessor,
|
| 122 |
+
depth_estimator: AutoModelForDepthEstimation
|
| 123 |
+
) -> Image:
|
| 124 |
image_to_depth = feature_extractor(images=image, return_tensors="pt").to(device)
|
| 125 |
with torch.no_grad():
|
| 126 |
depth_map = depth_estimator(**image_to_depth).predicted_depth
|
|
|
|
| 135 |
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 136 |
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 137 |
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
| 138 |
+
image = torch.cat([depth_map] * 3, dim=1)
|
| 139 |
+
|
| 140 |
image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
| 141 |
image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
| 142 |
return image
|
| 143 |
|
| 144 |
+
|
| 145 |
def resize_dimensions(dimensions, target_size):
|
| 146 |
+
"""
|
| 147 |
+
Resize PIL to target size while maintaining aspect ratio
|
| 148 |
+
If smaller than target size leave it as is
|
| 149 |
+
"""
|
| 150 |
width, height = dimensions
|
| 151 |
|
| 152 |
+
# Check if both dimensions are smaller than the target size
|
| 153 |
if width < target_size and height < target_size:
|
| 154 |
return dimensions
|
| 155 |
|
| 156 |
+
# Determine the larger side
|
| 157 |
if width > height:
|
| 158 |
+
# Calculate the aspect ratio
|
| 159 |
aspect_ratio = height / width
|
| 160 |
+
# Resize dimensions
|
| 161 |
return (target_size, int(target_size * aspect_ratio))
|
| 162 |
else:
|
| 163 |
+
# Calculate the aspect ratio
|
| 164 |
aspect_ratio = width / height
|
| 165 |
+
# Resize dimensions
|
| 166 |
return (int(target_size * aspect_ratio), target_size)
|
| 167 |
|
| 168 |
+
|
| 169 |
def flush():
|
| 170 |
gc.collect()
|
| 171 |
torch.cuda.empty_cache()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
class ControlNetDepthDesignModelMulti:
|
| 175 |
+
""" Produces random noise images """
|
| 176 |
+
|
| 177 |
def __init__(self):
|
| 178 |
+
""" Initialize your model(s) here """
|
| 179 |
+
#os.environ['HF_HUB_OFFLINE'] = "True"
|
| 180 |
+
|
| 181 |
self.seed = 323*111
|
| 182 |
self.neg_prompt = "window, door, low resolution, banner, logo, watermark, text, deformed, blurry, out of focus, surreal, ugly, beginner"
|
| 183 |
self.control_items = ["windowpane;window", "door;double;door"]
|
| 184 |
self.additional_quality_suffix = "interior design, 4K, high resolution, photorealistic"
|
| 185 |
+
|
| 186 |
@spaces.GPU
|
| 187 |
+
def generate_design(self, empty_room_image: Image, prompt: str, guidance_scale: int = 10, num_steps: int = 50, strength: float =0.9, img_size: int = 640) -> Image:
|
| 188 |
+
"""
|
| 189 |
+
Given an image.
|
| 190 |
+
"""
|
| 191 |
print(prompt)
|
| 192 |
flush()
|
| 193 |
self.generator = torch.Generator(device=device).manual_seed(self.seed)
|
|
|
|
| 197 |
orig_w, orig_h = empty_room_image.size
|
| 198 |
new_width, new_height = resize_dimensions(empty_room_image.size, img_size)
|
| 199 |
input_image = empty_room_image.resize((new_width, new_height))
|
| 200 |
+
real_seg = np.array(segment_image(input_image,
|
| 201 |
+
seg_image_processor,
|
| 202 |
+
image_segmentor))
|
| 203 |
unique_colors = np.unique(real_seg.reshape(-1, real_seg.shape[2]), axis=0)
|
| 204 |
unique_colors = [tuple(color) for color in unique_colors]
|
| 205 |
segment_items = [map_colors_rgb(i) for i in unique_colors]
|
| 206 |
+
chosen_colors, segment_items = filter_items(
|
| 207 |
+
colors_list=unique_colors,
|
| 208 |
+
items_list=segment_items,
|
| 209 |
+
items_to_remove=self.control_items
|
| 210 |
+
)
|
| 211 |
mask = np.zeros_like(real_seg)
|
| 212 |
for color in chosen_colors:
|
| 213 |
color_matches = (real_seg == color).all(axis=2)
|
|
|
|
| 224 |
flush()
|
| 225 |
new_width_ip = int(new_width / 8) * 8
|
| 226 |
new_height_ip = int(new_height / 8) * 8
|
| 227 |
+
ip_image = guide_pipe(pos_prompt,
|
| 228 |
+
num_inference_steps=num_steps,
|
| 229 |
+
negative_prompt=self.neg_prompt,
|
| 230 |
+
height=new_height_ip,
|
| 231 |
+
width=new_width_ip,
|
| 232 |
+
generator=[self.generator]).images[0]
|
| 233 |
|
| 234 |
flush()
|
| 235 |
+
generated_image = pipe(
|
| 236 |
+
prompt=pos_prompt,
|
| 237 |
+
negative_prompt=self.neg_prompt,
|
| 238 |
+
num_inference_steps=num_steps,
|
| 239 |
+
strength=strength,
|
| 240 |
+
guidance_scale=guidance_scale,
|
| 241 |
+
generator=[self.generator],
|
| 242 |
+
image=image,
|
| 243 |
+
mask_image=mask_image,
|
| 244 |
+
ip_adapter_image=ip_image,
|
| 245 |
+
control_image=[image_depth, segmentation_cond_image],
|
| 246 |
+
controlnet_conditioning_scale=[0.5, 0.5]
|
| 247 |
+
).images[0]
|
| 248 |
|
| 249 |
flush()
|
| 250 |
+
design_image = generated_image.resize(
|
| 251 |
+
(orig_w, orig_h), Image.Resampling.LANCZOS
|
| 252 |
+
)
|
| 253 |
|
| 254 |
return design_image
|
| 255 |
|
| 256 |
+
|
| 257 |
def create_demo(model):
|
| 258 |
gr.Markdown("### Stable Design demo")
|
| 259 |
with gr.Row():
|
|
|
|
| 261 |
input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
|
| 262 |
input_text = gr.Textbox(label='Prompt', placeholder='Please upload your image first', lines=2)
|
| 263 |
with gr.Accordion('Advanced options', open=False):
|
| 264 |
+
num_steps = gr.Slider(label='Steps',
|
| 265 |
+
minimum=1,
|
| 266 |
+
maximum=50,
|
| 267 |
+
value=50,
|
| 268 |
+
step=1)
|
| 269 |
+
img_size = gr.Slider(label='Image size',
|
| 270 |
+
minimum=256,
|
| 271 |
+
maximum=768,
|
| 272 |
+
value=768,
|
| 273 |
+
step=64)
|
| 274 |
+
guidance_scale = gr.Slider(label='Guidance Scale',
|
| 275 |
+
minimum=0.1,
|
| 276 |
+
maximum=30.0,
|
| 277 |
+
value=10.0,
|
| 278 |
+
step=0.1)
|
| 279 |
+
seed = gr.Slider(label='Seed',
|
| 280 |
+
minimum=-1,
|
| 281 |
+
maximum=2147483647,
|
| 282 |
+
value=323*111,
|
| 283 |
+
step=1,
|
| 284 |
+
randomize=True)
|
| 285 |
+
strength = gr.Slider(label='Strength',
|
| 286 |
+
minimum=0.1,
|
| 287 |
+
maximum=1.0,
|
| 288 |
+
value=0.9,
|
| 289 |
+
step=0.1)
|
| 290 |
+
a_prompt = gr.Textbox(
|
| 291 |
+
label='Added Prompt',
|
| 292 |
+
value="4K, high resolution, photorealistic")
|
| 293 |
+
n_prompt = gr.Textbox(
|
| 294 |
+
label='Negative Prompt',
|
| 295 |
+
value=" low resolution, banner, logo, watermark, deformed, blurry, out of focus, surreal, ugly, beginner")
|
| 296 |
submit = gr.Button("Submit")
|
| 297 |
|
| 298 |
with gr.Column():
|
|
|
|
| 310 |
return out_img
|
| 311 |
|
| 312 |
submit.click(on_submit, inputs=[input_image, input_text, num_steps, guidance_scale, seed, strength, a_prompt, n_prompt, img_size], outputs=design_image)
|
| 313 |
+
examples = gr.Examples(examples=[["imgs/bedroom_1.jpg", "An elegantly appointed bedroom in the Art Deco style, featuring a grand king-size bed with geometric bedding, a luxurious velvet armchair, and a mirrored nightstand that reflects the room's opulence. Art Deco-inspired artwork adds a touch of glamour"], ["imgs/bedroom_2.jpg", "A bedroom that exudes French country charm with a soft upholstered bed, walls adorned with floral wallpaper, and a vintage wooden wardrobe. A crystal chandelier casts a warm, inviting glow over the space"], ["imgs/dinning_room_1.jpg", "A cozy dining room that captures the essence of rustic charm with a solid wooden farmhouse table at its core, surrounded by an eclectic mix of mismatched chairs. An antique sideboard serves as a statement piece, and the ambiance is warmly lit by a series of quaint Edison bulbs dangling from the ceiling"], ["imgs/dinning_room_3.jpg", "A dining room that epitomizes contemporary elegance, anchored by a sleek, minimalist dining table paired with stylish modern chairs. Artistic lighting fixtures create a focal point above, while the surrounding minimalist decor ensures the space feels open, airy, and utterly modern"], ["imgs/image_1.jpg", "A glamorous master bedroom in Hollywood Regency style, boasting a plush tufted headboard, mirrored furniture reflecting elegance, luxurious fabrics in rich textures, and opulent gold accents for a touch of luxury."], ["imgs/image_2.jpg", "A vibrant living room with a tropical theme, complete with comfortable rattan furniture, large leafy plants bringing the outdoors in, bright cushions adding pops of color, and bamboo blinds for natural light control."], ["imgs/living_room_1.jpg", "A stylish living room embracing mid-century modern aesthetics, featuring a vintage teak coffee table at its center, complemented by a classic sunburst clock on the wall and a cozy shag rug underfoot, creating a warm and inviting atmosphere"]],
|
| 314 |
inputs=[input_image, input_text], cache_examples=False)
|
| 315 |
|
| 316 |
|
| 317 |
+
controlnet_depth= ControlNetModel.from_pretrained(
|
| 318 |
+
"controlnet_depth", torch_dtype=dtype, use_safetensors=True)
|
| 319 |
+
controlnet_seg = ControlNetModel.from_pretrained(
|
| 320 |
+
"own_controlnet", torch_dtype=dtype, use_safetensors=True)
|
| 321 |
|
| 322 |
+
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
|
| 323 |
+
"SG161222/Realistic_Vision_V5.1_noVAE",
|
| 324 |
+
#"models/runwayml--stable-diffusion-inpainting",
|
| 325 |
+
controlnet=[controlnet_depth, controlnet_seg],
|
| 326 |
+
safety_checker=None,
|
| 327 |
+
torch_dtype=dtype
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
pipe.load_ip_adapter("h94/IP-Adapter", subfolder="models",
|
| 331 |
+
weight_name="ip-adapter_sd15.bin")
|
| 332 |
pipe.set_ip_adapter_scale(0.4)
|
| 333 |
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 334 |
pipe = pipe.to(device)
|
| 335 |
+
guide_pipe = StableDiffusionXLPipeline.from_pretrained("segmind/SSD-1B",
|
| 336 |
+
torch_dtype=dtype, use_safetensors=True, variant="fp16")
|
| 337 |
guide_pipe = guide_pipe.to(device)
|
| 338 |
+
|
| 339 |
seg_image_processor, image_segmentor = get_segmentation_pipeline()
|
| 340 |
depth_feature_extractor, depth_estimator = get_depth_pipeline()
|
| 341 |
depth_estimator = depth_estimator.to(device)
|
|
|
|
| 355 |
|
| 356 |
create_demo(model)
|
| 357 |
|
| 358 |
+
demo.queue().launch(share=False)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
if __name__ == '__main__':
|
| 362 |
+
main()
|