collator.py 14.8 KB
Newer Older
H
Hui Zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
H
Haoxin Ma 已提交
14 15 16
import io
from typing import Optional

H
Hui Zhang 已提交
17
import numpy as np
H
Haoxin Ma 已提交
18
from yacs.config import CfgNode
H
Hui Zhang 已提交
19

H
Haoxin Ma 已提交
20 21 22 23
from deepspeech.frontend.augmentor.augmentation import AugmentationPipeline
from deepspeech.frontend.featurizer.speech_featurizer import SpeechFeaturizer
from deepspeech.frontend.normalizer import FeatureNormalizer
from deepspeech.frontend.speech import SpeechSegment
H
Haoxin Ma 已提交
24
from deepspeech.frontend.utility import IGNORE_ID
25 26
from deepspeech.frontend.utility import TarLocalData
from deepspeech.io.reader import LoadInputsAndTargets
H
Hui Zhang 已提交
27
from deepspeech.io.utility import pad_list
H
Haoxin Ma 已提交
28
from deepspeech.utils.log import Log
H
fix bug  
Haoxin Ma 已提交
29

30
__all__ = ["SpeechCollator", "TripletSpeechCollator"]
H
Hui Zhang 已提交
31

32
logger = Log(__name__).getlog()
H
Hui Zhang 已提交
33

H
Haoxin Ma 已提交
34

35
class SpeechCollatorBase():
H
Haoxin Ma 已提交
36 37 38 39 40 41 42 43
    def __init__(
            self,
            aug_file,
            mean_std_filepath,
            vocab_filepath,
            spm_model_prefix,
            random_seed=0,
            unit_type="char",
44
            spectrum_type='linear',  # 'linear', 'mfcc', 'fbank'
H
Haoxin Ma 已提交
45 46 47 48 49 50 51 52 53 54 55
            feat_dim=0,  # 'mfcc', 'fbank'
            delta_delta=False,  # 'mfcc', 'fbank'
            stride_ms=10.0,  # ms
            window_ms=20.0,  # ms
            n_fft=None,  # fft points
            max_freq=None,  # None for samplerate/2
            target_sample_rate=16000,  # target sample rate
            use_dB_normalization=True,
            target_dB=-20,
            dither=1.0,
            keep_transcription_text=True):
H
Haoxin Ma 已提交
56
        """SpeechCollator Collator
H
Haoxin Ma 已提交
57

H
Haoxin Ma 已提交
58 59 60 61 62 63 64 65 66 67 68
        Args:
            unit_type(str): token unit type, e.g. char, word, spm
            vocab_filepath (str): vocab file path.
            mean_std_filepath (str): mean and std file path, which suffix is *.npy
            spm_model_prefix (str): spm model prefix, need if `unit_type` is spm.
            augmentation_config (str, optional): augmentation json str. Defaults to '{}'.
            stride_ms (float, optional): stride size in ms. Defaults to 10.0.
            window_ms (float, optional): window size in ms. Defaults to 20.0.
            n_fft (int, optional): fft points for rfft. Defaults to None.
            max_freq (int, optional): max cut freq. Defaults to None.
            target_sample_rate (int, optional): target sample rate which used for training. Defaults to 16000.
69
            spectrum_type (str, optional): 'linear', 'mfcc' or 'fbank'. Defaults to 'linear'.
H
Haoxin Ma 已提交
70 71 72 73 74 75 76
            feat_dim (int, optional): audio feature dim, using by 'mfcc' or 'fbank'. Defaults to None.
            delta_delta (bool, optional): audio feature with delta-delta, using by 'fbank' or 'mfcc'. Defaults to False.
            use_dB_normalization (bool, optional): do dB normalization. Defaults to True.
            target_dB (int, optional): target dB. Defaults to -20.
            random_seed (int, optional): for random generator. Defaults to 0.
            keep_transcription_text (bool, optional): True, when not in training mode, will not do tokenizer; Defaults to False.
            if ``keep_transcription_text`` is False, text is token ids else is raw string.
H
Hui Zhang 已提交
77 78

        Do augmentations
H
Haoxin Ma 已提交
79 80
        Padding audio features with zeros to make them have the same shape (or
        a user-defined shape) within one batch.
H
Haoxin Ma 已提交
81
        """
