stevee00 commited on
Commit
6738da3
·
verified ·
1 Parent(s): 329b59a

Upload src/interiorfusion/pipelines.py

Browse files
Files changed (1) hide show
  1. src/interiorfusion/pipelines.py +414 -0
src/interiorfusion/pipelines.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """InteriorFusion main inference pipeline."""
2
+
3
+ import os
4
+ import tempfile
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import Image
13
+
14
+ from .models.scene_understanding import SceneUnderstandingModule
15
+ from .models.multiview_generation import MultiViewGenerationModule
16
+ from .models.reconstruction_3d import Reconstruction3DModule
17
+ from .models.scene_assembly import SceneAssemblyModule
18
+ from .models.material_texture import MaterialTextureModule
19
+ from .utils.mesh_utils import export_mesh
20
+ from .utils.gaussian_utils import export_gaussian_splatting
21
+
22
+
23
+ @dataclass
24
+ class InteriorFusionOutput:
25
+ """Output container for InteriorFusion pipeline."""
26
+
27
+ # 3D representations
28
+ scene_mesh: Optional["trimesh.Trimesh"] = None # type: ignore
29
+ room_shell_mesh: Optional["trimesh.Trimesh"] = None # type: ignore
30
+ object_meshes: List["trimesh.Trimesh"] = field(default_factory=list) # type: ignore
31
+ gaussian_cloud: Optional[torch.Tensor] = None # Scene Gaussians
32
+
33
+ # Materials
34
+ pbr_materials: List[dict] = field(default_factory=list)
35
+
36
+ # Scene graph
37
+ scene_graph: Optional[dict] = None
38
+ room_layout: Optional[dict] = None
39
+
40
+ # Metadata
41
+ room_type: str = "unknown"
42
+ style: str = "modern"
43
+ processing_time: float = 0.0
44
+
45
+ # Export paths (populated after export)
46
+ glb_path: Optional[str] = None
47
+ fbx_path: Optional[str] = None
48
+ obj_path: Optional[str] = None
49
+ usdz_path: Optional[str] = None
50
+ ply_path: Optional[str] = None # Gaussian splatting
51
+
52
+ def export_all(self, output_dir: Union[str, Path]) -> "InteriorFusionOutput":
53
+ """Export all formats to output directory."""
54
+ output_dir = Path(output_dir)
55
+ output_dir.mkdir(parents=True, exist_ok=True)
56
+
57
+ if self.scene_mesh is not None:
58
+ self.glb_path = str(output_dir / "scene.glb")
59
+ export_mesh(self.scene_mesh, self.glb_path, format="glb")
60
+
61
+ self.fbx_path = str(output_dir / "scene.fbx")
62
+ export_mesh(self.scene_mesh, self.fbx_path, format="fbx")
63
+
64
+ self.obj_path = str(output_dir / "scene.obj")
65
+ export_mesh(self.scene_mesh, self.obj_path, format="obj")
66
+
67
+ self.usdz_path = str(output_dir / "scene.usdz")
68
+ export_mesh(self.scene_mesh, self.usdz_path, format="usdz")
69
+
70
+ if self.gaussian_cloud is not None:
71
+ self.ply_path = str(output_dir / "scene.ply")
72
+ export_gaussian_splatting(self.gaussian_cloud, self.ply_path)
73
+
74
+ return self
75
+
76
+
77
+ class InteriorFusionPipeline:
78
+ """
79
+ Main inference pipeline for InteriorFusion.
80
+
81
+ Orchestrates 5 phases:
82
+ 1. Scene Understanding (depth, layout, segmentation)
83
+ 2. Multi-View Generation (per-object + room shell)
84
+ 3. 3D Reconstruction (room shell + per-object)
85
+ 4. Scene Assembly (layout optimization, scale normalization)
86
+ 5. Material & Texture (PBR generation, texture baking)
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ model_size: str = "L",
92
+ device: str = "cuda",
93
+ dtype: torch.dtype = torch.float16,
94
+ use_scene_graph: bool = True,
95
+ use_pbr: bool = True,
96
+ use_gaussian_splatting: bool = True,
97
+ cache_dir: Optional[str] = None,
98
+ ):
99
+ self.model_size = model_size
100
+ self.device = device
101
+ self.dtype = dtype
102
+ self.use_scene_graph = use_scene_graph
103
+ self.use_pbr = use_pbr
104
+ self.use_gaussian_splatting = use_gaussian_splatting
105
+ self.cache_dir = cache_dir or os.path.expanduser("~/.cache/interiorfusion")
106
+
107
+ os.makedirs(self.cache_dir, exist_ok=True)
108
+
109
+ # Initialize sub-modules (lazy loading)
110
+ self._scene_understanding = None
111
+ self._multiview_gen = None
112
+ self._reconstruction = None
113
+ self._scene_assembly = None
114
+ self._material_texture = None
115
+
116
+ @property
117
+ def scene_understanding(self):
118
+ if self._scene_understanding is None:
119
+ self._scene_understanding = SceneUnderstandingModule(
120
+ model_size=self.model_size,
121
+ device=self.device,
122
+ dtype=self.dtype,
123
+ cache_dir=self.cache_dir,
124
+ )
125
+ return self._scene_understanding
126
+
127
+ @property
128
+ def multiview_gen(self):
129
+ if self._multiview_gen is None:
130
+ self._multiview_gen = MultiViewGenerationModule(
131
+ model_size=self.model_size,
132
+ device=self.device,
133
+ dtype=self.dtype,
134
+ cache_dir=self.cache_dir,
135
+ )
136
+ return self._multiview_gen
137
+
138
+ @property
139
+ def reconstruction(self):
140
+ if self._reconstruction is None:
141
+ self._reconstruction = Reconstruction3DModule(
142
+ model_size=self.model_size,
143
+ device=self.device,
144
+ dtype=self.dtype,
145
+ cache_dir=self.cache_dir,
146
+ )
147
+ return self._reconstruction
148
+
149
+ @property
150
+ def scene_assembly(self):
151
+ if self._scene_assembly is None:
152
+ self._scene_assembly = SceneAssemblyModule(
153
+ device=self.device,
154
+ dtype=self.dtype,
155
+ )
156
+ return self._scene_assembly
157
+
158
+ @property
159
+ def material_texture(self):
160
+ if self._material_texture is None:
161
+ self._material_texture = MaterialTextureModule(
162
+ model_size=self.model_size,
163
+ device=self.device,
164
+ dtype=self.dtype,
165
+ use_pbr=self.use_pbr,
166
+ cache_dir=self.cache_dir,
167
+ )
168
+ return self._material_texture
169
+
170
+ @torch.no_grad()
171
+ def __call__(
172
+ self,
173
+ image: Union[str, Path, Image.Image, np.ndarray],
174
+ room_type_hint: Optional[str] = None,
175
+ style_hint: Optional[str] = None,
176
+ output_formats: Optional[List[str]] = None,
177
+ return_intermediates: bool = False,
178
+ ) -> InteriorFusionOutput:
179
+ """
180
+ Run full InteriorFusion pipeline on a single interior image.
181
+
182
+ Args:
183
+ image: Input interior photograph
184
+ room_type_hint: Optional room type ("living_room", "bedroom", etc.)
185
+ style_hint: Optional style ("modern", "scandinavian", etc.)
186
+ output_formats: List of formats to export ["glb", "fbx", "obj", "usdz", "ply"]
187
+ return_intermediates: Whether to return intermediate stage outputs
188
+
189
+ Returns:
190
+ InteriorFusionOutput with all generated 3D content
191
+ """
192
+ import time
193
+ start_time = time.time()
194
+
195
+ # Convert input to PIL Image
196
+ if isinstance(image, (str, Path)):
197
+ image = Image.open(image).convert("RGB")
198
+ elif isinstance(image, np.ndarray):
199
+ image = Image.fromarray(image).convert("RGB")
200
+
201
+ # ============================
202
+ # Phase 1: Scene Understanding
203
+ # ============================
204
+ print("[Phase 1/5] Scene Understanding...")
205
+ scene_info = self.scene_understanding(image)
206
+
207
+ depth_map = scene_info["depth"]
208
+ room_layout = scene_info["room_layout"]
209
+ semantic_seg = scene_info["semantic_segmentation"]
210
+ detected_objects = scene_info["detected_objects"]
211
+ room_type = scene_info.get("room_type", room_type_hint or "living_room")
212
+ style = scene_info.get("style", style_hint or "modern")
213
+
214
+ # ============================
215
+ # Phase 2: Multi-View Generation
216
+ # ============================
217
+ print("[Phase 2/5] Multi-View Generation...")
218
+
219
+ # Per-object multi-view generation
220
+ object_multiviews = {}
221
+ for obj_id, obj_info in detected_objects.items():
222
+ crop = obj_info["crop"]
223
+ mask = obj_info["mask"]
224
+ multiviews = self.multiview_gen.generate_object_views(
225
+ crop, mask, depth_map, num_views=6
226
+ )
227
+ object_multiviews[obj_id] = multiviews
228
+
229
+ # Room shell multi-view
230
+ room_shell_views = self.multiview_gen.generate_room_shell_views(
231
+ image, depth_map, room_layout
232
+ )
233
+
234
+ # ============================
235
+ # Phase 3: 3D Reconstruction
236
+ # ============================
237
+ print("[Phase 3/5] 3D Reconstruction...")
238
+
239
+ # Room shell reconstruction
240
+ room_shell_mesh = self.reconstruction.reconstruct_room_shell(
241
+ room_shell_views, room_layout, depth_map
242
+ )
243
+
244
+ # Per-object reconstruction
245
+ object_meshes = []
246
+ object_gaussians = []
247
+ for obj_id, multiviews in object_multiviews.items():
248
+ obj_mesh, obj_gaussians = self.reconstruction.reconstruct_object(
249
+ multiviews,
250
+ room_layout=room_layout,
251
+ depth_map=depth_map,
252
+ object_info=detected_objects[obj_id],
253
+ )
254
+ object_meshes.append(obj_mesh)
255
+ object_gaussians.append(obj_gaussians)
256
+
257
+ # Scene Gaussian splatting
258
+ gaussian_cloud = None
259
+ if self.use_gaussian_splatting:
260
+ gaussian_cloud = self.reconstruction.build_scene_gaussians(
261
+ room_shell_mesh, object_gaussians, object_meshes
262
+ )
263
+
264
+ # ============================
265
+ # Phase 4: Scene Assembly
266
+ # ============================
267
+ print("[Phase 4/5] Scene Assembly...")
268
+
269
+ assembled_scene = self.scene_assembly.assemble(
270
+ room_shell_mesh=room_shell_mesh,
271
+ object_meshes=object_meshes,
272
+ room_layout=room_layout,
273
+ detected_objects=detected_objects,
274
+ depth_map=depth_map,
275
+ )
276
+
277
+ scene_mesh = assembled_scene["scene_mesh"]
278
+ scene_graph = assembled_scene.get("scene_graph")
279
+
280
+ # ============================
281
+ # Phase 5: Material & Texture
282
+ # ============================
283
+ print("[Phase 5/5] Material & Texture...")
284
+
285
+ pbr_materials = []
286
+ if self.use_pbr:
287
+ # Room shell materials
288
+ room_shell_mesh = self.material_texture.generate_room_materials(
289
+ room_shell_mesh, image, semantic_seg
290
+ )
291
+
292
+ # Per-object materials
293
+ textured_objects = []
294
+ for i, obj_mesh in enumerate(object_meshes):
295
+ obj_id = list(detected_objects.keys())[i]
296
+ textured_obj, materials = self.material_texture.generate_object_materials(
297
+ obj_mesh,
298
+ object_multiviews[obj_id],
299
+ detected_objects[obj_id],
300
+ )
301
+ textured_objects.append(textured_obj)
302
+ pbr_materials.extend(materials)
303
+
304
+ # Re-assemble with textured objects
305
+ scene_mesh = self.scene_assembly.reassemble_with_textures(
306
+ room_shell_mesh, textured_objects, scene_graph
307
+ )
308
+
309
+ processing_time = time.time() - start_time
310
+
311
+ output = InteriorFusionOutput(
312
+ scene_mesh=scene_mesh,
313
+ room_shell_mesh=room_shell_mesh,
314
+ object_meshes=object_meshes if not self.use_pbr else textured_objects,
315
+ gaussian_cloud=gaussian_cloud,
316
+ pbr_materials=pbr_materials,
317
+ scene_graph=scene_graph,
318
+ room_layout=room_layout,
319
+ room_type=room_type,
320
+ style=style,
321
+ processing_time=processing_time,
322
+ )
323
+
324
+ print(f"\n✅ Generation complete in {processing_time:.1f}s")
325
+ print(f" Room type: {room_type}")
326
+ print(f" Style: {style}")
327
+ print(f" Objects detected: {len(detected_objects)}")
328
+ print(f" PBR materials: {len(pbr_materials)}")
329
+
330
+ return output
331
+
332
+ def edit_scene(
333
+ self,
334
+ scene_output: InteriorFusionOutput,
335
+ edits: List[dict],
336
+ ) -> InteriorFusionOutput:
337
+ """
338
+ Apply edits to a generated scene.
339
+
340
+ Edits format:
341
+ [
342
+ {"action": "move", "object_id": 0, "position": [x, y, z]},
343
+ {"action": "replace", "object_id": 1, "new_image": Image},
344
+ {"action": "remove", "object_id": 2},
345
+ {"action": "add", "new_image": Image, "position": [x, y, z]},
346
+ ]
347
+ """
348
+ print(f"Applying {len(edits)} edits...")
349
+
350
+ scene_graph = scene_output.scene_graph or {}
351
+ object_meshes = list(scene_output.object_meshes)
352
+
353
+ for edit in edits:
354
+ action = edit["action"]
355
+
356
+ if action == "move":
357
+ obj_id = edit["object_id"]
358
+ new_pos = edit["position"]
359
+ # Update scene graph
360
+ if "nodes" in scene_graph and obj_id < len(scene_graph["nodes"]):
361
+ scene_graph["nodes"][obj_id]["position"] = new_pos
362
+ # Update mesh transform
363
+ if obj_id < len(object_meshes):
364
+ # Apply translation
365
+ mesh = object_meshes[obj_id]
366
+ mesh.vertices += np.array(new_pos)
367
+
368
+ elif action == "replace":
369
+ obj_id = edit["object_id"]
370
+ new_image = edit["new_image"]
371
+ # Generate new object from image
372
+ new_multiviews = self.multiview_gen.generate_object_views(
373
+ new_image, None, None, num_views=6
374
+ )
375
+ new_mesh, _ = self.reconstruction.reconstruct_object(
376
+ new_multiviews, room_layout=scene_output.room_layout
377
+ )
378
+ object_meshes[obj_id] = new_mesh
379
+
380
+ elif action == "remove":
381
+ obj_id = edit["object_id"]
382
+ if obj_id < len(object_meshes):
383
+ object_meshes.pop(obj_id)
384
+
385
+ elif action == "add":
386
+ new_image = edit["new_image"]
387
+ position = edit["position"]
388
+ new_multiviews = self.multiview_gen.generate_object_views(
389
+ new_image, None, None, num_views=6
390
+ )
391
+ new_mesh, _ = self.reconstruction.reconstruct_object(
392
+ new_multiviews, room_layout=scene_output.room_layout
393
+ )
394
+ new_mesh.vertices += np.array(position)
395
+ object_meshes.append(new_mesh)
396
+
397
+ # Re-assemble
398
+ assembled = self.scene_assembly.reassemble_with_textures(
399
+ scene_output.room_shell_mesh,
400
+ object_meshes,
401
+ scene_graph,
402
+ )
403
+
404
+ return InteriorFusionOutput(
405
+ scene_mesh=assembled,
406
+ room_shell_mesh=scene_output.room_shell_mesh,
407
+ object_meshes=object_meshes,
408
+ gaussian_cloud=scene_output.gaussian_cloud,
409
+ pbr_materials=scene_output.pbr_materials,
410
+ scene_graph=scene_graph,
411
+ room_layout=scene_output.room_layout,
412
+ room_type=scene_output.room_type,
413
+ style=scene_output.style,
414
+ )