lionelgarnier commited on
Commit
e69d279
·
1 Parent(s): d4c4c25

change to flux

Browse files
Files changed (2) hide show
  1. app.py +109 -299
  2. requirements.txt +5 -1
app.py CHANGED
@@ -1,312 +1,122 @@
1
  import gradio as gr
 
 
2
  import spaces
3
- from gradio_litmodel3d import LitModel3D
4
-
5
- import os
6
- import shutil
7
- os.environ['SPCONV_ALGO'] = 'native'
8
- from typing import *
9
  import torch
10
- import numpy as np
11
- import imageio
12
- from easydict import EasyDict as edict
13
- from PIL import Image
14
- from trellis.pipelines import TrellisImageTo3DPipeline
15
- from trellis.representations import Gaussian, MeshExtractResult
16
- from trellis.utils import render_utils, postprocessing_utils
17
-
18
-
19
- MAX_SEED = np.iinfo(np.int32).max
20
- TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp')
21
- # os.makedirs(TMP_DIR, exist_ok=True)
22
-
23
-
24
- # def start_session(req: gr.Request):
25
- # gr.Warning('start start session')
26
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
27
- # os.makedirs(user_dir, exist_ok=True)
28
- # gr.Warning('end start session')
29
-
30
-
31
- # def end_session(req: gr.Request):
32
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
33
- # shutil.rmtree(user_dir)
34
-
35
-
36
- # def preprocess_image(image: Image.Image) -> Image.Image:
37
- # """
38
- # Preprocess the input image.
39
-
40
- # Args:
41
- # image (Image.Image): The input image.
42
-
43
- # Returns:
44
- # Image.Image: The preprocessed image.
45
- # """
46
- # processed_image = pipeline.preprocess_image(image)
47
- # return processed_image
48
-
49
-
50
- # def pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:
51
- # return {
52
- # 'gaussian': {
53
- # **gs.init_params,
54
- # '_xyz': gs._xyz.cpu().numpy(),
55
- # '_features_dc': gs._features_dc.cpu().numpy(),
56
- # '_scaling': gs._scaling.cpu().numpy(),
57
- # '_rotation': gs._rotation.cpu().numpy(),
58
- # '_opacity': gs._opacity.cpu().numpy(),
59
- # },
60
- # 'mesh': {
61
- # 'vertices': mesh.vertices.cpu().numpy(),
62
- # 'faces': mesh.faces.cpu().numpy(),
63
- # },
64
- # }
65
-
66
-
67
- # def unpack_state(state: dict) -> Tuple[Gaussian, edict, str]:
68
- # gs = Gaussian(
69
- # aabb=state['gaussian']['aabb'],
70
- # sh_degree=state['gaussian']['sh_degree'],
71
- # mininum_kernel_size=state['gaussian']['mininum_kernel_size'],
72
- # scaling_bias=state['gaussian']['scaling_bias'],
73
- # opacity_bias=state['gaussian']['opacity_bias'],
74
- # scaling_activation=state['gaussian']['scaling_activation'],
75
- # )
76
- # gs._xyz = torch.tensor(state['gaussian']['_xyz'], device='cuda')
77
- # gs._features_dc = torch.tensor(state['gaussian']['_features_dc'], device='cuda')
78
- # gs._scaling = torch.tensor(state['gaussian']['_scaling'], device='cuda')
79
- # gs._rotation = torch.tensor(state['gaussian']['_rotation'], device='cuda')
80
- # gs._opacity = torch.tensor(state['gaussian']['_opacity'], device='cuda')
81
-
82
- # mesh = edict(
83
- # vertices=torch.tensor(state['mesh']['vertices'], device='cuda'),
84
- # faces=torch.tensor(state['mesh']['faces'], device='cuda'),
85
- # )
86
-
87
- # return gs, mesh
88
-
89
-
90
- # def get_seed(randomize_seed: bool, seed: int) -> int:
91
- # """
92
- # Get the random seed.
93
- # """
94
- # return np.random.randint(0, MAX_SEED) if randomize_seed else seed
95
-
96
-
97
- # @spaces.GPU
98
- # def image_to_3d(
99
- # image: Image.Image,
100
- # seed: int,
101
- # ss_guidance_strength: float,
102
- # ss_sampling_steps: int,
103
- # slat_guidance_strength: float,
104
- # slat_sampling_steps: int,
105
- # req: gr.Request,
106
- # ) -> Tuple[dict, str]:
107
- # """
108
- # Convert an image to a 3D model.
109
-
110
- # Args:
111
- # image (Image.Image): The input image.
112
- # seed (int): The random seed.
113
- # ss_guidance_strength (float): The guidance strength for sparse structure generation.
114
- # ss_sampling_steps (int): The number of sampling steps for sparse structure generation.
115
- # slat_guidance_strength (float): The guidance strength for structured latent generation.
116
- # slat_sampling_steps (int): The number of sampling steps for structured latent generation.
117
-
118
- # Returns:
119
- # dict: The information of the generated 3D model.
120
- # str: The path to the video of the 3D model.
121
- # """
122
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
123
- # outputs = pipeline.run(
124
- # image,
125
- # seed=seed,
126
- # formats=["gaussian", "mesh"],
127
- # preprocess_image=False,
128
- # sparse_structure_sampler_params={
129
- # "steps": ss_sampling_steps,
130
- # "cfg_strength": ss_guidance_strength,
131
- # },
132
- # slat_sampler_params={
133
- # "steps": slat_sampling_steps,
134
- # "cfg_strength": slat_guidance_strength,
135
- # },
136
- # )
137
- # video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']
138
- # video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']
139
- # video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]
140
- # video_path = os.path.join(user_dir, 'sample.mp4')
141
- # imageio.mimsave(video_path, video, fps=15)
142
- # state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])
143
- # torch.cuda.empty_cache()
144
- # return state, video_path
145
 
 
 
