gokaygokay commited on
Commit
082faa8
·
verified ·
1 Parent(s): 57b54a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -66
app.py CHANGED
@@ -5,19 +5,45 @@ import time
5
  from os import path
6
  from safetensors.torch import load_file
7
  from huggingface_hub import hf_hub_download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
9
  cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
10
  os.environ["TRANSFORMERS_CACHE"] = cache_path
11
  os.environ["HF_HUB_CACHE"] = cache_path
12
  os.environ["HF_HOME"] = cache_path
13
 
14
- import gradio as gr
15
- import torch
16
- from diffusers import FluxPipeline
17
 
18
- torch.backends.cuda.matmul.allow_tf32 = True
 
19
 
20
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
21
 
22
  class timer:
23
  def __init__(self, method_name="timed process"):
@@ -29,84 +55,213 @@ class timer:
29
  end = time.time()
30
  print(f"{self.method} took {str(round(end - self.start, 2))}s")
31
 
32
- if not path.exists(cache_path):
33
- os.makedirs(cache_path, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16, token=huggingface_token)
36
- pipe.load_lora_weights(hf_hub_download("gokaygokay/Flux-Game-Assets-LoRA-v2", "game_asst.safetensors"))
37
- pipe.fuse_lora(lora_scale=1)
38
- pipe.to(device="cuda", dtype=torch.bfloat16)
39
- pipe.enable_model_cpu_offload()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
42
  gr.Markdown(
43
  """
44
  <div style="text-align: center; max-width: 650px; margin: 0 auto;">
45
- <h1 style="font-size: 2.5rem; font-weight: 700; margin-bottom: 1rem; display: contents;">Hyper-FLUX-8steps-LoRA</h1>
46
- <p style="font-size: 1rem; margin-bottom: 1.5rem;">AutoML team from ByteDance</p>
47
  </div>
48
  """
49
  )
50
 
51
  with gr.Row():
52
  with gr.Column(scale=3):
53
- with gr.Group():
54
- prompt = gr.Textbox(
55
- label="Your Image Description",
56
- placeholder="E.g., A serene landscape with mountains and a lake at sunset",
57
- lines=3
58
- )
59
-
60
- with gr.Accordion("Advanced Settings", open=False):
61
- with gr.Group():
62
- with gr.Row():
63
- height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=1024)
64
- width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=1024)
65
-
66
- with gr.Row():
67
- steps = gr.Slider(label="Inference Steps", minimum=10, maximum=50, step=1, value=28)
68
- scales = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=5.0, step=0.1, value=3.5)
69
-
70
- seed = gr.Number(label="Seed (for reproducibility)", value=3413, precision=0)
71
-
72
- generate_btn = gr.Button("Generate Image", variant="primary", scale=1)
73
 
74
  with gr.Column(scale=4):
75
- output = gr.Image(label="Your Generated Image")
76
-
77
- gr.Markdown(
78
- """
79
- <div style="max-width: 650px; margin: 2rem auto; padding: 1rem; border-radius: 10px; background-color: #f0f0f0;">
80
- <h2 style="font-size: 1.5rem; margin-bottom: 1rem;">How to Use</h2>
81
- <ol style="padding-left: 1.5rem;">
82
- <li>Enter a detailed description of the image you want to create.</li>
83
- <li>Adjust advanced settings if desired (tap to expand).</li>
84
- <li>Tap "Generate Image" and wait for your creation!</li>
85
- </ol>
86
- <p style="margin-top: 1rem; font-style: italic;">Tip: Be specific in your description for best results!</p>
87
- </div>
88
- """
89
- )
90
 
91
- @spaces.GPU
92
- def process_image(height, width, steps, scales, prompt, seed):
93
- global pipe
94
- with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
95
- return pipe(
96
- prompt=[prompt],
97
- generator=torch.Generator().manual_seed(int(seed)),
98
- num_inference_steps=int(steps),
99
- guidance_scale=float(scales),
100
- height=int(height),
101
- width=int(width),
102
- max_sequence_length=256
103
- ).images[0]
104
 
