code stringlengths 17 6.64M |
|---|
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... |
class DeepModel(nn.Module):
def __init__(self, input_dim, output_dim, model_type, pooling, **kwargs):
super(DeepModel, self).__init__()
self.pooling = pooling
self.model = eval(model_type)(input_dim=input_dim, output_class_num=output_dim, pooling=pooling, **kwargs)
def forward(self, ... |
class SeparationDataset(Dataset):
def __init__(self, data_dir, rate=16000, src=['mix_clean'], tgt=['s1', 's2'], n_fft=512, hop_length=320, win_length=512, window='hann', center=True):
super(SeparationDataset, self).__init__()
"\n Args:\n data_dir (str):\n prepared... |
class SepRNN(torch.nn.Module):
def __init__(self, input_dim, num_bins, rnn='lstm', num_spks=2, num_layers=3, hidden_size=896, dropout=0.0, non_linear='relu', bidirectional=True):
super(SepRNN, self).__init__()
if (non_linear not in ['relu', 'sigmoid', 'tanh']):
raise ValueError('Unsup... |
def main():
output_dir = '{}/wav{}/{}/{}'.format(args.tgt_dir, args.sample_rate, args.mode, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!')
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.src_dir, args.sample_... |
def main():
output_dir = '{}/wav{}/{}'.format(args.tgt_dir, args.sample_rate, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!')
else:
os.makedirs(output_dir)
if ((args.part == 'train') or (args.part == 'dev')):
dset = 'train... |
class SeparationDataset(Dataset):
def __init__(self, data_dir, rate=16000, src=['noisy'], tgt=['clean'], n_fft=512, hop_length=320, win_length=512, window='hann', center=True):
super(SeparationDataset, self).__init__()
'\n Args:\n data_dir (str):\n prepared data d... |
class SepRNN(torch.nn.Module):
def __init__(self, input_dim, num_bins, rnn='lstm', num_spks=2, num_layers=3, hidden_size=896, dropout=0.0, non_linear='relu', bidirectional=True):
super(SepRNN, self).__init__()
if (non_linear not in ['relu', 'sigmoid', 'tanh', 'none']):
raise ValueErro... |
def main():
output_dir = '{}/wav{}/{}/{}'.format(args.tgt_dir, args.sample_rate, args.mode, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!')
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.src_dir, args.sample_... |
def main():
output_dir = '{}/wav{}/{}'.format(args.tgt_dir, args.sample_rate, args.part)
if os.path.exists(output_dir):
raise ValueError('Warning: {} already exists, please check!')
else:
os.makedirs(output_dir)
if ((args.part == 'train') or (args.part == 'dev')):
dset = 'train... |
class RandomDataset(Dataset):
def __init__(self, **kwargs):
self.class_num = 48
def __getitem__(self, idx):
samples = random.randint((EXAMPLE_WAV_MIN_SEC * SAMPLE_RATE), (EXAMPLE_WAV_MAX_SEC * SAMPLE_RATE))
wav = torch.randn(samples)
label = random.randint(0, (self.class_num ... |
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 Model(nn.Module):
def __init__(self, input_dim, output_class_num, **kwargs):
super(Model, self).__init__()
self.linear = nn.Linear(input_dim, output_class_num)
def forward(self, features):
pooled = features.mean(dim=1)
predicted = self.linear(pooled)
return pred... |
class FluentCommandsDataset(Dataset):
def __init__(self, df, base_path, Sy_intent):
self.df = df
self.base_path = base_path
self.max_length = (SAMPLE_RATE * EXAMPLE_WAV_MAX_SEC)
self.Sy_intent = Sy_intent
def __len__(self):
return len(self.df)
def __getitem__(sel... |
def get_downstream_model(input_dim, output_dim, config):
model_cls = eval(config['select'])
model_conf = config.get(config['select'], {})
model = model_cls(input_dim, output_dim, **model_conf)
return model
|
class FrameLevel(nn.Module):
def __init__(self, input_dim, output_dim, hiddens=None, activation='ReLU', **kwargs):
super().__init__()
latest_dim = input_dim
self.hiddens = []
if (hiddens is not None):
for dim in hiddens:
self.hiddens += [nn.Linear(lates... |
class UtteranceLevel(nn.Module):
def __init__(self, input_dim, output_dim, pooling='MeanPooling', activation='ReLU', pre_net=None, post_net={'select': 'FrameLevel'}, **kwargs):
super().__init__()
latest_dim = input_dim
self.pre_net = (get_downstream_model(latest_dim, latest_dim, pre_net) ... |
class MeanPooling(nn.Module):
def __init__(self, **kwargs):
super(MeanPooling, self).__init__()
def forward(self, feature_BxTxH, features_len, **kwargs):
' \n Arguments\n feature_BxTxH - [BxTxH] Acoustic feature with shape \n features_len - [B] of feature leng... |
class AttentivePooling(nn.Module):
' Attentive Pooling module incoporate attention mask'
def __init__(self, input_dim, activation, **kwargs):
super(AttentivePooling, self).__init__()
self.sap_layer = AttentivePoolingModule(input_dim, activation)
def forward(self, feature_BxTxH, features_... |
class AttentivePoolingModule(nn.Module):
'\n Implementation of Attentive Pooling \n '
def __init__(self, input_dim, activation='ReLU', **kwargs):
super(AttentivePoolingModule, self).__init__()
self.W_a = nn.Linear(input_dim, input_dim)
self.W = nn.Linear(input_dim, 1)
se... |
class VCC18SegmentalDataset(Dataset):
def __init__(self, dataframe, base_path, idtable='', valid=False):
self.base_path = Path(base_path)
self.dataframe = dataframe
self.segments_durations = 1
if Path.is_file(idtable):
self.idtable = torch.load(idtable)
for... |
class VCC16SegmentalDataset(Dataset):
def __init__(self, wav_list, base_path):
self.wav_dir = Path(base_path)
self.wav_list = wav_list
self.segments_durations = 1
def __len__(self):
return len(self.wav_list)
def __getitem__(self, idx):
wav_name = self.wav_list[id... |
def unfold_segments(tensor, tgt_duration, sample_rate=16000):
seg_lengths = int((tgt_duration * sample_rate))
src_lengths = len(tensor)
step = (seg_lengths // 2)
tgt_lengths = (seg_lengths if (src_lengths <= seg_lengths) else (((src_lengths // step) + 1) * step))
pad_lengths = (tgt_lengths - src_l... |
class DownstreamExpert(nn.Module):
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__()
self.upstream_dim = upstream_dim
self.datarc = downstream_expert['datarc']
self.modelrc = downstream_expert['modelrc']
idtable = (Path... |
def preprocess(base_path, txt_file):
dataframe = pd.read_csv(Path(base_path, txt_file), index_col=False)
return dataframe
|
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, clipping=False, attention_pooling=False, num_judges=5000, **kwargs):
super(Model, self).__init__()
self.mean_net_linear = nn.Linear(input_dim, 1)
self.mean_net_clipping = clipping
self.mean_net_pooling = (SelfAttentionPooling(i... |
class MOSEIDataset(Dataset):
def __init__(self, split, data, path):
self.split = split
self.data = data
self.path = path
def __getitem__(self, idx):
wav_path = os.path.join(self.path, 'Segmented_Audio', self.split, self.data[idx][0])
(wav, sr) = torchaudio.load(wav_pa... |
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):
"\n Args:\n upstream_dim: int\n Diffe... |
class Model(nn.Module):
def __init__(self, input_dim, output_class_num, **kwargs):
super(Model, self).__init__()
self.linear = nn.Linear(input_dim, output_class_num)
def forward(self, features):
pooled = features.mean(dim=1)
predicted = self.linear(pooled)
return pred... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.