utils.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import numpy as np
  2. from scipy.io.wavfile import read
  3. import torch
  4. def get_mask_from_lengths(lengths):
  5. max_len = torch.max(lengths).item()
  6. # ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
  7. ids = torch.arange(0, max_len, out=torch.LongTensor(max_len))
  8. mask = (ids < lengths.unsqueeze(1)).bool()
  9. return mask
  10. def load_wav_to_torch(full_path):
  11. sampling_rate, data = read(full_path)
  12. return torch.FloatTensor(data.astype(np.float32)), sampling_rate
  13. def load_filepaths_and_text(filename, split="|"):
  14. with open(filename, encoding='utf-8') as f:
  15. filepaths_and_text = [line.strip().split(split) for line in f]
  16. return filepaths_and_text
  17. def files_to_list(filename):
  18. """
  19. Takes a text file of filenames and makes a list of filenames
  20. """
  21. with open(filename, encoding='utf-8') as f:
  22. files = f.readlines()
  23. files = [f.rstrip() for f in files]
  24. return files
  25. def to_gpu(x):
  26. x = x.contiguous()
  27. if torch.cuda.is_available():
  28. x = x.cuda(non_blocking=True)
  29. return torch.autograd.Variable(x)