Nightfury16 commited on
Commit
066b002
·
1 Parent(s): 56dac59

Initial Gradio app for virtual staging

Browse files
.gitattributes CHANGED
@@ -1,35 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ weights/*.pth filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
GroundingDINO ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 856dde20aee659246248e20734ef9ba5214f5e44
app.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from PIL import Image, ImageOps
4
+ import numpy as np
5
+ import cv2
6
+ import gradio as gr
7
+ import gc
8
+ import sys
9
+
10
+ GROUNDING_DINO_PATH = "./GroundingDINO"
11
+ if os.path.exists(GROUNDING_DINO_PATH) and GROUNDING_DINO_PATH not in sys.path:
12
+ sys.path.insert(0, GROUNDING_DINO_PATH)
13
+
14
+ from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
15
+ from transformers import pipeline as hf_pipeline
16
+
17
+ try:
18
+ from groundingdino.util.inference import load_model as load_gdino_model, predict as predict_gdino
19
+ import groundingdino.datasets.transforms as T
20
+ except ImportError:
21
+ load_gdino_model, predict_gdino, T = None, None, None
22
+
23
+ def box_cxcywh_to_xyxy(x: torch.Tensor, width: int, height: int) -> torch.Tensor:
24
+ """
25
+ Convert bounding boxes from center-x, center-y, width, height format to x1, y1, x2, y2 format.
26
+ """
27
+ if x.nelement() == 0:
28
+ return x
29
+ x_c, y_c, w, h = x.unbind(1)
30
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
31
+ b = torch.stack(b, dim=1)
32
+ b[:, [0, 2]] *= width
33
+ b[:, [1, 3]] *= height
34
+ return b
35
+
36
+ class SAMModel:
37
+ """
38
+ Wrapper for Segment Anything Model (SAM) for segmentation from bounding boxes.
39
+ """
40
+ def __init__(self, device: str = 'cuda:0') -> None:
41
+ self.device: str = device
42
+ self.model = None
43
+
44
+ def load(self, model_path: str = './weights/sam_l.pt') -> None:
45
+ from ultralytics import SAM
46
+ self.model = SAM(model_path).to(self.device)
47
+
48
+ def release(self) -> None:
49
+ if self.model is not None:
50
+ del self.model
51
+ self.model = None
52
+ gc.collect()
53
+ torch.cuda.empty_cache()
54
+
55
+ def segment_from_boxes(self, image: Image.Image, bboxes: torch.Tensor) -> np.ndarray:
56
+ if self.model is None:
57
+ raise RuntimeError("SAM Model not loaded.")
58
+ if bboxes.nelement() == 0:
59
+ return np.zeros((image.height, image.width), dtype=np.uint8)
60
+ results = self.model(image, bboxes=bboxes, verbose=False)
61
+ if not results or not results[0].masks:
62
+ return np.zeros((image.height, image.width), dtype=np.uint8)
63
+ final_mask = np.zeros((image.height, image.width), dtype=np.uint8)
64
+ for mask_data in results[0].masks.data:
65
+ final_mask = np.maximum(final_mask, mask_data.cpu().numpy().astype(np.uint8) * 255)
66
+ return final_mask
67
+
68
+ class DinoSamGrounding:
69
+ """
70
+ Combines GroundingDINO and SAM for text-guided object segmentation.
71
+ """
72
+ def __init__(self, device: str = 'cuda:0') -> None:
73
+ if predict_gdino is None:
74
+ raise ImportError("GroundingDINO is not installed or accessible.")
75
+ self.device: str = device
76
+ self.grounding_dino_model = None
77
+ self.sam_wrapper = SAMModel(device=device)
78
+
79
+ def load(self, config_path: str = "./GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py", checkpoint_path: str = "./weights/groundingdino_swint_ogc.pth") -> None:
80
+ self.grounding_dino_model = load_gdino_model(config_path, checkpoint_path, device=self.device)
81
+ self.sam_wrapper.load()
82
+
83
+ def release(self) -> None:
84
+ if self.grounding_dino_model is not None:
85
+ del self.grounding_dino_model
86
+ self.grounding_dino_model = None
87
+ self.sam_wrapper.release()
88
+ gc.collect()
89
+ torch.cuda.empty_cache()
90
+
91
+ def generate_mask_from_text(self, image: Image.Image, text_prompt: str, box_threshold: float = 0.35, text_threshold: float = 0.25) -> np.ndarray:
92
+ """
93
+ Generate a segmentation mask for objects matching the text prompt.
94
+ """
95
+ if self.grounding_dino_model is None:
96
+ raise RuntimeError("Models not loaded. Call .load() first.")
97
+ transform = T.Compose([
98
+ T.RandomResize([800], max_size=1333),
99
+ T.ToTensor(),
100
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
101
+ ])
102
+ image_tensor, _ = transform(image, None)
103
+ boxes_relative, logits, phrases = predict_gdino(
104
+ model=self.grounding_dino_model,
105
+ image=image_tensor,
106
+ caption=text_prompt,
107
+ box_threshold=box_threshold,
108
+ text_threshold=text_threshold,
109
+ device=self.device
110
+ )
111
+ if boxes_relative.nelement() == 0:
112
+ return np.zeros((image.height, image.width), dtype=np.uint8)
113
+ H, W = image.height, image.width
114
+ boxes_absolute = box_cxcywh_to_xyxy(x=boxes_relative, width=W, height=H)
115
+ boxes_absolute = boxes_absolute.to(self.device)
116
+ mask = self.sam_wrapper.segment_from_boxes(image, bboxes=boxes_absolute)
117
+ if np.sum(mask) > 0:
118
+ kernel = np.ones((15, 15), np.uint8)
119
+ mask = cv2.dilate(mask, kernel, iterations=3)
120
+ return mask
121
+
122
+ HF_USERNAME: str = "Nightfury16"
123
+ BASE_SD_MODEL: str = "runwayml/stable-diffusion-v1-5"
124
+ CONTROLNET_INPAINT_REPO: str = f"{HF_USERNAME}/virtual-staging-controlnet"
125
+ CONTROLNET_CANNY_REPO: str = "lllyasviel/control_v11p_sd15_canny"
126
+ CONTROLNET_DEPTH_REPO: str = "lllyasviel/sd-controlnet-depth"
127
+ LORA_MODEL_REPO: str = f"{HF_USERNAME}/virtual-staging-lora-sd-v1-5"
128
+
129
+ GROUNDING_DINO_CONFIG: str = "./GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"
130
+ GROUNDING_DINO_CHECKPOINT: str = "./weights/groundingdino_swint_ogc.pth"
131
+ SAM_CHECKPOINT: str = "./weights/sam_l.pt"
132
+
133
+ DEVICE: str = "cuda" if torch.cuda.is_available() else "cpu"
134
+ DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
135
+
136
+ try:
137
+ controlnet_inpaint = ControlNetModel.from_pretrained(CONTROLNET_INPAINT_REPO, torch_dtype=DTYPE)
138
+ controlnet_canny = ControlNetModel.from_pretrained(CONTROLNET_CANNY_REPO, torch_dtype=DTYPE)
139
+ controlnet_depth = ControlNetModel.from_pretrained(CONTROLNET_DEPTH_REPO, torch_dtype=DTYPE)
140
+
141
+ pipeline = StableDiffusionControlNetInpaintPipeline.from_pretrained(
142
+ BASE_SD_MODEL,
143
+ controlnet=[controlnet_inpaint, controlnet_canny, controlnet_depth],
144
+ torch_dtype=DTYPE,
145
+ safety_checker=None
146
+ ).to(DEVICE)
147
+ pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
148
+
149
+ try:
150
+ pipeline.load_lora_weights(
151
+ LORA_MODEL_REPO,
152
+ weight_name="pytorch_lora_weights.safetensors"
153
+ )
154
+ except Exception as e:
155
+ print(f"Error loading LoRA weights: {e}")
156
+
157
+ try:
158
+ pipeline.enable_xformers_memory_efficient_attention()
159
+ except Exception:
160
+ pass
161
+
162
+ depth_estimator = hf_pipeline("depth-estimation", model="LiheYoung/depth-anything-base-hf", device=DEVICE)
163
+ layout_generator = DinoSamGrounding(device=DEVICE)
164
+ layout_generator.load(
165
+ config_path=GROUNDING_DINO_CONFIG,
166
+ checkpoint_path=GROUNDING_DINO_CHECKPOINT
167
+ )
168
+ except Exception as e:
169
+ print(f"FATAL ERROR during model initialization: {e}")
170
+ pipeline, depth_estimator, layout_generator = None, None, None
171
+
172
+ def predict_staged_image(input_image: Image.Image, prompt: str) -> Image.Image:
173
+ """
174
+ Perform virtual staging inference given an empty room image and a prompt.
175
+
176
+ Args:
177
+ input_image (Image.Image): Input empty room image.
178
+ prompt (str): Staging prompt.
179
+
180
+ Returns:
181
+ Image.Image: Virtually staged image.
182
+ """
183
+ if pipeline is None:
184
+ return Image.new('RGB', (512, 512), color='red')
185
+
186
+ empty_image: Image.Image = input_image.convert("RGB").resize((1024, 1024))
187
+ canny_image_np: np.ndarray = cv2.Canny(np.array(empty_image), 100, 200)
188
+ canny_image: Image.Image = Image.fromarray(canny_image_np)
189
+ depth_map = depth_estimator(empty_image)['depth']
190
+ depth_image: Image.Image = depth_map.convert("RGB")
191
+
192
+ negative_prompt: str = "low quality, bad lighting, ugly, deformed, blurry, watermark, text, signature"
193
+ generator = torch.manual_seed(42)
194
+
195
+ control_images_phase1 = [empty_image, canny_image, depth_image]
196
+ controlnet_conditioning_scale_phase1 = [1.0, 0.3, 0.3]
197
+
198
+ pseudo_staged_image: Image.Image = pipeline(
199
+ prompt=prompt,
200
+ negative_prompt=negative_prompt,
201
+ image=empty_image,
202
+ mask_image=Image.new('L', (1024, 1024), 255),
203
+ control_image=control_images_phase1,
204
+ controlnet_conditioning_scale=controlnet_conditioning_scale_phase1,
205
+ num_inference_steps=30,
206
+ generator=generator,
207
+ guidance_scale=9.5
208
+ ).images[0]
209
+
210
+ FURNITURE_QUERY: str = "furniture . sofa . chair . table . lamp . rug . plant . decor . art"
211
+ BOX_THRESHOLD: float = 0.3
212
+
213
+ layout_mask_np: np.ndarray = layout_generator.generate_mask_from_text(
214
+ pseudo_staged_image,
215
+ text_prompt=FURNITURE_QUERY,
216
+ box_threshold=BOX_THRESHOLD
217
+ )
218
+
219
+ if np.sum(layout_mask_np) == 0:
220
+ layout_mask_np[0:5, 0:5] = 255
221
+
222
+ layout_mask: Image.Image = Image.fromarray(layout_mask_np)
223
+
224
+ final_control_images = [empty_image, canny_image, depth_image]
225
+ final_conditioning_scale = [1.0, 0.1, 0.1]
226
+
227
+ result_image: Image.Image = pipeline(
228
+ prompt=prompt,
229
+ negative_prompt=negative_prompt,
230
+ image=empty_image,
231
+ mask_image=layout_mask,
232
+ control_image=final_control_images,
233
+ controlnet_conditioning_scale=final_conditioning_scale,
234
+ num_inference_steps=50,
235
+ generator=generator,
236
+ guidance_scale=7.5
237
+ ).images[0]
238
+
239
+ return result_image
240
+
241
+ description_content: str = """
242
+ This project leverages a powerful pipeline of generative AI models to perform virtual staging on empty room images.
243
+ The primary goal is to create high-quality, photorealistic staged interior designs while meticulously preserving the original room's structural integrity and 3D geometry.
244
+
245
+ ### Approach
246
+ Our approach is built around a synergistic, multi-stage process, where each component is chosen for its specific strengths:
247
+
248
+ 1. **Creative Layout Generation:** An initial "pseudo-staged" image is generated to populate the room with furniture ideas based on the prompt.
249
+ 2. **Text-Guided Masking:** Grounding DINO and SAM identify and precisely segment objects within the pseudo-staged image to create a 'staging area' mask.
250
+ 3. **Multi-ControlNet Guided Inpainting:** The final staged image is generated in a single pass, using your trained Inpainting ControlNet, plus Canny and Depth ControlNets, guided by the generated mask, to inject furniture while preserving original room geometry.
251
+
252
+ ---
253
+ **Input an empty room image and describe your desired staging style!**
254
+ """
255
+
256
+ gr.Interface(
257
+ fn=predict_staged_image,
258
+ inputs=[
259
+ gr.Image(type="pil", label="Upload Empty Room Image"),
260
+ gr.Textbox(label="Staging Prompt", placeholder="e.g., 'modern interior styling, add detailed furniture, rugs, indoor plants, wall art, photorealistic materials, soft textures, warm tones'", lines=2)
261
+ ],
262
+ outputs=gr.Image(type="pil", label="Virtually Staged Image"),
263
+ title="Virtual Staging AI",
264
+ description=description_content,
265
+ allow_flagging="never",
266
+ examples=[
267
+ ["./example_images/empty_room_1.png", "A cozy living room with a mid-century modern sofa, a wooden coffee table, and a large abstract painting."],
268
+ ["./example_images/empty_room_2.png", "A luxurious bedroom with a king-sized bed, velvet headboard, and soft, ambient lighting."]
269
+ ]
270
+ ).launch(debug=True, share=True)
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # requirements.txt
2
+ torch==2.3.0
3
+ torchvision==0.18.0
4
+ pytorch-lightning==2.2.1
5
+ diffusers==0.27.2
6
+ transformers==4.39.3
7
+ accelerate==0.28.0
8
+ opencv-python-headless==4.9.0.80
9
+ numpy==1.26.4
10
+ Pillow==10.2.0
11
+ tqdm==4.66.2
12
+ einops
13
+ gradio==4.26.0
14
+ xformers==0.0.26.post1
15
+ peft==0.10.0
16
+ huggingface-hub==0.25.2
17
+ groundingdino-py
18
+ ultralytics==8.2.2
19
+ addict
20
+ yapf
weights/groundingdino_swint_ogc.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b3ca2563c77c69f651d7bd133e97139c186df06231157a64c507099c52bc799
3
+ size 693997677