File size: 18,532 Bytes
a285b9c 30b09aa 61b805a ac14d96 30b09aa edb4f10 ac14d96 c30bc0f 755623e c30bc0f 30b09aa a285b9c c30bc0f 30b09aa ac14d96 a285b9c c30bc0f ac14d96 61b805a ac14d96 c30bc0f ac14d96 d9980d9 ac14d96 a285b9c 829e08b a285b9c d9980d9 a285b9c 829e08b a285b9c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 |
import os
import time
import glob
import json
import numpy as np
import trimesh
import argparse
from scipy.spatial.transform import Rotation
from PIL import Image, ImageDraw
import math
import trimesh.transformations as tf
os.environ['PYOPENGL_PLATFORM'] = 'egl'
import gradio as gr
import spaces
# κ²°κ³Ό μ μ₯ κ²½λ‘
LOG_PATH = './results/demo'
os.makedirs(LOG_PATH, exist_ok=True)
def create_simple_rotation_animation(input_glb_path, output_glb_path, num_frames=30):
"""
μλ³Έ GLB νμΌμ νμ μ λλ©μ΄μ
μ μ μ©ν μλ‘μ΄ GLB νμΌ μμ±
"""
try:
# GLB νμΌ λ‘λ
scene = trimesh.load(input_glb_path)
if isinstance(scene, trimesh.Scene):
# μ λλ©μ΄μ
μ μ© (첫 λ²μ§Έ νλ μλ§ μ¬μ©)
angle = math.pi / 4 # 45λ νμ
# μ¬μ λͺ¨λ λ©μμ νμ μ μ©
for node_name, transform, geometry_name in scene.graph.nodes_geometry:
# μλ³Έ μμΉ λ°±μ
original_transform = scene.graph[node_name][0]
# νμ λ³ν κ³μ°
rotation = tf.rotation_matrix(angle, [0, 1, 0])
# μ λ³ν = μλ³Έ λ³ν * νμ λ³ν
new_transform = np.dot(original_transform, rotation)
# λ³ν μ μ©
scene.graph[node_name] = new_transform
# νμ λ GLB μ μ₯
scene.export(output_glb_path)
print(f"Saved animated GLB to {output_glb_path}")
return output_glb_path
elif isinstance(scene, trimesh.Trimesh):
# λ¨μΌ λ©μμΈ κ²½μ°
new_scene = trimesh.Scene()
# λ©μμ νμ μ μ©
angle = math.pi / 4 # 45λ νμ
rotation = tf.rotation_matrix(angle, [0, 1, 0])
scene.apply_transform(rotation)
# νμ λ λ©μλ₯Ό μ¬μ μΆκ°
new_scene.add_geometry(scene)
# μ¬μ GLBλ‘ μ μ₯
new_scene.export(output_glb_path)
print(f"Saved animated GLB to {output_glb_path}")
return output_glb_path
else:
print(f"Unsupported format: {type(scene)}")
return None
except Exception as e:
print(f"Error creating animation: {str(e)}")
return None
def create_textual_animation_gif(output_path, model_name, animation_type, duration=3.0, fps=30):
"""ν
μ€νΈ κΈ°λ°μ κ°λ¨ν μ λλ©μ΄μ
GIF μμ± - λ λλ§ μ€ν¨ μ λ체μ©"""
try:
# κ°λ¨ν νλ μ μνμ€ μμ±
frames = []
num_frames = int(duration * fps)
if num_frames > 60: # λ무 λ§μ νλ μμ ν¨μ¨μ μ΄μ§ μμ
num_frames = 60
for i in range(num_frames):
t = i / (num_frames - 1) # 0~1 λ²μ
angle = t * 360 # μ 체 νμ
# μ μ΄λ―Έμ§ μμ±
img = Image.new('RGB', (640, 480), color=(240, 240, 240))
draw = ImageDraw.Draw(img)
# μ 보 ν
μ€νΈ
draw.text((50, 50), f"Model: {os.path.basename(model_name)}", fill=(0, 0, 0))
draw.text((50, 100), f"Animation Type: {animation_type}", fill=(0, 0, 0))
draw.text((50, 150), f"Frame: {i+1}/{num_frames}", fill=(0, 0, 0))
# μ λλ©μ΄μ
μ νμ λ°λ₯Έ μκ°μ ν¨κ³Ό
center_x, center_y = 320, 240
if animation_type == 'rotate':
# νμ νλ μ¬κ°ν
radius = 100
x = center_x + radius * math.cos(math.radians(angle))
y = center_y + radius * math.sin(math.radians(angle))
draw.rectangle((x-40, y-40, x+40, y+40), outline=(0, 0, 0), fill=(255, 0, 0))
elif animation_type == 'float':
# μμλλ‘ μμ§μ΄λ μ
offset_y = 50 * math.sin(2 * math.pi * t)
draw.ellipse((center_x-50, center_y-50+offset_y, center_x+50, center_y+50+offset_y),
outline=(0, 0, 0), fill=(0, 0, 255))
elif animation_type == 'explode' or animation_type == 'assemble':
# λ°κΉ₯μͺ½/μμͺ½μΌλ‘ μμ§μ΄λ μ¬λ¬ λν
scale = t if animation_type == 'explode' else 1 - t
for j in range(8):
angle_j = j * 45
dist = 120 * scale
x = center_x + dist * math.cos(math.radians(angle_j))
y = center_y + dist * math.sin(math.radians(angle_j))
if j % 3 == 0:
draw.rectangle((x-20, y-20, x+20, y+20), outline=(0, 0, 0), fill=(255, 0, 0))
elif j % 3 == 1:
draw.ellipse((x-20, y-20, x+20, y+20), outline=(0, 0, 0), fill=(0, 255, 0))
else:
draw.polygon([(x, y-20), (x+20, y+20), (x-20, y+20)], outline=(0, 0, 0), fill=(0, 0, 255))
elif animation_type == 'pulse':
# ν¬κΈ°κ° λ³νλ μ
scale = 0.5 + 0.5 * math.sin(2 * math.pi * t)
radius = 100 * scale
draw.ellipse((center_x-radius, center_y-radius, center_x+radius, center_y+radius),
outline=(0, 0, 0), fill=(0, 255, 0))
elif animation_type == 'swing':
# μ’μ°λ‘ μμ§μ΄λ μΌκ°ν
angle_offset = 30 * math.sin(2 * math.pi * t)
points = [
(center_x + 100 * math.cos(math.radians(angle_offset)), center_y - 80),
(center_x + 100 * math.cos(math.radians(120 + angle_offset)), center_y + 40),
(center_x + 100 * math.cos(math.radians(240 + angle_offset)), center_y + 40)
]
draw.polygon(points, outline=(0, 0, 0), fill=(255, 165, 0))
# νλ μ μΆκ°
frames.append(img)
# GIFλ‘ μ μ₯
frames[0].save(
output_path,
save_all=True,
append_images=frames[1:],
optimize=False,
duration=int(1000 / fps),
loop=0
)
print(f"Created textual animation GIF at {output_path}")
return output_path
except Exception as e:
print(f"Error creating textual animation: {str(e)}")
return None
def create_glb_with_animation(input_glb_path, animation_type, duration=3.0, fps=30):
"""
μ
λ‘λλ GLB νμΌμ μ λλ©μ΄μ
μ μ μ©ν μλ‘μ΄ GLB νμΌ μμ±
"""
try:
base_filename = os.path.basename(input_glb_path).rsplit('.', 1)[0]
output_glb_path = os.path.join(LOG_PATH, f"animated_{base_filename}.glb")
# μλ³Έ λͺ¨λΈ λ‘λ
scene = trimesh.load(input_glb_path)
print(f"Loaded GLB: {type(scene)}")
# μ λλ©μ΄μ
μ νμ λ°λΌ μ²λ¦¬
if animation_type == 'rotate':
# μκ³λ°©ν₯ 45λ νμ
angle = math.pi / 4
axis = [0, 1, 0] # YμΆ (μμ§μΆ)
elif animation_type == 'float':
# μμ§μΌλ‘ μμ§μ
angle = 0
axis = [0, 1, 0]
# YμΆ λ°©ν₯μΌλ‘ μ΄λ
if isinstance(scene, trimesh.Scene):
for node_name, transform, geometry_name in scene.graph.nodes_geometry:
# κ°λ³κ² μλ‘ μ΄λ
translation = tf.translation_matrix([0, 0.2, 0])
original_transform = scene.graph[node_name][0]
new_transform = np.dot(original_transform, translation)
scene.graph[node_name] = new_transform
elif isinstance(scene, trimesh.Trimesh):
translation = tf.translation_matrix([0, 0.2, 0])
scene.apply_transform(translation)
elif animation_type == 'explode':
# κ° λΆλΆμ μ€μ¬μμ μ½κ° λ©μ΄μ§κ²
angle = 0
axis = [0, 1, 0]
# μ€λΈμ νΈκ° μ¬λ¬ κ°μΌ κ²½μ° μ€μ¬μμ λ°κΉ₯μͺ½μΌλ‘ μ΄λ
if isinstance(scene, trimesh.Scene):
# μ¬μ μ€μ¬μ κ³μ°
all_vertices = []
for geometry_name, geometry in scene.geometry.items():
if hasattr(geometry, 'vertices') and len(geometry.vertices) > 0:
all_vertices.append(geometry.vertices)
if all_vertices:
all_points = np.vstack(all_vertices)
center = np.mean(all_points, axis=0)
for node_name, transform, geometry_name in scene.graph.nodes_geometry:
# κ° λΆλΆμ μ€μ¬μ κ³μ°
geometry = scene.geometry[geometry_name]
if hasattr(geometry, 'centroid'):
part_center = geometry.centroid
# μ€μ¬μμ κ°μ²΄ λ°©ν₯ κ³μ°
direction = part_center - center
if np.linalg.norm(direction) > 0.001:
direction = direction / np.linalg.norm(direction)
# λ°©ν₯μΌλ‘ μ΄λ
translation = tf.translation_matrix(direction * 0.2)
original_transform = scene.graph[node_name][0]
new_transform = np.dot(original_transform, translation)
scene.graph[node_name] = new_transform
elif animation_type == 'pulse':
# λͺ¨λΈμ μ½κ° ν€μ
scale_factor = 1.2
if isinstance(scene, trimesh.Scene):
# μ¬μ μ€μ¬μ κ³μ°
all_vertices = []
for geometry_name, geometry in scene.geometry.items():
if hasattr(geometry, 'vertices') and len(geometry.vertices) > 0:
all_vertices.append(geometry.vertices)
if all_vertices:
all_points = np.vstack(all_vertices)
center = np.mean(all_points, axis=0)
for node_name, transform, geometry_name in scene.graph.nodes_geometry:
# μ€μ¬ κΈ°μ€ μ€μΌμΌλ§
translate_to_center = tf.translation_matrix(-center)
scale = np.eye(4)
scale[:3, :3] *= scale_factor
translate_back = tf.translation_matrix(center)
# λ³ν μ μ©
original_transform = scene.graph[node_name][0]
new_transform = np.dot(translate_back, np.dot(scale, np.dot(translate_to_center, original_transform)))
scene.graph[node_name] = new_transform
elif isinstance(scene, trimesh.Trimesh):
# λ©μ μ€μ¬ κΈ°μ€ μ€μΌμΌλ§
center = scene.centroid
translate_to_center = tf.translation_matrix(-center)
scale = tf.scale_matrix(scale_factor)
translate_back = tf.translation_matrix(center)
scene.apply_transform(np.dot(translate_back, np.dot(scale, translate_to_center)))
else:
# κΈ°λ³Έμ μΌλ‘ νμ μ μ©
angle = math.pi / 4
axis = [0, 1, 0]
# νμ μ μ© (float, explode, pulse μλ κ²½μ°)
if angle != 0:
if isinstance(scene, trimesh.Scene):
# μ¬μ λͺ¨λ λΆλΆμ νμ μ μ©
for node_name, transform, geometry_name in scene.graph.nodes_geometry:
rotation = tf.rotation_matrix(angle, axis)
original_transform = scene.graph[node_name][0]
new_transform = np.dot(original_transform, rotation)
scene.graph[node_name] = new_transform
elif isinstance(scene, trimesh.Trimesh):
# λ¨μΌ λ©μμ νμ μ μ©
rotation = tf.rotation_matrix(angle, axis)
scene.apply_transform(rotation)
# κ²°κ³Ό μ μ₯
scene.export(output_glb_path)
print(f"Saved animated GLB to {output_glb_path}")
return output_glb_path
except Exception as e:
print(f"Error creating animated GLB: {str(e)}")
# μ€λ₯ λ°μ μ μλ³Έ νμΌ λ³΅μ¬
try:
import shutil
output_path = os.path.join(LOG_PATH, f"copy_{os.path.basename(input_glb_path)}")
shutil.copy(input_glb_path, output_path)
print(f"Copied original GLB to {output_path}")
return output_path
except Exception as copy_error:
print(f"Error copying GLB: {copy_error}")
return input_glb_path # μλ³Έ κ²½λ‘ λ°ν
@spaces.GPU
def process_3d_model(input_3d, animation_type, animation_duration, fps):
"""Process a 3D model and apply animation"""
print(f"Processing: {input_3d} with animation type: {animation_type}")
try:
# 1. μ
λ‘λλ GLB νμΌμ μ€μ μ λλ©μ΄μ
μ μ©
animated_glb_path = create_glb_with_animation(
input_3d,
animation_type,
animation_duration,
fps
)
# 2. ν
μ€νΈ κΈ°λ° μ λλ©μ΄μ
GIF μμ± (λ°±μ
μ©)
base_filename = os.path.basename(input_3d).rsplit('.', 1)[0]
text_gif_path = os.path.join(LOG_PATH, f'text_animated_{base_filename}.gif')
animated_gif_path = create_textual_animation_gif(
text_gif_path,
os.path.basename(input_3d),
animation_type,
animation_duration,
fps
)
# 3. λ©νλ°μ΄ν° μμ±
metadata = {
"animation_type": animation_type,
"duration": animation_duration,
"fps": fps,
"original_model": os.path.basename(input_3d),
"created_at": time.strftime("%Y-%m-%d %H:%M:%S")
}
json_path = os.path.join(LOG_PATH, f'metadata_{base_filename}.json')
with open(json_path, 'w') as f:
json.dump(metadata, f, indent=4)
return animated_glb_path, animated_gif_path, json_path
except Exception as e:
error_msg = f"Error processing file: {str(e)}"
print(error_msg)
return error_msg, None, None
# Gradio μΈν°νμ΄μ€ μ€μ
with gr.Blocks(title="GLB μ λλ©μ΄μ
μμ±κΈ°") as demo:
# μ λͺ© μΉμ
gr.Markdown("""
<h2><b>GLB μ λλ©μ΄μ
μμ±κΈ° - 3D λͺ¨λΈ μμ§μ ν¨κ³Ό</b></h2>
μ΄ λ°λͺ¨λ₯Ό ν΅ν΄ μ μ μΈ 3D λͺ¨λΈ(GLB νμΌ)μ λ€μν μ λλ©μ΄μ
ν¨κ³Όλ₯Ό μ μ©ν μ μμ΅λλ€.
βοΈβοΈβοΈ**μ€μμ¬ν:**
- μ΄ λ°λͺ¨λ μ
λ‘λλ GLB νμΌμ μ λλ©μ΄μ
μ μ μ©ν©λλ€.
- λ€μν μ λλ©μ΄μ
μ€νμΌ μ€μμ μ ννμΈμ: νμ , λΆμ , νλ°, 쑰립, νμ€, μ€μ.
- κ²°κ³Όλ μ λλ©μ΄μ
λ GLB νμΌκ³Ό λ―Έλ¦¬λ³΄κΈ°μ© GIF νμΌλ‘ μ 곡λ©λλ€.
""")
with gr.Row():
with gr.Column():
# μ
λ ₯ μ»΄ν¬λνΈ
input_3d = gr.Model3D(label="3D λͺ¨λΈ νμΌ μ
λ‘λ (GLB ν¬λ§·)")
with gr.Row():
animation_type = gr.Dropdown(
label="μ λλ©μ΄μ
μ ν",
choices=["rotate", "float", "explode", "assemble", "pulse", "swing"],
value="rotate"
)
with gr.Row():
animation_duration = gr.Slider(
label="μ λλ©μ΄μ
κΈΈμ΄ (μ΄)",
minimum=1.0,
maximum=10.0,
value=3.0,
step=0.5
)
fps = gr.Slider(
label="μ΄λΉ νλ μ μ",
minimum=15,
maximum=60,
value=30,
step=1
)
submit_btn = gr.Button("λͺ¨λΈ μ²λ¦¬ λ° μ λλ©μ΄μ
μμ±")
with gr.Column():
# μΆλ ₯ μ»΄ν¬λνΈ
output_3d = gr.Model3D(label="μ λλ©μ΄μ
μ μ©λ 3D λͺ¨λΈ")
output_gif = gr.Image(label="μ λλ©μ΄μ
미리보기 (GIF)")
output_json = gr.File(label="λ©νλ°μ΄ν° νμΌ λ€μ΄λ‘λ")
# μ λλ©μ΄μ
μ ν μ€λͺ
gr.Markdown("""
### μ λλ©μ΄μ
μ ν μ€λͺ
- **νμ (rotate)**: λͺ¨λΈμ΄ YμΆμ μ€μ¬μΌλ‘ νμ ν©λλ€.
- **λΆμ (float)**: λͺ¨λΈμ΄ μμλλ‘ λΆλλ½κ² λ λ€λλλ€.
- **νλ°(explode)**: λͺ¨λΈμ κ° λΆλΆμ΄ μ€μ¬μμ λ°κΉ₯μͺ½μΌλ‘ νΌμ Έλκ°λλ€.
- **쑰립(assemble)**: νλ° μ λλ©μ΄μ
μ λ°λ - λΆνλ€μ΄ ν¨κ» λͺ¨μ
λλ€.
- **νμ€(pulse)**: λͺ¨λΈμ΄ ν¬κΈ°κ° 컀μ‘λ€ μμμ‘λ€λ₯Ό λ°λ³΅ν©λλ€.
- **μ€μ(swing)**: λͺ¨λΈμ΄ μ’μ°λ‘ λΆλλ½κ² νλ€λ¦½λλ€.
### ν
- μ λλ©μ΄μ
κΈΈμ΄μ FPSλ₯Ό μ‘°μ νμ¬ μμ§μμ μλμ λΆλλ¬μμ μ‘°μ ν μ μμ΅λλ€.
- 볡μ‘ν λͺ¨λΈμ μ²λ¦¬ μκ°μ΄ λ μ€λ 걸릴 μ μμ΅λλ€.
- GIF 미리보기λ λΉ λ₯Έ μ°Έμ‘°μ©μ΄λ©°, κ³ νμ§ κ²°κ³Όλ₯Ό μν΄μλ μ λλ©μ΄μ
λ GLB νμΌμ λ€μ΄λ‘λνμΈμ.
""")
# λ²νΌ λμ μ€μ
submit_btn.click(
fn=process_3d_model,
inputs=[input_3d, animation_type, animation_duration, fps],
outputs=[output_3d, output_gif, output_json]
)
# μμ μ€λΉ
example_files = [[f] for f in glob.glob('./data/demo_glb/*.glb')]
if example_files:
gr.Examples(
examples=example_files,
inputs=[input_3d],
examples_per_page=10,
)
# μ± μ€ν
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860) |