cavargas10 commited on
Commit
d0b5340
verified
1 Parent(s): 1d6c686

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -56
app.py CHANGED
@@ -2,79 +2,57 @@ import os
2
  import shlex
3
  import spaces
4
  import subprocess
5
- import argparse
6
  import uuid
7
- import random
 
 
8
  import numpy as np
 
 
9
 
10
  # --------------------------------------------------------------------------
11
- # BLOQUE 1: INSTALACI脫N DEL ENTORNO Y DEPENDENCIAS
12
- # Esta secci贸n DEBE ejecutarse en su totalidad ANTES de importar torch o gradio.
13
  # --------------------------------------------------------------------------
14
-
15
  @spaces.GPU(duration=120)
16
  def setup_environment():
17
- """
18
- Prepara todo el entorno necesario, instalando CUDA y compilando las extensiones.
19
- Esta funci贸n se ejecuta una vez al inicio del Space.
20
- """
21
  print("--- INICIANDO CONFIGURACI脫N DEL ENTORNO ---")
22
-
23
- # 1. Instalar CUDA Toolkit
24
  if not os.path.exists("/usr/local/cuda"):
25
  print("Instalando CUDA Toolkit...")
26
  CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/12.4.0/local_installers/cuda_12.4.0_550.54.14_linux.run"
27
  CUDA_TOOLKIT_FILE = f"/tmp/{os.path.basename(CUDA_TOOLKIT_URL)}"
28
-
29
  subprocess.run(["wget", "-q", CUDA_TOOLKIT_URL, "-O", CUDA_TOOLKIT_FILE], check=True)
30
  subprocess.run(["chmod", "+x", CUDA_TOOLKIT_FILE], check=True)
31
- # Se a帽ade --override para evitar problemas en algunos entornos de HF Spaces
32
  subprocess.run([CUDA_TOOLKIT_FILE, "--silent", "--toolkit", "--override"], check=True)
33
- print("CUDA Toolkit instalado.")
34
  else:
35
  print("CUDA Toolkit ya est谩 instalado.")
36
-
37
- # 2. Configurar variables de entorno
38
  os.environ["CUDA_HOME"] = "/usr/local/cuda"
39
  os.environ["PATH"] = f"{os.environ['CUDA_HOME']}/bin:{os.environ['PATH']}"
40
- # La ruta correcta en la mayor铆a de las distribuciones de Linux es lib64
41
  os.environ["LD_LIBRARY_PATH"] = f"{os.environ['CUDA_HOME']}/lib64:{os.environ.get('LD_LIBRARY_PATH', '')}"
42
  os.environ["TORCH_CUDA_ARCH_LIST"] = "8.0;8.6"
43
  print("Variables de entorno de CUDA configuradas.")
44
-
45
- # 3. Verificar NVCC
46
- print("Verificando versi贸n de NVCC:")
47
  os.system('nvcc -V')
48
 
49
- # 4. Compilar extensiones C++/CUDA
50
  print("Compilando extensi贸n de renderizador diferenciable...")
51
  try:
52
- subprocess.run(
53
- "cd /home/user/app/step1x3d_texture/differentiable_renderer/ && python setup.py install",
54
- shell=True, check=True, capture_output=True, text=True
55
- )
56
- print("Renderizador diferenciable compilado.")
57
  except subprocess.CalledProcessError as e:
58
- print(f"ERROR al compilar el renderizador diferenciable:\n{e.stderr}")
59
  raise RuntimeError("Fallo cr铆tico en la compilaci贸n del renderizador.")
60
 
61
  print("Instalando rasterizador personalizado...")
62
  try:
63
  subprocess.run(shlex.split("pip install custom_rasterizer-0.1-cp310-cp310-linux_x86_64.whl"), check=True)
64
- print("Rasterizador personalizado instalado.")
65
  except Exception as e:
66
  print(f"ERROR al instalar el rasterizador personalizado: {e}")
67
  raise RuntimeError("Fallo cr铆tico en la instalaci贸n del rasterizador.")
68
-
69
  print("--- CONFIGURACI脫N DEL ENTORNO FINALIZADA ---")
70
 
71
- # Ejecutar la configuraci贸n del entorno antes de cualquier otra cosa
72
  setup_environment()
73
 
74
-
75
  # --------------------------------------------------------------------------
