File size: 1,329 Bytes
855b061 |
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 |
"""Meta's XLS-R based speaker embedding.
- feature dimension: 768
- source: https://huggingface.co/facebook/wav2vec2-large-xlsr-53
"""
from typing import Optional
import torch
import librosa
import numpy as np
from transformers import AutoFeatureExtractor, AutoModelForPreTraining
class XLSRSE:
def __init__(self):
self.processor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53")
self.model = AutoModelForPreTraining.from_pretrained("facebook/wav2vec2-large-xlsr-53")
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.projected_states.mean(1).cpu().numpy()[0]
# return outputs.projected_quantized_states.mean(1).cpu().numpy()[0]
|