-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathutils.py
executable file
·64 lines (48 loc) · 1.63 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import numpy as np
from scipy.io.wavfile import read
import torch
def get_mask_from_lengths(lengths):
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
boolean_tmp = (ids < lengths.unsqueeze(1))
# mask = boolean_tmp.bool()
# return mask
return boolean_tmp
def read_wav_np(path):
try:
sr, wav = read(path)
except Exception as e:
print(str(e) + path)
return Exception
if len(wav.shape) == 2:
wav = wav[:, 0]
if wav.dtype == np.int16:
wav = wav / 32768.0
elif wav.dtype == np.int32:
wav = wav / 2147483648.0
elif wav.dtype == np.uint8:
wav = (wav - 128) / 128.0
wav = wav.astype(np.float32)
return sr, wav
def load_wav_to_torch(full_path):
# scipy.wavefil.read does not take care of the case where wav is int or uint.
# Thus, scipy.read is replaced with read_wav_np
sampling_rate, data = read_wav_np(full_path)
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
def load_filepaths_and_text(filename, split="|"):
with open(filename, encoding='utf-8-sig') as f:
filepaths_and_text = [line.strip().split(split) for line in f]
return filepaths_and_text
def files_to_list(filename):
"""
Takes a text file of filenames and makes a list of filenames
"""
with open(filename, encoding='utf-8') as f:
files = f.readlines()
files = [f.rstrip() for f in files]
return files
def to_gpu(x):
x = x.contiguous()
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return torch.autograd.Variable(x)