Kafke/Code-Realize-TTS
0
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": "CodeRealize",116 "languages": ['日本語', '简体中文', 'English', 'Mix'],117 "description": """118 This model is trained on Code Realize voice clips - Guardian of Rebirth.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)\n\n122 """,123 "model_path": "./pretrained_models/coderealize.pth",124 "config_path": "./configs/coderealize.json",125 "examples": [],126 "onnx_dir": ""127 },128]129 130if __name__ == "__main__":131 parser = argparse.ArgumentParser()132 parser.add_argument("--share", action="store_true", default=False, help="share gradio app")133 args = parser.parse_args()134 for info in models_info:135 name = info['title']136 lang = info['languages']137 examples = info['examples']138 config_path = info['config_path']139 model_path = info['model_path']140 description = info['description']141 onnx_dir = info["onnx_dir"]142 hps = utils.get_hparams_from_file(config_path)143 model = models.SynthesizerTrn(144 len(hps.symbols),145 hps.data.filter_length // 2 + 1,146 hps.train.segment_size // hps.data.hop_length,147 n_speakers=hps.data.n_speakers,148 emotion_embedding=False,149 **hps.model)150 utils.load_checkpoint(model_path, model, None)151 model.eval()152 speaker_ids = hps.speakers153 speakers = list(hps.speakers.keys())154 models_tts.append((name, description, speakers, lang, examples,155 hps.symbols, create_tts_fn(model, hps, speaker_ids),156 create_to_symbol_fn(hps)))157 models_vc.append((name, description, speakers, create_vc_fn(model, hps, speaker_ids)))158 app = gr.Blocks()159 with app:160 gr.Markdown("# English & Chinese & Japanese Code Realize TTS\n\n"161 )162 with gr.Tabs():163 with gr.TabItem("TTS"):164 with gr.Tabs():165 for i, (name, description, speakers, lang, example, symbols, tts_fn, to_symbol_fn) in enumerate(166 models_tts):167 with gr.TabItem(name):168 gr.Markdown(description)169 with gr.Row():170 with gr.Column():171 textbox = gr.TextArea(label="Text",172 placeholder="Type your sentence here (Maximum 150 words)",173 value="こんにちわ。", elem_id=f"tts-input")174 with gr.Accordion(label="Phoneme Input", open=False):175 temp_text_var = gr.Variable()176 symbol_input = gr.Checkbox(value=False, label="Symbol input")177 symbol_list = gr.Dataset(label="Symbol list", components=[textbox],178 samples=[[x] for x in symbols],179 elem_id=f"symbol-list")180 symbol_list_json = gr.Json(value=symbols, visible=False)181 symbol_input.change(to_symbol_fn,182 [symbol_input, textbox, temp_text_var],183 [textbox, temp_text_var])184 symbol_list.click(None, [symbol_list, symbol_list_json], textbox,185 _js=f"""186 (i, symbols, text) => {{187 let root = document.querySelector("body > gradio-app");188 if (root.shadowRoot != null)189 root = root.shadowRoot;190 let text_input = root.querySelector("#tts-input").querySelector("textarea");191 let startPos = text_input.selectionStart;192 let endPos = text_input.selectionEnd;193 let oldTxt = text_input.value;194 let result = oldTxt.substring(0, startPos) + symbols[i] + oldTxt.substring(endPos);195 text_input.value = result;196 let x = window.scrollX, y = window.scrollY;197 text_input.focus();198 text_input.selectionStart = startPos + symbols[i].length;199 text_input.selectionEnd = startPos + symbols[i].length;200 text_input.blur();201 window.scrollTo(x, y);202 203 text = text_input.value;204 205 return text;206 }}""")207 # select character208 char_dropdown = gr.Dropdown(choices=speakers, value=speakers[0], label='character')209 language_dropdown = gr.Dropdown(choices=lang, value=lang[0], label='language')210 duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1,211 label='Speed')212 with gr.Column():213 text_output = gr.Textbox(label="Message")214 audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")215 btn = gr.Button("Generate!")216 btn.click(tts_fn,217 inputs=[textbox, char_dropdown, language_dropdown, duration_slider,218 symbol_input],219 outputs=[text_output, audio_output])220 gr.Examples(221 examples=example,222 inputs=[textbox, char_dropdown, language_dropdown,223 duration_slider, symbol_input],224 outputs=[text_output, audio_output],225 fn=tts_fn226 )227 app.queue(concurrency_count=3).launch(show_api=False, share=args.share)