File size: 814 Bytes
254b144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import numpy as np

from src.config import SR, CODE2IDX


def get_idx(duration, n_secs=5, sr=SR, random_chunk=True):
    num_frames = np.ceil(sr * duration)
    chunk_idx = (n_secs*sr)
    DEFAULT_OFFSET = 10
    start = np.random.randint(DEFAULT_OFFSET, num_frames-chunk_idx) if random_chunk else DEFAULT_OFFSET
    return start, start+chunk_idx

def to_square(arr):
    """Convert (almost square) array to a square array by padding/truncating."""
    rows, cols = arr.shape
    
    if cols < rows:
        pad_width = ((0, 0), (0, rows - cols))
        return np.pad(arr, pad_width, mode='constant')
    else:
        return arr[:, :rows]

def to_tensor(data):
    return [torch.FloatTensor(x) for x in data]

def one_hot(idx):
    y = torch.zeros(len(CODE2IDX.keys()))
    y[idx] = 1.
    return y