cosyvoice.py 11 KB

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