File size: 9,730 Bytes
f4d4ab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import os
import random
import json
from pathlib import Path

import tgt
import librosa
import numpy as np
import pyworld as pw
from scipy.interpolate import interp1d
from sklearn.preprocessing import StandardScaler
from tqdm import tqdm

import audio as Audio


class Preprocessor:
    def __init__(self, config):
        self.config = config
        self.in_dir = Path(config["path"]["raw_path"])
        self.out_dir = Path(config["path"]["preprocessed_path"])
        self.val_size = config["preprocessing"]["val_size"]
        self.sampling_rate = config["preprocessing"]["audio"]["sampling_rate"]
        self.hop_length = config["preprocessing"]["stft"]["hop_length"]

        assert config["preprocessing"]["pitch"]["feature"] in ["phoneme_level", "frame_level"]
        assert config["preprocessing"]["energy"]["feature"] in ["phoneme_level", "frame_level"]
        
        self.pitch_phoneme_averaging = config["preprocessing"]["pitch"]["feature"] == "phoneme_level"
        self.energy_phoneme_averaging = config["preprocessing"]["energy"]["feature"] == "phoneme_level"
        self.pitch_normalization = config["preprocessing"]["pitch"]["normalization"]
        self.energy_normalization = config["preprocessing"]["energy"]["normalization"]

        self.STFT = Audio.stft.TacotronSTFT(
            config["preprocessing"]["stft"]["filter_length"],
            config["preprocessing"]["stft"]["hop_length"],
            config["preprocessing"]["stft"]["win_length"],
            config["preprocessing"]["mel"]["n_mel_channels"],
            config["preprocessing"]["audio"]["sampling_rate"],
            config["preprocessing"]["mel"]["mel_fmin"],
            config["preprocessing"]["mel"]["mel_fmax"],
        )

    def build_from_path(self):
        (self.out_dir / "mel").mkdir(parents=True, exist_ok=True)
        (self.out_dir / "pitch").mkdir(parents=True, exist_ok=True)
        (self.out_dir / "energy").mkdir(parents=True, exist_ok=True)
        (self.out_dir / "duration").mkdir(parents=True, exist_ok=True)

        print("Processing Data ...")
        out = list()
        n_frames = 0
        pitch_scaler = StandardScaler()
        energy_scaler = StandardScaler()

        speakers = {}
        search_dirs = [p for p in self.in_dir.iterdir() if p.is_dir()]
        
        for i, speaker_dir in enumerate(tqdm(search_dirs)):
            speaker = speaker_dir.name
            speakers[speaker] = i

            for wav_path in speaker_dir.iterdir():
                if wav_path.suffix != ".wav":
                    continue

                basename = wav_path.stem
                tg_path = self.out_dir / "TextGrid" / speaker / f"{basename}.TextGrid"
                
                if tg_path.exists():
                    ret = self.process_utterance(speaker, basename)
                    if ret is None:
                        continue
                    
                    info, pitch, energy, n = ret
                    out.append(info)

                    if len(pitch) > 0:
                        pitch_scaler.partial_fit(pitch.reshape((-1, 1)))
                    if len(energy) > 0:
                        energy_scaler.partial_fit(energy.reshape((-1, 1)))

                    n_frames += n

        print("Computing statistic quantities ...")
        if hasattr(pitch_scaler, "mean_") and pitch_scaler.mean_ is not None and n_frames > 0:
            pitch_mean = pitch_scaler.mean_[0] if self.pitch_normalization else 0
            pitch_std = pitch_scaler.scale_[0] if self.pitch_normalization else 1
            energy_mean = energy_scaler.mean_[0] if self.energy_normalization else 0
            energy_std = energy_scaler.scale_[0] if self.energy_normalization else 1

            pitch_min, pitch_max = self.normalize(self.out_dir / "pitch", pitch_mean, pitch_std)
            energy_min, energy_max = self.normalize(self.out_dir / "energy", energy_mean, energy_std)
        else:
            print("\n[!] Warning: No audio samples matched with a corresponding TextGrid file.")
            pitch_min, pitch_max, pitch_mean, pitch_std = 0, 1, 0, 1
            energy_min, energy_max, energy_mean, energy_std = 0, 1, 0, 1

        with open(self.out_dir / "speakers.json", "w") as f:
            f.write(json.dumps(speakers))

        with open(self.out_dir / "stats.json", "w") as f:
            stats = {
                "pitch": [float(pitch_min), float(pitch_max), float(pitch_mean), float(pitch_std)],
                "energy": [float(energy_min), float(energy_max), float(energy_mean), float(energy_std)],
            }
            f.write(json.dumps(stats))

        print(f"Total time: {n_frames * self.hop_length / self.sampling_rate / 3600:.2f} hours")

        random.shuffle(out)
        out = [r for r in out if r is not None]

        with open(self.out_dir / "train.txt", "w", encoding="utf-8") as f:
            for m in out[self.val_size :]:
                f.write(f"{m}\n")
        with open(self.out_dir / "val.txt", "w", encoding="utf-8") as f:
            for m in out[: self.val_size]:
                f.write(f"{m}\n")

        return out

    def process_utterance(self, speaker, basename):
        wav_path = self.in_dir / speaker / f"{basename}.wav"
        text_path = self.in_dir / speaker / f"{basename}.lab"
        tg_path = self.out_dir / "TextGrid" / speaker / f"{basename}.TextGrid"

        textgrid = tgt.io.read_textgrid(str(tg_path))
        phone, duration, start, end = self.get_alignment(textgrid.get_tier_by_name("phones"))
        text = "{" + " ".join(phone) + "}"
        if start >= end:
            return None

        wav, _ = librosa.load(str(wav_path))
        wav = wav[int(self.sampling_rate * start) : int(self.sampling_rate * end)].astype(np.float32)

        with open(text_path, "r", encoding="utf-8") as f:
            raw_text = f.readline().strip("\n")

        pitch, t = pw.dio(
            wav.astype(np.float64),
            self.sampling_rate,
            frame_period=self.hop_length / self.sampling_rate * 1000,
        )
        pitch = pw.stonemask(wav.astype(np.float64), pitch, t, self.sampling_rate)
        pitch = pitch[: sum(duration)]
        if np.sum(pitch != 0) <= 1:
            return None

        mel_spectrogram, energy = Audio.tools.get_mel_from_wav(wav, self.STFT)
        mel_spectrogram = mel_spectrogram[:, : sum(duration)]
        energy = energy[: sum(duration)]

        if self.pitch_phoneme_averaging:
            nonzero_ids = np.where(pitch != 0)[0]
            interp_fn = interp1d(
                nonzero_ids,
                pitch[nonzero_ids],
                fill_value=(pitch[nonzero_ids[0]], pitch[nonzero_ids[-1]]),
                bounds_error=False,
            )
            pitch = interp_fn(np.arange(0, len(pitch)))

            pos = 0
            for i, d in enumerate(duration):
                pitch[i] = np.mean(pitch[pos : pos + d]) if d > 0 else 0
                pos += d
            pitch = pitch[: len(duration)]

        if self.energy_phoneme_averaging:
            pos = 0
            for i, d in enumerate(duration):
                energy[i] = np.mean(energy[pos : pos + d]) if d > 0 else 0
                pos += d
            energy = energy[: len(duration)]

        np.save(self.out_dir / "duration" / f"{speaker}-duration-{basename}.npy", duration)
        np.save(self.out_dir / "pitch" / f"{speaker}-pitch-{basename}.npy", pitch)
        np.save(self.out_dir / "energy" / f"{speaker}-energy-{basename}.npy", energy)
        np.save(self.out_dir / "mel" / f"{speaker}-mel-{basename}.npy", mel_spectrogram.T)

        return (
            "|".join([basename, speaker, text, raw_text]),
            self.remove_outlier(pitch),
            self.remove_outlier(energy),
            mel_spectrogram.shape[1],
        )

    def get_alignment(self, tier):
        sil_phones = ["sil", "sp", "spn"]
        phones, durations = [], []
        start_time, end_time, end_idx = 0, 0, 0
        
        for t in tier._objects:
            s, e, p = t.start_time, t.end_time, t.text
            if phones == []:
                if p in sil_phones:
                    continue
                else:
                    start_time = s

            if p not in sil_phones:
                phones.append(p)
                end_time = e
                end_idx = len(phones)
            else:
                phones.append(p)

            durations.append(
                int(np.round(e * self.sampling_rate / self.hop_length) - np.round(s * self.sampling_rate / self.hop_length))
            )

        return phones[:end_idx], durations[:end_idx], start_time, end_time

    def remove_outlier[T](self, values: T) -> T:
        values = np.array(values)
        p25 = np.percentile(values, 25)
        p75 = np.percentile(values, 75)
        lower = p25 - 1.5 * (p75 - p25)
        upper = p75 + 1.5 * (p75 - p25)
        normal_indices = np.logical_and(values > lower, values < upper)
        return values[normal_indices]

    def normalize(self, in_dir: Path, mean: float, std: float):
        max_value = np.finfo(np.float64).min
        min_value = np.finfo(np.float64).max
        
        for file_path in in_dir.iterdir():
            if file_path.is_file():
                values = (np.load(file_path) - mean) / std
                np.save(file_path, values)
                max_value = max(max_value, max(values))
                min_value = min(min_value, min(values))

        return min_value, max_value