Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
@@ -1,299 +1,228 @@
|
|
1 |
-
# Not ready to use yet
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
|
6 |
-
|
7 |
-
import
|
8 |
-
|
9 |
-
import
|
10 |
-
from
|
11 |
-
|
12 |
-
import
|
13 |
-
import
|
14 |
-
|
15 |
-
import
|
16 |
-
import
|
17 |
-
import
|
18 |
-
|
19 |
-
|
20 |
-
from
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
width
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
new_image
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
padded_image
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
image =
|
93 |
-
image =
|
94 |
-
image
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
pipeline
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
parser
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
parser.
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
model =
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
)
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
)
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
]
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|