File size: 9,202 Bytes
f3bc318
 
4763a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3bc318
 
 
4763a4b
f3bc318
 
 
 
 
 
 
 
 
4763a4b
f3bc318
 
 
 
 
 
 
4763a4b
f3bc318
 
 
 
 
4763a4b
 
 
f3bc318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4763a4b
 
f3bc318
4763a4b
 
 
 
 
 
f3bc318
 
4763a4b
f3bc318
4763a4b
 
 
f3bc318
 
 
 
 
4763a4b
f3bc318
 
4763a4b
f3bc318
 
 
 
 
 
 
 
 
 
 
 
 
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


# import os
# import subprocess

# # Убираем pyenv, если вдруг остался .python-version
# os.environ.pop("PYENV_VERSION", None)

# # Установка зависимостей
# subprocess.run(["pip", "install", "torch", "wheel"], check=True)
# subprocess.run([
#     "pip", "install", "--no-build-isolation", 
#     "diso@git+https://github.com/SarahWeiii/diso.git"
# ], check=True)

# # Импорты
# import gradio as gr
# import uuid
# import torch
# import zipfile
# import requests
# import traceback
# import trimesh
# from trimesh.exchange.gltf import export_glb 

# print("Trimesh version:", trimesh.__version__)


# from inference_triposg import run_triposg
# from triposg.pipelines.pipeline_triposg import TripoSGPipeline
# from briarmbg import BriaRMBG

# # Настройки устройства
# device = "cuda" if torch.cuda.is_available() else "cpu"
# dtype = torch.float16 if device == "cuda" else torch.float32

# # Загрузка весов
# weights_dir = "pretrained_weights"
# triposg_path = os.path.join(weights_dir, "TripoSG")
# rmbg_path = os.path.join(weights_dir, "RMBG-1.4")

# if not (os.path.exists(triposg_path) and os.path.exists(rmbg_path)):
#     print("📦 Downloading pretrained weights...")
#     url = "https://huggingface.co/datasets/endlesstools/pretrained-assets/resolve/main/pretrained_models.zip"
#     zip_path = "pretrained_models.zip"

#     with requests.get(url, stream=True) as r:
#         r.raise_for_status()
#         with open(zip_path, "wb") as f:
#             for chunk in r.iter_content(chunk_size=8192):
#                 f.write(chunk)

#     print("📦 Extracting weights...")
#     with zipfile.ZipFile(zip_path, "r") as zip_ref:
#         zip_ref.extractall(weights_dir)

#     os.remove(zip_path)
#     print("✅ Weights ready.")

# # Загрузка моделей
# pipe = TripoSGPipeline.from_pretrained(triposg_path).to(device, dtype)
# rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
# rmbg_net.eval()

# # Генерация .glb
# # def generate(image_path):
# def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
#     print("[API CALL] image_path received:", image_path)
#     print("[API CALL] File exists:", os.path.exists(image_path))

#     temp_id = str(uuid.uuid4())
#     output_path = f"/tmp/{temp_id}.glb"

#     print("[DEBUG] Generating mesh from:", image_path)

#     try:
#         # mesh = run_triposg(
#         #     pipe=pipe,
#         #     image_input=image_path,
#         #     rmbg_net=rmbg_net,
#         #     seed=42,
#         #     num_inference_steps=25,
#         #     guidance_scale=5.0,
#         #     faces=-1,
#         # )
#         mesh = run_triposg(
#             pipe=pipe,
#             image_input=image_path,
#             rmbg_net=rmbg_net,
#             seed=42,
#             num_inference_steps=int(num_steps),
#             guidance_scale=float(guidance_scale),
#             faces=int(face_number),
#         )

#         # if mesh is None:
#         #     raise ValueError("Mesh generation failed")

#         # mesh.export(output_path)
#         # print(f"[DEBUG] Mesh saved to {output_path}")

#         # return output_path if os.path.exists(output_path) else "Error: output file not found"

        
#         # if mesh is None:
#         #     raise ValueError("Mesh generation failed")

#         # # Убираем визуал, метаданные, обертки
#         # mesh.visual = None
#         # mesh.metadata.clear()
#         # mesh.name = "endless_tools"

#         # # Экспорт только геометрии
#         # glb_data = mesh.export(file_type="glb")
#         # with open(output_path, "wb") as f:
#         #     f.write(glb_data)

#         # print(f"[DEBUG] Mesh saved to {output_path}")

#         # return output_path if os.path.exists(output_path) else "Error: output file not found"

#         if mesh is None:
#             raise ValueError("Mesh generation returned None")

#         # Очистка визуала, метаданных и имени
#         mesh.visual = None
#         mesh.metadata.clear()
#         mesh.name = "geometry_0"

