Mariam-Elz commited on
Commit
200bf7b
·
verified ·
1 Parent(s): ceaec8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +294 -232
app.py CHANGED
@@ -1,237 +1,299 @@
1
- # Not ready to use yet
2
- import spaces
3
- import argparse
4
- import numpy as np
5
- import gradio as gr
6
- from omegaconf import OmegaConf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import torch
8
- from PIL import Image
9
- import PIL
10
- from pipelines import TwoStagePipeline
11
- from huggingface_hub import hf_hub_download
12
- import os
13
- import rembg
14
- from typing import Any
15
- import json
16
  import os
17
- import json
18
- import argparse
19
-
20
- from model import CRM
21
- from inference import generate3d
22
-
23
- pipeline = None
24
- rembg_session = rembg.new_session()
25
-
26
-
27
- def expand_to_square(image, bg_color=(0, 0, 0, 0)):
28
- # expand image to 1:1
29
- width, height = image.size
30
- if width == height:
31
- return image
32
- new_size = (max(width, height), max(width, height))
33
- new_image = Image.new("RGBA", new_size, bg_color)
34
- paste_position = ((new_size[0] - width) // 2, (new_size[1] - height) // 2)
35
- new_image.paste(image, paste_position)
36
- return new_image
37
-
38
- def check_input_image(input_image):
39
- if input_image is None:
40
- raise gr.Error("No image uploaded!")
41
-
42
-
43
- def remove_background(
44
- image: PIL.Image.Image,
45
- rembg_session: Any = None,
46
- force: bool = False,
47
- **rembg_kwargs,
48
- ) -> PIL.Image.Image:
49
- do_remove = True
50
- if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
51
- # explain why current do not rm bg
52
- print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
53
- background = Image.new("RGBA", image.size, (0, 0, 0, 0))
54
- image = Image.alpha_composite(background, image)
55
- do_remove = False
56
- do_remove = do_remove or force
57
- if do_remove:
58
- image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
59
- return image
60
-
61
- def do_resize_content(original_image: Image, scale_rate):
62
- # resize image content wile retain the original image size
63
- if scale_rate != 1:
64
- # Calculate the new size after rescaling
65
- new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
66
- # Resize the image while maintaining the aspect ratio
67
- resized_image = original_image.resize(new_size)
68
- # Create a new image with the original size and black background
69
- padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
70
- paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
71
- padded_image.paste(resized_image, paste_position)
72
- return padded_image
73
- else:
74
- return original_image
75
-
76
- def add_background(image, bg_color=(255, 255, 255)):
77
- # given an RGBA image, alpha channel is used as mask to add background color
78
- background = Image.new("RGBA", image.size, bg_color)
79
- return Image.alpha_composite(background, image)
80
-
81
-
82
- def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
83
- """
84
- input image is a pil image in RGBA, return RGB image
85
- """
86
- print(background_choice)
87
- if background_choice == "Alpha as mask":
88
- background = Image.new("RGBA", image.size, (0, 0, 0, 0))
89
- image = Image.alpha_composite(background, image)
90
- else:
91
- image = remove_background(image, rembg_session, force=True)
92
- image = do_resize_content(image, foreground_ratio)
93
- image = expand_to_square(image)
94
- image = add_background(image, backgroud_color)
95
- return image.convert("RGB")
96
-
97
- @spaces.GPU
98
- def gen_image(input_image, seed, scale, step):
99
- global pipeline, model, args
100
- pipeline.set_seed(seed)
101
- rt_dict = pipeline(input_image, scale=scale, step=step)
102
- stage1_images = rt_dict["stage1_images"]
103
- stage2_images = rt_dict["stage2_images"]
104
- np_imgs = np.concatenate(stage1_images, 1)
105
- np_xyzs = np.concatenate(stage2_images, 1)
106
-
107
- glb_path = generate3d(model, np_imgs, np_xyzs, args.device)
108
- return Image.fromarray(np_imgs), Image.fromarray(np_xyzs), glb_path#, obj_path
109
-
110
-
111
- parser = argparse.ArgumentParser()
112
- parser.add_argument(
113
- "--stage1_config",
114
- type=str,
115
- default="configs/nf7_v3_SNR_rd_size_stroke.yaml",
116
- help="config for stage1",
117
- )
118
- parser.add_argument(
119
- "--stage2_config",
120
- type=str,
121
- default="configs/stage2-v2-snr.yaml",
122
- help="config for stage2",
123
- )
124
 
125
- parser.add_argument("--device", type=str, default="cuda")
126
- args = parser.parse_args()
127
-
128
- crm_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="CRM.pth")
129
- specs = json.load(open("configs/specs_objaverse_total.json"))
130
- model = CRM(specs)
131
- model.load_state_dict(torch.load(crm_path, map_location="cpu"), strict=False)
132
- model = model.to(args.device)
133
-
134
- stage1_config = OmegaConf.load(args.stage1_config).config
135
- stage2_config = OmegaConf.load(args.stage2_config).config
136
- stage2_sampler_config = stage2_config.sampler
137
- stage1_sampler_config = stage1_config.sampler
138
-
139
- stage1_model_config = stage1_config.models
140
- stage2_model_config = stage2_config.models
141
-
142
- xyz_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="ccm-diffusion.pth")
143
- pixel_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="pixel-diffusion.pth")
144
- stage1_model_config.resume = pixel_path
145
- stage2_model_config.resume = xyz_path
146
-
147
- pipeline = TwoStagePipeline(
148
- stage1_model_config,
149
- stage2_model_config,
150
- stage1_sampler_config,
151
- stage2_sampler_config,
152
- device=args.device,
153
- dtype=torch.float32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  )
155
 
