|
"""Meta's w2vBERT based speaker embedding. |
|
- feature dimension: 1024 |
|
- source: https://huggingface.co/facebook/w2v-bert-2.0 |
|
""" |
|
from typing import Optional |
|
|
|
import torch |
|
import librosa |
|
import numpy as np |
|
from transformers import Wav2Vec2BertModel, AutoFeatureExtractor |
|
|
|
|
|
class W2VBertSE: |
|
def __init__(self): |
|
self.processor = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0") |
|
self.model = Wav2Vec2BertModel.from_pretrained("facebook/w2v-bert-2.0") |
|
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: |
|
|
|
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] |
|
|