Merge branch 'master' of ssh://dev.rcrai.com:30022/liangsen/audio-to-motion

This commit is contained in:
sen.liang committed 2022-04-24 14:10:15 +08:00
commit 4d4015350c
53 files changed
+4284 -1371

No files matched your search

@@ -32,7 +32,7 @@ if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor1/processing")
path_save = Path('data/Actor1/Actor1-raw-7h') # processing
path_save = Path('data/Actor1/Actor1-raw-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -63,6 +63,7 @@ if __name__ == "__main__":
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# vid_tmp = ["34-28min"]
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
@@ -71,8 +72,10 @@ if __name__ == "__main__":
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 5: break
# if vid in vid_tmp:continue
if durations_train / 3600 > 8: break
# if durations_valid / 3600 > 4: break
print(f"\n processing the {i}-th video {vid} ... ")
@@ -100,14 +103,13 @@ if __name__ == "__main__":
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
# 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}"
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
@@ -146,7 +148,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
@@ -159,7 +161,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
@@ -172,7 +174,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
+77 -67
View File
@@ -1,3 +1,4 @@
import os
from pathlib import Path
import json
import moviepy
@@ -8,8 +9,10 @@ if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_raw = Path("/ssdata1/cf/data/raw/20220319")
path_root = Path("/yrfs/lsen/DATA/Actor2")
# path_raw = Path("/ssdata1/cf/data/raw/20220319")
path_raw = Path("/ssdata1/cf/data/raw/20220408")
# path_root = Path("/mfs/lsen/DATA/Actor2/processing")
path_root = Path("/mfs/lsen/DATA/Actor2/happy")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
@@ -25,7 +28,7 @@ if __name__ == '__main__':
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
ipath_data = path_root.joinpath(ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video")
@@ -36,19 +39,19 @@ if __name__ == '__main__':
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info & check
if ipath_infor.exists():
# continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframe_info = info['nframes']
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframe_info:
print(f"\n Skip: have already done!")
continue
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
@@ -60,73 +63,80 @@ if __name__ == '__main__':
durations += video.duration
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# # Trim
# # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
# video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# # video = video.subclip(t_start=5.0, t_end=60.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = int(video.duration * video.fps)
# # nframes = len(list(video.iter_frames()))
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# # if fps != 50
# if video.fps != 50:
# print("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}")
# # save sub video fps=50
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# if ipath_video_sub.exists():
# print("\nERROR: ipath_video_sub.exists()")
# continue
# else:
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# # reload video
# video.close()
# video = VideoFileClip(str(ipath_video_sub))
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = len(list(video.iter_frames()))
# # get audio
# audio_sub = video.audio
# if audio_sub is None:
# print("\nERROR: audio info is None")
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # save audio_sub
# ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
# audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
# print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# # # check fps
# # if int(video.fps) != 50:
# # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# # video.write_videofile(str(ipath_video_save), fps=50.0)
# # print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
# # save video feature
# info = {"nframes": nframes,
# "fps": video.fps,
# "width": video.w,
# "height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# with open(str(ipath_infor), 'w+') as f:
# json.dump(info, f)
# print(info)
# print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
# # save trim video
# print(f"write_images_sequence...")
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
# video.write_images_sequence(ipath_format, fps=50)
@@ -24,8 +24,9 @@ def main(args):
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
@@ -39,7 +40,6 @@ def main(args):
# if ivideo_name not in IDs: continue
# if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
+4 -2
View File
@@ -7,8 +7,10 @@ from pathlib import Path
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
v_dir_videos = sorted(path_data.glob("*"))
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
@@ -29,8 +29,10 @@ def landmark_resample_fps(y, source_fps = 30, target_fps=25):
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
path_save = Path('data/Actor2/Actor2-raw-7h') # processing
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
path_save = Path('data/Actor2/Actor2-happy-1h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -40,22 +42,20 @@ if __name__ == "__main__":
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["AA7A9568", "AA7A9577"])
# vid_valid = set(["AA7A9569", "AA7A9578"])
vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
'AA7A9628'])
### for processing data
# vid_test = set(["AA7A9568", "AA7A9577"])
# # vid_valid = set(["AA7A9569", "AA7A9578"])
# vid_valid = set(['AA7A9641', 'AA7A9644', 'AA7A9645', 'AA7A9648', 'AA7A9640',
# 'AA7A9630', 'AA7A9637', 'AA7A9636', 'AA7A9569', 'AA7A9578',
# 'AA7A9632', 'AA7A9638', 'AA7A9651', 'AA7A9647', 'AA7A9643',
# 'AA7A9650', 'AA7A9629', 'AA7A9642', 'AA7A9631', 'AA7A9635',
# 'AA7A9634'])
# vid_train = vids - vid_test - vid_valid
vid_valid = vids - vid_test - vid_train
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
vid_test = set(["4R3A0004"])
vid_valid = set(["4R3A0004"])
vid_train = vids - vid_test - vid_valid
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
+71 -62
View File
@@ -1,5 +1,6 @@
from pathlib import Path
import json
import os
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
@@ -36,18 +37,18 @@ if __name__ == '__main__':
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info & check
if ipath_infor.exists():
# continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframe_info = info['nframes']
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframe_info:
print(f"\n Skip: have already done!")
continue
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
@@ -61,71 +62,79 @@ if __name__ == '__main__':
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# # Trim
# # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
# video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# # video = video.subclip(t_start=5.0, t_end=60.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = int(video.duration * video.fps)
# # nframes = len(list(video.iter_frames()))
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# # if fps != 50
# if video.fps != 50:
# print("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}")
# # save sub video fps=50
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# if ipath_video_sub.exists():
# print("\nERROR: ipath_video_sub.exists()")
# continue
# else:
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# # reload video
# video.close()
# video = VideoFileClip(str(ipath_video_sub))
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = len(list(video.iter_frames()))
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
# # get audio
# audio_sub = video.audio
# if audio_sub is None:
# print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # save audio_sub
# ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
# audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
# print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# # # check fps
# # if int(video.fps) != 50:
# # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# # video.write_videofile(str(ipath_video_save), fps=50.0)
# # print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
# # save video feature
# info = {"nframes": nframes,
# "fps": video.fps,
# "width": video.w,
# "height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# with open(str(ipath_infor), 'w+') as f:
# json.dump(info, f)
# print(info)
# print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
# # save trim video
# print(f"write_images_sequence...")
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
# video.write_images_sequence(ipath_format, fps=50)
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "BU6A9965"
path_root = Path("/mfs/lsen/DATA/Actor3/processing")
path_save = Path("./data/Actor3/DECA_Actor3_mean.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
path_data = path_root.joinpath(fid)
path_coeff = path_data.joinpath("DECA_coeff")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
print(f"Have {len(vpath_coeff)} frames")
feat_shape = []
feat_tex = []
feat_cam = []
feat_exp = []
feat_pos = []
feat_light = []
feat_detail = []
for i, ipath_coeff in enumerate(vpath_coeff):
if i > 1000: break
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_tex.append(data_coeff["tex"])
feat_cam.append(data_coeff["cam"])
feat_light.append(data_coeff["light"])
feat_detail.append(data_coeff["detail"])
feat_shape.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_tex = np.array(feat_tex) # (nframe_trim, 50)
feat_cam = np.array(feat_cam) # (nframe_trim, 6)
feat_light = np.array(feat_light) # (nframe_trim, 50)
feat_detail = np.array(feat_detail) # (nframe_trim, 6)
feat_shape = np.array(feat_shape) # (nframe_trim, 50)
mean_exp = feat_exp.mean(axis=0)
mean_pos = feat_pos.mean(axis=0)
mean_tex = feat_tex.mean(axis=0)
mean_cam = feat_cam.mean(axis=0)
mean_light = feat_light.mean(axis=0)
mean_detail = feat_detail.mean(axis=0)
mean_shape = feat_shape.mean(axis=0)
print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}")
# save
mean_DECA = {
"exp": mean_exp, # (50, )
"pose": mean_pos, # (6, )
"tex": mean_tex, # (50, )
"cam": mean_cam, # (3, )
"light": mean_light, # (9, 3)
"detail": mean_detail,# (128, )
"shape": mean_shape, # (100, )
}
np.save(path_save, mean_DECA)
print("save to --> ", path_save)
print(f"mean deca = \n {mean_DECA}")
+139
View File
@@ -0,0 +1,139 @@
from pathlib import Path
import json
import os
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
path_raw = Path("/ssdata1/cf/data/raw/20220422")
path_root = Path("/mfs/lsen/DATA/Actor4")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["clip_full"]
durations = 0
# for each video
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video")
ipath_audio = ipath_data.joinpath("audio")
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame.mkdir(parents=True, exist_ok=True)
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
if video.audio is None:
print("\nERROR: audio info is None")
continue
durations += video.duration
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -hide_banner -loglevel error -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,157 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:7"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
# if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
# ipath_vis = ipath_data.joinpath("DECA_vis2")
ipath_kpt2d.mkdir(parents=True, exist_ok=True)
ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
# ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_kpt2d.glob("*.txt")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%10 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# # save render
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# if vis_name not in visdict.keys():
# continue
# img = util.tensor2image(visdict[vis_name][j])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:0', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
@@ -0,0 +1,99 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_idn.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == feat_idn.shape[0]:
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
@@ -0,0 +1,103 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
device = torch.device("cuda:4")
pid = "AA7A9568" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
# path_audio = path_data.joinpath("audio/audio_trim.wav")
path_audio = path_data.joinpath("audio/audio_trim_120s.wav")
# data_pos = np.load(path_pos)[:] # N x 6
# data_idn = np.load(path_idn) # N x 100
# data_exp = np.load(path_exp) # N x 50
# N = data_exp.shape[0]
data_pos = np.load(path_pos)[:6000] # N x 6
data_idn = np.load(path_idn)[:6000] # N x 100
data_exp = np.load(path_exp)[:6000] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/Actor2/DECA_Actor2_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_trim_120s.mp4")
v_render_pt = []
nbatch_render = 5
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
# codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
@@ -0,0 +1,73 @@
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
class ImagesDataset(Dataset):
def __init__(self, path_folder:Path):
self.path_folder = path_folder
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
def __len__(self):
return len(self.list_image)
def __getitem__(self, idx):
path_frame = self.list_image[idx]
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
image = np.asarray(image)
return {"image_name": path_frame.stem, "image": image}
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
vpath_videos = sorted(path_data.glob("*"))
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:1"
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
print(f"load FaceAlignment model in {device}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
dataset = ImagesDataset(ipath_frame)
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
for k, ibatch in enumerate(dloader):
ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
if k%100 == 0:
print(f"batching {k}/{len(dloader)} ... ")
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
# save landmarks
for jldmk, jname in zip(pred, ibatch_name):
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
# break
@@ -0,0 +1,188 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
path_save = Path('data/Actor3/Actor3-raw-2h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["BU6A9978"])
vid_valid = set(["BU6A9965","BU6A9980","BU6A9978"])
# vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
# 'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
# 'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
# 'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
# 'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
# 'AA7A9628'])
vid_train = vids - vid_test - vid_valid
# vid_valid = vids - vid_test - vid_train
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_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_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
print(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
# print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
# print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+66
View File
@@ -0,0 +1,66 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
fps_save = 50
path_save = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/video/predict_compare_3_AR.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220312/20220314-15H08M06S/audio_trim_120s_infer_20220313-13H26M47S_epoch_100_002.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2meshAR_CN_20220314/20220317-15H57M26S/audio_trim_120s_infer_20220316-23H56M06S_epoch_050_002.mp4"
path_clipC = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/video/deca_render_no_pose_120s.mp4"
# path_clipC = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos_no_idn.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4"
# path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
# path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
print(f"clip_A duration = {clip_A.duration}, clip_B duration = {clip_B.duration}")
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
print(f"audio duration = {audio.duration}")
# txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18)
# clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18)
# clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18)
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_B.duration), audio.duration)
print(f"duration min = {duration}")
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
clip_C = clip_C.set_duration(duration)
audio = audio.set_duration(duration)
# stack
# video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")
Whitespace-only changes.
@@ -0,0 +1,87 @@
import json
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps // 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_pos = []
feat_cam = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframes == feat.shape[0] + 1:
feat = np.pad(feat, ((0,1),(0,0)), mode="edge")
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
elif nframes == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
else:
print("ERROR, skip! ")
@@ -0,0 +1,165 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData/LuoXData-pose-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_pos_cam_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["2021-P09", "2021-P22"])
vid_valid = set(["2021-P14", "2021-P20"])
vid_train = vids - vid_test - vid_valid
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 9)
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}"
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
# if durations_train / 3600 > 16:
# break
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
print(f"--> {path_save}")
@@ -0,0 +1,84 @@
import json
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}, duration ={nframe_trim / fps // 60}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# check
# vframe_frame = list(ipath_frame.glob("*.jpg"))
# vframe_coeff = list(ipath_coeff.glob("*.npy"))
# print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
# if len(vframe_frame) != nframe_trim:
# print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframe_trim}")
# continue
feat_pos = []
feat_cam = []
for j in range(ibeg, iend):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:05d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframe_trim == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframe_trim}\n save to -> {ipath_save_pos}") # (nframe, 9)
duration_coeff += nframe_trim / fps / 60
print(f"add duration_coeff={duration_coeff} min")
else:
print("ERROR, skip! ")
@@ -0,0 +1,184 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def convert_fps(y, source_fps = 30, target_fps=25):
"""
y, nframes x nc_feat (with source_fps)
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/Obama/obama-pose-8h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_pos_cam_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}")
# print(f"vids total= {vids}")
vid_test = set(vids[ :2])
vid_valid = set(vids[2:10])
vid_train = set(vids) - vid_test - vid_valid
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
# print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
if not ipath_info.exists():
print(f"ERROR: NOT Exist {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}, duration ={nframe_trim / fps // 60}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 9)
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}"
# resample to 30fps
fps_convert = 50
data_exp = convert_fps(data_exp, source_fps=fps, target_fps=fps_convert)
data_pos = convert_fps(data_pos, source_fps=fps, target_fps=fps_convert)
data_idn = convert_fps(data_idn, source_fps=fps, target_fps=fps_convert)
nframe_convert = data_pos.shape[0]
print(f"after convert motion = {data_pos.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
# assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}"
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train:
durations_train += nframe_convert/fps_convert
data_train[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if durations_train / 3600 > 8:
break
if vid in vid_valid:
durations_valid += nframe_convert/fps_convert
data_valid[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if vid in vid_test:
durations_test += nframe_convert/fps_convert
data_test[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
print(f"--> {path_save}")
View File
Whitespace-only changes.
@@ -0,0 +1,141 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from src.models import create_model, calculate_model_params
from common.logger import Logger
def _convert_batchnorm(module):
"""Convert the syncBNs into normal BN3ds."""
module_output = module
if isinstance(module, torch.nn.SyncBatchNorm):
module_output = torch.nn.BatchNorm3d(module.num_features, module.eps,
module.momentum, module.affine,
module.track_running_stats)
if module.affine:
module_output.weight.data = module.weight.data.clone().detach()
module_output.bias.data = module.bias.data.clone().detach()
# keep requires_grad unchanged
module_output.weight.requires_grad = module.weight.requires_grad
module_output.bias.requires_grad = module.bias.requires_grad
module_output.running_mean = module.running_mean
module_output.running_var = module.running_var
module_output.num_batches_tracked = module.num_batches_tracked
for name, child in module.named_children():
module_output.add_module(name, _convert_batchnorm(child))
del module
return module_output
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml", help="experiment configure file name")
args, _ = parser.parse_known_args()
update_config(args.opt)
# parser.add_argument('checkpoint', help='checkpoint file')
# parser.add_argument('--show', action='store_true', help='show onnx graph')
# parser.add_argument('--output-file', type=str, default='tmp.onnx')
# parser.add_argument('--opset-version', type=int, default=11)
# parser.add_argument('--verify', action='store_true', help='verify the onnx model output against pytorch output')
# parser.add_argument('--is-localizer', action='store_true', help='whether it is a localizer')
# parser.add_argument('--shape', type=int, nargs='+', default=[1, 3, 8, 224, 224], help='input video size')
# parser.add_argument('--softmax', action='store_true', help='wheter to add softmax layer at the end of recognizers')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_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)
# load dataset
test_dataset = create_dataset(opt, phase='valid')
test_loader = DataLoader(test_dataset,
batch_size=opt.TEST.batch_size * len(opt.GPUS),
shuffle=True, # NOTE: usually set False
num_workers=opt.WORKERS,
pin_memory=False)
logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
# for _, ibatch_test in enumerate(test_loader):
# model.testing(batch_input=ibatch_test, cur_epoch=epoch) # forward and backward
# break
# build the model
model = create_model(opt, logger)
model.setup(opt) # load checkpoints
model.eval()
# export model
netG = model.netG
netG.eval() # set inference model
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/audio2mesh-{path_ckpt.stem}-{opt.MODEL.load_epoch}.onnx")
if not path_onnx.exists():
# forward
batch_input = next(iter(test_loader))
batch_otput = model.forward(batch_input)
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG, # model being run
model.cond,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["cond"],
output_names=["mesh"],
dynamic_axes = {
"cond": {0: "batch_size", 1: "nseqlen"},
"mesh": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
# valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
# get pytorch output
batch_input = next(iter(test_loader))
batch_otput = model.forward(batch_input).detach().cpu().numpy()
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["mesh"], {"cond": model.cond.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx), 'The outputs are different between Pytorch and ONNX'
print('The numerical values are same between Pytorch and ONNX')
@@ -0,0 +1,83 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
from lsp.models import create_model
from lsp.models import feature2face_model
from lsp.models.feature2face_G import Feature2Face_G
if __name__ == '__main__':
# create m2f model
gen_opt = RenderOptions().parse()
gen_opt.name = "ljj" #args.name
gen_opt.batch_size = 64 #args.batch_size_m2f
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
device = torch.device("cuda:0")
# model_m2f = create_model(gen_opt)
# model_m2f.Feature2Face_G.eval()
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG = Feature2Face_G(gen_opt).to(device)
netG = torch.nn.DataParallel(netG, [device,])
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG.eval()
path_onnx = Path(f"./data/render/models/{gen_opt.name}/render_g.onnx")
if not path_onnx.exists():
# forward test
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input) # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG.module, # model being run
batch_input,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["input"],
output_names=["output"],
dynamic_axes = {
"input": {0: "batch_size"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
# valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
print('The numerical values are same between Pytorch and ONNX')
print(f"output[0, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")
+157
View File
@@ -0,0 +1,157 @@
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchaudio.models.wav2vec2.utils import import_huggingface_model
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from src.models import create_model, calculate_model_params
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
# https://github.com/ccoreilly/wav2vec2-service/blob/master/convert_torch_to_onnx.py
# https://huggingface.co/docs/transformers/serialization
# https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2Model
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = parser.parse_known_args()
update_config(args.opt)
# parser.add_argument('checkpoint', help='checkpoint file')
# parser.add_argument('--show', action='store_true', help='show onnx graph')
# parser.add_argument('--output-file', type=str, default='tmp.onnx')
# parser.add_argument('--opset-version', type=int, default=11)
# parser.add_argument('--verify', action='store_true', help='verify the onnx model output against pytorch output')
# parser.add_argument('--is-localizer', action='store_true', help='whether it is a localizer')
# parser.add_argument('--shape', type=int, nargs='+', default=[1, 3, 8, 224, 224], help='input video size')
# parser.add_argument('--softmax', action='store_true', help='wheter to add softmax layer at the end of recognizers')
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_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)
# load dataset
test_dataset = create_dataset(opt, phase='valid')
test_loader = DataLoader(test_dataset,
batch_size=opt.TEST.batch_size * len(opt.GPUS),
shuffle=True, # NOTE: usually set False
num_workers=opt.WORKERS,
pin_memory=False)
logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
# build the model
device = "cuda:9"
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
# import
model_extractor = import_huggingface_model(extractor)
model_extractor.eval() # set the model to inference mode
model_extractor.to(device)
# print(f"model_extractor device = {model_extractor.device}")
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/wav2vec2/{MODEL_ID.split('/')[-1]}.onnx")
# forward
batch_input = next(iter(test_loader))
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
print(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
# padding half frame length for bed and end
npad = int(0.5 * 16000 * ( 1 / 50) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
print(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
speech = list(raw_speech)
inputs = processor(speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
print(f"inputs keys = {inputs.keys()}")
with torch.no_grad():
# output = extractor(**inputs)
output = extractor(**inputs).last_hidden_state
output = output.cpu().numpy()
print(f"self.output shape = {output.shape}")
print(f"input_values shape = {inputs['input_values'].shape}, attention_mask shape = {inputs['attention_mask'].shape}")
# x_input = (inputs["input_values"], inputs["attention_mask"])
raw_speech = torch.from_numpy(raw_speech).float().to(device)
if not path_onnx.exists():
torch.onnx.export(
model_extractor, # model being run
raw_speech, # model input (or a tuple for multiple inputs)
str(path_onnx), # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=11, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0: "batch_size", 1 : 'audio_len'}, # variable length axes
'output' : {0: "batch_size", 1 : 'nseqlen'}
})
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################
# valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
# get pytorch output
# batch_input = next(iter(test_loader))
# model.set_input(batch_input)
# print(f"cond shape = {model.cond.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
# x_input = {
# "input_values": model.inputs["input_values"].cpu().numpy(),
# "attention_mask": model.inputs["attention_mask"].cpu().numpy()
# }
print(f"raw_speech = {raw_speech.shape}, inputs['input_values'] = {inputs['input_values'].shape}")
raw_speech = inputs['input_values']
batch_onnx = sess.run(['output'], {"input": raw_speech.detach().cpu().numpy()})
print(f"batch_onnx len= {len(batch_onnx)}, [0] shape = {batch_onnx[0].shape}")
assert np.allclose(output, batch_onnx[0], atol=1e-3), 'The outputs are different between Pytorch and ONNX'
print(f"output[0, :, 100] = \n{output[0, :, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0][0,:,100]}")
print('The numerical values are same between Pytorch and ONNX')
@@ -0,0 +1,36 @@
import onnx
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="input model")
parser.add_argument("--output", required=True, help="output model")
args = parser.parse_args()
return args
def remove_initializer_from_input():
args = get_args()
model = onnx.load(args.input)
if model.ir_version < 4:
print(
'Model with ir_version below 4 requires to include initilizer in graph input'
)
return
inputs = model.graph.input
name_to_input = {}
for input in inputs:
name_to_input[input.name] = input
for initializer in model.graph.initializer:
if initializer.name in name_to_input:
inputs.remove(name_to_input[initializer.name])
onnx.save(model, args.output)
if __name__ == '__main__':
remove_initializer_from_input()
@@ -0,0 +1,65 @@
GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: True
verbose: False
isTrain: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh2'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# # # 1h 1:10
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-02H14M47S"
load_epoch: 100
# # # 2h 1:10
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-18H22M47S"
# load_epoch: 100
# # 3h 1:100
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220316-16H38M26S"
# load_epoch: 100
# # 5h
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220321-17H42M19S"
# load_epoch: 100
DATASET:
fps: 50
sr: 16000
# name: "motion_live"
name: "motion_eval"
root: './data/Actor1/Actor1-raw-1h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor1/processing'
path_mean_dict: './data/Actor1/DECA_Actor1_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
@@ -0,0 +1 @@
[2022-04-06 16:22:02,962][INFO] device set to cuda:8