import gradio as gr import torch import commons import utils from models import SynthesizerTrn from text.symbols import symbols from text import text_to_sequence import numpy as np def get_text(text, hps): text_norm = text_to_sequence(text, hps.data.text_cleaners) if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0) text_norm = torch.LongTensor(text_norm) return text_norm hps = utils.get_hparams_from_file("./configs/leo.json") net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, **hps.model) _ = net_g.eval() _ = utils.load_checkpoint("./logs/leo/G_4000.pth", net_g, None) all_emotions = np.load("all_emotions.npy") emotion_dict = { "小声(目前没区分)": 0, "激动": 1, "平静1": 2, "平静2": 3 } import random def tts(txt, emotion, ns, nsw, ls): stn_tst = get_text(txt, hps) randsample = None with torch.no_grad(): x_tst = stn_tst.unsqueeze(0) x_tst_lengths = torch.LongTensor([stn_tst.size(0)]) sid = torch.LongTensor([0]) if type(emotion) ==int: emo = torch.FloatTensor(all_emotions[emotion]).unsqueeze(0) elif emotion == "random": emo = torch.randn([1,1024]) elif emotion == "random_sample": randint = random.randint(0, all_emotions.shape[0]) emo = torch.FloatTensor(all_emotions[randint]).unsqueeze(0) randsample = randint elif emotion.endswith("wav"): import emotion_extract emo = torch.FloatTensor(emotion_extract.extract_wav(emotion)) else: emo = torch.FloatTensor(all_emotions[emotion_dict[emotion]]).unsqueeze(0) audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=ns, noise_scale_w=nsw, length_scale=ls, emo=emo)[0][0,0].data.float().numpy() return audio, randsample def tts1(text, emotion, ns, nsw, ls): if len(text) > 150: return "Error: Text is too long", None audio, _ = tts(text, emotion, ns, nsw, ls) return "Success", (hps.data.sampling_rate, audio) def tts2(text, ns, nsw, ls): if len(text) > 150: return "Error: Text is too long", None audio, randsample = tts(text, "random_sample", ns, nsw, ls) return str(randsample), (hps.data.sampling_rate, audio) def tts3(text, sample, ns, nsw, ls): if len(text) > 150: return "Error: Text is too long", None try: audio, _ = tts(text, int(sample), ns, nsw, ls) return "Success", (hps.data.sampling_rate, audio) except: return "输入参数不为整数或其他错误", None app = gr.Blocks() with app: with gr.Blocks() as app: gr.Markdown( "#