CoolFace
Apppublic

fighter-programmer/voicegen

sourceHugging Faceupdated 4y agoView on Hugging Face
0likes
app.py256 linesDownload Raw Back to root
1import argparse2import json3import os4import re5import tempfile6import logging7 8logging.getLogger('numba').setLevel(logging.WARNING)9import librosa10import numpy as np11import torch12from torch import no_grad, LongTensor13import commons14import utils15import gradio as gr16import gradio.utils as gr_utils17import gradio.processing_utils as gr_processing_utils18import ONNXVITS_infer19import models20from text import text_to_sequence, _clean_text21from text.symbols import symbols22from mel_processing import spectrogram_torch23import psutil24from datetime import datetime25 26language_marks = {27    "Japanese": "",28    "日本語": "[JA]",29    "简体中文": "[ZH]",30    "English": "[EN]",31    "Mix": "",32}33 34limitation = os.getenv("SYSTEM") == "spaces"  # limit text and audio length in huggingface spaces35 36 37def create_tts_fn(model, hps, speaker_ids):38    def tts_fn(text, speaker, language, speed, is_symbol):39        if limitation:40            text_len = len(re.sub("\[([A-Z]{2})\]", "", text))41            max_len = 15042            if is_symbol:43                max_len *= 344            if text_len > max_len:45                return "Error: Text is too long", None46        if language is not None:47            text = language_marks[language] + text + language_marks[language]48        speaker_id = speaker_ids[speaker]49        stn_tst = get_text(text, hps, is_symbol)50        with no_grad():51            x_tst = stn_tst.unsqueeze(0)52            x_tst_lengths = LongTensor([stn_tst.size(0)])53            sid = LongTensor([speaker_id])54            audio = model.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8,55                                length_scale=1.0 / speed)[0][0, 0].data.cpu().float().numpy()56        del stn_tst, x_tst, x_tst_lengths, sid57        return "Success", (hps.data.sampling_rate, audio)58 59    return tts_fn60 61 62def create_vc_fn(model, hps, speaker_ids):63    def vc_fn(original_speaker, target_speaker, input_audio):64        if input_audio is None:65            return "You need to upload an audio", None66        sampling_rate, audio = input_audio67        duration = audio.shape[0] / sampling_rate68        if limitation and duration > 30:69            return "Error: Audio is too long", None70        original_speaker_id = speaker_ids[original_speaker]71        target_speaker_id = speaker_ids[target_speaker]72 73        audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)74        if len(audio.shape) > 1:75            audio = librosa.to_mono(audio.transpose(1, 0))76        if sampling_rate != hps.data.sampling_rate:77            audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=hps.data.sampling_rate)78        with no_grad():79            y = torch.FloatTensor(audio)80            y = y.unsqueeze(0)81            spec = spectrogram_torch(y, hps.data.filter_length,82                                     hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length,83                                     center=False)84            spec_lengths = LongTensor([spec.size(-1)])85            sid_src = LongTensor([original_speaker_id])86            sid_tgt = LongTensor([target_speaker_id])87            audio = model.voice_conversion(spec, spec_lengths, sid_src=sid_src, sid_tgt=sid_tgt)[0][88                0, 0].data.cpu().float().numpy()89        del y, spec, spec_lengths, sid_src, sid_tgt90        return "Success", (hps.data.sampling_rate, audio)91 92    return vc_fn93 94 95def get_text(text, hps, is_symbol):96    text_norm = text_to_sequence(text, hps.symbols, [] if is_symbol else hps.data.text_cleaners)97    if hps.data.add_blank:98        text_norm = commons.intersperse(text_norm, 0)99    text_norm = LongTensor(text_norm)100    return text_norm101 102 103def create_to_symbol_fn(hps):104    def to_symbol_fn(is_symbol_input, input_text, temp_text):105        return (_clean_text(input_text, hps.data.text_cleaners), input_text) if is_symbol_input \106            else (temp_text, temp_text)107 108    return to_symbol_fn109 110 111models_tts = []112models_vc = []113models_info = [114    {115        "title": "Trilingual",116        "languages": ['日本語', '简体中文', 'English', 'Mix'],117        "description": """118    This model is trained on a mix up of Umamusume, Genshin Impact, Sanoba Witch & VCTK voice data to learn multilanguage.119    All characters can speak English, Chinese & Japanese.\n\n120    To mix multiple languages in a single sentence, wrap the corresponding part with language tokens121     ([JA] for Japanese, [ZH] for Chinese, [EN] for English), as shown in the examples.\n\n122    这个模型在赛马娘,原神,魔女的夜宴以及VCTK数据集上混合训练以学习多种语言。123    所有角色均可说中日英三语。\n\n124    若需要在同一个句子中混合多种语言,使用相应的语言标记包裹句子。125    (日语用[JA], 中文用[ZH], 英文用[EN]),参考Examples中的示例。126    """,127        "model_path": "./pretrained_models/G_trilingual.pth",128        "config_path": "./configs/uma_trilingual.json",129        "examples": [['你好,训练员先生,很高兴见到你。', '草上飞 Grass Wonder (Umamusume Pretty Derby)', '简体中文', 1, False],130                     ['To be honest, I have no idea what to say as examples.', '派蒙 Paimon (Genshin Impact)', 'English',131                      1, False],132                     ['授業中に出しだら,学校生活終わるですわ。', '綾地 寧々 Ayachi Nene (Sanoba Witch)', '日本語', 1, False],133                     ['[JA]こんにちわ。[JA][ZH]你好![ZH][EN]Hello![EN]', '綾地 寧々 Ayachi Nene (Sanoba Witch)', 'Mix', 1, False]],134        "onnx_dir": "./ONNX_net/G_trilingual/"135    },136    {137        "title": "Japanese",138        "languages": ["Japanese"],139        "description": """140                       This model contains 87 characters from Umamusume: Pretty Derby, Japanese only.\n\n141                       这个模型包含赛马娘的所有87名角色,只能合成日语。142                       """,143        "model_path": "./pretrained_models/G_jp.pth",144        "config_path": "./configs/uma87.json",145        "examples": [['お疲れ様です,トレーナーさん。', '无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)', 'Japanese', 1, False],146                     ['張り切っていこう!', '北部玄驹 Kitasan Black (Umamusume Pretty Derby)', 'Japanese', 1, False],147                     ['何でこんなに慣れでんのよ,私のほが先に好きだっだのに。', '草上飞 Grass Wonder (Umamusume Pretty Derby)', 'Japanese', 1, False],148                     ['授業中に出しだら,学校生活終わるですわ。', '目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)', 'Japanese', 1, False],149                     ['お帰りなさい,お兄様!', '米浴 Rice Shower (Umamusume Pretty Derby)', 'Japanese', 1, False],150                     ['私の処女をもらっでください!', '米浴 Rice Shower (Umamusume Pretty Derby)', 'Japanese', 1, False]],151        "onnx_dir": "./ONNX_net/G_jp/"152    },153]154 155if __name__ == "__main__":156    parser = argparse.ArgumentParser()157    parser.add_argument("--share", action="store_true", default=False, help="share gradio app")158    args = parser.parse_args()159    for info in models_info:160        name = info['title']161        lang = info['languages']162        examples = info['examples']163        config_path = info['config_path']164        model_path = info['model_path']165        description = info['description']166        onnx_dir = info["onnx_dir"]167        hps = utils.get_hparams_from_file(config_path)168        model = ONNXVITS_infer.SynthesizerTrn(169            len(hps.symbols),170            hps.data.filter_length // 2 + 1,171            hps.train.segment_size // hps.data.hop_length,172            n_speakers=hps.data.n_speakers,173            ONNX_dir=onnx_dir,174            **hps.model)175        utils.load_checkpoint(model_path, model, None)176        model.eval()177        speaker_ids = hps.speakers178        speakers = list(hps.speakers.keys())179        models_tts.append((name, description, speakers, lang, examples,180                           hps.symbols, create_tts_fn(model, hps, speaker_ids),181                           create_to_symbol_fn(hps)))182        models_vc.append((name, description, speakers, create_vc_fn(model, hps, speaker_ids)))183    app = gr.Blocks()184    with app:185        gr.Markdown("# English & Chinese & Japanese Anime TTS\n\n"186                    "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=Plachta.VITS-Umamusume-voice-synthesizer)\n\n"187                    "Including Japanese TTS & Trilingual TTS, speakers are all anime characters. \n\n包含一个纯日语TTS和一个中日英三语TTS模型,主要为二次元角色。\n\n"188                    "If you have any suggestions or bug reports, feel free to open discussion in [Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions).\n\n"189                    "若有bug反馈或建议,请在[Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions)下开启一个新的Discussion。 \n\n"190                    )191        with gr.Tabs():192            with gr.TabItem("TTS"):193                with gr.Tabs():194                    for i, (name, description, speakers, lang, example, symbols, tts_fn, to_symbol_fn) in enumerate(195                            models_tts):196                        with gr.TabItem(name):197                            gr.Markdown(description)198                            with gr.Row():199                                with gr.Column():200                                    textbox = gr.TextArea(label="Text",201                                                          placeholder="Type your sentence here (Maximum 150 words)",202                                                          value="こんにちわ。", elem_id=f"tts-input")203                                    with gr.Accordion(label="Phoneme Input", open=False):204                                        temp_text_var = gr.Variable()205                                        symbol_input = gr.Checkbox(value=False, label="Symbol input")206                                        symbol_list = gr.Dataset(label="Symbol list", components=[textbox],207                                                                 samples=[[x] for x in symbols],208                                                                 elem_id=f"symbol-list")209                                        symbol_list_json = gr.Json(value=symbols, visible=False)210                                    symbol_input.change(to_symbol_fn,211                                                        [symbol_input, textbox, temp_text_var],212                                                        [textbox, temp_text_var])213                                    symbol_list.click(None, [symbol_list, symbol_list_json], textbox,214                                                      _js=f"""215                                    (i, symbols, text) => {{216                                        let root = document.querySelector("body > gradio-app");217                                        if (root.shadowRoot != null)218                                            root = root.shadowRoot;219                                        let text_input = root.querySelector("#tts-input").querySelector("textarea");220                                        let startPos = text_input.selectionStart;221                                        let endPos = text_input.selectionEnd;222                                        let oldTxt = text_input.value;223                                        let result = oldTxt.substring(0, startPos) + symbols[i] + oldTxt.substring(endPos);224                                        text_input.value = result;225                                        let x = window.scrollX, y = window.scrollY;226                                        text_input.focus();227                                        text_input.selectionStart = startPos + symbols[i].length;228                                        text_input.selectionEnd = startPos + symbols[i].length;229                                        text_input.blur();230                                        window.scrollTo(x, y);231 232                                        text = text_input.value;233 234                                        return text;235                                    }}""")236                                    # select character237                                    char_dropdown = gr.Dropdown(choices=speakers, value=speakers[0], label='character')238                                    language_dropdown = gr.Dropdown(choices=lang, value=lang[0], label='language')239                                    duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1,240                                                                label='速度 Speed')241                                with gr.Column():242                                    text_output = gr.Textbox(label="Message")243                                    audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")244                                    btn = gr.Button("Generate!")245                                    btn.click(tts_fn,246                                              inputs=[textbox, char_dropdown, language_dropdown, duration_slider,247                                                      symbol_input],248                                              outputs=[text_output, audio_output])249                            gr.Examples(250                                examples=example,251                                inputs=[textbox, char_dropdown, language_dropdown,252                                        duration_slider, symbol_input],253                                outputs=[text_output, audio_output],254                                fn=tts_fn255                            )256    app.queue(concurrency_count=3).launch(show_api=False, share=args.share)