wyysf commited on
Commit
3734a92
β€’
1 Parent(s): 28e43fe

Upload gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +77 -47
gradio_app.py CHANGED
@@ -12,9 +12,6 @@ from huggingface_hub import hf_hub_download
12
 
13
  from collections import OrderedDict
14
  import trimesh
15
- from einops import repeat, rearrange
16
- import pytorch_lightning as pl
17
- from typing import Dict, Optional, Tuple, List
18
  import gradio as gr
19
  from typing import Any
20
 
@@ -22,12 +19,8 @@ proj_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
  sys.path.append(os.path.join(proj_dir))
23
 
24
  import tempfile
25
- import craftsman
26
- from craftsman.systems.base import BaseSystem
27
- from craftsman.utils.config import ExperimentConfig, load_config
28
 
29
  from apps.utils import *
30
- from apps.mv_models import GenMVImage
31
 
32
  _TITLE = '''CraftsMan: High-fidelity Mesh Generation with 3D Native Generation and Interactive Geometry Refiner'''
33
  _DESCRIPTION = '''
@@ -64,6 +57,8 @@ CraftsMan is under [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.en.html), so
64
  If you have any questions, feel free to open a discussion or contact us at <b>weiyuli.cn@gmail.com</b>.
65
  """
66
  from apps.third_party.CRM.pipelines import TwoStagePipeline
 
 
67
 
68
  model = None
69
  cached_dir = None
@@ -74,17 +69,43 @@ stage1_model_config.resume = hf_hub_download(repo_id="Zhengyi/CRM", filename="pi
74
  stage1_model_config.config = f"{parent_dir}/apps/third_party/CRM/" + stage1_model_config.config
75
  crm_pipeline = None
76
 
 
 
 
 
 
77
  @spaces.GPU
78
  def gen_mvimg(
79
- mvimg_model, text, image, crop_size, seed, guidance_scale, step
80
  ):
81
- global crm_pipeline
82
  if seed == 0:
83
  seed = np.random.randint(1, 65535)
84
- crm_pipeline.set_seed(seed)
85
- rt_dict = crm_pipeline(image, scale=guidance_scale, step=step)
86
- mv_imgs = rt_dict["stage1_images"]
87
- return mv_imgs[5], mv_imgs[3], mv_imgs[2], mv_imgs[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  @spaces.GPU
90
  def image2mesh(view_front: np.ndarray,
@@ -153,22 +174,27 @@ if __name__=="__main__":
153
  device = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu")
154
  print(f"using device: {device}")
155
 
 
 
 
 
 
 
 
156
  crm_pipeline = TwoStagePipeline(
157
  stage1_model_config,
158
  stage1_sampler_config,
159
  device=device,
160
  dtype=torch.float16
161
  )
 
 
 
 
 
 
 
162
 
163
- # for multi-view images generation
164
- background_choice = OrderedDict({
165
- "Alpha as Mask": "Alpha as Mask",
166
- "Auto Remove Background": "Auto Remove Background",
167
- "Original Image": "Original Image",
168
- })
169
- mvimg_model_config_list = ["CRM"]
170
- # mvimg_model_config_list = ["CRM", "ImageDream", "Wonder3D"]
171
-
172
  # for 3D latent set diffusion
173
  ckpt_path = "./ckpts/image-to-shape-diffusion/clip-mvrgb-modln-l256-e64-ne8-nd16-nl6/model.ckpt"
174
  config_path = "./ckpts/image-to-shape-diffusion/clip-mvrgb-modln-l256-e64-ne8-nd16-nl6/config.yaml"
@@ -196,24 +222,33 @@ if __name__=="__main__":
196
 
197
  with gr.Row():
198
  with gr.Column(scale=2):
 
 
 
 
 
 
 
 
 
 
 
199
  with gr.Row():
200
- image_input = gr.Image(
201
- label="Image Input",
202
- image_mode="RGBA",
203
- sources="upload",
204
- type="pil",
205
- )
206
- with gr.Row():
207
- text = gr.Textbox(label="Prompt (Optional, only works for mvdream)", visible=False)
208
- with gr.Row():
209
- gr.Markdown('''Try a different <b>seed</b> if the result is unsatisfying. Good Luck :)''')
210
  with gr.Row():
211
  seed = gr.Number(0, label='Seed', show_label=True)
 
212
  more = gr.CheckboxGroup(["Remesh", "Symmetry(TBD)"], label="More", show_label=False)
213
- # remesh = gr.Checkbox(value=False, label='Remesh')
214
- # symmetry = gr.Checkbox(value=False, label='Symmetry(TBD)', interactive=False)
215
- run_btn = gr.Button('Generate', variant='primary', interactive=True)
216
-
 
 
 
 
 
 
217
  with gr.Row():
218
  gr.Examples(
219
  examples=[os.path.join("./apps/examples", i) for i in os.listdir("./apps/examples")],
@@ -243,10 +278,6 @@ if __name__=="__main__":
243
  run_3d_btn = gr.Button('Only Generate 3D', interactive=True)
244
 
245
  with gr.Accordion('Advanced options (2D)', open=False):
246
- with gr.Row():
247
- crop_size = gr.Number(224, label='Crop size')
248
- mvimg_model = gr.Dropdown(value="CRM", label="MV Image Model", choices=mvimg_model_config_list)
249
-
250
  with gr.Row():
251
  foreground_ratio = gr.Slider(
252
  label="Foreground Ratio",
@@ -259,11 +290,11 @@ if __name__=="__main__":
259
  with gr.Row():
260
  background_choice = gr.Dropdown(label="Backgroud Choice", value="Auto Remove Background",choices=list(background_choice.keys()))
261
  rmbg_type = gr.Dropdown(label="Backgroud Remove Type", value="rembg",choices=['sam', "rembg"])
262
- # backgroud_color = gr.ColorPicker(label="Background Color", value="#FFFFFF", interactive=True)
263
- backgroud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=True)
264
 
265
  with gr.Row():
266
- mvimg_guidance_scale = gr.Number(value=3.5, minimum=3, maximum=10, label="2D Guidance Scale")
267
  mvimg_steps = gr.Number(value=30, minimum=20, maximum=100, label="2D Sample Steps")
268
 
269
  with gr.Accordion('Advanced options (3D)', open=False):
@@ -280,17 +311,16 @@ if __name__=="__main__":
280
  outputs = [output_model_obj]
281
  rmbg = RMBG(device)
282
 
283
- # gen_mvimg = GenMVImage(device)
284
  model = load_model(ckpt_path, config_path, device)
285
 
286
  run_btn.click(fn=check_input_image, inputs=[image_input]
287
  ).success(
288
  fn=rmbg.run,
289
- inputs=[rmbg_type, image_input, crop_size, foreground_ratio, background_choice, backgroud_color],
290
  outputs=[image_input]
291
  ).success(
292
  fn=gen_mvimg,
293
- inputs=[mvimg_model, text, image_input, crop_size, seed, mvimg_guidance_scale, mvimg_steps],
294
  outputs=[view_front, view_right, view_back, view_left]
295
  ).success(
296
  fn=image2mesh,
@@ -298,7 +328,7 @@ if __name__=="__main__":
298
  outputs=outputs,
299
  api_name="generate_img2obj")
300
  run_mv_btn.click(fn=gen_mvimg,
301
- inputs=[mvimg_model, text, image_input, crop_size, seed, mvimg_guidance_scale, mvimg_steps],
302
  outputs=[view_front, view_right, view_back, view_left]
303
  )
304
  run_3d_btn.click(fn=image2mesh,
 
12
 
13
  from collections import OrderedDict
14
  import trimesh
 
 
 
15
  import gradio as gr
16
  from typing import Any
17
 
 
19
  sys.path.append(os.path.join(proj_dir))
20
 
21
  import tempfile
 
 
 
22
 
23
  from apps.utils import *
 
24
 
25
  _TITLE = '''CraftsMan: High-fidelity Mesh Generation with 3D Native Generation and Interactive Geometry Refiner'''
26
  _DESCRIPTION = '''
 
57
  If you have any questions, feel free to open a discussion or contact us at <b>weiyuli.cn@gmail.com</b>.
58
  """
59
  from apps.third_party.CRM.pipelines import TwoStagePipeline
60
+ from apps.third_party.LGM.pipeline_mvdream import MVDreamPipeline
61
+
62
 
63
  model = None
64
  cached_dir = None
 
69
  stage1_model_config.config = f"{parent_dir}/apps/third_party/CRM/" + stage1_model_config.config
70
  crm_pipeline = None
71
 
72
+ sys.path.append(f"apps/third_party/LGM")
73
+ imgaedream_pipeline = None
74
+
75
+ generator = None
76
+
77
  @spaces.GPU
78
  def gen_mvimg(
79
+ mvimg_model, image, seed, guidance_scale, step, text, neg_text, elevation,
80
  ):
 
81
  if seed == 0:
82
  seed = np.random.randint(1, 65535)
83
+
84
+ if mvimg_model == "CRM":
85
+ global crm_pipeline
86
+ crm_pipeline.set_seed(seed)
87
+ mv_imgs = crm_pipeline(
88
+ image,
89
+ scale=guidance_scale,
90
+ step=step
91
+ )["stage1_images"]
92
+ return mv_imgs[5], mv_imgs[3], mv_imgs[2], mv_imgs[0]
93
+
94
+ elif mvimg_model == "ImageDream":
95
+ global imagedream_pipeline, generator
96
+ image = np.array(image).astype(np.float32) / 255.0
97
+ image = image[..., :3] * image[..., 3:4] + (1 - image[..., 3:4])
98
+ mv_imgs = imagedream_pipeline(
99
+ text,
100
+ image,
101
+ negative_prompt=neg_text,
102
+ guidance_scale=guidance_scale,
103
+ num_inference_steps=step,
104
+ elevation=elevation,
105
+ generator=generator.manual_seed(seed),
106
+ )
107
+ return mv_imgs[1], mv_imgs[2], mv_imgs[3], mv_imgs[0]
108
+
109
 
110
  @spaces.GPU
111
  def image2mesh(view_front: np.ndarray,
 
174
  device = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu")
175
  print(f"using device: {device}")
176
 
177
+ # for multi-view images generation
178
+ background_choice = OrderedDict({
179
+ "Alpha as Mask": "Alpha as Mask",
180
+ "Auto Remove Background": "Auto Remove Background",
181
+ "Original Image": "Original Image",
182
+ })
183
+ mvimg_model_config_list = ["CRM", "ImageDream"]
184
  crm_pipeline = TwoStagePipeline(
185
  stage1_model_config,
186
  stage1_sampler_config,
187
  device=device,
188
  dtype=torch.float16
189
  )
190
+ imagedream_pipeline = MVDreamPipeline.from_pretrained(
191
+ "ashawkey/imagedream-ipmv-diffusers", # remote weights
192
+ torch_dtype=torch.float16,
193
+ trust_remote_code=True,
194
+ )
195
+ generator = torch.Generator(device)
196
+
197
 
 
 
 
 
 
 
 
 
 
198
  # for 3D latent set diffusion
199
  ckpt_path = "./ckpts/image-to-shape-diffusion/clip-mvrgb-modln-l256-e64-ne8-nd16-nl6/model.ckpt"
200
  config_path = "./ckpts/image-to-shape-diffusion/clip-mvrgb-modln-l256-e64-ne8-nd16-nl6/config.yaml"
 
222
 
223
  with gr.Row():
224
  with gr.Column(scale=2):
225
+ with gr.Column():
226
+ # input image
227
+ with gr.Row():
228
+ image_input = gr.Image(
229
+ label="Image Input",
230
+ image_mode="RGBA",
231
+ sources="upload",
232
+ type="pil",
233
+ )
234
+ run_btn = gr.Button('Generate', variant='primary', interactive=True)
235
+
236
  with gr.Row():
237
+ gr.Markdown('''Try a different <b>seed and MV Model</b> for better results. Good Luck :)''')
 
 
 
 
 
 
 
 
 
238
  with gr.Row():
239
  seed = gr.Number(0, label='Seed', show_label=True)
240
+ mvimg_model = gr.Dropdown(value="CRM", label="MV Image Model", choices=list(mvimg_model_config_list))
241
  more = gr.CheckboxGroup(["Remesh", "Symmetry(TBD)"], label="More", show_label=False)
242
+ with gr.Row():
243
+ # input prompt
244
+ text = gr.Textbox(label="Prompt (Opt.)", info="only works for ImageDream")
245
+
246
+ with gr.Accordion('Advanced options', open=False):
247
+ # negative prompt
248
+ neg_text = gr.Textbox(label="Negative Prompt", value='ugly, blurry, pixelated obscure, unnatural colors, poor lighting, dull, unclear, cropped, lowres, low quality, artifacts, duplicate')
249
+ # elevation
250
+ elevation = gr.Slider(label="elevation", minimum=-90, maximum=90, step=1, value=0)
251
+
252
  with gr.Row():
253
  gr.Examples(
254
  examples=[os.path.join("./apps/examples", i) for i in os.listdir("./apps/examples")],
 
278
  run_3d_btn = gr.Button('Only Generate 3D', interactive=True)
279
 
280
  with gr.Accordion('Advanced options (2D)', open=False):
 
 
 
 
281
  with gr.Row():
282
  foreground_ratio = gr.Slider(
283
  label="Foreground Ratio",
 
290
  with gr.Row():
291
  background_choice = gr.Dropdown(label="Backgroud Choice", value="Auto Remove Background",choices=list(background_choice.keys()))
292
  rmbg_type = gr.Dropdown(label="Backgroud Remove Type", value="rembg",choices=['sam', "rembg"])
293
+ backgroud_color = gr.ColorPicker(label="Background Color", value="#FFFFFF", interactive=True)
294
+ # backgroud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=True)
295
 
296
  with gr.Row():
297
+ mvimg_guidance_scale = gr.Number(value=4.0, minimum=3, maximum=10, label="2D Guidance Scale")
298
  mvimg_steps = gr.Number(value=30, minimum=20, maximum=100, label="2D Sample Steps")
299
 
300
  with gr.Accordion('Advanced options (3D)', open=False):
 
311
  outputs = [output_model_obj]
312
  rmbg = RMBG(device)
313
 
 
314
  model = load_model(ckpt_path, config_path, device)
315
 
316
  run_btn.click(fn=check_input_image, inputs=[image_input]
317
  ).success(
318
  fn=rmbg.run,
319
+ inputs=[rmbg_type, image_input, foreground_ratio, background_choice, backgroud_color],
320
  outputs=[image_input]
321
  ).success(
322
  fn=gen_mvimg,
323
+ inputs=[mvimg_model, image_input, seed, mvimg_guidance_scale, mvimg_steps, text, neg_text, elevation],
324
  outputs=[view_front, view_right, view_back, view_left]
325
  ).success(
326
  fn=image2mesh,
 
328
  outputs=outputs,
329
  api_name="generate_img2obj")
330
  run_mv_btn.click(fn=gen_mvimg,
331
+ inputs=[mvimg_model, image_input, seed, mvimg_guidance_scale, mvimg_steps, text, neg_text, elevation],
332
  outputs=[view_front, view_right, view_back, view_left]
333
  )
334
  run_3d_btn.click(fn=image2mesh,