cosyvoice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. import os
  15. import time
  16. from typing import Generator
  17. from tqdm import tqdm
  18. from hyperpyyaml import load_hyperpyyaml
  19. from modelscope import snapshot_download
  20. import torch
  21. from cosyvoice.cli.frontend import CosyVoiceFrontEnd
  22. from cosyvoice.cli.model import CosyVoiceModel, CosyVoice2Model
  23. from cosyvoice.utils.file_utils import logging
  24. from cosyvoice.utils.class_utils import get_model_type
  25. class CosyVoice:
  26. def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False):
  27. self.instruct = True if '-Instruct' in model_dir else False
  28. self.model_dir = model_dir
  29. self.fp16 = fp16
  30. if not os.path.exists(model_dir):
  31. model_dir = snapshot_download(model_dir)
  32. hyper_yaml_path = '{}/cosyvoice.yaml'.format(model_dir)
  33. if not os.path.exists(hyper_yaml_path):
  34. raise ValueError('{} not found!'.format(hyper_yaml_path))
  35. with open(hyper_yaml_path, 'r') as f:
  36. configs = load_hyperpyyaml(f)
  37. assert get_model_type(configs) != CosyVoice2Model, 'do not use {} for CosyVoice initialization!'.format(model_dir)
  38. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  39. configs['feat_extractor'],
  40. '{}/campplus.onnx'.format(model_dir),
  41. '{}/speech_tokenizer_v1.onnx'.format(model_dir),
  42. '{}/spk2info.pt'.format(model_dir),
  43. configs['allowed_special'])
  44. self.sample_rate = configs['sample_rate']
  45. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or fp16 is True):
  46. load_jit, load_trt, fp16 = False, False, False
  47. logging.warning('no cuda device, set load_jit/load_trt/fp16 to False')
  48. self.model = CosyVoiceModel(configs['llm'], configs['flow'], configs['hift'], fp16)
  49. self.model.load('{}/llm.pt'.format(model_dir),
  50. '{}/flow.pt'.format(model_dir),
  51. '{}/hift.pt'.format(model_dir))
  52. if load_jit:
  53. self.model.load_jit('{}/llm.text_encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  54. '{}/llm.llm.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  55. '{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  56. if load_trt:
  57. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  58. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  59. self.fp16)
  60. del configs
  61. def list_available_spks(self):
  62. spks = list(self.frontend.spk2info.keys())
  63. return spks
  64. def add_zero_shot_spk(self, prompt_text, prompt_speech_16k, zero_shot_spk_id):
  65. assert zero_shot_spk_id != '', 'do not use empty zero_shot_spk_id'
  66. model_input = self.frontend.frontend_zero_shot('', prompt_text, prompt_speech_16k, self.sample_rate, '')
  67. del model_input['text']
  68. del model_input['text_len']
  69. self.frontend.spk2info[zero_shot_spk_id] = model_input
  70. return True
  71. def inference_sft(self, tts_text, spk_id, stream=False, speed=1.0, text_frontend=True):
  72. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  73. model_input = self.frontend.frontend_sft(i, spk_id)
  74. start_time = time.time()
  75. logging.info('synthesis text {}'.format(i))
  76. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  77. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  78. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  79. yield model_output
  80. start_time = time.time()
  81. def inference_zero_shot(self, tts_text, prompt_text, prompt_speech_16k, zero_shot_spk_id='', stream=False, speed=1.0, text_frontend=True):
  82. prompt_text = self.frontend.text_normalize(prompt_text, split=False, text_frontend=text_frontend)
  83. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  84. if (not isinstance(i, Generator)) and len(i) < 0.5 * len(prompt_text):
  85. logging.warning('synthesis text {} too short than prompt text {}, this may lead to bad performance'.format(i, prompt_text))
  86. model_input = self.frontend.frontend_zero_shot(i, prompt_text, prompt_speech_16k, self.sample_rate, zero_shot_spk_id)
  87. start_time = time.time()
  88. logging.info('synthesis text {}'.format(i))
  89. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  90. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  91. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  92. yield model_output
  93. start_time = time.time()
  94. def inference_cross_lingual(self, tts_text, prompt_speech_16k, stream=False, speed=1.0, text_frontend=True):
  95. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  96. model_input = self.frontend.frontend_cross_lingual(i, prompt_speech_16k, self.sample_rate)
  97. start_time = time.time()
  98. logging.info('synthesis text {}'.format(i))
  99. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  100. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  101. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  102. yield model_output
  103. start_time = time.time()
  104. def inference_instruct(self, tts_text, spk_id, instruct_text, stream=False, speed=1.0, text_frontend=True):
  105. assert isinstance(self.model, CosyVoiceModel), 'inference_instruct is only implemented for CosyVoice!'
  106. if self.instruct is False:
  107. raise ValueError('{} do not support instruct inference'.format(self.model_dir))
  108. instruct_text = self.frontend.text_normalize(instruct_text, split=False, text_frontend=text_frontend)
  109. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  110. model_input = self.frontend.frontend_instruct(i, spk_id, instruct_text)
  111. start_time = time.time()
  112. logging.info('synthesis text {}'.format(i))
  113. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  114. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  115. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  116. yield model_output
  117. start_time = time.time()
  118. def inference_vc(self, source_speech_16k, prompt_speech_16k, stream=False, speed=1.0):
  119. model_input = self.frontend.frontend_vc(source_speech_16k, prompt_speech_16k, self.sample_rate)
  120. start_time = time.time()
  121. for model_output in self.model.vc(**model_input, stream=stream, speed=speed):
  122. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  123. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  124. yield model_output
  125. start_time = time.time()
  126. class CosyVoice2(CosyVoice):
  127. def __init__(self, model_dir, load_jit=False, load_trt=False, fp16=False, use_flow_cache=False):
  128. self.instruct = True if '-Instruct' in model_dir else False
  129. self.model_dir = model_dir
  130. self.fp16 = fp16
  131. if not os.path.exists(model_dir):
  132. model_dir = snapshot_download(model_dir)
  133. hyper_yaml_path = '{}/cosyvoice2.yaml'.format(model_dir)
  134. if not os.path.exists(hyper_yaml_path):
  135. raise ValueError('{} not found!'.format(hyper_yaml_path))
  136. with open(hyper_yaml_path, 'r') as f:
  137. configs = load_hyperpyyaml(f, overrides={'qwen_pretrain_path': os.path.join(model_dir, 'CosyVoice-BlankEN')})
  138. assert get_model_type(configs) == CosyVoice2Model, 'do not use {} for CosyVoice2 initialization!'.format(model_dir)
  139. self.frontend = CosyVoiceFrontEnd(configs['get_tokenizer'],
  140. configs['feat_extractor'],
  141. '{}/campplus.onnx'.format(model_dir),
  142. '{}/speech_tokenizer_v2.onnx'.format(model_dir),
  143. '{}/spk2info.pt'.format(model_dir),
  144. configs['allowed_special'])
  145. self.sample_rate = configs['sample_rate']
  146. if torch.cuda.is_available() is False and (load_jit is True or load_trt is True or fp16 is True):
  147. load_jit, load_trt, fp16 = False, False, False
  148. logging.warning('no cuda device, set load_jit/load_trt/fp16 to False')
  149. self.model = CosyVoice2Model(configs['llm'], configs['flow'], configs['hift'], fp16, use_flow_cache)
  150. self.model.load('{}/llm.pt'.format(model_dir),
  151. '{}/flow.pt'.format(model_dir) if use_flow_cache is False else '{}/flow.cache.pt'.format(model_dir),
  152. '{}/hift.pt'.format(model_dir))
  153. if load_jit:
  154. self.model.load_jit('{}/flow.encoder.{}.zip'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'))
  155. if load_trt:
  156. self.model.load_trt('{}/flow.decoder.estimator.{}.mygpu.plan'.format(model_dir, 'fp16' if self.fp16 is True else 'fp32'),
  157. '{}/flow.decoder.estimator.fp32.onnx'.format(model_dir),
  158. self.fp16)
  159. del configs
  160. def inference_instruct(self, *args, **kwargs):
  161. raise NotImplementedError('inference_instruct is not implemented for CosyVoice2!')
  162. def inference_instruct2(self, tts_text, instruct_text, prompt_speech_16k, stream=False, speed=1.0, text_frontend=True):
  163. assert isinstance(self.model, CosyVoice2Model), 'inference_instruct2 is only implemented for CosyVoice2!'
  164. for i in tqdm(self.frontend.text_normalize(tts_text, split=True, text_frontend=text_frontend)):
  165. model_input = self.frontend.frontend_instruct2(i, instruct_text, prompt_speech_16k, self.sample_rate)
  166. start_time = time.time()
  167. logging.info('synthesis text {}'.format(i))
  168. for model_output in self.model.tts(**model_input, stream=stream, speed=speed):
  169. speech_len = model_output['tts_speech'].shape[1] / self.sample_rate
  170. logging.info('yield speech len {}, rtf {}'.format(speech_len, (time.time() - start_time) / speech_len))
  171. yield model_output
  172. start_time = time.time()