File size: 23,141 Bytes
829e08b
 
 
 
ac14d96
829e08b
 
 
ac14d96
 
c30bc0f
ac14d96
 
829e08b
3362da1
8f1810a
ac14d96
edb4f10
829e08b
 
ac14d96
829e08b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
 
 
 
ac14d96
c30bc0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829e08b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac14d96
 
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829e08b
ac14d96
 
c30bc0f
 
 
ac14d96
 
 
c30bc0f
 
 
 
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
 
 
ac14d96
 
c30bc0f
 
 
ac14d96
 
 
c30bc0f
 
ac14d96
 
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
 
 
ac14d96
 
c30bc0f
 
 
ac14d96
 
 
6a6eb1e
 
 
 
 
 
 
c30bc0f
6a6eb1e
 
 
ac14d96
6a6eb1e
 
 
 
 
ac14d96
6a6eb1e
ac14d96
 
 
c30bc0f
6a6eb1e
 
ac14d96
6a6eb1e
ac14d96
6a6eb1e
 
c30bc0f
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac14d96
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
 
 
ac14d96
 
 
 
 
 
 
 
c30bc0f
 
 
ac14d96
 
c30bc0f
 
 
 
ac14d96
 
 
 
 
 
 
c30bc0f
ac14d96
 
c30bc0f
 
 
ac14d96
 
 
 
c30bc0f
ac14d96
 
c30bc0f
ac14d96
 
 
 
 
c30bc0f
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a6eb1e
 
 
 
ac14d96
6a6eb1e
ac14d96
6a6eb1e
ac14d96
6a6eb1e
 
ac14d96
6a6eb1e
 
 
ac14d96
 
6a6eb1e
 
 
ac14d96
 
6a6eb1e
ac14d96
 
 
 
c30bc0f
ac14d96
c30bc0f
 
 
 
 
 
ac14d96
 
 
 
 
 
 
 
6a6eb1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
ac14d96
 
c30bc0f
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
ac14d96
c30bc0f
ac14d96
 
c30bc0f
ac14d96
c30bc0f
ac14d96
 
c30bc0f
edb4f10
ac14d96
 
c30bc0f
755623e
c30bc0f
ac14d96
 
c30bc0f
 
 
 
 
 
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
c30bc0f
ac14d96
c30bc0f
ac14d96
c30bc0f
ac14d96
 
 
d9980d9
 
ac14d96
8051051
ac14d96
8051051
ac14d96
 
 
 
d9980d9
 
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
d9980d9
829e08b
ac14d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829e08b
ac14d96
d9980d9
ac14d96
829e08b
ac14d96
edb4f10
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
import os
import time
import glob
import json
import numpy as np
import trimesh
import argparse
from scipy.spatial.transform import Rotation
import PIL.Image
from PIL import Image
import math
import trimesh.transformations as tf
from trimesh.exchange.gltf import export_glb

os.environ['PYOPENGL_PLATFORM'] = 'egl'

import gradio as gr
import spaces

def parse_args():
    parser = argparse.ArgumentParser(description='Create animations for 3D models')
    
    parser.add_argument(
        '--input',
        type=str,
        default='./data/demo_glb/',
        help='Input file or directory path (default: ./data/demo_glb/)'
    )
    
    parser.add_argument(
        '--log_path',
        type=str,
        default='./results/demo',
        help='Output directory path (default: results/demo)'
    )
    
    parser.add_argument(
        '--animation_type',
        type=str,
        default='rotate',
        choices=['rotate', 'float', 'explode', 'assemble', 'pulse', 'swing'],
        help='Type of animation to apply'
    )
    
    parser.add_argument(
        '--animation_duration',
        type=float,
        default=3.0,
        help='Duration of animation in seconds'
    )
    
    parser.add_argument(
        '--fps',
        type=int,
        default=30,
        help='Frames per second for animation'
    )
    
    return parser.parse_args()

def get_input_files(input_path):
    if os.path.isfile(input_path):
        return [input_path]
    elif os.path.isdir(input_path):
        return glob.glob(os.path.join(input_path, '*'))
    else:
        raise ValueError(f"Input path {input_path} is neither a file nor a directory")

args = parse_args()