146
 
147
- # @spaces.GPU(duration=90)
148
- # def extract_glb(
149
- # state: dict,
150
- # mesh_simplify: float,
151
- # texture_size: int,
152
- # req: gr.Request,
153
- # ) -> Tuple[str, str]:
154
- # """
155
- # Extract a GLB file from the 3D model.
156
 
157
- # Args:
158
- # state (dict): The state of the generated 3D model.
159
- # mesh_simplify (float): The mesh simplification factor.
160
- # texture_size (int): The texture resolution.
161
-
162
- # Returns:
163
- # str: The path to the extracted GLB file.
164
- # """
165
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
166
- # gs, mesh = unpack_state(state)
167
- # glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)
168
- # glb_path = os.path.join(user_dir, 'sample.glb')
169
- # glb.export(glb_path)
170
- # torch.cuda.empty_cache()
171
- # return glb_path, glb_path
172
-
173
-
174
- # @spaces.GPU
175
- # def extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:
176
- # """
177
- # Extract a Gaussian file from the 3D model.
178
-
179
- # Args:
180
- # state (dict): The state of the generated 3D model.
181
-
182
- # Returns:
183
- # str: The path to the extracted Gaussian file.
184
- # """
185
- # user_dir = os.path.join(TMP_DIR, str(req.session_hash))
186
- # gs, _ = unpack_state(state)
187
- # gaussian_path = os.path.join(user_dir, 'sample.ply')
188
- # gs.save_ply(gaussian_path)
189
- # torch.cuda.empty_cache()
190
- # return gaussian_path, gaussian_path
191
-
192
-
193
- # def split_image(image: Image.Image) -> List[Image.Image]:
194
- # """
195
- # Split an image into multiple views.
196
- # """
197
- # image = np.array(image)
198
- # alpha = image[..., 3]
199
- # alpha = np.any(alpha>0, axis=0)
200
- # start_pos = np.where(~alpha[:-1] & alpha[1:])[0].tolist()
201
- # end_pos = np.where(alpha[:-1] & ~alpha[1:])[0].tolist()
202
- # images = []
203
- # for s, e in zip(start_pos, end_pos):
204
- # images.append(Image.fromarray(image[:, s:e+1]))
205
- # return [preprocess_image(image) for image in images]
206
-
207
-
208
- with gr.Blocks(delete_cache=(600, 600)) as demo:
209
- gr.Markdown("""
210
- ## Text to 3D Asset with Mistral + Flux + Trellis
211
- * Upload an image and click "Generate" to create a 3D asset
212
- """)
213
 
214
- with gr.Row():
215
- with gr.Column():
216
- image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=300)
 
 
 
 
217
 
218
- with gr.Accordion(label="Generation Settings", open=False):
219
- seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)
220
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
221
- gr.Markdown("Stage 1: Sparse Structure Generation")
222
- with gr.Row():
223
- ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=7.5, step=0.1)
224
- ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
225
- gr.Markdown("Stage 2: Structured Latent Generation")
226
- with gr.Row():
227
- slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)
228
- slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)
229
-
230
- generate_btn = gr.Button("Generate")
 
 
 
 
 
 
 
 
231
 
232
- with gr.Accordion(label="GLB Extraction Settings", open=False):
233
- mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)
234
- texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)
235
 
236
  with gr.Row():
237
- extract_glb_btn = gr.Button("Extract GLB", interactive=False)
238
- extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)
239
-
240
- with gr.Column():
241
- video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)
242
- model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=10.0, height=300)
 
 
 
 
 
 
 
 
 
 
243
 
244
  with gr.Row():
245
- download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
246
- download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)
247
-
248
- # output_buf = gr.State()
249
-
250
-
251
- # Handlers
252
- # demo.load(start_session)
253
- # demo.unload(end_session)
254
-
255
-
256
- # image_prompt.upload(
257
- # preprocess_image,
258
- # inputs=[image_prompt],
259
- # outputs=[image_prompt],
260
- # )
261
-
262
- # generate_btn.click(
263
- # get_seed,
264
- # inputs=[randomize_seed, seed],
265
- # outputs=[seed],
266
- # ).then(
267
- # image_to_3d,
268
- # inputs=[image_prompt, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],
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
- # extract_glb_btn.click(
281
- # extract_glb,
282
- # inputs=[output_buf, mesh_simplify, texture_size],
283
- # outputs=[model_output, download_glb],
284
- # ).then(
285
- # lambda: gr.Button(interactive=True),
286
- # outputs=[download_glb],
287
- # )
288
-
289
- # extract_gs_btn.click(
290
- # extract_gaussian,
291
- # inputs=[output_buf],
292
- # outputs=[model_output, download_gs],
293
- # ).then(
294
- # lambda: gr.Button(interactive=True),
295
- # outputs=[download_gs],
296
- # )
297
-
298
- # model_output.clear(
299
- # lambda: gr.Button(interactive=False),
300
- # outputs=[download_glb],
301
- # )
302
-
303
-
304
- # Launch the Gradio app
305
- if __name__ == "__main__":
306
- pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large")
307
- pipeline.cuda()
308
- # try:
309
- # pipeline.preprocess_image(Image.fromarray(np.zeros((512, 512, 3), dtype=np.uint8))) # Preload rembg
310
- # except:
311
- # pass
312
- demo.launch()
 
1
  import gradio as gr
2
+ import numpy as np
3
+ import random
4
  import spaces
 
 
 
 
 
 
5
  import torch
6
+ from diffusers import DiffusionPipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ dtype = torch.bfloat16
9
+ device = "cuda" if torch.cuda.is_available() else "cpu"
10
 
11
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to(device)
 
 
 
 
 
 
 
 
12
 
