from lib2to3.refactor import get_fixers_from_package import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) import time import argparse import wandb import random import numpy as np import scipy as sp from custom_utils.custom_utils import UV2Mesh, maskFacesBatch, _maskFaces from tensorboardX import SummaryWriter import plotly.graph_objects as go import plotly.express as ex from PIL import Image from utils import str_to_bool from tf_utils import check_tf_version, allow_memory_growth, split_gpu_for_testing from load_models import load_generator, load_discriminator from losses import d_logistic, d_logistic_r1_reg, g_logistic_non_saturating, g_logistic_ns_pathreg, edge_loss, uv_mask_loss, bend_loss # from losses import collision_penalty as collision_penalty from losses import collision_loss as collision_penalty from convnext.models.convnext_tf import ConvNeXt, ConvNeXtReverse, Block from stylegan2_ae.generator import Generator from custom_utils.graph_utils import Reconstructor_V4_Decoder as GNNDecoder, sparse_to_tensor from custom_utils.graph_utils import Reconstructor_v2 as SimpleReconstructor from dataset import DatasetFactory, StaticDataset from custom_utils.custom_utils import batch_to_dict from custom_utils.smpl import SMPL from auto_encoder_body import AutoEncoder as BodyAE from auto_encoder_curv import AutoEncoder as CurvatureAE from auto_encoder_static import AutoEncoder as StaticAE from cvae_curv import CVAE as CVAECurv from models.cvae_model import CVAE as CVAEMain name='cvae_12_6' def init_wandb(): run = wandb.init(project='plots', name=name, notes='') artifact = wandb.Artifact('code', type='code') artifact.add_file('cvae.py') artifact.add_file('dataset.py') artifact.add_file('losses.py') artifact.add_file('convnext/models/convnext_tf.py') run.log_artifact(artifact) uv2mesh = UV2Mesh(res=256) def plot_3d(mesh_gt, mesh_pred_unposed, faces, collision, collision_faces, collision_color): mesh_pred_unposed[:,2] += 1 collision[:,2] += 2 fig = go.Figure(data=[ go.Mesh3d( # 8 vertices of a cube x=mesh_gt[:,0], y=mesh_gt[:,2], z=mesh_gt[:,1], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] ), go.Mesh3d( # 8 vertices of a cube x=mesh_pred_unposed[:,0], y=mesh_pred_unposed[:,2], z=mesh_pred_unposed[:,1], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2], ), go.Mesh3d( # 8 vertices of a cube x=collision[:,0], y=collision[:,2], z=collision[:,1], # i, j and k give the vertices of triangles i = collision_faces[:,0], j = collision_faces[:,1], k = collision_faces[:,2], vertexcolor=collision_color ) ]) fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=2, z=1)) fig.update_layout( scene = dict( xaxis = dict(nticks=4, range=[-1,1],), yaxis = dict(nticks=4, range=[-1,3],), zaxis = dict(nticks=4, range=[-1,1],),) ) return fig @tf.function def train_step(batch): with tf.GradientTape() as tape: uv_curvature = tf.one_hot(batch['uv_curvature'], 7) pred, mean, logvar, z = model([batch['uv_unposed'], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask'], batch['uv_shaped_body']]) def plot_everything(batch: dict, type: str): uv_curvature = tf.one_hot(batch['uv_curvature'], 7) pred, mean, logvar, z = model([batch['uv_unposed'], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask'], batch['uv_shaped_body']]) mesh_pred = uv2mesh(tf.transpose(pred, [0,3,1,2])) mesh_orig = batch['mesh_unposed'] orig_img = tf.transpose(batch['uv_unposed'], [0,2,3,1]) uv_static_img = tf.transpose(batch['uv_static'], [0,2,3,1]) uv_body_posed_img = tf.transpose(batch['uv_body_posed'], [0,2,3,1]) pred_img = pred img = tf.concat((uv_static_img, uv_body_posed_img, orig_img, pred_img), axis=2) imgs = [wandb.Image((img[i] + 1) / 2.0) for i in range(4)] F = np.load("custom_utils/smpl_faces.npy") mask = batch['mesh_mask'].numpy().astype(bool) garment_unposed, faces = maskFacesBatch(mesh_pred.numpy(), F, mask) gt = [mesh_orig[i].numpy()[mask[i], :] for i in range(pred.shape[0])] body = batch['mesh_body_posed'].numpy() mesh_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred).numpy() garment_posed = [mesh_posed[i, mask[i], :] for i in range(body.shape[0])] collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))] collision_faces = [np.concatenate((F, faces[i] + 14475), axis=0) for i in range(len(garment_posed))] collision_color = [np.concatenate((np.ones_like(body[i], dtype=np.int32)*100, np.ones_like(garment_posed[i], dtype=np.int32)*230), axis=0) for i in range(len(garment_posed))] figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i]) for i in range(4) } mean_hist = wandb.Histogram(sequence=mean.numpy().mean(axis=0), num_bins=model.latent_dim) logvar_hist = wandb.Histogram(sequence=logvar.numpy().mean(axis=0), num_bins=model.latent_dim) return { **figs, **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } } def load_model(model, checkpoint): ckpt = tf.train.Checkpoint(model=model) manager = tf.train.CheckpointManager(ckpt, checkpoint, max_to_keep=1) ckpt.restore(manager.latest_checkpoint) def get_frame(folder, nr): pose_folder = os.path.join(folder, 'pose_shape') frames = sorted(os.listdir(pose_folder)) frames = [frame.split('.')[0] for frame in frames] # .split('_')[0] random.shuffle(frames) return frames[0], frames[1:nr] def get_bodies(folder, frame_main, frame_rand, nr=4, random=True): bodies = [] uv_posed_body_no_orient = np.load(os.path.join(folder, 'uv_posed_body_no_orient', frame_main + '.npz')); uv_posed_body_no_orient = uv_posed_body_no_orient['uv_posed_body_no_orient']; bodies.append(uv_posed_body_no_orient) pass def get_curvs(folder, body, static, mask, frame=None, nr=4, random=True, model=None): assert (random and model is not None) or (not random and model is None) if random: curv = model([body, static, mask]) uv_curvature = tf.math.argmax(pred, axis=-1) uv_curvature = tf.one_hot(uv_curvature, 7) pass else: curv = np.load(os.path.join(folder, 'uv_curvature')) #... pass def get_statics(folder, nr=4, random=True): pass def get_unposed(folder, nr=4, random=True): pass def plot_inputs(unposed, static, body, curv): pass def plot_variable_condition(condition, is_curv=False): pass def plot_results(unposed, posed, body, mesh_mask): body_color = np.ones_like(body, dtype=np.int32)*100 F = np.load("custom_utils/smpl_faces.npy") _, faces = _maskFaces(np.ones((14475, 3)), F, mesh_mask) pass def sample(folder, variable_condition, fix_noise, nr=4): # run = wandb.init(project='vae_plots', name=) random_static, random_body, random_curv, random_unposed = variable_condition == 'static', variable_condition == 'body', variable_condition == 'curv', variable_condition == 'unposed' frame_main, frame_rand = get_frame(folder, nr) unposed, uv_mask, mesh_mask = get_unposed(folder, frame, nr, random_unposed) static = get_statics(folder, nr, random_static) body, pose, shape = get_bodies(folder, nr, random_body) curv = get_curvs(folder, body, static, uv_mask, frame, nr, random_curv, curv_model) pred = model([unposed, static, body, curv, uv_mask], fix_noise=fix_noise) mesh_pred = uv2mesh(pred) gender = tf.cast(tf.greater_equal(shape[:, 10] , 0.5), tf.int32) shape_offsets = tf.stack([tf.gather(tf.tensordot(shape[i,:10][tf.newaxis, :], smpl.shapedirs[gender[i]], axes=[[1], [2]])[0,:,:], smpl.to_keep, axis=0) for i in range(shape.shape[0])]) mesh_pred_shaped = mesh_pred + shape_offsets mesh_posed = smpl.run_garment(pose, shape, mesh_pred_shaped).numpy() plot_inputs(unposed[0], static[0], body[0], curv[0]) variable_cond = None if random_static: variable_cond = static elif random_body: variable_cond = body elif random_curv: variable_cond = curv elif random_unposed: variable_cond = unposed else: assert False plot_variable_condition(variable_cond, is_curv=random_curv) plot_results(mesh_pred, mesh_posed, body, mesh_mask) print() if __name__ == '__main__': # init_wandb() # allow_memory_growth() parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) args = vars(parser.parse_args()) folder = '/home/workspace/local-data/train_100' folder_main = 'checkpoints/cvae_13' folder_curv = 'checkpoints/cvae_curv_2' variable_condition = 'curv' batch_size = 4 smpl = SMPL() model = CVAEMain(avg_garment_path='custom_data/train_100_no_shape_avg_uv.npy', latent_dim=128, static_model='checkpoints/ae_static_4', body_model='checpoints/ae_body_8', curvature_model='checpoints/ae_curvature_7') curv_model = CVAECurv() load_model(model, folder_main) load_model(curv_model, folder_curv) sample(folder, variable_condition, fix_noise=True)