LOG_PATH = args.log_path
os.makedirs(LOG_PATH, exist_ok=True)

print(f"Output directory: {LOG_PATH}")

def normalize_mesh(mesh):
    """Normalize mesh to fit in a unit cube centered at origin"""
    if isinstance(mesh, trimesh.Scene):
        # Scene ๊ฐ์ฒด ์ฒ˜๋ฆฌ
        # ์”ฌ์—์„œ ๋ชจ๋“  ๋ฉ”์‹œ ์ถ”์ถœ
        meshes = []
        for geometry in mesh.geometry.values():
            if isinstance(geometry, trimesh.Trimesh):
                meshes.append(geometry)
        
        if not meshes:
            raise ValueError("No meshes found in scene")
        
        # ๋ชจ๋“  ๋ฉ”์‹œ์˜ ์ •์ ์„ ๊ฒฐํ•ฉํ•˜์—ฌ ๊ฒฝ๊ณ„ ์ƒ์ž ๊ณ„์‚ฐ
        all_vertices = np.vstack([m.vertices for m in meshes])
        bounds = np.array([all_vertices.min(axis=0), all_vertices.max(axis=0)])
        center = (bounds[0] + bounds[1]) / 2
        scale = 1.0 / (bounds[1] - bounds[0]).max()
        
        # ๊ฐ ๋ฉ”์‹œ๋ฅผ ์ •๊ทœํ™”ํ•˜์—ฌ ์ƒˆ ์”ฌ ์ƒ์„ฑ
        normalized_scene = trimesh.Scene()
        for mesh_obj in meshes:
            normalized_mesh = mesh_obj.copy()
            normalized_mesh.vertices = (normalized_mesh.vertices - center) * scale
            normalized_scene.add_geometry(normalized_mesh)
        
        return normalized_scene, center, scale
    else:
        # ์ผ๋ฐ˜ Trimesh ๊ฐ์ฒด ์ฒ˜๋ฆฌ
        vertices = mesh.vertices
        bounds = np.array([vertices.min(axis=0), vertices.max(axis=0)])
        center = (bounds[0] + bounds[1]) / 2
        scale = 1.0 / (bounds[1] - bounds[0]).max()
        
        # ๋ณต์‚ฌ๋ณธ ์ƒ์„ฑํ•˜์—ฌ ์›๋ณธ ๋ณ€๊ฒฝ ๋ฐฉ์ง€
        normalized_mesh = mesh.copy()
        normalized_mesh.vertices = (vertices - center) * scale
        
        return normalized_mesh, center, scale

def create_rotation_animation(mesh, duration=3.0, fps=30):
    """Create a rotation animation around the Y axis"""
    num_frames = int(duration * fps)
    frames = []
    
    # Normalize the mesh for consistent animation
    mesh, original_center, original_scale = normalize_mesh(mesh)
    
    for frame_idx in range(num_frames):
        t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
        angle = t * 2 * math.pi  # Full rotation
        
        if isinstance(mesh, trimesh.Scene):
            # Scene ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ ๊ฐ ๋ฉ”์‹œ์— ํšŒ์ „ ์ ์šฉ
            frame_scene = trimesh.Scene()
            
            for node_name, transform, geometry_name in mesh.graph.nodes_geometry:
                # ๋ฉ”์‹œ๋ฅผ ๋ณต์‚ฌํ•˜๊ณ  ํšŒ์ „ ์ ์šฉ
                mesh_copy = mesh.geometry[geometry_name].copy()
                
                # ๋ฉ”์‹œ์˜ ์ค‘์‹ฌ์  ๊ณ„์‚ฐ
                center_point = mesh_copy.centroid if hasattr(mesh_copy, 'centroid') else np.zeros(3)
                
                # ํšŒ์ „ ํ–‰๋ ฌ ์ƒ์„ฑ
                rotation_matrix = tf.rotation_matrix(angle, [0, 1, 0], center_point)
                
                # ๋ณ€ํ™˜ ์ ์šฉ
                mesh_copy.apply_transform(rotation_matrix)
                
                # ์”ฌ์— ์ถ”๊ฐ€
                frame_scene.add_geometry(mesh_copy, node_name=node_name)
            
            frames.append(frame_scene)
        else:
            # ์ผ๋ฐ˜ Trimesh ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ ์ง์ ‘ ํšŒ์ „ ์ ์šฉ
            animated_mesh = mesh.copy()
            rotation_matrix = tf.rotation_matrix(angle, [0, 1, 0])
            animated_mesh.apply_transform(rotation_matrix)
            frames.append(animated_mesh)
    
    return frames

