HongFangzhou commited on
Commit
a6e635b
β€’
1 Parent(s): 9db45af

first commit

Browse files
Files changed (3) hide show
  1. LICENSE +201 -0
  2. app.py +359 -0
  3. requirements.txt +57 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
app.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+
4
+ os.system("git clone https://github.com/3DTopia/3DTopia")
5
+ sys.path.append("3DTopia")
6
+
7
+ import os
8
+ import cv2
9
+ import time
10
+ import json
11
+ import torch
12
+ import mcubes
13
+ import trimesh
14
+ import datetime
15
+ import argparse
16
+ import subprocess
17
+ import numpy as np
18
+ import gradio as gr
19
+ from tqdm import tqdm
20
+ import imageio.v2 as imageio
21
+ import pytorch_lightning as pl
22
+ from omegaconf import OmegaConf
23
+
24
+ from ldm.models.diffusion.ddim import DDIMSampler
25
+ from ldm.models.diffusion.plms import PLMSSampler
26
+ from ldm.models.diffusion.dpm_solver import DPMSolverSampler
27
+
28
+ from utility.initialize import instantiate_from_config, get_obj_from_str
29
+ from utility.triplane_renderer.eg3d_renderer import sample_from_planes, generate_planes
30
+ from utility.triplane_renderer.renderer import get_rays, to8b
31
+ from safetensors.torch import load_file
32
+ from huggingface_hub import hf_hub_download
33
+
34
+ import warnings
35
+ warnings.filterwarnings("ignore", category=UserWarning)
36
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
37
+
38
+ def add_text(rgb, caption):
39
+ font = cv2.FONT_HERSHEY_SIMPLEX
40
+ # org
41
+ gap = 10
42
+ org = (gap, gap)
43
+ # fontScale
44
+ fontScale = 0.3
45
+ # Blue color in BGR
46
+ color = (255, 0, 0)
47
+ # Line thickness of 2 px
48
+ thickness = 1
49
+ break_caption = []
50
+ for i in range(len(caption) // 30 + 1):
51
+ break_caption_i = caption[i*30:(i+1)*30]
52
+ break_caption.append(break_caption_i)
53
+ for i, bci in enumerate(break_caption):
54
+ cv2.putText(rgb, bci, (gap, gap*(i+1)), font, fontScale, color, thickness, cv2.LINE_AA)
55
+ return rgb
56
+
57
+ config = "configs/default.yaml"
58
+ local_ckpt = "checkpoints/3dtopia_diffusion_state_dict.ckpt"
59
+ if os.path.exists(local_ckpt):
60
+ ckpt = local_ckpt
61
+ else:
62
+ ckpt = hf_hub_download(repo_id="hongfz16/3DTopia", filename="model.safetensors")
63
+ configs = OmegaConf.load(config)
64
+ os.makedirs("tmp", exist_ok=True)
65
+
66
+ if ckpt.endswith(".ckpt"):
67
+ model = get_obj_from_str(configs.model["target"]).load_from_checkpoint(ckpt, map_location='cpu', strict=False, **configs.model.params)
68
+ elif ckpt.endswith(".safetensors"):
69
+ model = get_obj_from_str(configs.model["target"])(**configs.model.params)
70
+ model_ckpt = load_file(ckpt)
71
+ model.load_state_dict(model_ckpt)
72
+ else:
73
+ raise NotImplementedError
74
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
75
+ model = model.to(device)
76
+ sampler = DDIMSampler(model)
77
+
78
+ img_size = configs.model.params.unet_config.params.image_size
79
+ channels = configs.model.params.unet_config.params.in_channels
80
+ shape = [channels, img_size, img_size * 3]
81
+
82
+ pose_folder = 'assets/sample_data/pose'
83
+ poses_fname = sorted([os.path.join(pose_folder, f) for f in os.listdir(pose_folder)])
84
+ batch_rays_list = []
85
+ H = 128
86
+ ratio = 512 // H
87
+ for p in poses_fname:
88
+ c2w = np.loadtxt(p).reshape(4, 4)
89
+ c2w[:3, 3] *= 2.2
90
+ c2w = np.array([
91
+ [1, 0, 0, 0],
92
+ [0, 0, -1, 0],
93
+ [0, 1, 0, 0],
94
+ [0, 0, 0, 1]
95
+ ]) @ c2w
96
+
97
+ k = np.array([
98
+ [560 / ratio, 0, H * 0.5],
99
+ [0, 560 / ratio, H * 0.5],
100
+ [0, 0, 1]
101
+ ])
102
+
103
+ rays_o, rays_d = get_rays(H, H, torch.Tensor(k), torch.Tensor(c2w[:3, :4]))
104
+ coords = torch.stack(torch.meshgrid(torch.linspace(0, H-1, H), torch.linspace(0, H-1, H), indexing='ij'), -1)
105
+ coords = torch.reshape(coords, [-1,2]).long()
106
+ rays_o = rays_o[coords[:, 0], coords[:, 1]]
107
+ rays_d = rays_d[coords[:, 0], coords[:, 1]]
108
+ batch_rays = torch.stack([rays_o, rays_d], 0)
109
+ batch_rays_list.append(batch_rays)
110
+ batch_rays_list = torch.stack(batch_rays_list, 0)
111
+
112
+ def marching_cube(b, text, global_info):
113
+ # prepare volumn for marching cube
114
+ res = 128
115
+ assert 'decode_res' in global_info
116
+ decode_res = global_info['decode_res']
117
+ c_list = torch.linspace(-1.2, 1.2, steps=res)
118
+ grid_x, grid_y, grid_z = torch.meshgrid(
119
+ c_list, c_list, c_list, indexing='ij'
120
+ )
121
+ coords = torch.stack([grid_x, grid_y, grid_z], -1).to(device)
122
+ plane_axes = generate_planes()
123
+ feats = sample_from_planes(
124
+ plane_axes, decode_res[b:b+1].reshape(1, 3, -1, 256, 256), coords.reshape(1, -1, 3), padding_mode='zeros', box_warp=2.4
125
+ )
126
+ fake_dirs = torch.zeros_like(coords)
127
+ fake_dirs[..., 0] = 1
128
+ out = model.first_stage_model.triplane_decoder.decoder(feats, fake_dirs)
129
+ u = out['sigma'].reshape(res, res, res).detach().cpu().numpy()
130
+ del out
131
+
132
+ # marching cube
133
+ vertices, triangles = mcubes.marching_cubes(u, 10)
134
+ min_bound = np.array([-1.2, -1.2, -1.2])
135
+ max_bound = np.array([1.2, 1.2, 1.2])
136
+ vertices = vertices / (res - 1) * (max_bound - min_bound)[None, :] + min_bound[None, :]
137
+ pt_vertices = torch.from_numpy(vertices).to(device)
138
+
139
+ # extract vertices color
140
+ res_triplane = 256
141
+ render_kwargs = {
142
+ 'depth_resolution': 128,
143
+ 'disparity_space_sampling': False,
144
+ 'box_warp': 2.4,
145
+ 'depth_resolution_importance': 128,
146
+ 'clamp_mode': 'softplus',
147
+ 'white_back': True,
148
+ 'det': True
149
+ }
150
+ rays_o_list = [
151
+ np.array([0, 0, 2]),
152
+ np.array([0, 0, -2]),
153
+ np.array([0, 2, 0]),
154
+ np.array([0, -2, 0]),
155
+ np.array([2, 0, 0]),
156
+ np.array([-2, 0, 0]),
157
+ ]
158
+ rgb_final = None
159
+ diff_final = None
160
+ for rays_o in tqdm(rays_o_list):
161
+ rays_o = torch.from_numpy(rays_o.reshape(1, 3)).repeat(vertices.shape[0], 1).float().to(device)
162
+ rays_d = pt_vertices.reshape(-1, 3) - rays_o
163
+ rays_d = rays_d / torch.norm(rays_d, dim=-1).reshape(-1, 1)
164
+ dist = torch.norm(pt_vertices.reshape(-1, 3) - rays_o, dim=-1).cpu().numpy().reshape(-1)
165
+
166
+ render_out = model.first_stage_model.triplane_decoder(
167
+ decode_res[b:b+1].reshape(1, 3, -1, res_triplane, res_triplane),
168
+ rays_o.unsqueeze(0), rays_d.unsqueeze(0), render_kwargs,
169
+ whole_img=False, tvloss=False
170
+ )
171
+ rgb = render_out['rgb_marched'].reshape(-1, 3).detach().cpu().numpy()
172
+ depth = render_out['depth_final'].reshape(-1).detach().cpu().numpy()
173
+ depth_diff = np.abs(dist - depth)
174
+
175
+ if rgb_final is None:
176
+ rgb_final = rgb.copy()
177
+ diff_final = depth_diff.copy()
178
+
179
+ else:
180
+ ind = diff_final > depth_diff
181
+ rgb_final[ind] = rgb[ind]
182
+ diff_final[ind] = depth_diff[ind]
183
+
184
+ # bgr to rgb
185
+ rgb_final = np.stack([
186
+ rgb_final[:, 2], rgb_final[:, 1], rgb_final[:, 0]
187
+ ], -1)
188
+
189
+ # export to ply
190
+ mesh = trimesh.Trimesh(vertices, triangles, vertex_colors=(rgb_final * 255).astype(np.uint8))
191
+ path = os.path.join('tmp', f"{text.replace(' ', '_')}_{str(datetime.datetime.now()).replace(' ', '_')}.ply")
192
+ trimesh.exchange.export.export_mesh(mesh, path, file_type='ply')
193
+
194
+ del vertices, triangles, rgb_final
195
+ torch.cuda.empty_cache()
196
+
197
+ return path
198
+
199
+ def infer(prompt, samples, steps, scale, seed, global_info):
200
+ prompt = prompt.replace('/', '')
201
+ pl.seed_everything(seed)
202
+ batch_size = samples
203
+ with torch.no_grad():
204
+ noise = None
205
+ c = model.get_learned_conditioning([prompt])
206
+ unconditional_c = torch.zeros_like(c)
207
+ sample, _ = sampler.sample(
208
+ S=steps,
209
+ batch_size=batch_size,
210
+ shape=shape,
211
+ verbose=False,
212
+ x_T = noise,
213
+ conditioning = c.repeat(batch_size, 1, 1),
214
+ unconditional_guidance_scale=scale,
215
+ unconditional_conditioning=unconditional_c.repeat(batch_size, 1, 1)
216
+ )
217
+ decode_res = model.decode_first_stage(sample)
218
+
219
+ big_video_list = []
220
+
221
+ global_info['decode_res'] = decode_res
222
+
223
+ for b in range(batch_size):
224
+ def render_img(v):
225
+ rgb_sample, _ = model.first_stage_model.render_triplane_eg3d_decoder(
226
+ decode_res[b:b+1], batch_rays_list[v:v+1].to(device), torch.zeros(1, H, H, 3).to(device),
227
+ )
228
+ rgb_sample = to8b(rgb_sample.detach().cpu().numpy())[0]
229
+ rgb_sample = np.stack(
230
+ [rgb_sample[..., 2], rgb_sample[..., 1], rgb_sample[..., 0]], -1
231
+ )
232
+ rgb_sample = add_text(rgb_sample, str(b))
233
+ return rgb_sample
234
+
235
+ view_num = len(batch_rays_list)
236
+ video_list = []
237
+ for v in tqdm(range(view_num//8*3, view_num//8*5, 2)):
238
+ rgb_sample = render_img(v)
239
+ video_list.append(rgb_sample)
240
+ big_video_list.append(video_list)
241
+ # if batch_size == 2:
242
+ # cat_video_list = [
243
+ # np.concatenate([big_video_list[j][i] for j in range(len(big_video_list))], 1) \
244
+ # for i in range(len(big_video_list[0]))
245
+ # ]
246
+ # elif batch_size > 2:
247
+ # if batch_size == 3:
248
+ # big_video_list.append(
249
+ # [np.zeros_like(f) for f in big_video_list[0]]
250
+ # )
251
+ # cat_video_list = [
252
+ # np.concatenate([
253
+ # np.concatenate([big_video_list[0][i], big_video_list[1][i]], 1),
254
+ # np.concatenate([big_video_list[2][i], big_video_list[3][i]], 1),
255
+ # ], 0) \
256
+ # for i in range(len(big_video_list[0]))
257
+ # ]
258
+ # else:
259
+ # cat_video_list = big_video_list[0]
260
+
261
+ for _ in range(4 - batch_size):
262
+ big_video_list.append(
263
+ [np.zeros_like(f) + 255 for f in big_video_list[0]]
264
+ )
265
+ cat_video_list = [
266
+ np.concatenate([
267
+ np.concatenate([big_video_list[0][i], big_video_list[1][i]], 1),
268
+ np.concatenate([big_video_list[2][i], big_video_list[3][i]], 1),
269
+ ], 0) \
270
+ for i in range(len(big_video_list[0]))
271
+ ]
272
+
273
+ path = f"tmp/{prompt.replace(' ', '_')}_{str(datetime.datetime.now()).replace(' ', '_')}.mp4"
274
+ imageio.mimwrite(path, np.stack(cat_video_list, 0))
275
+
276
+ return global_info, path
277
+
278
+ def infer_stage2(prompt, selection, seed, global_info):
279
+ prompt = prompt.replace('/', '')
280
+ mesh_path = marching_cube(int(selection), prompt, global_info)
281
+ mesh_name = mesh_path.split('/')[-1][:-4]
282
+
283
+ if2_cmd = f"threefiner if2 --mesh {mesh_path} --prompt \"{prompt}\" --outdir tmp --save {mesh_name}_if2.glb --text_dir --front_dir=-y"
284
+ print(if2_cmd)
285
+ # os.system(if2_cmd)
286
+ subprocess.Popen(if2_cmd, shell=True).wait()
287
+ torch.cuda.empty_cache()
288
+
289
+ video_path = f"tmp/{prompt.replace(' ', '_')}_{str(datetime.datetime.now()).replace(' ', '_')}.mp4"
290
+ render_cmd = f"kire {os.path.join('tmp', mesh_name + '_if2.glb')} --save_video {video_path} --wogui --force_cuda_rast --H 256 --W 256"
291
+ print(render_cmd)
292
+ # os.system(render_cmd)
293
+ subprocess.Popen(render_cmd, shell=True).wait()
294
+ torch.cuda.empty_cache()
295
+
296
+ return video_path, os.path.join('tmp', mesh_name + '_if2.glb')
297
+
298
+ markdown=f'''
299
+ # 3DTopia
300
+ A two-stage text-to-3D generation model. The first stage uses diffusion model to quickly generate candidates. The second stage refines the assets chosen from the first stage.
301
+
302
+ ### Usage:
303
+ First enter prompt for a 3D object, hit "Generate 3D". Then choose one candidate from the dropdown options for the second stage refinement and hit "Start Refinement". The final mesh can be downloaded from the bottom right box.
304
+
305
+ ### Runtime:
306
+ The first stage takes 30s if generating 4 samples. The second stage takes roughly 3 min.
307
+
308
+ ### Useful links:
309
+ [Github Repo](https://github.com/3DTopia/3DTopia)
310
+ '''
311
+
312
+ block = gr.Blocks()
313
+
314
+ with block:
315
+ global_info = gr.State(dict())
316
+ gr.Markdown(markdown)
317
+ with gr.Row():
318
+ with gr.Column():
319
+ with gr.Row():
320
+ text = gr.Textbox(
321
+ label = "Enter your prompt",
322
+ max_lines = 1,
323
+ placeholder = "Enter your prompt",
324
+ container = False,
325
+ )
326
+ btn = gr.Button("Generate 3D")
327
+ gallery = gr.Video(height=512)
328
+ # advanced_button = gr.Button("Advanced Options", elem_id="advanced-btn")
329
+ with gr.Row(elem_id="advanced-options"):
330
+ with gr.Tab("Advanced options"):
331
+ samples = gr.Slider(label="Number of Samples", minimum=1, maximum=4, value=4, step=1)
332
+ steps = gr.Slider(label="Steps", minimum=1, maximum=500, value=50, step=1)
333
+ scale = gr.Slider(
334
+ label="Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1
335
+ )
336
+ seed = gr.Slider(
337
+ label="Seed",
338
+ minimum=0,
339
+ maximum=2147483647,
340
+ step=1,
341
+ randomize=True,
342
+ )
343
+ gr.on([text.submit, btn.click], infer, inputs=[text, samples, steps, scale, seed, global_info], outputs=[global_info, gallery])
344
+ # advanced_button.click(
345
+ # None,
346
+ # [],
347
+ # text,
348
+ # )
349
+ with gr.Column():
350
+ with gr.Row():
351
+ dropdown = gr.Dropdown(
352
+ ['0', '1', '2', '3'], label="Choose a candidate for stage2", value='0'
353
+ )
354
+ btn_stage2 = gr.Button("Start Refinement")
355
+ gallery = gr.Video(height=512)
356
+ download = gr.File(label="Download mesh", file_count="single", height=100)
357
+ gr.on([btn_stage2.click], infer_stage2, inputs=[text, dropdown, seed, global_info], outputs=[gallery, download])
358
+
359
+ block.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch==1.12.0+cu113
3
+ torchvision==0.13.0+cu113
4
+ torchaudio==0.12.0
5
+ numpy
6
+ tqdm
7
+ yaml
8
+ git+https://github.com/openai/CLIP.git
9
+ einops==1.2.0
10
+ huggingface-hub==0.16.4
11
+ imageio==2.31.0
12
+ imageio-ffmpeg==0.4.8
13
+ importlib-resources==6.1.0
14
+ ipdb==0.13.13
15
+ ipython==8.12.2
16
+ jedi==0.19.0
17
+ kiwisolver==1.4.5
18
+ kornia==0.6.0
19
+ lpips==0.1.4
20
+ matplotlib==3.7.3
21
+ matplotlib-inline==0.1.6
22
+ omegaconf==2.3.0
23
+ open-clip-torch==2.20.0
24
+ opencv-python==4.7.0.72
25
+ parso==0.8.3
26
+ pathtools==0.1.2
27
+ pexpect==4.8.0
28
+ pickleshare==0.7.5
29
+ pillow==9.5.0
30
+ prompt-toolkit==3.0.39
31
+ protobuf==3.20.3
32
+ psutil==5.9.5
33
+ ptyprocess==0.7.0
34
+ pure-eval==0.2.2
35
+ pygments==2.16.1
36
+ pymcubes==0.1.4
37
+ pyparsing==3.1.1
38
+ pytorch-fid==0.3.0
39
+ pytorch-msssim==1.0.0
40
+ regex==2023.6.3
41
+ safetensors==0.3.3
42
+ scipy==1.10.1
43
+ sentencepiece==0.1.99
44
+ sentry-sdk==1.25.0
45
+ setproctitle==1.3.2
46
+ smmap==5.0.0
47
+ stack-data==0.6.2
48
+ timm==0.9.7
49
+ tokenizers==0.12.1
50
+ tomli==2.0.1
51
+ traitlets==5.9.0
52
+ transformers
53
+ trimesh==4.0.2
54
+ vit-pytorch==1.2.2
55
+ wandb==0.15.3
56
+ wcwidth==0.2.6
57
+ zipp==3.17.0