staswrs commited on
Commit
f3bc318
·
1 Parent(s): e8dac8f

clean scene 7

Browse files
Files changed (2) hide show
  1. app.py +18 -70
  2. app_backlog.py +166 -0
app.py CHANGED
@@ -1,19 +1,5 @@
1
-
2
-
3
  import os
4
  import subprocess
5
-
6
- # Убираем pyenv, если вдруг остался .python-version
7
- os.environ.pop("PYENV_VERSION", None)
8
-
9
- # Установка зависимостей
10
- subprocess.run(["pip", "install", "torch", "wheel"], check=True)
11
- subprocess.run([
12
- "pip", "install", "--no-build-isolation",
13
- "diso@git+https://github.com/SarahWeiii/diso.git"
14
- ], check=True)
15
-
16
- # Импорты
17
  import gradio as gr
18
  import uuid
19
  import torch
@@ -21,13 +7,24 @@ import zipfile
21
  import requests
22
  import traceback
23
  import trimesh
24
- print("Trimesh version:", trimesh.__version__)
25
-
26
 
27
  from inference_triposg import run_triposg
28
  from triposg.pipelines.pipeline_triposg import TripoSGPipeline
29
  from briarmbg import BriaRMBG
30
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # Настройки устройства
32
  device = "cuda" if torch.cuda.is_available() else "cpu"
33
  dtype = torch.float16 if device == "cuda" else torch.float32
@@ -61,26 +58,15 @@ rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
61
  rmbg_net.eval()
62
 
63
  # Генерация .glb
64
- # def generate(image_path):
65
  def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
66
  print("[API CALL] image_path received:", image_path)
67
  print("[API CALL] File exists:", os.path.exists(image_path))
68
 
69
  temp_id = str(uuid.uuid4())
70
  output_path = f"/tmp/{temp_id}.glb"
71
-
72
  print("[DEBUG] Generating mesh from:", image_path)
73
 
74
  try:
75
- # mesh = run_triposg(
76
- # pipe=pipe,
77
- # image_input=image_path,
78
- # rmbg_net=rmbg_net,
79
- # seed=42,
80
- # num_inference_steps=25,
81
- # guidance_scale=5.0,
82
- # faces=-1,
83
- # )
84
  mesh = run_triposg(
85
  pipe=pipe,
86
  image_input=image_path,
@@ -91,59 +77,25 @@ def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
91
  faces=int(face_number),
92
  )
93
 
94
- # if mesh is None:
95
- # raise ValueError("Mesh generation failed")
96
-
97
- # mesh.export(output_path)
98
- # print(f"[DEBUG] Mesh saved to {output_path}")
99
-
100
- # return output_path if os.path.exists(output_path) else "Error: output file not found"
101
-
102
-
103
- # if mesh is None:
104
- # raise ValueError("Mesh generation failed")
105
-
106
- # # Убираем визуал, метаданные, обертки
107
- # mesh.visual = None
108
- # mesh.metadata.clear()
109
- # mesh.name = "endless_tools"
110
-
111
- # # Экспорт только геометрии
112
- # glb_data = mesh.export(file_type="glb")
113
- # with open(output_path, "wb") as f:
114
- # f.write(glb_data)
115
-
116
- # print(f"[DEBUG] Mesh saved to {output_path}")
117
-
118
- # return output_path if os.path.exists(output_path) else "Error: output file not found"
119
-
120
  if mesh is None:
121
  raise ValueError("Mesh generation returned None")
122
 
123
  # Очистка визуала, метаданных и имени
124
- # mesh.visual = None
125
  mesh.metadata.clear()
126
  mesh.name = "geometry_0"
127
 
128
- glb_data = mesh.export(file_type="glb")
 
129
  with open(output_path, "wb") as f:
130
  f.write(glb_data)
131
 
132
- # Экспорт .glb вручную (иначе Trimesh добавляет сцену)
133
- # glb_data = mesh.export(file_type="glb")
134
- # with open(output_path, "wb") as f:
135
- # f.write(glb_data)
136
-
137
-
138
  print(f"[DEBUG] Mesh saved to {output_path}")
139
  return output_path if os.path.exists(output_path) else None
140
- # except Exception as e:
141
- # print("[ERROR]", e)
142
- # return f"Error: {e}"
143
  except Exception as e:
144
- # import traceback
145
  print("[ERROR]", e)
146
- traceback.print_exc() # ← выведет полную трассировку в логи
147
  return f"Error: {e}"
148
 
149
  # Интерфейс Gradio
