1
0

file_utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
  2. # 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 json
  16. import torchaudio
  17. import logging
  18. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  19. logging.basicConfig(level=logging.DEBUG,
  20. format='%(asctime)s %(levelname)s %(message)s')
  21. def read_lists(list_file):
  22. lists = []
  23. with open(list_file, 'r', encoding='utf8') as fin:
  24. for line in fin:
  25. lists.append(line.strip())
  26. return lists
  27. def read_json_lists(list_file):
  28. lists = read_lists(list_file)
  29. results = {}
  30. for fn in lists:
  31. with open(fn, 'r', encoding='utf8') as fin:
  32. results.update(json.load(fin))
  33. return results
  34. def load_wav(wav, target_sr):
  35. speech, sample_rate = torchaudio.load(wav)
  36. speech = speech.mean(dim=0, keepdim=True)
  37. if sample_rate != target_sr:
  38. assert sample_rate > target_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
  39. speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
  40. return speech