cavargas10 commited on
Commit
33b5608
verified
1 Parent(s): 5422690

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -54
app.py CHANGED
@@ -7,7 +7,6 @@ import random
7
  import uuid
8
  from datetime import datetime
9
  from diffusers import DiffusionPipeline
10
-
11
  os.environ['SPCONV_ALGO'] = 'native'
12
  from typing import *
13
  import torch
@@ -18,16 +17,14 @@ from PIL import Image
18
  from trellis.pipelines import TrellisImageTo3DPipeline
19
  from trellis.representations import Gaussian, MeshExtractResult
20
  from trellis.utils import render_utils, postprocessing_utils
21
-
22
  NUM_INFERENCE_STEPS = 8
23
-
24
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
25
-
26
  # Constants
27
  MAX_SEED = np.iinfo(np.int32).max
28
  TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
29
  os.makedirs(TMP_DIR, exist_ok=True)
30
 
 
31
  def start_session(req: gr.Request):
32
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
33
  os.makedirs(user_dir, exist_ok=True)
@@ -70,12 +67,10 @@ def unpack_state(state: dict) -> Tuple[Gaussian, edict]:
70
  gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
71
  gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
72
  gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
73
-
74
  mesh = edict(
75
  vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
76
  faces=torch.tensor(state['mesh']['faces'], device='cuda'),
77
  )
78
-
79
  return gs, mesh
80
 
81
  def get_seed(randomize_seed: bool, seed: int) -> int:
@@ -106,16 +101,13 @@ def generate_flux_image(
106
  generator=generator,
107
  ).images[0]
108
 
109
- # Guardar la imagen en el directorio temporal
110
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
111
  os.makedirs(user_dir, exist_ok=True)
112
-
113
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
114
  unique_id = str(uuid.uuid4())[:8]
115
  filename = f"{timestamp}_{unique_id}.png"
116
  filepath = os.path.join(user_dir, filename)
117
  image.save(filepath)
118
-
119
  return image
120
 
121
  @spaces.GPU
@@ -167,23 +159,16 @@ def extract_glb(
167
  torch.cuda.empty_cache()
168
  return glb_path, glb_path
169
 
170
- @spaces.GPU
171
- def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
172
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
173
- gs, _ = unpack_state(state)
174
- gaussian_path = os.path.join(user_dir, 'sample.ply')
175
- gs.save_ply(gaussian_path)
176
- torch.cuda.empty_cache()
177
- return gaussian_path, gaussian_path
178
-
179
- # Gradio Interface
180
  with gr.Blocks() as demo:
181
  gr.Markdown("""
182
- ## Game Asset Generation to 3D with FLUX and TRELLIS
183
- * Enter a prompt to generate a game asset image, then convert it to 3D
184
- * If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.
 
 
185
  """)
186
-
187
  with gr.Row():
188
  with gr.Column():
189
  # Flux image generation inputs
@@ -196,25 +181,20 @@ with gr.Blocks() as demo:
196
  height = gr.Slider(512, 1024, label="Height", value=1024, step=16)
197
  with gr.Row():
198
  guidance_scale = gr.Slider(0.0, 10.0, label="Guidance Scale", value=3.5, step=0.1)
199
-
200
  # Botones separados
201
  generate_image_btn = gr.Button("Generar Imagen")
202
  generate_video_btn = gr.Button("Generar Video", interactive=False)
203
-
204
  with gr.Column():
205
  generated_image = gr.Image(label="Generated Asset", type="pil")
206
  video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True)
207
-
208
- model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=8.0, height=400)
209
-
210
  with gr.Row():
211
  extract_glb_btn = gr.Button("Extract GLB", interactive=False)
212
- extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
213
-
214
  with gr.Row():
215
  download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
216
- download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
217
-
218
  # Variables adicionales para la generaci贸n 3D
219
  with gr.Accordion("3D Generation Settings", open=False):
220
  gr.Markdown("Stage 1: Sparse Structure Generation")
@@ -225,18 +205,18 @@ with gr.Blocks() as demo:
225
  with gr.Row():
226
  slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
227
  slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
228
-
229
  # Variables para la extracci贸n de GLB
230
  with gr.Accordion("GLB Extraction Settings", open=False):
231
  mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
232
  texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
233
-
234
  output_buf = gr.State()
235
 
236
  # Event handlers
237
  demo.load(start_session)
238
  demo.unload(end_session)
239
-
240
  # Generar imagen
241
  generate_image_btn.click(
242
  generate_flux_image,
@@ -246,7 +226,7 @@ with gr.Blocks() as demo:
246
  lambda: gr.Button(interactive=True),
247
  outputs=[generate_video_btn],
248
  )
