File size: 2,141 Bytes
7b838b6
4325a58
 
 
 
 
b24d689
4325a58
 
b24d689
 
 
 
 
4325a58
 
 
 
 
 
 
 
 
 
 
 
 
2bafee2
4325a58
 
b24d689
 
 
 
 
 
 
 
 
4325a58
 
bb0e417
 
b24d689
bb0e417
 
 
b24d689
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
"""Meta's w2vBERT based speaker embedding."""
from typing import Optional

import torch
import librosa
import numpy as np
from transformers import AutoModel, AutoFeatureExtractor


############
# W2V BERT #
############
class W2VBERTEmbedding:
    def __init__(self, ckpt: str = "facebook/w2v-bert-2.0"):
        self.processor = AutoFeatureExtractor.from_pretrained(ckpt)
        self.model = AutoModel.from_pretrained(ckpt)
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model.to(self.device)
        self.model.eval()

    def get_speaker_embedding(self, wav: np.ndarray, sampling_rate: Optional[int] = None) -> np.ndarray:
        # audio file is decoded on the fly
        if sampling_rate != self.processor.sampling_rate:
            wav = librosa.resample(wav, orig_sr=sampling_rate, target_sr=self.processor.sampling_rate)
        inputs = self.processor(wav, sampling_rate=self.processor.sampling_rate, return_tensors="pt")
        with torch.no_grad():
            outputs = self.model(**{k: v.to(self.device) for k, v in inputs.items()})
        return outputs.last_hidden_state.mean(1).cpu().numpy()[0]


##########
# HuBERT #
##########
class HuBERTXLEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/hubert-xlarge-ll60k")


class HuBERTLargeEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/hubert-large-ll60k")


class HuBERTBaseEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/hubert-base-ls960")


###########
# wav2vec #
###########
class Wav2VecEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/wav2vec2-large-xlsr-53")


#########
# XLS-R #
#########
class XLSR2BEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/wav2vec2-xls-r-2b")


class XLSR1BEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/wav2vec2-xls-r-1b")


class XLSR300MEmbedding(W2VBERTEmbedding):
    def __init__(self):
        super().__init__("facebook/wav2vec2-xls-r-300m")