CoolFace
Apppublic

hanfish/LSai

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py289 linesDownload Raw Back to root
1import os2cnhubert_base_path = "pretrained_models/chinese-hubert-base"3bert_path = "pretrained_models/chinese-roberta-wwm-ext-large"4 5import gradio as gr6from transformers import AutoModelForMaskedLM, AutoTokenizer7import sys,torch,numpy as np8from pathlib import Path9import os,pdb,utils,librosa,math,traceback,requests,argparse,torch,multiprocessing,pandas as pd,torch.multiprocessing as mp,soundfile10# torch.backends.cuda.sdp_kernel("flash")11# torch.backends.cuda.enable_flash_sdp(True)12# torch.backends.cuda.enable_mem_efficient_sdp(True)  # Not avaliable if torch version is lower than 2.013# torch.backends.cuda.enable_math_sdp(True)14from random import shuffle15from AR.utils import get_newest_ckpt16from glob import glob17from tqdm import tqdm18from feature_extractor import cnhubert19cnhubert.cnhubert_base_path=cnhubert_base_path20from io import BytesIO21from module.models import SynthesizerTrn22from AR.models.t2s_lightning_module import Text2SemanticLightningModule23from AR.utils.io import load_yaml_config24from text import cleaned_text_to_sequence25from text.cleaner import text_to_sequence, clean_text26from time import time as ttime27from module.mel_processing import spectrogram_torch28from my_utils import load_audio29 30import logging31logging.getLogger('httpx').setLevel(logging.WARNING)32logging.getLogger('httpcore').setLevel(logging.WARNING)33logging.getLogger('multipart').setLevel(logging.WARNING)34 35device = "cpu"36is_half = False37 38tokenizer = AutoTokenizer.from_pretrained(bert_path)39bert_model=AutoModelForMaskedLM.from_pretrained(bert_path)40if(is_half==True):bert_model=bert_model.half().to(device)41else:bert_model=bert_model.to(device)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 60def load_model(sovits_path, gpt_path):61    n_semantic = 102462    dict_s2 = torch.load(sovits_path, map_location="cpu")63    hps = dict_s2["config"]64 65    class DictToAttrRecursive:66        def __init__(self, input_dict):67            for key, value in input_dict.items():68                if isinstance(value, dict):69                    # 如果值是字典,递归调用构造函数70                    setattr(self, key, DictToAttrRecursive(value))71                else:72                    setattr(self, key, value)73 74    hps = DictToAttrRecursive(hps)75    hps.model.semantic_frame_rate = "25hz"76    dict_s1 = torch.load(gpt_path, map_location="cpu")77    config = dict_s1["config"]78    ssl_model = cnhubert.get_model()79    if (is_half == True):80        ssl_model = ssl_model.half().to(device)81    else:82        ssl_model = ssl_model.to(device)83 84    vq_model = SynthesizerTrn(85        hps.data.filter_length // 2 + 1,86        hps.train.segment_size // hps.data.hop_length,87        n_speakers=hps.data.n_speakers,88        **hps.model)89    if (is_half == True):90        vq_model = vq_model.half().to(device)91    else:92        vq_model = vq_model.to(device)93    vq_model.eval()94    vq_model.load_state_dict(dict_s2["weight"], strict=False)95    hz = 5096    max_sec = config['data']['max_sec']97    # t2s_model = Text2SemanticLightningModule.load_from_checkpoint(checkpoint_path=gpt_path, config=config, map_location="cpu")#########todo98    t2s_model = Text2SemanticLightningModule(config, "ojbk", is_train=False)99    t2s_model.load_state_dict(dict_s1["weight"])100    if (is_half == True): t2s_model = t2s_model.half()101    t2s_model = t2s_model.to(device)102    t2s_model.eval()103    total = sum([param.nelement() for param in t2s_model.parameters()])104    print("Number of parameter: %.2fM" % (total / 1e6))105    return vq_model, ssl_model, t2s_model, hps, config, hz, max_sec106 107 108def get_spepc(hps, filename):109    audio=load_audio(filename,int(hps.data.sampling_rate))110    audio=torch.FloatTensor(audio)111    audio_norm = audio112    audio_norm = audio_norm.unsqueeze(0)113    spec = spectrogram_torch(audio_norm, hps.data.filter_length,hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,center=False)114    return spec115 116 117def create_tts_fn(vq_model, ssl_model, t2s_model, hps, config, hz, max_sec):118    def tts_fn(ref_wav_path, prompt_text, prompt_language, text, text_language):119        t0 = ttime()120        prompt_text=prompt_text.strip("\n")121        prompt_language,text=prompt_language,text.strip("\n")122        print(text)123        if len(text) > 50:124            return f"Error: Text is too long, ({len(text)}>50)", None125        with torch.no_grad():126            wav16k, sr = librosa.load(ref_wav_path, sr=16000)  # 派蒙127            wav16k = torch.from_numpy(wav16k)128            if(is_half==True):wav16k=wav16k.half().to(device)129            else:wav16k=wav16k.to(device)130            ssl_content = ssl_model.model(wav16k.unsqueeze(0))["last_hidden_state"].transpose(1, 2)#.float()131            codes = vq_model.extract_latent(ssl_content)132            prompt_semantic = codes[0, 0]133        t1 = ttime()134        phones1, word2ph1, norm_text1 = clean_text(prompt_text, prompt_language)135        phones1=cleaned_text_to_sequence(phones1)136        texts=text.split("\n")137        audio_opt = []138        zero_wav=np.zeros(int(hps.data.sampling_rate*0.3),dtype=np.float16 if is_half==True else np.float32)139        for text in texts:140            phones2, word2ph2, norm_text2 = clean_text(text, text_language)141            phones2 = cleaned_text_to_sequence(phones2)142            if(prompt_language=="zh"):bert1 = get_bert_feature(norm_text1, word2ph1).to(device)143            else:bert1 = torch.zeros((1024, len(phones1)),dtype=torch.float16 if is_half==True else torch.float32).to(device)144            if(text_language=="zh"):bert2 = get_bert_feature(norm_text2, word2ph2).to(device)145            else:bert2 = torch.zeros((1024, len(phones2))).to(bert1)146            bert = torch.cat([bert1, bert2], 1)147 148            all_phoneme_ids = torch.LongTensor(phones1+phones2).to(device).unsqueeze(0)149            bert = bert.to(device).unsqueeze(0)150            all_phoneme_len = torch.tensor([all_phoneme_ids.shape[-1]]).to(device)151            prompt = prompt_semantic.unsqueeze(0).to(device)152            t2 = ttime()153            with torch.no_grad():154                # pred_semantic = t2s_model.model.infer(155                pred_semantic,idx = t2s_model.model.infer_panel(156                    all_phoneme_ids,157                    all_phoneme_len,158                    prompt,159                    bert,160                    # prompt_phone_len=ph_offset,161                    top_k=config['inference']['top_k'],162                    early_stop_num=hz * max_sec)163            t3 = ttime()164            # print(pred_semantic.shape,idx)165            pred_semantic = pred_semantic[:,-idx:].unsqueeze(0)  # .unsqueeze(0)#mq要多unsqueeze一次166            refer = get_spepc(hps, ref_wav_path)#.to(device)167            if(is_half==True):refer=refer.half().to(device)168            else:refer=refer.to(device)169            # audio = vq_model.decode(pred_semantic, all_phoneme_ids, refer).detach().cpu().numpy()[0, 0]170            audio = vq_model.decode(pred_semantic, torch.LongTensor(phones2).to(device).unsqueeze(0), refer).detach().cpu().numpy()[0, 0]###试试重建不带上prompt部分171            audio_opt.append(audio)172            audio_opt.append(zero_wav)173            t4 = ttime()174        print("%.3f\t%.3f\t%.3f\t%.3f" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))175        return "Success", (hps.data.sampling_rate,(np.concatenate(audio_opt,0)*32768).astype(np.int16))176    return tts_fn177 178 179splits={",","。","?","!",",",".","?","!","~",":",":","—","…",}#不考虑省略号180def split(todo_text):181    todo_text = todo_text.replace("……", "。").replace("——", ",")182    if (todo_text[-1] not in splits): todo_text += "。"183    i_split_head = i_split_tail = 0184    len_text = len(todo_text)185    todo_texts = []186    while (1):187        if (i_split_head >= len_text): break  # 结尾一定有标点,所以直接跳出即可,最后一段在上次已加入188        if (todo_text[i_split_head] in splits):189            i_split_head += 1190            todo_texts.append(todo_text[i_split_tail:i_split_head])191            i_split_tail = i_split_head192        else:193            i_split_head += 1194    return todo_texts195 196 197def change_reference_audio(prompt_text, transcripts):198    return transcripts[prompt_text]199 200 201models = []202models_info = {203    "AnZhiLe": {204        "gpt_weight": "blue_archive/AnZhiLe/GPT-anzhile-e15.ckpt",205        "sovits_weight": "blue_archive/AnZhiLe/SoVITS-anzhile_e8_s120.pth",206        "title": "安致乐 - 老大哥",207        "cover": "https://www.liusi.cloudns.org/img/azl2.png",208        "example_reference": "不行了,我要去找谢霆锋了,谢霆锋能治愈我的心。"209    },210}211for i, info in models_info.items():212    title = info['title']213    cover = info['cover']214    gpt_weight = info['gpt_weight']215    sovits_weight = info['sovits_weight']216    example_reference = info['example_reference']217    transcripts = {}218    with open(f"blue_archive/{i}/reference_audio/transcript.txt", 'r', encoding='utf-8') as file:219        for line in file:220            line = line.strip()221            wav, t = line.split("|")222            transcripts[t] = os.path.join(f"blue_archive/{i}/reference_audio", wav)223 224    vq_model, ssl_model, t2s_model, hps, config, hz, max_sec = load_model(sovits_weight, gpt_weight)225 226 227    models.append(228        (229            i,230            title,231            cover,232            transcripts,233            example_reference,234            create_tts_fn(235                vq_model, ssl_model, t2s_model, hps, config, hz, max_sec236            )237        )238    )239with gr.Blocks(title="AI语音合成|chenHen") as app:240    gr.Markdown(241        "# <center> ChenHen \n"242        "## <center> https://www.liusi.cloudns.org\n"243    )244    with gr.Tabs():245        for (name, title, cover, transcripts, example_reference, tts_fn) in models:246            with gr.TabItem(name):247                with gr.Row():248                    gr.Markdown(249                        '<div align="center">'250                        f'<a><strong>{title}</strong></a>'251                        f'<img style="width:auto;height:300px;" src="{cover}">' if cover else ""252                        '</div>')253                with gr.Row():254                    with gr.Column():255                        prompt_text = gr.Dropdown(256                            label="选择参考音频",257                            value=example_reference,258                            choices=list(transcripts.keys())259                        )260                        inp_ref_audio = gr.Audio(261                            label="参考音频",262                            type="filepath",263                            interactive=False,264                            value=transcripts[example_reference]265                        )266                        transcripts_state = gr.State(value=transcripts)267                        prompt_text.change(268                            fn=change_reference_audio,269                            inputs=[prompt_text, transcripts_state],270                            outputs=[inp_ref_audio]271                        )272                        prompt_language = gr.State(value="zh")273                    with gr.Column():274                        text = gr.Textbox(label="Input Text", value="你好。")275                        text_language = gr.Dropdown(276                            label="语言",277                            choices=["zh", "en", "ja"],278                            value="zh"279                        )280                        inference_button = gr.Button("启动", variant="primary")281                        om = gr.Textbox(label="生成消息")282                        output = gr.Audio(label="生成结果")283                        inference_button.click(284                            fn=tts_fn,285                            inputs=[inp_ref_audio, prompt_text, prompt_language, text, text_language],286                            outputs=[om, output]287                        )288 289app.queue().launch()