import warnings warnings.filterwarnings("ignore") # 外部库 import argparse import json import os import re import tempfile import librosa import numpy as np import torch from torch import no_grad, LongTensor import commons import gradio as gr import gradio.utils as gr_utils import gradio.processing_utils as gr_processing_utils # 内部库 from models import SynthesizerTrn from text import text_to_sequence, _clean_text, text_to_sequence_inference from mel_processing import spectrogram_torch import utils limitation = os.getenv("SYSTEM") == "spaces" # limit text and audio length in huggingface spaces # def process_func(x, sampling_rate, embeddings): # """ # Predict emotions or extract embeddings from raw audio signal # :param x: np.ndarray # :param sampling_rate: # :param embeddings: # :return: np.ndarray # """ # # run through processor to normalize signal # # always returns a batch, so we just get the first entry # # then we put it on the device # y = processor(x, sampling_rate=sampling_rate) # y = y['input_values'][0] # y = torch.from_numpy(y).to(device) # # run through model # with torch.no_grad(): # y = emotion_model(y)[0 if embeddings else 1] # # convert to numpy # y = y.detach().cpu().numpy() # return y # def audio_postprocess(self, y): # """ # 修改gr的音频后处理函数 # :param self: # :param y: # :return: # """ # if y is None: # return None # if gr_utils.validate_url(y): # file = gr_processing_utils.download_to_file(y, dir=self.temp_dir) # elif isinstance(y, tuple): # sample_rate, data = y # file = tempfile.NamedTemporaryFile( # suffix=".wav", dir=self.temp_dir, delete=False # ) # gr_processing_utils.audio_to_file(sample_rate, data, file.name) # else: # file = gr_processing_utils.create_tmp_copy_of_file(y, dir=self.temp_dir) # return gr_processing_utils.encode_url_or_file_to_base64(file.name) # gr.Audio.postprocess = audio_postprocess def get_text(text, hps, is_symbol): """ :param text: :param hps: :param is_symbol: :return: """ # text_norm = text_to_sequence(text, hps.data.text_cleaners) text_norm = text_to_sequence_inference(text, hps.symbols, [] if is_symbol else hps.data.text_cleaners) if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0) text_norm = LongTensor(text_norm) return text_norm def create_tts_fn(model, hps): """ :param model: :param hps: :param speaker_ids: :return: """ def tts_fn(text, speed, volume=1.0, is_symbol=False): """ :param text: :param speaker: :param speed: :param emo: :param volume: :param is_symbol: :return: """ if limitation: text_len = len(re.sub("\[([A-Z]{2})\]", "", text)) max_len = 150 if is_symbol: max_len *= 3 if text_len > max_len: return "Error: Text is too long", None stn_tst = get_text(text, hps, is_symbol) with no_grad(): x_tst = stn_tst.unsqueeze(0) x_tst_lengths = LongTensor([stn_tst.size(0)]) audio = model.infer(x_tst, x_tst_lengths, noise_scale=.667, noise_scale_w=0.8, length_scale=1.0 / speed)[0][0, 0].data.cpu().float().numpy() del stn_tst, x_tst, x_tst_lengths audio = audio * volume return "Success", (hps.data.sampling_rate, audio) return tts_fn if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model_path', type=str, default='./saved_model_dingzhi') args = parser.parse_args() name = 'orga' author = 'xxx' lang = '日语(Japanese)' example = "今日は天気がいいから、一緒にハイキングに行きましょう。" config_path = f"{args.model_path}/config.json" model_path = f"{args.model_path}/model.pth" cover = '' hps = utils.get_hparams_from_file(config_path) model = SynthesizerTrn( len(hps.symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, **hps.model) utils.load_checkpoint(model_path, model, None) model.eval() models_tts = create_tts_fn(model, hps) app = gr.Blocks() with app: gr.Markdown("TTS Demo for orga") with gr.Tabs(): with gr.TabItem("TTS"): with gr.Column(): gr.Markdown(f"## {name}\n\n" f"language: {lang}") tts_input1 = gr.TextArea(label="Text", value=example) tts_input2 = gr.Slider(label="Speed", value=1.0, minimum=0.4, maximum=3, step=0.1) tts_submit = gr.Button("Generate", variant="primary") tts_output1 = gr.Textbox(label="Output Message") tts_output2 = gr.Audio(label="Output Audio") tts_submit.click(models_tts, [tts_input1, tts_input2], [tts_output1, tts_output2]) app.launch()