Plachta commited on
Commit
e7373fa
1 Parent(s): ac19060

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -19
app.py CHANGED
@@ -44,7 +44,6 @@ def audio_postprocess(self, y):
44
  gr.Audio.postprocess = audio_postprocess
45
 
46
  limitation = os.getenv("SYSTEM") == "spaces" # limit text and audio length in huggingface spaces
47
- max_len = 150
48
  languages = ['日本語', '简体中文', 'English']
49
  characters = ['0:特别周', '1:无声铃鹿', '2:东海帝王', '3:丸善斯基',
50
  '4:富士奇迹', '5:小栗帽', '6:黄金船', '7:伏特加',
@@ -76,14 +75,15 @@ def show_memory_info(hint):
76
  print("{} 内存占用: {} MB".format(hint, memory))
77
 
78
 
79
- def get_text(text, hps):
80
- text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
81
  if hps.data.add_blank:
82
  text_norm = commons.intersperse(text_norm, 0)
83
- text_norm = torch.LongTensor(text_norm)
84
  return text_norm
85
 
86
  hps = utils.get_hparams_from_file("./configs/uma87.json")
 
87
  net_g = ONNXVITS_infer.SynthesizerTrn(
88
  len(hps.symbols),
89
  hps.data.filter_length // 2 + 1,
@@ -94,7 +94,11 @@ _ = net_g.eval()
94
 
95
  _ = utils.load_checkpoint("pretrained_models/G_1153000.pth", net_g)
96
 
97
- def infer(text_raw, character, language, duration, noise_scale, noise_scale_w):
 
 
 
 
98
  # check character & duraction parameter
99
  if language not in languages:
100
  print("Error: No such language\n")
@@ -104,28 +108,33 @@ def infer(text_raw, character, language, duration, noise_scale, noise_scale_w):
104
  return "Error: No such character", None
105
  # check text length
106
  if limitation:
107
- text_len = len(re.sub("\[([A-Z]{2})\]", "", text_raw))
 
 
 
108
  if text_len > max_len:
109
  print(f"Refused: Text too long ({text_len}).")
110
  return "Error: Text is too long", None
111
  if text_len == 0:
112
  print("Refused: Text length is zero.")
113
  return "Error: Please input text!", None
114
- if language == '日本語':
 
 
115
  text = text_raw
116
  elif language == '简体中文':
117
  text = tss.google(text_raw, from_language='zh', to_language='ja')
118
  elif language == 'English':
119
  text = tss.google(text_raw, from_language='en', to_language='ja')
120
  char_id = int(character.split(':')[0])
121
- stn_tst = get_text(text, hps)
122
  with torch.no_grad():
123
  x_tst = stn_tst.unsqueeze(0)
124
  x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
125
- sid = torch.LongTensor([char_id])
126
  audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=duration)[0][0,0].data.float().numpy()
127
  currentDateAndTime = datetime.now()
128
- print(f"\nCharacter {character} inference successful: {text}")
129
  if language != '日本語':
130
  print(f"translate from {language}: {text_raw}")
131
  show_memory_info(str(currentDateAndTime) + " infer调用后")
@@ -171,7 +180,37 @@ if __name__ == "__main__":
171
  with gr.Row():
172
  with gr.Column():
173
  # We instantiate the Textbox class
174
- textbox = gr.Textbox(label="Text", placeholder="Type your sentence here (Maximum 150 words)", value = "こんにちわ!", lines=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  # select character
176
  char_dropdown = gr.Dropdown(choices=characters, value = "0:特别周", label='character')
177
  language_dropdown = gr.Dropdown(choices=languages, value = "日本語", label='language')
@@ -180,6 +219,9 @@ if __name__ == "__main__":
180
  duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1, label='时长 Duration')
181
  noise_scale_slider = gr.Slider(minimum=0.1, maximum=5, value=0.667, step=0.001, label='噪声比例 noise_scale')
182
  noise_scale_w_slider = gr.Slider(minimum=0.1, maximum=5, value=0.8, step=0.1, label='噪声偏差 noise_scale_w')
 
 
 
183
  with gr.Column():
184
  text_output = gr.Textbox(label="Output Text")
185
  audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")
@@ -187,22 +229,24 @@ if __name__ == "__main__":
187
  download.click(None, [], [], _js=download_audio_js.format(audio_id="tts-audio"))
188
  btn = gr.Button("Generate!")
189
  btn.click(infer, inputs=[textbox, char_dropdown, language_dropdown,
190
- duration_slider, noise_scale_slider, noise_scale_w_slider],
191
  outputs=[text_output, audio_output])
192
- examples = [['お疲れ様です,トレーナーさん。', '1:无声铃鹿', '日本語', 1, 0.667, 0.8],
193
- ['張り切っていこう!', '67:北部玄驹', '日本語', 1, 0.667, 0.8],
194
- ['何でこんなに慣れでんのよ,私のほが先に好きだっだのに。', '10:草上飞', '日本語', 1, 0.667, 0.8],
195
- ['授業中に出しだら,学校生活終わるですわ。', '12:目白麦昆', '日本語', 1, 0.667, 0.8],
196
- ['お帰りなさい,お兄様!', '29:米浴', '日本語', 1, 0.667, 0.8],
197
- ['私の処女をもらっでください!', '29:米浴', '日本語', 1, 0.667, 0.8]]
198
  gr.Examples(
199
  examples=examples,
200
  inputs=[textbox, char_dropdown, language_dropdown,
201
- duration_slider, noise_scale_slider,noise_scale_w_slider],
202
  outputs=[text_output, audio_output],
203
  fn=infer
204
  )
205
  gr.Markdown("# Updates Logs 更新日志:\n\n"
 
 
206
  "2023/1/10:\n\n"
207
  "数据集已上传,您可以在[这里](https://huggingface.co/datasets/Plachta/Umamusume-voice-text-pairs/tree/main)下载。\n\n"
208
  "2023/1/9:\n\n"
 
44
  gr.Audio.postprocess = audio_postprocess
45
 
46
  limitation = os.getenv("SYSTEM") == "spaces" # limit text and audio length in huggingface spaces
 
47
  languages = ['日本語', '简体中文', 'English']
48
  characters = ['0:特别周', '1:无声铃鹿', '2:东海帝王', '3:丸善斯基',
49
  '4:富士奇迹', '5:小栗帽', '6:黄金船', '7:伏特加',
 
75
  print("{} 内存占用: {} MB".format(hint, memory))
76
 
77
 
78
+ def get_text(text, hps, is_symbol):
79
+ text_norm = text_to_sequence(text, hps.symbols, [] if is_symbol else hps.data.text_cleaners)
80
  if hps.data.add_blank:
81
  text_norm = commons.intersperse(text_norm, 0)
82
+ text_norm = LongTensor(text_norm)
83
  return text_norm
84
 
85
  hps = utils.get_hparams_from_file("./configs/uma87.json")
86
+ symbols = hps.symbols
87
  net_g = ONNXVITS_infer.SynthesizerTrn(
88
  len(hps.symbols),
89
  hps.data.filter_length // 2 + 1,
 
94
 
95
  _ = utils.load_checkpoint("pretrained_models/G_1153000.pth", net_g)
96
 
97
+ def to_symbol_fn(is_symbol_input, input_text, temp_text):
98
+ return (_clean_text(input_text, hps.data.text_cleaners), input_text) if is_symbol_input \
99
+ else (temp_text, temp_text)
100
+
101
+ def infer(text_raw, character, language, duration, noise_scale, noise_scale_w, is_symbol):
102
  # check character & duraction parameter
103
  if language not in languages:
104
  print("Error: No such language\n")
 
108
  return "Error: No such character", None
109
  # check text length
110
  if limitation:
111
+ text_len = len(text_raw) if is_symbol else len(re.sub("\[([A-Z]{2})\]", "", text_raw))
112
+ max_len = 150
113
+ if is_symbol:
114
+ max_len *= 3
115
  if text_len > max_len:
116
  print(f"Refused: Text too long ({text_len}).")
117
  return "Error: Text is too long", None
118
  if text_len == 0:
119
  print("Refused: Text length is zero.")
120
  return "Error: Please input text!", None
121
+ if is_symbol:
122
+ text = text_raw
123
+ elif language == '日本語':
124
  text = text_raw
125
  elif language == '简体中文':
126
  text = tss.google(text_raw, from_language='zh', to_language='ja')
127
  elif language == 'English':
128
  text = tss.google(text_raw, from_language='en', to_language='ja')
129
  char_id = int(character.split(':')[0])
130
+ stn_tst = get_text(text, hps, is_symbol)
131
  with torch.no_grad():
132
  x_tst = stn_tst.unsqueeze(0)
133
  x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
134
+ sid = torch.LongTensor([0])
135
  audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=duration)[0][0,0].data.float().numpy()
136
  currentDateAndTime = datetime.now()
137
+ print(f"Character {character} inference successful: {text}\n")
138
  if language != '日本語':
139
  print(f"translate from {language}: {text_raw}")
140
  show_memory_info(str(currentDateAndTime) + " infer调用后")
 
180
  with gr.Row():
181
  with gr.Column():
182
  # We instantiate the Textbox class
183
+ textbox = gr.TextArea(label="Text", placeholder="Type your sentence here (Maximum 150 words)", value="こんにちわ。", elem_id=f"tts-input")
184
+ with gr.Accordion(label="Advanced Options", open=False):
185
+ temp_text_var = gr.Variable()
186
+ symbol_input = gr.Checkbox(value=False, label="Symbol input")
187
+ symbol_list = gr.Dataset(label="Symbol list", components=[textbox],
188
+ samples=[[x] for x in symbols],
189
+ elem_id=f"symbol-list")
190
+ symbol_list_json = gr.Json(value=symbols, visible=False)
191
+ symbol_input.change(to_symbol_fn,
192
+ [symbol_input, textbox, temp_text_var],
193
+ [textbox, temp_text_var])
194
+ symbol_list.click(None, [symbol_list, symbol_list_json], [],
195
+ _js=f"""
196
+ (i, symbols) => {{
197
+ let root = document.querySelector("body > gradio-app");
198
+ if (root.shadowRoot != null)
199
+ root = root.shadowRoot;
200
+ let text_input = root.querySelector("#tts-input").querySelector("textarea");
201
+ let startPos = text_input.selectionStart;
202
+ let endPos = text_input.selectionEnd;
203
+ let oldTxt = text_input.value;
204
+ let result = oldTxt.substring(0, startPos) + symbols[i] + oldTxt.substring(endPos);
205
+ text_input.value = result;
206
+ let x = window.scrollX, y = window.scrollY;
207
+ text_input.focus();
208
+ text_input.selectionStart = startPos + symbols[i].length;
209
+ text_input.selectionEnd = startPos + symbols[i].length;
210
+ text_input.blur();
211
+ window.scrollTo(x, y);
212
+ return [];
213
+ }}""")
214
  # select character
215
  char_dropdown = gr.Dropdown(choices=characters, value = "0:特别周", label='character')
216
  language_dropdown = gr.Dropdown(choices=languages, value = "日本語", label='language')
 
219
  duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1, label='时长 Duration')
220
  noise_scale_slider = gr.Slider(minimum=0.1, maximum=5, value=0.667, step=0.001, label='噪声比例 noise_scale')
221
  noise_scale_w_slider = gr.Slider(minimum=0.1, maximum=5, value=0.8, step=0.1, label='噪声偏差 noise_scale_w')
222
+
223
+
224
+
225
  with gr.Column():
226
  text_output = gr.Textbox(label="Output Text")
227
  audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")
 
229
  download.click(None, [], [], _js=download_audio_js.format(audio_id="tts-audio"))
230
  btn = gr.Button("Generate!")
231
  btn.click(infer, inputs=[textbox, char_dropdown, language_dropdown,
232
+ duration_slider, noise_scale_slider, noise_scale_w_slider, symbol_input],
233
  outputs=[text_output, audio_output])
234
+ examples = [['お疲れ様です,トレーナーさん。', '1:无声铃鹿', '日本語', 1, 0.667, 0.8, False],
235
+ ['張り切っていこう!', '67:北部玄驹', '日本語', 1, 0.667, 0.8, False],
236
+ ['何でこんなに慣れでんのよ,私のほが先に好きだっだのに。', '10:草上飞', '日本語', 1, 0.667, 0.8, False],
237
+ ['授業中に出しだら,学校生活終わるですわ。', '12:目白麦昆', '日本語', 1, 0.667, 0.8, False],
238
+ ['お帰りなさい,お兄様!', '29:米浴', '日本語', 1, 0.667, 0.8, False],
239
+ ['私の処女をもらっでください!', '29:米浴', '日本語', 1, 0.667, 0.8, False]]
240
  gr.Examples(
241
  examples=examples,
242
  inputs=[textbox, char_dropdown, language_dropdown,
243
+ duration_slider, noise_scale_slider,noise_scale_w_slider, symbol_input],
244
  outputs=[text_output, audio_output],
245
  fn=infer
246
  )
247
  gr.Markdown("# Updates Logs 更新日志:\n\n"
248
+ "2023/1/12:\n\n"
249
+ "增加了音素输入的功能,可以对语气和语调做到一定程度的精细控制。"
250
  "2023/1/10:\n\n"
251
  "数据集已上传,您可以在[这里](https://huggingface.co/datasets/Plachta/Umamusume-voice-text-pairs/tree/main)下载。\n\n"
252
  "2023/1/9:\n\n"