File size: 7,219 Bytes
58ddaaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f334f8a
 
58ddaaa
 
 
 
 
 
f334f8a
58ddaaa
 
 
 
 
 
 
 
 
 
 
 
 
 
f334f8a
 
58ddaaa
f334f8a
 
 
 
 
 
 
 
58ddaaa
 
 
f334f8a
 
 
 
 
 
 
 
58ddaaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from datasets import load_dataset
from tqdm.auto import tqdm
from speech_collator import SpeechCollator
import json
from torch.utils.data import DataLoader
import torch
from vocex import Vocex
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

vocex = Vocex.from_pretrained("cdminix/vocex")


dataset = load_dataset("libritts-r-aligned.py")

# Load the speaker2idx and phone2idx dictionaries
with open("data/speaker2idx.json", "r") as f:
    speaker2idx = json.load(f)
    idx2speaker = {v: k for k, v in speaker2idx.items()}
with open("data/phone2idx.json", "r") as f:
    phone2idx = json.load(f)
    idx2phone = {v: k for k, v in phone2idx.items()}

collator = SpeechCollator(
    speaker2idx=speaker2idx,
    phone2idx=phone2idx,
)

dataloader = DataLoader(
    dataset["dev"],
    batch_size=1,
    shuffle=False,
    collate_fn=collator.collate_fn,
    num_workers=4,
)

def resample(x, vpw=5):
    return np.interp(np.linspace(0, 1, vpw), np.linspace(0, 1, len(x)), x)

mean_pitchs = []
std_pitchs = []
mean_energys = []
std_energys = []
mean_durations = []
std_durations = []
mean_dvecs = []
std_dvecs = []

for item in tqdm(dataloader):
    result = vocex.model(item["mel"], inference=True)
    pitch = result["measures"]["pitch"]
    energy = result["measures"]["energy"]
    va = result["measures"]["voice_activity_binary"]
    dvec = result["dvector"]
    mean_pitch = pitch.mean()
    std_pitch = pitch.std()
    mean_energy = energy.mean()
    std_energy = energy.std()
    durations = item["phone_durations"].squeeze().numpy()
    durations = np.log(durations + 1)
    mean_duration = durations.mean()
    std_duration = durations.std()
    mean_pitchs.append(mean_pitch)
    std_pitchs.append(std_pitch)
    mean_energys.append(mean_energy)
    std_energys.append(std_energy)
    mean_durations.append(mean_duration)
    std_durations.append(std_duration)
    mean_dvecs.append(dvec.mean())
    std_dvecs.append(dvec.std())

mean_pitch = [float(np.mean(mean_pitchs)), float(np.std(mean_pitchs))]
std_pitch = [float(np.mean(std_pitchs)), float(np.std(std_pitchs))]
mean_energy = [float(np.mean(mean_energys)), float(np.std(mean_energys))]
std_energy = [float(np.mean(std_energys)), float(np.std(std_energys))]
mean_duration = [float(np.mean(mean_durations)), float(np.std(mean_durations))]
std_duration = [float(np.mean(std_durations)), float(np.std(std_durations))]
mean_dvec = [float(np.mean(mean_dvecs)), float(np.std(mean_dvecs))]
std_dvec = [float(np.mean(std_dvecs)), float(np.std(std_dvecs))]

# save the stats
stats = {
    "mean_pitch": mean_pitch,
    "std_pitch": std_pitch,
    "mean_energy": mean_energy,
    "std_energy": std_energy,
    "mean_duration": mean_duration,
    "std_duration": std_duration,
    "mean_dvec": mean_dvec,
    "std_dvec": std_dvec,
}

with open("data/stats.json", "w") as f:
    json.dump(stats, f)

for item in tqdm(dataloader):
    plt.figure(figsize=(20, 10))
    plt.subplot(4, 1, 1)
    plt.title("Mel spectrogram")
    plt.imshow(item["mel"].squeeze().numpy().T, aspect="auto", origin="lower")
    result = vocex.model(item["mel"], inference=True)
    pitch = result["measures"]["pitch"]
    energy = result["measures"]["energy"]
    va = result["measures"]["voice_activity_binary"]
    mean_pitch = pitch.mean()
    std_pitch = pitch.std()
    pitch = (pitch - pitch.mean()) / pitch.std()
    mean_energy = energy.mean()
    std_energy = energy.std()
    energy = (energy - energy.mean()) / energy.std()
    va = (va - 0.5) * 2
    durations = item["phone_durations"].squeeze().numpy()
    plt.subplot(4, 1, 2)
    sns.lineplot(
        x=np.arange(len(pitch[0])),
        y=pitch[0],
        color="red",
        label="Pitch",
    )
    sns.lineplot(
        x=np.arange(len(energy[0])),
        y=energy[0],
        color="blue",
        label="Energy",
    )
    sns.lineplot(
        x=np.arange(len(va[0])),
        y=va[0],
        color="green",
        label="Voice activity",
    )
    plt.legend()
    dur = [d for d in durations if d > 0]
    current_idx = 0
    vpw = 5 # values per window
    new_repr = np.zeros((len(dur), vpw*3 + 1))
    for i, d in enumerate(dur):
        new_repr[i, 0] = d
        # get values in duration window
        pitch_win = pitch[0, current_idx:current_idx+d]
        energy_win = energy[0, current_idx:current_idx+d]
        va_win = va[0, current_idx:current_idx+d]
        current_idx += d
        # resample to vpw values
        pitch_win = resample(pitch_win, vpw)
        energy_win = resample(energy_win, vpw)
        va_win = resample(va_win, vpw)
        new_repr[i, 1:vpw+1] = pitch_win
        new_repr[i, vpw+1:2*vpw+1] = energy_win
        new_repr[i, 2*vpw+1:3*vpw+1] = va_win
    new_repr[:, 0] = np.log(new_repr[:, 0] + 1)
    mean_dur = new_repr[:, 0].mean()
    std_dur = new_repr[:, 0].std()
    new_repr[:, 0] = (new_repr[:, 0] - mean_dur) / std_dur
    plt.subplot(4, 1, 3)
    # heatmap with log scale
    phones = [idx2phone[int(p)] for i, p in enumerate(item["phones"][0]) if item["phone_durations"][0][i] > 0]
    for p_i, p in enumerate(phones):
        if "[" in p:
            # make empty symbol for phones with []
            phones[p_i] = ""
    sns.heatmap(new_repr.T, cmap="viridis")
    # set xticks while making sure they are in the middle of the phone
    plt.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=True)
    plt.xticks(np.arange(len(phones))+0.5, np.arange(len(phones)), rotation=0)
    plt.yticks([0.5]+list(np.array([1,2,3])*(vpw)-vpw/2+1), ["Duration", "Pitch", "Energy", "Voice activity"], rotation=0)
    plt.twiny()
    plt.xticks(np.arange(len(phones))+0.5, phones, rotation=0)
    plt.xlim(0, len(phones))
    # allow some space between this plot and the next one
    plt.subplots_adjust(hspace=0.5)
    # reconstruct pitch, energy and va from new_repr
    r_pitch = np.zeros(len(pitch[0]))
    r_energy = np.zeros(len(energy[0]))
    r_va = np.zeros(len(va[0]))
    current_idx = 0
    for i, d in enumerate(dur):
        # get values in duration window
        pitch_win = new_repr[i, 1:vpw+1]
        energy_win = new_repr[i, vpw+1:2*vpw+1]
        va_win = new_repr[i, 2*vpw+1:3*vpw+1]
        # resample to d values
        pitch_win = resample(pitch_win, d)
        energy_win = resample(energy_win, d)
        va_win = resample(va_win, d)
        r_pitch[current_idx:current_idx+d] = pitch_win
        r_energy[current_idx:current_idx+d] = energy_win
        r_va[current_idx:current_idx+d] = va_win
        current_idx += d
    plt.subplot(4, 1, 4)
    sns.lineplot(
        x=np.arange(len(r_pitch)),
        y=r_pitch,
        color="red",
        label="Pitch",
    )
    sns.lineplot(
        x=np.arange(len(r_energy)),
        y=r_energy,
        color="blue",
        label="Energy",
    )
    sns.lineplot(
        x=np.arange(len(r_va)),
        y=r_va,
        color="green",
        label="Voice activity",
    )
    plt.legend()
    plt.savefig("test.png")
    print("Mean pitch:", mean_pitch)
    print("Std pitch:", std_pitch)
    print("Mean energy:", mean_energy)
    print("Std energy:", std_energy)
    print("Mean duration:", mean_dur)
    print("Std duration:", std_dur)
    break