76
- # BLOQUE 2: IMPORTACIONES DE LA APLICACI脫N Y L脫GICA PRINCIPAL
77
- # Todas las importaciones que dependen de CUDA se hacen AHORA.
78
  # --------------------------------------------------------------------------
79
  import torch
80
  import trimesh
@@ -82,9 +60,6 @@ import gradio as gr
82
  from step1x3d_texture.pipelines.step1x_3d_texture_synthesis_pipeline import Step1X3DTexturePipeline
83
  from step1x3d_geometry.models.pipelines.pipeline_utils import reduce_face, remove_degenerate_face
84
 
85
- # --------------------------------------------------------------------------
86
- # 3. CONFIGURACI脫N Y CARGA DEL MODELO DE TEXTURA
87
- # --------------------------------------------------------------------------
88
  parser = argparse.ArgumentParser()
89
  parser.add_argument("--texture_model", type=str, default="Step1X-3D-Texture")
90
  parser.add_argument("--cache_dir", type=str, default="cache")
@@ -94,7 +69,6 @@ os.makedirs(args.cache_dir, exist_ok=True)
94
  device = "cuda" if torch.cuda.is_available() else "cpu"
95
  MAX_SEED = np.iinfo(np.int32).max
96
 
97
- print(f"Dispositivo detectado: {device}")
98
  if not torch.cuda.is_available():
99
  raise RuntimeError("CUDA no est谩 disponible para PyTorch. La aplicaci贸n no puede continuar.")
100
 
@@ -102,30 +76,32 @@ print(f"Cargando modelo de textura: {args.texture_model}...")
102
  texture_model = Step1X3DTexturePipeline.from_pretrained("stepfun-ai/Step1X-3D", subfolder=args.texture_model)
103
  print("Modelo de textura cargado y listo.")
104
 
105
-
106
  # --------------------------------------------------------------------------
107
- # 4. FUNCI脫N DE GENERACI脫N DE TEXTURA
108
  # --------------------------------------------------------------------------
109
 
110
  def get_random_seed(randomize_seed, seed):
111
- """Genera una semilla aleatoria si se solicita."""
112
  if randomize_seed:
113
- return random.randint(0, MAX_SEED)
114
- return int(seed)
 
 
 
 
115
 
116
  @spaces.GPU(duration=180)
117
- def generate_texture_for_user_mesh(
118
  input_image_path,
119
  input_mesh_path,
120
  guidance_scale,
121
  inference_steps,
122
- seed,
123
- randomize_seed,
124
  reference_conditioning_scale,
125
  progress=gr.Progress(track_tqdm=True)
126
  ):
127
  """
128
- Funci贸n principal que genera la textura para un modelo 3D proporcionado por el usuario.
129
  """
130
  if input_image_path is None:
131
  raise gr.Error("Por favor, sube una imagen de referencia para empezar.")
