code
stringlengths
17
6.64M
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...
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}...