13
+ MAX_SEED = np.iinfo(np.int32).max
14
+ MAX_IMAGE_SIZE = 2048
15
+
16
+ @spaces.GPU()
17
+ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
18
+ if randomize_seed:
19
+ seed = random.randint(0, MAX_SEED)
20
+ generator = torch.Generator().manual_seed(seed)
21
+ image = pipe(
22
+ prompt = prompt,
23
+ width = width,
24
+ height = height,
25
+ num_inference_steps = num_inference_steps,
26
+ generator = generator,
27
+ guidance_scale=0.0
28
+ ).images[0]
29
+ return image, seed
30
+
31
+ examples = [
32
+ "a tiny astronaut hatching from an egg on the moon",
33
+ "a cat holding a sign that says hello world",
34
+ "an anime illustration of a wiener schnitzel",
35
+ ]
36
+
37
+ css="""
38
+ #col-container {
39
+ margin: 0 auto;
40
+ max-width: 520px;
41
+ }
42
+ """
43
+
44
+ with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ with gr.Column(elem_id="col-container"):
47
+ gr.Markdown(f"""# FLUX.1 [schnell]
48
+ 12B param rectified flow transformer distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) for 4 step generation
49
+ [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-schnell)]
50
+ """)
51
+
52
+ with gr.Row():
53
 
54
+ prompt = gr.Text(
55
+ label="Prompt",
56
+ show_label=False,
57
+ max_lines=1,
58
+ placeholder="Enter your prompt",
59
+ container=False,
60
+ )
61
+
62
+ run_button = gr.Button("Run", scale=0)
63
+
64
+ result = gr.Image(label="Result", show_label=False)
65
+
66
+ with gr.Accordion("Advanced Settings", open=False):
67
+
68
+ seed = gr.Slider(
69
+ label="Seed",
70
+ minimum=0,
71
+ maximum=MAX_SEED,
72
+ step=1,
73
+ value=0,
74
+ )
75
 
76
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
77
 
78
  with gr.Row():
79
+
80
+ width = gr.Slider(
81
+ label="Width",
82
+ minimum=256,
83
+ maximum=MAX_IMAGE_SIZE,
84
+ step=32,
85
+ value=1024,
86
+ )
87
+
88
+ height = gr.Slider(
89
+ label="Height",
90
+ minimum=256,
91
+ maximum=MAX_IMAGE_SIZE,
92
+ step=32,
93
+ value=1024,
94
+ )
95
 
96
  with gr.Row():
97
+
98
+
99
+ num_inference_steps = gr.Slider(
100
+ label="Number of inference steps",
101
+ minimum=1,
102
+ maximum=50,
103
+ step=1,
104
+ value=4,
105
+ )
106
+
107
+ gr.Examples(
108
+ examples = examples,
109
+ fn = infer,
110
+ inputs = [prompt],
111
+ outputs = [result, seed],
112
+ cache_examples="lazy"
113
+ )
114
+
115
+ gr.on(
116
+ triggers=[run_button.click, prompt.submit],
117
+ fn = infer,
118
+ inputs = [prompt, seed, randomize_seed, width, height, num_inference_steps],
119
+ outputs = [result, seed]
120
+ )
121
+
122
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -23,4 +23,8 @@ transformers==4.46.3
23
  gradio_litmodel3d==0.0.1
24
  https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.0.post2/flash_attn-2.7.0.post2+cu12torch2.4cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
25
  https://huggingface.co/spaces/JeffreyXiang/TRELLIS/resolve/main/wheels/diff_gaussian_rasterization-0.0.0-cp310-cp310-linux_x86_64.whl?download=true
26
- https://huggingface.co/spaces/JeffreyXiang/TRELLIS/resolve/main/wheels/nvdiffrast-0.3.3-cp310-cp310-linux_x86_64.whl?download=true
 
 
 
 
 
23
  gradio_litmodel3d==0.0.1
24
  https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.0.post2/flash_attn-2.7.0.post2+cu12torch2.4cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
25
  https://huggingface.co/spaces/JeffreyXiang/TRELLIS/resolve/main/wheels/diff_gaussian_rasterization-0.0.0-cp310-cp310-linux_x86_64.whl?download=true
26
+ https://huggingface.co/spaces/JeffreyXiang/TRELLIS/resolve/main/wheels/nvdiffrast-0.3.3-cp310-cp310-linux_x86_64.whl?download=true
27
+ accelerate
28
+ git+https://github.com/huggingface/diffusers.git
29
+ invisible_watermark
30
+ sentencepiece