def create_float_animation(mesh, duration=3.0, fps=30, amplitude=0.2):
    """Create a floating animation where the mesh moves up and down"""
    num_frames = int(duration * fps)
    frames = []
    
    # Normalize the mesh for consistent animation
    mesh, original_center, original_scale = normalize_mesh(mesh)
    
    for frame_idx in range(num_frames):
        t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
        y_offset = amplitude * math.sin(2 * math.pi * t)
        
        if isinstance(mesh, trimesh.Scene):
            # Scene ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ
            frame_scene = trimesh.Scene()
            
            for node_name, transform, geometry_name in mesh.graph.nodes_geometry:
                # ๋ฉ”์‹œ๋ฅผ ๋ณต์‚ฌ
                mesh_copy = mesh.geometry[geometry_name].copy()
                
                # ๋ณ€ํ™˜ ์ ์šฉ
                translation_matrix = tf.translation_matrix([0, y_offset, 0])
                mesh_copy.apply_transform(translation_matrix)
                
                # ์”ฌ์— ์ถ”๊ฐ€
                frame_scene.add_geometry(mesh_copy, node_name=node_name)
            
            frames.append(frame_scene)
        else:
            # ์ผ๋ฐ˜ Trimesh ๊ฐ์ฒด์ธ ๊ฒฝ์šฐ
            animated_mesh = mesh.copy()
            translation_matrix = tf.translation_matrix([0, y_offset, 0])
            animated_mesh.apply_transform(translation_matrix)
            frames.append(animated_mesh)
    
    return frames

