Files
audio2motion/infer_stream.py

345 lines
14 KiB
Python

import os
import argparse
import numpy as np
from pathlib import Path
import json
import time
import cv2
import tempfile
from scipy.io import wavfile
from scipy.signal import savgol_filter
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
def write_video(list_images, raw_speech, path_video, W=1920, H=1080, fps=50):
num_frame = len(list_images)
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=16000, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True)
for i in range(num_frame):
writer.write(list_images[i])
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
logger.info(f"save video to -> {path_video}")
# close tmp file
file_audio.close()
file_video.close()
def load_speech_data(path_audio, align=True):
"""
return sr=16000 raw audio data
"""
if not path_audio.exists():
raise(f"NOT existing {path_audio}")
# Load raw audio data
raw_speech, sr = torchaudio.load(path_audio)
logger.info(f"raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech[0])/sr)} s")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
# resampling to 16KHz
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy()
sr = 16000
logger.info(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/16000)} s")
else:
raw_speech = raw_speech.numpy()
# if align to 1/50s
if align:
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
logger.info(f"align to 1/50s: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/sr)} s")
return raw_speech, sr
def load_motion_data(path_info, path_feat_exp, path_feat_pos):
if not path_feat_exp.exists() or not path_feat_pos.exists() :
raise(f"NOT existing {path_feat_exp} | {path_feat_pos}")
# load video info
with open(str(path_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
# logger.info(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(path_feat_exp) # (nframe, 50)
data_pos = np.load(path_feat_pos) # (nframe, 6)
# data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_coeff = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
return data_coeff
def define_extractor(device):
logger.info("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# logger.info(plogger.info.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
logger.info(f"logging path = {opt.OUTPUT_DIR}")
# load wav2Vec model
processor, extractor = define_extractor(device)
# load audio-driven model
model = create_model(opt, logger)
model.setup(opt)
# input audio data
fID = "4R3A0139"
actor="Actor6"
sub_folder = "processing2" # smile, processing, processing2
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}/{fID}/") # processing
path_audio = path_data.joinpath("audio/audio_trim.wav")
# path_audio = Path("./data/test/Actor6_4R3A0139_audio_trim.wav")
# path_folder = Path("./data")
# opt.OUTPUT_DIR = path_folder.joinpath(f"tmp_{path_audio.stem}")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# load audio
raw_speech, sr = load_speech_data(path_audio, align=True)
# setting stream chunk
fps = 50
nduration_predict = 0.5
nduration_history = 3
nduration_future = 0.5
logger.info(f"[stream setting]: fps = {fps}, sr = {sr}")
# setting stream parameters
nsteps_frame = int(nduration_predict * fps + 0.5)
nsteps_segmt = int(nduration_predict * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_predict = {nduration_predict}, nsteps_frame = {nsteps_frame}, nsteps_segmt={nsteps_segmt}")
nsteps_frame_pre = int(nduration_history * fps + 0.5)
nsteps_segmt_pre = int(nduration_history * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_history = {nduration_history}, nsteps_frame_pre = {nsteps_frame_pre}, nsteps_segmt_fut={nsteps_segmt_pre}")
nsteps_frame_fut = int(nduration_future * fps + 0.5)
nsteps_segmt_fut = int(nduration_future * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_future = {nduration_future}, nsteps_frame_fut = {nsteps_frame_fut}, nsteps_segmt_fut={nsteps_segmt_fut}")
nsteps_each_batch = nsteps_frame + nsteps_frame_pre + nsteps_frame_fut
logger.info(f"[stream setting]: \t nsteps_each_batch = {nduration_future}")
# get total frame size
total_segmt = raw_speech.shape[0]
total_frame = int((total_segmt / sr) * fps + 0.5)
# total_frame = int((total_frame // nsteps_frame ) * nsteps_frame + 0.5) # align & trim to predict turnk size
total_frame = int((total_frame // nsteps_frame + 1) * nsteps_frame + 0.5) # align & trim to predict turnk size, add more
logger.info(f"total_frame = {total_frame}, total_segmt = {total_segmt}")
# start stream
beg_segmt, beg_frame = 0, 0
batch_mesh, batch_coef = [],[]
time_beg = time.time()
total_time_wav2vec, total_time_audio2motion = [], []
while beg_frame < total_frame:
end_segmt = beg_segmt + nsteps_segmt # update (beg_segmt, end_segmt)
end_frame = beg_frame + nsteps_frame # update (beg_frame, end_frame)
logger.info(f"\t\t while loop ... (beg,end) frame = ({beg_frame:06d}:{end_frame:06d}), segmt = ({beg_segmt:06d}:{end_segmt:06d})")
# if not(end_segmt <= total_segmt and end_frame <= total_frame):
# logger.info(f"\t\t while loop ... (beg,end) frame = ({beg_frame:06d}:{end_frame:06d}), segmt = ({beg_segmt:06d}:{end_segmt:06d})")
# break
# assert end_segmt <= total_segmt and end_frame <= total_frame
# padding raw speech
npad_wv = int(0.5 * sr * ( 1 / fps) + 0.5) # for wav2vec 2.0: padding half frame length for bed and end
npad_wd_head, npad_wd_tail = 7, 8 # for audio2motion: nwind_size = 16, need_pad 15 frame for each clips
ibeg_segmt = int(beg_segmt - sr * (npad_wd_head / fps) - npad_wv - nsteps_segmt_pre - 0.5)
iend_segmt = int(end_segmt + sr * (npad_wd_tail / fps) + npad_wv + nsteps_segmt_fut + 0.5)
idata_speech = raw_speech[max(ibeg_segmt, 0): min(iend_segmt, total_segmt)] # (nsegmt_steps + npad_wv, )
# if ibeg_segmt & iend_segmt out-of-range
# then need padding
npad_head = - ibeg_segmt if ibeg_segmt < 0 else 0
npda_tail = iend_segmt - total_segmt if iend_segmt > total_segmt else 0
if npad_head + npda_tail > 0:
logger.info(f"\t before padding idata_speech = {idata_speech.shape}, npad_head = {npad_head}, npda_tail={npda_tail} npad_wv={npad_wv}")
idata_speech = np.pad(idata_speech, pad_width=((npad_head, npda_tail)), mode='constant', constant_values=0) # (nsegmt_steps + 2npad_wv, )
logger.info(f"\t after padding idata_speech = {idata_speech.shape}")
# audio feature extraction
logger.info(f"\t [wav2vec] input idata_speech = {idata_speech.shape}")
with torch.no_grad():
inputs = processor(idata_speech, sampling_rate=16000, return_tensors="pt").to(device)
logger.info(f"\t\t [processor] processor input_values = {inputs['input_values'].shape}")
time_wav2vec_beg = time.time()
ifeat_speech = extractor(**inputs).last_hidden_state
total_time_wav2vec.append( time.time() - time_wav2vec_beg)
logger.info(f"\t\t [extractor] last_hidden_state = {ifeat_speech.shape}")
ifeat_speech = ifeat_speech.unfold(dimension=1, size=16, step=1) # (1, nseqs, nc_motion, 16)
ifeat_speech = ifeat_speech.permute(0, 1, 3, 2) # (1, nseqs, 16, 53)
nseq = ifeat_speech.size(1)
logger.info(f"\t\t after convert window ifeat_speech shape = {ifeat_speech.shape}")
assert nseq == nsteps_frame_pre + nsteps_frame + nsteps_frame_fut, f"\t ifeat_speech = {ifeat_speech.shape} != nsteps_frame + nsteps_frame_pre + nsteps_frame_fut ={nsteps_frame + nsteps_frame_pre + nsteps_frame_fut}"
# cut the history & future condition
ifeat_speech = ifeat_speech[:, nsteps_frame_pre:nsteps_frame_pre+nsteps_frame, : ] # (B, nsteps_frame, 16, nc_condit)
# infer mesh
time_audio2motion_beg = time.time()
ibatch_coef = model.forward(ifeat_speech) # 1 x nsteps_frame x 53
total_time_audio2motion.append( time.time() - time_audio2motion_beg)
ibatch_mesh, *_ = model.get_vertices(ibatch_coef) # 1 x nsteps_frame x 5023 x 3
batch_coef.append(ibatch_coef[0]) # nstep_frame x 53
batch_mesh.append(ibatch_mesh[0]) # nstep_frame x 5023 x 3
logger.info(f"\t [audio2motion] ifeat_speech = {ifeat_speech.shape}, ibatch_coef = {ibatch_coef.shape}, ibatch_mesh = {ibatch_mesh.shape}")
##### update
beg_segmt = end_segmt
beg_frame = end_frame
# record time
total_time = time.time() - time_beg
logger.info(f"total_time = {total_time:.2f}, total_frame = {total_frame}, fps = {total_frame / total_time : 0.2f}")
mean_time_wav2vec = np.mean(total_time_wav2vec)
logger.info(f"one forward mean_time_wav2vec = {mean_time_wav2vec:.6f}, one forward fps = {1 / mean_time_wav2vec : 0.2f}, batch forward fps= {nsteps_frame / mean_time_wav2vec : 0.2f}")
mean_time_audio2motion = np.mean(total_time_audio2motion)
logger.info(f"one forward mean_time_audio2motion = {mean_time_audio2motion:.6f}, one forward fps = {1 / mean_time_audio2motion : 0.2f}, batch forward fps= {nsteps_frame / mean_time_audio2motion : 0.2f}")
# render to video
batch_coef = torch.cat(batch_coef, dim=0) # N x 53
batch_mesh = torch.cat(batch_mesh, dim=0) # N x 5023 x 3
logger.info(f"concat batch_coef = {batch_coef.shape}, batch_mesh = {batch_mesh.shape}")
assert batch_mesh.shape[0] == total_frame
# compare with normal pdt result
if True:
# load GT coeff
ipath_feat_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_coeff = np.concatenate([data_exp, data_pos[:, 3:]], axis=1) # (nframe, 53)
data_coeff = savgol_filter(data_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
data_coeff = data_coeff[:total_frame] # (N, 53)
# path_coeff = Path("experiments/audio2motion/infer_audio2motion_CN_20220525/20220614-17H32M35S/Actor6_4R3A0139_audio_trim_infer_20220602-16H31M37S_epoch_150_coeff.npy")
# data_coeff = np.load(path_coeff)[0, :total_frame]
# logger.info(f"data_coeff = {data_coeff.shape}, load from -> {path_coeff}")
batch_coef = batch_coef.cpu().numpy()
# Diff
diff = np.abs(batch_coef - data_coeff).mean()
logger.info(f"rec_exp = {diff:0.6f}, rato = { ((0.075764 - diff ) / 0.075764) * 100 :0.2f} %")
# velocity loss
diff_pt = batch_coef[1:] - batch_coef[:-1]
diff_gt = data_coeff[1:] - data_coeff[:-1]
diff = np.abs(diff_pt - diff_gt).mean()
logger.info(f"vel_exp = {diff:0.6f}, rato = { ((0.017867 - diff ) / 0.017867) * 100 :0.2f} %")
rendered_mesh = model.render_geometry_batch(batch_mesh, vis_landmarks=False) # N x 512 x 512 x 3
logger.info(f"rendered_mesh len = {len(rendered_mesh)}")
# save video
path_video = opt.OUTPUT_DIR.joinpath(path_audio.stem + "_S2_rendered_mesh_video.mp4")
write_video(rendered_mesh, raw_speech, path_video, W=512, H=512)
logger.info(f"write_video to --> {path_video}")