File size: 1,294 Bytes
e18a750
 
 
 
 
 
 
 
8bf27de
c4aab69
e18a750
4b3147f
 
e18a750
 
4b3147f
e18a750
 
 
 
 
 
 
 
 
 
 
 
 
 
8bf27de
e18a750
 
 
 
 
 
 
 
 
 
 
 
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

from typing import Callable, Optional

import numpy as np

import librosa

import gradio as gr
from datetime import datetime


def predict_gradio(data, 
        uniform_lambda,
        sklearn_model,
        label_transform,
        target_sr: int = 22_050):
    if data is None:
        return 

    classes = sklearn_model.classes_
    if label_transform is not None:
        classes = label_transform.inverse_transform(classes)
    
    
    y, sr = data[1], data[0]
    y_original_signal = load_as_librosa(y, sr, target_sr=target_sr)
    y_uniform = uniform_lambda(y_original_signal, target_sr).astype(np.float32)
    prediction = sklearn_model.predict_proba(y_uniform.reshape(1, -1))
    result = {str(label): float(confidence) for (
        label, confidence) in zip(classes, prediction.flatten())}
    print(f"{datetime.now()}")
    return result

def load_as_librosa(y: np.ndarray, sr: int, target_sr: int = 22050) -> np.ndarray:
    data_dtype = y.dtype
    dtype_min = np.iinfo(data_dtype).min
    dtype_max = np.iinfo(data_dtype).max
    dtype_range = np.abs(dtype_max-dtype_min)
    y_normalize = (y.astype(np.float32)-dtype_min)/dtype_range
    y_normalize_resample = librosa.resample(y=y_normalize,
        orig_sr=sr,
        target_sr=target_sr)
    return y_normalize_resample