def create_explode_animation(mesh, duration=3.0, fps=30):
    """Create an explode animation where parts of the mesh move outward"""
    num_frames = int(duration * fps)
    frames = []
    
    # Normalize the mesh for consistent animation
    mesh, original_center, original_scale = normalize_mesh(mesh)
    
    # ์”ฌ์ธ ๊ฒฝ์šฐ ๋ถ€๋ถ„๋ณ„ ์ฒ˜๋ฆฌ
    if isinstance(mesh, trimesh.Scene):
        for frame_idx in range(num_frames):
            t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
            
            # ์ƒˆ ์”ฌ ์ƒ์„ฑ
            frame_scene = trimesh.Scene()
            
            # ๊ฐ ๋…ธ๋“œ๋ณ„ ํญ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์ ์šฉ
            for node_name, transform, geometry_name in mesh.graph.nodes_geometry:
                mesh_copy = mesh.geometry[geometry_name].copy()
                
                # ๋…ธ๋“œ์˜ ์ค‘์‹ฌ์  ๊ณ„์‚ฐ
                center_point = mesh_copy.centroid if hasattr(mesh_copy, 'centroid') else np.zeros(3)
                
                # ๋ฐฉํ–ฅ ๋ฒกํ„ฐ (์›์ ์—์„œ ๊ฐ์ฒด ์ค‘์‹ฌ๊นŒ์ง€)
                direction = center_point
                if np.linalg.norm(direction) < 1e-10:
                    # ์ค‘์‹ฌ์ ์ด ์›์ ๊ณผ ๋„ˆ๋ฌด ๊ฐ€๊นŒ์šฐ๋ฉด ๋žœ๋ค ๋ฐฉํ–ฅ ์„ ํƒ
                    direction = np.random.rand(3) - 0.5
                
                direction = direction / np.linalg.norm(direction)
                
                # ํญ๋ฐœ ์ด๋™ ์ ์šฉ
                translation = direction * t * 0.5  # ํญ๋ฐœ ๊ฐ•๋„ ์กฐ์ ˆ
                translation_matrix = tf.translation_matrix(translation)
                mesh_copy.apply_transform(translation_matrix)
                
                # ์”ฌ์— ์ถ”๊ฐ€
                frame_scene.add_geometry(mesh_copy, node_name=f"{node_name}_{frame_idx}")
            
            frames.append(frame_scene)
    else:
        # ๋ฉ”์‹œ๋ฅผ ์—ฌ๋Ÿฌ ๋ถ€๋ถ„์œผ๋กœ ๋ถ„ํ• 
        try:
            components = mesh.split(only_watertight=False)
            if len(components) <= 1:
                # ์ปดํฌ๋„ŒํŠธ๊ฐ€ ํ•˜๋‚˜๋ฟ์ด๋ฉด ์ •์  ๊ธฐ๋ฐ˜ ํญ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์‚ฌ์šฉ
                raise ValueError("Mesh cannot be split into components")
        except:
            # ๋ถ„ํ• ์ด ์‹คํŒจํ•˜๋ฉด ์ •์  ๊ธฐ๋ฐ˜ ํญ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์‚ฌ์šฉ
            for frame_idx in range(num_frames):
                t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
                
                # ๋ฉ”์‹œ ๋ณต์‚ฌ
                animated_mesh = mesh.copy()
                vertices = animated_mesh.vertices.copy()
                
                # ๊ฐ ์ •์ ์„ ์ค‘์‹ฌ์—์„œ ๋ฐ”๊นฅ์ชฝ์œผ๋กœ ์ด๋™
                directions = vertices.copy()
                norms = np.linalg.norm(directions, axis=1, keepdims=True)
                mask = norms > 1e-10
                directions[mask] = directions[mask] / norms[mask]
                directions[~mask] = np.random.rand(np.sum(~mask), 3) - 0.5
                
                # ํญ๋ฐœ ๊ณ„์ˆ˜ ์ ์šฉ
                vertices += directions * t * 0.3
                animated_mesh.vertices = vertices
                
                frames.append(animated_mesh)
        else:
            # ์ปดํฌ๋„ŒํŠธ ๊ธฐ๋ฐ˜ ํญ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜
            for frame_idx in range(num_frames):
                t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
                
                # ์ƒˆ ์”ฌ ์ƒ์„ฑ
                scene = trimesh.Scene()
                
                # ๊ฐ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ค‘์‹ฌ์—์„œ ๋ฐ”๊นฅ์ชฝ์œผ๋กœ ์ด๋™
                for i, component in enumerate(components):
                    # ์ปดํฌ๋„ŒํŠธ ๋ณต์‚ฌ
                    animated_component = component.copy()
                    
                    # ์ปดํฌ๋„ŒํŠธ ์ค‘์‹ฌ์ ์—์„œ ๋ฐฉํ–ฅ ๊ณ„์‚ฐ
                    direction = animated_component.centroid
                    if np.linalg.norm(direction) < 1e-10:
                        # ์ค‘์‹ฌ์ ์ด ์›์ ๊ณผ ๋„ˆ๋ฌด ๊ฐ€๊นŒ์šฐ๋ฉด ๋žœ๋ค ๋ฐฉํ–ฅ ์„ ํƒ
                        direction = np.random.rand(3) - 0.5
                    
                    direction = direction / np.linalg.norm(direction)
                    
                    # ํญ๋ฐœ ์ด๋™ ์ ์šฉ
                    translation = direction * t * 0.5
                    translation_matrix = tf.translation_matrix(translation)
                    animated_component.apply_transform(translation_matrix)
                    
                    # ์”ฌ์— ์ถ”๊ฐ€
                    scene.add_geometry(animated_component, node_name=f"component_{i}")
                
                # ์”ฌ์„ ๋‹จ์ผ ๋ฉ”์‹œ๋กœ ๋ณ€ํ™˜ (๊ทผ์‚ฌ์น˜)
                animated_mesh = trimesh.util.concatenate(scene.dump())
                frames.append(animated_mesh)
    
    return frames

def create_assemble_animation(mesh, duration=3.0, fps=30):
    """Create an assembly animation (reverse of explode)"""
    # Get explode animation and reverse it
    explode_frames = create_explode_animation(mesh, duration, fps)
    return list(reversed(explode_frames))

