extract_embedding.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 os
  17. from concurrent.futures import ThreadPoolExecutor
  18. import onnxruntime
  19. import torch
  20. import torchaudio
  21. import torchaudio.compliance.kaldi as kaldi
  22. from tqdm import tqdm
  23. from itertools import repeat
  24. def extract_embedding(utt: str, wav_file: str, ort_session: onnxruntime.InferenceSession):
  25. audio, sample_rate = torchaudio.load(wav_file)
  26. if sample_rate != 16000:
  27. audio = torchaudio.transforms.Resample(
  28. orig_freq=sample_rate, new_freq=16000
  29. )(audio)
  30. feat = kaldi.fbank(audio, num_mel_bins=80, dither=0, sample_frequency=16000)
  31. feat = feat - feat.mean(dim=0, keepdim=True)
  32. embedding = ort_session.run(None, {ort_session.get_inputs()[0].name: feat.unsqueeze(dim=0).cpu().numpy()})[0].flatten().tolist()
  33. return (utt, embedding)
  34. def main(args):
  35. utt2wav, utt2spk = {}, {}
  36. with open("{}/wav.scp".format(args.dir)) as f:
  37. for l in f:
  38. l = l.replace("\n", "").split()
  39. utt2wav[l[0]] = l[1]
  40. with open("{}/utt2spk".format(args.dir)) as f:
  41. for l in f:
  42. l = l.replace("\n", "").split()
  43. utt2spk[l[0]] = l[1]
  44. assert os.path.exists(args.onnx_path), "onnx_path not exists"
  45. option = onnxruntime.SessionOptions()
  46. option.graph_optimization_level = (
  47. onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  48. )
  49. option.intra_op_num_threads = 1
  50. providers = ["CPUExecutionProvider"]
  51. ort_session = onnxruntime.InferenceSession(
  52. args.onnx_path, sess_options=option, providers=providers
  53. )
  54. all_utt = utt2wav.keys()
  55. with ThreadPoolExecutor(max_workers=args.num_thread) as executor:
  56. results = list(
  57. tqdm(
  58. executor.map(extract_embedding, all_utt, [utt2wav[utt] for utt in all_utt], repeat(ort_session)),
  59. total=len(utt2wav),
  60. desc="Process data: "
  61. )
  62. )
  63. utt2embedding, spk2embedding = {}, {}
  64. for utt, embedding in results:
  65. utt2embedding[utt] = embedding
  66. spk = utt2spk[utt]
  67. if spk not in spk2embedding:
  68. spk2embedding[spk] = []
  69. spk2embedding[spk].append(embedding)
  70. for k, v in spk2embedding.items():
  71. spk2embedding[k] = torch.tensor(v).mean(dim=0).tolist()
  72. torch.save(utt2embedding, "{}/utt2embedding.pt".format(args.dir))
  73. torch.save(spk2embedding, "{}/spk2embedding.pt".format(args.dir))
  74. if __name__ == "__main__":
  75. parser = argparse.ArgumentParser()
  76. parser.add_argument("--dir", type=str)
  77. parser.add_argument("--onnx_path", type=str)
  78. parser.add_argument("--num_thread", type=int, default=8)
  79. args = parser.parse_args()
  80. main(args)