Files
audio2motion/scripts/Obama/run-11-speech-features-split.py
T
2022-01-21 17:42:41 +08:00

140 lines
5.5 KiB
Python

import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, '/mnt/data/CODE/Audio2Expression/3rdpart/')
import tacotron2
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} dir files")
# load STFT
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# set windows
nwin_train_secs = 6 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_audio = ipath_data.joinpath("audio/audio_trim.wav")
ipath_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
ipath_save_audio = ipath_data.joinpath("audio/feat_mel_trim_split_6s.npy") # feat_mel_trim_split
ipath_save_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_6s.npy") # feat_ldmk_trim_norm_split
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
if not ipath_audio.exists() or not ipath_ladmk.exists():
print(f"ERROR: NOT Exist {ipath_audio} or {ipath_ladmk}")
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
# 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']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load landmark
data_ladmk = np.load(ipath_ladmk).reshape(-1, 136) # (nframe, 136)
assert data_ladmk.shape[0] == nframe_trim, f"the length of landmark {data_ladmk.shape[0]} != nframe_trim {nframe_trim}"
nsize_ldmk = int( nwin_train_secs * fps )
nstep_ldmk = int( nwin_train_secs * fps * (1-overlap) )
data_ladmk = torch.from_numpy(data_ladmk).float()
data_ladmk2 = data_ladmk.unfold(dimension=0, size=nsize_ldmk, step=nstep_ldmk) # (nframe_trim//30, 136, 30)
data_ladmk2 = data_ladmk2.permute(0, 2, 1) # (nsplits, nsteps, 136)
print(f"data landmark unfold = {data_ladmk2.shape}")
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
print(f"ldmk ==> nsize = {nsize_ldmk}, nstep = {nstep_ldmk}, len = {nframe_trim // nstep_ldmk}")
# load trim audio
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
if sr != 22050:
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
audio = torch.from_numpy(audio).float()
audio = audio.unsqueeze(0)
melspec = model.mel_spectrogram(audio)
melspec = torch.squeeze(melspec, 0) # (80, 20374)
print(f"landmark = {data_ladmk.shape}, min-max({data_ladmk.min():.4f}, {data_ladmk.max():.4f}), Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
rato = melspec.shape[1] / nframe_trim
nsize_audio = int( nsize_ldmk * rato) + 1 # 518 (if nwind=6s),
nstep_audio = int( nstep_ldmk * rato)
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}, nstep = {nstep_audio}, len={melspec.shape[1] // nstep_audio }")
nsplit = data_ladmk2.shape[0]
data_melspec = torch.zeros(nsplit, 80, nsize_audio)
# nsize = int(nwin_train_secs * fps * rato) + 1 # rate = melspec.shape[1] / nframe_trim
for i in range(nsplit):
nseg_beg = int( i * nstep_ldmk * rato )
nseg_end = nseg_beg + nsize_audio
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
print(f"data_melspec = {data_melspec.shape}, data_ladmk = {data_ladmk2.shape}")
# save
np.save(ipath_save_audio, data_melspec) # (nsplit, 173, 80)
np.save(ipath_save_ladmk, data_ladmk2) # (nsplit, 60, 136)
# break