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|
2 |
+
import os
|
3 |
+
import spaces
|
4 |
+
from transformers import GemmaTokenizer, AutoModelForCausalLM
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
6 |
+
from threading import Thread
|
7 |
+
|
8 |
+
# Set an environment variable
|
9 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
10 |
+
|
11 |
+
|
12 |
+
DESCRIPTION = '''
|
13 |
+
<div>
|
14 |
+
<h1 style="text-align: center;">LLaMA-Mesh</h1>
|
15 |
+
<div>
|
16 |
+
<a style="display:inline-block" href="https://research.nvidia.com/labs/toronto-ai/LLaMA-Mesh/"><img src='https://img.shields.io/badge/public_website-8A2BE2'></a>
|
17 |
+
<a style="display:inline-block; margin-left: .5em" href="https://github.com/nv-tlabs/LLaMA-Mesh"><img src='https://img.shields.io/github/stars/nv-tlabs/LLaMA-Mesh?style=social'/></a>
|
18 |
+
</div>
|
19 |
+
<p>LLaMA-Mesh: Unifying 3D Mesh Generation with Language Models.</p>
|
20 |
+
<p> Notice: (1) This demo supports up to 4096 tokens due to computational limits, while our full model supports 8k tokens. This limitation may result in incomplete generated meshes. To experience the full 8k token context, please run our model locally.</p>
|
21 |
+
<p>(2) We only support generating a single mesh per dialog round. To generate another mesh, click the "clear" button and start a new dialog.</p>
|
22 |
+
<p>(3) If the LLM refuses to generate a 3D mesh, try adding more explicit instructions to the prompt, such as "create a 3D model of a table <strong>in OBJ format</strong>." A more effective approach is to request the mesh generation at the start of the dialog.</p>
|
23 |
+
</div>
|
24 |
+
'''
|
25 |
+
|
26 |
+
LICENSE = """
|
27 |
+
<p/>
|
28 |
+
|
29 |
+
---
|
30 |
+
Built with Meta Llama 3.1 8B
|
31 |
+
"""
|
32 |
+
|
33 |
+
PLACEHOLDER = """
|
34 |
+
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
35 |
+
<h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">LLaMA-Mesh</h1>
|
36 |
+
<p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
|
37 |
+
</div>
|
38 |
+
"""
|
39 |
+
|
40 |
+
|
41 |
+
css = """
|
42 |
+
h1 {
|
43 |
+
text-align: center;
|
44 |
+
display: block;
|
45 |
+
}
|
46 |
+
|
47 |
+
#duplicate-button {
|
48 |
+
margin: auto;
|
49 |
+
color: white;
|
50 |
+
background: #1565c0;
|
51 |
+
border-radius: 100vh;
|
52 |
+
}
|
53 |
+
"""
|
54 |
+
# Load the tokenizer and model
|
55 |
+
model_path = "Zhengyi/LLaMA-Mesh"
|
56 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
57 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto")
|
58 |
+
terminators = [
|
59 |
+
tokenizer.eos_token_id,
|
60 |
+
tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
61 |
+
]
|
62 |
+
|
63 |
+
|
64 |
+
from trimesh.exchange.gltf import export_glb
|
65 |
+
import gradio as gr
|
66 |
+
import trimesh
|
67 |
+
import numpy as np
|
68 |
+
import tempfile
|
69 |
+
def apply_gradient_color(mesh_text):
|
70 |
+
"""
|
71 |
+
Apply a gradient color to the mesh vertices based on the Y-axis and save as GLB.
|
72 |
+
Args:
|
73 |
+
mesh_text (str): The input mesh in OBJ format as a string.
|
74 |
+
Returns:
|
75 |
+
str: Path to the GLB file with gradient colors applied.
|
76 |
+
"""
|
77 |
+
# Load the mesh
|
78 |
+
temp_file = tempfile.NamedTemporaryFile(suffix=f"", delete=False).name#"temp_mesh.obj"
|
79 |
+
with open(temp_file+".obj", "w") as f:
|
80 |
+
f.write(mesh_text)
|
81 |
+
# return temp_file
|
82 |
+
mesh = trimesh.load_mesh(temp_file+".obj", file_type='obj')
|
83 |
+
|
84 |
+
# Get vertex coordinates
|
85 |
+
vertices = mesh.vertices
|
86 |
+
y_values = vertices[:, 1] # Y-axis values
|
87 |
+
|
88 |
+
# Normalize Y values to range [0, 1] for color mapping
|
89 |
+
y_normalized = (y_values - y_values.min()) / (y_values.max() - y_values.min())
|
90 |
+
|
91 |
+
# Generate colors: Map normalized Y values to RGB gradient (e.g., blue to red)
|
92 |
+
colors = np.zeros((len(vertices), 4)) # RGBA
|
93 |
+
colors[:, 0] = y_normalized # Red channel
|
94 |
+
colors[:, 2] = 1 - y_normalized # Blue channel
|
95 |
+
colors[:, 3] = 1.0 # Alpha channel (fully opaque)
|
96 |
+
|
97 |
+
# Attach colors to mesh vertices
|
98 |
+
mesh.visual.vertex_colors = colors
|
99 |
+
|
100 |
+
# Export to GLB format
|
101 |
+
glb_path = temp_file+".glb"
|
102 |
+
with open(glb_path, "wb") as f:
|
103 |
+
f.write(export_glb(mesh))
|
104 |
+
|
105 |
+
return glb_path
|
106 |
+
|
107 |
+
def visualize_mesh(mesh_text):
|
108 |
+
"""
|
109 |
+
Convert the provided 3D mesh text into a visualizable format.
|
110 |
+
This function assumes the input is in OBJ format.
|
111 |
+
"""
|
112 |
+
temp_file = "temp_mesh.obj"
|
113 |
+
with open(temp_file, "w") as f:
|
114 |
+
f.write(mesh_text)
|
115 |
+
return temp_file
|
116 |
+
|
117 |
+
@spaces.GPU(duration=180)
|
118 |
+
def chat_llama3_8b(message: str,
|
119 |
+
history: list,
|
120 |
+
temperature: float,
|
121 |
+
max_new_tokens: int
|
122 |
+
) -> str:
|
123 |
+
"""
|
124 |
+
Generate a streaming response using the llama3-8b model.
|
125 |
+
Args:
|
126 |
+
message (str): The input message.
|
127 |
+
history (list): The conversation history used by ChatInterface.
|
128 |
+
temperature (float): The temperature for generating the response.
|
129 |
+
max_new_tokens (int): The maximum number of new tokens to generate.
|
130 |
+
Returns:
|
131 |
+
str: The generated response.
|
132 |
+
"""
|
133 |
+
conversation = []
|
134 |
+
for user, assistant in history:
|
135 |
+
conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
|
136 |
+
conversation.append({"role": "user", "content": message})
|
137 |
+
|
138 |
+
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
|
139 |
+
|
140 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
141 |
+
|
142 |
+
generate_kwargs = dict(
|
143 |
+
input_ids= input_ids,
|
144 |
+
streamer=streamer,
|
145 |
+
max_new_tokens=max_new_tokens,
|
146 |
+
do_sample=True,
|
147 |
+
temperature=temperature,
|
148 |
+
eos_token_id=terminators,
|
149 |
+
)
|
150 |
+
# This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
|
151 |
+
if temperature == 0:
|
152 |
+
generate_kwargs['do_sample'] = False
|
153 |
+
|
154 |
+
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
155 |
+
t.start()
|
156 |
+
|
157 |
+
outputs = []
|
158 |
+
for text in streamer:
|
159 |
+
outputs.append(text)
|
160 |
+
#print(outputs)
|
161 |
+
yield "".join(outputs)
|
162 |
+
|
163 |
+
|
164 |
+
# Gradio block
|
165 |
+
chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
|
166 |
+
|
167 |
+
with gr.Blocks(fill_height=True, css=css) as demo:
|
168 |
+
with gr.Column():
|
169 |
+
gr.Markdown(DESCRIPTION)
|
170 |
+
# gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
|
171 |
+
with gr.Row():
|
172 |
+
with gr.Column(scale=3):
|
173 |
+
gr.ChatInterface(
|
174 |
+
fn=chat_llama3_8b,
|
175 |
+
chatbot=chatbot,
|
176 |
+
fill_height=True,
|
177 |
+
additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
|
178 |
+
additional_inputs=[
|
179 |
+
gr.Slider(minimum=0,
|
180 |
+
maximum=1,
|
181 |
+
step=0.1,
|
182 |
+
value=0.95,
|
183 |
+
label="Temperature",
|
184 |
+
render=False),
|
185 |
+
gr.Slider(minimum=128,
|
186 |
+
maximum=4096,
|
187 |
+
step=1,
|
188 |
+
value=4096,
|
189 |
+
label="Max new tokens",
|
190 |
+
render=False),
|
191 |
+
],
|
192 |
+
examples=[
|
193 |
+
['Create a 3D model of a wooden hammer'],
|
194 |
+
['Create a 3D model of a pyramid in obj format'],
|
195 |
+
['Create a 3D model of a cabinet.'],
|
196 |
+
['Create a low poly 3D model of a coffe cup'],
|
197 |
+
['Create a 3D model of a table.'],
|
198 |
+
["Create a low poly 3D model of a tree."],
|
199 |
+
['Write a python code for sorting.'],
|
200 |
+
['How to setup a human base on Mars? Give short answer.'],
|
201 |
+
['Explain theory of relativity to me like I’m 8 years old.'],
|
202 |
+
['What is 9,000 * 9,000?'],
|
203 |
+
['Create a 3D model of a soda can.'],
|
204 |
+
['Create a 3D model of a sword.'],
|
205 |
+
['Create a 3D model of a wooden barrel'],
|
206 |
+
['Create a 3D model of a chair.']
|
207 |
+
],
|
208 |
+
cache_examples=False,
|
209 |
+
)
|
210 |
+
gr.Markdown(LICENSE)
|
211 |
+
|
212 |
+
with gr.Column(scale=2):
|
213 |
+
output_model = gr.Model3D(
|
214 |
+
label="3D Mesh Visualization",
|
215 |
+
interactive=False,
|
216 |
+
)
|
217 |
+
gr.Markdown("You can copy the generated 3d objects in the left and paste in the textbox below. Put the button and you will see the visualization of the 3D mesh.")
|
218 |
+
|
219 |
+
# Add the text box for 3D mesh input and button
|
220 |
+
mesh_input = gr.Textbox(
|
221 |
+
label="3D Mesh Input",
|
222 |
+
placeholder="Paste your 3D mesh in OBJ format here...",
|
223 |
+
lines=5,
|
224 |
+
)
|
225 |
+
visualize_button = gr.Button("Visualize 3D Mesh")
|
226 |
+
|
227 |
+
# Link the button to the visualization function
|
228 |
+
visualize_button.click(
|
229 |
+
fn=apply_gradient_color,
|
230 |
+
inputs=[mesh_input],
|
231 |
+
outputs=[output_model]
|
232 |
+
)
|
233 |
+
|
234 |
+
if __name__ == "__main__":
|
235 |
+
demo.launch()
|
236 |
+
|