File size: 4,012 Bytes
24303c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | import math
import os
from random import shuffle
import numpy as np
import torch.nn.functional as F
from module import commons
from module.aligner import beta_binomial_prior_distribution
from module.mel_processing import spectrogram_torch
from text import cleaned_text_to_sequence
from text.symbols import v
import torch
from glob import glob
import torchaudio
from tqdm import tqdm
import utils
import logging
from data_conf import data_root
from module.models import SynthesizerTrn
logging.getLogger("numba").setLevel(logging.WARNING)
s2_config_path = "configs/vits.json"
s2_ckpt_dir = 'logs/vits'
def get_audio(hps, filename):
audio, sampling_rate = utils.load_wav_to_torch(filename)
if sampling_rate != hps.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, hps.sampling_rate))
audio_norm = audio
audio_norm = audio_norm.unsqueeze(0)
spec = spectrogram_torch(audio_norm, hps.filter_length,
hps.sampling_rate, hps.hop_length, hps.win_length,
center=False)
spec = torch.squeeze(spec, 0)
return spec, audio_norm
def process_one(file_path, hps,net_g, phoneme_data, device):
ssl_path = file_path.replace(".wav", ".ssl.pt")
if 'zh' not in file_path:
return
try:
phoneme = phoneme_data[file_path]
phoneme = phoneme.split(' ')
phoneme_ids = cleaned_text_to_sequence(phoneme)
except Exception:
return
phonemes = [0] * (len(phoneme_ids) * 3)
phonemes[1::3] = phoneme_ids
phoneme_ids = phonemes
text = torch.LongTensor(phoneme_ids)
spec, wav = get_audio(hps.data, file_path)
ssl = torch.load(ssl_path).float()
ssl = F.interpolate(ssl, size=spec.shape[-1], mode="nearest")
beta_binomial_scaling_factor = 1.0
# Calculate attention prior
attn_prior = beta_binomial_prior_distribution(
spec.shape[-1],
text.shape[-1],
beta_binomial_scaling_factor,
)
x = text.unsqueeze(0).to(device)
ssl = ssl.to(device)
x_lengths = torch.LongTensor([len(phoneme_ids)]).to(device)
spec_lengths = torch.LongTensor([spec.shape[-1]]).to(device)
attn_prior = torch.FloatTensor(attn_prior).to(device).unsqueeze(0)
spec = spec.to(device).unsqueeze(0)
codes = net_g.get_codes(x, x_lengths,spec, spec_lengths, ssl, attn_prior)
code_path = file_path.replace(".wav", ".latent.pt")
assert code_path.endswith(".latent.pt")
# if os.path.exists(code_path):
# print(f"Skip {file_path}")
# return
torch.save(codes, code_path)
def process_batch(filenames):
print("Loading models ...")
device = torch.device(f"cuda:{0}")
print(device)
hps = utils.get_hparams_from_file(s2_config_path)
net_g = SynthesizerTrn(
hps.data.filter_length // 2 + 1,
hps.train.segment_size // hps.data.hop_length,
n_speakers=hps.data.n_speakers,
**hps.model).to(device)
model_path = utils.latest_checkpoint_path(s2_ckpt_dir, "G_*.pth")
utils.load_checkpoint(model_path, net_g,
None, False)
net_g.eval()
phoneme_path = 'dump/phoneme.npy'
phoneme_data = np.load(phoneme_path, allow_pickle=True).item()
print("Loaded .")
with torch.no_grad():
for filename in tqdm(filenames):
process_one(filename, hps, net_g, phoneme_data, device)
if __name__ == "__main__":
print('only chinese and skip other languages!!!!!!!!')
print('only chinese and skip other languages!!!!!!!!')
print('only chinese and skip other languages!!!!!!!!')
hps = utils.get_hparams_from_file(s2_config_path)
training_files = [line.strip() for line in open(hps.data.training_files).readlines()]
validation_files = [line.strip() for line in open(hps.data.validation_files).readlines()]
filenames = training_files + validation_files
# sort
filenames.sort()
process_batch(filenames)
|