cosyvoice.py 9.9 KB

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