1
0

extract_embedding.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. def extract_embedding(input_list):
  24. utt, wav_file, ort_session = input_list
  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 = (
  33. ort_session.run(
  34. None,
  35. {
  36. ort_session.get_inputs()[0]
  37. .name: feat.unsqueeze(dim=0)
  38. .cpu()
  39. .numpy()
  40. },
  41. )[0]
  42. .flatten()
  43. .tolist()
  44. )
  45. return (utt, embedding)
  46. def main(args):
  47. utt2wav, utt2spk = {}, {}
  48. with open("{}/wav.scp".format(args.dir)) as f:
  49. for l in f:
  50. l = l.replace("\n", "").split()
  51. utt2wav[l[0]] = l[1]
  52. with open("{}/utt2spk".format(args.dir)) as f:
  53. for l in f:
  54. l = l.replace("\n", "").split()
  55. utt2spk[l[0]] = l[1]
  56. assert os.path.exists(args.onnx_path), "onnx_path not exists"
  57. option = onnxruntime.SessionOptions()
  58. option.graph_optimization_level = (
  59. onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  60. )
  61. option.intra_op_num_threads = 1
  62. providers = ["CPUExecutionProvider"]
  63. ort_session = onnxruntime.InferenceSession(
  64. args.onnx_path, sess_options=option, providers=providers
  65. )
  66. inputs = [
  67. (utt, utt2wav[utt], ort_session)
  68. for utt in tqdm(utt2wav.keys(), desc="Load data")
  69. ]
  70. with ThreadPoolExecutor(max_workers=args.num_thread) as executor:
  71. results = list(
  72. tqdm(
  73. executor.map(extract_embedding, inputs),
  74. total=len(inputs),
  75. desc="Process data: ",
  76. )
  77. )
  78. utt2embedding, spk2embedding = {}, {}
  79. for utt, embedding in results:
  80. utt2embedding[utt] = embedding
  81. spk = utt2spk[utt]
  82. if spk not in spk2embedding:
  83. spk2embedding[spk] = []
  84. spk2embedding[spk].append(embedding)
  85. for k, v in spk2embedding.items():
  86. spk2embedding[k] = torch.tensor(v).mean(dim=0).tolist()
  87. torch.save(utt2embedding, "{}/utt2embedding.pt".format(args.dir))
  88. torch.save(spk2embedding, "{}/spk2embedding.pt".format(args.dir))
  89. if __name__ == "__main__":
  90. parser = argparse.ArgumentParser()
  91. parser.add_argument("--dir", type=str)
  92. parser.add_argument("--onnx_path", type=str)
  93. parser.add_argument("--num_thread", type=int, default=8)
  94. args = parser.parse_args()
  95. main(args)