Sm0kyWu commited on
Commit
81b4cc3
Β·
verified Β·
1 Parent(s): 89862ae

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -119
app.py CHANGED
@@ -94,113 +94,118 @@ def segment_and_overlay(image, points, sam_predictor):
94
  return overlaid, visible_mask
95
 
96
 
97
- # def image_to_3d(images,masks,seed,ss_guidance_strength,ss_sampling_steps,slat_guidance_strength,slat_sampling_steps):
98
- # """
99
- # 将图像转捒为 3D ζ¨‘εž‹γ€‚
100
- # """
101
- # print(images.shape, masks.shape)
102
- # print(type(images), type(masks))
103
- # print(seed)
104
- # print(ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps)
105
- # # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
106
- # test_tensor = torch.zeros((1, 3, 64, 64))
107
- # print(test_tensor.shape, test_tensor.device)
108
- # # outputs = pipeline.run_multi_image(
109
- # # [images],
110
- # # [masks],
111
- # # seed=seed,
112
- # # formats=["gaussian", "mesh"],
113
- # # preprocess_image=False,
114
- # # sparse_structure_sampler_params={
115
- # # "steps": ss_sampling_steps,
116
- # # "cfg_strength": ss_guidance_strength,
117
- # # },
118
- # # slat_sampler_params={
119
- # # "steps": slat_sampling_steps,
120
- # # "cfg_strength": slat_guidance_strength,
121
- # # },
122
- # # mode="stochastic",
123
- # # )
124
- # # video = render_utils.render_video(outputs['gaussian'][0], num_frames=120, bg_color=(1, 1, 1))['color']
125
- # # video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120, bg_color=(1, 1, 1))['normal']
126
- # # video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
127
- # # video_path = os.path.join(user_dir, 'sample.mp4')
128
- # # imageio.mimsave(video_path, video, fps=15)
129
- # # state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
130
- # # torch.cuda.empty_cache()
131
- # state = None
132
- # video_path = None
133
- # return state, video_path
134
-
135
- # @spaces.GPU(duration=90)
136
- # def extract_glb(
137
- # state: dict,
138
- # mesh_simplify: float,
139
- # texture_size: int,
140
- # req: gr.Request,
141
- # ) -> tuple:
142
- # """
143
- # δ»Žη”Ÿζˆηš„ 3D ζ¨‘εž‹δΈ­ζε– GLB 文仢。
144
- # """
145
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
146
- # gs, mesh = unpack_state(state)
147
- # glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
148
- # glb_path = os.path.join(user_dir, 'sample.glb')
149
- # glb.export(glb_path)
150
- # torch.cuda.empty_cache()
151
- # return glb_path, glb_path
152
-
153
- # @spaces.GPU
154
- # def extract_gaussian(state: dict, req: gr.Request) -> tuple:
155
- # """
156
- # δ»Žη”Ÿζˆηš„ 3D ζ¨‘εž‹δΈ­ζε– Gaussian 文仢。
157
- # """
158
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
159
- # gs, _ = unpack_state(state)
160
- # gaussian_path = os.path.join(user_dir, 'sample.ply')
161
- # gs.save_ply(gaussian_path)
162
- # torch.cuda.empty_cache()
163
- # return gaussian_path, gaussian_path
164
-
165
-
166
- # def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
167
- # return {
168
- # 'gaussian': {
169
- # **gs.init_params,
170
- # '_xyz': gs._xyz.cpu().numpy(),
171
- # '_features_dc': gs._features_dc.cpu().numpy(),
172
- # '_scaling': gs._scaling.cpu().numpy(),
173
- # '_rotation': gs._rotation.cpu().numpy(),
174
- # '_opacity': gs._opacity.cpu().numpy(),
175
- # },
176
- # 'mesh': {
177
- # 'vertices': mesh.vertices.cpu().numpy(),
178
- # 'faces': mesh.faces.cpu().numpy(),
179
- # },
180
- # }
 
 
 
 
 
181
 
