File size: 1,372 Bytes
557d798
 
 
 
 
 
8d18b82
6a9e591
557d798
8d18b82
6a9e591
 
557d798
 
6a9e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d18b82
 
6a9e591
 
8d18b82
 
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
import numpy as np
import librosa

SR = 16000
N_COEFFS = 20

def extract_mfcc(y, sr, n_mfcc=N_COEFFS):
    return librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc)

def extract_lfcc(y, sr, n_lfcc=N_COEFFS):
    S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=n_lfcc, fmin=0, fmax=sr/2)
    return librosa.power_to_db(S)

def extract_features_with_time_series(file_path, sr=SR, n_coeffs=N_COEFFS):
    try:
        y, _ = librosa.load(file_path, sr=sr, mono=True)
        y, _ = librosa.effects.trim(y)
        if np.max(np.abs(y)) > 0:
            y = y / np.max(np.abs(y))

        mfccs = extract_mfcc(y, sr, n_mfcc=n_coeffs)
        lfccs = extract_lfcc(y, sr, n_lfcc=n_coeffs)
        chroma = librosa.feature.chroma_stft(y=y, sr=sr)
        spec_centroid = librosa.feature.spectral_centroid(y=y, sr=sr)
        spec_bandwidth = librosa.feature.spectral_bandwidth(y=y, sr=sr)
        zcr = librosa.feature.zero_crossing_rate(y)

        features_to_stack = [mfccs, lfccs, chroma, spec_centroid, spec_bandwidth, zcr]
        max_len = max(f.shape[1] for f in features_to_stack)
        padded = [librosa.util.fix_length(f, size=max_len, axis=1) for f in features_to_stack]
        stacked_features = np.vstack(padded).astype(np.float32)
        return stacked_features.T
    except Exception as e:
        print(f"[extract_features] Error: {e}")
        return None