code
stringlengths
17
6.64M
class FluentSpeechCommands(Corpus): '\n Parse the Fluent Speech Command dataset\n\n Args:\n dataset_root: (str) The dataset root of Fluent Speech Command\n ' def __init__(self, dataset_root: str, n_jobs: int=4) -> None: self.dataset_root = Path(dataset_root) self.train = self....
class IEMOCAP(Corpus): '\n Parse the IEMOCAP dataset\n\n Args:\n dataset_root: (str) The dataset root of IEMOCAP\n ' def __init__(self, dataset_root: str, n_jobs: int=4) -> None: self.dataset_root = Path(dataset_root) self.sessions = [self._preprocess_single_session(self.datas...
def read_text(file: Path) -> str: src_file = ('-'.join(str(file).split('-')[:(- 1)]) + '.trans.txt') idx = file.stem.replace('.flac', '') with open(src_file, 'r') as fp: for line in fp: if (idx == line.split(' ')[0]): return line[:(- 1)].split(' ', 1)[1] logging.war...
def check_no_repeat(splits: List[str]) -> bool: count = defaultdict(int) for split in splits: count[split] += 1 repeated = '' for (key, val) in count.items(): if (val > 1): repeated += f' {key} ({val} times)' if (len(repeated) != 0): logging.warning(f'Found repe...
def _parse_spk_to_gender(speaker_file: Path) -> dict: speaker_file = Path(speaker_file) with speaker_file.open() as file: lines = [line.strip() for line in file.readlines()] for line_id in range(len(lines)): line = lines[line_id] if (('SEX' in line) and ('SUBSET' in line) and ('MIN...
class LibriLight(Corpus): def __init__(self, dataset_root: str, n_jobs: int=4, train_split: str='10m-fold0') -> None: self.dataset_root = Path(dataset_root).resolve() self.train_split = train_split if (train_split == '10h'): roots = [(self.dataset_root / '1h'), (self.dataset_r...
def read_text(file: Path) -> str: src_file = ('-'.join(str(file).split('-')[:(- 1)]) + '.trans.txt') idx = file.stem.replace('.flac', '') with open(src_file, 'r') as fp: for line in fp: if (idx == line.split(' ')[0]): return line[:(- 1)].split(' ', 1)[1] logger.warn...
def check_no_repeat(splits: List[str]) -> bool: count = defaultdict(int) for split in splits: count[split] += 1 repeated = '' for (key, val) in count.items(): if (val > 1): repeated += f' {key} ({val} times)' if (len(repeated) != 0): logger.warning(f'Found repea...
def _parse_spk_to_gender(speaker_file: Path) -> dict: speaker_file = Path(speaker_file) with speaker_file.open() as file: lines = [line.strip() for line in file.readlines()] for line_id in range(len(lines)): line = lines[line_id] if (('SEX' in line) and ('SUBSET' in line) and ('MIN...
class LibriSpeech(Corpus): 'LibriSpeech Corpus\n Link: https://www.openslr.org/12\n\n Args:\n dataset_root (str): Path to LibriSpeech corpus directory.\n n_jobs (int, optional): Number of jobs. Defaults to 4.\n train_split (List[str], optional): Training splits. Defaults to ["train-clea...
class Quesst14(): def __init__(self, dataset_root: str): dataset_root = Path(dataset_root) self.doc_paths = self._english_audio_paths(dataset_root, 'language_key_utterances.lst') self.dev_query_paths = self._english_audio_paths(dataset_root, f'language_key_dev.lst') self.eval_quer...
class SNIPS(Corpus): def __init__(self, dataset_root: str, train_speakers: List[str], valid_speakers: List[str], test_speakers: List[str]) -> None: self.dataset_root = Path(dataset_root) self.train_speakers = train_speakers self.valid_speakers = valid_speakers self.test_speakers =...
class SpeechCommandsV1(Corpus): "\n Args:\n dataset_root (str): should contain a 'dev' sub-folder for the training/validation set\n and a 'test' sub-folder for the testing set\n " def __init__(self, gsc1: str, gsc1_test: str, n_jobs: int=4) -> None: train_dataset_root = Path(g...
class VoxCeleb1SID(Corpus): def __init__(self, dataset_root: str, n_jobs: int=4, cache_root: str=CACHE_ROOT) -> None: self.dataset_root = Path(dataset_root).resolve() uid2split = self._get_standard_usage(self.dataset_root, cache_root) self._split2uids = defaultdict(list) for (uid,...
class VoxCeleb1SV(Corpus): def __init__(self, dataset_root: str, download_dir: str, force_download: bool=True) -> None: self.dataset_root = Path(dataset_root).resolve() (train_path, valid_path, test_path, speakerid2label) = self.format_path(self.dataset_root, download_dir, force_download) ...
class Dataset(data.Dataset): def __len__(self) -> int: raise NotImplementedError def __getitem__(self, index: int): raise NotImplementedError def getinfo(self, index: int): raise NotImplementedError
class EncodeCategory(Dataset): def __init__(self, labels: List[str], encoder: CategoryEncoder) -> None: super().__init__() self.labels = labels self.encoder = encoder def __len__(self): return len(self.labels) def __getitem__(self, index: int): label = self.label...
class EncodeCategories(Dataset): def __init__(self, labels: List[List[str]], encoders: CategoryEncoders) -> None: super().__init__() self.labels = labels self.encoders = encoders def __len__(self): return len(self.labels) def __getitem__(self, index: int): labels...
class EncodeMultiLabel(Dataset): def __init__(self, labels: List[List[str]], encoder: CategoryEncoder) -> None: super().__init__() self.labels = labels self.encoder = encoder def __len__(self): return len(self.labels) @staticmethod def label_to_binary_vector(label_id...
class EncodeText(Dataset): def __init__(self, text: List[str], tokenizer: Tokenizer, iob: List[str]=None) -> None: super().__init__() self.text = text self.iob = iob if (iob is not None): assert (len(text) == len(iob)) self.tokenizer = tokenizer def __len_...
def get_info(dataset, names: List[str], cache_dir: str=None, n_jobs: int=6): logger.info(f"Getting info from dataset {dataset.__class__.__qualname__}: {' '.join(names)}") if isinstance(cache_dir, (str, Path)): logger.info(f'Using cached info in {cache_dir}') cache_dir: Path = Path(cache_dir) ...
class CategoryEncoder(): def __init__(self, category: List[str]) -> None: self.category = list(sorted(set(category))) def __len__(self) -> int: return len(self.category) def encode(self, label: str) -> int: return self.category.index(label) def decode(self, index: int) -> s...
class CategoryEncoders(): def __init__(self, categories: List[List[str]]) -> None: self.categories = [CategoryEncoder(c) for c in categories] def __len__(self) -> int: return sum([len(c) for c in self.categories]) def __iter__(self): for category in self.categories: ...
def parse_lexicon(line: str) -> Tuple[(str, List[str])]: line.replace('\t', ' ') (word, *phonemes) = line.split() return (word, phonemes)
def read_lexicon_files(file_list: List[str]) -> Dict[(str, List[str])]: w2p_dict = defaultdict(list) for file in file_list: with open(file, 'r') as fp: lines = [line.strip() for line in fp] for line in lines: (word, phonemes) = parse_lexicon(line) ...
class G2P(): 'Grapheme-to-phoneme\n\n Args:\n file_list (List[str], optional): List of lexicon files. Defaults to None.\n allow_unk (bool): If false, raise Error when a word can not be recognized by this basic G2P\n ' def __init__(self, file_list: List[str]=None, allow_unk: bool=False): ...
class Tokenizer(): def __init__(self): super().__init__() @abc.abstractmethod def encode(self, text: str, iob: str=None) -> List[int]: raise NotImplementedError @abc.abstractmethod def decode(self, idxs: List[int], ignore_repeat: bool=False) -> str: raise NotImplementedE...
class CharacterTokenizer(Tokenizer): 'Character tokenizer.' def __init__(self, vocab_list: List[str]=None): super().__init__() if (vocab_list is None): vocab_list = CHARACTER_VOCAB for tok in ['<pad>', '<eos>', '<unk>']: assert (tok not in vocab_list) s...
class CharacterSlotTokenizer(Tokenizer): 'Character tokenizer with slots.' def __init__(self, vocab_list: List[str], slots: List[str]): super().__init__() for tok in ['<pad>', '<eos>', '<unk>']: assert (tok not in vocab_list) self._vocab_list = (['<pad>', '<eos>', '<unk>']...
class SubwordTokenizer(Tokenizer): 'Subword tokenizer using sentencepiece.' def __init__(self, spm): super().__init__() if ((spm.pad_id() != 0) or (spm.eos_id() != 1) or (spm.unk_id() != 2)): raise ValueError('Please train sentencepiece model with following argument:\n--pad_id=0 -...
class SubwordSlotTokenizer(Tokenizer): 'Subword tokenizer with slots.' def __init__(self, spm, slots): super().__init__() if ((spm.pad_id() != 0) or (spm.eos_id() != 1) or (spm.unk_id() != 2)): raise ValueError('Please train sentencepiece model with following argument:\n--pad_id=0...
class WordTokenizer(CharacterTokenizer): 'Word tokenizer.' def encode(self, s: str) -> List[int]: s = s.strip('\r\n ') words = s.split(' ') return ([self.vocab_to_idx(v) for v in words] + [self.eos_idx]) def decode(self, idxs: List[int], ignore_repeat: bool=False) -> str: ...
class PhonemeTokenizer(WordTokenizer): 'Phoneme tokenizer.' @property def token_type(self) -> str: return 'phoneme'
class BertTokenizer(Tokenizer): 'Bert Tokenizer.\n\n https://github.com/huggingface/pytorch-transformers/blob/master/pytorch_transformers/tokenization_bert.py\n ' def __init__(self, tokenizer): super().__init__() self._tokenizer = tokenizer self._tokenizer.pad_token = '<pad>' ...
def load_tokenizer(mode: str, vocab_file: str=None, vocab_list: List[str]=None, slots_file: str=None) -> Tokenizer: 'Load a text tokenizer.\n\n Args:\n mode (str): Mode ("character", "character-slot", "subword", "subword-slot", "word", "bert-...")\n vocab_file (str, optional): Path to vocabularie...
def default_phoneme_tokenizer() -> PhonemeTokenizer: 'Returns a default LibriSpeech phoneme tokenizer.\n\n Returns:\n PhonemeTokenizer: Vocabs include 71 phonemes\n ' return PhonemeTokenizer.load_from_file(vocab_list=PHONEME_VOCAB)
def generate_basic_vocab(mode: str, text_list: List[str], vocab_size: int=(- 1), coverage: float=1.0, sort_vocab: bool=True) -> List[str]: 'Generates basic vocabularies, including character and word-based vocabularies.\n\n Args:\n mode (str): Vocabulary type (character or word).\n text_list (List...
def generate_subword_vocab(text_list: List[str]=None, text_file: str=None, output_file: str=None, vocab_size: int=1000, character_coverage: float=1.0) -> str: 'Generates subword vocabularies based on `sentencepiece`.\n\n Args:\n text_list (List[str], optional): List of text data. Defaults to None.\n ...
def generate_vocab(mode: str, text_list: List[str]=None, text_file: str=None, read_lines: int=10000000, **vocab_args) -> Union[(List[str], str)]: 'Generates vocabularies given text data.\n\n Args:\n mode (str): Vocabulary type\n text_list (List[str], optional): List of text data. Defaults to None...
class BalancedWeightedSampler(): '\n This batch sampler is always randomized, hence cannot be used for testing\n ' def __init__(self, labels: List[str], batch_size: int, duplicate: int=1, seed: int=12345678) -> None: self.epoch = 0 self.seed = seed self.batch_size = batch_size ...
class DistributedBatchSamplerWrapper(): def __init__(self, batch_sampler: BatchSampler, num_replicas: Optional[int]=None, rank: Optional[int]=None, allow_duplicates: bool=False, allow_uneven: bool=False) -> None: if (num_replicas is None): if (not dist.is_available()): raise R...
class FixedBatchSizeBatchSampler(): '\n The reduced timestamps for a batch should not exceed the max_timestamp.\n If shuffled, each indices are first shuffled before aggregated into batches\n\n Args:\n data_source: __len__ is implemented\n ' def __init__(self, data_source, batch_size: int,...
class GroupSameItemSampler(): def __init__(self, items: List[str]) -> None: self.indices = defaultdict(list) for (idx, item) in enumerate(items): self.indices[item].append(idx) self.epoch = 0 def set_epoch(self, epoch: int): self.epoch = epoch def __iter__(se...
class MaxTimestampBatchSampler(): '\n The reduced timestamps for a batch should not exceed the max_timestamp.\n If shuffled, each indices are first shuffled before aggregated into batches\n ' def __init__(self, lengths: List[int], max_length: int, shuffle: bool=False, seed: int=12345678, reduce_func...
class SortedSliceSampler(): '\n This sampler should only be used for training hence is always in random shuffle mode\n\n Args:\n lengths (List[int])\n batch_size (int): the default batch size\n max_length (int): if a batch contains at least on utt longer than max_length, half the batch\...
class SortedBucketingSampler(): '\n Args:\n lengths (List[int])\n batch_size (int): the default batch size\n max_length (int): if a batch contains at least on utt longer than max_length, half the batch\n get_length_func (callable): get the length of each item in the dataset, if None...
class AugmentedDynamicItemDataset(DynamicItemDataset): def __init__(self, data, dynamic_items=[], output_keys=[], tools: dict={}): super().__init__(data, dynamic_items, output_keys) assert isinstance(data, OrderedDict) self._tools = {} for (name, item) in tools.items(): ...
class DataPipe(): def __call__(self, dataset: Union[(dict, AugmentedDynamicItemDataset)], tools: dict=None) -> Any: if isinstance(dataset, dict): dataset = AugmentedDynamicItemDataset(dataset) if (tools is not None): dataset.add_tools(tools) return self.forward(dat...
class SequentialDataPipe(DataPipe): def __init__(self, *pipes: List[DataPipe]) -> None: self._pipes = pipes def forward(self, dataset: AugmentedDynamicItemDataset) -> AugmentedDynamicItemDataset: for pipe in self._pipes: dataset = pipe(dataset) return dataset
def default_collate_fn(samples, padding_value: int=0): '\n Each item in **DynamicItemDataset** is a dict\n This function pad (or transform into numpy list) a batch of dict\n\n Args:\n samples (List[dict]): Suppose each Container is in\n\n .. code-block:: yaml\n\n wav: a s...
def _count_frames(data_len, size, step): return int((((data_len - size) + step) / step))
def _gen_frame_indices(data_length, size=2000, step=2000, use_last_samples=True): i = (- 1) for i in range(_count_frames(data_length, size, step)): (yield ((i * step), ((i * step) + size))) if (use_last_samples and (((i * step) + size) < data_length)): if ((data_length - ((i + 1) * step)) ...
@dataclass class UnfoldChunkByFrame(DataPipe): "\n Given a dataset with items containing `start_sec_name` and `end_sec_name`.\n For each item, produce `((end_sec_name - start_sec_name) * sample_rate / feat_frame_shift) / chunk_frames`\n items with the smaller durations between `min_chunk_frames` and `max...
@dataclass class UnfoldChunkBySec(DataPipe): use_last_samples: bool = True min_chunk_secs: float = 2.5 max_chunk_secs: float = 2.5 step_secs: int = 2.5 start_sec_name: str = 'start_sec' end_sec_name: str = 'end_sec' def forward(self, dataset: AugmentedDynamicItemDataset) -> AugmentedDynam...
class SetOutputKeys(DataPipe): def __init__(self, output_keys: dict=None) -> None: super().__init__() self.output_keys = output_keys def forward(self, dataset: AugmentedDynamicItemDataset): dataset.update_output_keys(self.output_keys) return dataset
@dataclass class LoadAudio(DataPipe): audio_sample_rate: int = 16000 audio_channel_reduction: str = 'first' sox_effects: list = None wav_path_name: str = 'wav_path' wav_name: str = 'wav' start_sec_name: str = 'start_sec' end_sec_name: str = 'end_sec' def load_audio(self, wav_path, sta...
@dataclass class EncodeCategory(DataPipe): train_category_encoder: bool = False label_name: str = 'label' category_encoder_name: str = 'category' encoded_target_name: str = 'class_id' def prepare_category(self, labels): return CategoryEncoder(sorted(list(set(labels)))) def encode_lab...
@dataclass class EncodeMultipleCategory(EncodeCategory): train_category_encoder: bool = False label_name: str = 'labels' category_encoder_name: str = 'categories' encoded_target_name: str = 'class_ids' def encode_label(self, categories, labels): return torch.LongTensor([category.encode(la...
@dataclass class EncodeMultiLabel(DataPipe): label_name: str = 'labels' category_encoder_name: str = 'category' encoded_target_name: str = 'binary_labels' @staticmethod def label_to_binary_vector(label: List, num_labels: int) -> torch.Tensor: if (len(label) == 0): binary_label...
@dataclass class GenerateTokenizer(DataPipe): generate: bool = True tokenizer_name: str = 'tokenizer' text_name: str = 'transcription' vocab_type: str = 'character' text_file: str = None vocab_file: str = None slots_file: str = None vocab_args: dict = None def prepare_tokenizer(se...
@dataclass class EncodeText(DataPipe): text_name: str = 'transcription' output_text_name: str = 'tokenized_text' tokenizer_name: str = 'tokenizer' def encode_text(self, tokenizer: Tokenizer, text: str) -> torch.LongTensor: return torch.LongTensor(tokenizer.encode(text)) def forward(self,...
@dataclass class Phonemize(DataPipe): text_name: str = 'transcription' phonemized_text_name: str = 'phonemized_text' output_text_name: str = 'tokenized_text' g2p_name: str = 'g2p' tokenizer_name: str = 'tokenizer' def grapheme2phoneme(self, g2p: G2P, text: str) -> str: return g2p.enco...
@dataclass class RandomCrop(DataPipe): '\n Completely randomized for every batch even with the same datapoint id.\n Only suitable for training.\n ' sample_rate: int = 16000 max_secs: float = None wav_name: str = 'wav' crop_name: str = 'wav_crop' def crop_wav(self, wav): if ((...
@dataclass class ExtractKaldiFeat(DataPipe): kaldi: dict = None delta: dict = None cmvn: dict = None wav_name: str = 'wav' feat_name: str = 'feat' '\n Args:\n kaldi (dict): args for the kaldi extracter\n delta (dict): args for applying delta on features\n cmvn (dict): a...
@dataclass class ExtractOnlineFeat(DataPipe): win_ms: int = 25 hop_ms: int = 10 n_freq: int = 201 n_mels: int = 80 n_mfcc: int = 13 input: dict = None target: dict = None wav_name: str = 'wav' feat_name: str = 'feat' '\n Args:\n win_ms (int): window size in ms\n ...
@dataclass class ExtractApcFeat(DataPipe): feat_type: str = 'fbank' feat_dim: int = 80 frame_length: int = 25 frame_shift: int = 10 decode_wav: bool = False cmvn: bool = True wav_name: str = 'wav' feat_name: str = 'feat' '\n Args:\n feat_type (str): feature type\n ...
@dataclass class ExtractNpcFeat(DataPipe): feat_type: str = 'fbank' feat_dim: int = 80 frame_length: int = 25 frame_shift: int = 10 decode_wav: bool = False cmvn: bool = True wav_name: str = 'wav' feat_name: str = 'feat' '\n Args:\n feat_type (str): feature type\n ...
class HearTimestampDatapipe(SequentialDataPipe): def __init__(self, sample_rate: int=16000, feat_frame_shift: int=160): super().__init__(UnfoldChunkBySec(min_chunk_secs=4.0, max_chunk_secs=4.0, step_secs=4.0), LoadAudio(audio_sample_rate=sample_rate), BuildMultiClassTagging(sample_rate=sample_rate, feat_...
@dataclass class NoiseAugmentation(DataPipe): noise_proportion: float = 0.0 input_feat_name: str = 'input_feat' output_feat_name: str = 'output_feat' '\n Args:\n noise_proportion (float): for this percentage of the time, Gaussian noise will be applied on all frames during MAM training, set t...
@dataclass class NormWavDecibel(DataPipe): target_level: int = (- 25) wav_name: str = 'wav' norm_wav_name: str = 'wav' '\n Args:\n target_level (int): normalize the wav decibel level to the target value\n wav_name (str): handle for the `takes` (input)\n norm_wav_name (str): han...
class PretrainApcPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n ' def __init__(self, output_keys: dict=None, n_future: int=5, feat_type: str='fbank', feat_dim: int=80, frame_length: int=25, frame_shift: int=10, decode_wav: bool=False, cmvn: bool=True,...
class PretrainAudioAlbertPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n ' def __init__(self, output_keys: dict=None, position_encoding_size: int=768, mask_proportion: float=0.15, mask_consecutive_min: int=7, mask_consecutive_max: int=7, mask_allow_ove...
class PretrainMockingjayPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n ' def __init__(self, output_keys: dict=None, position_encoding_size: int=768, mask_proportion: float=0.15, mask_consecutive_min: int=7, mask_consecutive_max: int=7, mask_allow_over...
class PretrainNpcPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n ' def __init__(self, output_keys: dict=None, feat_type: str='fbank', feat_dim: int=80, frame_length: int=25, frame_shift: int=10, decode_wav: bool=False, cmvn: bool=True, audio_sample_rat...
class PretrainTeraPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n ' def __init__(self, output_keys: dict=None, position_encoding_size: int=768, mask_proportion: float=0.15, mask_consecutive_min: int=7, mask_consecutive_max: int=7, mask_allow_overlap: b...
class SpeakerVerificationPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n label: str\n ' def __init__(self, audio_sample_rate: int=16000, audio_channel_reduction: str='first', random_crop_secs: float=(- 1), sox_effects: List[List]=None): ...
class Speech2PhonemePipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n transcription: str\n ' def __init__(self): output_keys = dict(x='wav', x_len='wav_len', labels='phonemized_text', class_ids='tokenized_text', unique_name='id') s...
class Speech2TextPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n transcription: str\n ' def __init__(self, generate_tokenizer: bool=False, vocab_type: str='character', text_file: str=None, vocab_file: str=None, slots_file: str=None, vocab_args: ...
class UtteranceClassificationPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n label: str\n ' def __init__(self, output_keys: dict=None, audio_sample_rate: int=16000, audio_channel_reduction: str='first', sox_effects: list=None, train_category_enc...
class UtteranceMultipleCategoryClassificationPipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n labels: List[str]\n ' def __init__(self, output_keys: dict=None, audio_sample_rate: int=16000, audio_channel_reduction: str='first', sox_effects: list=N...
class HearScenePipe(SequentialDataPipe): '\n each item in the input dataset should have:\n wav_path: str\n labels: List[str]\n ' def __init__(self, output_keys: dict=None, audio_sample_rate: int=16000, audio_channel_reduction: str='first'): output_keys = (output_keys or dict(x='wa...
def generate_eval_pairs(file_list, train_file_list, eval_data_root, num_samples): X = [] for trgspk in TRGSPKS_TASK1: spk_file_list = [] for number in train_file_list: wav_path = os.path.join(eval_data_root, trgspk, (number + '.wav')) if os.path.isfile(wav_path): ...
class VCTK_VCC2020Dataset(Dataset): def __init__(self, split, trdev_data_root, eval_data_root, spk_embs_root, lists_root, eval_lists_root, fbank_config, spk_emb_source, num_ref_samples, train_dev_seed=1337, **kwargs): super(VCTK_VCC2020Dataset, self).__init__() self.split = split self.fba...
class CustomDataset(Dataset): def __init__(self, eval_pair_list_file, spk_emb_source, **kwargs): super(CustomDataset, self).__init__() self.spk_emb_source = spk_emb_source if os.path.isfile(eval_pair_list_file): print('[Dataset] Reading custom eval pair list file: {}'.format(e...
def get_basename(path): return os.path.splitext(os.path.split(path)[(- 1)])[0]
def get_trgspk_and_number(basename): if ('_' in basename): (trgspk, srcspk, number) = basename.split('_')[:3] return (trgspk, number) else: return basename
def _calculate_asv_score(model, file_list, gt_root, threshold): results = {} for (i, cvt_wav_path) in enumerate(tqdm(file_list)): basename = get_basename(cvt_wav_path) (trgspk, number) = get_trgspk_and_number(basename) gt_wav_path = os.path.join(gt_root, trgspk, (number + '.wav')) ...
def _calculate_asr_score(model, device, file_list, groundtruths): keys = ['hits', 'substitutions', 'deletions', 'insertions'] ers = {} c_results = {k: 0 for k in keys} w_results = {k: 0 for k in keys} for (i, cvt_wav_path) in enumerate(tqdm(file_list)): basename = get_basename(cvt_wav_path...
def _calculate_mcd_f0(file_list, gt_root, f0_all, results): for (i, cvt_wav_path) in enumerate(file_list): basename = get_basename(cvt_wav_path) (trgspk, number) = get_trgspk_and_number(basename) f0min = f0_all[trgspk]['f0min'] f0max = f0_all[trgspk]['f0max'] gt_wav_path = ...
def get_parser(): parser = argparse.ArgumentParser(description='objective evaluation script.') parser.add_argument('--wavdir', required=True, type=str, help='directory for converted waveforms') parser.add_argument('--task', required=True, type=str, choices=['task1', 'task2'], help='task 1 or task 2') ...
def main(): args = get_parser().parse_args() task = args.task gt_root = os.path.join(args.data_root, 'vcc2020') f0_path = os.path.join(args.data_root, 'f0.yaml') threshold_path = os.path.join(args.data_root, 'thresholds.yaml') transcription_path = os.path.join(args.data_root, 'vcc2020', 'promp...
def get_parser(): parser = argparse.ArgumentParser(description='Extract results.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--upstream', type=str, required=True, help='upstream') parser.add_argument('--task', type=str, required=True, help='task') parser.add_argument...
def grep(filepath, query): lines = [] with open(filepath, 'r') as f: for line in f: if (query in line): lines.append(line.rstrip()) return lines
def encoder_init(m): 'Initialize encoder parameters.' if isinstance(m, torch.nn.Conv1d): torch.nn.init.xavier_uniform_(m.weight, torch.nn.init.calculate_gain('relu'))
class Taco2Encoder(torch.nn.Module): 'Encoder module of the Tacotron2 TTS model.\n\n Reference:\n _`Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_\n https://arxiv.org/abs/1712.05884\n\n ' def __init__(self, idim, elayers=1, eunits=512, econv_layers=3, econv_chan...
class Taco2Prenet(torch.nn.Module): 'Prenet module for decoder of Tacotron2.\n\n The Prenet preforms nonlinear conversion\n of inputs before input to auto-regressive lstm,\n which helps alleviate the exposure bias problem.\n\n Note:\n This module alway applies dropout even in evaluation.\n ...
class RNNLayer(nn.Module): ' RNN wrapper, includes time-downsampling' def __init__(self, input_dim, module, bidirection, dim, dropout, layer_norm, sample_rate, proj): super(RNNLayer, self).__init__() rnn_out_dim = ((2 * dim) if bidirection else dim) self.out_dim = rnn_out_dim ...
class RNNCell(nn.Module): ' RNN cell wrapper' def __init__(self, input_dim, module, dim, dropout, layer_norm, proj): super(RNNCell, self).__init__() rnn_out_dim = dim self.out_dim = rnn_out_dim self.dropout = dropout self.layer_norm = layer_norm self.proj = pro...
class Model(nn.Module): def __init__(self, input_dim, output_dim, resample_ratio, stats, ar, encoder_type, hidden_dim, lstmp_layers, lstmp_dropout_rate, lstmp_proj_dim, lstmp_layernorm, spk_emb_integration_type, spk_emb_dim, prenet_layers=2, prenet_dim=256, prenet_dropout_rate=0.5, **kwargs): super(Model...
class VCC2020Dataset(Dataset): def __init__(self, split, trgspk, data_root, lists_root, fbank_config, train_dev_seed=1337, **kwargs): super(VCC2020Dataset, self).__init__() self.trgspk = trgspk self.trg_lang = trgspk[1] self.fbank_config = fbank_config X = [] if ((...