code stringlengths 17 6.64M |
|---|
def label2a(a):
if (a < 0):
return 0
return 1
|
def label2b(a):
if (a < 0):
return (- 1)
if (a > 0):
return 1
return 0
|
def label7(a):
if (a < (- 2)):
return (- 3)
if (a < (- 1)):
return (- 2)
if (a < 0):
return (- 1)
if (a == 0):
return 0
if (a <= 1):
return 1
if (a <= 2):
return 2
return 3
|
class DownstreamExpert(PhoneExpert):
'\n Basically the same as the phone linear expert\n '
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs)
delattr(self, 'model')
self.model = Model(i... |
class Model(nn.Module):
def __init__(self, input_dim, output_class_num, hidden_size, dropout, **kwargs):
super(Model, self).__init__()
self.in_linear = nn.Linear(input_dim, hidden_size)
self.out_linear = nn.Linear(hidden_size, output_class_num)
self.drop = nn.Dropout(dropout)
... |
class PhoneDataset(Dataset):
def __init__(self, split, bucket_size, libri_root, phone_path, bucket_file, sample_rate=16000, train_dev_seed=1337, **kwargs):
super(PhoneDataset, self).__init__()
self.libri_root = libri_root
self.phone_path = phone_path
self.sample_rate = sample_rate... |
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):
predicted = self.linear(features)
return predicted
|
class DownstreamExpert(PhoneExpert):
'\n Basically the same as the phone linear expert\n '
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs)
delattr(self, 'model')
self.model = Model(i... |
class QUESST14Dataset(Dataset):
'QUESST 2014 dataset (English-only).'
def __init__(self, split, **kwargs):
dataset_root = Path(kwargs['dataset_root'])
doc_paths = english_audio_paths(dataset_root, 'language_key_utterances.lst')
query_paths = english_audio_paths(dataset_root, f'languag... |
def english_audio_paths(dataset_root_path, lst_name):
'Extract English audio paths.'
audio_paths = []
with open(((dataset_root_path / 'scoring') / lst_name)) as f:
for line in f:
(audio_path, lang) = tuple(line.strip().split())
if (lang != 'nnenglish'):
cont... |
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: int, downstream_expert: dict, expdir: str, **kwargs):
super(DownstreamExpert, self).__init__()
self.... |
class Model(nn.Module):
def __init__(self, input_dim, bottleneck_dim, hidden_dim, num_layers, **kwargs):
super(Model, self).__init__()
self.connector = nn.Linear(input_dim, bottleneck_dim)
self.rnn = nn.LSTM(input_size=bottleneck_dim, hidden_size=hidden_dim, num_layers=num_layers, batch_f... |
class QUESST14Testset(Dataset):
'QUESST 2014 testing dataset (English-only).'
def __init__(self, split, **kwargs):
assert (split in ['dev', 'eval'])
dataset_root = Path(kwargs['quesst2014_root'])
doc_paths = get_audio_paths(dataset_root, 'language_key_utterances.lst')
query_pa... |
def get_audio_paths(dataset_root_path, lst_name):
'Extract audio paths.'
audio_paths = []
with open(((dataset_root_path / 'scoring') / lst_name)) as f:
for line in f:
(audio_path, lang) = tuple(line.strip().split())
if (lang != 'nnenglish'):
continue
... |
class QUESST14Trainset(Dataset):
'QUESST 2014 training dataset.'
def __init__(self, split, **kwargs):
dataset_root = Path(kwargs['quesst2014_root'])
scoring_root = (dataset_root / 'scoring')
split_root = (scoring_root / f'groundtruth_quesst14_{split}')
query2positives = parse_... |
def parse_rttm(rttm_path):
'Parse audio and query pairs from *.rttm.'
pattern = re.compile('LEXEME\\s+(quesst14_[0-9]+).*?(quesst14_(dev|eval)_[0-9]+)')
query2audios = defaultdict(list)
with open(rttm_path) as fd:
for line in fd:
match = pattern.match(line)
if (match is... |
def parse_lst(lst_path):
'Extract audio names of nnenglish.'
audio_names = []
with open(lst_path) as fd:
for line in fd:
(audio_path, lang) = tuple(line.strip().split())
if (lang != 'nnenglish'):
continue
audio_name = Path(audio_path).with_suffix... |
def path2tensor(filepath):
(tensor, _) = apply_effects_file(str(filepath), [['channels', '1'], ['rate', '16000'], ['norm']])
return tensor.squeeze(0)
|
def crop_segment(tensor, tgt_dur, sample_rate=16000):
src_dur = (len(tensor) / sample_rate)
random_shift = random.uniform(0, (src_dur - tgt_dur))
(audio_tensor, _) = apply_effects_tensor(tensor.unsqueeze(0), sample_rate, [['pad', f'{tgt_dur}', f'{tgt_dur}'], ['trim', f'{(tgt_dur + random_shift)}', f'{tgt_... |
def unfold_segments(tensor, tgt_dur, sample_rate=16000):
seg_len = int((tgt_dur * sample_rate))
src_len = len(tensor)
hop_len = (seg_len // 4)
tgt_len = (seg_len if (src_len <= seg_len) else (((src_len // hop_len) + 1) * hop_len))
pad_len = (tgt_len - src_len)
front_pad_len = random.randint(0,... |
class ModelEntry():
def __init__(self, model, name, trainable, interfaces):
self.model = model
self.name = name
self.trainable = trainable
self.interfaces = interfaces
|
class Runner():
'\n Used to handle high-level concepts of a ML experiment\n eg. training loop, evaluation loop, upstream propagation, optimization, logging, checkpoint saving\n '
def __init__(self, args, config):
self.args = args
self.config = config
self.init_ckpt = (torch.l... |
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!'.format(output_dir))
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.sr... |
def get_utt2path(wav_scp_file):
utt2path = {}
with open(wav_scp_file, 'r') as fh:
content = fh.readlines()
for line in content:
line = line.strip('\n')
(utt, path) = line.split()
utt2path[utt] = path
return utt2path
|
def main():
random.seed(args.seed)
with open('{}/s1/utt2spk'.format(args.src_dir), 'r') as fh:
content = fh.readlines()
uttlist = []
for line in content:
line = line.strip('\n')
utt = line.split()[0]
uttlist.append(utt)
uttlist.sort()
num_utt_ori = len(uttlist)
... |
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', '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!'.format(output_dir))
else:
os.makedirs(output_dir)
wav_dir = '{}/wav{}/{}/{}'.format(args.sr... |
def get_utt2path(wav_scp_file):
utt2path = {}
with open(wav_scp_file, 'r') as fh:
content = fh.readlines()
for line in content:
line = line.strip('\n')
(utt, path) = line.split()
utt2path[utt] = path
return utt2path
|
def main():
random.seed(args.seed)
with open('{}/s1/utt2spk'.format(args.src_dir), 'r') as fh:
content = fh.readlines()
uttlist = []
for line in content:
line = line.strip('\n')
utt = line.split()[0]
uttlist.append(utt)
uttlist.sort()
num_utt_ori = len(uttlist)
... |
class DownstreamExpert(SpeakerExpert):
'\n Basically the same as the speaker utterance expert, except handles the speaker frame-wise label\n '
def __init__(self, upstream_dim, downstream_expert, expdir, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, expdir, *... |
class SpeakerDataset(Dataset):
def __init__(self, split, bucket_size, libri_root, split_file, bucket_file, sample_rate=16000, train_dev_seed=1337, **kwargs):
self.libri_root = libri_root
self.split_file = split_file
self.sample_rate = sample_rate
assert os.path.isdir(bucket_file),... |
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 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):
predicted = self.linear(features)
return predicted
|
class SpeechCommandsBaseDataset(Dataset):
'12-class Speech Commands base dataset.'
def __init__(self):
self.class2index = {CLASSES[i]: i for i in range(len(CLASSES))}
self.class_num = 12
self.data = []
def __getitem__(self, idx):
(class_name, audio_path) = self.data[idx]
... |
class SpeechCommandsDataset(SpeechCommandsBaseDataset):
'Training and validation dataset.'
def __init__(self, data_list, **kwargs):
super().__init__()
data = [((class_name, audio_path) if (class_name in self.class2index.keys()) else ('_unknown_', audio_path)) for (class_name, audio_path) in d... |
class SpeechCommandsTestingDataset(SpeechCommandsBaseDataset):
'Testing dataset.'
def __init__(self, **kwargs):
super().__init__()
self.data = [(class_dir.name, audio_path) for class_dir in Path(kwargs['speech_commands_test_root']).iterdir() if class_dir.is_dir() for audio_path in class_dir.g... |
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: int, downstream_expert: dict, expdir: str, **kwargs):
super(DownstreamExpert, self).__init__()
self.... |
def split_dataset(root_dir: Union[(str, Path)], max_uttr_per_class=((2 ** 27) - 1)) -> Tuple[(List[Tuple[(str, str)]], List[Tuple[(str, str)]])]:
'Split Speech Commands into 3 set.\n \n Args:\n root_dir: speech commands dataset root dir\n max_uttr_per_class: predefined value in the original pa... |
class Model(nn.Module):
'\n Not used in SUPERB Benchmark\n '
def __init__(self, input_dim, output_class_num, **kwargs):
super(Model, self).__init__()
hidden_dim = kwargs['hidden_dim']
self.connector = nn.Linear(input_dim, hidden_dim)
self.fc1 = nn.Linear(hidden_dim, hidd... |
class AdditionalDataset():
@classmethod
def from_tsv(cls, file, key, bpe_tokenizer=None, pre_tokenizer=None):
data = []
with open(file, 'r') as file:
reader = csv.DictReader(file, delimiter='\t', quotechar=None, doublequote=False, lineterminator='\n', quoting=csv.QUOTE_NONE)
... |
class S3prl_SpeechToTextTask(SpeechToTextTask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def load_dataset(self, split, max_feature_len=(- 1), epoch=1, combine=False, **kwargs):
is_train_split = split.startswith('train')
pre_tokenizer = self.build_tokeniz... |
class S3prl_SpeechToTextDatasetCreator(SpeechToTextDatasetCreator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
KEY_SAMPLE_RATE = 'sr'
DEFAULT_SAMPLE_RATE = 16000
@classmethod
def _from_list(cls, split_name: str, is_train_split, samples: List[List[Dict]], data_... |
class S3prl_SpeechToTextDataset(SpeechToTextDataset):
TARGET_RATE = 16000
def __init__(self, *args, srs=Optional[List[int]], upstream_rate=160, max_feature_len=(- 1), **kwargs):
super().__init__(*args, **kwargs)
self.srs = srs
self.max_feature_len = max_feature_len
self.max_wa... |
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 ... |
def verbose(args, text):
if args.verbose:
print(text)
|
def length(s):
return len(s.split())
|
def verbose(args, text):
if args.verbose:
print(text)
|
def create_sentencepiece(filenames, model_type, vocab_size, output_prefix):
sp.SentencePieceTrainer.train(input=','.join(filenames), model_prefix=output_prefix, vocab_size=vocab_size, model_type=model_type, character_coverage=1.0, unk_id=UNK_TOKEN_ID, bos_id=BOS_TOKEN_ID, eos_id=EOS_TOKEN_ID, pad_id=PAD_TOKEN_ID)... |
def verbose(args, text):
if args.verbose:
print(text)
|
class SpeakerVerifi_train(Dataset):
def __init__(self, vad_config, key_list, file_path, meta_data, max_timestep=None, n_jobs=12):
self.roots = file_path
self.root_key = key_list
self.max_timestep = max_timestep
self.vad_c = vad_config
self.dataset = []
self.all_spe... |
class SpeakerVerifi_test(Dataset):
def __init__(self, vad_config, file_path, meta_data):
self.root = file_path
self.meta_data = meta_data
self.necessary_dict = self.processing()
self.vad_c = vad_config
self.dataset = self.necessary_dict['spk_paths']
self.pair_table... |
class DownstreamExpert(nn.Module):
'\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n\n Note 1.\n dataloaders should output in the following format:\n\n [[wav1, wav2, ...], your_other_contents, ...]\n\n where wav1, wav2 .... |
def collect_speaker_ids(roots, speaker_num):
all_speaker = []
all_speaker.extend([f.path for f in os.scandir(roots) if f.is_dir()])
ids = [[speaker.split('/')[(- 3)], speaker.split('/')[(- 1)]] for speaker in all_speaker]
vox1 = []
for id in ids:
if (id[0] == roots.split('/')[(- 2)]):
... |
def construct_dev_speaker_id_txt(dev_speakers, dev_txt_name):
f = open(dev_txt_name, 'w')
for dev in dev_speakers:
f.write(dev)
f.write('\n')
f.close()
return
|
def sample_wavs_and_dump_txt(root, dev_ids, numbers, meta_data_name):
wav_list = []
count_positive = 0
print(f'generate {numbers} sample pairs')
for _ in trange(numbers):
prob = random.random()
if (prob > 0.5):
dev_id_pair = random.sample(dev_ids, 2)
sample1 = '... |
def EER(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)
s = interp1d(fpr, tpr)
a = (lambda x: ((1.0 - x) - interp1d(fpr, tpr)(x)))
eer = brentq(a, 0.0, 1.0)
thresh = interp1d(fpr, thresholds)(eer)
... |
def eer_yist_f(labels, scores):
'\n Args:\n labels: (N,1) with value being 0 or 1\n scores: (N,1) within [-1, 1]\n\n Returns:\n equal_error_rates\n threshold\n '
joints = sorted(zip(scores, labels), key=(lambda x: x[0]))
(sorted_scores, sorted_labels) = zip(*joints)
... |
def _count_labels(counted_so_far, label, label_to_count=0):
return ((counted_so_far + 1) if (label == label_to_count) else counted_so_far)
|
def compute_metrics(input_x_speaker, ylabel):
wav1 = []
wav2 = []
for i in range(len(ylabel)):
wav1.append(input_x_speaker[i].unsqueeze(0))
wav2.append(input_x_speaker[(len(ylabel) + i)].unsqueeze(0))
wav1 = torch.stack(wav1)
wav2 = torch.stack(wav2)
ylabel = torch.stack(ylabel... |
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: int, downstream_expert: dict, expdir: str, **kwargs):
super(DownstreamExpert, self).__init__()
self.... |
class Model(nn.Module):
def __init__(self, input_dim, bottleneck_dim, hidden_dim, **kwargs):
super(Model, self).__init__()
self.connector = nn.Linear(input_dim, bottleneck_dim)
self.fc1 = nn.Linear(bottleneck_dim, hidden_dim)
self.attention_linear = nn.Linear(hidden_dim, 1)
d... |
class QUESST14Dataset(Dataset):
'QUESST 2014 dataset (English-only).'
def __init__(self, split, **kwargs):
assert (split in ['dev', 'eval'])
dataset_root = Path(kwargs['quesst2014_root'])
doc_paths = get_audio_paths(dataset_root, 'language_key_utterances.lst')
query_paths = ge... |
def get_audio_paths(dataset_root_path, lst_name):
'Extract audio paths.'
audio_paths = []
with open(((dataset_root_path / 'scoring') / lst_name)) as f:
for line in f:
(audio_path, lang) = tuple(line.strip().split())
audio_path = re.sub('^.*?\\/', '', audio_path)
... |
class SWS2013Dataset(Dataset):
'SWS 2013 dataset.'
def __init__(self, split, **kwargs):
assert (split in ['dev', 'eval'])
dataset_root = Path(kwargs['sws2013_root'])
split_root = (Path(kwargs['sws2013_scoring_root']) / f'sws2013_{split}')
audio2dur = parse_ecf((split_root / 's... |
def parse_rttm(rttm_path):
'Parse audio and query pairs from *.rttm.'
pattern = re.compile('LEXEME\\s+(sws2013_[0-9]+).*?([0-9]\\.[0-9]+)\\s+([0-9]\\.[0-9]+)\\s+(sws2013_(dev|eval)_[0-9]+)')
query2audios = defaultdict(list)
with open(rttm_path) as fd:
for line in fd:
match = patter... |
def parse_ecf(ecf_path):
'Find audios from sws2013.ecf.xml.'
root = ET.parse(str(ecf_path)).getroot()
audio2dur = {}
for excerpt in root.findall('excerpt'):
audio_name = excerpt.attrib['audio_filename'].replace('Audio/', '').replace('.wav', '')
duration = float(excerpt.attrib['dur'])
... |
def find_queries(query_dir_path):
'Find all queries under sws2013_dev & sws2013_eval.'
pattern = re.compile('(_[0-9]{2})?\\.wav')
query2tensors = defaultdict(list)
for query_path in tqdm(list(query_dir_path.glob('*.wav')), ncols=0, desc='Load queries'):
query_name = pattern.sub('', query_path.... |
def path2segment(filepath, src_dur, tgt_dur, offset):
random_shift = random.uniform(0, (src_dur - tgt_dur))
(audio_tensor, _) = apply_effects_file(str(filepath), [['channels', '1'], ['rate', '16000'], ['norm'], ['pad', f'{tgt_dur}', f'{tgt_dur}'], ['trim', f'{((tgt_dur + offset) + random_shift)}', f'{tgt_dur}... |
def tensor2segment(tensor, tgt_dur, sample_rate=16000):
src_dur = (len(tensor) / sample_rate)
random_shift = random.uniform(0, (src_dur - tgt_dur))
(audio_tensor, _) = apply_effects_tensor(tensor.unsqueeze(0), sample_rate, [['pad', f'{tgt_dur}', f'{tgt_dur}'], ['trim', f'{(tgt_dur + random_shift)}', f'{tg... |
class SWS2013Testset(Dataset):
'SWS 2013 testset.'
def __init__(self, split, **kwargs):
assert (split in ['dev', 'eval'])
scoring_root = Path(kwargs['sws2013_scoring_root'])
audio_names = parse_ecf(((scoring_root / f'sws2013_{split}') / 'sws2013.ecf.xml'))
query_names = parse_... |
def parse_ecf(ecf_path):
'Find audio paths from sws2013.ecf.xml.'
root = ET.parse(str(ecf_path)).getroot()
audio_names = []
for excerpt in root.findall('excerpt'):
audio_name = excerpt.attrib['audio_filename'].replace('Audio/', '').replace('.wav', '')
audio_names.append(audio_name)
... |
def parse_tlist(tlist_path):
'Find audio paths from sws2013_eval.tlist.xml.'
root = ET.parse(str(tlist_path)).getroot()
audio_names = []
for term in root.findall('term'):
audio_names.append(term.attrib['termid'])
return audio_names
|
class DownstreamExpert(PhoneExpert):
'\n Basically the same as the phone linear expert\n '
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs)
delattr(self, 'model')
model_cls = eval(sel... |
def timit_posteriorgram_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def timit_posteriorgram_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return timit_posteriorgram_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def timit_posteriorgram(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://www.dropbox.com/s/fb2hkvetp26wges/convbank.ckpt?dl=1'
return timit_posteriorgram_url(*args, refresh=refresh, ... |
class ConvBank(nn.Module):
def __init__(self, input_dim, output_class_num, kernels, cnn_size, hidden_size, dropout, **kwargs):
super(ConvBank, self).__init__()
self.drop_p = dropout
self.in_linear = nn.Linear(input_dim, hidden_size)
latest_size = hidden_size
self.cnns = nn... |
class UpstreamExpert(nn.Module):
def __init__(self, ckpt, **kwargs):
super(UpstreamExpert, self).__init__()
ckpt = torch.load(ckpt, map_location='cpu')
args = ckpt['Args']
self.upstream = getattr(s3prl.hub, args.upstream)()
self.featurizer = Featurizer(self.upstream, 'last... |
class DownstreamExpert(PhoneExpert):
'\n Basically the same as the phone linear expert\n '
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs)
delattr(self, 'model')
self.model = Model(i... |
class Model(nn.Module):
def __init__(self, input_dim, output_class_num, hidden_size, dropout, **kwargs):
super(Model, self).__init__()
self.in_linear = nn.Linear(input_dim, hidden_size)
self.out_linear = nn.Linear(hidden_size, output_class_num)
self.drop = nn.Dropout(dropout)
... |
class PhoneDataset(Dataset):
def __init__(self, split, bucket_size, data_root, phone_path, bucket_file, sample_rate=16000, train_dev_seed=1337, **kwargs):
super(PhoneDataset, self).__init__()
self.data_root = data_root
self.phone_path = phone_path
self.sample_rate = sample_rate
... |
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):
predicted = self.linear(features)
return predicted
|
class DownstreamExpert(PhoneExpert):
'\n Basically the same as the phone linear expert\n '
def __init__(self, upstream_dim, downstream_expert, **kwargs):
super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs)
delattr(self, 'model')
self.model = Model(i... |
class SpeakerClassifiDataset(Dataset):
def __init__(self, mode, file_path, meta_data, max_timestep=None):
self.root = file_path
self.speaker_num = 1251
self.meta_data = meta_data
self.max_timestep = max_timestep
self.usage_list = open(self.meta_data, 'r').readlines()
... |
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 DownstreamExpert(SpeakerExpert):
'\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__(upstream_dim, downstream_ex... |
class SpeakerVerifi_train(Dataset):
def __init__(self, vad_config, file_path, meta_data, max_timestep=None):
self.roots = file_path
self.root_key = list(self.roots.keys())
self.max_timestep = max_timestep
self.vad_c = vad_config
self.dataset = []
self.all_speakers ... |
class SpeakerVerifi_dev(Dataset):
def __init__(self, vad_config, segment_config, file_path, meta_data):
self.root = file_path
self.meta_data = meta_data
self.segment_config = segment_config
self.vad_c = vad_config
self.pair_dict = self.preprocessing()
cache_path = ... |
class SpeakerVerifi_test(Dataset):
def __init__(self, vad_config, segment_config, file_path, meta_data):
self.root = file_path
self.meta_data = meta_data
self.segment_config = segment_config
self.vad_c = vad_config
self.pair_dict = self.preprocessing()
cache_path =... |
class DownstreamExpert(nn.Module):
'\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n\n Note 1.\n dataloaders should output in the following format:\n\n [[wav1, wav2, ...], your_other_contents, ...]\n\n where wav1, wav2 .... |
def EER(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)
s = interp1d(fpr, tpr)
a = (lambda x: ((1.0 - x) - interp1d(fpr, tpr)(x)))
eer = brentq(a, 0.0, 1.0)
thresh = interp1d(fpr, thresholds)(eer)
... |
def eer_yist_f(labels, scores):
'\n Args:\n labels: (N,1) with value being 0 or 1\n scores: (N,1) within [-1, 1]\n\n Returns:\n equal_error_rates\n threshold\n '
joints = sorted(zip(scores, labels), key=(lambda x: x[0]))
(sorted_scores, sorted_labels) = zip(*joints)
... |
def _count_labels(counted_so_far, label, label_to_count=0):
return ((counted_so_far + 1) if (label == label_to_count) else counted_so_far)
|
def compute_metrics(input_x_speaker, ylabel):
wav1 = []
wav2 = []
for i in range(len(ylabel)):
wav1.append(input_x_speaker[i].unsqueeze(0))
wav2.append(input_x_speaker[(len(ylabel) + i)].unsqueeze(0))
wav1 = torch.stack(wav1)
wav2 = torch.stack(wav2)
ylabel = torch.stack(ylabel... |
class DownstreamExpert(nn.Module):
'\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n\n Note 1.\n dataloaders should output in the following format:\n\n [[wav1, wav2, ...], your_other_contents, ...]\n\n where wav1, wav2 .... |
def collect_speaker_ids(roots, speaker_num):
all_speaker = []
for key in list(roots.keys()):
all_speaker.extend([f.path for f in os.scandir(roots[key]) if f.is_dir()])
ids = [[speaker.split('/')[(- 3)], speaker.split('/')[(- 1)]] for speaker in all_speaker]
vox1 = []
vox2 = []
for id i... |
def construct_dev_speaker_id_txt(dev_speakers, dev_txt_name):
f = open(dev_txt_name, 'w')
for dev in dev_speakers:
f.write(dev)
f.write('\n')
f.close()
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.