code stringlengths 17 6.64M |
|---|
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 ((... |
class CustomDataset(Dataset):
def __init__(self, eval_list_file, **kwargs):
super(CustomDataset, self).__init__()
X = []
if os.path.isfile(eval_list_file):
print('[Dataset] Reading custom eval list file: {}'.format(eval_list_file))
X = open(eval_list_file, 'r').rea... |
def get_basename(path):
return os.path.splitext(os.path.split(path)[(- 1)])[0]
|
def get_number(basename):
if ('_' in basename):
return basename.split('_')[1]
else:
return basename
|
def _calculate_asv_score(model, file_list, gt_root, trgspk, threshold):
results = {}
for (i, cvt_wav_path) in enumerate(tqdm(file_list)):
basename = get_basename(cvt_wav_path)
number = get_number(basename)
gt_wav_path = os.path.join(gt_root, trgspk, (number + '.wav'))
results[b... |
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, trgspk, f0min, f0max, results):
for (i, cvt_wav_path) in enumerate(file_list):
basename = get_basename(cvt_wav_path)
number = get_number(basename)
gt_wav_path = os.path.join(gt_root, trgspk, (number + '.wav'))
(cvt_wav, cvt_fs) = librosa.lo... |
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('--trgspk', required=True, type=str, help='target speaker')
parser.add_argument('--data_... |
def main():
args = get_parser().parse_args()
trgspk = args.trgspk
task = ('task1' if (trgspk[1] == 'E') else 'task2')
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')
transcr... |
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, choices=['task1', 'task2'], help='ta... |
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, prenet_layers=2, prenet_dim=256, prenet_dropout_rate=0.5, **kwargs):
super(Model, self).__init__()
self.ar = ar... |
def low_cut_filter(x, fs, cutoff=70):
'FUNCTION TO APPLY LOW CUT FILTER\n\n Args:\n x (ndarray): Waveform sequence\n fs (int): Sampling frequency\n cutoff (float): Cutoff frequency of low cut filter\n\n Return:\n (ndarray): Low cut filtered waveform sequence\n '
nyquist = ... |
def spc2npow(spectrogram):
'Calculate normalized power sequence from spectrogram\n\n Parameters\n ----------\n spectrogram : array, shape (T, `fftlen / 2 + 1`)\n Array of spectrum envelope\n\n Return\n ------\n npow : array, shape (`T`, `1`)\n Normalized power sequence\n\n '
... |
def _spvec2pow(specvec):
'Convert a spectrum envelope into a power\n\n Parameters\n ----------\n specvec : vector, shape (`fftlen / 2 + 1`)\n Vector of specturm envelope |H(w)|^2\n\n Return\n ------\n power : scala,\n Power of a frame\n\n '
fftl2 = (len(specvec) - 1)
fft... |
def extfrm(data, npow, power_threshold=(- 20)):
'Extract frame over the power threshold\n\n Parameters\n ----------\n data: array, shape (`T`, `dim`)\n Array of input data\n npow : array, shape (`T`)\n Vector of normalized power sequence.\n power_threshold : float, optional\n V... |
def world_extract(x, fs, f0min, f0max):
x = (x * np.iinfo(np.int16).max)
x = np.array(x, dtype=np.float64)
x = low_cut_filter(x, fs)
(f0, time_axis) = pw.harvest(x, fs, f0_floor=f0min, f0_ceil=f0max, frame_period=MCEP_SHIFT)
sp = pw.cheaptrick(x, f0, time_axis, fs, fft_size=MCEP_FFTL)
ap = pw.... |
def calculate_mcd_f0(x, y, fs, f0min, f0max):
'\n x and y must be in range [-1, 1]\n '
gt_feats = world_extract(x, fs, f0min, f0max)
cvt_feats = world_extract(y, fs, f0min, f0max)
gt_mcep_nonsil_pow = extfrm(gt_feats['mcep'], gt_feats['npow'])
cvt_mcep_nonsil_pow = extfrm(cvt_feats['mcep'], ... |
def load_asr_model(device):
'Load model'
print(f'[INFO]: Load the pre-trained ASR by {ASR_PRETRAINED_MODEL}.')
model = Wav2Vec2ForCTC.from_pretrained(ASR_PRETRAINED_MODEL).to(device)
tokenizer = Wav2Vec2Tokenizer.from_pretrained(ASR_PRETRAINED_MODEL)
models = {'model': model, 'tokenizer': tokenize... |
def normalize_sentence(sentence):
'Normalize sentence'
sentence = sentence.upper()
sentence = jiwer.RemovePunctuation()(sentence)
sentence = jiwer.RemoveWhiteSpace(replace_by_space=True)(sentence)
sentence = jiwer.RemoveMultipleSpaces()(sentence)
sentence = jiwer.Strip()(sentence)
sentence... |
def calculate_measures(groundtruth, transcription):
'Calculate character/word measures (hits, subs, inserts, deletes) for one given sentence'
groundtruth = normalize_sentence(groundtruth)
transcription = normalize_sentence(transcription)
c_result = jiwer.cer(groundtruth, transcription, return_dict=Tru... |
def transcribe(model, device, wav):
'Calculate score on one single waveform'
inputs = model['tokenizer'](wav, sampling_rate=16000, return_tensors='pt', padding='longest')
input_values = inputs.input_values.to(device)
attention_mask = inputs.attention_mask.to(device)
logits = model['model'](input_v... |
def load_asv_model(device):
model = VoiceEncoder().to(device)
return model
|
def get_embedding(wav_path, encoder):
wav = preprocess_wav(wav_path)
embedding = encoder.embed_utterance(wav)
return embedding
|
def get_cosine_similarity(x_emb, y_emb):
return (np.inner(x_emb, y_emb) / (np.linalg.norm(x_emb) * np.linalg.norm(y_emb)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.