def create_pulse_animation(mesh, duration=3.0, fps=30, min_scale=0.8, max_scale=1.2):
    """Create a pulsing animation where the mesh scales up and down"""
    num_frames = int(duration * fps)
    frames = []
    
    # Normalize the mesh for consistent animation
    mesh, original_center, original_scale = normalize_mesh(mesh)
    
    for frame_idx in range(num_frames):
        t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
        
        # Create a copy of the mesh to animate
        animated_mesh = mesh.copy()
        
        # Apply pulsing motion (sinusoidal scale)
        scale_factor = min_scale + (max_scale - min_scale) * (0.5 + 0.5 * math.sin(2 * math.pi * t))
        scale_matrix = tf.scale_matrix(scale_factor)
        animated_mesh.apply_transform(scale_matrix)
        
        # Add to frames
        frames.append(animated_mesh)
    
    return frames

def create_swing_animation(mesh, duration=3.0, fps=30, max_angle=math.pi/6):
    """Create a swinging animation where the mesh rotates back and forth"""
    num_frames = int(duration * fps)
    frames = []
    
    # Normalize the mesh for consistent animation
    mesh, original_center, original_scale = normalize_mesh(mesh)
    
    for frame_idx in range(num_frames):
        t = frame_idx / (num_frames - 1)  # Normalized time [0, 1]
        
        # Create a copy of the mesh to animate
        animated_mesh = mesh.copy()
        
        # Apply swinging motion (sinusoidal rotation)
        angle = max_angle * math.sin(2 * math.pi * t)
        rotation_matrix = tf.rotation_matrix(angle, [0, 1, 0])
        animated_mesh.apply_transform(rotation_matrix)
        
        # Add to frames
        frames.append(animated_mesh)
    
    return frames

def generate_gif_from_frames(frames, output_path, fps=30, resolution=(640, 480), background_color=(255, 255, 255, 255)):
    """Generate a GIF from animation frames"""
    gif_frames = []
    
    for frame in frames:
        # Create a scene with the frame
        if not isinstance(frame, trimesh.Scene):
            scene = trimesh.Scene(frame)
        else:
            scene = frame
        
        # ์ž๋™ ์นด๋ฉ”๋ผ ์„ค์ • (์ „์ฒด ์žฅ๋ฉด์ด ๋ณด์ด๋„๋ก)
        try:
            scene.camera
        except:
            # ๊ธฐ๋ณธ ์นด๋ฉ”๋ผ๊ฐ€ ์—†์œผ๋ฉด ์ƒ์„ฑ
            scene.set_camera()
        
        # ๋ชจ๋“  ๊ฐ์ฒด๊ฐ€ ๋ณด์ด๋„๋ก ์นด๋ฉ”๋ผ ์œ„์น˜ ์กฐ์ •
        scene.camera_transform = scene.camera_transform

        # Render the frame
        try:
            rendered_img = scene.save_image(resolution=resolution, background=background_color)
            pil_img = Image.open(rendered_img)
            gif_frames.append(pil_img)
        except Exception as e:
            print(f"Error rendering frame: {str(e)}")
            # ๋ Œ๋”๋ง ์‹คํŒจ ์‹œ ๋นˆ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
            gif_frames.append(Image.new('RGB', resolution, (255, 255, 255)))
    
    # Save as GIF
    if gif_frames:
        gif_frames[0].save(
            output_path,
            save_all=True,
            append_images=gif_frames[1:],
            optimize=False,
            duration=int(1000 / fps),
            loop=0
        )
        return output_path
    else:
        return None