82 83 84 85 86 87
        self.keep_transcription_text = keep_transcription_text
        self.stride_ms = stride_ms
        self.window_ms = window_ms
        self.feat_dim = feat_dim

        self.loader = LoadInputsAndTargets()
H
Haoxin Ma 已提交
88

89
        # only for tar filetype
H
fix bug  
Haoxin Ma 已提交
90
        self._local_data = TarLocalData(tar2info={}, tar2object={})
91 92

        self.augmentation = AugmentationPipeline(
H
Haoxin Ma 已提交
93 94
            augmentation_config=aug_file.read(), random_seed=random_seed)

H
Haoxin Ma 已提交
95
        self._normalizer = FeatureNormalizer(
H
Haoxin Ma 已提交
96
            mean_std_filepath) if mean_std_filepath else None
H
Haoxin Ma 已提交
97 98

        self._speech_featurizer = SpeechFeaturizer(
H
Haoxin Ma 已提交
99 100 101
            unit_type=unit_type,
            vocab_filepath=vocab_filepath,
            spm_model_prefix=spm_model_prefix,
102
            spectrum_type=spectrum_type,
H
Haoxin Ma 已提交
103 104 105 106 107 108 109 110 111 112
            feat_dim=feat_dim,
            delta_delta=delta_delta,
            stride_ms=stride_ms,
            window_ms=window_ms,
            n_fft=n_fft,
            max_freq=max_freq,
            target_sample_rate=target_sample_rate,
            use_dB_normalization=use_dB_normalization,
            target_dB=target_dB,
            dither=dither)
H
Haoxin Ma 已提交
113

114 115 116 117 118
        self.feature_size = self._speech_featurizer.audio_feature.feature_size
        self.text_feature = self._speech_featurizer.text_feature
        self.vocab_dict = self.text_feature.vocab_dict
        self.vocab_list = self.text_feature.vocab_list
        self.vocab_size = self.text_feature.vocab_size
H
Haoxin Ma 已提交
119 120 121 122 123 124 125 126 127 128 129 130

    def process_utterance(self, audio_file, transcript):
        """Load, augment, featurize and normalize for speech data.

        :param audio_file: Filepath or file object of audio file.
        :type audio_file: str | file
        :param transcript: Transcription text.
        :type transcript: str
        :return: Tuple of audio feature tensor and data of transcription part,
                 where transcription part could be token ids or text.
        :rtype: tuple of (2darray, list)
        """
131 132 133 134 135 136 137 138 139 140 141 142
        filetype = self.loader.file_type(audio_file)

        if filetype != 'sound':
            spectrum = self.loader._get_from_loader(audio_file, filetype)
            feat_dim = spectrum.shape[1]
            assert feat_dim == self.feat_dim, f"expect feat dim {self.feat_dim}, but got {feat_dim}"

            if self.keep_transcription_text:
                transcript_part = transcript
            else:
                text_ids = self.text_feature.featurize(transcript)
                transcript_part = text_ids
H
Haoxin Ma 已提交
143
        else:
144 145 146 147 148
            # read audio
            speech_segment = SpeechSegment.from_file(
                audio_file, transcript, infos=self._local_data)
            # audio augment
            self.augmentation.transform_audio(speech_segment)
H
Haoxin Ma 已提交
149

150 151 152
            # extract speech feature
            spectrum, transcript_part = self._speech_featurizer.featurize(
                speech_segment, self.keep_transcription_text)
H
Haoxin Ma 已提交
153

154 155 156
            # CMVN spectrum
            if self._normalizer:
                spectrum = self._normalizer.apply(spectrum)
H
Haoxin Ma 已提交
157

158 159 160
        # spectrum augment
        spectrum = self.augmentation.transform_feature(spectrum)
        return spectrum, transcript_part
H
Haoxin Ma 已提交
161

H
Hui Zhang 已提交
162
    def __call__(self, batch):
