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

120 lines
4.4 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/data2/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/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
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 = 2 # 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_save = ipath_data.joinpath("audio/feat_mel_trim_split_2s.npy") # feat_mel_trim_split
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
if not ipath_audio.exists():
print(f"ERROR: NOT Exist {ipath_audio}")
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
# split frames
nsize_split = int( nwin_train_secs * fps )
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
nsplit = (nframe_trim - nsize_split) // nstep_split + 1
print(f"frame ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {nsplit}")
# 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"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_split * rato) + 1 # 518 (if nwind=6s),
# nstep_audio = int( nstep_split * rato)
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}") # nstep = {nstep_audio}, len={(melspec.shape[1] - nsize_audio) // nstep_audio + 1}")
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_split * rato )
nseg_end = nseg_beg + nsize_audio
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
# save
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
np.save(ipath_save, data_melspec) # (nsplit, 173, 80)
print(f"data_melspec = {data_melspec.shape}, save to --> {ipath_save}")
# break