182
 
183
- # def unpack_state(state: dict) -> tuple:
184
- # gs = Gaussian(
185
- # aabb=state['gaussian']['aabb'],
186
- # sh_degree=state['gaussian']['sh_degree'],
187
- # mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
188
- # scaling_bias=state['gaussian']['scaling_bias'],
189
- # opacity_bias=state['gaussian']['opacity_bias'],
190
- # scaling_activation=state['gaussian']['scaling_activation'],
191
- # )
192
- # gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
193
- # gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
194
- # gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
195
- # gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
196
- # gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
197
 
198
- # mesh = edict(
199
- # vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
200
- # faces=torch.tensor(state['mesh']['faces'], device='cuda'),
201
- # )
202
 
203
- # return gs, mesh
204
 
205
  def get_sam_predictor():
206
  sam_checkpoint = hf_hub_download("ybelkada/segment-anything", "checkpoints/sam_vit_h_4b8939.pth")
@@ -425,22 +430,22 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
425
  * Different random seeds can be tried in "Generation Settings", if you think the results are not ideal.
426
  * If the reconstruction 3D asset is satisfactory, you can extract the GLB file and download it.
427
  """)
428
- with gr.Row():
429
- with gr.Column():
430
- with gr.Accordion(label="Generation Settings", open=True):
431
- seed = gr.Slider(0, MAX_SEED, label="Seed", value=1, step=1)
432
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
433
- gr.Markdown("Stage 1: Sparse Structure Generation")
434
- with gr.Row():
435
- ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
436
- ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
437
- gr.Markdown("Stage 2: Structured Latent Generation")
438
- with gr.Row():
439
- slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
440
- slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
441
- generate_btn = gr.Button("Generate")
442
- with gr.Column():
443
- video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)
444
 
445
  # # Handlers
446
  # demo.load(start_session)
@@ -540,6 +545,7 @@ with gr.Blocks(delete_cache=(600, 600)) as demo:
540
  # 启动 Gradio App
541
  if __name__ == "__main__":
542
  pipeline = Amodal3RImageTo3DPipeline.from_pretrained("Sm0kyWu/Amodal3R")
 
543
  try:
544
  pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
545
  except:
 
94
  return overlaid, visible_mask
95
 
96
 
97
+ @spaces.GPU
98
+ def image_to_3d(
99
+ image: List[tuple],
100
+ masks: List[np.ndarray],
101
+ seed: int,
102
+ ss_guidance_strength: float,
103
+ ss_sampling_steps: int,
104
+ slat_guidance_strength: float,
105
+ slat_sampling_steps: int,
106
+ multiimage_algo: str,
107
+ req: gr.Request,
108
+ ) -> tuple:
109
+ """
110
+ 将图像转捒为 3D ζ¨‘εž‹γ€‚
111
+ """
112
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
113
+ outputs = pipeline.run_multi_image(
114
+ [img[0] for img in image],
115
+ [mask[0] for mask in masks],
116
+ seed=seed,
117
+ formats=["gaussian", "mesh"],
118
+ preprocess_image=False,
119
+ sparse_structure_sampler_params={
120
+ "steps": ss_sampling_steps,
121
+ "cfg_strength": ss_guidance_strength,
122
+ },
123
+ slat_sampler_params={
124
+ "steps": slat_sampling_steps,
125
+ "cfg_strength": slat_guidance_strength,
126
+ },
127
+ mode=multiimage_algo,
128
+ )
129
+ video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
130
+ video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
131
+ video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
132
+ video_path = os.path.join(user_dir, 'sample.mp4')
133
+ imageio.mimsave(video_path, video, fps=15)
134
+ state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
135
+ torch.cuda.empty_cache()
136
+ return state, video_path
137
+
138
+
139
+ @spaces.GPU(duration=90)
140
+ def extract_glb(
141
+ state: dict,
142
+ mesh_simplify: float,
143
+ texture_size: int,
144
+ req: gr.Request,
145
+ ) -> tuple:
146
+ """
147
+ δ»Žη”Ÿζˆηš„ 3D ζ¨‘εž‹δΈ­ζε– GLB 文仢。
148
+ """
149
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
150
+ gs, mesh = unpack_state(state)
151
+ glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
152
+ glb_path = os.path.join(user_dir, 'sample.glb')
153
+ glb.export(glb_path)
154
+ torch.cuda.empty_cache()
155
+ return glb_path, glb_path
156
+
157
+
158
+ @spaces.GPU
159
+ def extract_gaussian(state: dict, req: gr.Request) -> tuple:
160
+ """
161
+ δ»Žη”Ÿζˆηš„ 3D ζ¨‘εž‹δΈ­ζε– Gaussian 文仢。
162
+ """
163
+ user_dir = os.path.join(TMP_DIR, str(req.session_hash))
164
+ gs, _ = unpack_state(state)
165
+ gaussian_path = os.path.join(user_dir, 'sample.ply')
166
+ gs.save_ply(gaussian_path)
167
+ torch.cuda.empty_cache()
168
+ return gaussian_path, gaussian_path
169
+
170
+
171
+ def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
172
+ return {
173
+ 'gaussian': {
174
+ **gs.init_params,
175
+ '_xyz': gs._xyz.cpu().numpy(),
176
+ '_features_dc': gs._features_dc.cpu().numpy(),
177
+ '_scaling': gs._scaling.cpu().numpy(),
178
+ '_rotation': gs._rotation.cpu().numpy(),
179
+ '_opacity': gs._opacity.cpu().numpy(),
180
+ },
181
+ 'mesh': {
182
+ 'vertices': mesh.vertices.cpu().numpy(),
183
+ 'faces': mesh.faces.cpu().numpy(),
184
+ },
185
+ }
186
 
187
 
188
+ def unpack_state(state: dict) -> tuple:
189
+ gs = Gaussian(
190
+ aabb=state['gaussian']['aabb'],
191
+ sh_degree=state['gaussian']['sh_degree'],
192
+ mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
193
+ scaling_bias=state['gaussian']['scaling_bias'],
194
+ opacity_bias=state['gaussian']['opacity_bias'],
195
+ scaling_activation=state['gaussian']['scaling_activation'],
196
+ )
197
+ gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
198
+ gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
199
+ gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
200
+ gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
201
+ gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
202
 
203
+ mesh = edict(
204
+ vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
205
+ faces=torch.tensor(state['mesh']['faces'], device='cuda'),
206
+ )
207
 
208
+ return gs, mesh
209
 
210
  def get_sam_predictor():
211
  sam_checkpoint = hf_hub_download("ybelkada/segment-anything", "checkpoints/sam_vit_h_4b8939.pth")
 
430
  * Different random seeds can be tried in "Generation Settings", if you think the results are not ideal.
431
  * If the reconstruction 3D asset is satisfactory, you can extract the GLB file and download it.
432
  """)
433
+ # with gr.Row():
434
+ # with gr.Column():
435
+ # with gr.Accordion(label="Generation Settings", open=True):
436
+ # seed = gr.Slider(0, MAX_SEED, label="Seed", value=1, step=1)
437
+ # randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
438
+ # gr.Markdown("Stage 1: Sparse Structure Generation")
439
+ # with gr.Row():
440
+ # ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
441
+ # ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
442
+ # gr.Markdown("Stage 2: Structured Latent Generation")
443
+ # with gr.Row():
444
+ # slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
445
+ # slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
446
+ # generate_btn = gr.Button("Generate")
447
+ # with gr.Column():
448
+ # video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)
449
 
450
  # # Handlers
451
  # demo.load(start_session)
 
545
  # 启动 Gradio App
546
  if __name__ == "__main__":
547
  pipeline = Amodal3RImageTo3DPipeline.from_pretrained("Sm0kyWu/Amodal3R")
548
+ pipeline.cuda()
549
  try:
550
  pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
551
  except: