File size: 6,015 Bytes
8c92a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# Copyright (c) 2023 Amphion.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import os

import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F
from tqdm import tqdm
import librosa

from evaluation.metrics.similarity.models.RawNetModel import RawNet3
from evaluation.metrics.similarity.models.RawNetBasicBlock import Bottle2neck

from transformers import Wav2Vec2FeatureExtractor, WavLMForXVector
from resemblyzer import VoiceEncoder, preprocess_wav


def extract_rawnet_speaker_embd(
    model, fn: str, n_samples: int, n_segments: int = 10, gpu: bool = False
) -> np.ndarray:
    audio, sample_rate = sf.read(fn)
    if len(audio.shape) > 1:
        raise ValueError(
            f"RawNet3 supports mono input only. Input data has a shape of {audio.shape}."
        )

    if sample_rate != 16000:
        audio = librosa.resample(audio, orig_sr=sample_rate, target_sr=16000)
    if len(audio) < n_samples:
        shortage = n_samples - len(audio) + 1
        audio = np.pad(audio, (0, shortage), "wrap")

    audios = []
    startframe = np.linspace(0, len(audio) - n_samples, num=n_segments)
    for asf in startframe:
        audios.append(audio[int(asf) : int(asf) + n_samples])

    audios = torch.from_numpy(np.stack(audios, axis=0).astype(np.float32))
    if gpu:
        audios = audios.to("cuda")
    with torch.no_grad():
        output = model(audios)

    return output


def extract_similarity(path_ref, path_deg, **kwargs):
    kwargs = kwargs["kwargs"]
    model_name = kwargs["model_name"]

    ref_embds = []
    deg_embds = []

    if torch.cuda.is_available():
        device = torch.device("cuda")
    else:
        device = torch.device("cpu")

    if model_name == "rawnet":
        model = RawNet3(
            Bottle2neck,
            model_scale=8,
            context=True,
            summed=True,
            encoder_type="ECA",
            nOut=256,
            out_bn=False,
            sinc_stride=10,
            log_sinc=True,
            norm_sinc="mean",
            grad_mult=1,
        )
        model.load_state_dict(
            torch.load(
                "pretrained/rawnet3/model.pt",
                map_location=lambda storage, loc: storage,
            )["model"]
        )
        model.eval()
        model = model.to(device)

        for file in tqdm(os.listdir(path_ref)):
            output = extract_rawnet_speaker_embd(
                model,
                fn=os.path.join(path_ref, file),
                n_samples=48000,
                n_segments=10,
                gpu=torch.cuda.is_available(),
            ).mean(0)
            ref_embds.append(output)

        for file in tqdm(os.listdir(path_deg)):
            output = extract_rawnet_speaker_embd(
                model,
                fn=os.path.join(path_deg, file),
                n_samples=48000,
                n_segments=10,
                gpu=torch.cuda.is_available(),
            ).mean(0)
            deg_embds.append(output)
    elif model_name == "wavlm":
        try:
            feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
                "microsoft/wavlm-base-plus-sv"
            )
            model = WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv")
        except:
            feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
                "pretrained/wavlm", sampling_rate=16000
            )
            model = WavLMForXVector.from_pretrained("pretrained/wavlm")
        model = model.to(device)

        for file in tqdm(os.listdir(path_ref)):
            wav_path = os.path.join(path_ref, file)
            wav, _ = librosa.load(wav_path, sr=16000)

            inputs = feature_extractor(
                [wav], padding=True, return_tensors="pt", sampling_rate=16000
            )
            if torch.cuda.is_available():
                for key in inputs.keys():
                    inputs[key] = inputs[key].to(device)

            with torch.no_grad():
                embds = model(**inputs).embeddings
                embds = embds
                ref_embds.append(embds[0])

        for file in tqdm(os.listdir(path_deg)):
            wav_path = os.path.join(path_deg, file)
            wav, _ = librosa.load(wav_path, sr=16000)

            inputs = feature_extractor(
                [wav], padding=True, return_tensors="pt", sampling_rate=16000
            )
            if torch.cuda.is_available():
                for key in inputs.keys():
                    inputs[key] = inputs[key].to(device)

            with torch.no_grad():
                embds = model(**inputs).embeddings
                embds = embds
                deg_embds.append(embds[0])
    elif model_name == "resemblyzer":
        encoder = VoiceEncoder().to(device)

        for file in tqdm(os.listdir(path_ref)):
            wav_path = os.path.join(path_ref, file)
            wav = preprocess_wav(wav_path)

            output = encoder.embed_utterance(wav)
            ref_embds.append(torch.from_numpy(output).to(device))

        for file in tqdm(os.listdir(path_deg)):
            wav_path = os.path.join(path_deg, file)
            wav = preprocess_wav(wav_path)

            output = encoder.embed_utterance(wav)
            deg_embds.append(torch.from_numpy(output).to(device))

    similarity_mode = kwargs["similarity_mode"]
    scores = []

    if similarity_mode == "pairwith":
        for ref_embd, deg_embd in zip(ref_embds, deg_embds):
            scores.append(
                F.cosine_similarity(ref_embd, deg_embd, dim=-1).detach().cpu().numpy()
            )
    elif similarity_mode == "overall":
        for ref_embd in ref_embds:
            for deg_embd in deg_embds:
                scores.append(
                    F.cosine_similarity(ref_embd, deg_embd, dim=-1)
                    .detach()
                    .cpu()
                    .numpy()
                )

    return np.mean(scores)