gokaygokay commited on
Commit
6afb035
·
1 Parent(s): cd9c33a
Files changed (1) hide show
  1. app.py +8 -306
app.py CHANGED
@@ -1,4 +1,3 @@
1
- <<<<<<< HEAD
2
  import gradio as gr
3
  import spaces
4
  from gradio_litmodel3d import LitModel3D
@@ -274,18 +273,21 @@ with gr.Blocks() as demo:
274
 
275
  # Initialize both pipelines
276
  if __name__ == "__main__":
277
- from diffusers import FluxTransformer2DModel, FluxPipeline
 
 
278
  # Initialize Flux pipeline
279
  device = "cuda" if torch.cuda.is_available() else "cpu"
280
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
281
 
282
- #quantization_config = BitsAndBytesConfig(load_in_4bit=True)
283
- hf_token = ""
284
  dtype = torch.bfloat16
285
  file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/gokaygokay_00001_.safetensors"
286
  single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
287
- transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model)
288
- flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, torch_dtype=dtype, token=huggingface_token, quantization_config=quantization_config)
 
 
 
289
 
290
  # Initialize Trellis pipeline
291
  trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
@@ -295,304 +297,4 @@ if __name__ == "__main__":
295
  except:
296
  pass
297
 
298
- =======
299
- import gradio as gr
300
- import spaces
301
- from gradio_litmodel3d import LitModel3D
302
- import os
303
- import shutil
304
- import random
305
- import uuid
306
- from datetime import datetime
307
- from diffusers import DiffusionPipeline
308
-
309
- os.environ['SPCONV_ALGO'] = 'native'
310
- from typing import *
311
- import torch
312
- import numpy as np
313
- import imageio
314
- from easydict import EasyDict as edict
315
- from PIL import Image
316
- from trellis.pipelines import TrellisImageTo3DPipeline
317
- from trellis.representations import Gaussian, MeshExtractResult
318
- from trellis.utils import render_utils, postprocessing_utils
319
-
320
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
321
- # Constants
322
- MAX_SEED = np.iinfo(np.int32).max
323
- TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
324
- os.makedirs(TMP_DIR, exist_ok=True)
325
-
326
- # Create permanent storage directory for Flux generated images
327
- SAVE_DIR = "saved_images"
328
- if not os.path.exists(SAVE_DIR):
329
- os.makedirs(SAVE_DIR, exist_ok=True)
330
-
331
- def start_session(req: gr.Request):
332
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
333
- os.makedirs(user_dir, exist_ok=True)
334
-
335
- def end_session(req: gr.Request):
336
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
337
- shutil.rmtree(user_dir)
338
-
339
- def preprocess_image(image: Image.Image) -> Image.Image:
340
- processed_image = trellis_pipeline.preprocess_image(image)
341
- return processed_image
342
-
343
- def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
344
- return {
345
- 'gaussian': {
346
- **gs.init_params,
347
- '_xyz': gs._xyz.cpu().numpy(),
348
- '_features_dc': gs._features_dc.cpu().numpy(),
349
- '_scaling': gs._scaling.cpu().numpy(),
350
- '_rotation': gs._rotation.cpu().numpy(),
351
- '_opacity': gs._opacity.cpu().numpy(),
352
- },
353
- 'mesh': {
354
- 'vertices': mesh.vertices.cpu().numpy(),
355
- 'faces': mesh.faces.cpu().numpy(),
356
- },
357
- }
358
-
359
- def unpack_state(state: dict) -> Tuple[Gaussian, edict]:
360
- gs = Gaussian(
361
- aabb=state['gaussian']['aabb'],
362
- sh_degree=state['gaussian']['sh_degree'],
363
- mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
364
- scaling_bias=state['gaussian']['scaling_bias'],
365
- opacity_bias=state['gaussian']['opacity_bias'],
366
- scaling_activation=state['gaussian']['scaling_activation'],
367
- )
368
- gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
369
- gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
370
- gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
371
- gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
372
- gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
373
-
374
- mesh = edict(
375
- vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
376
- faces=torch.tensor(state['mesh']['faces'], device='cuda'),
377
- )
378
-
379
- return gs, mesh
380
-
381
- def get_seed(randomize_seed: bool, seed: int) -> int:
382
- return np.random.randint(0, MAX_SEED) if randomize_seed else seed
383
-
384
- @spaces.GPU
385
- def generate_flux_image(
386
- prompt: str,
387
- seed: int,
388
- randomize_seed: bool,
389
- width: int,
390
- height: int,
391
- guidance_scale: float,
392
- num_inference_steps: int,
393
- lora_scale: float,
394
- progress: gr.Progress = gr.Progress(track_tqdm=True),
395
- ) -> Image.Image:
396
- """Generate image using Flux pipeline"""
397
- if randomize_seed:
398
- seed = random.randint(0, MAX_SEED)
399
- generator = torch.Generator(device=device).manual_seed(seed)
400
-
401
- image = flux_pipeline(
402
- prompt=prompt,
403
- guidance_scale=guidance_scale,
404
- num_inference_steps=num_inference_steps,
405
- width=width,
406
- height=height,
407
- generator=generator,
408
- joint_attention_kwargs={"scale": lora_scale},
409
- ).images[0]
410
-
411
- # Save the generated image
412
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
413
- unique_id = str(uuid.uuid4())[:8]
414
- filename = f"{timestamp}_{unique_id}.png"
415
- filepath = os.path.join(SAVE_DIR, filename)
416
- image.save(filepath)
417
-
418
- return image
419
-
420
- @spaces.GPU
421
- def image_to_3d(
422
- image: Image.Image,
423
- seed: int,
424
- ss_guidance_strength: float,
425
- ss_sampling_steps: int,
426
- slat_guidance_strength: float,
427
- slat_sampling_steps: int,
428
- req: gr.Request,
429
- ) -> Tuple[dict, str]:
430
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
431
- outputs = trellis_pipeline.run(
432
- image,
433
- seed=seed,
434
- formats=["gaussian", "mesh"],
435
- preprocess_image=False,
436
- sparse_structure_sampler_params={
437
- "steps": ss_sampling_steps,
438
- "cfg_strength": ss_guidance_strength,
439
- },
440
- slat_sampler_params={
441
- "steps": slat_sampling_steps,
442
- "cfg_strength": slat_guidance_strength,
443
- },
444
- )
445
- video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
446
- video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
447
- video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
448
- video_path = os.path.join(user_dir, 'sample.mp4')
449
- imageio.mimsave(video_path, video, fps=15)
450
- state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
451
- torch.cuda.empty_cache()
452
- return state, video_path
453
-
454
- @spaces.GPU(duration=90)
455
- def extract_glb(
456
- state: dict,
457
- mesh_simplify: float,
458
- texture_size: int,
459
- req: gr.Request,
460
- ) -> Tuple[str, str]:
461
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
462
- gs, mesh = unpack_state(state)
463
- glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
464
- glb_path = os.path.join(user_dir, 'sample.glb')
465
- glb.export(glb_path)
466
- torch.cuda.empty_cache()
467
- return glb_path, glb_path
468
-
469
- @spaces.GPU
470
- def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
471
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
472
- gs, _ = unpack_state(state)
473
- gaussian_path = os.path.join(user_dir, 'sample.ply')
474
- gs.save_ply(gaussian_path)
475
- torch.cuda.empty_cache()
476
- return gaussian_path, gaussian_path
477
-
478
- # Gradio Interface
479
- with gr.Blocks() as demo:
480
- gr.Markdown("""
481
- ## Game Asset Generation to 3D with FLUX and TRELLIS
482
- * Enter a prompt to generate a game asset image, then convert it to 3D
483
- * If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.
484
- """)
485
-
486
- with gr.Row():
487
- with gr.Column():
488
- # Flux image generation inputs
489
- prompt = gr.Text(label="Prompt", placeholder="Enter your game asset description")
490
- with gr.Accordion("Generation Settings", open=False):
491
- seed = gr.Slider(0, MAX_SEED, label="Seed", value=42, step=1)
492
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
493
- with gr.Row():
494
- width = gr.Slider(256, 1024, label="Width", value=768, step=32)
495
- height = gr.Slider(256, 1024, label="Height", value=768, step=32)
496
- with gr.Row():
497
- guidance_scale = gr.Slider(0.0, 10.0, label="Guidance Scale", value=3.5, step=0.1)
498
- num_inference_steps = gr.Slider(1, 50, label="Steps", value=30, step=1)
499
- lora_scale = gr.Slider(0.0, 1.0, label="LoRA Scale", value=1.0, step=0.1)
500
-
501
- with gr.Accordion("3D Generation Settings", open=False):
502
- gr.Markdown("Stage 1: Sparse Structure Generation")
503
- with gr.Row():
504
- ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
505
- ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
506
- gr.Markdown("Stage 2: Structured Latent Generation")
507
- with gr.Row():
508
- slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
509
- slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
510
-
511
- generate_btn = gr.Button("Generate")
512
-
513
- with gr.Accordion("GLB Extraction Settings", open=False):
514
- mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
515
- texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
516
-
517
- with gr.Row():
518
- extract_glb_btn = gr.Button("Extract GLB", interactive=False)
519
- extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
520
-
521
- with gr.Column():
522
- generated_image = gr.Image(label="Generated Asset", type="pil")
523
- video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True)
524
- model_output = LitModel3D(label="Extracted GLB/Gaussian")
525
-
526
- with gr.Row():
527
- download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
528
- download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
529
-
530
- output_buf = gr.State()
531
-
532
- # Event handlers
533
- demo.load(start_session)
534
- demo.unload(end_session)
535
-
536
- generate_btn.click(
537
- generate_flux_image,
538
- inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, lora_scale],
539
- outputs=[generated_image],
540
- ).then(
541
- image_to_3d,
542
- inputs=[generated_image, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],
543
- outputs=[output_buf, video_output],
544
- ).then(
545
- lambda: tuple([gr.Button(interactive=True), gr.Button(interactive=True)]),
546
- outputs=[extract_glb_btn, extract_gs_btn],
547
- )
548
-
549
- extract_glb_btn.click(
550
- extract_glb,
551
- inputs=[output_buf, mesh_simplify, texture_size],
552
- outputs=[model_output, download_glb],
553
- ).then(
554
- lambda: gr.Button(interactive=True),
555
- outputs=[download_glb],
556
- )
557
-
558
- extract_gs_btn.click(
559
- extract_gaussian,
560
- inputs=[output_buf],
561
- outputs=[model_output, download_gs],
562
- ).then(
563
- lambda: gr.Button(interactive=True),
564
- outputs=[download_gs],
565
- )
566
-
567
- model_output.clear(
568
- lambda: gr.Button(interactive=False),
569
- outputs=[download_glb],
570
- )
571
-
572
- # Initialize both pipelines
573
- if __name__ == "__main__":
574
- from diffusers import FluxTransformer2DModel, FluxPipeline, BitsAndBytesConfig
575
- from transformers import BitsAndBytesConfig as BitsAndBytesConfigTF
576
- # Initialize Flux pipeline
577
- device = "cuda" if torch.cuda.is_available() else "cpu"
578
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
579
-
580
- dtype = torch.bfloat16
581
- file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/gokaygokay_00001_.safetensors"
582
- single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
583
- quantization_config_tf = BitsAndBytesConfigTF(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
584
- 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)
585
- quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
586
- transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config, token=huggingface_token)
587
- flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, text_encoder_2=text_encoder_2, torch_dtype=dtype, quantization_config=quantization_config, token=huggingface_token)
588
-
589
- # Initialize Trellis pipeline
590
- trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
591
- trellis_pipeline.cuda()
592
- try:
593
- trellis_pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
594
- except:
595
- pass
596
-
597
- >>>>>>> d74f4adbedc376ca385ce749e827d3c18535c4f0
598
  demo.launch()
 
 
1
  import gradio as gr
2
  import spaces
3
  from gradio_litmodel3d import LitModel3D
 
273
 
274
  # Initialize both pipelines
275
  if __name__ == "__main__":
276
+ from diffusers import FluxTransformer2DModel, FluxPipeline, BitsAndBytesConfig, BitsAndBytesConfigTF
277
+ from transformers import T5EncoderModel
278
+
279
  # Initialize Flux pipeline
280
  device = "cuda" if torch.cuda.is_available() else "cpu"
281
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
282
 
 
 
283
  dtype = torch.bfloat16
284
  file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/gokaygokay_00001_.safetensors"
285
  single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
286
+ quantization_config_tf = BitsAndBytesConfigTF(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
287
+ 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)
288
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
289
+ transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config, token=huggingface_token)
290
+ flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, text_encoder_2=text_encoder_2, torch_dtype=dtype, quantization_config=quantization_config, token=huggingface_token)
291
 
292
  # Initialize Trellis pipeline
293
  trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
 
297
  except:
298
  pass
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  demo.launch()