#         # glb_data = mesh.export(file_type="glb")
#         glb_data = export_glb(mesh)
#         with open(output_path, "wb") as f:
#             f.write(glb_data)

#         # Экспорт .glb вручную (иначе Trimesh добавляет сцену)
#         # glb_data = mesh.export(file_type="glb")
#         # with open(output_path, "wb") as f:
#         #     f.write(glb_data)
        

#         print(f"[DEBUG] Mesh saved to {output_path}")
#         return output_path if os.path.exists(output_path) else None
#     # except Exception as e:
#     #     print("[ERROR]", e)
#     #     return f"Error: {e}"
#     except Exception as e:
#         # import traceback
#         print("[ERROR]", e)
#         traceback.print_exc()  # ← выведет полную трассировку в логи
#         return f"Error: {e}"

# # Интерфейс Gradio
# demo = gr.Interface(
#     fn=generate,
#     inputs=gr.Image(type="filepath", label="Upload image"),
#     outputs=gr.File(label="Download .glb"),
#     title="TripoSG Image to 3D",
#     description="Upload an image to generate a 3D model (.glb)",
# )

# # Запуск
# demo.launch()













import os
import subprocess

# Убираем pyenv
os.environ.pop("PYENV_VERSION", None)

# Установка зависимостей
subprocess.run(["pip", "install", "torch", "wheel"], check=True)
subprocess.run([
    "pip", "install", "--no-build-isolation", 
    "diso@git+https://github.com/SarahWeiii/diso.git"
], check=True)

# Импорты (перенесены после установки зависимостей)
import gradio as gr
import uuid
import torch
import zipfile
import requests
import traceback
import trimesh
from trimesh.exchange.gltf import export_glb

from inference_triposg import run_triposg
from triposg.pipelines.pipeline_triposg import TripoSGPipeline
from briarmbg import BriaRMBG


print("Trimesh version:", trimesh.__version__)

# Настройки устройства
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.float32

# Загрузка весов
weights_dir = "pretrained_weights"
triposg_path = os.path.join(weights_dir, "TripoSG")
rmbg_path = os.path.join(weights_dir, "RMBG-1.4")

if not (os.path.exists(triposg_path) and os.path.exists(rmbg_path)):
    print("📦 Downloading pretrained weights...")
    url = "https://huggingface.co/datasets/endlesstools/pretrained-assets/resolve/main/pretrained_models.zip"
    zip_path = "pretrained_models.zip"

    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(zip_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)

    print("📦 Extracting weights...")
    with zipfile.ZipFile(zip_path, "r") as zip_ref:
        zip_ref.extractall(weights_dir)

    os.remove(zip_path)
    print("✅ Weights ready.")

# Загрузка моделей
pipe = TripoSGPipeline.from_pretrained(triposg_path).to(device, dtype)
rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
rmbg_net.eval()

# Генерация .glb
def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
    print("[API CALL] image_path received:", image_path)
    print("[API CALL] File exists:", os.path.exists(image_path))

    temp_id = str(uuid.uuid4())
    output_path = f"/tmp/{temp_id}.glb"
    print("[DEBUG] Generating mesh from:", image_path)

    try:
        mesh = run_triposg(
            pipe=pipe,
            image_input=image_path,
            rmbg_net=rmbg_net,
            seed=42,
            num_inference_steps=int(num_steps),
            guidance_scale=float(guidance_scale),
            faces=int(face_number),
        )

        if mesh is None or mesh.vertices.shape[0] == 0 or mesh.faces.shape[0] == 0:
            raise ValueError("Mesh generation returned an empty mesh")

        # Безопасная очистка визуала
        if hasattr(mesh, "visual") and mesh.visual is not None:
            try:
                mesh.visual = None
            except Exception:
                print("[WARN] Failed to clear visual, skipping")

        mesh.metadata.clear()
        mesh.name = "endless_tools_mesh"

        # Экспорт .glb
        # glb_data = export_glb(mesh)
        glb_data = mesh.export(file_type='glb')
        with open(output_path, "wb") as f:
            f.write(glb_data)

        print(f"[DEBUG] Mesh saved to {output_path}")
        return output_path if os.path.exists(output_path) else None

    except Exception as e:
        print("[ERROR]", e)
        traceback.print_exc()
        return f"Error: {e}"

# Интерфейс Gradio
demo = gr.Interface(
    fn=generate,
    inputs=gr.Image(type="filepath", label="Upload image"),
    outputs=gr.File(label="Download .glb"),
    title="TripoSG Image to 3D",
    description="Upload an image to generate a 3D model (.glb)",
)

# Запуск
demo.launch()