105
  generate_btn.click(
106
- process_image,
107
- inputs=[height, width, steps, scales, prompt, seed],
108
- outputs=output
109
  )
110
 
111
  if __name__ == "__main__":
112
- demo.launch()
 
5
  from os import path
6
  from safetensors.torch import load_file
7
  from huggingface_hub import hf_hub_download
8
+ import imageio
9
+ import numpy as np
10
+ import torch
11
+ import rembg
12
+ from PIL import Image
13
+ from torchvision.transforms import v2
14
+ from pytorch_lightning import seed_everything
15
+ from omegaconf import OmegaConf
16
+ from einops import rearrange, repeat
17
+ from tqdm import tqdm
18
+ from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
19
+ import gradio as gr
20
+ import shutil
21
+ import tempfile
22
+ from functools import partial
23
+ from optimum.quanto import quantize, qfloat8, freeze
24
+ from diffusers import FluxPipeline
25
 
26
+ from src.utils.train_util import instantiate_from_config
27
+ from src.utils.camera_util import (
28
+ FOV_to_intrinsics,
29
+ get_zero123plus_input_cameras,
30
+ get_circular_camera_poses,
31
+ )
32
+ from src.utils.mesh_util import save_obj, save_glb
33
+ from src.utils.infer_util import remove_background, resize_foreground, images_to_video
34
+
35
+ # Set up cache path
36
  cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
37
  os.environ["TRANSFORMERS_CACHE"] = cache_path
38
  os.environ["HF_HUB_CACHE"] = cache_path
39
  os.environ["HF_HOME"] = cache_path
40
 
41
+ huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
 
 
42
 
43
+ if not path.exists(cache_path):
44
+ os.makedirs(cache_path, exist_ok=True)
45
 
46
+ torch.backends.cuda.matmul.allow_tf32 = True
47
 
48
  class timer:
49
  def __init__(self, method_name="timed process"):
 
55
  end = time.time()
56
  print(f"{self.method} took {str(round(end - self.start, 2))}s")
57
 
58
+ def find_cuda():
59
+ cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')
60
+ if cuda_home and os.path.exists(cuda_home):
61
+ return cuda_home
62
+ nvcc_path = shutil.which('nvcc')
63
+ if nvcc_path:
64
+ cuda_path = os.path.dirname(os.path.dirname(nvcc_path))
65
+ return cuda_path
66
+ return None
67
+
68
+ cuda_path = find_cuda()
69
+ if cuda_path:
70
+ print(f"CUDA installation found at: {cuda_path}")
71
+ else:
72
+ print("CUDA installation not found")
73
+
74
+
75
+ device = torch.device('cuda')
76
+
77
+ base_model = "black-forest-labs/FLUX.1-dev"
78
+ pipe = FluxPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16, token=huggingface_token).to(device)
79
+
80
+ # Load and fuse LoRA BEFORE quantizing
81
+ print('Loading and fusing lora, please wait...')
82
+ lora_path = hf_hub_download("gokaygokay/Flux-Game-Assets-LoRA-v2", "game_asst.safetensors")
83
+ pipe.load_lora_weights(lora_path)
84
+ pipe.fuse_lora(lora_scale=1.0)
85
+ pipe.unload_lora_weights()
86
+
87
+
88
+ # Load 3D generation models
89
+ config_path = 'configs/instant-mesh-large.yaml'
90
+ config = OmegaConf.load(config_path)
91
+ config_name = os.path.basename(config_path).replace('.yaml', '')
92
+ model_config = config.model_config
93
+ infer_config = config.infer_config
94
+
95
+ IS_FLEXICUBES = True if config_name.startswith('instant-mesh') else False
96
+
97
+ # Load diffusion model for 3D generation
98
+ print('Loading diffusion model ...')
99
+ pipeline = DiffusionPipeline.from_pretrained(
100
+ "sudo-ai/zero123plus-v1.2",
101
+ custom_pipeline="zero123plus",
102
+ torch_dtype=torch.float16,
103
+ )
104
+ pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
105
+ pipeline.scheduler.config, timestep_spacing='trailing'
106
+ )
107
 