@@ -157,7 +109,3 @@ demo = gr.Interface(
157
 
158
  # Запуск
159
  demo.launch()
160
-
161
-
162
-
163
-
 
 
 
1
  import os
2
  import subprocess
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
  import uuid
5
  import torch
 
7
  import requests
8
  import traceback
9
  import trimesh
10
+ from trimesh.exchange.gltf import export_glb
 
11
 
12
  from inference_triposg import run_triposg
13
  from triposg.pipelines.pipeline_triposg import TripoSGPipeline
14
  from briarmbg import BriaRMBG
15
 
16
+ # Убираем pyenv
17
+ os.environ.pop("PYENV_VERSION", None)
18
+
19
+ # Установка зависимостей
20
+ subprocess.run(["pip", "install", "torch", "wheel"], stdout=subprocess.DEVNULL)
21
+ subprocess.run([
22
+ "pip", "install", "--no-build-isolation",
23
+ "diso@git+https://github.com/SarahWeiii/diso.git"
24
+ ], stdout=subprocess.DEVNULL)
25
+
26
+ print("Trimesh version:", trimesh.__version__)
27
+
28
  # Настройки устройства
29
  device = "cuda" if torch.cuda.is_available() else "cpu"
30
  dtype = torch.float16 if device == "cuda" else torch.float32
 
58
  rmbg_net.eval()
59
 
60
  # Генерация .glb
 
61
  def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
62
  print("[API CALL] image_path received:", image_path)
63
  print("[API CALL] File exists:", os.path.exists(image_path))
64
 
65
  temp_id = str(uuid.uuid4())
66
  output_path = f"/tmp/{temp_id}.glb"
 
67
  print("[DEBUG] Generating mesh from:", image_path)
68
 
69
  try:
 
 
 
 
 
 
 
 
 
70
  mesh = run_triposg(
71
  pipe=pipe,
72
  image_input=image_path,
 
77
  faces=int(face_number),
78
  )
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  if mesh is None:
81
  raise ValueError("Mesh generation returned None")
82
 
83
  # Очистка визуала, метаданных и имени
84
+ mesh.visual = None
85
  mesh.metadata.clear()
86
  mesh.name = "geometry_0"
87
 
88
+ # Экспорт в GLB без scene/world
89
+ glb_data = export_glb(mesh)
90
  with open(output_path, "wb") as f:
91
  f.write(glb_data)
92
 
 
 
 
 
 
 
93
  print(f"[DEBUG] Mesh saved to {output_path}")
94
  return output_path if os.path.exists(output_path) else None
95
+
 
 
96
  except Exception as e:
 
97
  print("[ERROR]", e)
98
+ traceback.print_exc()
99
  return f"Error: {e}"
100
 
101
  # Интерфейс Gradio
 
109
 
110
  # Запуск
111
  demo.launch()
 
 
 
 
app_backlog.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import subprocess
5
+
6
+ # Убираем pyenv, если вдруг остался .python-version
7
+ os.environ.pop("PYENV_VERSION", None)
8
+
9
+ # Установка зависимостей
10
+ subprocess.run(["pip", "install", "torch", "wheel"], check=True)
11
+ subprocess.run([
12
+ "pip", "install", "--no-build-isolation",
13
+ "diso@git+https://github.com/SarahWeiii/diso.git"
14
+ ], check=True)
15
+
16
+ # Импорты
17
+ import gradio as gr
18
+ import uuid
19
+ import torch
20
+ import zipfile
21
+ import requests
22
+ import traceback
23
+ import trimesh
24
+ from trimesh.exchange.gltf import export_glb
25
+
26
+ print("Trimesh version:", trimesh.__version__)
27
+
28
+
29
+ from inference_triposg import run_triposg
30
+ from triposg.pipelines.pipeline_triposg import TripoSGPipeline
31
+ from briarmbg import BriaRMBG
32
+
33
+ # Настройки устройства
34
+ device = "cuda" if torch.cuda.is_available() else "cpu"
35
+ dtype = torch.float16 if device == "cuda" else torch.float32
36
+
37
+ # Загрузка весов
38
+ weights_dir = "pretrained_weights"
39
+ triposg_path = os.path.join(weights_dir, "TripoSG")
40
+ rmbg_path = os.path.join(weights_dir, "RMBG-1.4")
41
+
42
+ if not (os.path.exists(triposg_path) and os.path.exists(rmbg_path)):
43
+ print("📦 Downloading pretrained weights...")
44
+ url = "https://huggingface.co/datasets/endlesstools/pretrained-assets/resolve/main/pretrained_models.zip"
45
+ zip_path = "pretrained_models.zip"
46
+
47
+ with requests.get(url, stream=True) as r:
48
+ r.raise_for_status()
49
+ with open(zip_path, "wb") as f:
50
+ for chunk in r.iter_content(chunk_size=8192):
51
+ f.write(chunk)
52
+
53
+ print("📦 Extracting weights...")
54
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
55
+ zip_ref.extractall(weights_dir)
56
+
57
+ os.remove(zip_path)
58
+ print("✅ Weights ready.")
59
+
60
+ # Загрузка моделей
61
+ pipe = TripoSGPipeline.from_pretrained(triposg_path).to(device, dtype)
62
+ rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
63
+ rmbg_net.eval()
64
+
65
+ # Генерация .glb
66
+ # def generate(image_path):
67
+ def generate(image_path, face_number=50000, guidance_scale=5.0, num_steps=25):
68
+ print("[API CALL] image_path received:", image_path)
69
+ print("[API CALL] File exists:", os.path.exists(image_path))
70
+
71
+ temp_id = str(uuid.uuid4())
72
+ output_path = f"/tmp/{temp_id}.glb"
73
+
74
+ print("[DEBUG] Generating mesh from:", image_path)
75
+
76
+ try:
77
+ # mesh = run_triposg(
78
+ # pipe=pipe,
79
+ # image_input=image_path,
80
+ # rmbg_net=rmbg_net,
81
+ # seed=42,
82
+ # num_inference_steps=25,
83
+ # guidance_scale=5.0,
84
+ # faces=-1,
85
+ # )
86
+ mesh = run_triposg(
87
+ pipe=pipe,
88
+ image_input=image_path,
89
+ rmbg_net=rmbg_net,
90
+ seed=42,
91
+ num_inference_steps=int(num_steps),
92
+ guidance_scale=float(guidance_scale),
93
+ faces=int(face_number),
94
+ )
95
+
96
+ # if mesh is None:
97
+ # raise ValueError("Mesh generation failed")
98
+
99
+ # mesh.export(output_path)
100
+ # print(f"[DEBUG] Mesh saved to {output_path}")
101
+
102
+ # return output_path if os.path.exists(output_path) else "Error: output file not found"
103
+
104
+
105
+ # if mesh is None:
106
+ # raise ValueError("Mesh generation failed")
107
+
108
+ # # Убираем визуал, метаданные, обертки
109
+ # mesh.visual = None
110
+ # mesh.metadata.clear()
111
+ # mesh.name = "endless_tools"
112
+
113
+ # # Экспорт только геометрии
114
+ # glb_data = mesh.export(file_type="glb")
115
+ # with open(output_path, "wb") as f:
116
+ # f.write(glb_data)
117
+
118
+ # print(f"[DEBUG] Mesh saved to {output_path}")
119
+
120
+ # return output_path if os.path.exists(output_path) else "Error: output file not found"
121
+
122
+ if mesh is None:
123
+ raise ValueError("Mesh generation returned None")
124
+
125
+ # Очистка визуала, метаданных и имени
126
+ mesh.visual = None
127
+ mesh.metadata.clear()
128
+ mesh.name = "geometry_0"
129
+
130
+ # glb_data = mesh.export(file_type="glb")
131
+ glb_data = export_glb(mesh)
132
+ with open(output_path, "wb") as f:
133
+ f.write(glb_data)
134
+
135
+ # Экспорт .glb вручную (иначе Trimesh добавляет сцену)
136
+ # glb_data = mesh.export(file_type="glb")
137
+ # with open(output_path, "wb") as f:
138
+ # f.write(glb_data)
139
+
140
+
141
+ print(f"[DEBUG] Mesh saved to {output_path}")
142
+ return output_path if os.path.exists(output_path) else None
143
+ # except Exception as e:
144
+ # print("[ERROR]", e)
145
+ # return f"Error: {e}"
146
+ except Exception as e:
147
+ # import traceback
148
+ print("[ERROR]", e)
149
+ traceback.print_exc() # ← выведет полную трассировку в логи
150
+ return f"Error: {e}"
151
+
152
+ # Интерфейс Gradio
153
+ demo = gr.Interface(
154
+ fn=generate,
155
+ inputs=gr.Image(type="filepath", label="Upload image"),
156
+ outputs=gr.File(label="Download .glb"),
157
+ title="TripoSG Image to 3D",
158
+ description="Upload an image to generate a 3D model (.glb)",
159
+ )
160
+
161
+ # Запуск
162
+ demo.launch()
163
+
164
+
165
+
166
+