1
0

extract_speech_token.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import logging
  17. import torch
  18. from tqdm import tqdm
  19. import onnxruntime
  20. import numpy as np
  21. import torchaudio
  22. import whisper
  23. def main(args):
  24. utt2wav = {}
  25. with open('{}/wav.scp'.format(args.dir)) as f:
  26. for l in f:
  27. l = l.replace('\n', '').split()
  28. utt2wav[l[0]] = l[1]
  29. option = onnxruntime.SessionOptions()
  30. option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  31. option.intra_op_num_threads = 1
  32. providers = ["CUDAExecutionProvider"]
  33. ort_session = onnxruntime.InferenceSession(args.onnx_path, sess_options=option, providers=providers)
  34. utt2speech_token = {}
  35. for utt in tqdm(utt2wav.keys()):
  36. audio, sample_rate = torchaudio.load(utt2wav[utt])
  37. if sample_rate != 16000:
  38. audio = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(audio)
  39. if audio.shape[1] / 16000 > 30:
  40. logging.warning('do not support extract speech token for audio longer than 30s')
  41. speech_token = []
  42. else:
  43. feat = whisper.log_mel_spectrogram(audio, n_mels=128)
  44. speech_token = ort_session.run(None, {ort_session.get_inputs()[0].name: feat.detach().cpu().numpy(),
  45. ort_session.get_inputs()[1].name: np.array([feat.shape[2]], dtype=np.int32)})[0].flatten().tolist()
  46. utt2speech_token[utt] = speech_token
  47. torch.save(utt2speech_token, '{}/utt2speech_token.pt'.format(args.dir))
  48. if __name__ == "__main__":
  49. parser = argparse.ArgumentParser()
  50. parser.add_argument('--dir',
  51. type=str)
  52. parser.add_argument('--onnx_path',
  53. type=str)
  54. args = parser.parse_args()
  55. main(args)