allow inference to input and output style vectors

This commit is contained in:
Justin John
2024-01-12 11:31:29 +05:30
committed by GitHub
parent e9a710c75d
commit e2e9fe1589
2 changed files with 436 additions and 426 deletions
+48 -41
View File
@@ -1,41 +1,48 @@
# FakeYou StyleTTS 2 Inference # FakeYou StyleTTS 2 Inference
import argparse import os
import numpy as np import torch
import soundfile as sf import argparse
from styletts2importable import compute_style, inference import numpy as np
from tortoise.utils.text import split_and_recombine_text import soundfile as sf
from styletts2importable import compute_style, inference
def clsynthesize(text_file_path, voice_path, vcsteps): from tortoise.utils.text import split_and_recombine_text
# Load the text from the file
with open(text_file_path, 'r', encoding="utf-8") as file: def clsynthesize(text_file_path, voice_path, vcsteps, style_npz_path=None, npz_output_path=None):
text = file.read() # Load the text from the file
with open(text_file_path, 'r', encoding="utf-8") as file:
# Load the custom voice text = file.read()
custom_voice = compute_style(voice_path)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Split and recombine long text into manageable chunks
texts = split_and_recombine_text(text) if style_npz_path and os.path.exists(style_npz_path):
# Load style vector from NPZ file
audios = [] style_vector_np = np.load(style_npz_path)['style_vector']
for t in texts: custom_voice = torch.from_numpy(style_vector_np).float().to(device)
# Generate audio for each text chunk elif voice_path:
audios.append(inference(t, custom_voice, alpha=0.3, beta=0.7, diffusion_steps=vcsteps, embedding_scale=1)) # Compute and save style vector
custom_voice = compute_style(voice_path, save_npz=True, npz_path=npz_output_path or "default_output_path.npz").to(device)
return 24000, np.concatenate(audios) else:
raise ValueError("Either a voice path or an input style NPZ file must be provided")
def main():
parser = argparse.ArgumentParser(description='CLI for StyleTTS Voice Synthesis') texts = split_and_recombine_text(text)
parser.add_argument('--input', type=str, required=True, help='Path to the text file') audios = [inference(t, custom_voice, alpha=0.3, beta=0.7, diffusion_steps=vcsteps, embedding_scale=1) for t in texts]
parser.add_argument('--voice', type=str, required=True, help='Path to the custom voice audio file')
parser.add_argument('--vcsteps', type=int, required=True, help='Number of diffusion steps') return 24000, np.concatenate(audios)
parser.add_argument('--output', type=str, required=True, help='Output path for the synthesized audio file')
args = parser.parse_args() def main():
parser = argparse.ArgumentParser(description='CLI for StyleTTS Voice Synthesis')
sample_rate, audio = clsynthesize(args.input, args.voice, args.vcsteps) parser.add_argument('--input', type=str, required=True, help='Path to the text file')
parser.add_argument('--voice', type=str, help='Path to the custom voice audio file (optional if using --input-style-npz)')
# Save the synthesized audio to the specified output path parser.add_argument('--vcsteps', type=int, required=True, help='Number of diffusion steps')
sf.write(args.output, audio, sample_rate) parser.add_argument('--output', type=str, help='Output path for the synthesized audio file (optional)')
parser.add_argument('--input-style-npz', type=str, help='Path to the input style vector NPZ file')
if __name__ == "__main__": parser.add_argument('--output-style-npz', type=str, help='Output path for the style vector NPZ file')
main() args = parser.parse_args()
if args.output:
sample_rate, audio = clsynthesize(args.input, args.voice, args.vcsteps, args.input_style_npz, args.output_style_npz)
sf.write(args.output, audio, sample_rate)
if __name__ == "__main__":
main()
+388 -385
View File
@@ -1,385 +1,388 @@
import torch import torch
from time import strftime from time import strftime
import os, sys, time import os, sys, time
import platform import platform
print("Env vars:") print("Env vars:")
print(os.environ) print(os.environ)
def print_gpu_info(): def print_gpu_info():
print('========================================') print('========================================')
print('Python interpreter', sys.executable) print('Python interpreter', sys.executable)
print('PyTorch version', torch.__version__) print('PyTorch version', torch.__version__)
print('CUDA Available?', torch.cuda.is_available()) print('CUDA Available?', torch.cuda.is_available())
print('CUDA Device count', torch.cuda.device_count()) print('CUDA Device count', torch.cuda.device_count())
print('CUDA threads for parallelizing CPU operations', torch.get_num_threads()) print('CUDA threads for parallelizing CPU operations', torch.get_num_threads())
print('CUDA architectures library was compiled for', torch.cuda.get_arch_list()) print('CUDA architectures library was compiled for', torch.cuda.get_arch_list())
#try: #try:
# from tensorflow.python.client import device_lib # from tensorflow.python.client import device_lib
# print('local devices', str(device_lib.list_local_devices()).replace("\n", "\n ")) # print('local devices', str(device_lib.list_local_devices()).replace("\n", "\n "))
#except ImportError: #except ImportError:
# print('no tensorflow - cannot list devices') # print('no tensorflow - cannot list devices')
# pass # pass
print('========================================', flush=True) print('========================================', flush=True)
print_gpu_info( print_gpu_info(
) )
print("NLTK") print("NLTK")
import nltk import nltk
nltk.download('punkt') nltk.download('punkt')
print("SCIPY") print("SCIPY")
from scipy.io.wavfile import write from scipy.io.wavfile import write
print("TORCH STUFF") print("START")
import torch torch.manual_seed(0)
print("START") torch.backends.cudnn.benchmark = False
torch.manual_seed(0) torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True import random
random.seed(0)
import random
random.seed(0) import numpy as np
np.random.seed(0)
import numpy as np
np.random.seed(0) # load packages
import time
# load packages import random
import time import yaml
import random from munch import Munch
import yaml import numpy as np
from munch import Munch import torch
import numpy as np from torch import nn
import torch import torch.nn.functional as F
from torch import nn import torchaudio
import torch.nn.functional as F import librosa
import torchaudio from nltk.tokenize import word_tokenize
import librosa
from nltk.tokenize import word_tokenize from models import *
from utils import *
from models import * from text_utils import TextCleaner
from utils import * textclenaer = TextCleaner()
from text_utils import TextCleaner
textclenaer = TextCleaner()
to_mel = torchaudio.transforms.MelSpectrogram(
n_mels=80, n_fft=2048, win_length=1200, hop_length=300)
to_mel = torchaudio.transforms.MelSpectrogram( mean, std = -4, 4
n_mels=80, n_fft=2048, win_length=1200, hop_length=300)
mean, std = -4, 4 def length_to_mask(lengths):
mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
def length_to_mask(lengths): mask = torch.gt(mask+1, lengths.unsqueeze(1))
mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) return mask
mask = torch.gt(mask+1, lengths.unsqueeze(1))
return mask def preprocess(wave):
wave_tensor = torch.from_numpy(wave).float()
def preprocess(wave): mel_tensor = to_mel(wave_tensor)
wave_tensor = torch.from_numpy(wave).float() mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
mel_tensor = to_mel(wave_tensor) return mel_tensor
mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
return mel_tensor def compute_style(path, save_npz=False, npz_path=None):
wave, sr = librosa.load(path, sr=24000)
def compute_style(path): audio, index = librosa.effects.trim(wave, top_db=30)
wave, sr = librosa.load(path, sr=24000) if sr != 24000:
audio, index = librosa.effects.trim(wave, top_db=30) audio = librosa.resample(audio, sr, 24000)
if sr != 24000: mel_tensor = preprocess(audio).to(device)
audio = librosa.resample(audio, sr, 24000)
mel_tensor = preprocess(audio).to(device) with torch.no_grad():
ref_s = model.style_encoder(mel_tensor.unsqueeze(1))
with torch.no_grad(): ref_p = model.predictor_encoder(mel_tensor.unsqueeze(1))
ref_s = model.style_encoder(mel_tensor.unsqueeze(1)) style_vector = torch.cat([ref_s, ref_p], dim=1)
ref_p = model.predictor_encoder(mel_tensor.unsqueeze(1))
# Save style vector to NPZ file if requested
return torch.cat([ref_s, ref_p], dim=1) if save_npz and npz_path:
np.savez(npz_path, style_vector=style_vector.cpu().numpy())
device = 'cpu'
if torch.cuda.is_available(): return style_vector
device = 'cuda'
elif torch.backends.mps.is_available(): device = 'cpu'
print("MPS would be available but cannot be used rn") if torch.cuda.is_available():
# device = 'mps' device = 'cuda'
elif torch.backends.mps.is_available():
import phonemizer print("MPS would be available but cannot be used rn")
global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True) # device = 'mps'
config = yaml.safe_load(open("Models/LibriTTS/config.yml")) import phonemizer
global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True)
# load pretrained ASR model
ASR_config = config.get('ASR_config', False) config = yaml.safe_load(open("Models/LibriTTS/config.yml"))
ASR_path = config.get('ASR_path', False)
text_aligner = load_ASR_models(ASR_path, ASR_config) # load pretrained ASR model
ASR_config = config.get('ASR_config', False)
# load pretrained F0 model ASR_path = config.get('ASR_path', False)
F0_path = config.get('F0_path', False) text_aligner = load_ASR_models(ASR_path, ASR_config)
pitch_extractor = load_F0_models(F0_path)
# load pretrained F0 model
# load BERT model F0_path = config.get('F0_path', False)
from Utils.PLBERT.util import load_plbert pitch_extractor = load_F0_models(F0_path)
BERT_path = config.get('PLBERT_dir', False)
plbert = load_plbert(BERT_path) # load BERT model
from Utils.PLBERT.util import load_plbert
model_params = recursive_munch(config['model_params']) BERT_path = config.get('PLBERT_dir', False)
model = build_model(model_params, text_aligner, pitch_extractor, plbert) plbert = load_plbert(BERT_path)
_ = [model[key].eval() for key in model]
_ = [model[key].to(device) for key in model] model_params = recursive_munch(config['model_params'])
model = build_model(model_params, text_aligner, pitch_extractor, plbert)
params_whole = torch.load("Models/LibriTTS/epochs_2nd_00020.pth", map_location='cpu') _ = [model[key].eval() for key in model]
params = params_whole['net'] _ = [model[key].to(device) for key in model]
for key in model: params_whole = torch.load("Models/LibriTTS/epochs_2nd_00020.pth", map_location='cpu')
if key in params: params = params_whole['net']
print('%s loaded' % key)
try: for key in model:
model[key].load_state_dict(params[key]) if key in params:
except: print('%s loaded' % key)
from collections import OrderedDict try:
state_dict = params[key] model[key].load_state_dict(params[key])
new_state_dict = OrderedDict() except:
for k, v in state_dict.items(): from collections import OrderedDict
name = k[7:] # remove `module.` state_dict = params[key]
new_state_dict[name] = v new_state_dict = OrderedDict()
# load params for k, v in state_dict.items():
model[key].load_state_dict(new_state_dict, strict=False) name = k[7:] # remove `module.`
# except: new_state_dict[name] = v
# _load(params[key], model[key]) # load params
_ = [model[key].eval() for key in model] model[key].load_state_dict(new_state_dict, strict=False)
# except:
from Modules.diffusion.sampler import DiffusionSampler, ADPM2Sampler, KarrasSchedule # _load(params[key], model[key])
_ = [model[key].eval() for key in model]
sampler = DiffusionSampler(
model.diffusion.diffusion, from Modules.diffusion.sampler import DiffusionSampler, ADPM2Sampler, KarrasSchedule
sampler=ADPM2Sampler(),
sigma_schedule=KarrasSchedule(sigma_min=0.0001, sigma_max=3.0, rho=9.0), # empirical parameters sampler = DiffusionSampler(
clamp=False model.diffusion.diffusion,
) sampler=ADPM2Sampler(),
sigma_schedule=KarrasSchedule(sigma_min=0.0001, sigma_max=3.0, rho=9.0), # empirical parameters
def inference(text, ref_s, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False): clamp=False
text = text.strip() )
ps = global_phonemizer.phonemize([text])
ps = word_tokenize(ps[0]) def inference(text, ref_s, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False):
ps = ' '.join(ps) text = text.strip()
tokens = textclenaer(ps) ps = global_phonemizer.phonemize([text])
tokens.insert(0, 0) ps = word_tokenize(ps[0])
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) ps = ' '.join(ps)
tokens = textclenaer(ps)
with torch.no_grad(): tokens.insert(0, 0)
input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device) tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
text_mask = length_to_mask(input_lengths).to(device)
with torch.no_grad():
t_en = model.text_encoder(tokens, input_lengths, text_mask) input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) text_mask = length_to_mask(input_lengths).to(device)
d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
t_en = model.text_encoder(tokens, input_lengths, text_mask)
s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), bert_dur = model.bert(tokens, attention_mask=(~text_mask).int())
embedding=bert_dur, d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
embedding_scale=embedding_scale,
features=ref_s, # reference from the same speaker as the embedding s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device),
num_steps=diffusion_steps).squeeze(1) embedding=bert_dur,
embedding_scale=embedding_scale,
features=ref_s, # reference from the same speaker as the embedding
s = s_pred[:, 128:] num_steps=diffusion_steps).squeeze(1)
ref = s_pred[:, :128]
ref = alpha * ref + (1 - alpha) * ref_s[:, :128] s = s_pred[:, 128:]
s = beta * s + (1 - beta) * ref_s[:, 128:] ref = s_pred[:, :128]
d = model.predictor.text_encoder(d_en, ref = alpha * ref + (1 - alpha) * ref_s[:, :128]
s, input_lengths, text_mask) s = beta * s + (1 - beta) * ref_s[:, 128:]
x, _ = model.predictor.lstm(d) d = model.predictor.text_encoder(d_en,
duration = model.predictor.duration_proj(x) s, input_lengths, text_mask)
duration = torch.sigmoid(duration).sum(axis=-1) x, _ = model.predictor.lstm(d)
pred_dur = torch.round(duration.squeeze()).clamp(min=1) duration = model.predictor.duration_proj(x)
duration = torch.sigmoid(duration).sum(axis=-1)
pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) pred_dur = torch.round(duration.squeeze()).clamp(min=1)
c_frame = 0
for i in range(pred_aln_trg.size(0)):
pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data))
c_frame += int(pred_dur[i].data) c_frame = 0
for i in range(pred_aln_trg.size(0)):
# encode prosody pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1
en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) c_frame += int(pred_dur[i].data)
if model_params.decoder.type == "hifigan":
asr_new = torch.zeros_like(en) # encode prosody
asr_new[:, :, 0] = en[:, :, 0] en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = en[:, :, 0:-1] if model_params.decoder.type == "hifigan":
en = asr_new asr_new = torch.zeros_like(en)
asr_new[:, :, 0] = en[:, :, 0]
F0_pred, N_pred = model.predictor.F0Ntrain(en, s) asr_new[:, :, 1:] = en[:, :, 0:-1]
en = asr_new
asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
if model_params.decoder.type == "hifigan": F0_pred, N_pred = model.predictor.F0Ntrain(en, s)
asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0] asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = asr[:, :, 0:-1] if model_params.decoder.type == "hifigan":
asr = asr_new asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0]
out = model.decoder(asr, asr_new[:, :, 1:] = asr[:, :, 0:-1]
F0_pred, N_pred, ref.squeeze().unsqueeze(0)) asr = asr_new
out = model.decoder(asr,
return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later F0_pred, N_pred, ref.squeeze().unsqueeze(0))
def LFinference(text, s_prev, ref_s, alpha = 0.3, beta = 0.7, t = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False):
text = text.strip() return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later
ps = global_phonemizer.phonemize([text])
ps = word_tokenize(ps[0]) def LFinference(text, s_prev, ref_s, alpha = 0.3, beta = 0.7, t = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False):
ps = ' '.join(ps) text = text.strip()
ps = ps.replace('``', '"') ps = global_phonemizer.phonemize([text])
ps = ps.replace("''", '"') ps = word_tokenize(ps[0])
ps = ' '.join(ps)
tokens = textclenaer(ps) ps = ps.replace('``', '"')
tokens.insert(0, 0) ps = ps.replace("''", '"')
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
tokens = textclenaer(ps)
with torch.no_grad(): tokens.insert(0, 0)
input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device) tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
text_mask = length_to_mask(input_lengths).to(device)
with torch.no_grad():
t_en = model.text_encoder(tokens, input_lengths, text_mask) input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) text_mask = length_to_mask(input_lengths).to(device)
d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
t_en = model.text_encoder(tokens, input_lengths, text_mask)
s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), bert_dur = model.bert(tokens, attention_mask=(~text_mask).int())
embedding=bert_dur, d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
embedding_scale=embedding_scale,
features=ref_s, # reference from the same speaker as the embedding s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device),
num_steps=diffusion_steps).squeeze(1) embedding=bert_dur,
embedding_scale=embedding_scale,
if s_prev is not None: features=ref_s, # reference from the same speaker as the embedding
# convex combination of previous and current style num_steps=diffusion_steps).squeeze(1)
s_pred = t * s_prev + (1 - t) * s_pred
if s_prev is not None:
s = s_pred[:, 128:] # convex combination of previous and current style
ref = s_pred[:, :128] s_pred = t * s_prev + (1 - t) * s_pred
ref = alpha * ref + (1 - alpha) * ref_s[:, :128] s = s_pred[:, 128:]
s = beta * s + (1 - beta) * ref_s[:, 128:] ref = s_pred[:, :128]
s_pred = torch.cat([ref, s], dim=-1) ref = alpha * ref + (1 - alpha) * ref_s[:, :128]
s = beta * s + (1 - beta) * ref_s[:, 128:]
d = model.predictor.text_encoder(d_en,
s, input_lengths, text_mask) s_pred = torch.cat([ref, s], dim=-1)
x, _ = model.predictor.lstm(d) d = model.predictor.text_encoder(d_en,
duration = model.predictor.duration_proj(x) s, input_lengths, text_mask)
duration = torch.sigmoid(duration).sum(axis=-1) x, _ = model.predictor.lstm(d)
pred_dur = torch.round(duration.squeeze()).clamp(min=1) duration = model.predictor.duration_proj(x)
duration = torch.sigmoid(duration).sum(axis=-1)
pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) pred_dur = torch.round(duration.squeeze()).clamp(min=1)
c_frame = 0
for i in range(pred_aln_trg.size(0)):
pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data))
c_frame += int(pred_dur[i].data) c_frame = 0
for i in range(pred_aln_trg.size(0)):
# encode prosody pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1
en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) c_frame += int(pred_dur[i].data)
if model_params.decoder.type == "hifigan":
asr_new = torch.zeros_like(en) # encode prosody
asr_new[:, :, 0] = en[:, :, 0] en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = en[:, :, 0:-1] if model_params.decoder.type == "hifigan":
en = asr_new asr_new = torch.zeros_like(en)
asr_new[:, :, 0] = en[:, :, 0]
F0_pred, N_pred = model.predictor.F0Ntrain(en, s) asr_new[:, :, 1:] = en[:, :, 0:-1]
en = asr_new
asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
if model_params.decoder.type == "hifigan": F0_pred, N_pred = model.predictor.F0Ntrain(en, s)
asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0] asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = asr[:, :, 0:-1] if model_params.decoder.type == "hifigan":
asr = asr_new asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0]
out = model.decoder(asr, asr_new[:, :, 1:] = asr[:, :, 0:-1]
F0_pred, N_pred, ref.squeeze().unsqueeze(0)) asr = asr_new
out = model.decoder(asr,
return out.squeeze().cpu().numpy()[..., :-100], s_pred # weird pulse at the end of the model, need to be fixed later F0_pred, N_pred, ref.squeeze().unsqueeze(0))
def STinference(text, ref_s, ref_text, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False):
text = text.strip() return out.squeeze().cpu().numpy()[..., :-100], s_pred # weird pulse at the end of the model, need to be fixed later
ps = global_phonemizer.phonemize([text])
ps = word_tokenize(ps[0]) def STinference(text, ref_s, ref_text, alpha = 0.3, beta = 0.7, diffusion_steps=5, embedding_scale=1, use_gruut=False):
ps = ' '.join(ps) text = text.strip()
ps = global_phonemizer.phonemize([text])
tokens = textclenaer(ps) ps = word_tokenize(ps[0])
tokens.insert(0, 0) ps = ' '.join(ps)
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
tokens = textclenaer(ps)
ref_text = ref_text.strip() tokens.insert(0, 0)
ps = global_phonemizer.phonemize([ref_text]) tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
ps = word_tokenize(ps[0])
ps = ' '.join(ps) ref_text = ref_text.strip()
ps = global_phonemizer.phonemize([ref_text])
ref_tokens = textclenaer(ps) ps = word_tokenize(ps[0])
ref_tokens.insert(0, 0) ps = ' '.join(ps)
ref_tokens = torch.LongTensor(ref_tokens).to(device).unsqueeze(0)
ref_tokens = textclenaer(ps)
ref_tokens.insert(0, 0)
with torch.no_grad(): ref_tokens = torch.LongTensor(ref_tokens).to(device).unsqueeze(0)
input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
text_mask = length_to_mask(input_lengths).to(device)
with torch.no_grad():
t_en = model.text_encoder(tokens, input_lengths, text_mask) input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) text_mask = length_to_mask(input_lengths).to(device)
d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
t_en = model.text_encoder(tokens, input_lengths, text_mask)
ref_input_lengths = torch.LongTensor([ref_tokens.shape[-1]]).to(device) bert_dur = model.bert(tokens, attention_mask=(~text_mask).int())
ref_text_mask = length_to_mask(ref_input_lengths).to(device) d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
ref_bert_dur = model.bert(ref_tokens, attention_mask=(~ref_text_mask).int())
s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device), ref_input_lengths = torch.LongTensor([ref_tokens.shape[-1]]).to(device)
embedding=bert_dur, ref_text_mask = length_to_mask(ref_input_lengths).to(device)
embedding_scale=embedding_scale, ref_bert_dur = model.bert(ref_tokens, attention_mask=(~ref_text_mask).int())
features=ref_s, # reference from the same speaker as the embedding s_pred = sampler(noise = torch.randn((1, 256)).unsqueeze(1).to(device),
num_steps=diffusion_steps).squeeze(1) embedding=bert_dur,
embedding_scale=embedding_scale,
features=ref_s, # reference from the same speaker as the embedding
s = s_pred[:, 128:] num_steps=diffusion_steps).squeeze(1)
ref = s_pred[:, :128]
ref = alpha * ref + (1 - alpha) * ref_s[:, :128] s = s_pred[:, 128:]
s = beta * s + (1 - beta) * ref_s[:, 128:] ref = s_pred[:, :128]
d = model.predictor.text_encoder(d_en, ref = alpha * ref + (1 - alpha) * ref_s[:, :128]
s, input_lengths, text_mask) s = beta * s + (1 - beta) * ref_s[:, 128:]
x, _ = model.predictor.lstm(d) d = model.predictor.text_encoder(d_en,
duration = model.predictor.duration_proj(x) s, input_lengths, text_mask)
duration = torch.sigmoid(duration).sum(axis=-1) x, _ = model.predictor.lstm(d)
pred_dur = torch.round(duration.squeeze()).clamp(min=1) duration = model.predictor.duration_proj(x)
duration = torch.sigmoid(duration).sum(axis=-1)
pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) pred_dur = torch.round(duration.squeeze()).clamp(min=1)
c_frame = 0
for i in range(pred_aln_trg.size(0)):
pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1 pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data))
c_frame += int(pred_dur[i].data) c_frame = 0
for i in range(pred_aln_trg.size(0)):
# encode prosody pred_aln_trg[i, c_frame:c_frame + int(pred_dur[i].data)] = 1
en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) c_frame += int(pred_dur[i].data)
if model_params.decoder.type == "hifigan":
asr_new = torch.zeros_like(en) # encode prosody
asr_new[:, :, 0] = en[:, :, 0] en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = en[:, :, 0:-1] if model_params.decoder.type == "hifigan":
en = asr_new asr_new = torch.zeros_like(en)
asr_new[:, :, 0] = en[:, :, 0]
F0_pred, N_pred = model.predictor.F0Ntrain(en, s) asr_new[:, :, 1:] = en[:, :, 0:-1]
en = asr_new
asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
if model_params.decoder.type == "hifigan": F0_pred, N_pred = model.predictor.F0Ntrain(en, s)
asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0] asr = (t_en @ pred_aln_trg.unsqueeze(0).to(device))
asr_new[:, :, 1:] = asr[:, :, 0:-1] if model_params.decoder.type == "hifigan":
asr = asr_new asr_new = torch.zeros_like(asr)
asr_new[:, :, 0] = asr[:, :, 0]
out = model.decoder(asr, asr_new[:, :, 1:] = asr[:, :, 0:-1]
F0_pred, N_pred, ref.squeeze().unsqueeze(0)) asr = asr_new
out = model.decoder(asr,
return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later F0_pred, N_pred, ref.squeeze().unsqueeze(0))
return out.squeeze().cpu().numpy()[..., :-50] # weird pulse at the end of the model, need to be fixed later