156
- _DESCRIPTION = '''
157
- * Our [official implementation](https://github.com/thu-ml/CRM) uses UV texture instead of vertex color. It has better texture than this online demo.
158
- * Project page of CRM: https://ml.cs.tsinghua.edu.cn/~zhengyi/CRM/
159
- * If you find the output unsatisfying, try using different seeds:)
160
- '''
161
-
162
- with gr.Blocks() as demo:
163
- gr.Markdown("# CRM: Single Image to 3D Textured Mesh with Convolutional Reconstruction Model")
164
- gr.Markdown(_DESCRIPTION)
165
- with gr.Row():
166
- with gr.Column():
167
- with gr.Row():
168
- image_input = gr.Image(
169
- label="Image input",
170
- image_mode="RGBA",
171
- sources="upload",
172
- type="pil",
173
- )
174
- processed_image = gr.Image(label="Processed Image", interactive=False, type="pil", image_mode="RGB")
175
- with gr.Row():
176
- with gr.Column():
177
- with gr.Row():
178
- background_choice = gr.Radio([
179
- "Alpha as mask",
180
- "Auto Remove background"
181
- ], value="Auto Remove background",
182
- label="backgroud choice")
183
- # do_remove_background = gr.Checkbox(label=, value=True)
184
- # force_remove = gr.Checkbox(label=, value=False)
185
- back_groud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=False)
186
- foreground_ratio = gr.Slider(
187
- label="Foreground Ratio",
188
- minimum=0.5,
189
- maximum=1.0,
190
- value=1.0,
191
- step=0.05,
192
- )
193
-
194
- with gr.Column():
195
- seed = gr.Number(value=1234, label="seed", precision=0)
196
- guidance_scale = gr.Number(value=5.5, minimum=3, maximum=10, label="guidance_scale")
197
- step = gr.Number(value=30, minimum=30, maximum=100, label="sample steps", precision=0)
198
- text_button = gr.Button("Generate 3D shape")
199
- gr.Examples(
200
- examples=[os.path.join("examples", i) for i in os.listdir("examples")],
201
- inputs=[image_input],
202
- examples_per_page = 20,
203
- )
204
- with gr.Column():
205
- image_output = gr.Image(interactive=False, label="Output RGB image")
206
- xyz_ouput = gr.Image(interactive=False, label="Output CCM image")
207
-
208
- output_model = gr.Model3D(
209
- label="Output OBJ",
210
- interactive=False,
211
- )
212
- gr.Markdown("Note: Ensure that the input image is correctly pre-processed into a grey background, otherwise the results will be unpredictable.")
213
-
214
- inputs = [
215
- processed_image,
216
- seed,
217
- guidance_scale,
218
- step,
219
- ]
220
- outputs = [
221
- image_output,
222
- xyz_ouput,
223
- output_model,
224
- # output_obj,
225
- ]
226
-
227
-
228
- text_button.click(fn=check_input_image, inputs=[image_input]).success(
229
- fn=preprocess_image,
230
- inputs=[image_input, background_choice, foreground_ratio, back_groud_color],
231
- outputs=[processed_image],
232
- ).success(
233
- fn=gen_image,
234
- inputs=inputs,
235
- outputs=outputs,
236
- )
237
- demo.queue().launch()
 
1
+ # # Not ready to use yet
2
+ # import spaces
3
+ # import argparse
4
+ # import numpy as np
5
+ # import gradio as gr
6
+ # from omegaconf import OmegaConf
7
+ # import torch
8
+ # from PIL import Image
9
+ # import PIL
10
+ # from pipelines import TwoStagePipeline
11
+ # from huggingface_hub import hf_hub_download
12
+ # import os
13
+ # import rembg
14
+ # from typing import Any
15
+ # import json
16
+ # import os
17
+ # import json
18
+ # import argparse
19
+
20
+ # from model import CRM
21
+ # from inference import generate3d
22
+
23
+ # pipeline = None
24
+ # rembg_session = rembg.new_session()
25
+
26
+
27
+ # def expand_to_square(image, bg_color=(0, 0, 0, 0)):
28
+ # # expand image to 1:1
29
+ # width, height = image.size
30
+ # if width == height:
31
+ # return image
32
+ # new_size = (max(width, height), max(width, height))
33
+ # new_image = Image.new("RGBA", new_size, bg_color)
34
+ # paste_position = ((new_size[0] - width) // 2, (new_size[1] - height) // 2)
35
+ # new_image.paste(image, paste_position)
36
+ # return new_image
37
+
38
+ # def check_input_image(input_image):
39
+ # if input_image is None:
40
+ # raise gr.Error("No image uploaded!")
41
+
42
+
43
+ # def remove_background(
44
+ # image: PIL.Image.Image,
45
+ # rembg_session: Any = None,
46
+ # force: bool = False,
47
+ # **rembg_kwargs,
48
+ # ) -> PIL.Image.Image:
49
+ # do_remove = True
50
+ # if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
51
+ # # explain why current do not rm bg
52
+ # print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
53
+ # background = Image.new("RGBA", image.size, (0, 0, 0, 0))
54
+ # image = Image.alpha_composite(background, image)
55
+ # do_remove = False
56
+ # do_remove = do_remove or force
57
+ # if do_remove:
58
+ # image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
59
+ # return image
60
+
61
+ # def do_resize_content(original_image: Image, scale_rate):
62
+ # # resize image content wile retain the original image size
63
+ # if scale_rate != 1:
64
+ # # Calculate the new size after rescaling
65
+ # new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
66
+ # # Resize the image while maintaining the aspect ratio
67
+ # resized_image = original_image.resize(new_size)
68
+ # # Create a new image with the original size and black background
69
+ # padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
70
+ # paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
71
+ # padded_image.paste(resized_image, paste_position)
72
+ # return padded_image
73
+ # else:
74
+ # return original_image
75
+
76
+ # def add_background(image, bg_color=(255, 255, 255)):
77
+ # # given an RGBA image, alpha channel is used as mask to add background color
78
+ # background = Image.new("RGBA", image.size, bg_color)
79
+ # return Image.alpha_composite(background, image)
80
+
81
+
82
+ # def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
83
+ # """
84
+ # input image is a pil image in RGBA, return RGB image
85
+ # """
86
+ # print(background_choice)
87
+ # if background_choice == "Alpha as mask":
88
+ # background = Image.new("RGBA", image.size, (0, 0, 0, 0))
89
+ # image = Image.alpha_composite(background, image)
90
+ # else:
91
+ # image = remove_background(image, rembg_session, force=True)
92
+ # image = do_resize_content(image, foreground_ratio)
93
+ # image = expand_to_square(image)
94
+ # image = add_background(image, backgroud_color)
95
+ # return image.convert("RGB")
96
+
97
+ # @spaces.GPU
98
+ # def gen_image(input_image, seed, scale, step):
99
+ # global pipeline, model, args
100
+ # pipeline.set_seed(seed)
101
+ # rt_dict = pipeline(input_image, scale=scale, step=step)
102
+ # stage1_images = rt_dict["stage1_images"]
103
+ # stage2_images = rt_dict["stage2_images"]
104
+ # np_imgs = np.concatenate(stage1_images, 1)
105
+ # np_xyzs = np.concatenate(stage2_images, 1)
106
+
107
+ # glb_path = generate3d(model, np_imgs, np_xyzs, args.device)
108
+ # return Image.fromarray(np_imgs), Image.fromarray(np_xyzs), glb_path#, obj_path
109
+
110
+
111
+ # parser = argparse.ArgumentParser()
112
+ # parser.add_argument(
113
+ # "--stage1_config",
114
+ # type=str,
115
+ # default="configs/nf7_v3_SNR_rd_size_stroke.yaml",
116
+ # help="config for stage1",
117
+ # )
118
+ # parser.add_argument(
119
+ # "--stage2_config",
120
+ # type=str,
121
+ # default="configs/stage2-v2-snr.yaml",
122
+ # help="config for stage2",
123
+ # )
124
+
125
+ # parser.add_argument("--device", type=str, default="cuda")
126
+ # args = parser.parse_args()
127
+
128
+ # crm_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="CRM.pth")
129
+ # specs = json.load(open("configs/specs_objaverse_total.json"))
130
+ # model = CRM(specs)
131
+ # model.load_state_dict(torch.load(crm_path, map_location="cpu"), strict=False)
132
+ # model = model.to(args.device)
133
+
134
+ # stage1_config = OmegaConf.load(args.stage1_config).config
135
+ # stage2_config = OmegaConf.load(args.stage2_config).config
136
+ # stage2_sampler_config = stage2_config.sampler
137
+ # stage1_sampler_config = stage1_config.sampler
138
+
139
+ # stage1_model_config = stage1_config.models
140
+ # stage2_model_config = stage2_config.models
141
+
142
+ # xyz_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="ccm-diffusion.pth")
143
+ # pixel_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="pixel-diffusion.pth")
144
+ # stage1_model_config.resume = pixel_path
145
+ # stage2_model_config.resume = xyz_path
146
+
147
+ # pipeline = TwoStagePipeline(
148
+ # stage1_model_config,
149
+ # stage2_model_config,
150
+ # stage1_sampler_config,
151
+ # stage2_sampler_config,
152
+ # device=args.device,
153
+ # dtype=torch.float32
154
+ # )
155
+
156
+ # _DESCRIPTION = '''
157
+ # * Our [official implementation](https://github.com/thu-ml/CRM) uses UV texture instead of vertex color. It has better texture than this online demo.
158
+ # * Project page of CRM: https://ml.cs.tsinghua.edu.cn/~zhengyi/CRM/
159
+ # * If you find the output unsatisfying, try using different seeds:)
160
+ # '''
161
+
162
+ # with gr.Blocks() as demo:
163
+ # gr.Markdown("# CRM: Single Image to 3D Textured Mesh with Convolutional Reconstruction Model")
164
+ # gr.Markdown(_DESCRIPTION)
165
+ # with gr.Row():
166
+ # with gr.Column():
167
+ # with gr.Row():
168
+ # image_input = gr.Image(
169
+ # label="Image input",
170
+ # image_mode="RGBA",
171
+ # sources="upload",
172
+ # type="pil",
173
+ # )
174
+ # processed_image = gr.Image(label="Processed Image", interactive=False, type="pil", image_mode="RGB")
175
+ # with gr.Row():
176
+ # with gr.Column():
177
+ # with gr.Row():
178
+ # background_choice = gr.Radio([
179
+ # "Alpha as mask",
180
+ # "Auto Remove background"
181
+ # ], value="Auto Remove background",
182
+ # label="backgroud choice")
183
+ # # do_remove_background = gr.Checkbox(label=, value=True)
184
+ # # force_remove = gr.Checkbox(label=, value=False)
185
+ # back_groud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=False)
186
+ # foreground_ratio = gr.Slider(
187
+ # label="Foreground Ratio",
188
+ # minimum=0.5,
189
+ # maximum=1.0,
190
+ # value=1.0,
191
+ # step=0.05,
192
+ # )
193
+
194
+ # with gr.Column():
195
+ # seed = gr.Number(value=1234, label="seed", precision=0)
196
+ # guidance_scale = gr.Number(value=5.5, minimum=3, maximum=10, label="guidance_scale")
197
+ # step = gr.Number(value=30, minimum=30, maximum=100, label="sample steps", precision=0)
198
+ # text_button = gr.Button("Generate 3D shape")
199
+ # gr.Examples(
200
+ # examples=[os.path.join("examples", i) for i in os.listdir("examples")],
201
+ # inputs=[image_input],
202
+ # examples_per_page = 20,
203
+ # )
204
+ # with gr.Column():
205
+ # image_output = gr.Image(interactive=False, label="Output RGB image")
206
+ # xyz_ouput = gr.Image(interactive=False, label="Output CCM image")
207
+
208
+ # output_model = gr.Model3D(
209
+ # label="Output OBJ",
210
+ # interactive=False,
211
+ # )
212
+ # gr.Markdown("Note: Ensure that the input image is correctly pre-processed into a grey background, otherwise the results will be unpredictable.")
213
+
214
+ # inputs = [
215
+ # processed_image,
216
+ # seed,
217
+ # guidance_scale,
218
+ # step,
219
+ # ]
220
+ # outputs = [
221
+ # image_output,
222
+ # xyz_ouput,
223
+ # output_model,
224
+ # # output_obj,
225
+ # ]
226
+
227
+
228
+ # text_button.click(fn=check_input_image, inputs=[image_input]).success(
229
+ # fn=preprocess_image,
230
+ # inputs=[image_input, background_choice, foreground_ratio, back_groud_color],
231
+ # outputs=[processed_image],
232
+ # ).success(
233
+ # fn=gen_image,
234
+ # inputs=inputs,
235
+ # outputs=outputs,
236
+ # )
237
+ # demo.queue().launch()
238
+
239
+
240
+
241
  import torch
242
+ import gradio as gr
243
+ import requests
 
 
 
 
 
 
244
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
+ # Download model weights from Hugging Face model repo (if not already present)
247
+ model_repo = "Mariam-Elz/CRM" # Your Hugging Face model repo
248
+
249
+ model_files = {
250
+ "ccm-diffusion.pth": "ccm-diffusion.pth",
251
+ "pixel-diffusion.pth": "pixel-diffusion.pth",
252
+ "CRM.pth": "CRM.pth",
253
+ }
254
+
255
+
256
+ os.makedirs("models", exist_ok=True)
257
+
258
+
259
+
260
+ for filename, output_path in model_files.items():
261
+ file_path = f"models/{output_path}"
262
+ if not os.path.exists(file_path):
263
+ url = f"https://huggingface.co/{model_repo}/resolve/main/{filename}"
264
+ print(f"Downloading {filename}...")
265
+ response = requests.get(url)
266
+ with open(file_path, "wb") as f:
267
+ f.write(response.content)
268
+
269
+ # Load model (This part depends on how the model is defined)
270
+ device = "cuda" if torch.cuda.is_available() else "cpu"
271
+
272
+ def load_model():
273
+ model_path = "models/CRM.pth"
274
+ model = torch.load(model_path, map_location=device)
275
+ model.eval()
276
+ return model
277
+
278
+ model = load_model()
279
+
280
+ # Define inference function
281
+ def infer(image):
282
+ """Process input image and return a reconstructed image."""
283
+ with torch.no_grad():
284
+ # Assuming model expects a tensor input
285
+ image_tensor = torch.tensor(image).to(device)
286
+ output = model(image_tensor)
287
+ return output.cpu().numpy()
288
+
289
+ # Create Gradio UI
290
+ demo = gr.Interface(
291
+ fn=infer,
292
+ inputs=gr.Image(type="numpy"),
293
+ outputs=gr.Image(type="numpy"),
294
+ title="Convolutional Reconstruction Model",
295
+ description="Upload an image to get the reconstructed output."
296
  )
297
 
298
+ if __name__ == "__main__":
299
+ demo.launch()