code
stringlengths
17
6.64M
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)))
def generate_sample(embeddings, this_spk, other_spks, label): '\n Calculate cosine similarity.\n Generate positive or negative samples with the label.\n ' this_spk_embs = embeddings[this_spk] other_spk_embs = list(chain(*[embeddings[spk] for spk in other_spks])) samples = [] for this_spk_...
def calculate_equal_error_rate(labels, scores): '\n labels: (N,1) value: 0,1\n\n scores: (N,1) value: -1 ~ 1\n\n ' (fpr, tpr, thresholds) = roc_curve(labels, scores) a = (lambda x: ((1.0 - x) - interp1d(fpr, tpr)(x))) equal_error_rate = brentq(a, 0.0, 1.0) threshold = interp1d(fpr, thresh...
def calculate_threshold(data_root, task, device, query='E3*.wav'): if (task == 'task1'): spks = (SRCSPKS + TRGSPKS_TASK1) if (task == 'task2'): spks = (SRCSPKS + TRGSPKS_TASK2) else: raise NotImplementedError encoder = load_asv_model(device) embeddings = defaultdict(list) ...
def calculate_accept(x_path, y_path, encoder, threshold): x_emb = get_embedding(x_path, encoder) y_emb = get_embedding(y_path, encoder) cosine_similarity = get_cosine_similarity(x_emb, y_emb) return (cosine_similarity > threshold)
class SequenceDataset(Dataset): def __init__(self, split, bucket_size, dictionary, libri_root, bucket_file, **kwargs): super(SequenceDataset, self).__init__() self.dictionary = dictionary self.libri_root = libri_root self.sample_rate = SAMPLE_RATE self.split_sets = kwargs[...
class Dictionary(fairseq_Dictionary): 'Dictionary inheritted from FairSeq' @staticmethod def _add_transcripts_to_dictionary_single_worker(transcripts, eos_word, worker_id=0, num_workers=1): counter = Counter() size = len(transcripts) chunk_size = (size // num_workers) offs...
def token_to_word(text): return text.replace(' ', '').replace('|', ' ').strip()
def get_decoder(decoder_args_dict, dictionary): decoder_args = Namespace(**decoder_args_dict) if (decoder_args.decoder_type == 'kenlm'): from .w2l_decoder import W2lKenLMDecoder decoder_args.beam_size_token = len(dictionary) if isinstance(decoder_args.unk_weight, str): deco...
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n ' def __init__(self, upstream_dim, upstream_rate, downstream_expert, expdir, **kwargs): "\n Args:\n upstream_dim: int\n ...
class W2lDecoder(object): def __init__(self, args, tgt_dict): self.tgt_dict = tgt_dict self.vocab_size = len(tgt_dict) self.nbest = args.nbest self.criterion_type = CriterionType.CTC self.blank = (tgt_dict.index('<ctc_blank>') if ('<ctc_blank>' in tgt_dict.indices) else tg...
class W2lKenLMDecoder(W2lDecoder): def __init__(self, args, tgt_dict): super().__init__(args, tgt_dict) self.unit_lm = getattr(args, 'unit_lm', False) if args.lexicon: self.lexicon = load_words(args.lexicon) self.word_dict = create_word_dict(self.lexicon) ...
class AtisDataset(Dataset): def __init__(self, df, base_path, Sy_intent, type): self.df = df self.base_path = base_path self.max_length = (SAMPLE_RATE * EXAMPLE_WAV_MAX_SEC) self.Sy_intent = Sy_intent self.type = type def __len__(self): return len(self.df) ...
class Identity(nn.Module): def __init__(self, config): super(Identity, self).__init__() def forward(self, feature, att_mask, head_mask): return [feature]
class Mean(nn.Module): def __init__(self, out_dim): super(Mean, self).__init__() def forward(self, feature, att_mask): ' \n Arguments\n feature - [BxTxD] Acoustic feature with shape \n att_mask - [BxTx1] Attention Mask logits\n ' agg_vec_li...
class SAP(nn.Module): ' Self Attention Pooling module incoporate attention mask' def __init__(self, out_dim): super(SAP, self).__init__() self.act_fn = nn.Tanh() self.sap_layer = SelfAttentionPooling(out_dim) def forward(self, feature, att_mask): ' \n Arguments\n ...
class SelfAttentionPooling(nn.Module): '\n Implementation of SelfAttentionPooling \n Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition\n https://arxiv.org/pdf/2008.01077v1.pdf\n ' def __init__(self, input_dim): super(SelfAttentionPooling, self).__init__() ...
class Model(nn.Module): def __init__(self, input_dim, agg_module, output_dim, config): super(Model, self).__init__() self.agg_method = eval(agg_module)(input_dim) self.linear = nn.Linear(input_dim, output_dim) self.model = eval(config['module'])(Namespace(**config['hparams'])) ...
class AudioSLUDataset(Dataset): def __init__(self, df, base_path, Sy_intent, speaker_name): self.df = df self.base_path = base_path self.max_length = (SAMPLE_RATE * EXAMPLE_WAV_MAX_SEC) self.Sy_intent = Sy_intent self.speaker_name = speaker_name self.resampler = to...
class Identity(nn.Module): def __init__(self, config, **kwargs): super(Identity, self).__init__() def forward(self, feature, att_mask, head_mask, **kwargs): return [feature]
class Mean(nn.Module): def __init__(self, out_dim): super(Mean, self).__init__() def forward(self, feature, att_mask): ' \n Arguments\n feature - [BxTxD] Acoustic feature with shape \n att_mask - [BxTx1] Attention Mask logits\n ' agg_vec_li...
class SAP(nn.Module): ' Self Attention Pooling module incoporate attention mask' def __init__(self, out_dim): super(SAP, self).__init__() self.act_fn = nn.Tanh() self.sap_layer = SelfAttentionPooling(out_dim) def forward(self, feature, att_mask): ' \n Arguments\n ...
class SelfAttentionPooling(nn.Module): '\n Implementation of SelfAttentionPooling \n Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition\n https://arxiv.org/pdf/2008.01077v1.pdf\n ' def __init__(self, input_dim): super(SelfAttentionPooling, self).__init__() ...
class Model(nn.Module): def __init__(self, input_dim, agg_module, output_dim, config): super(Model, self).__init__() self.agg_method = eval(agg_module)(input_dim) self.linear = nn.Linear(input_dim, output_dim) self.model = eval(config['module'])(Namespace(**config['hparams'])) ...
class CommonVoiceDataset(Dataset): def __init__(self, split, tokenizer, bucket_size, path, ascending=False, ratio=1.0, offset=0, **kwargs): self.path = path self.bucket_size = bucket_size for s in split: with open(s, 'r') as fp: rows = csv.reader(fp, delimiter=...
def normalize(sent, language): sent = unicodedata.normalize('NFKC', sent).upper() sent = sent.translate(translator) sent = re.sub(' +', ' ', sent) if (language in ['zh-TW', 'zh-CN', 'ja']): sent = sent.replace(' ', '') if (language in ['zh-TW', 'zh-CN', 'ja', 'ar', 'ru']): if any([...
def read_tsv(path, corpus_root, language, accent=None, hours=(- 1)): with open(path, 'r') as fp: rows = csv.reader(fp, delimiter='\t') data_list = [] total_len = 0 iterator = tqdm(enumerate(rows)) for (i, row) in iterator: if (i == 0): continue ...
def write_tsv(data, out_path): with open(out_path, 'w') as fp: writer = csv.writer(fp, delimiter='\t') writer.writerow(['path', 'sentence']) for d in data: path = (d['path'][:(- 3)] + 'wav') writer.writerow([path, d['sentence']])
def write_txt(data, out_path): with open(out_path, 'w') as fp: for d in data: fp.write((d['sentence'] + '\n'))
def main(): parser = argparse.ArgumentParser() parser.add_argument('--root', type=str, help='Root of Common Voice 7.0 directory.') parser.add_argument('--lang', type=str, help='Language abbreviation.') parser.add_argument('--out', type=str, help='Path to output directory.') parser.add_argument('--...
def read_processed_tsv(path): with open(path, 'r') as fp: rows = csv.reader(fp, delimiter='\t') file_list = [] for (i, row) in enumerate(rows): if (i == 0): continue file_list.append((row[0][:(- 3)] + 'mp3')) return file_list
def main(): parser = argparse.ArgumentParser() parser.add_argument('--root', type=str, help='Directory of the dataset.') parser.add_argument('--tsv', type=str, help='Path to processed tsv file.') args = parser.parse_args() file_list = read_processed_tsv(args.tsv) for file in tqdm(file_list): ...
def parse_lexicon(line, tokenizer): line.replace('\t', ' ') (word, *phonemes) = line.split() for p in phonemes: assert (p in tokenizer._vocab2idx.keys()) return (word, phonemes)
def read_text(file, word2phonemes, tokenizer): "Get transcription of target wave file, \n it's somewhat redundant for accessing each txt multiplt times,\n but it works fine with multi-thread" src_file = ('-'.join(file.split('-')[:(- 1)]) + '.trans.txt') idx = file.split('/')[(- 1)].split('.')[...
class LibriPhoneDataset(Dataset): def __init__(self, split, tokenizer, bucket_size, path, lexicon, ascending=False, **kwargs): self.path = path self.bucket_size = bucket_size word2phonemes_all = defaultdict(list) for lexicon_file in lexicon: with open(lexicon_file, 'r'...
def read_text(file): "Get transcription of target wave file, \n it's somewhat redundant for accessing each txt multiplt times,\n but it works fine with multi-thread" src_file = ('-'.join(file.split('-')[:(- 1)]) + '.trans.txt') idx = file.split('/')[(- 1)].split('.')[0] with open(src_file,...
class LibriDataset(Dataset): def __init__(self, split, tokenizer, bucket_size, path, ascending=False, **kwargs): self.path = path self.bucket_size = bucket_size file_list = [] for s in split: split_list = list(Path(join(path, s)).rglob('*.flac')) assert (le...
class SnipsDataset(Dataset): def __init__(self, split, tokenizer, bucket_size, path, num_workers=12, ascending=False, **kwargs): self.path = path self.bucket_size = bucket_size self.speaker_list = (kwargs[f'{split}_speakers'] if (type(split) == str) else kwargs[f'{split[0]}_speakers']) ...
def collect_audio_batch(batch, split, half_batch_size_wav_len=300000): 'Collects a batch, should be list of tuples (audio_path <str>, list of int token <list>) \n e.g. [(file1,txt1),(file2,txt2),...]\n ' def audio_reader(filepath): (wav, sample_rate) = torchaudio.load(filepath) retur...
def create_dataset(split, tokenizer, name, bucketing, batch_size, **kwargs): ' Interface for creating all kinds of dataset' if (name.lower() == 'librispeech'): from .corpus.librispeech import LibriDataset as Dataset elif (name.lower() == 'snips'): from .corpus.snips import SnipsDataset as ...
def load_dataset(split, tokenizer, corpus): ' Prepare dataloader for training/validation' num_workers = corpus.pop('num_workers', 12) (dataset, loader_bs) = create_dataset(split, tokenizer, num_workers=num_workers, **corpus) collate_fn = partial(collect_audio_batch, split=split) if (split == 'trai...
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n ' def __init__(self, upstream_dim, upstream_rate, downstream_expert, expdir, **kwargs): super(DownstreamExpert, self).__init__() self.e...
def cer(hypothesis, groundtruth, **kwargs): err = 0 tot = 0 for (p, t) in zip(hypothesis, groundtruth): err += float(ed.eval(p, t)) tot += len(t) return (err / tot)
def per(*args, **kwargs): return wer(*args, **kwargs)
def wer(hypothesis, groundtruth, **kwargs): err = 0 tot = 0 for (p, t) in zip(hypothesis, groundtruth): p = p.split(' ') t = t.split(' ') err += float(ed.eval(p, t)) tot += len(t) return (err / tot)
def clean(ref): ref = re.sub('B\\-(\\S+) ', '', ref) ref = re.sub(' E\\-(\\S+)', '', ref) return ref
def parse(hyp, ref): gex = re.compile('B\\-(\\S+) (.+?) E\\-\\1') hyp = re.sub(' +', ' ', hyp) ref = re.sub(' +', ' ', ref) hyp_slots = gex.findall(hyp) ref_slots = gex.findall(ref) ref_slots = ';'.join([':'.join([x[1], x[0]]) for x in ref_slots]) if (len(hyp_slots) > 0): hyp_slots...
def slot_type_f1(hypothesis, groundtruth, **kwargs): F1s = [] for (p, t) in zip(hypothesis, groundtruth): (ref_text, hyp_text, ref_slots, hyp_slots) = parse(p, t) ref_slots = ref_slots.split(';') hyp_slots = hyp_slots.split(';') unique_slots = [] ref_dict = {} h...
def slot_value_cer(hypothesis, groundtruth, **kwargs): value_hyps = [] value_refs = [] for (p, t) in zip(hypothesis, groundtruth): (ref_text, hyp_text, ref_slots, hyp_slots) = parse(p, t) ref_slots = ref_slots.split(';') hyp_slots = hyp_slots.split(';') unique_slots = [] ...
def slot_value_wer(hypothesis, groundtruth, **kwargs): value_hyps = [] value_refs = [] for (p, t) in zip(hypothesis, groundtruth): (ref_text, hyp_text, ref_slots, hyp_slots) = parse(p, t) ref_slots = ref_slots.split(';') hyp_slots = hyp_slots.split(';') unique_slots = [] ...
def slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot, **kwargs): (test_case, TPs, FNs, FPs) = ([], 0, 0, 0) slot2F1 = {} for (p, t) in zip(hypothesis, groundtruth): (ref_text, hyp_text, ref_slots, hyp_slots) = parse(p, t) ref_slots = ref_slots.split(';') hyp_slots = hyp_slo...
def slot_edit_f1_full(hypothesis, groundtruth, **kwargs): return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=True, **kwargs)
def slot_edit_f1_part(hypothesis, groundtruth, **kwargs): return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=False, **kwargs)
class _BaseTextEncoder(abc.ABC): @abc.abstractmethod def encode(self, s): raise NotImplementedError @abc.abstractmethod def decode(self, ids, ignore_repeat=False): raise NotImplementedError @abc.abstractproperty def vocab_size(self): raise NotImplementedError @a...
class CharacterTextEncoder(_BaseTextEncoder): def __init__(self, vocab_list): self._vocab_list = (['<pad>', '<eos>', '<unk>'] + vocab_list) self._vocab2idx = {v: idx for (idx, v) in enumerate(self._vocab_list)} def encode(self, s): s = s.strip('\r\n ') return ([self.vocab_to_...
class CharacterTextSlotEncoder(_BaseTextEncoder): def __init__(self, vocab_list, slots): self._vocab_list = (['<pad>', '<eos>', '<unk>'] + vocab_list) self._vocab2idx = {v: idx for (idx, v) in enumerate(self._vocab_list)} self.slots = slots self.slot2id = {self.slots[i]: (i + len(...
class SubwordTextEncoder(_BaseTextEncoder): def __init__(self, spm): 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 --eos_id=1 --unk_id=2 --bos_id=-1 --model_type=bpe --eos_piece=<...
class SubwordTextSlotEncoder(_BaseTextEncoder): def __init__(self, spm, slots): 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 --eos_id=1 --unk_id=2 --bos_id=-1 --model_type=bpe --...
class WordTextEncoder(CharacterTextEncoder): def encode(self, s): 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, ignore_repeat=False): vocabs = [] for (t, idx) in enumerate(idxs): ...
class BertTextEncoder(_BaseTextEncoder): 'Bert Tokenizer.\n\n https://github.com/huggingface/pytorch-transformers/blob/master/pytorch_transformers/tokenization_bert.py\n ' def __init__(self, tokenizer): self._tokenizer = tokenizer self._tokenizer.pad_token = '<pad>' self._tokeni...
def load_text_encoder(mode, vocab_file, slots_file=None): if (mode == 'character'): return CharacterTextEncoder.load_from_file(vocab_file) elif (mode == 'character-slot'): return CharacterTextSlotEncoder.load_from_file(vocab_file, slots_file) elif (mode == 'subword'): return Subwor...
class Model(nn.Module): def __init__(self, input_dim, output_class_num, rnn_layers, hidden_size, **kwargs): super(Model, self).__init__() self.use_rnn = (rnn_layers > 0) if self.use_rnn: self.rnn = nn.LSTM(input_dim, hidden_size, num_layers=rnn_layers, batch_first=True) ...
def get_wav_paths(data_dirs): wav_paths = find_files(data_dirs) wav_dict = {} for wav_path in wav_paths: wav_name = splitext(basename(wav_path))[0] start = wav_path.find('Session') wav_path = wav_path[start:] wav_dict[wav_name] = wav_path return wav_dict
def preprocess(data_dirs, paths, out_path): meta_data = [] for path in paths: wav_paths = get_wav_paths(path_join(data_dirs, path, WAV_DIR_PATH)) label_dir = path_join(data_dirs, path, LABEL_DIR_PATH) label_paths = list(os.listdir(label_dir)) label_paths = [label_path for label...
def main(data_dir): 'Main function.' paths = list(os.listdir(data_dir)) paths = [path for path in paths if (path[:7] == 'Session')] paths.sort() out_dir = os.path.join(data_dir, 'meta_data') os.makedirs(out_dir, exist_ok=True) for (i, path) in enumerate(paths): os.makedirs(f'{out_d...
class IEMOCAPDataset(Dataset): def __init__(self, data_dir, meta_path, pre_load=True): self.data_dir = data_dir self.pre_load = pre_load with open(meta_path, 'r') as f: self.data = json.load(f) self.class_dict = self.data['labels'] self.idx2emotion = {value: ke...
def collate_fn(samples): return zip(*samples)
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n ' def __init__(self, upstream_dim, downstream_expert, expdir, **kwargs): super(DownstreamExpert, self).__init__() self.upstream_dim = u...
class SelfAttentionPooling(nn.Module): '\n Implementation of SelfAttentionPooling\n Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition\n https://arxiv.org/pdf/2008.01077v1.pdf\n ' def __init__(self, input_dim): super(SelfAttentionPooling, self).__init__() ...
class CNNSelfAttention(nn.Module): def __init__(self, input_dim, hidden_dim, kernel_size, padding, pooling, dropout, output_class_num, **kwargs): super(CNNSelfAttention, self).__init__() self.model_seq = nn.Sequential(nn.AvgPool1d(kernel_size, pooling, padding), nn.Dropout(p=dropout), nn.Conv1d(i...
class FCN(nn.Module): def __init__(self, input_dim, hidden_dim, kernel_size, padding, pooling, dropout, output_class_num, **kwargs): super(FCN, self).__init__() self.model_seq = nn.Sequential(nn.Conv1d(input_dim, 96, 11, stride=4, padding=5), nn.LocalResponseNorm(96), nn.ReLU(), nn.MaxPool1d(3, 2...
class DeepNet(nn.Module): def __init__(self, input_dim, hidden_dim, kernel_size, padding, pooling, dropout, output_class_num, **kwargs): super(DeepNet, self).__init__() self.model_seq = nn.Sequential(nn.Conv1d(input_dim, 10, 9), nn.ReLU(), nn.Conv1d(10, 10, 5), nn.ReLU(), nn.Conv1d(10, 10, 3), nn...