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IFFUSION_CONFIGS, diffusion_from_config
|
5 |
+
from point_e.diffusion.sampler import PointCloudSampler
|
6 |
+
from point_e.models.download import load_checkpoint
|
7 |
+
from point_e.models.configs import MODEL_CONFIGS, model_from_config
|
8 |
+
from point_e.util.plotting import plot_point_cloud
|
9 |
+
from point_e.util.pc_to_mesh import marching_cubes_mesh
|
10 |
+
|
11 |
+
import skimage.measure
|
12 |
+
|
13 |
+
from pyntcloud import PyntCloud
|
14 |
+
import matplotlib.colors
|
15 |
+
import plotly.graph_objs as go
|
16 |
+
|
17 |
+
import trimesh
|
18 |
+
|
19 |
+
import gradio as gr
|
20 |
+
|
21 |
+
|
22 |
+
state = ""
|
23 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
24 |
+
|
25 |
+
def set_state(s):
|
26 |
+
print(s)
|
27 |
+
global state
|
28 |
+
state = s
|
29 |
+
|
30 |
+
def get_state():
|
31 |
+
return state
|
32 |
+
|
33 |
+
set_state('Creating txt2mesh model...')
|
34 |
+
t2m_name = 'base40M-textvec' # 'base40M'
|
35 |
+
t2m_model = model_from_config(MODEL_CONFIGS[t2m_name], device)
|
36 |
+
t2m_model.eval()
|
37 |
+
base_diffusion_t2m = diffusion_from_config(DIFFUSION_CONFIGS[t2m_name])
|
38 |
+
|
39 |
+
set_state('Downloading txt2mesh checkpoint...')
|
40 |
+
t2m_model.load_state_dict(load_checkpoint(t2m_name, device))
|
41 |
+
|
42 |
+
|
43 |
+
def load_img2mesh_model(model_name):
|
44 |
+
set_state(f'Creating img2mesh model {model_name}...')
|
45 |
+
i2m_name = model_name
|
46 |
+
i2m_model = model_from_config(MODEL_CONFIGS[i2m_name], device)
|
47 |
+
i2m_model.eval()
|
48 |
+
base_diffusion_i2m = diffusion_from_config(DIFFUSION_CONFIGS[i2m_name])
|
49 |
+
|
50 |
+
set_state(f'Downloading img2mesh checkpoint {model_name}...')
|
51 |
+
i2m_model.load_state_dict(load_checkpoint(i2m_name, device))
|
52 |
+
|
53 |
+
return i2m_model, base_diffusion_i2m
|
54 |
+
|
55 |
+
img2mesh_model_name = 'base40M' #'base300M' #'base1B'
|
56 |
+
img2mesh_model, base_diffusion_i2m = load_img2mesh_model(img2mesh_model_name)
|
57 |
+
|
58 |
+
|
59 |
+
set_state('Creating upsample model...')
|
60 |
+
upsampler_model = model_from_config(MODEL_CONFIGS['upsample'], device)
|
61 |
+
upsampler_model.eval()
|
62 |
+
upsampler_diffusion = diffusion_from_config(DIFFUSION_CONFIGS['upsample'])
|
63 |
+
|
64 |
+
set_state('Downloading upsampler checkpoint...')
|
65 |
+
upsampler_model.load_state_dict(load_checkpoint('upsample', device))
|
66 |
+
|
67 |
+
set_state('Creating SDF model...')
|
68 |
+
sdf_name = 'sdf'
|
69 |
+
sdf_model = model_from_config(MODEL_CONFIGS[sdf_name], device)
|
70 |
+
sdf_model.eval()
|
71 |
+
|
72 |
+
set_state('Loading SDF model...')
|
73 |
+
sdf_model.load_state_dict(load_checkpoint(sdf_name, device))
|
74 |
+
|
75 |
+
set_state('')
|
76 |
+
|
77 |
+
def get_sampler(model_name, txt2obj, guidance_scale):
|
78 |
+
|
79 |
+
global img2mesh_model_name
|
80 |
+
global base_diffusion_i2m
|
81 |
+
global img2mesh_model
|
82 |
+
if model_name != img2mesh_model_name:
|
83 |
+
img2mesh_model_name = model_name
|
84 |
+
img2mesh_model, base_diffusion_i2m = load_img2mesh_model(model_name)
|
85 |
+
|
86 |
+
return PointCloudSampler(
|
87 |
+
device=device,
|
88 |
+
models=[t2m_model, upsampler_model],
|
89 |
+
diffusions=[base_diffusion_t2m if txt2obj else base_diffusion_i2m, upsampler_diffusion],
|
90 |
+
num_points=[1024, 4096 - 1024],
|
91 |
+
aux_channels=['R', 'G', 'B'],
|
92 |
+
guidance_scale=[guidance_scale, 0.0 if txt2obj else guidance_scale],
|
93 |
+
model_kwargs_key_filter=('texts', '') if txt2obj else ("*",)
|
94 |
+
)
|
95 |
+
|
96 |
+
def generate(model_name, input, guidance_scale, grid_size):
|
97 |
+
|
98 |
+
set_state('Entered generate function...')
|
99 |
+
|
100 |
+
if isinstance(input, Image.Image):
|
101 |
+
input = prepare_img(input)
|
102 |
+
|
103 |
+
# if input is a string, it's a text prompt
|
104 |
+
sampler = get_sampler(model_name, txt2obj=True if isinstance(input, str) else False, guidance_scale=guidance_scale)
|
105 |
+
|
106 |
+
# Produce a sample from the model.
|
107 |
+
set_state('Sampling...')
|
108 |
+
samples = None
|
109 |
+
kw_args = dict(texts=[input]) if isinstance(input, str) else dict(images=[input])
|
110 |
+
for x in sampler.sample_batch_progressive(batch_size=1, model_kwargs=kw_args):
|
111 |
+
samples = x
|
112 |
+
|
113 |
+
set_state('Converting to point cloud...')
|
114 |
+
pc = sampler.output_to_point_clouds(samples)[0]
|
115 |
+
|
116 |
+
set_state('Converting to mesh...')
|
117 |
+
save_ply(pc, 'output.ply', grid_size)
|
118 |
+
|
119 |
+
set_state('')
|
120 |
+
|
121 |
+
return pc_to_plot(pc), ply_to_obj('output.ply', 'output.obj'), gr.update(value='output.obj', visible=True)
|
122 |
+
|
123 |
+
def prepare_img(img):
|
124 |
+
|
125 |
+
w, h = img.size
|
126 |
+
if w > h:
|
127 |
+
img = img.crop(((w-h)/2, 0, (w+h)/2, h))
|
128 |
+
else:
|
129 |
+
img = img.crop((0, (h-w)/2, w, (h+w)/2))
|
130 |
+
|
131 |
+
# resize to 256x256
|
132 |
+
img = img.resize((256, 256))
|
133 |
+
|
134 |
+
return img
|
135 |
+
|
136 |
+
def pc_to_plot(pc):
|
137 |
+
|
138 |
+
return go.Figure(
|
139 |
+
data=[
|
140 |
+
go.Scatter3d(
|
141 |
+
x=pc.coords[:,0], y=pc.coords[:,1], z=pc.coords[:,2],
|
142 |
+
mode='markers',
|
143 |
+
marker=dict(
|
144 |
+
size=2,
|
145 |
+
color=['rgb({},{},{})'.format(r,g,b) for r,g,b in zip(pc.channels["R"], pc.channels["G"], pc.channels["B"])],
|
146 |
+
)
|
147 |
+
)
|
148 |
+
],
|
149 |
+
layout=dict(
|
150 |
+
scene=dict(xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False))
|
151 |
+
),
|
152 |
+
)
|
153 |
+
|
154 |
+
def ply_to_obj(ply_file, obj_file):
|
155 |
+
mesh = trimesh.load(ply_file)
|
156 |
+
mesh.export(obj_file)
|
157 |
+
|
158 |
+
return obj_file
|
159 |
+
|
160 |
+
def save_ply(pc, file_name, grid_size):
|
161 |
+
|
162 |
+
# Produce a mesh (with vertex colors)
|
163 |
+
mesh = marching_cubes_mesh(
|
164 |
+
pc=pc,
|
165 |
+
model=sdf_model,
|
166 |
+
batch_size=4096,
|
167 |
+
grid_size=grid_size, # increase to 128 for resolution used in evals
|
168 |
+
progress=True,
|
169 |
+
)
|
170 |
+
|
171 |
+
# Write the mesh to a PLY file to import into some other program.
|
172 |
+
with open(file_name, 'wb') as f:
|
173 |
+
mesh.write_ply(f)
|
174 |
+
|
175 |
+
|
176 |
+
with gr.Blocks() as app:
|
177 |
+
gr.Markdown("## Point-E text-to-3D Demo")
|
178 |
+
gr.Markdown("This is a demo for [Point-E: A System for Generating 3D Point Clouds from Complex Prompts](https://arxiv.org/abs/2212.08751) by OpenAI. Check out the [GitHub repo](https://github.com/openai/point-e) for more information.")
|
179 |
+
|
180 |
+
with gr.Row():
|
181 |
+
with gr.Column():
|
182 |
+
with gr.Tab("Text to 3D"):
|
183 |
+
prompt = gr.Textbox(label="Prompt", placeholder="A cactus in a pot")
|
184 |
+
btn_generate_txt2obj = gr.Button(value="Generate")
|
185 |
+
with gr.Tab("Image to 3D"):
|
186 |
+
img = gr.Image(label="Image")
|
187 |
+
btn_generate_img2obj = gr.Button(value="Generate")
|
188 |
+
with gr.Accordion("Advanced settings", open=False):
|
189 |
+
dropdown_models = gr.Dropdown(label="Model", value="base40M", choices=["base40M", "base300M", "base1B"])
|
190 |
+
guidance_scale = gr.Slider(label="Guidance scale", value=3.0, minimum=3.0, maximum=10.0, step=1.0)
|
191 |
+
grid_size = gr.Slider(label="Grid size", value=32, minimum=16, maximum=128, step=16)
|
192 |
+
|
193 |
+
state_info = state_info = gr.Textbox(label="State", show_label=False).style(container=False)
|
194 |
+
|
195 |
+
with gr.Column():
|
196 |
+
plot = gr.Plot(label="Point cloud")
|
197 |
+
# btn_pc_to_obj = gr.Button(value="Convert to OBJ", visible=False)
|
198 |
+
model_3d = gr.Model3D(value=None)
|
199 |
+
file_out = gr.File(label="Obj file", visible=False)
|
200 |
+
|
201 |
+
|
202 |
+
|
203 |
+
# inputs = [dropdown_models, prompt, img, guidance_scale, grid_size]
|
204 |
+
outputs = [plot, model_3d, file_out]
|
205 |
+
|
206 |
+
prompt.submit(generate, inputs=[dropdown_models, prompt, guidance_scale, grid_size], outputs=outputs)
|
207 |
+
btn_generate_txt2obj.click(generate, inputs=[dropdown_models, prompt, guidance_scale, grid_size], outputs=outputs)
|
208 |
+
btn_generate_img2obj.click(generate, inputs=[dropdown_models, img, guidance_scale, grid_size], outputs=outputs)
|
209 |
+
# btn_pc_to_obj.click(ply_to_obj, inputs=plot, outputs=[model_3d, file_out])
|
210 |
+
|
211 |
+
gr.HTML("""
|
212 |
+
<div style="border-top: 1px solid #303030;">
|
213 |
+
<br>
|
214 |
+
<p>Space by:<br>
|
215 |
+
<a href="https://twitter.com/hahahahohohe"><img src="https://img.shields.io/twitter/follow/hahahahohohe?label=%40anzorq&style=social" alt="Twitter Follow"></a><br>
|
216 |
+
<a href="https://github.com/qunash"><img alt="GitHub followers" src="https://img.shields.io/github/followers/qunash?style=social" alt="Github Follow"></a></p><br>
|
217 |
+
<a href="https://www.buymeacoffee.com/anzorq" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 35px !important;width: 120px !important;" ></a><br><br>
|
218 |
+
<p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.point-e_demo" alt="visitors"></p>
|
219 |
+
</div>
|
220 |
+
""")
|
221 |
+
|
222 |
+
app.load(get_state, inputs=[], outputs=state_info, every=0.5, show_progress=False)
|
223 |
+
|
224 |
+
|
225 |
+
app.queue()
|
226 |
+
# app.launch(debug=True, share=True, height=768)
|
227 |
+
app.launch(debug=True)
|