163 164 165 166
        """batch examples

        Args:
            batch ([List]): batch is (audio, text)
H
Hui Zhang 已提交
167
                audio (np.ndarray) shape (T, D)
168 169 170 171 172 173 174 175 176 177
                text (List[int] or str): shape (U,)

        Returns:
            tuple(audio, text, audio_lens, text_lens): batched data.
                audio : (B, Tmax, D)
                audio_lens: (B)
                text : (B, Umax)
                text_lens: (B)
        """
        audios = []
H
Hui Zhang 已提交
178
        audio_lens = []
179 180
        texts = []
        text_lens = []
H
Haoxin Ma 已提交
181
        utts = []
H
Haoxin Ma 已提交
182
        for utt, audio, text in batch:
H
Haoxin Ma 已提交
183
            audio, text = self.process_utterance(audio, text)
H
Haoxin Ma 已提交
184 185
            #utt
            utts.append(utt)
H
Hui Zhang 已提交
186
            # audio
H
Haoxin Ma 已提交
187
            audios.append(audio)  # [T, D]
H
Hui Zhang 已提交
188
            audio_lens.append(audio.shape[0])
H
Hui Zhang 已提交
189
            # text
190
            # for training, text is token ids, else text is string, convert to unicode ord
191
            tokens = []
192
            if self.keep_transcription_text:
193 194
                assert isinstance(text, str), (type(text), text)
                tokens = [ord(t) for t in text]
H
Hui Zhang 已提交
195
            else:
196
                tokens = text  # token ids
197
            tokens = np.array(tokens, dtype=np.int64)
198 199
            texts.append(tokens)
            text_lens.append(tokens.shape[0])
H
Hui Zhang 已提交
200

H
Hui Zhang 已提交
201 202 203 204 205 206
        #[B, T, D]
        xs_pad = pad_list(audios, 0.0).astype(np.float32)
        ilens = np.array(audio_lens).astype(np.int64)
        ys_pad = pad_list(texts, IGNORE_ID).astype(np.int64)
        olens = np.array(text_lens).astype(np.int64)
        return utts, xs_pad, ilens, ys_pad, olens
H
Haoxin Ma 已提交
207

H
Haoxin Ma 已提交
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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
class SpeechCollator(SpeechCollatorBase):
    @classmethod
    def params(cls, config: Optional[CfgNode]=None) -> CfgNode:
        default = CfgNode(
            dict(
                augmentation_config="",
                random_seed=0,
                mean_std_filepath="",
                unit_type="char",
                vocab_filepath="",
                spm_model_prefix="",
                spectrum_type='linear',  # 'linear', 'mfcc', 'fbank'
                feat_dim=0,  # 'mfcc', 'fbank'
                delta_delta=False,  # 'mfcc', 'fbank'
                stride_ms=10.0,  # ms
                window_ms=20.0,  # ms
                n_fft=None,  # fft points
                max_freq=None,  # None for samplerate/2
                target_sample_rate=16000,  # target sample rate
                use_dB_normalization=True,
                target_dB=-20,
                dither=1.0,  # feature dither
                keep_transcription_text=False))

        if config is not None:
            config.merge_from_other_cfg(default)
        return default

    @classmethod
    def from_config(cls, config):
        """Build a SpeechCollator object from a config.

        Args:
            config (yacs.config.CfgNode): configs object.

        Returns:
            SpeechCollator: collator object.
        """
        assert 'augmentation_config' in config.collator
        assert 'keep_transcription_text' in config.collator
        assert 'mean_std_filepath' in config.collator
        assert 'vocab_filepath' in config.collator
        assert 'spectrum_type' in config.collator
        assert 'n_fft' in config.collator
        assert config.collator

        if isinstance(config.collator.augmentation_config, (str, bytes)):
            if config.collator.augmentation_config:
                aug_file = io.open(
                    config.collator.augmentation_config,
                    mode='r',
                    encoding='utf8')
            else:
                aug_file = io.StringIO(initial_value='{}', newline='')
        else:
            aug_file = config.collator.augmentation_config
            assert isinstance(aug_file, io.StringIO)

        speech_collator = cls(
            aug_file=aug_file,
            random_seed=0,
            mean_std_filepath=config.collator.mean_std_filepath,
            unit_type=config.collator.unit_type,
            vocab_filepath=config.collator.vocab_filepath,
            spm_model_prefix=config.collator.spm_model_prefix,
            spectrum_type=config.collator.spectrum_type,
            feat_dim=config.collator.feat_dim,
            delta_delta=config.collator.delta_delta,
            stride_ms=config.collator.stride_ms,
            window_ms=config.collator.window_ms,
            n_fft=config.collator.n_fft,
            max_freq=config.collator.max_freq,
            target_sample_rate=config.collator.target_sample_rate,
            use_dB_normalization=config.collator.use_dB_normalization,
            target_dB=config.collator.target_dB,
            dither=config.collator.dither,
            keep_transcription_text=config.collator.keep_transcription_text)
        return speech_collator


