Spaces:
Running
on
Zero
Running
on
Zero
import torch | |
torch.manual_seed(0) | |
torch.backends.cudnn.benchmark = False | |
torch.backends.cudnn.deterministic = True | |
import random | |
random.seed(0) | |
import numpy as np | |
np.random.seed(0) | |
import spaces | |
import yaml | |
import re | |
import numpy as np | |
import torch | |
import torch.nn.functional as F | |
import torchaudio | |
from ipa_uk import ipa | |
from unicodedata import normalize | |
from ukrainian_word_stress import Stressifier, StressSymbol | |
stressify = Stressifier() | |
from models import * | |
from utils import * | |
from text_utils import TextCleaner | |
textclenaer = TextCleaner() | |
device = 'cuda' if torch.cuda.is_available() else 'cpu' | |
to_mel = torchaudio.transforms.MelSpectrogram( | |
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) | |
mask = torch.gt(mask+1, lengths.unsqueeze(1)) | |
return mask | |
config = yaml.safe_load(open('styletts_config.yml')) | |
# load pretrained ASR model | |
ASR_config = config.get('ASR_config', False) | |
ASR_path = config.get('ASR_path', False) | |
text_aligner = load_ASR_models(ASR_path, ASR_config) | |
# load pretrained F0 model | |
F0_path = config.get('F0_path', False) | |
pitch_extractor = load_F0_models(F0_path) | |
# load BERT model | |
from Utils.PLBERT.util import load_plbert | |
plbert = load_plbert('weights/plbert.bin', 'Utils/PLBERT/config.yml') | |
model = build_model(recursive_munch(config['model_params']), text_aligner, pitch_extractor, plbert) | |
_ = [model[key].eval() for key in model] | |
_ = [model[key].to(device) for key in model] | |
params = torch.load('weights/filatov.bin', map_location='cpu') | |
for key in model: | |
if key in params: | |
print('%s loaded' % key) | |
try: | |
model[key].load_state_dict(params[key]) | |
except: | |
from collections import OrderedDict | |
state_dict = params[key] | |
new_state_dict = OrderedDict() | |
for k, v in state_dict.items(): | |
name = k[7:] # remove `module.` | |
new_state_dict[name] = v | |
# load params | |
model[key].load_state_dict(new_state_dict, strict=False) | |
# except: | |
# _load(params[key], model[key]) | |
_ = [model[key].eval() for key in model] | |
from Modules.diffusion.sampler import DiffusionSampler, ADPM2Sampler, KarrasSchedule | |
sampler = DiffusionSampler( | |
model.diffusion.diffusion, | |
sampler=ADPM2Sampler(), | |
sigma_schedule=KarrasSchedule(sigma_min=0.0001, sigma_max=3.0, rho=9.0), # empirical parameters | |
clamp=False | |
) | |
def split_to_parts(text): | |
split_symbols = '.?!:' | |
parts = [''] | |
index = 0 | |
for s in text: | |
parts[index] += s | |
if s in split_symbols and len(parts[index]) > 150: | |
index += 1 | |
parts.append('') | |
return parts | |
def _inf(text, speed, s_prev, noise, alpha, diffusion_steps, embedding_scale): | |
text = text.strip() | |
text = text.replace('"', '') | |
text = text.replace('+', '\u0301') | |
text = normalize('NFKC', text) | |
text = re.sub(r'[α βββββββ»βββΈΊβΈ»]', '-', text) | |
text = re.sub(r' - ', ': ', text) | |
stressed = stressify(text) | |
ps = ipa(stressed) | |
print(stressed) | |
tokens = textclenaer(ps) | |
tokens.insert(0, 0) | |
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0) | |
with torch.no_grad(): | |
input_lengths = torch.LongTensor([tokens.shape[-1]]).to(tokens.device) | |
text_mask = length_to_mask(input_lengths).to(tokens.device) | |
t_en = model.text_encoder(tokens, input_lengths, text_mask) | |
bert_dur = model.bert(tokens, attention_mask=(~text_mask).int()) | |
d_en = model.bert_encoder(bert_dur).transpose(-1, -2) | |
s_pred = sampler(noise, | |
embedding=bert_dur[0].unsqueeze(0), num_steps=diffusion_steps, | |
embedding_scale=embedding_scale).squeeze(0) | |
if s_prev is not None: | |
# convex combination of previous and current style | |
s_pred = alpha * s_prev + (1 - alpha) * s_pred | |
s = s_pred[:, 128:] | |
ref = s_pred[:, :128] | |
d = model.predictor.text_encoder(d_en, s, input_lengths, text_mask) | |
x, _ = model.predictor.lstm(d) | |
duration = model.predictor.duration_proj(x) | |
duration = torch.sigmoid(duration).sum(axis=-1)/speed | |
pred_dur = torch.round(duration.squeeze()).clamp(min=1) | |
pred_aln_trg = torch.zeros(input_lengths, int(pred_dur.sum().data)) | |
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 | |
c_frame += int(pred_dur[i].data) | |
# encode prosody | |
en = (d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)) | |
F0_pred, N_pred = model.predictor.F0Ntrain(en, s) | |
out = model.decoder((t_en @ pred_aln_trg.unsqueeze(0).to(device)), | |
F0_pred, N_pred, ref.squeeze().unsqueeze(0)) | |
return out.squeeze().cpu().numpy(), s_pred, ps | |
def inference(text, progress, speed = 1.0, alpha=0.7, diffusion_steps=10, embedding_scale=1.2): | |
wavs = [] | |
s_prev = None | |
#sentences = text.split('|') | |
sentences = split_to_parts(text) | |
print(sentences) | |
phonemes = '' | |
noise = torch.randn(1,1,256).to(device) | |
for text in progress.tqdm(sentences): | |
if text.strip() == "": continue | |
wav, s_prev, ps = _inf(text, speed, s_prev, noise, alpha=alpha, diffusion_steps=diffusion_steps, embedding_scale=embedding_scale) | |
wavs.append(wav) | |
phonemes += ' ' + ps | |
return np.concatenate(wavs), phonemes | |