def create_animation_mesh(input_mesh_path, animation_type='rotate', duration=3.0, fps=30):
    """Create animation from input mesh based on animation type"""
    # Load the mesh
    try:
        # ๋จผ์ € Scene์œผ๋กœ ๋กœ๋“œ ์‹œ๋„
        loaded_obj = trimesh.load(input_mesh_path)
        
        # Scene์ธ ๊ฒฝ์šฐ ๋‹จ์ผ ๋ฉ”์‹œ๋กœ ๋ณ€ํ™˜ ์‹œ๋„
        if isinstance(loaded_obj, trimesh.Scene):
            print("Loaded a scene, extracting meshes...")
            # ์”ฌ์—์„œ ๋ชจ๋“  ๋ฉ”์‹œ ์ถ”์ถœ
            meshes = []
            for geometry in loaded_obj.geometry.values():
                if isinstance(geometry, trimesh.Trimesh):
                    meshes.append(geometry)
            
            if not meshes:
                print("No meshes found in scene")
                return None, None
                
            # ๋ชจ๋“  ๋ฉ”์‹œ๋ฅผ ํ•˜๋‚˜๋กœ ๊ฒฐํ•ฉ
            mesh = trimesh.util.concatenate(meshes)
        elif isinstance(loaded_obj, trimesh.Trimesh):
            mesh = loaded_obj
        else:
            print(f"Unsupported object type: {type(loaded_obj)}")
            return None, None
            
    except Exception as e:
        print(f"Error loading mesh: {str(e)}")
        return None, None
    
    # Generate animation frames based on animation type
    if animation_type == 'rotate':
        frames = create_rotation_animation(mesh, duration, fps)
    elif animation_type == 'float':
        frames = create_float_animation(mesh, duration, fps)
    elif animation_type == 'explode':
        frames = create_explode_animation(mesh, duration, fps)
    elif animation_type == 'assemble':
        frames = create_assemble_animation(mesh, duration, fps)
    elif animation_type == 'pulse':
        frames = create_pulse_animation(mesh, duration, fps)
    elif animation_type == 'swing':
        frames = create_swing_animation(mesh, duration, fps)
    else:
        print(f"Unknown animation type: {animation_type}")
        return None, None
    
    base_filename = os.path.basename(input_mesh_path).rsplit('.', 1)[0]
    
    # Save animated mesh as GLB
    try:
        animated_glb_path = os.path.join(LOG_PATH, f'animated_{base_filename}.glb')
        
        # For GLB output, we'll use the first frame for now
        # In a production environment, you'd want to use proper animation keyframes
        if frames and len(frames) > 0:
            # First frame for static GLB
            first_frame = frames[0]
            # Export as GLB
            scene = trimesh.Scene(first_frame)
            scene.export(animated_glb_path)
        else:
            return None, None
    except Exception as e:
        print(f"Error exporting GLB: {str(e)}")
        animated_glb_path = None
    
    # Create GIF for preview
    try:
        animated_gif_path = os.path.join(LOG_PATH, f'animated_{base_filename}.gif')
        generate_gif_from_frames(frames, animated_gif_path, fps)
    except Exception as e:
        print(f"Error creating GIF: {str(e)}")
        animated_gif_path = None
    
    return animated_glb_path, animated_gif_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:
        # Create animation
        animated_glb_path, animated_gif_path = create_animation_mesh(
            input_3d,
            animation_type=animation_type,
            duration=animation_duration,
            fps=fps
        )
        
        if not animated_glb_path or not animated_gif_path:
            return "Error creating animation", None
        
        # Create a simple JSON metadata file
        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_{os.path.basename(input_3d).rsplit(".", 1)[0]}.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

_HEADER_ = '''
<h2><b>GLB ์• ๋‹ˆ๋ฉ”์ด์…˜ ์ƒ์„ฑ๊ธฐ - 3D ๋ชจ๋ธ ์›€์ง์ž„ ํšจ๊ณผ</b></h2>

์ด ๋ฐ๋ชจ๋ฅผ ํ†ตํ•ด ์ •์ ์ธ 3D ๋ชจ๋ธ(GLB ํŒŒ์ผ)์— ๋‹ค์–‘ํ•œ ์• ๋‹ˆ๋ฉ”์ด์…˜ ํšจ๊ณผ๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

โ—๏ธโ—๏ธโ—๏ธ**์ค‘์š”์‚ฌํ•ญ:**
- ์ด ๋ฐ๋ชจ๋Š” ์—…๋กœ๋“œ๋œ GLB ํŒŒ์ผ์— ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ์ ์šฉํ•ฉ๋‹ˆ๋‹ค.
- ๋‹ค์–‘ํ•œ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์Šคํƒ€์ผ ์ค‘์—์„œ ์„ ํƒํ•˜์„ธ์š”: ํšŒ์ „, ๋ถ€์œ , ํญ๋ฐœ, ์กฐ๋ฆฝ, ํŽ„์Šค, ์Šค์œ™.
- ๊ฒฐ๊ณผ๋Š” ์• ๋‹ˆ๋ฉ”์ด์…˜๋œ GLB ํŒŒ์ผ๊ณผ ๋ฏธ๋ฆฌ๋ณด๊ธฐ์šฉ GIF ํŒŒ์ผ๋กœ ์ œ๊ณต๋ฉ๋‹ˆ๋‹ค.
'''

