CoolFace
Apppublic

goathead777/Zero_Shot_Inference

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
inference_webui.py361 linesDownload Raw Back to root
1import os2 3gpt_path = os.environ.get(4    "gpt_path", "pretrained_models/s1bert25hz-2kh-longer-epoch=68e-step=50232.ckpt"5)6sovits_path = os.environ.get("sovits_path", "pretrained_models/s2G488k.pth")7cnhubert_base_path = os.environ.get(8    "cnhubert_base_path", "pretrained_models/chinese-hubert-base"9)10bert_path = os.environ.get(11    "bert_path", "pretrained_models/chinese-roberta-wwm-ext-large"12)13infer_ttswebui = os.environ.get("infer_ttswebui", 9872)14infer_ttswebui = int(infer_ttswebui)15if "_CUDA_VISIBLE_DEVICES" in os.environ:16    os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]17is_half = eval(os.environ.get("is_half", "True"))18import gradio as gr19from transformers import AutoModelForMaskedLM, AutoTokenizer20import numpy as np21import librosa,torch22from feature_extractor import cnhubert23cnhubert.cnhubert_base_path=cnhubert_base_path24 25from module.models import SynthesizerTrn26from AR.models.t2s_lightning_module import Text2SemanticLightningModule27from text import cleaned_text_to_sequence28from text.cleaner import clean_text29from time import time as ttime30from module.mel_processing import spectrogram_torch31from my_utils import load_audio32 33device = "cuda"34tokenizer = AutoTokenizer.from_pretrained(bert_path)35bert_model = AutoModelForMaskedLM.from_pretrained(bert_path)36if is_half == True:37    bert_model = bert_model.half().to(device)38else:39    bert_model = bert_model.to(device)40 41 42# bert_model=bert_model.to(device)43def get_bert_feature(text, word2ph):44    with torch.no_grad():45        inputs = tokenizer(text, return_tensors="pt")46        for i in inputs:47            inputs[i] = inputs[i].to(device)  #####输入是long不用管精度问题,精度随bert_model48        res = bert_model(**inputs, output_hidden_states=True)49        res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()[1:-1]50    assert len(word2ph) == len(text)51    phone_level_feature = []52    for i in range(len(word2ph)):53        repeat_feature = res[i].repeat(word2ph[i], 1)54        phone_level_feature.append(repeat_feature)55    phone_level_feature = torch.cat(phone_level_feature, dim=0)56    # if(is_half==True):phone_level_feature=phone_level_feature.half()57    return phone_level_feature.T58 59 60n_semantic = 102461 62dict_s2=torch.load(sovits_path,map_location="cpu")63hps=dict_s2["config"]64 65class DictToAttrRecursive(dict):66    def __init__(self, input_dict):67        super().__init__(input_dict)68        for key, value in input_dict.items():69            if isinstance(value, dict):70                value = DictToAttrRecursive(value)71            self[key] = value72            setattr(self, key, value)73 74    def __getattr__(self, item):75        try:76            return self[item]77        except KeyError:78            raise AttributeError(f"Attribute {item} not found")79 80    def __setattr__(self, key, value):81        if isinstance(value, dict):82            value = DictToAttrRecursive(value)83        super(DictToAttrRecursive, self).__setitem__(key, value)84        super().__setattr__(key, value)85 86    def __delattr__(self, item):87        try:88            del self[item]89        except KeyError:90            raise AttributeError(f"Attribute {item} not found")91 92 93hps = DictToAttrRecursive(hps)94 95hps.model.semantic_frame_rate = "25hz"96dict_s1 = torch.load(gpt_path, map_location="cpu")97config = dict_s1["config"]98ssl_model = cnhubert.get_model()99if is_half == True:100    ssl_model = ssl_model.half().to(device)101else:102    ssl_model = ssl_model.to(device)103 104vq_model = SynthesizerTrn(105    hps.data.filter_length // 2 + 1,106    hps.train.segment_size // hps.data.hop_length,107    n_speakers=hps.data.n_speakers,108    **hps.model109)110if is_half == True:111    vq_model = vq_model.half().to(device)112else:113    vq_model = vq_model.to(device)114vq_model.eval()115print(vq_model.load_state_dict(dict_s2["weight"], strict=False))116hz = 50117max_sec = config["data"]["max_sec"]118# t2s_model = Text2SemanticLightningModule.load_from_checkpoint(checkpoint_path=gpt_path, config=config, map_location="cpu")#########todo119t2s_model = Text2SemanticLightningModule(config, "ojbk", is_train=False)120t2s_model.load_state_dict(dict_s1["weight"])121if is_half == True:122    t2s_model = t2s_model.half()123t2s_model = t2s_model.to(device)124t2s_model.eval()125total = sum([param.nelement() for param in t2s_model.parameters()])126print("Number of parameter: %.2fM" % (total / 1e6))127 128 129def get_spepc(hps, filename):130    audio = load_audio(filename, int(hps.data.sampling_rate))131    audio = torch.FloatTensor(audio)132    audio_norm = audio133    audio_norm = audio_norm.unsqueeze(0)134    spec = spectrogram_torch(135        audio_norm,136        hps.data.filter_length,137        hps.data.sampling_rate,138        hps.data.hop_length,139        hps.data.win_length,140        center=False,141    )142    return spec143 144 145dict_language = {"中文": "zh", "英文": "en", "日文": "ja"}146 147 148def get_tts_wav(ref_wav_path, prompt_text, prompt_language, text, text_language):149    t0 = ttime()150    prompt_text = prompt_text.strip("\n")151    prompt_language, text = prompt_language, text.strip("\n")152    with torch.no_grad():153        wav16k, sr = librosa.load(ref_wav_path, sr=16000)  # 派蒙154        wav16k = torch.from_numpy(wav16k)155        if is_half == True:156            wav16k = wav16k.half().to(device)157        else:158            wav16k = wav16k.to(device)159        ssl_content = ssl_model.model(wav16k.unsqueeze(0))[160            "last_hidden_state"161        ].transpose(162            1, 2163        )  # .float()164        codes = vq_model.extract_latent(ssl_content)165        prompt_semantic = codes[0, 0]166    t1 = ttime()167    prompt_language = dict_language[prompt_language]168    text_language = dict_language[text_language]169    phones1, word2ph1, norm_text1 = clean_text(prompt_text, prompt_language)170    phones1 = cleaned_text_to_sequence(phones1)171    texts = text.split("\n")172    audio_opt = []173    zero_wav = np.zeros(174        int(hps.data.sampling_rate * 0.3),175        dtype=np.float16 if is_half == True else np.float32,176    )177    for text in texts:178        phones2, word2ph2, norm_text2 = clean_text(text, text_language)179        phones2 = cleaned_text_to_sequence(phones2)180        if prompt_language == "zh":181            bert1 = get_bert_feature(norm_text1, word2ph1).to(device)182        else:183            bert1 = torch.zeros(184                (1024, len(phones1)),185                dtype=torch.float16 if is_half == True else torch.float32,186            ).to(device)187        if text_language == "zh":188            bert2 = get_bert_feature(norm_text2, word2ph2).to(device)189        else:190            bert2 = torch.zeros((1024, len(phones2))).to(bert1)191        bert = torch.cat([bert1, bert2], 1)192 193        all_phoneme_ids = torch.LongTensor(phones1 + phones2).to(device).unsqueeze(0)194        bert = bert.to(device).unsqueeze(0)195        all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)196        prompt = prompt_semantic.unsqueeze(0).to(device)197        t2 = ttime()198        with torch.no_grad():199            # pred_semantic = t2s_model.model.infer(200            pred_semantic, idx = t2s_model.model.infer_panel(201                all_phoneme_ids,202                all_phoneme_len,203                prompt,204                bert,205                # prompt_phone_len=ph_offset,206                top_k=config["inference"]["top_k"],207                early_stop_num=hz * max_sec,208            )209        t3 = ttime()210        # print(pred_semantic.shape,idx)211        pred_semantic = pred_semantic[:, -idx:].unsqueeze(212            0213        )  # .unsqueeze(0)#mq要多unsqueeze一次214        refer = get_spepc(hps, ref_wav_path)  # .to(device)215        if is_half == True:216            refer = refer.half().to(device)217        else:218            refer = refer.to(device)219        # audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]220        audio = (221            vq_model.decode(222                pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer223            )224            .detach()225            .cpu()226            .numpy()[0, 0]227        )  ###试试重建不带上prompt部分228        audio_opt.append(audio)229        audio_opt.append(zero_wav)230        t4 = ttime()231    print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))232    yield hps.data.sampling_rate, (np.concatenate(audio_opt, 0) * 32768).astype(233        np.int16234    )235 236 237splits = {238    ",",239    "。",240    "?",241    "!",242    ",",243    ".",244    "?",245    "!",246    "~",247    ":",248    ":",249    "—",250    "…",251}  # 不考虑省略号252 253 254def split(todo_text):255    todo_text = todo_text.replace("……", "。").replace("——", ",")256    if todo_text[-1] not in splits:257        todo_text += "。"258    i_split_head = i_split_tail = 0259    len_text = len(todo_text)260    todo_texts = []261    while 1:262        if i_split_head >= len_text:263            break  # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入264        if todo_text[i_split_head] in splits:265            i_split_head += 1266            todo_texts.append(todo_text[i_split_tail:i_split_head])267            i_split_tail = i_split_head268        else:269            i_split_head += 1270    return todo_texts271 272 273def cut1(inp):274    inp = inp.strip("\n")275    inps = split(inp)276    split_idx = list(range(0, len(inps), 5))277    split_idx[-1] = None278    if len(split_idx) > 1:279        opts = []280        for idx in range(len(split_idx) - 1):281            opts.append("".join(inps[split_idx[idx] : split_idx[idx + 1]]))282    else:283        opts = [inp]284    return "\n".join(opts)285 286 287def cut2(inp):288    inp = inp.strip("\n")289    inps = split(inp)290    if len(inps) < 2:291        return [inp]292    opts = []293    summ = 0294    tmp_str = ""295    for i in range(len(inps)):296        summ += len(inps[i])297        tmp_str += inps[i]298        if summ > 50:299            summ = 0300            opts.append(tmp_str)301            tmp_str = ""302    if tmp_str != "":303        opts.append(tmp_str)304    if len(opts[-1]) < 50:  ##如果最后一个太短了,和前一个合一起305        opts[-2] = opts[-2] + opts[-1]306        opts = opts[:-1]307    return "\n".join(opts)308 309 310def cut3(inp):311    inp = inp.strip("\n")312    return "\n".join(["%s。" % item for item in inp.strip("。").split("。")])313 314 315with gr.Blocks(title="GPT-SoVITS WebUI") as app:316    gr.Markdown(317        value="本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责. <br>如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录<b>LICENSE</b>."318    )319    # with gr.Tabs():320    #     with gr.TabItem(i18n("伴奏人声分离&去混响&去回声")):321    with gr.Group():322        gr.Markdown(value="*请上传并填写参考信息")323        with gr.Row():324            inp_ref = gr.Audio(label="请上传参考音频", type="filepath")325            prompt_text = gr.Textbox(label="参考音频的文本", value="")326            prompt_language = gr.Dropdown(327                label="参考音频的语种", choices=["中文", "英文", "日文"], value="中文"328            )329        gr.Markdown(value="*请填写需要合成的目标文本")330        with gr.Row():331            text = gr.Textbox(label="需要合成的文本", value="")332            text_language = gr.Dropdown(333                label="需要合成的语种", choices=["中文", "英文", "日文"], value="中文"334            )335            inference_button = gr.Button("合成语音", variant="primary")336            output = gr.Audio(label="输出的语音")337        inference_button.click(338            get_tts_wav,339            [inp_ref, prompt_text, prompt_language, text, text_language],340            [output],341        )342 343        gr.Markdown(value="文本切分工具。太长的文本合成出来效果不一定好,所以太长建议先切。合成会根据文本的换行分开合成再拼起来。")344        with gr.Row():345            text_inp = gr.Textbox(label="需要合成的切分前文本", value="")346            button1 = gr.Button("凑五句一切", variant="primary")347            button2 = gr.Button("凑50字一切", variant="primary")348            button3 = gr.Button("按中文句号。切", variant="primary")349            text_opt = gr.Textbox(label="切分后文本", value="")350            button1.click(cut1, [text_inp], [text_opt])351            button2.click(cut2, [text_inp], [text_opt])352            button3.click(cut3, [text_inp], [text_opt])353        gr.Markdown(value="后续将支持混合语种编码文本输入。")354 355app.queue(concurrency_count=511, max_size=1022).launch(356    server_name="0.0.0.0",357    inbrowser=True,358    server_port=infer_ttswebui,359    quiet=True,360)361