1
0

inference.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 __future__ import print_function
  15. import argparse
  16. import logging
  17. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  18. import os
  19. import torch
  20. from torch.utils.data import DataLoader
  21. import torchaudio
  22. from hyperpyyaml import load_hyperpyyaml
  23. from tqdm import tqdm
  24. from cosyvoice.cli.model import CosyVoiceModel
  25. from cosyvoice.dataset.dataset import Dataset
  26. def get_args():
  27. parser = argparse.ArgumentParser(description='inference with your model')
  28. parser.add_argument('--config', required=True, help='config file')
  29. parser.add_argument('--prompt_data', required=True, help='prompt data file')
  30. parser.add_argument('--prompt_utt2data', required=True, help='prompt data file')
  31. parser.add_argument('--tts_text', required=True, help='tts input file')
  32. parser.add_argument('--llm_model', required=True, help='llm model file')
  33. parser.add_argument('--flow_model', required=True, help='flow model file')
  34. parser.add_argument('--hifigan_model', required=True, help='hifigan model file')
  35. parser.add_argument('--gpu',
  36. type=int,
  37. default=-1,
  38. help='gpu id for this rank, -1 for cpu')
  39. parser.add_argument('--mode',
  40. default='sft',
  41. choices=['sft', 'zero_shot'],
  42. help='inference mode')
  43. parser.add_argument('--result_dir', required=True, help='asr result file')
  44. args = parser.parse_args()
  45. print(args)
  46. return args
  47. def main():
  48. args = get_args()
  49. logging.basicConfig(level=logging.DEBUG,
  50. format='%(asctime)s %(levelname)s %(message)s')
  51. os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)
  52. # Init cosyvoice models from configs
  53. use_cuda = args.gpu >= 0 and torch.cuda.is_available()
  54. device = torch.device('cuda' if use_cuda else 'cpu')
  55. with open(args.config, 'r') as f:
  56. configs = load_hyperpyyaml(f)
  57. model = CosyVoiceModel(configs['llm'], configs['flow'], configs['hift'])
  58. model.load(args.llm_model, args.flow_model, args.hifigan_model)
  59. test_dataset = Dataset(args.prompt_data, data_pipeline=configs['data_pipeline'], mode='inference', shuffle=False, partition=False, tts_file=args.tts_text, prompt_utt2data=args.prompt_utt2data)
  60. test_data_loader = DataLoader(test_dataset, batch_size=None, num_workers=0)
  61. del configs
  62. os.makedirs(args.result_dir, exist_ok=True)
  63. fn = os.path.join(args.result_dir, 'wav.scp')
  64. f = open(fn, 'w')
  65. with torch.no_grad():
  66. for batch_idx, batch in tqdm(enumerate(test_data_loader)):
  67. utts = batch["utts"]
  68. assert len(utts) == 1, "inference mode only support batchsize 1"
  69. text = batch["text"]
  70. text_token = batch["text_token"].to(device)
  71. text_token_len = batch["text_token_len"].to(device)
  72. tts_text = batch["tts_text"]
  73. tts_index = batch["tts_index"]
  74. tts_text_token = batch["tts_text_token"].to(device)
  75. tts_text_token_len = batch["tts_text_token_len"].to(device)
  76. speech_token = batch["speech_token"].to(device)
  77. speech_token_len = batch["speech_token_len"].to(device)
  78. speech_feat = batch["speech_feat"].to(device)
  79. speech_feat_len = batch["speech_feat_len"].to(device)
  80. utt_embedding = batch["utt_embedding"].to(device)
  81. spk_embedding = batch["spk_embedding"].to(device)
  82. if args.mode == 'sft':
  83. model_input = {'text': tts_text_token, 'text_len': tts_text_token_len,
  84. 'llm_embedding': spk_embedding, 'flow_embedding': spk_embedding}
  85. else:
  86. model_input = {'text': tts_text_token, 'text_len': tts_text_token_len,
  87. 'prompt_text': text_token, 'prompt_text_len': text_token_len,
  88. 'llm_prompt_speech_token': speech_token, 'llm_prompt_speech_token_len': speech_token_len,
  89. 'flow_prompt_speech_token': speech_token, 'flow_prompt_speech_token_len': speech_token_len,
  90. 'prompt_speech_feat': speech_feat, 'prompt_speech_feat_len': speech_feat_len,
  91. 'llm_embedding': utt_embedding, 'flow_embedding': utt_embedding}
  92. tts_speeches = []
  93. for model_output in model.inference(**model_input):
  94. tts_speeches.append(model_output['tts_speech'])
  95. tts_speeches = torch.concat(tts_speeches, dim=1)
  96. tts_key = '{}_{}'.format(utts[0], tts_index[0])
  97. tts_fn = os.path.join(args.result_dir, '{}.wav'.format(tts_key))
  98. torchaudio.save(tts_fn, tts_speeches, sample_rate=22050)
  99. f.write('{} {}\n'.format(tts_key, tts_fn))
  100. f.flush()
  101. f.close()
  102. logging.info('Result wav.scp saved in {}'.format(fn))
  103. if __name__ == '__main__':
  104. main()