File size: 7,641 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
131
132
133
134
135
136
137
138
139
140
141
from text import cleaned_text_to_sequence
from text.cleaner import text_to_sequence, clean_text
from gen_phonemes import get_bert_feature
import torch.nn.functional as F
from module import commons
import torch    
import utils
from module.models import SynthesizerTrn
from module.mel_processing import spectrogram_torch, spec_to_mel_torch
import soundfile
import torchaudio
from pyannote.audio import Model
from pyannote.audio import Inference
from s1.trainer import Wav2TTS
import json


class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

def text2phoneid(text, lang='zh'):
    phones, word2ph, norm_text = clean_text(text, lang)
    print(phones)

    bert = get_bert_feature(norm_text, word2ph, 'cpu', lang)
    phoneme_ids = cleaned_text_to_sequence(phones)
    
    phonemes = [0] * (len(phoneme_ids) * 3)
    phonemes[1::3] = phoneme_ids
        

    bert = F.interpolate(bert.unsqueeze(0), scale_factor=3, mode='nearest')
    return phones, phonemes, bert



def load_model(device="cuda", config_path_s2="configs/vits.json",config_path_s1="configs/mq.json", model_path_s2=None, model_path_s1=None):
    device = torch.device(device)
    print('loading models...')
    hps = utils.get_hparams_from_file(config_path_s2)
    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)
    if model_path_s2 is None:
        model_path_s2 = utils.latest_checkpoint_path(hps.s2_ckpt_dir, "G_*.pth")
    utils.load_checkpoint(model_path_s2, net_g,
                          None, False)
    net_g.eval()
    spk_emb_model = Model.from_pretrained("pyannote/wespeaker-voxceleb-resnet34-LM")
    spk_emb_model = spk_emb_model.to(device)
    inference = Inference(spk_emb_model, window="whole")

    args = AttrDict()

    arg_dict = json.load(open('configs/mq.json', 'r'))
    args.__dict__.update(arg_dict)
    training_wrapper = Wav2TTS(args, vits_s2=net_g).to(device)
    state_dict = torch.load(model_path_s1, map_location='cpu')
    training_wrapper.load_state_dict(state_dict['state_dict'])
    training_wrapper.eval()

    return hps, net_g, training_wrapper, inference



def get_spepc(hps, filename):
    audio, sampling_rate = utils.load_wav_to_torch(filename)
    audio = audio.unsqueeze(0)
    if sampling_rate != hps.data.sampling_rate:
        audio = torchaudio.functional.resample(audio, sampling_rate, hps.data.sampling_rate)
    audio_norm = audio
    spec = spectrogram_torch(audio_norm, hps.data.filter_length,
                             hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,
                             center=False)
    return spec


@torch.no_grad()
def inference(models, text, reference_path):
    hps, model,model_s1, spk_emb_model = models
    device = model.parameters().__next__().device
    phlist, phones, bert = text2phoneid(text)
    print(len(phones))
    ref = get_spepc(hps, reference_path).to(device)
    spk_emb = spk_emb_model(reference_path)
    spk_emb = torch.FloatTensor(spk_emb).to(device).unsqueeze(0)

    all_phoneme_ids = torch.LongTensor(phones).to(device).unsqueeze(0)
    bert = bert.to(device)
    x_lengths = torch.LongTensor([all_phoneme_ids.shape[-1]]).to(device)
    ref_lengths = torch.LongTensor([ref.shape[-1]]).to(device)

    ref_latent = torch.load(reference_path.replace(".wav", ".latent.pt"))
    ref_latent = ref_latent.to(device)

    tokens = model_s1.inference(all_phoneme_ids, bert,ref_latent, n_steps=2, guidance=1.5)
    
    print(tokens.shape, x_lengths)
    wavs = model.decode(tokens, all_phoneme_ids, x_lengths, ref, ref_lengths, noise_scale=0.5)
    # wavs = model.infer(all_phoneme_ids, x_lengths, ref, bert, spk_emb, noise_scale=.4)
    return wavs

import os
if __name__ == '__main__':

    device = 'cuda:0'
    outdir = 'out_fm_cfg'
    os.makedirs(outdir, exist_ok=True)
    txt_list = [
        '大家好啊,我是派蒙啊,今天来点大家想看的东西!',
         "先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。",
        '话说天下大势,分久必合,合久必分。周末七国分争,并入于秦。及秦灭之后,楚汉分争,又并入于汉。汉朝自高祖斩白蛇而起义,一统天下,后来光武中兴,传至献帝,遂分为三国。',
        ' “最难沟通的就是读过一些书,但满脑子标准答案的人”。这句话也包括这位up,没人能保证自己说的一定是对的,自己的立场一定是公正的。',
        '而且椅子背都很高,坐下时候基本看不到前后排的。怎么形成围观的?',
        '同样参数情况下,不同种子的差距有点大,在不指定风格的情况下,动漫真人随机出现。至于NSFW这一块,我认为它与SD3完全不一样,没有审查,是能出特定内容的,以后说不定有Pony',
        '这个不能搞颜色,个人感觉好像是优先出拟真风格的图[笑哭]另外贼TM吃内存,独显直连模式显存吃到15.5,内存32直接吃满,虚拟内存占用没看,速度挺慢4090m要几十秒。',
        '但是与此同时,从以色列政府的考虑来说,在面对这种压力的时候,还要考虑到极右翼他们的诉求,现在毕竟在国内政治出现波折之时,正是内塔尼亚胡政府受到了六十四名极右翼议员的支持,才保证这种政府的维系。',
        '如果真的是货物差异给了补偿达到南方电网满意就不会被南方电网拉黑了。既然拉黑了肯定是没谈拢南方电网被迫做出的拉黑决定。要道歉早点干啥去了人家拉黑了才出来道歉,果真欺软怕硬 软骨头。',
        '可爱的小猫猫……嘿嘿🤤……可爱的小猫猫……嘿嘿[爱心]🤤……可爱的小猫猫……[爱心]……嘿嘿🤤……可爱的小猫猫…(吸)身上的味道……好好闻~[爱心]',
        '就是要顶住800p画质三十帧,一到复杂场景',
        '人的记忆力会随着岁月的流逝而衰退,写作可以弥补记忆的不足,将曾经的人生经历和感悟记录下来,也便于保存一份美好的回忆。',
        '范文书写有哪些要求呢?我们怎样才能写好一篇范文呢?下面是小编帮大家整理的优质范文,仅供参考,大家一起来看看吧。',
        '当年高中毕业我都挑好游戏本了,结果亲戚送的当年最新的surface,还是最低配,被动散热加128g大容量。这是我用过最勾史的笔记本。',
        '也是几乎在同时期被带向了世界各地,日本音乐界自然也受到了其影响。1956年日本作词作曲家原六朗借曼波音乐的形式,创作了这首以江户祭典为主题的歌曲《祭典曼波》',
        '要性能没性能 要性价比没性价比 兼容还没传统x86强,难不成买来就是为了当个精致的office启动器?[笑哭]'
    ]

    prompt_list = [ "/home/rcell/genshin_data/zh/派蒙/vo_DQAQ003_1_paimon_06.wav"]

    
    all_models = load_model(device=device, model_path_s1='logs/s1/last.ckpt')

    for name, text in enumerate(txt_list):
        for i, prompt_wav_path in enumerate(prompt_list):
            out_path = f'{outdir}/{name}_{i}.wav'
            wavs = inference(all_models, text, prompt_wav_path)
            soundfile.write(out_path, wavs[0,0].cpu().numpy(), 32000)