nick_93 commited on
Commit
bf2495a
1 Parent(s): 60f5285
Files changed (2) hide show
  1. app.py +358 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union, List
2
+ import os
3
+
4
+ import numpy as np
5
+ from PIL import Image
6
+
7
+ import torch
8
+ from diffusers.pipelines.controlnet import StableDiffusionControlNetInpaintPipeline
9
+ from diffusers import ControlNetModel, UniPCMultistepScheduler, AutoPipelineForText2Image
10
+ from transformers import AutoImageProcessor, UperNetForSemanticSegmentation, AutoModelForDepthEstimation
11
+ from models.colors import ade_palette
12
+ from models.utils import map_colors_rgb
13
+ from diffusers import StableDiffusionXLPipeline
14
+ import gradio as gr
15
+
16
+ device = "cuda"
17
+ dtype = torch.float16
18
+
19
+
20
+ css = """
21
+ #img-display-container {
22
+ max-height: 50vh;
23
+ }
24
+ #img-display-input {
25
+ max-height: 40vh;
26
+ }
27
+ #img-display-output {
28
+ max-height: 40vh;
29
+ }
30
+
31
+ """
32
+
33
+
34
+ def filter_items(
35
+ colors_list: Union[List, np.ndarray],
36
+ items_list: Union[List, np.ndarray],
37
+ items_to_remove: Union[List, np.ndarray]
38
+ ) -> Tuple[Union[List, np.ndarray], Union[List, np.ndarray]]:
39
+ """
40
+ Filters items and their corresponding colors from given lists, excluding
41
+ specified items.
42
+
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
+
48
+ Returns:
49
+ A tuple of two lists or numpy arrays: filtered colors and filtered
50
+ items.
51
+ """
52
+ filtered_colors = []
53
+ filtered_items = []
54
+ for color, item in zip(colors_list, items_list):
55
+ if item not in items_to_remove:
56
+ filtered_colors.append(color)
57
+ filtered_items.append(item)
58
+ return filtered_colors, filtered_items
59
+
60
+ def get_segmentation_pipeline(
61
+ ) -> Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]:
62
+ """Method to load the segmentation pipeline
63
+ Returns:
64
+ Tuple[AutoImageProcessor, UperNetForSemanticSegmentation]: segmentation pipeline
65
+ """
66
+ image_processor = AutoImageProcessor.from_pretrained(
67
+ "models/openmmlab--upernet-convnext-small"
68
+ )
69
+ image_segmentor = UperNetForSemanticSegmentation.from_pretrained(
70
+ "models/openmmlab--upernet-convnext-small"
71
+ )
72
+ return image_processor, image_segmentor
73
+
74
+
75
+ @torch.inference_mode()
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
+
84
+ Args:
85
+ image (Image): The input image to be segmented.
86
+ image_processor (AutoImageProcessor): The processor to prepare the
87
+ image for segmentation.
88
+ image_segmentor (UperNetForSemanticSegmentation): The semantic
89
+ segmentation model used to identify different segments in the image.
90
+
91
+ Returns:
92
+ Image: The segmented image with each segment colored differently based
93
+ on its identified class.
94
+ """
95
+ # image_processor, image_segmentor = get_segmentation_pipeline()
96
+ pixel_values = image_processor(image, return_tensors="pt").pixel_values
97
+ with torch.no_grad():
98
+ outputs = image_segmentor(pixel_values)
99
+
100
+ seg = image_processor.post_process_semantic_segmentation(
101
+ outputs, target_sizes=[image.size[::-1]])[0]
102
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
103
+ palette = np.array(ade_palette())
104
+ for label, color in enumerate(palette):
105
+ color_seg[seg == label, :] = color
106
+ color_seg = color_seg.astype(np.uint8)
107
+ seg_image = Image.fromarray(color_seg).convert('RGB')
108
+ return seg_image
109
+
110
+
111
+ def get_depth_pipeline():
112
+ feature_extractor = AutoImageProcessor.from_pretrained("models/models--LiheYoung--depth-anything-large-hf",
113
+ torch_dtype=torch.float16)
114
+ depth_estimator = AutoModelForDepthEstimation.from_pretrained("models/models--LiheYoung--depth-anything-large-hf",
115
+ torch_dtype=torch.float16)
116
+ return feature_extractor, depth_estimator
117
+
118
+
119
+ @torch.inference_mode()
120
+ def get_depth_image(
121
+ image: Image,
122
+ feature_extractor: AutoImageProcessor,
123
+ depth_estimator: AutoModelForDepthEstimation
124
+ ) -> Image:
125
+ image_to_depth = feature_extractor(images=image, return_tensors="pt").to(device)
126
+ with torch.no_grad():
127
+ depth_map = depth_estimator(**image_to_depth).predicted_depth
128
+
129
+ width, height = image.size
130
+ depth_map = torch.nn.functional.interpolate(
131
+ depth_map.unsqueeze(1).float(),
132
+ size=(height, width),
133
+ mode="bicubic",
134
+ align_corners=False,
135
+ )
136
+ depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
137
+ depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
138
+ depth_map = (depth_map - depth_min) / (depth_max - depth_min)
139
+ image = torch.cat([depth_map] * 3, dim=1)
140
+
141
+ image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
142
+ image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
143
+ return image
144
+
145
+
146
+ def resize_dimensions(dimensions, target_size):
147
+ """
148
+ Resize PIL to target size while maintaining aspect ratio
149
+ If smaller than target size leave it as is
150
+ """
151
+ width, height = dimensions
152
+
153
+ # Check if both dimensions are smaller than the target size
154
+ if width < target_size and height < target_size:
155
+ return dimensions
156
+
157
+ # Determine the larger side
158
+ if width > height:
159
+ # Calculate the aspect ratio
160
+ aspect_ratio = height / width
161
+ # Resize dimensions
162
+ return (target_size, int(target_size * aspect_ratio))
163
+ else:
164
+ # Calculate the aspect ratio
165
+ aspect_ratio = width / height
166
+ # Resize dimensions
167
+ return (int(target_size * aspect_ratio), target_size)
168
+
169
+
170
+ class ControlNetDepthDesignModelMulti:
171
+ """ Produces random noise images """
172
+ def __init__(self):
173
+ """ Initialize your model(s) here """
174
+
175
+ #os.environ['HF_HUB_OFFLINE'] = "True"
176
+ controlnet_depth= ControlNetModel.from_pretrained(
177
+ "models/controlnet_depth", torch_dtype=torch.float16, use_safetensors=True)
178
+ controlnet_seg = ControlNetModel.from_pretrained(
179
+ "models/own_controlnet", torch_dtype=torch.float16, use_safetensors=True)
180
+
181
+ self.pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
182
+ "SG161222/Realistic_Vision_V5.1_noVAE",
183
+ #"models/runwayml--stable-diffusion-inpainting",
184
+ controlnet=[controlnet_depth, controlnet_seg],
185
+ safety_checker=None,
186
+ torch_dtype=torch.float16
187
+ )
188
+
189
+ self.pipe.load_ip_adapter("h94/IP-Adapter", subfolder="models",
190
+ weight_name="ip-adapter_sd15.bin")
191
+ self.pipe.set_ip_adapter_scale(0.4)
192
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
193
+ self.pipe = self.pipe.to(device)
194
+ self.guide_pipe = StableDiffusionXLPipeline.from_pretrained("segmind/SSD-1B",
195
+ torch_dtype=dtype, use_safetensors=True, variant="fp16")
196
+ self.guide_pipe = self.guide_pipe.to(device)
197
+
198
+ self.seed = 323*111
199
+ self.neg_prompt = "window, door, low resolution, banner, logo, watermark, text, deformed, blurry, out of focus, surreal, ugly, beginner"
200
+ self.control_items = ["windowpane;window", "door;double;door"]
201
+ self.additional_quality_suffix = "interior design, 4K, high resolution, photorealistic"
202
+
203
+ self.seg_image_processor, self.image_segmentor = get_segmentation_pipeline()
204
+ self.depth_feature_extractor, self.depth_estimator = get_depth_pipeline()
205
+ self.depth_estimator = self.depth_estimator.to(device)
206
+
207
+ def generate_design(self, empty_room_image: Image, prompt: str, guidance_scale: int = 10, num_steps: int = 50, strength: float =0.9) -> Image:
208
+ """
209
+ Given an image of an empty room and a prompt
210
+ generate the designed room according to the prompt
211
+ Inputs -
212
+ empty_room_image - An RGB PIL Image of the empty room
213
+ prompt - Text describing the target design elements of the room
214
+ Returns -
215
+ design_image - PIL Image of the same size as the empty room image
216
+ If the size is not the same the submission will fail.
217
+ """
218
+ print(prompt)
219
+ self.generator = torch.Generator(device=device).manual_seed(self.seed)
220
+
221
+ pos_prompt = prompt + f', {self.additional_quality_suffix}'
222
+
223
+ orig_w, orig_h = empty_room_image.size
224
+ new_width, new_height = resize_dimensions(empty_room_image.size, 768)
225
+ input_image = empty_room_image.resize((new_width, new_height))
226
+ real_seg = np.array(segment_image(input_image,
227
+ self.seg_image_processor,
228
+ self.image_segmentor))
229
+ unique_colors = np.unique(real_seg.reshape(-1, real_seg.shape[2]), axis=0)
230
+ unique_colors = [tuple(color) for color in unique_colors]
231
+ segment_items = [map_colors_rgb(i) for i in unique_colors]
232
+ chosen_colors, segment_items = filter_items(
233
+ colors_list=unique_colors,
234
+ items_list=segment_items,
235
+ items_to_remove=self.control_items
236
+ )
237
+ mask = np.zeros_like(real_seg)
238
+ for color in chosen_colors:
239
+ color_matches = (real_seg == color).all(axis=2)
240
+ mask[color_matches] = 1
241
+
242
+ image_np = np.array(input_image)
243
+ image = Image.fromarray(image_np).convert("RGB")
244
+ mask_image = Image.fromarray((mask * 255).astype(np.uint8)).convert("RGB")
245
+ segmentation_cond_image = Image.fromarray(real_seg).convert("RGB")
246
+
247
+ image_depth = get_depth_image(image, self.depth_feature_extractor, self.depth_estimator)
248
+
249
+ # generate image that would be used as IP-adapter
250
+ new_width_ip = int(new_width / 8) * 8
251
+ new_height_ip = int(new_height / 8) * 8
252
+ ip_image = self.guide_pipe(pos_prompt,
253
+ num_inference_steps=num_steps,
254
+ negative_prompt=self.neg_prompt,
255
+ height=new_height_ip,
256
+ width=new_width_ip,
257
+ generator=[self.generator]).images[0]
258
+
259
+
260
+ generated_image = self.pipe(
261
+ prompt=pos_prompt,
262
+ negative_prompt=self.neg_prompt,
263
+ num_inference_steps=num_steps,
264
+ strength=strength,
265
+ guidance_scale=guidance_scale,
266
+ generator=[self.generator],
267
+ image=image,
268
+ mask_image=mask_image,
269
+ ip_adapter_image=ip_image,
270
+ control_image=[image_depth, segmentation_cond_image],
271
+ controlnet_conditioning_scale=[0.5, 0.5]
272
+ ).images[0]
273
+
274
+ design_image = generated_image.resize(
275
+ (orig_w, orig_h), Image.Resampling.LANCZOS
276
+ )
277
+
278
+ return design_image
279
+
280
+
281
+ def create_refseg_demo(model, device):
282
+ gr.Markdown("### Stable Design demo")
283
+ with gr.Row():
284
+ with gr.Column():
285
+ input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
286
+ input_text = gr.Textbox(label='Prompt', placeholder='Please upload your image first', lines=2)
287
+ with gr.Accordion('Advanced options', open=False):
288
+ num_steps = gr.Slider(label='Steps',
289
+ minimum=1,
290
+ maximum=50,
291
+ value=50,
292
+ step=1)
293
+ guidance_scale = gr.Slider(label='Guidance Scale',
294
+ minimum=0.1,
295
+ maximum=30.0,
296
+ value=10.0,
297
+ step=0.1)
298
+ seed = gr.Slider(label='Seed',
299
+ minimum=-1,
300
+ maximum=2147483647,
301
+ value=323*111,
302
+ step=1,
303
+ randomize=True)
304
+ strength = gr.Slider(label='Strength',
305
+ minimum=0.1,
306
+ maximum=1.0,
307
+ value=0.9,
308
+ step=0.1)
309
+ a_prompt = gr.Textbox(
310
+ label='Added Prompt',
311
+ value="interior design, 4K, high resolution, photorealistic")
312
+ n_prompt = gr.Textbox(
313
+ label='Negative Prompt',
314
+ value="window, door, low resolution, banner, logo, watermark, text, deformed, blurry, out of focus, surreal, ugly, beginner")
315
+ submit = gr.Button("Submit")
316
+
317
+ with gr.Column():
318
+ design_image = gr.Image(label="Output Mask", elem_id='img-display-output')
319
+
320
+
321
+ def on_submit(image, text, num_steps, guidance_scale, seed, strength, a_prompt, n_prompt):
322
+ model.seed = seed
323
+ model.neg_prompt = n_prompt
324
+ model.additional_quality_suffix = a_prompt
325
+
326
+ with torch.no_grad():
327
+ out_img = model.generate_design(image, text, guidance_scale=guidance_scale, num_steps=num_steps, strength=strength)
328
+
329
+ return out_img
330
+
331
+ submit.click(on_submit, inputs=[input_image, input_text, num_steps, guidance_scale, seed, strength, a_prompt, n_prompt], outputs=design_image)
332
+ 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"]],
333
+ inputs=[input_image, input_text])
334
+
335
+
336
+ def main():
337
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
338
+ model = ControlNetDepthDesignModelMulti()
339
+ print('Models uploaded successfully')
340
+
341
+ title = "# StableDesign"
342
+ description = """
343
+ <p style='font-size: 14px; margin-bottom: 10px;'><a href='https://www.linkedin.com/in/mykola-lavreniuk/'>Mykola Lavreniuk</a>, <a href='https://www.linkedin.com/in/bartosz-ludwiczuk-a677a760/'>Bartosz Ludwiczuk</a></p>
344
+ <p style='font-size: 16px; margin-bottom: 0px; margin-top=0px;'>Official demo for <strong>StableDesign:</strong> 2nd place solution for the Generative Interior Design 2024 <a href='https://www.aicrowd.com/challenges/generative-interior-design-challenge-2024/leaderboards?challenge_round_id=1314'>competition</a>. StableDesign is a deep learning model designed to harness the power of AI, providing innovative and creative tools for designers. Using our algorithms, images of empty rooms can be transformed into fully furnished spaces based on text descriptions. Please refer to our <a href='https://github.com/Lavreniuk/generative-interior-design'>GitHub</a> for more details.</p>
345
+ """
346
+ with gr.Blocks() as demo:
347
+ gr.Markdown(title)
348
+ gr.Markdown(description)
349
+
350
+ create_refseg_demo(model, device)
351
+ gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:<a href="https://huggingface.co/spaces/MykolaL/StableDesign?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
352
+ <p><img src="https://visitor-badge.glitch.me/badge?page_id=MykolaL/StableDesign" alt="visitors"></p></center>''')
353
+
354
+ demo.queue().launch(share=True)
355
+
356
+
357
+ if __name__ == '__main__':
358
+ main()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers==0.25.0
2
+ xformers==0.0.23.post1
3
+ transformers==4.39.1
4
+ torchvision
5
+ accelerate==0.26.1
6
+ opencv-python==4.9.0.80
7
+ scipy==1.11.4
8
+ triton==2.1.0
9
+ altair==4.1.0
10
+ pandas==2.1.4