1
0

frontend.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from functools import partial
  15. import onnxruntime
  16. import torch
  17. import numpy as np
  18. import whisper
  19. from typing import Callable
  20. import torchaudio.compliance.kaldi as kaldi
  21. import torchaudio
  22. import os
  23. import inflect
  24. import ttsfrd
  25. from cosyvoice.utils.frontend_utils import contains_chinese, replace_blank, replace_corner_mark, remove_bracket, spell_out_number, split_paragraph
  26. class CosyVoiceFrontEnd:
  27. def __init__(self,
  28. get_tokenizer: Callable,
  29. feat_extractor: Callable,
  30. campplus_model: str,
  31. speech_tokenizer_model: str,
  32. spk2info: str = '',
  33. instruct: bool = False,
  34. allowed_special: str = 'all'):
  35. self.tokenizer = get_tokenizer()
  36. self.feat_extractor = feat_extractor
  37. self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  38. option = onnxruntime.SessionOptions()
  39. option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  40. option.intra_op_num_threads = 1
  41. self.campplus_session = onnxruntime.InferenceSession(campplus_model, sess_options=option, providers=["CPUExecutionProvider"])
  42. self.speech_tokenizer_session = onnxruntime.InferenceSession(speech_tokenizer_model, sess_options=option, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
  43. if os.path.exists(spk2info):
  44. self.spk2info = torch.load(spk2info, map_location=self.device)
  45. self.instruct = instruct
  46. self.allowed_special = allowed_special
  47. self.inflect_parser = inflect.engine()
  48. self.frd = ttsfrd.TtsFrontendEngine()
  49. ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
  50. assert self.frd.initialize('{}/../../pretrained_models/speech_kantts_ttsfrd/resource'.format(ROOT_DIR)) is True, 'failed to initialize ttsfrd resource'
  51. self.frd.set_lang_type('pinyin')
  52. self.frd.enable_pinyin_mix(True)
  53. self.frd.set_breakmodel_index(1)
  54. def _extract_text_token(self, text):
  55. text_token = self.tokenizer.encode(text, allowed_special=self.allowed_special)
  56. text_token = torch.tensor([text_token], dtype=torch.int32).to(self.device)
  57. text_token_len = torch.tensor([text_token.shape[1]], dtype=torch.int32).to(self.device)
  58. return text_token, text_token_len
  59. def _extract_speech_token(self, speech):
  60. feat = whisper.log_mel_spectrogram(speech, n_mels=128)
  61. speech_token = self.speech_tokenizer_session.run(None, {self.speech_tokenizer_session.get_inputs()[0].name: feat.detach().cpu().numpy(),
  62. self.speech_tokenizer_session.get_inputs()[1].name: np.array([feat.shape[2]], dtype=np.int32)})[0].flatten().tolist()
  63. speech_token = torch.tensor([speech_token], dtype=torch.int32).to(self.device)
  64. speech_token_len = torch.tensor([speech_token.shape[1]], dtype=torch.int32).to(self.device)
  65. return speech_token, speech_token_len
  66. def _extract_spk_embedding(self, speech):
  67. feat = kaldi.fbank(speech,
  68. num_mel_bins=80,
  69. dither=0,
  70. sample_frequency=16000)
  71. feat = feat - feat.mean(dim=0, keepdim=True)
  72. embedding = self.campplus_session.run(None, {self.campplus_session.get_inputs()[0].name: feat.unsqueeze(dim=0).cpu().numpy()})[0].flatten().tolist()
  73. embedding = torch.tensor([embedding]).to(self.device)
  74. return embedding
  75. def _extract_speech_feat(self, speech):
  76. speech_feat = self.feat_extractor(speech).squeeze(dim=0).transpose(0, 1).to(self.device)
  77. speech_feat = speech_feat.unsqueeze(dim=0)
  78. speech_feat_len = torch.tensor([speech_feat.shape[1]], dtype=torch.int32).to(self.device)
  79. return speech_feat, speech_feat_len
  80. def text_normalize(self, text, split=True):
  81. text = text.strip()
  82. if contains_chinese(text):
  83. text = self.frd.get_frd_extra_info(text, 'input').replace("\n", "")
  84. text = replace_blank(text)
  85. text = replace_corner_mark(text)
  86. text = text.replace(".", "、")
  87. text = text.replace(" - ", ",")
  88. text = remove_bracket(text)
  89. texts = [i for i in split_paragraph(text, partial(self.tokenizer.encode, allowed_special=self.allowed_special), "zh", token_max_n=80,
  90. token_min_n=60, merge_len=20,
  91. comma_split=False)]
  92. else:
  93. text = spell_out_number(text, self.inflect_parser)
  94. texts = [i for i in split_paragraph(text, partial(self.tokenizer.encode, allowed_special=self.allowed_special), "en", token_max_n=80,
  95. token_min_n=60, merge_len=20,
  96. comma_split=False)]
  97. if split is False:
  98. return text
  99. return texts
  100. def frontend_sft(self, tts_text, spk_id):
  101. tts_text_token, tts_text_token_len = self._extract_text_token(tts_text)
  102. embedding = self.spk2info[spk_id]['embedding']
  103. model_input = {'text': tts_text_token, 'text_len': tts_text_token_len, 'llm_embedding': embedding, 'flow_embedding': embedding}
  104. return model_input
  105. def frontend_zero_shot(self, tts_text, prompt_text, prompt_speech_16k):
  106. tts_text_token, tts_text_token_len = self._extract_text_token(tts_text)
  107. prompt_text_token, prompt_text_token_len = self._extract_text_token(prompt_text)
  108. prompt_speech_22050 = torchaudio.transforms.Resample(orig_freq=16000, new_freq=22050)(prompt_speech_16k)
  109. speech_feat, speech_feat_len = self._extract_speech_feat(prompt_speech_22050)
  110. speech_token, speech_token_len = self._extract_speech_token(prompt_speech_16k)
  111. embedding = self._extract_spk_embedding(prompt_speech_16k)
  112. model_input = {'text': tts_text_token, 'text_len': tts_text_token_len,
  113. 'prompt_text': prompt_text_token, 'prompt_text_len': prompt_text_token_len,
  114. 'llm_prompt_speech_token': speech_token, 'llm_prompt_speech_token_len': speech_token_len,
  115. 'flow_prompt_speech_token': speech_token, 'flow_prompt_speech_token_len': speech_token_len,
  116. 'prompt_speech_feat': speech_feat, 'prompt_speech_feat_len': speech_feat_len,
  117. 'llm_embedding': embedding, 'flow_embedding': embedding}
  118. return model_input
  119. def frontend_cross_lingual(self, tts_text, prompt_speech_16k):
  120. model_input = self.frontend_zero_shot(tts_text, '', prompt_speech_16k)
  121. # in cross lingual mode, we remove prompt in llm
  122. del model_input['prompt_text']
  123. del model_input['prompt_text_len']
  124. del model_input['llm_prompt_speech_token']
  125. del model_input['llm_prompt_speech_token_len']
  126. return model_input
  127. def frontend_instruct(self, tts_text, spk_id, instruct_text):
  128. model_input = self.frontend_sft(tts_text, spk_id)
  129. # in instruct mode, we remove spk_embedding in llm due to information leakage
  130. del model_input['llm_embedding']
  131. instruct_text_token, instruct_text_token_len = self._extract_text_token(instruct_text + '<endofprompt>')
  132. model_input['prompt_text'] = instruct_text_token
  133. model_input['prompt_text_len'] = instruct_text_token_len
  134. return model_input