Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,36 +1,124 @@
|
|
1 |
-
import io
|
2 |
-
import base64
|
3 |
import os
|
4 |
-
|
5 |
-
import
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
|
8 |
-
|
|
|
9 |
|
10 |
-
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
-
|
18 |
-
def generate():
|
19 |
try:
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
logger.info("Serving precomputed .glb file...")
|
26 |
-
with open(glb_path, "rb") as f:
|
27 |
-
mesh_data = base64.b64encode(f.read()).decode("utf-8")
|
28 |
-
|
29 |
-
logger.info("Mesh served successfully")
|
30 |
-
return jsonify({"mesh": f"data:model/gltf-binary;base64,{mesh_data}"})
|
31 |
except Exception as e:
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
|
|
35 |
if __name__ == "__main__":
|
36 |
-
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import gradio as gr
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
import trimesh
|
7 |
+
from diffusers import Zero123Pipeline
|
8 |
+
import tempfile
|
9 |
|
10 |
+
# Check if CUDA is available, otherwise use CPU
|
11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
12 |
+
print(f"Using device: {device}")
|
13 |
|
14 |
+
# Initialize the pipeline
|
15 |
+
pipe = Zero123Pipeline.from_pretrained(
|
16 |
+
"bennyguo/zero123-xl-diffusers",
|
17 |
+
torch_dtype=torch.float16 if device.type == "cuda" else torch.float32,
|
18 |
+
).to(device)
|
19 |
|
20 |
+
def image_to_3d(input_image, num_inference_steps=75, guidance_scale=3.0):
|
21 |
+
"""
|
22 |
+
Convert a single image to a 3D model
|
23 |
+
"""
|
24 |
+
# Preprocess image
|
25 |
+
if input_image is None:
|
26 |
+
return None
|
27 |
+
|
28 |
+
input_image = input_image.convert("RGB").resize((256, 256))
|
29 |
+
|
30 |
+
# Generate multiple views using Zero123
|
31 |
+
images = []
|
32 |
+
|
33 |
+
# Generate views from different angles
|
34 |
+
for elevation in [0, 30]:
|
35 |
+
for azimuth in [0, 90, 180, 270]:
|
36 |
+
print(f"Generating view: elevation={elevation}, azimuth={azimuth}")
|
37 |
+
with torch.no_grad():
|
38 |
+
image = pipe(
|
39 |
+
image=input_image,
|
40 |
+
elevation=elevation,
|
41 |
+
azimuth=azimuth,
|
42 |
+
num_inference_steps=num_inference_steps,
|
43 |
+
guidance_scale=guidance_scale,
|
44 |
+
).images[0]
|
45 |
+
images.append(np.array(image))
|
46 |
+
|
47 |
+
# Create point cloud from multiple views
|
48 |
+
# This is a simplified approach - in production you might want to use a more sophisticated method
|
49 |
+
points = []
|
50 |
+
for i, img in enumerate(images):
|
51 |
+
# Extract depth information (simplified approach)
|
52 |
+
gray = np.mean(img, axis=2)
|
53 |
+
# Sample points from the image
|
54 |
+
h, w = gray.shape
|
55 |
+
for y in range(0, h, 4):
|
56 |
+
for x in range(0, w, 4):
|
57 |
+
depth = gray[y, x] / 255.0 # Normalize depth
|
58 |
+
|
59 |
+
# Convert to 3D point based on view angle
|
60 |
+
angle_idx = i % 4
|
61 |
+
elevation = 0 if i < 4 else 30
|
62 |
+
azimuth = angle_idx * 90
|
63 |
+
|
64 |
+
# Convert to radians
|
65 |
+
elevation_rad = elevation * np.pi / 180
|
66 |
+
azimuth_rad = azimuth * np.pi / 180
|
67 |
+
|
68 |
+
# Calculate 3D position based on spherical coordinates
|
69 |
+
z = depth * np.cos(elevation_rad) * np.cos(azimuth_rad)
|
70 |
+
x = depth * np.cos(elevation_rad) * np.sin(azimuth_rad)
|
71 |
+
y = depth * np.sin(elevation_rad)
|
72 |
+
|
73 |
+
points.append([x, y, z])
|
74 |
+
|
75 |
+
# Create a point cloud
|
76 |
+
point_cloud = np.array(points)
|
77 |
+
|
78 |
+
# Save point cloud to OBJ file
|
79 |
+
with tempfile.NamedTemporaryFile(suffix='.obj', delete=False) as tmp_file:
|
80 |
+
mesh = trimesh.points.PointCloud(point_cloud)
|
81 |
+
mesh.export(tmp_file.name)
|
82 |
+
|
83 |
+
# Also export as PLY for better compatibility
|
84 |
+
ply_path = tmp_file.name.replace('.obj', '.ply')
|
85 |
+
mesh.export(ply_path)
|
86 |
+
|
87 |
+
return [tmp_file.name, ply_path]
|
88 |
|
89 |
+
def process_image(image, num_steps, guidance):
|
|
|
90 |
try:
|
91 |
+
model_paths = image_to_3d(image, num_inference_steps=num_steps, guidance_scale=guidance)
|
92 |
+
if model_paths:
|
93 |
+
return model_paths[0], model_paths[1], "3D model generated successfully!"
|
94 |
+
else:
|
95 |
+
return None, None, "Failed to process the image."
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
except Exception as e:
|
97 |
+
return None, None, f"Error: {str(e)}"
|
98 |
+
|
99 |
+
# Create Gradio interface
|
100 |
+
with gr.Blocks(title="Image to 3D Model Converter") as demo:
|
101 |
+
gr.Markdown("# Image to 3D Model Converter")
|
102 |
+
gr.Markdown("Upload an image to convert it to a 3D model that you can use in Unity or other engines.")
|
103 |
+
|
104 |
+
with gr.Row():
|
105 |
+
with gr.Column(scale=1):
|
106 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
107 |
+
num_steps = gr.Slider(minimum=20, maximum=100, value=75, step=5, label="Number of Inference Steps")
|
108 |
+
guidance = gr.Slider(minimum=1.0, maximum=7.0, value=3.0, step=0.5, label="Guidance Scale")
|
109 |
+
submit_btn = gr.Button("Convert to 3D")
|
110 |
+
|
111 |
+
with gr.Column(scale=1):
|
112 |
+
obj_file = gr.File(label="OBJ File")
|
113 |
+
ply_file = gr.File(label="PLY File")
|
114 |
+
output_message = gr.Textbox(label="Output Message")
|
115 |
+
|
116 |
+
submit_btn.click(
|
117 |
+
fn=process_image,
|
118 |
+
inputs=[input_image, num_steps, guidance],
|
119 |
+
outputs=[obj_file, ply_file, output_message]
|
120 |
+
)
|
121 |
|
122 |
+
# Launch the app
|
123 |
if __name__ == "__main__":
|
124 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|