@@ -134,13 +110,14 @@ def generate_texture_for_user_mesh(
134
 
135
  print("Iniciando generaci贸n de textura para el modelo del usuario...")
136
 
137
- seed = get_random_seed(randomize_seed, seed)
138
-
139
  texture_model.config.guidance_scale = float(guidance_scale)
140
  texture_model.config.num_inference_steps = int(inference_steps)
141
  texture_model.config.reference_conditioning_scale = float(reference_conditioning_scale)
142
 
143
- print(f"Par谩metros: Pasos={inference_steps}, Escala Gu铆a={guidance_scale}, Semilla={seed}")
 
 
144
 
145
  print(f"Cargando malla desde: {input_mesh_path}")
146
  try:
@@ -157,7 +134,7 @@ def generate_texture_for_user_mesh(
157
  image=input_image_path,
158
  mesh=user_mesh,
159
  remove_bg=True,
160
- seed=seed
161
  )
162
 
163
  save_name = str(uuid.uuid4())
@@ -169,9 +146,8 @@ def generate_texture_for_user_mesh(
169
 
170
  return textured_save_path
171
 
172
-
173
  # --------------------------------------------------------------------------
174
- # 5. INTERFAZ DE USUARIO CON GRADIO
175
  # --------------------------------------------------------------------------
176
 
177
  with gr.Blocks(title="Step1X-3D Texture Generator") as demo:
@@ -196,19 +172,23 @@ with gr.Blocks(title="Step1X-3D Texture Generator") as demo:
196
  with gr.Column(scale=3):
197
  output_model = gr.Model3D(label="Resultado: Modelo Texturizado", height=600, clear_color=[0.0, 0.0, 0.0, 0.0])
198
 
 
 
199
  btn_generate.click(
200
- fn=generate_texture_for_user_mesh,
 
 
 
 
201
  inputs=[
202
  input_image,
203
  input_mesh,
204
  guidance_scale,
205
  inference_steps,
206
- seed,
207
- randomize_seed,
208
  reference_conditioning_scale,
209
  ],
210
  outputs=[output_model]
211
  )
212
 
213
- # Lanza la aplicaci贸n (share=True no es necesario en HF Spaces)
214
  demo.launch(ssr_mode=False)
 
2
  import shlex
3
  import spaces
4
  import subprocess
 
5
  import uuid
6
+ import torch
7
+ import trimesh
8
+ import argparse
9
  import numpy as np
10
+ import gradio as gr
11
+ import random
12
 
13
  # --------------------------------------------------------------------------
14
+ # 1. INSTALACI脫N DEL ENTORNO Y DEPENDENCIAS (Sin cambios)
 
15
  # --------------------------------------------------------------------------
 
16
  @spaces.GPU(duration=120)
17
  def setup_environment():
18
+ """Prepara el entorno, instalando CUDA y compilando extensiones."""
 
 
 
19
  print("--- INICIANDO CONFIGURACI脫N DEL ENTORNO ---")
 
 
20
  if not os.path.exists("/usr/local/cuda"):
21
  print("Instalando CUDA Toolkit...")
22
  CUDA_TOOLKIT_URL = "https://developer.download.nvidia.com/compute/cuda/12.4.0/local_installers/cuda_12.4.0_550.54.14_linux.run"
23
  CUDA_TOOLKIT_FILE = f"/tmp/{os.path.basename(CUDA_TOOLKIT_URL)}"
 
24
  subprocess.run(["wget", "-q", CUDA_TOOLKIT_URL, "-O", CUDA_TOOLKIT_FILE], check=True)
25
  subprocess.run(["chmod", "+x", CUDA_TOOLKIT_FILE], check=True)
 
26
  subprocess.run([CUDA_TOOLKIT_FILE, "--silent", "--toolkit", "--override"], check=True)
 
27
  else:
28
  print("CUDA Toolkit ya est谩 instalado.")
29
+
 
30
  os.environ["CUDA_HOME"] = "/usr/local/cuda"
31
  os.environ["PATH"] = f"{os.environ['CUDA_HOME']}/bin:{os.environ['PATH']}"
 
32
  os.environ["LD_LIBRARY_PATH"] = f"{os.environ['CUDA_HOME']}/lib64:{os.environ.get('LD_LIBRARY_PATH', '')}"
33
  os.environ["TORCH_CUDA_ARCH_LIST"] = "8.0;8.6"
34
  print("Variables de entorno de CUDA configuradas.")
 
 
 
35
  os.system('nvcc -V')
36
 
 
37
  print("Compilando extensi贸n de renderizador diferenciable...")
38
  try:
39
+ subprocess.run("cd /home/user/app/step1x3d_texture/differentiable_renderer/ && python setup.py install", shell=True, check=True)
 
 
 
 
40
  except subprocess.CalledProcessError as e:
41
+ print(f"ERROR al compilar el renderizador diferenciable: {e}")
42
  raise RuntimeError("Fallo cr铆tico en la compilaci贸n del renderizador.")
43
 
44
  print("Instalando rasterizador personalizado...")
45
  try:
46
  subprocess.run(shlex.split("pip install custom_rasterizer-0.1-cp310-cp310-linux_x86_64.whl"), check=True)
 
47
  except Exception as e:
48
  print(f"ERROR al instalar el rasterizador personalizado: {e}")
49
  raise RuntimeError("Fallo cr铆tico en la instalaci贸n del rasterizador.")
 
50
  print("--- CONFIGURACI脫N DEL ENTORNO FINALIZADA ---")
51
 
 
52
  setup_environment()
53
 
 
54
  # --------------------------------------------------------------------------
55
+ # 2. IMPORTACIONES Y CARGA DE MODELOS (Despu茅s de la configuraci贸n)
 
56
  # --------------------------------------------------------------------------
57
  import torch
58
  import trimesh
 
60
  from step1x3d_texture.pipelines.step1x_3d_texture_synthesis_pipeline import Step1X3DTexturePipeline
61
  from step1x3d_geometry.models.pipelines.pipeline_utils import reduce_face, remove_degenerate_face
62
 
 
 
 
63
  parser = argparse.ArgumentParser()
64
  parser.add_argument("--texture_model", type=str, default="Step1X-3D-Texture")
65
  parser.add_argument("--cache_dir", type=str, default="cache")
 
69
  device = "cuda" if torch.cuda.is_available() else "cpu"
70
  MAX_SEED = np.iinfo(np.int32).max
71
 
 
72
  if not torch.cuda.is_available():
73
  raise RuntimeError("CUDA no est谩 disponible para PyTorch. La aplicaci贸n no puede continuar.")
74
 
 
76
  texture_model = Step1X3DTexturePipeline.from_pretrained("stepfun-ai/Step1X-3D", subfolder=args.texture_model)
77
  print("Modelo de textura cargado y listo.")
78
 
 
79
  # --------------------------------------------------------------------------
80
+ # 3. FUNCIONES DE L脫GICA
81
  # --------------------------------------------------------------------------
82
 
83
  def get_random_seed(randomize_seed, seed):
84
+ """Devuelve una semilla aleatoria si la casilla est谩 marcada, de lo contrario devuelve la semilla del slider."""
85
  if randomize_seed:
86
+ new_seed = random.randint(0, MAX_SEED)
87
+ print(f"Generando semilla aleatoria: {new_seed}")
88
+ return new_seed
89
+ else:
90
+ print(f"Usando semilla fija: {int(seed)}")
91
+ return int(seed)
92
 
93
  @spaces.GPU(duration=180)
94
+ def generate_texture(
95
  input_image_path,
96
  input_mesh_path,
97
  guidance_scale,
98
  inference_steps,
99
+ seed, # Ahora este valor es el definitivo (aleatorio o fijo)
 
100
  reference_conditioning_scale,
101
  progress=gr.Progress(track_tqdm=True)
102
  ):
103
  """
104
+ Funci贸n principal que genera la textura. Ya no necesita el par谩metro 'randomize_seed'.
105
  """
106
  if input_image_path is None:
107
  raise gr.Error("Por favor, sube una imagen de referencia para empezar.")
 
110
 
111
  print("Iniciando generaci贸n de textura para el modelo del usuario...")
112
 
113
+ # Actualizar la configuraci贸n del pipeline con los valores de la UI
 
114
  texture_model.config.guidance_scale = float(guidance_scale)
115
  texture_model.config.num_inference_steps = int(inference_steps)
116
  texture_model.config.reference_conditioning_scale = float(reference_conditioning_scale)
117
 
118
+ # La semilla ya viene procesada
119
+ final_seed = int(seed)
120
+ print(f"Par谩metros: Pasos={inference_steps}, Escala Gu铆a={guidance_scale}, Semilla Final={final_seed}")
121
 
122
  print(f"Cargando malla desde: {input_mesh_path}")
123
  try:
 
134
  image=input_image_path,
135
  mesh=user_mesh,
136
  remove_bg=True,
137
+ seed=final_seed
138
  )
139
 
140
  save_name = str(uuid.uuid4())
 
146
 
147
  return textured_save_path
148
 
 
149
  # --------------------------------------------------------------------------
150
+ # 4. INTERFAZ DE USUARIO CON GRADIO
151
  # --------------------------------------------------------------------------
152
 
153
  with gr.Blocks(title="Step1X-3D Texture Generator") as demo:
 
172
  with gr.Column(scale=3):
173
  output_model = gr.Model3D(label="Resultado: Modelo Texturizado", height=600, clear_color=[0.0, 0.0, 0.0, 0.0])
174
 
175
+ # --- L贸gica de la interfaz ---
176
+
177
  btn_generate.click(
178
+ fn=get_random_seed,
179
+ inputs=[randomize_seed, seed],
180
+ outputs=[seed]
181
+ ).then(
182
+ fn=generate_texture,
183
  inputs=[
184
  input_image,
185
  input_mesh,
186
  guidance_scale,
187
  inference_steps,
188
+ seed,
 
189
  reference_conditioning_scale,
190
  ],
191
  outputs=[output_model]
192
  )
193
 
 
194
  demo.launch(ssr_mode=False)