geyik2 commited on
Commit
4b307b0
·
verified ·
1 Parent(s): 3836717

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -327
app.py DELETED
@@ -1,327 +0,0 @@
1
- import gradio as gr
2
- import spaces
3
- from gradio_litmodel3d import LitModel3D
4
- import os
5
- import shutil
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
14
- import numpy as np
15
- import imageio
16
- from easydict import EasyDict as edict
17
- 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
- # Constants
26
- MAX_SEED = np.iinfo(np.int32).max
27
- TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
28
- os.makedirs(TMP_DIR, exist_ok=True)
29
-
30
- # Create permanent storage directory for Flux generated images
31
- SAVE_DIR = "saved_images"
32
- if not os.path.exists(SAVE_DIR):
33
- os.makedirs(SAVE_DIR, exist_ok=True)
34
-
35
- # Initialize device
36
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
37
-
38
- # Initialize Flux pipeline
39
- flux_pipeline = DiffusionPipeline.from_pretrained(
40
- "black-forest-labs/FLUX.1-dev",
41
- torch_dtype=torch.float16,
42
- variant="fp16",
43
- use_safetensors=True
44
- ).to(device)
45
-
46
- # Initialize TRELLIS pipeline
47
- trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained(
48
- "JeffreyXiang/TRELLIS-image-large",
49
- torch_dtype=torch.float16,
50
- variant="fp16",
51
- use_safetensors=True
52
- ).to(device)
53
-
54
- def start_session(req: gr.Request):
55
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
56
- os.makedirs(user_dir, exist_ok=True)
57
-
58
- def end_session(req: gr.Request):
59
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
60
- shutil.rmtree(user_dir)
61
-
62
- def preprocess_image(image: Image.Image) -> Image.Image:
63
- processed_image = trellis_pipeline.preprocess_image(image)
64
- return processed_image
65
-
66
- def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
67
- return {
68
- 'gaussian': {
69
- **gs.init_params,
70
- '_xyz': gs._xyz.cpu().numpy(),
71
- '_features_dc': gs._features_dc.cpu().numpy(),
72
- '_scaling': gs._scaling.cpu().numpy(),
73
- '_rotation': gs._rotation.cpu().numpy(),
74
- '_opacity': gs._opacity.cpu().numpy(),
75
- },
76
- 'mesh': {
77
- 'vertices': mesh.vertices.cpu().numpy(),
78
- 'faces': mesh.faces.cpu().numpy(),
79
- },
80
- }
81
-
82
- def unpack_state(state: dict) -> Tuple[Gaussian, edict]:
83
- gs = Gaussian(
84
- aabb=state['gaussian']['aabb'],
85
- sh_degree=state['gaussian']['sh_degree'],
86
- mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
87
- scaling_bias=state['gaussian']['scaling_bias'],
88
- opacity_bias=state['gaussian']['opacity_bias'],
89
- scaling_activation=state['gaussian']['scaling_activation'],
90
- )
91
- gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
92
- gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
93
- gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
94
- gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
95
- gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
96
-
97
- mesh = edict(
98
- vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
99
- faces=torch.tensor(state['mesh']['faces'], device='cuda'),
100
- )
101
-
102
- return gs, mesh
103
-
104
- def get_seed(randomize_seed: bool, seed: int) -> int:
105
- return np.random.randint(0, MAX_SEED) if randomize_seed else seed
106
-
107
- @spaces.GPU
108
- def generate_flux_image(
109
- prompt: str,
110
- seed: int,
111
- randomize_seed: bool,
112
- width: int,
113
- height: int,
114
- guidance_scale: float,
115
- progress: gr.Progress = gr.Progress(track_tqdm=True),
116
- ) -> Image.Image:
117
- """Generate image using Flux pipeline"""
118
- if randomize_seed:
119
- seed = random.randint(0, MAX_SEED)
120
- generator = torch.Generator(device=device).manual_seed(seed)
121
- prompt = "wbgmsst, " + prompt + ", 3D isometric, white background"
122
- image = flux_pipeline(
123
- prompt=prompt,
124
- guidance_scale=guidance_scale,
125
- num_inference_steps=NUM_INFERENCE_STEPS,
126
- width=width,
127
- height=height,
128
- generator=generator,
129
- ).images[0]
130
-
131
- # Save the generated image
132
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
133
- unique_id = str(uuid.uuid4())[:8]
134
- filename = f"{timestamp}_{unique_id}.png"
135
- filepath = os.path.join(SAVE_DIR, filename)
136
- image.save(filepath)
137
-
138
- return image
139
-
140
- @spaces.GPU
141
- def image_to_3d(
142
- image: Image.Image,
143
- seed: int,
144
- ss_guidance_strength: float,
145
- ss_sampling_steps: int,
146
- slat_guidance_strength: float,
147
- slat_sampling_steps: int,
148
- req: gr.Request,
149
- ) -> Tuple[dict, str]:
150
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
151
- outputs = trellis_pipeline.run(
152
- image,
153
- seed=seed,
154
- formats=["gaussian", "mesh"],
155
- preprocess_image=False,
156
- sparse_structure_sampler_params={
157
- "steps": ss_sampling_steps,
158
- "cfg_strength": ss_guidance_strength,
159
- },
160
- slat_sampler_params={
161
- "steps": slat_sampling_steps,
162
- "cfg_strength": slat_guidance_strength,
163
- },
164
- )
165
- video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
166
- video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
167
- video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
168
- video_path = os.path.join(user_dir, 'sample.mp4')
169
- imageio.mimsave(video_path, video, fps=15)
170
- state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
171
- torch.cuda.empty_cache()
172
- return state, video_path
173
-
174
- @spaces.GPU(duration=90)
175
- def extract_glb(
176
- state: dict,
177
- mesh_simplify: float,
178
- texture_size: int,
179
- req: gr.Request,
180
- ) -> Tuple[str, str]:
181
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
182
- gs, mesh = unpack_state(state)
183
- glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
184
- glb_path = os.path.join(user_dir, 'sample.glb')
185
- glb.export(glb_path)
186
- torch.cuda.empty_cache()
187
- return glb_path, glb_path
188
-
189
- @spaces.GPU
190
- def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
191
- user_dir = os.path.join(TMP_DIR, str(req.session_hash))
192
- gs, _ = unpack_state(state)
193
- gaussian_path = os.path.join(user_dir, 'sample.ply')
194
- gs.save_ply(gaussian_path)
195
- torch.cuda.empty_cache()
196
- return gaussian_path, gaussian_path
197
-
198
- # Gradio Interface
199
- with gr.Blocks() as demo:
200
- gr.Markdown("""
201
- ## Game Asset Generation to 3D with FLUX and TRELLIS
202
- * Enter a prompt to generate a game asset image, then convert it to 3D
203
- * If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.
204
- * [TRELLIS Model](https://huggingface.co/JeffreyXiang/TRELLIS-image-large) [Trellis Github](https://github.com/microsoft/TRELLIS) [Flux-Dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)
205
- * [Flux Game Assets LoRA](https://huggingface.co/gokaygokay/Flux-Game-Assets-LoRA-v2) [Hyper FLUX 8Steps LoRA](https://huggingface.co/ByteDance/Hyper-SD) [safetensors to GGUF for Flux](https://github.com/ruSauron/to-gguf-bat) [Thanks to John6666](https://huggingface.co/John6666)
206
- """)
207
-
208
- with gr.Row():
209
- with gr.Column():
210
- # Flux image generation inputs
211
- prompt = gr.Text(label="Prompt", placeholder="Enter your game asset description")
212
-
213
- with gr.Accordion("Generation Settings", open=False):
214
- seed = gr.Slider(0, MAX_SEED, label="Seed", value=42, step=1)
215
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
216
- with gr.Row():
217
- width = gr.Slider(512, 1024, label="Width", value=1024, step=16)
218
- height = gr.Slider(512, 1024, label="Height", value=1024, step=16)
219
- with gr.Row():
220
- guidance_scale = gr.Slider(0.0, 10.0, label="Guidance Scale", value=3.5, step=0.1)
221
- # num_inference_steps = gr.Slider(1, 50, label="Steps", value=8, step=1)
222
-
223
- with gr.Accordion("3D Generation Settings", open=False):
224
- gr.Markdown("Stage 1: Sparse Structure Generation")
225
- with gr.Row():
226
- ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
227
- ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
228
- gr.Markdown("Stage 2: Structured Latent Generation")
229
- with gr.Row():
230
- slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
231
- slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
232
-
233
- generate_btn = gr.Button("Generate")
234
-
235
- with gr.Accordion("GLB Extraction Settings", open=False):
236
- mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
237
- texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
238
-
239
- with gr.Row():
240
- extract_glb_btn = gr.Button("Extract GLB", interactive=False)
241
- extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
242
-
243
- with gr.Column():
244
- generated_image = gr.Image(label="Generated Asset", type="pil")
245
-
246
- with gr.Column():
247
-
248
- video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True)
249
- model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=8.0, height=400)
250
-
251
- with gr.Row():
252
- download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
253
- download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
254
-
255
- output_buf = gr.State()
256
-
257
- # Event handlers
258
- demo.load(start_session)
259
- demo.unload(end_session)
260
-
261
- generate_btn.click(
262
- generate_flux_image,
263
- inputs=[prompt, seed, randomize_seed, width, height, guidance_scale],
264
- outputs=[generated_image],
265
- ).then(
266
- image_to_3d,
267
- inputs=[generated_image, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],
268
- outputs=[output_buf, video_output],
269
- ).then(
270
- lambda: (True, True),
271
- outputs=[extract_glb_btn, extract_gs_btn]
272
- )
273
-
274
- extract_glb_btn.click(
275
- extract_glb,
276
- inputs=[output_buf, mesh_simplify, texture_size],
277
- outputs=[model_output, download_glb]
278
- ).then(
279
- lambda: True,
280
- outputs=[download_glb]
281
- )
282
-
283
- extract_gs_btn.click(
284
- extract_gaussian,
285
- inputs=[output_buf],
286
- outputs=[model_output, download_gs]
287
- ).then(
288
- lambda: True,
289
- outputs=[download_gs]
290
- )
291
-
292
- model_output.clear(
293
- lambda: gr.Button(interactive=False),
294
- outputs=[download_glb],
295
- )
296
-
297
- # Initialize both pipelines
298
- if __name__ == "__main__":
299
- from diffusers import FluxTransformer2DModel, FluxPipeline, BitsAndBytesConfig, GGUFQuantizationConfig
300
- from transformers import T5EncoderModel, BitsAndBytesConfig as BitsAndBytesConfigTF
301
-
302
- # Initialize Flux pipeline
303
- device = "cuda" if torch.cuda.is_available() else "cpu"
304
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
305
-
306
- dtype = torch.bfloat16
307
- file_url = "https://huggingface.co/gokaygokay/flux-game/blob/main/hyperflux_00001_.q8_0.gguf"
308
- file_url = file_url.replace("/resolve/main/", "/blob/main/").replace("?download=true", "")
309
- single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
310
- quantization_config_tf = BitsAndBytesConfigTF(load_in_8bit=True, bnb_8bit_compute_dtype=torch.bfloat16)
311
- 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)
312
- if ".gguf" in file_url:
313
- transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", quantization_config=GGUFQuantizationConfig(compute_dtype=dtype), torch_dtype=dtype, config=single_file_base_model)
314
- else:
315
- 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)
316
- transformer = FluxTransformer2DModel.from_single_file(file_url, subfolder="transformer", torch_dtype=dtype, config=single_file_base_model, quantization_config=quantization_config, token=huggingface_token)
317
- flux_pipeline = FluxPipeline.from_pretrained(single_file_base_model, transformer=transformer, text_encoder_2=text_encoder_2, torch_dtype=dtype, token=huggingface_token)
318
- flux_pipeline.to("cuda")
319
- # Initialize Trellis pipeline
320
- trellis_pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
321
- trellis_pipeline.cuda()
322
- try:
323
- trellis_pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8)))
324
- except:
325
- pass
326
-
327
- demo.queue(max_size=10).launch()