extract_embedding.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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 torch
  17. import torchaudio
  18. from tqdm import tqdm
  19. import onnxruntime
  20. import torchaudio.compliance.kaldi as kaldi
  21. from queue import Queue, Empty
  22. from threading import Thread
  23. class ExtractEmbedding:
  24. def __init__(self, model_path: str, queue: Queue, out_queue: Queue):
  25. self.model_path = model_path
  26. self.queue = queue
  27. self.out_queue = out_queue
  28. self.is_run = True
  29. def run(self):
  30. self.consumer_thread = Thread(target=self.consumer)
  31. self.consumer_thread.start()
  32. def stop(self):
  33. self.is_run = False
  34. self.consumer_thread.join()
  35. def consumer(self):
  36. option = onnxruntime.SessionOptions()
  37. option.graph_optimization_level = (
  38. onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
  39. )
  40. option.intra_op_num_threads = 1
  41. providers = ["CPUExecutionProvider"]
  42. ort_session = onnxruntime.InferenceSession(
  43. self.model_path, sess_options=option, providers=providers
  44. )
  45. while self.is_run:
  46. try:
  47. utt, wav_file = self.queue.get(timeout=1)
  48. audio, sample_rate = torchaudio.load(wav_file)
  49. if sample_rate != 16000:
  50. audio = torchaudio.transforms.Resample(
  51. orig_freq=sample_rate, new_freq=16000
  52. )(audio)
  53. feat = kaldi.fbank(
  54. audio, num_mel_bins=80, dither=0, sample_frequency=16000
  55. )
  56. feat = feat - feat.mean(dim=0, keepdim=True)
  57. embedding = (
  58. ort_session.run(
  59. None,
  60. {
  61. ort_session.get_inputs()[0]
  62. .name: feat.unsqueeze(dim=0)
  63. .cpu()
  64. .numpy()
  65. },
  66. )[0]
  67. .flatten()
  68. .tolist()
  69. )
  70. self.out_queue.put((utt, embedding))
  71. except Empty:
  72. self.is_run = False
  73. break
  74. def main(args):
  75. utt2wav, utt2spk = {}, {}
  76. with open("{}/wav.scp".format(args.dir)) as f:
  77. for l in f:
  78. l = l.replace("\n", "").split()
  79. utt2wav[l[0]] = l[1]
  80. with open("{}/utt2spk".format(args.dir)) as f:
  81. for l in f:
  82. l = l.replace("\n", "").split()
  83. utt2spk[l[0]] = l[1]
  84. input_queue = Queue()
  85. output_queue = Queue()
  86. consumers = [
  87. ExtractEmbedding(args.onnx_path, input_queue, output_queue)
  88. for _ in range(args.num_thread)
  89. ]
  90. utt2embedding, spk2embedding = {}, {}
  91. for utt in tqdm(utt2wav.keys(), desc="Load data"):
  92. input_queue.put((utt, utt2wav[utt]))
  93. for c in consumers:
  94. c.run()
  95. with tqdm(desc="Process data: ", total=len(utt2wav)) as pbar:
  96. while any([c.is_run for c in consumers]):
  97. try:
  98. utt, embedding = output_queue.get(timeout=1)
  99. utt2embedding[utt] = embedding
  100. spk = utt2spk[utt]
  101. if spk not in spk2embedding:
  102. spk2embedding[spk] = []
  103. spk2embedding[spk].append(embedding)
  104. pbar.update(1)
  105. except Empty:
  106. continue
  107. for k, v in spk2embedding.items():
  108. spk2embedding[k] = torch.tensor(v).mean(dim=0).tolist()
  109. torch.save(utt2embedding, "{}/utt2embedding.pt".format(args.dir))
  110. torch.save(spk2embedding, "{}/spk2embedding.pt".format(args.dir))
  111. if __name__ == "__main__":
  112. parser = argparse.ArgumentParser()
  113. parser.add_argument("--dir", type=str)
  114. parser.add_argument("--onnx_path", type=str)
  115. parser.add_argument("--num_thread", type=int, default=8)
  116. args = parser.parse_args()
  117. main(args)