_INFO_ = r"""
### ์• ๋‹ˆ๋ฉ”์ด์…˜ ์œ ํ˜• ์„ค๋ช…
- **ํšŒ์ „(rotate)**: ๋ชจ๋ธ์ด Y์ถ•์„ ์ค‘์‹ฌ์œผ๋กœ ํšŒ์ „ํ•ฉ๋‹ˆ๋‹ค.
- **๋ถ€์œ (float)**: ๋ชจ๋ธ์ด ์œ„์•„๋ž˜๋กœ ๋ถ€๋“œ๋Ÿฝ๊ฒŒ ๋– ๋‹ค๋‹™๋‹ˆ๋‹ค.
- **ํญ๋ฐœ(explode)**: ๋ชจ๋ธ์˜ ๊ฐ ๋ถ€๋ถ„์ด ์ค‘์‹ฌ์—์„œ ๋ฐ”๊นฅ์ชฝ์œผ๋กœ ํผ์ ธ๋‚˜๊ฐ‘๋‹ˆ๋‹ค.
- **์กฐ๋ฆฝ(assemble)**: ํญ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜์˜ ๋ฐ˜๋Œ€ - ๋ถ€ํ’ˆ๋“ค์ด ํ•จ๊ป˜ ๋ชจ์ž…๋‹ˆ๋‹ค.
- **ํŽ„์Šค(pulse)**: ๋ชจ๋ธ์ด ํฌ๊ธฐ๊ฐ€ ์ปค์กŒ๋‹ค ์ž‘์•„์กŒ๋‹ค๋ฅผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
- **์Šค์œ™(swing)**: ๋ชจ๋ธ์ด ์ขŒ์šฐ๋กœ ๋ถ€๋“œ๋Ÿฝ๊ฒŒ ํ”๋“ค๋ฆฝ๋‹ˆ๋‹ค.

### ํŒ
- ์• ๋‹ˆ๋ฉ”์ด์…˜ ๊ธธ์ด์™€ FPS๋ฅผ ์กฐ์ ˆํ•˜์—ฌ ์›€์ง์ž„์˜ ์†๋„์™€ ๋ถ€๋“œ๋Ÿฌ์›€์„ ์กฐ์ ˆํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
- ๋ณต์žกํ•œ ๋ชจ๋ธ์€ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด ๋” ์˜ค๋ž˜ ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
- GIF ๋ฏธ๋ฆฌ๋ณด๊ธฐ๋Š” ๋น ๋ฅธ ์ฐธ์กฐ์šฉ์ด๋ฉฐ, ๊ณ ํ’ˆ์งˆ ๊ฒฐ๊ณผ๋ฅผ ์œ„ํ•ด์„œ๋Š” ์• ๋‹ˆ๋ฉ”์ด์…˜๋œ GLB ํŒŒ์ผ์„ ๋‹ค์šด๋กœ๋“œํ•˜์„ธ์š”.
"""

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ •
def create_gradio_interface():
    with gr.Blocks(title="GLB ์• ๋‹ˆ๋ฉ”์ด์…˜ ์ƒ์„ฑ๊ธฐ") as demo:
        # ์ œ๋ชฉ ์„น์…˜
        gr.Markdown(_HEADER_)
        
        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(_INFO_)
        
        # ๋ฒ„ํŠผ ๋™์ž‘ ์„ค์ •
        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:
            example = gr.Examples(
                examples=example_files,
                inputs=[input_3d],
                examples_per_page=10,
            )
    
    return demo

# ๋ฉ”์ธ ์‹คํ–‰ ๋ถ€๋ถ„
if __name__ == "__main__":
    demo = create_gradio_interface()
    demo.launch(share=True, server_name="0.0.0.0", server_port=7860)