249
-
250
  # Generar video
251
  generate_video_btn.click(
252
  get_seed,
@@ -268,13 +248,13 @@ with gr.Blocks() as demo:
268
  ],
269
  outputs=[output_buf, video_output],
270
  ).then(
271
- lambda: tuple([gr.Button(interactive=True), gr.Button(interactive=True)]),
272
- outputs=[extract_glb_btn, extract_gs_btn],
273
  )
274
-
275
  video_output.clear(
276
- lambda: tuple([gr.Button(interactive=False), gr.Button(interactive=False)]),
277
- outputs=[extract_glb_btn, extract_gs_btn],
278
  )
279
 
280
  # Extraer GLB
@@ -286,22 +266,12 @@ with gr.Blocks() as demo:
286
  lambda: gr.Button(interactive=True),
287
  outputs=[download_glb],
288
  )
289
-
290
- # Extraer Gaussian
291
- extract_gs_btn.click(
292
- extract_gaussian,
293
- inputs=[output_buf],
294
- outputs=[model_output, download_gs],
295
- ).then(
296
- lambda: gr.Button(interactive=True),
297
- outputs=[download_gs],
298
- )
299
-
300
  model_output.clear(
301
  lambda: gr.Button(interactive=False),
302
  outputs=[download_glb],
303
  )
304
-
305
  # Initialize both pipelines
306
  if __name__ == "__main__":
307
  from diffusers import FluxTransformer2DModel, FluxPipeline, BitsAndBytesConfig, GGUFQuantizationConfig
@@ -310,23 +280,26 @@ if __name__ == "__main__":
310
  # Initialize Flux pipeline
311
  device = "cuda" if torch.cuda.is_available() else "cpu"
312
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
313
-
314
  dtype = torch.bfloat16
315
  file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/hyperflux_00001_.q8_0.gguf"
316
  file_url = file_url.replace("/resolve/main/", "/blob/main/").replace("?download=true", "")
317
  single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
318
  quantization_config_tf = BitsAndBytesConfigTF(load_in_8bit=True, bnb_8bit_compute_dtype=torch.bfloat16)
319
  text_encoder_2 = T5EncoderModel.from_pretrained(single_file_base_model, subfolder="text_encoder_2", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config_tf, token=huggingface_token)
 
320
  if ".gguf" in file_url:
321
  transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", quantization_config=GGUFQuantizationConfig(compute_dtype=dtype), torch_dtype=dtype, config=single_file_base_model)
322
  else:
323
  quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, token=huggingface_token)
324
  transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config, token=huggingface_token)
 
325
  flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, text_encoder_2=text_encoder_2, torch_dtype=dtype, token=huggingface_token)
326
  flux_pipeline.to("cuda")
 
327
  # Initialize Trellis pipeline
328
  trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("cavargas10/TRELLIS")
329
  trellis_pipeline.cuda()
 
330
  try:
331
  trellis_pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
332
  except:
 
7
  import uuid
8
  from datetime import datetime
9
  from diffusers import DiffusionPipeline
 
10
  os.environ['SPCONV_ALGO'] = 'native'
11
  from typing import *
12
  import torch
 
17
  from trellis.pipelines import TrellisImageTo3DPipeline
18
  from trellis.representations import Gaussian, MeshExtractResult
19
  from trellis.utils import render_utils, postprocessing_utils
 
20
  NUM_INFERENCE_STEPS = 8
 
21
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
 
22
  # Constants
23
  MAX_SEED = np.iinfo(np.int32).max
24
  TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
25
  os.makedirs(TMP_DIR, exist_ok=True)
26
 
27
+ # Funciones auxiliares
28
  def start_session(req: gr.Request):
29
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
30
  os.makedirs(user_dir, exist_ok=True)
 
67
  gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
68
  gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
69
  gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
 
70
  mesh = edict(
71
  vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
72
  faces=torch.tensor(state['mesh']['faces'], device='cuda'),
73
  )
 
74
  return gs, mesh
75
 
76
  def get_seed(randomize_seed: bool, seed: int) -> int:
 
101
  generator=generator,
102
  ).images[0]
103
 
 
104
  user_dir = os.path.join(TMP_DIR, str(req.session_hash))
105
  os.makedirs(user_dir, exist_ok=True)
 
106
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
107
  unique_id = str(uuid.uuid4())[:8]
108
  filename = f"{timestamp}_{unique_id}.png"
109
  filepath = os.path.join(user_dir, filename)
110
  image.save(filepath)
 
111
  return image
112
 
113
  @spaces.GPU
 
159
  torch.cuda.empty_cache()
160
  return glb_path, glb_path
161
 
162
+ # Interfaz Gradio
 
 
 
 
 
 
 
 
 