class TripletSpeechCollator(SpeechCollator):
    def process_utterance(self, audio_file, translation, transcript):
        """Load, augment, featurize and normalize for speech data.
H
Haoxin Ma 已提交
292

293 294 295 296 297 298 299 300 301 302 303 304 305
        :param audio_file: Filepath or file object of audio file.
        :type audio_file: str | file
        :param translation: translation text.
        :type translation: str
        :return: Tuple of audio feature tensor and data of translation part,
                    where translation part could be token ids or text.
        :rtype: tuple of (2darray, list)
        """
        spectrum, translation_part = super().process_utterance(audio_file,
                                                               translation)
        transcript_part = self._speech_featurizer.text_featurize(
            transcript, self.keep_transcription_text)
        return spectrum, translation_part, transcript_part
H
Haoxin Ma 已提交
306

307 308 309 310 311 312 313
    def __call__(self, batch):
        """batch examples

        Args:
            batch ([List]): batch is (audio, text)
                audio (np.ndarray) shape (T, D)
                text (List[int] or str): shape (U,)
H
Haoxin Ma 已提交
314

315 316 317 318 319 320 321 322 323 324 325 326 327
        Returns:
            tuple(audio, text, audio_lens, text_lens): batched data.
                audio : (B, Tmax, D)
                audio_lens: (B)
                text : (B, Umax)
                text_lens: (B)
        """
        audios = []
        audio_lens = []
        translation_text = []
        translation_text_lens = []
        transcription_text = []
        transcription_text_lens = []
H
Haoxin Ma 已提交
328

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        utts = []
        for utt, audio, translation, transcription in batch:
            audio, translation, transcription = self.process_utterance(
                audio, translation, transcription)
            #utt
            utts.append(utt)
            # audio
            audios.append(audio)  # [T, D]
            audio_lens.append(audio.shape[0])
            # text
            # for training, text is token ids
            # else text is string, convert to unicode ord
            tokens = [[], []]
            for idx, text in enumerate([translation, transcription]):
                if self.keep_transcription_text:
                    assert isinstance(text, str), (type(text), text)
                    tokens[idx] = [ord(t) for t in text]
                else:
                    tokens[idx] = text  # token ids
                tokens[idx] = np.array(tokens[idx], dtype=np.int64)

            translation_text.append(tokens[0])
            translation_text_lens.append(tokens[0].shape[0])
            transcription_text.append(tokens[1])
            transcription_text_lens.append(tokens[1].shape[0])

        padded_audios = pad_sequence(
            audios, padding_value=0.0).astype(np.float32)  #[B, T, D]
        audio_lens = np.array(audio_lens).astype(np.int64)
        padded_translation = pad_sequence(
            translation_text, padding_value=IGNORE_ID).astype(np.int64)
        translation_lens = np.array(translation_text_lens).astype(np.int64)
        padded_transcription = pad_sequence(
            transcription_text, padding_value=IGNORE_ID).astype(np.int64)
        transcription_lens = np.array(transcription_text_lens).astype(np.int64)
        return utts, padded_audios, audio_lens, (
            padded_translation, padded_transcription), (translation_lens,
                                                        transcription_lens)