camenduru commited on
Commit
d15c2d5
1 Parent(s): f6ab7ac

Create worker_runpod.py

Browse files
Files changed (1) hide show
  1. worker_runpod.py +225 -0
worker_runpod.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import rembg
4
+ from PIL import Image
5
+ from pytorch_lightning import seed_everything
6
+ from einops import rearrange
7
+ from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
8
+ from diffusers.utils import load_image
9
+ from huggingface_hub import hf_hub_download
10
+ from src.utils.infer_util import remove_background, resize_foreground
11
+
12
+ import os, json
13
+ from torchvision.transforms import v2
14
+ from omegaconf import OmegaConf
15
+ from einops import repeat
16
+ import tempfile
17
+ from tqdm import tqdm
18
+ import imageio
19
+
20
+ from src.utils.train_util import instantiate_from_config
21
+ from src.utils.camera_util import (FOV_to_intrinsics, get_zero123plus_input_cameras,get_circular_camera_poses,)
22
+ from src.utils.mesh_util import save_obj, save_obj_with_mtl
23
+
24
+ import runpod
25
+
26
+ def preprocess(input_image, do_remove_background):
27
+ rembg_session = rembg.new_session() if do_remove_background else None
28
+ if do_remove_background:
29
+ input_image = remove_background(input_image, rembg_session)
30
+ input_image = resize_foreground(input_image, 0.85)
31
+ return input_image
32
+
33
+ def generate_mvs(input_image, sample_steps, sample_seed, pipeline, device):
34
+ seed_everything(sample_seed)
35
+ generator = torch.Generator(device=device)
36
+ z123_image = pipeline(
37
+ input_image,
38
+ num_inference_steps=sample_steps,
39
+ generator=generator,
40
+ ).images[0]
41
+ show_image = np.asarray(z123_image, dtype=np.uint8)
42
+ show_image = torch.from_numpy(show_image) # (960, 640, 3)
43
+ show_image = rearrange(show_image, '(n h) (m w) c -> (n m) h w c', n=3, m=2)
44
+ show_image = rearrange(show_image, '(n m) h w c -> (n h) (m w) c', n=2, m=3)
45
+ show_image = Image.fromarray(show_image.numpy())
46
+ return z123_image, show_image
47
+
48
+ def images_to_video(images, output_path, fps=30):
49
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
50
+ frames = []
51
+ for i in range(images.shape[0]):
52
+ frame = (images[i].permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8).clip(0, 255)
53
+ assert frame.shape[0] == images.shape[2] and frame.shape[1] == images.shape[3], \
54
+ f"Frame shape mismatch: {frame.shape} vs {images.shape}"
55
+ assert frame.min() >= 0 and frame.max() <= 255, \
56
+ f"Frame value out of range: {frame.min()} ~ {frame.max()}"
57
+ frames.append(frame)
58
+ imageio.mimwrite(output_path, np.stack(frames), fps=fps, codec='h264')
59
+
60
+ def get_render_cameras(batch_size=1, M=120, radius=2.5, elevation=10.0, is_flexicubes=False):
61
+ c2ws = get_circular_camera_poses(M=M, radius=radius, elevation=elevation)
62
+ if is_flexicubes:
63
+ cameras = torch.linalg.inv(c2ws)
64
+ cameras = cameras.unsqueeze(0).repeat(batch_size, 1, 1, 1)
65
+ else:
66
+ extrinsics = c2ws.flatten(-2)
67
+ intrinsics = FOV_to_intrinsics(30.0).unsqueeze(0).repeat(M, 1, 1).float().flatten(-2)
68
+ cameras = torch.cat([extrinsics, intrinsics], dim=-1)
69
+ cameras = cameras.unsqueeze(0).repeat(batch_size, 1, 1)
70
+ return cameras
71
+
72
+ def make_mesh(mesh_fpath, planes, model, infer_config, export_texmap):
73
+ mesh_basename = os.path.basename(mesh_fpath).split('.')[0]
74
+ mesh_dirname = os.path.dirname(mesh_fpath)
75
+ mesh_vis_fpath = os.path.join(mesh_dirname, f"{mesh_basename}.glb")
76
+ with torch.no_grad():
77
+ mesh_out = model.extract_mesh(planes, use_texture_map=export_texmap, **infer_config,)
78
+ if export_texmap:
79
+ vertices, faces, uvs, mesh_tex_idx, tex_map = mesh_out
80
+ save_obj_with_mtl(
81
+ vertices.data.cpu().numpy(),
82
+ uvs.data.cpu().numpy(),
83
+ faces.data.cpu().numpy(),
84
+ mesh_tex_idx.data.cpu().numpy(),
85
+ tex_map.permute(1, 2, 0).data.cpu().numpy(),
86
+ mesh_fpath,
87
+ )
88
+ print(f"Mesh with texmap saved to {mesh_fpath}")
89
+ else:
90
+ vertices, faces, vertex_colors = mesh_out
91
+ vertices = vertices[:, [1, 2, 0]]
92
+ vertices[:, -1] *= -1
93
+ faces = faces[:, [2, 1, 0]]
94
+ save_obj(vertices, faces, vertex_colors, mesh_fpath)
95
+ print(f"Mesh saved to {mesh_fpath}")
96
+ return mesh_fpath
97
+
98
+ def make3d(images, model, device, IS_FLEXICUBES, infer_config, export_video, export_texmap):
99
+ images = np.asarray(images, dtype=np.float32) / 255.0
100
+ images = torch.from_numpy(images).permute(2, 0, 1).contiguous().float() # (3, 960, 640)
101
+ images = rearrange(images, 'c (n h) (m w) -> (n m) c h w', n=3, m=2) # (6, 3, 320, 320)
102
+ input_cameras = get_zero123plus_input_cameras(batch_size=1, radius=4.0).to(device)
103
+ render_cameras = get_render_cameras(
104
+ batch_size=1, radius=4.5, elevation=20.0, is_flexicubes=IS_FLEXICUBES).to(device)
105
+ images = images.unsqueeze(0).to(device)
106
+ images = v2.functional.resize(images, (320, 320), interpolation=3, antialias=True).clamp(0, 1)
107
+ mesh_fpath = tempfile.NamedTemporaryFile(suffix=f".obj", delete=False).name
108
+ print(mesh_fpath)
109
+ mesh_basename = os.path.basename(mesh_fpath).split('.')[0]
110
+ mesh_dirname = os.path.dirname(mesh_fpath)
111
+ video_fpath = os.path.join(mesh_dirname, f"{mesh_basename}.mp4")
112
+ with torch.no_grad():
113
+ planes = model.forward_planes(images, input_cameras)
114
+ chunk_size = 20 if IS_FLEXICUBES else 1
115
+ render_size = 384
116
+ frames = []
117
+ for i in tqdm(range(0, render_cameras.shape[1], chunk_size)):
118
+ if IS_FLEXICUBES:
119
+ frame = model.forward_geometry(planes, render_cameras[:, i:i+chunk_size], render_size=render_size,)['img']
120
+ else:
121
+ frame = model.synthesizer(planes, cameras=render_cameras[:, i:i+chunk_size],render_size=render_size,)['images_rgb']
122
+ frames.append(frame)
123
+ frames = torch.cat(frames, dim=1)
124
+ if export_video:
125
+ images_to_video(frames[0], video_fpath, fps=30,)
126
+ print(f"Video saved to {video_fpath}")
127
+ mesh_fpath = make_mesh(mesh_fpath, planes, model, infer_config, export_texmap)
128
+ if export_video:
129
+ return video_fpath, mesh_fpath
130
+ else:
131
+ return mesh_fpath
132
+
133
+ @torch.inference_mode()
134
+ def generate(input):
135
+ values = json.loads(command)
136
+ input_image = values['input_image']
137
+ sample_steps = values['sample_steps']
138
+ seed = values['seed']
139
+ remove_background = True
140
+ export_video = True
141
+ export_texmap = True
142
+
143
+ input_image = load_image(input_image)
144
+ processed_image = preprocess(input_image, remove_background)
145
+
146
+ model = None
147
+ torch.cuda.empty_cache()
148
+ pipeline = DiffusionPipeline.from_pretrained("sudo-ai/zero123plus-v1.2", custom_pipeline="zero123plus",torch_dtype=torch.float16,)
149
+ pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(pipeline.scheduler.config, timestep_spacing='trailing')
150
+ unet_ckpt_path = hf_hub_download(repo_id="TencentARC/InstantMesh", filename="diffusion_pytorch_model.bin", repo_type="model")
151
+ state_dict = torch.load(unet_ckpt_path, map_location='cpu')
152
+ pipeline.unet.load_state_dict(state_dict, strict=True)
153
+ device = torch.device('cuda:0')
154
+ pipeline = pipeline.to(device)
155
+ seed_everything(0)
156
+ mv_images, mv_show_images = generate_mvs(processed_image, sample_steps, seed, pipeline, device)
157
+
158
+ pipeline = None
159
+ torch.cuda.empty_cache()
160
+ config_path = 'configs/instant-mesh-base.yaml'
161
+ config = OmegaConf.load(config_path)
162
+ config_name = os.path.basename(config_path).replace('.yaml', '')
163
+ model_config = config.model_config
164
+ infer_config = config.infer_config
165
+ model_ckpt_path = hf_hub_download(repo_id="TencentARC/InstantMesh", filename="instant_mesh_base.ckpt", repo_type="model")
166
+ model = instantiate_from_config(model_config)
167
+ state_dict = torch.load(model_ckpt_path, map_location='cpu')['state_dict']
168
+ state_dict = {k[14:]: v for k, v in state_dict.items() if k.startswith('lrm_generator.') and 'source_camera' not in k}
169
+ model.load_state_dict(state_dict, strict=True)
170
+ device = torch.device('cuda')
171
+ model = model.to(device)
172
+ IS_FLEXICUBES = True if config_name.startswith('instant-mesh') else False
173
+ if IS_FLEXICUBES:
174
+ model.init_flexicubes_geometry(device, fovy=30.0)
175
+ model = model.eval()
176
+
177
+ output_video, output_model_obj = make3d(mv_images, model, device, IS_FLEXICUBES, infer_config, export_video, export_texmap)
178
+ mesh_basename = os.path.splitext(output_model_obj)[0]
179
+ result = output_video, [output_model_obj, mesh_basename+'.mtl', mesh_basename+'.png']
180
+
181
+ response = None
182
+ try:
183
+ source_id = values['source_id']
184
+ del values['source_id']
185
+ source_channel = values['source_channel']
186
+ del values['source_channel']
187
+ job_id = values['job_id']
188
+ del values['job_id']
189
+
190
+ first_key = next(iter(result[0]))
191
+ file_path = result[0][first_key]
192
+ file_paths = result[1]
193
+ default_filename = os.path.basename(file_path)
194
+ files = { default_filename: open(file_path, "rb").read() }
195
+ for path in file_paths:
196
+ filename = os.path.basename(path)
197
+ with open(path, "rb") as file:
198
+ files[filename] = file.read()
199
+
200
+ payload = {"content": f"{json.dumps(values)} <@{source_id}>"}
201
+ response = requests.post(
202
+ f"https://discord.com/api/v9/channels/{source_channel}/messages",
203
+ data=payload,
204
+ headers={"authorization": f"Bot {discord_token}"},
205
+ files=files
206
+ )
207
+ response.raise_for_status()
208
+ except Exception as e:
209
+ print(f"An unexpected error occurred: {e}")
210
+ finally:
211
+ if os.path.exists(result):
212
+ os.remove(result)
213
+
214
+ if response and response.status_code == 200:
215
+ try:
216
+ payload = {"jobId": job_id, "result": response.json()['attachments'][0]['url']}
217
+ requests.post(f"{web_uri}/api/notify", data=json.dumps(payload), headers={'Content-Type': 'application/json', "authorization": f"{web_token}"})
218
+ except Exception as e:
219
+ print(f"An unexpected error occurred: {e}")
220
+ finally:
221
+ return {"result": response.json()['attachments'][0]['url']}
222
+ else:
223
+ return {"result": "ERROR"}
224
+
225
+ runpod.serverless.start({"handler": generate})