163
  with gr.Blocks() as demo:
164
  gr.Markdown("""
165
+ # UTPL - Conversi贸n de Texto a Imagen a objetos 3D usando IA
166
+ ### Tesis: *"Objetos tridimensionales creados por IA: Innovaci贸n en entornos virtuales"*
167
+ **Autor:** Carlos Vargas
168
+ **Base t茅cnica:** Adaptaci贸n de [TRELLIS](https://trellis3d.github.io/) y Flux
169
+ **Prop贸sito educativo:** Demostraciones acad茅micas e Investigaci贸n en modelado 3D autom谩tico
170
  """)
171
+
172
  with gr.Row():
173
  with gr.Column():
174
  # Flux image generation inputs
 
181
  height = gr.Slider(512, 1024, label="Height", value=1024, step=16)
182
  with gr.Row():
183
  guidance_scale = gr.Slider(0.0, 10.0, label="Guidance Scale", value=3.5, step=0.1)
 
184
  # Botones separados
185
  generate_image_btn = gr.Button("Generar Imagen")
186
  generate_video_btn = gr.Button("Generar Video", interactive=False)
 
187
  with gr.Column():
188
  generated_image = gr.Image(label="Generated Asset", type="pil")
189
  video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True)
190
+ model_output = LitModel3D(label="Extracted GLB", exposure=8.0, height=400)
191
+
 
192
  with gr.Row():
193
  extract_glb_btn = gr.Button("Extract GLB", interactive=False)
194
+
 
195
  with gr.Row():
196
  download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
197
+
 
198
  # Variables adicionales para la generaci贸n 3D
199
  with gr.Accordion("3D Generation Settings", open=False):
200
  gr.Markdown("Stage 1: Sparse Structure Generation")
 
205
  with gr.Row():
206
  slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
207
  slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
208
+
209
  # Variables para la extracci贸n de GLB
210
  with gr.Accordion("GLB Extraction Settings", open=False):
211
  mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
212
  texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
213
+
214
  output_buf = gr.State()
215
 
216
  # Event handlers
217
  demo.load(start_session)
218
  demo.unload(end_session)
219
+
220
  # Generar imagen
221
  generate_image_btn.click(
222
  generate_flux_image,
 
226
  lambda: gr.Button(interactive=True),
227
  outputs=[generate_video_btn],
228
  )
229
+
230
  # Generar video
231
  generate_video_btn.click(
232
  get_seed,
 
248
  ],
249
  outputs=[output_buf, video_output],
250
  ).then(
251
+ lambda: gr.Button(interactive=True),
252
+ outputs=[extract_glb_btn],
253
  )
254
+
255
  video_output.clear(
256
+ lambda: gr.Button(interactive=False),
257
+ outputs=[extract_glb_btn],
258
  )
259
 
260
  # Extraer GLB
 
266
  lambda: gr.Button(interactive=True),
267
  outputs=[download_glb],
268
  )
269
+
 
 
 
 
 
 
 
 
 
 
270
  model_output.clear(
271
  lambda: gr.Button(interactive=False),
272
  outputs=[download_glb],
273
  )
274
+
275
  # Initialize both pipelines
276
  if __name__ == "__main__":
277
  from diffusers import FluxTransformer2DModel, FluxPipeline, BitsAndBytesConfig, GGUFQuantizationConfig
 
280
  # Initialize Flux pipeline
281
  device = "cuda" if torch.cuda.is_available() else "cpu"
282
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
 
283
  dtype = torch.bfloat16
284
  file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/hyperflux_00001_.q8_0.gguf"
285
  file_url = file_url.replace("/resolve/main/", "/blob/main/").replace("?download=true", "")
286
  single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
287
  quantization_config_tf = BitsAndBytesConfigTF(load_in_8bit=True, bnb_8bit_compute_dtype=torch.bfloat16)
288
  text_encoder_2 = T5EncoderModel.from_pretrained(single_file_base_model, subfolder="text_encoder_2", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config_tf, token=huggingface_token)
289
+
290
  if ".gguf" in file_url:
291
  transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", quantization_config=GGUFQuantizationConfig(compute_dtype=dtype), torch_dtype=dtype, config=single_file_base_model)
292
  else:
293
  quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, token=huggingface_token)
294
  transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config, token=huggingface_token)
295
+
296
  flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, text_encoder_2=text_encoder_2, torch_dtype=dtype, token=huggingface_token)
297
  flux_pipeline.to("cuda")
298
+
299
  # Initialize Trellis pipeline
300
  trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("cavargas10/TRELLIS")
301
  trellis_pipeline.cuda()
302
+
303
  try:
304
  trellis_pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
305
  except: