Mariam-Elz commited on
Commit
84246b9
·
verified ·
1 Parent(s): 95e9efa

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +228 -299
app.py CHANGED
@@ -1,299 +1,228 @@
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()
 
1
+ # Not ready to use yet
2
+ import argparse
3
+ import numpy as np
4
+ import gradio as gr
5
+ from omegaconf import OmegaConf
6
+ import torch
7
+ from PIL import Image
8
+ import PIL
9
+ from pipelines import TwoStagePipeline
10
+ from huggingface_hub import hf_hub_download
11
+ import os
12
+ import rembg
13
+ from typing import Any
14
+ import json
15
+ import os
16
+ import json
17
+ import argparse
18
+
19
+ from model import CRM
20
+ from inference import generate3d
21
+
22
+ pipeline = None
23
+ rembg_session = rembg.new_session()
24
+
25
+
26
+ def expand_to_square(image, bg_color=(0, 0, 0, 0)):
27
+ # expand image to 1:1
28
+ width, height = image.size
29
+ if width == height:
30
+ return image
31
+ new_size = (max(width, height), max(width, height))
32
+ new_image = Image.new("RGBA", new_size, bg_color)
33
+ paste_position = ((new_size[0] - width) // 2, (new_size[1] - height) // 2)
34
+ new_image.paste(image, paste_position)
35
+ return new_image
36
+
37
+ def check_input_image(input_image):
38
+ if input_image is None:
39
+ raise gr.Error("No image uploaded!")
40
+
41
+
42
+ def remove_background(
43
+ image: PIL.Image.Image,
44
+ rembg_session = None,
45
+ force: bool = False,
46
+ **rembg_kwargs,
47
+ ) -> PIL.Image.Image:
48
+ do_remove = True
49
+ if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
50
+ # explain why current do not rm bg
51
+ print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
52
+ background = Image.new("RGBA", image.size, (0, 0, 0, 0))
53
+ image = Image.alpha_composite(background, image)
54
+ do_remove = False
55
+ do_remove = do_remove or force
56
+ if do_remove:
57
+ image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
58
+ return image
59
+
60
+ def do_resize_content(original_image: Image, scale_rate):
61
+ # resize image content wile retain the original image size
62
+ if scale_rate != 1:
63
+ # Calculate the new size after rescaling
64
+ new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
65
+ # Resize the image while maintaining the aspect ratio
66
+ resized_image = original_image.resize(new_size)
67
+ # Create a new image with the original size and black background
68
+ padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
69
+ paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
70
+ padded_image.paste(resized_image, paste_position)
71
+ return padded_image
72
+ else:
73
+ return original_image
74
+
75
+ def add_background(image, bg_color=(255, 255, 255)):
76
+ # given an RGBA image, alpha channel is used as mask to add background color
77
+ background = Image.new("RGBA", image.size, bg_color)
78
+ return Image.alpha_composite(background, image)
79
+
80
+
81
+ def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
82
+ """
83
+ input image is a pil image in RGBA, return RGB image
84
+ """
85
+ print(background_choice)
86
+ if background_choice == "Alpha as mask":
87
+ background = Image.new("RGBA", image.size, (0, 0, 0, 0))
88
+ image = Image.alpha_composite(background, image)
89
+ else:
90
+ image = remove_background(image, rembg_session, force_remove=True)
91
+ image = do_resize_content(image, foreground_ratio)
92
+ image = expand_to_square(image)
93
+ image = add_background(image, backgroud_color)
94
+ return image.convert("RGB")
95
+
96
+
97
+ def gen_image(input_image, seed, scale, step):
98
+ global pipeline, model, args
99
+ pipeline.set_seed(seed)
100
+ rt_dict = pipeline(input_image, scale=scale, step=step)
101
+ stage1_images = rt_dict["stage1_images"]
102
+ stage2_images = rt_dict["stage2_images"]
103
+ np_imgs = np.concatenate(stage1_images, 1)
104
+ np_xyzs = np.concatenate(stage2_images, 1)
105
+
106
+ glb_path, obj_path = generate3d(model, np_imgs, np_xyzs, args.device)
107
+ return Image.fromarray(np_imgs), Image.fromarray(np_xyzs), glb_path, obj_path
108
+
109
+
110
+ parser = argparse.ArgumentParser()
111
+ parser.add_argument(
112
+ "--stage1_config",
113
+ type=str,
114
+ default="configs/nf7_v3_SNR_rd_size_stroke.yaml",
115
+ help="config for stage1",
116
+ )
117
+ parser.add_argument(
118
+ "--stage2_config",
119
+ type=str,
120
+ default="configs/stage2-v2-snr.yaml",
121
+ help="config for stage2",
122
+ )
123
+
124
+ parser.add_argument("--device", type=str, default="cuda")
125
+ args = parser.parse_args()
126
+
127
+ crm_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="CRM.pth")
128
+ specs = json.load(open("configs/specs_objaverse_total.json"))
129
+ model = CRM(specs).to(args.device)
130
+ model.load_state_dict(torch.load(crm_path, map_location = args.device), strict=False)
131
+
132
+ stage1_config = OmegaConf.load(args.stage1_config).config
133
+ stage2_config = OmegaConf.load(args.stage2_config).config
134
+ stage2_sampler_config = stage2_config.sampler
135
+ stage1_sampler_config = stage1_config.sampler
136
+
137
+ stage1_model_config = stage1_config.models
138
+ stage2_model_config = stage2_config.models
139
+
140
+ xyz_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="ccm-diffusion.pth")
141
+ pixel_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="pixel-diffusion.pth")
142
+ stage1_model_config.resume = pixel_path
143
+ stage2_model_config.resume = xyz_path
144
+
145
+ pipeline = TwoStagePipeline(
146
+ stage1_model_config,
147
+ stage2_model_config,
148
+ stage1_sampler_config,
149
+ stage2_sampler_config,
150
+ device=args.device,
151
+ dtype=torch.float16
152
+ )
153
+
154
+ with gr.Blocks() as demo:
155
+ gr.Markdown("# CRM: Single Image to 3D Textured Mesh with Convolutional Reconstruction Model")
156
+ with gr.Row():
157
+ with gr.Column():
158
+ with gr.Row():
159
+ image_input = gr.Image(
160
+ label="Image input",
161
+ image_mode="RGBA",
162
+ sources="upload",
163
+ type="pil",
164
+ )
165
+ processed_image = gr.Image(label="Processed Image", interactive=False, type="pil", image_mode="RGB")
166
+ with gr.Row():
167
+ with gr.Column():
168
+ with gr.Row():
169
+ background_choice = gr.Radio([
170
+ "Alpha as mask",
171
+ "Auto Remove background"
172
+ ], value="Auto Remove background",
173
+ label="backgroud choice")
174
+ # do_remove_background = gr.Checkbox(label=, value=True)
175
+ # force_remove = gr.Checkbox(label=, value=False)
176
+ back_groud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=False)
177
+ foreground_ratio = gr.Slider(
178
+ label="Foreground Ratio",
179
+ minimum=0.5,
180
+ maximum=1.0,
181
+ value=1.0,
182
+ step=0.05,
183
+ )
184
+
185
+ with gr.Column():
186
+ seed = gr.Number(value=1234, label="seed", precision=0)
187
+ guidance_scale = gr.Number(value=5.5, minimum=3, maximum=10, label="guidance_scale")
188
+ step = gr.Number(value=50, minimum=30, maximum=100, label="sample steps", precision=0)
189
+ text_button = gr.Button("Generate 3D shape")
190
+ gr.Examples(
191
+ examples=[os.path.join("examples", i) for i in os.listdir("examples")],
192
+ inputs=[image_input],
193
+ )
194
+ with gr.Column():
195
+ image_output = gr.Image(interactive=False, label="Output RGB image")
196
+ xyz_ouput = gr.Image(interactive=False, label="Output CCM image")
197
+
198
+ output_model = gr.Model3D(
199
+ label="Output GLB",
200
+ interactive=False,
201
+ )
202
+ gr.Markdown("Note: The GLB model shown here has a darker lighting and enlarged UV seams. Download for correct results.")
203
+ output_obj = gr.File(interactive=False, label="Output OBJ")
204
+
205
+ inputs = [
206
+ processed_image,
207
+ seed,
208
+ guidance_scale,
209
+ step,
210
+ ]
211
+ outputs = [
212
+ image_output,
213
+ xyz_ouput,
214
+ output_model,
215
+ output_obj,
216
+ ]
217
+
218
+
219
+ text_button.click(fn=check_input_image, inputs=[image_input]).success(
220
+ fn=preprocess_image,
221
+ inputs=[image_input, background_choice, foreground_ratio, back_groud_color],
222
+ outputs=[processed_image],
223
+ ).success(
224
+ fn=gen_image,
225
+ inputs=inputs,
226
+ outputs=outputs,
227
+ )
228
+ demo.queue().launch()