108
+ # Load custom white-background UNet
109
+ unet_ckpt_path = hf_hub_download(repo_id="TencentARC/InstantMesh", filename="diffusion_pytorch_model.bin", repo_type="model")
110
+ state_dict = torch.load(unet_ckpt_path, map_location='cpu')
111
+ pipeline.unet.load_state_dict(state_dict, strict=True)
112
+
113
+ pipeline = pipeline.to(device)
114
+
115
+ # Load reconstruction model
116
+ print('Loading reconstruction model ...')
117
+ model_ckpt_path = hf_hub_download(repo_id="TencentARC/InstantMesh", filename="instant_mesh_large.ckpt", repo_type="model")
118
+ model = instantiate_from_config(model_config)
119
+ state_dict = torch.load(model_ckpt_path, map_location='cpu')['state_dict']
120
+ state_dict = {k[14:]: v for k, v in state_dict.items() if k.startswith('lrm_generator.') and 'source_camera' not in k}
121
+ model.load_state_dict(state_dict, strict=True)
122
+
123
+ model = model.to(device)
124
+
125
+ print('Loading Finished!')
126
+
127
+ def get_render_cameras(batch_size=1, M=120, radius=2.5, elevation=10.0, is_flexicubes=False):
128
+ c2ws = get_circular_camera_poses(M=M, radius=radius, elevation=elevation)
129
+ if is_flexicubes:
130
+ cameras = torch.linalg.inv(c2ws)
131
+ cameras = cameras.unsqueeze(0).repeat(batch_size, 1, 1, 1)
132
+ else:
133
+ extrinsics = c2ws.flatten(-2)
134
+ intrinsics = FOV_to_intrinsics(50.0).unsqueeze(0).repeat(M, 1, 1).float().flatten(-2)
135
+ cameras = torch.cat([extrinsics, intrinsics], dim=-1)
136
+ cameras = cameras.unsqueeze(0).repeat(batch_size, 1, 1)
137
+ return cameras
138
+
139
+ def preprocess(input_image, do_remove_background):
140
+ rembg_session = rembg.new_session() if do_remove_background else None
141
+ if do_remove_background:
142
+ input_image = remove_background(input_image, rembg_session)
143
+ input_image = resize_foreground(input_image, 0.85)
144
+ return input_image
145
+
146
+ ts_cutoff = 2
147
+
148
+ @spaces.GPU
149
+ def generate_flux_image(prompt, height, width, steps, scales, seed):
150
+ return pipe(
151
+ prompt=prompt,
152
+ width=int(height),
153
+ height=int(width),
154
+ num_inference_steps=int(steps),
155
+ generator=torch.Generator().manual_seed(int(seed)),
156
+ guidance_scale=float(scales),
157
+ timestep_to_start_cfg=ts_cutoff,
158
+ ).images[0]
159
+
160
+
161
+ @spaces.GPU
162
+ def generate_mvs(input_image, sample_steps, sample_seed):
163
+ seed_everything(sample_seed)
164
+ z123_image = pipeline(
165
+ input_image,
166
+ num_inference_steps=sample_steps
167
+ ).images[0]
168
+ show_image = np.asarray(z123_image, dtype=np.uint8)
169
+ show_image = torch.from_numpy(show_image)
170
+ show_image = rearrange(show_image, '(n h) (m w) c -> (n m) h w c', n=3, m=2)
171
+ show_image = rearrange(show_image, '(n m) h w c -> (n h) (m w) c', n=2, m=3)
172
+ show_image = Image.fromarray(show_image.numpy())
173
+ return z123_image, show_image
174
+
175
+ @spaces.GPU
176
+ def make3d(images):
177
+ global model
178
+ if IS_FLEXICUBES:
179
+ model.init_flexicubes_geometry(device, use_renderer=False)
180
+ model = model.eval()
181
+
182
+ images = np.asarray(images, dtype=np.float32) / 255.0
183
+ images = torch.from_numpy(images).permute(2, 0, 1).contiguous().float()
184
+ images = rearrange(images, 'c (n h) (m w) -> (n m) c h w', n=3, m=2)
185
+
186
+ input_cameras = get_zero123plus_input_cameras(batch_size=1, radius=4.0).to(device)
187
+ render_cameras = get_render_cameras(batch_size=1, radius=2.5, is_flexicubes=IS_FLEXICUBES).to(device)
188
+
189
+ images = images.unsqueeze(0).to(device)
190
+ images = v2.functional.resize(images, (320, 320), interpolation=3, antialias=True).clamp(0, 1)
191
+
192
+ mesh_fpath = tempfile.NamedTemporaryFile(suffix=f".obj", delete=False).name
193
+ mesh_basename = os.path.basename(mesh_fpath).split('.')[0]
194
+ mesh_dirname = os.path.dirname(mesh_fpath)
195
+ mesh_glb_fpath = os.path.join(mesh_dirname, f"{mesh_basename}.glb")
196
+
197
+ with torch.no_grad():
198
+ planes = model.forward_planes(images, input_cameras)
199
+ mesh_out = model.extract_mesh(
200
+ planes,
201
+ use_texture_map=False,
202
+ **infer_config,
203
+ )
204
+ vertices, faces, vertex_colors = mesh_out
205
+ vertices = vertices[:, [1, 2, 0]]
206
+ save_glb(vertices, faces, vertex_colors, mesh_glb_fpath)
207
+ save_obj(vertices, faces, vertex_colors, mesh_fpath)
208
+
209
+ return mesh_fpath, mesh_glb_fpath
210
 
211
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
212
  gr.Markdown(
213
  """
214
  <div style="text-align: center; max-width: 650px; margin: 0 auto;">
215
+ <h1 style="font-size: 2.5rem; font-weight: 700; margin-bottom: 1rem;">Flux Image to 3D Model Generator</h1>
 
216
  </div>
217
  """
218
  )
219
 
220
  with gr.Row():
221
  with gr.Column(scale=3):
222
+ prompt = gr.Textbox(
223
+ label="Your Image Description",
224
+ placeholder="E.g., A serene landscape with mountains and a lake at sunset",
225
+ lines=3
226
+ )
227
+
228
+ with gr.Accordion("Advanced Settings", open=False):
229
+ with gr.Group():
230
+ with gr.Row():
231
+ height = gr.Slider(label="Height", minimum=256, maximum=1152, step=64, value=1024)
232
+ width = gr.Slider(label="Width", minimum=256, maximum=1152, step=64, value=1024)
233
+
234
+ with gr.Row():
235
+ steps = gr.Slider(label="Inference Steps", minimum=10, maximum=50, step=1, value=28)
236
+ scales = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=5.0, step=0.1, value=3.5)
237
+
238
+ seed = gr.Number(label="Seed (for reproducibility)", value=3413, precision=0)
239
+
240
+ generate_btn = gr.Button("Generate 3D Model", variant="primary")
 
241
 
242
  with gr.Column(scale=4):
243
+ flux_output = gr.Image(label="Generated Flux Image")
244
+ mv_show_images = gr.Image(label="Generated Multi-views")
245
+ with gr.Row():
246
+ with gr.Tab("OBJ"):
247
+ output_model_obj = gr.Model3D(label="Output Model (OBJ Format)")
248
+ with gr.Tab("GLB"):
249
+ output_model_glb = gr.Model3D(label="Output Model (GLB Format)")
250
+
251
+ mv_images = gr.State()
 
 
 
 
 
 
252
 
253
+ def process_pipeline(prompt, height, width, steps, scales, seed):
254
+ flux_image = generate_flux_image(prompt, height, width, steps, scales, seed)
255
+ processed_image = preprocess(flux_image, do_remove_background=True)
256
+ mv_images, show_image = generate_mvs(processed_image, steps, seed)
257
+ obj_path, glb_path = make3d(mv_images)
258
+ return flux_image, show_image, obj_path, glb_path
 
 
 
 
 
 
 
259
 
260
  generate_btn.click(
261
+ fn=process_pipeline,
262
+ inputs=[prompt, height, width, steps, scales, seed],
263
+ outputs=[flux_output, mv_show_images, output_model_obj, output_model_glb]
264
  )
265
 
266
  if __name__ == "__main__":
267
+ demo.launch()