Create utils.py
Browse files
utils.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# timeforge/utils.py
|
2 |
+
|
3 |
+
import tempfile
|
4 |
+
import trimesh
|
5 |
+
from trimesh.exchange.gltf import export_glb
|
6 |
+
import numpy as np
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
def apply_gradient_color(mesh_text):
|
10 |
+
"""
|
11 |
+
Apply a gradient color to the mesh vertices and return as GLB.
|
12 |
+
Args:
|
13 |
+
mesh_text (str): The input mesh in OBJ format as a string.
|
14 |
+
Returns:
|
15 |
+
str: Path to the GLB file with gradient colors applied.
|
16 |
+
"""
|
17 |
+
# Load the mesh
|
18 |
+
temp_file = tempfile.NamedTemporaryFile(suffix=f"", delete=False).name
|
19 |
+
with open(temp_file+".obj", "w") as f:
|
20 |
+
f.write(mesh_text)
|
21 |
+
mesh = trimesh.load_mesh(temp_file+".obj", file_type='obj')
|
22 |
+
|
23 |
+
# Get vertex coordinates
|
24 |
+
vertices = mesh.vertices
|
25 |
+
y_values = vertices[:, 1] # Y-axis values
|
26 |
+
|
27 |
+
# Normalize Y values to range [0, 1] for color mapping
|
28 |
+
y_normalized = (y_values - y_values.min()) / (y_values.max() - y_values.min())
|
29 |
+
|
30 |
+
# Generate colors: Map normalized Y values to RGB gradient (e.g., blue to red)
|
31 |
+
colors = np.zeros((len(vertices), 4)) # RGBA
|
32 |
+
colors[:, 0] = y_normalized # Red channel
|
33 |
+
colors[:, 2] = 1 - y_normalized # Blue channel
|
34 |
+
colors[:, 3] = 1.0 # Alpha channel (fully opaque)
|
35 |
+
|
36 |
+
# Attach colors to mesh vertices
|
37 |
+
mesh.visual.vertex_colors = colors
|
38 |
+
|
39 |
+
# Export to GLB format
|
40 |
+
glb_path = temp_file+".glb"
|
41 |
+
with open(glb_path, "wb") as f:
|
42 |
+
f.write(export_glb(mesh))
|
43 |
+
|
44 |
+
return glb_path
|
45 |
+
|
46 |
+
def create_image_grid(images):
|
47 |
+
images = [Image.fromarray((img * 255).astype("uint8")) for img in images]
|
48 |
+
|
49 |
+
width, height = images[0].size
|
50 |
+
grid_img = Image.new("RGB", (2 * width, 2 * height))
|
51 |
+
|
52 |
+
grid_img.paste(images[0], (0, 0))
|
53 |
+
grid_img.paste(images[1], (width, 0))
|
54 |
+
grid_img.paste(images[2], (0, height))
|
55 |
+
grid_img.paste(images[3], (width, height))
|
56 |
+
|
57 |
+
return grid_img
|