Spaces:
Runtime error
Runtime error
Upload model/crm/model.py with huggingface_hub
Browse files- model/crm/model.py +217 -0
model/crm/model.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
from pathlib import Path
|
9 |
+
import cv2
|
10 |
+
import trimesh
|
11 |
+
import nvdiffrast.torch as dr
|
12 |
+
|
13 |
+
from model.archs.decoders.shape_texture_net import TetTexNet
|
14 |
+
from model.archs.unet import UNetPP
|
15 |
+
from util.renderer import Renderer
|
16 |
+
from model.archs.mlp_head import SdfMlp, RgbMlp
|
17 |
+
import xatlas
|
18 |
+
|
19 |
+
|
20 |
+
class Dummy:
|
21 |
+
pass
|
22 |
+
|
23 |
+
class CRM(nn.Module):
|
24 |
+
def __init__(self, specs):
|
25 |
+
super(CRM, self).__init__()
|
26 |
+
|
27 |
+
self.specs = specs
|
28 |
+
# configs
|
29 |
+
input_specs = specs["Input"]
|
30 |
+
self.input = Dummy()
|
31 |
+
self.input.scale = input_specs['scale']
|
32 |
+
self.input.resolution = input_specs['resolution']
|
33 |
+
self.tet_grid_size = input_specs['tet_grid_size']
|
34 |
+
self.camera_angle_num = input_specs['camera_angle_num']
|
35 |
+
|
36 |
+
self.arch = Dummy()
|
37 |
+
self.arch.fea_concat = specs["ArchSpecs"]["fea_concat"]
|
38 |
+
self.arch.mlp_bias = specs["ArchSpecs"]["mlp_bias"]
|
39 |
+
|
40 |
+
self.dec = Dummy()
|
41 |
+
self.dec.c_dim = specs["DecoderSpecs"]["c_dim"]
|
42 |
+
self.dec.plane_resolution = specs["DecoderSpecs"]["plane_resolution"]
|
43 |
+
|
44 |
+
self.geo_type = specs["Train"].get("geo_type", "flex") # "dmtet" or "flex"
|
45 |
+
|
46 |
+
self.unet2 = UNetPP(in_channels=self.dec.c_dim)
|
47 |
+
|
48 |
+
mlp_chnl_s = 3 if self.arch.fea_concat else 1 # 3 for queried triplane feature concatenation
|
49 |
+
self.decoder = TetTexNet(plane_reso=self.dec.plane_resolution, fea_concat=self.arch.fea_concat)
|
50 |
+
|
51 |
+
if self.geo_type == "flex":
|
52 |
+
self.weightMlp = nn.Sequential(
|
53 |
+
nn.Linear(mlp_chnl_s * 32 * 8, 512),
|
54 |
+
nn.SiLU(),
|
55 |
+
nn.Linear(512, 21))
|
56 |
+
|
57 |
+
self.sdfMlp = SdfMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
58 |
+
self.rgbMlp = RgbMlp(mlp_chnl_s * 32, 512, bias=self.arch.mlp_bias)
|
59 |
+
# self.renderer = Renderer(tet_grid_size=self.tet_grid_size, camera_angle_num=self.camera_angle_num,
|
60 |
+
# scale=self.input.scale, geo_type = self.geo_type)
|
61 |
+
|
62 |
+
|
63 |
+
self.spob = True if specs['Pretrain']['mode'] is None else False # whether to add sphere
|
64 |
+
self.radius = specs['Pretrain']['radius'] # used when spob
|
65 |
+
|
66 |
+
self.denoising = True
|
67 |
+
from diffusers import DDIMScheduler
|
68 |
+
self.scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-2-1-base", subfolder="scheduler")
|
69 |
+
|
70 |
+
def decode(self, data, triplane_feature2):
|
71 |
+
if self.geo_type == "flex":
|
72 |
+
tet_verts = self.renderer.flexicubes.verts.unsqueeze(0)
|
73 |
+
tet_indices = self.renderer.flexicubes.indices
|
74 |
+
|
75 |
+
dec_verts = self.decoder(triplane_feature2, tet_verts)
|
76 |
+
out = self.sdfMlp(dec_verts)
|
77 |
+
|
78 |
+
weight = None
|
79 |
+
if self.geo_type == "flex":
|
80 |
+
grid_feat = torch.index_select(input=dec_verts, index=self.renderer.flexicubes.indices.reshape(-1),dim=1)
|
81 |
+
grid_feat = grid_feat.reshape(dec_verts.shape[0], self.renderer.flexicubes.indices.shape[0], self.renderer.flexicubes.indices.shape[1] * dec_verts.shape[-1])
|
82 |
+
weight = self.weightMlp(grid_feat)
|
83 |
+
weight = weight * 0.1
|
84 |
+
|
85 |
+
pred_sdf, deformation = out[..., 0], out[..., 1:]
|
86 |
+
if self.spob:
|
87 |
+
pred_sdf = pred_sdf + self.radius - torch.sqrt((tet_verts**2).sum(-1))
|
88 |
+
|
89 |
+
_, verts, faces = self.renderer(data, pred_sdf, deformation, tet_verts, tet_indices, weight= weight)
|
90 |
+
return verts[0].unsqueeze(0), faces[0].int()
|
91 |
+
|
92 |
+
def export_mesh(self, data, out_dir, tri_fea_2 = None):
|
93 |
+
verts = data['verts']
|
94 |
+
faces = data['faces']
|
95 |
+
|
96 |
+
dec_verts = self.decoder(tri_fea_2, verts.unsqueeze(0))
|
97 |
+
colors = self.rgbMlp(dec_verts).squeeze().detach().cpu().numpy()
|
98 |
+
# Expect predicted colors value range from [-1, 1]
|
99 |
+
colors = (colors * 0.5 + 0.5).clip(0, 1)
|
100 |
+
|
101 |
+
verts = verts[..., [0, 2, 1]]
|
102 |
+
verts[..., 0]*= -1
|
103 |
+
verts[..., 2]*= -1
|
104 |
+
verts = verts.squeeze().cpu().numpy()
|
105 |
+
faces = faces[..., [2, 1, 0]][..., [0, 2, 1]]#[..., [1, 0, 2]]
|
106 |
+
faces = faces.squeeze().cpu().numpy()#faces[..., [2, 1, 0]].squeeze().cpu().numpy()
|
107 |
+
|
108 |
+
# export the final mesh
|
109 |
+
with torch.no_grad():
|
110 |
+
mesh = trimesh.Trimesh(verts, faces, vertex_colors=colors, process=False) # important, process=True leads to seg fault...
|
111 |
+
mesh.export(f'{out_dir}.obj')
|
112 |
+
|
113 |
+
def export_mesh_wt_uv(self, ctx, data, out_dir, ind, device, res, tri_fea_2=None):
|
114 |
+
|
115 |
+
mesh_v = data['verts'].squeeze().cpu().numpy()
|
116 |
+
mesh_pos_idx = data['faces'].squeeze().cpu().numpy()
|
117 |
+
|
118 |
+
def interpolate(attr, rast, attr_idx, rast_db=None):
|
119 |
+
return dr.interpolate(attr.contiguous(), rast, attr_idx, rast_db=rast_db,
|
120 |
+
diff_attrs=None if rast_db is None else 'all')
|
121 |
+
|
122 |
+
vmapping, indices, uvs = xatlas.parametrize(mesh_v, mesh_pos_idx)
|
123 |
+
|
124 |
+
mesh_v = torch.tensor(mesh_v, dtype=torch.float32, device=device)
|
125 |
+
mesh_pos_idx = torch.tensor(mesh_pos_idx, dtype=torch.int64, device=device)
|
126 |
+
|
127 |
+
# Convert to tensors
|
128 |
+
indices_int64 = indices.astype(np.uint64, casting='same_kind').view(np.int64)
|
129 |
+
|
130 |
+
uvs = torch.tensor(uvs, dtype=torch.float32, device=mesh_v.device)
|
131 |
+
mesh_tex_idx = torch.tensor(indices_int64, dtype=torch.int64, device=mesh_v.device)
|
132 |
+
# mesh_v_tex. ture
|
133 |
+
uv_clip = uvs[None, ...] * 2.0 - 1.0
|
134 |
+
|
135 |
+
# pad to four component coordinate
|
136 |
+
uv_clip4 = torch.cat((uv_clip, torch.zeros_like(uv_clip[..., 0:1]), torch.ones_like(uv_clip[..., 0:1])), dim=-1)
|
137 |
+
|
138 |
+
# rasterize
|
139 |
+
rast, _ = dr.rasterize(ctx, uv_clip4, mesh_tex_idx.int(), res)
|
140 |
+
|
141 |
+
# Interpolate world space position
|
142 |
+
gb_pos, _ = interpolate(mesh_v[None, ...], rast, mesh_pos_idx.int())
|
143 |
+
mask = rast[..., 3:4] > 0
|
144 |
+
|
145 |
+
# return uvs, mesh_tex_idx, gb_pos, mask
|
146 |
+
gb_pos_unsqz = gb_pos.view(-1, 3)
|
147 |
+
mask_unsqz = mask.view(-1)
|
148 |
+
tex_unsqz = torch.zeros_like(gb_pos_unsqz) + 1
|
149 |
+
|
150 |
+
gb_mask_pos = gb_pos_unsqz[mask_unsqz]
|
151 |
+
|
152 |
+
gb_mask_pos = gb_mask_pos[None, ]
|
153 |
+
|
154 |
+
with torch.no_grad():
|
155 |
+
|
156 |
+
dec_verts = self.decoder(tri_fea_2, gb_mask_pos)
|
157 |
+
colors = self.rgbMlp(dec_verts).squeeze()
|
158 |
+
|
159 |
+
# Expect predicted colors value range from [-1, 1]
|
160 |
+
lo, hi = (-1, 1)
|
161 |
+
colors = (colors - lo) * (255 / (hi - lo))
|
162 |
+
colors = colors.clip(0, 255)
|
163 |
+
|
164 |
+
tex_unsqz[mask_unsqz] = colors
|
165 |
+
|
166 |
+
tex = tex_unsqz.view(res + (3,))
|
167 |
+
|
168 |
+
verts = mesh_v.squeeze().cpu().numpy()
|
169 |
+
faces = mesh_pos_idx[..., [2, 1, 0]].squeeze().cpu().numpy()
|
170 |
+
# faces = mesh_pos_idx
|
171 |
+
# faces = faces.detach().cpu().numpy()
|
172 |
+
# faces = faces[..., [2, 1, 0]]
|
173 |
+
indices = indices[..., [2, 1, 0]]
|
174 |
+
|
175 |
+
# xatlas.export(f"{out_dir}/{ind}.obj", verts[vmapping], indices, uvs)
|
176 |
+
matname = f'{out_dir}.mtl'
|
177 |
+
# matname = f'{out_dir}/{ind}.mtl'
|
178 |
+
fid = open(matname, 'w')
|
179 |
+
fid.write('newmtl material_0\n')
|
180 |
+
fid.write('Kd 1 1 1\n')
|
181 |
+
fid.write('Ka 1 1 1\n')
|
182 |
+
# fid.write('Ks 0 0 0\n')
|
183 |
+
fid.write('Ks 0.4 0.4 0.4\n')
|
184 |
+
fid.write('Ns 10\n')
|
185 |
+
fid.write('illum 2\n')
|
186 |
+
fid.write(f'map_Kd {out_dir.split("/")[-1]}.png\n')
|
187 |
+
fid.close()
|
188 |
+
|
189 |
+
fid = open(f'{out_dir}.obj', 'w')
|
190 |
+
# fid = open(f'{out_dir}/{ind}.obj', 'w')
|
191 |
+
fid.write('mtllib %s.mtl\n' % out_dir.split("/")[-1])
|
192 |
+
|
193 |
+
for pidx, p in enumerate(verts):
|
194 |
+
pp = p
|
195 |
+
fid.write('v %f %f %f\n' % (pp[0], pp[2], - pp[1]))
|
196 |
+
|
197 |
+
for pidx, p in enumerate(uvs):
|
198 |
+
pp = p
|
199 |
+
fid.write('vt %f %f\n' % (pp[0], 1 - pp[1]))
|
200 |
+
|
201 |
+
fid.write('usemtl material_0\n')
|
202 |
+
for i, f in enumerate(faces):
|
203 |
+
f1 = f + 1
|
204 |
+
f2 = indices[i] + 1
|
205 |
+
fid.write('f %d/%d %d/%d %d/%d\n' % (f1[0], f2[0], f1[1], f2[1], f1[2], f2[2]))
|
206 |
+
fid.close()
|
207 |
+
|
208 |
+
img = np.asarray(tex.data.cpu().numpy(), dtype=np.float32)
|
209 |
+
mask = np.sum(img.astype(float), axis=-1, keepdims=True)
|
210 |
+
mask = (mask <= 3.0).astype(float)
|
211 |
+
kernel = np.ones((3, 3), 'uint8')
|
212 |
+
dilate_img = cv2.dilate(img, kernel, iterations=1)
|
213 |
+
img = img * (1 - mask) + dilate_img * mask
|
214 |
+
img = img.clip(0, 255).astype(np.uint8)
|
215 |
+
|
216 |
+
cv2.imwrite(f'{out_dir}.png', img[..., [2, 1, 0]])
|
217 |
+
# cv2.imwrite(f'{out_dir}/{ind}.png', img[..., [2, 1, 0]])
|