code
stringlengths
17
6.64M
def sample_wavs_and_dump_txt(root, dev_ids, numbers, meta_data_name): wav_list = [] count_positive = 0 for _ in range(numbers): prob = random.random() if (prob > 0.5): dev_id_pair = random.sample(dev_ids, 2) sample1 = '/'.join(random.choice(find_files(os.path.join(r...
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...
def options(only_registered_ckpt: bool=False): all_options = [] for (name, value) in globals().items(): torch_hubconf_policy = ((not name.startswith('_')) and callable(value)) if (torch_hubconf_policy and (name != 'options')): if (only_registered_ckpt and (name.endswith('_local') o...
def main(): try: cls = getattr(problem, sys.argv[1]) except: available_problems = [name for name in dir(problem) if ((not name.startswith('_')) and isinstance(getattr(problem, name), type))] print(traceback.format_exc()) print(f'''Usage: 1. s3prl-main [PROBLEM] -h 2. python3 -m...
def accuracy(xs, ys, item_same_fn=None): if isinstance(xs, (tuple, list)): assert isinstance(ys, (tuple, list)) return _accuracy_impl(xs, ys, item_same_fn) elif isinstance(xs, dict): assert isinstance(ys, dict) keys = sorted(list(xs.keys())) xs = [xs[k] for k in keys] ...
def _accuracy_impl(xs, ys, item_same_fn=None): item_same_fn = (item_same_fn or (lambda x, y: (x == y))) same = [int(item_same_fn(x, y)) for (x, y) in zip(xs, ys)] return (sum(same) / len(same))
def ter(hyps: List[Union[(str, List[str])]], refs: List[Union[(str, List[str])]]) -> float: 'Token error rate calculator.\n\n Args:\n hyps (List[Union[str, List[str]]]): List of hypotheses.\n refs (List[Union[str, List[str]]]): List of references.\n\n Returns:\n float: Averaged token er...
def wer(hyps: List[str], refs: List[str]) -> float: 'Word error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged word error rate overall utterances.\n ' hyps = [h.split(' ') for h in hyps] ...
def per(hyps: List[str], refs: List[str]) -> float: 'Phoneme error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged phoneme error rate overall utterances.\n ' return wer(hyps, refs)
def cer(hyps: List[str], refs: List[str]) -> float: 'Character error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged character error rate overall utterances.\n ' return ter(hyps, refs)
def compute_eer(labels: List[int], scores: List[float]): 'Compute equal error rate.\n\n Args:\n scores (List[float]): List of hypotheses.\n labels (List[int]): List of references.\n\n Returns:\n eer (float): Equal error rate.\n treshold (float): The treshold to accept a target tr...
def compute_minDCF(labels: List[int], scores: List[float], p_target: float=0.01, c_miss: int=1, c_fa: int=1): 'Compute MinDCF.\n Computes the minimum of the detection cost function. The comments refer to\n equations in Section 3 of the NIST 2016 Speaker Recognition Evaluation Plan.\n\n Args:\n sc...
def clean(ref: str) -> str: ref = re.sub('B\\-(\\S+) ', '', ref) ref = re.sub(' E\\-(\\S+)', '', ref) return ref
def parse(hyp: str, ref: str) -> Tuple[(str, str, str, str)]: 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]) i...
def get_slot_dict(hyp: str, ref: str) -> Tuple[(Dict[(str, List[str])], Dict[(str, List[str])])]: (ref_text, hyp_text, ref_slots, hyp_slots) = parse(hyp, ref) ref_slots = ref_slots.split(';') hyp_slots = hyp_slots.split(';') (ref_dict, hyp_dict) = ({}, {}) if (ref_slots[0] != ''): for ref_...
def slot_type_f1(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: F1s = [] for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) if ((len(hyp_dict.keys()) == 0) and (len(ref_dict.keys()) == 0)): F1 = 1.0 elif (len(hyp_dict....
def slot_value_cer(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: (value_hyps, value_refs) = ([], []) for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) for slot in unique_slots: fo...
def slot_value_wer(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: value_hyps = [] value_refs = [] for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) for slot in unique_slots: fo...
def slot_edit_f1(hypothesis: List[str], groundtruth: List[str], loop_over_all_slot: bool, **kwargs) -> float: slot2F1 = {} for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) if loop_over_all_slot: uniq...
def slot_edit_f1_full(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=True, **kwargs)
def slot_edit_f1_part(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=False, **kwargs)
class BeamDecoder(object): 'Beam decoder powered by flashlight.\n\n Args:\n token (str, optional): Path to dictionary file. Defaults to "".\n lexicon (str, optional): Path to lexicon file. Defaults to "".\n lm (str, optional): Path to KenLM file. Defaults to "".\n nbest (int, option...
class FrameLevel(nn.Module): "\n The common frame-to-frame probing model\n\n Args:\n input_size (int): input size\n output_size (int): output size\n hidden_sizes (List[int]): a list of hidden layers' hidden size.\n by default is [256] to project all different input sizes to t...
class UtteranceLevel(nn.Module): "\n Args:\n input_size (int): input_size\n output_size (int): output_size\n hidden_sizes (List[int]): a list of hidden layers' hidden size.\n by default is [256] to project all different input sizes to the same dimension.\n set empty l...
class HearFullyConnectedPrediction(torch.nn.Module): '\n The specific prediction head used in the Hear Benchmark.\n Modified from: https://github.com/hearbenchmark/hear-eval-kit/blob/855964977238e89dfc76394aa11c37010edb6f20/heareval/predictions/task_predictions.py#L142\n\n Args:\n input_size (int)...
class AbsUpstream(nn.Module): '\n The upstream model should follow this interface. Please subclass it.\n ' @property def num_layer(self) -> int: '\n number of hidden states\n ' raise NotImplementedError @property def hidden_sizes(self) -> List[int]: '\...
class AbsFeaturizer(nn.Module): "\n The featurizer should follow this interface. Please subclass it.\n The featurizer's mission is to reduce (standardize) the multiple hidden\n states from :obj:`AbsUpstream` into a single hidden state, so that\n the downstream model can use it as a conventional repres...
class AbsFrameModel(nn.Module): '\n The frame-level model interface.\n ' @property def input_size(self) -> int: raise NotImplementedError @property def output_size(self) -> int: raise NotImplementedError def forward(self, x: torch.FloatTensor, x_len: torch.LongTensor) ...
class AbsUtteranceModel(nn.Module): '\n The utterance-level model interface, which pools the temporal dimension.\n ' @property def input_size(self) -> int: raise NotImplementedError @property def output_size(self) -> int: raise NotImplementedError def forward(self, x: ...
class FrameLevelLinear(FrameLevel): '\n The frame-level linear probing model used in SUPERB Benchmark\n ' def __init__(self, input_size: int, output_size: int, hidden_size: int=256): super().__init__(input_size, output_size, hidden_sizes=[hidden_size])
class MeanPoolingLinear(UtteranceLevel): '\n The utterance-level linear probing model used in SUPERB Benchmark\n ' def __init__(self, input_size: int, output_size: int, hidden_size: int=256): super().__init__(input_size, output_size, hidden_sizes=[hidden_size])
class MeanPooling(nn.Module): '\n Computes Temporal Average Pooling (MeanPooling over time) Module\n ' def __init__(self, input_size: int): super().__init__() self._in_size = input_size @property def input_size(self) -> int: return self._in_size @property def o...
class TemporalStatisticsPooling(nn.Module): '\n TemporalStatisticsPooling\n Paper: X-vectors: Robust DNN Embeddings for Speaker Recognition\n Link: http://www.danielpovey.com/files/2018_icassp_xvectors.pdf\n ' def __init__(self, input_size: int): super().__init__() self._input_siz...
class SelfAttentivePooling(nn.Module): '\n SelfAttentivePooling\n Paper: Self-Attentive Speaker Embeddings for Text-Independent Speaker Verification\n Link: https://danielpovey.com/files/2018_interspeech_xvector_attention.pdf\n ' def __init__(self, input_size: int): super().__init__() ...
class AttentiveStatisticsPooling(nn.Module): '\n AttentiveStatisticsPooling\n Paper: Attentive Statistics Pooling for Deep Speaker Embedding\n Link: https://arxiv.org/pdf/1803.10963.pdf\n ' def __init__(self, input_size: int): super().__init__() self._indim = input_size se...
class PredictorIdentity(nn.Module): '\n This nn module is used as a predictor placeholder for certain SSL problems.\n ' def __init__(self, **kwargs): super(PredictorIdentity, self).__init__() def forward(self, output: Output): '\n Args:\n output (s3prl.Output): An...
class PredictorMockingjay(nn.Module): '\n The predictor model for SSL pre-training tasks.\n Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert.\n ' def __init__(self, config, output_dim, input_dim=None, **kwargs): '\n Args:\n config (TransformerConfig):...
class softmax(nn.Module): '\n The standard softmax loss in an unified interface for all speaker-related softmax losses\n ' def __init__(self, input_size: int, output_size: int): super().__init__() self._indim = input_size self._outdim = output_size self.fc = nn.Linear(in...
class amsoftmax(nn.Module): '\n AMSoftmax\n\n Args:\n input_size (int): The input feature size\n output_size (int): The output feature size\n margin (float): Hyperparameter denotes the margin to the decision boundry\n scale (float): Hyperparameter that scales the cosine value\n ...
class TDNN(nn.Module): '\n TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf.\n\n Context size and dilation determine the frames selected\n (although context size is not really defined in the traditional sense).\n\n For example:\n\n context size 5 and dilatio...
class XVectorBackbone(nn.Module): '\n The TDNN layers the same as in https://danielpovey.com/files/2018_odyssey_xvector_lid.pdf.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1500) The size of the speaker embe...
class _SEModule(nn.Module): def __init__(self, channels, bottleneck=128): super().__init__() self.se = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Conv1d(channels, bottleneck, kernel_size=1, padding=0), nn.ReLU(), nn.Conv1d(bottleneck, channels, kernel_size=1, padding=0), nn.Sigmoid()) def for...
class _Bottle2neck(nn.Module): def __init__(self, inplanes, planes, kernel_size=None, dilation=None, scale=8): super().__init__() width = int(math.floor((planes / scale))) self.conv1 = nn.Conv1d(inplanes, (width * scale), kernel_size=1) self.bn1 = nn.BatchNorm1d((width * scale)) ...
class ECAPA_TDNN(nn.Module): '\n ECAPA-TDNN model as in https://arxiv.org/abs/2005.07143.\n\n Reference code: https://github.com/TaoRuijie/ECAPA-TDNN.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1536) The...
class SpeakerEmbeddingExtractor(nn.Module): '\n The speaker embedding extractor module.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1500) The size of the speaker embedding\n backbone (str): (default, ...
class _UtteranceExtractor(nn.Module): def __init__(self, input_size, output_size): super().__init__() self._indim = input_size self._outdim = output_size self.linear1 = nn.Linear(input_size, output_size) self.linear2 = nn.Linear(output_size, output_size) self.act_f...
class SuperbXvector(nn.Module): '\n The Xvector used in the SUPERB Benchmark with the exact default arguments.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 512) The size of the speaker embedding\n hidd...
class TransformerConfig(object): '\n Configuration class to store the configuration of a `TransformerModel`.\n ' def __init__(self, hidden_size: int=768, num_hidden_layers: int=3, num_attention_heads: int=12, intermediate_size: int=3072, hidden_act: str='gelu', hidden_dropout_prob: float=0.1, attention...
def prune_linear_layer(layer, index, dim=0): '\n Prune a linear layer (a model parameters) to keep only entries in index.\n Return the pruned layer as a new layer with requires_grad=True.\n Used to remove heads.\n ' index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index...
def gelu(x): "\n Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n "...
def swish(x): return (x * torch.sigmoid(x))
class TransformerLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): '\n Construct a layernorm module in the TF style (epsilon inside the square root).\n ' super(TransformerLayerNorm, self).__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) ...
class TransformerInputRepresentations(nn.Module): '\n Construct the input representation from spectrogram, and position encodings.\n ' def __init__(self, config, input_dim): super(TransformerInputRepresentations, self).__init__() self.hidden_size = config.hidden_size self.spec_t...
class TransformerSelfAttention(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerSelfAttention, self).__init__() if ((config.hidden_size % config.num_attention_heads) != 0): raise ValueError(('The hidden size (%d) is not a m...
class TransformerSelfOutput(nn.Module): def __init__(self, config): super(TransformerSelfOutput, self).__init__() self.pre_layer_norm = config.pre_layer_norm self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) ...
class TransformerAttention(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerAttention, self).__init__() self.output_attentions = output_attentions self.pre_layer_norm = config.pre_layer_norm self.self = TransformerSelfA...
class TransformerIntermediate(nn.Module): def __init__(self, config): super(TransformerIntermediate, self).__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act...
class TransformerOutput(nn.Module): def __init__(self, config): super(TransformerOutput, self).__init__() self.pre_layer_norm = config.pre_layer_norm self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) ...
class TransformerLayer(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerLayer, self).__init__() self.output_attentions = output_attentions self.pre_layer_norm = config.pre_layer_norm self.attention = TransformerAttentio...
class TransformerEncoder(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False, **kwargs): super(TransformerEncoder, self).__init__() if (type(config) is dict): config = TransformerConfig(**config) self.output_attentions = output_attention...
class TransformerInitModel(nn.Module): '\n An abstract class to handle weights initialization.\n ' def __init__(self, config, output_attentions, *inputs, **kwargs): super(TransformerInitModel, self).__init__() self.config = config self.output_attentions = output_attentions ...
class TransformerMockingjay(TransformerInitModel): '\n The Transformer model.\n Currently supporting upstreams models of Mockingjay, Tera, and Audio Albert.\n ' def __init__(self, config, input_dim, output_attentions=False, keep_multihead_output=False, with_input_module=True): '\n Arg...
class VqApcLayer(nn.Module): '\n The Vq Layer.\n Currently used in the upstream model of VQ-APC (nn/rnn_apc.py).\n Defines a VQ layer that follows an RNN layer.\n ' def __init__(self, input_size, codebook_size, code_dim, gumbel_temperature): '\n Args:\n input_size (int):...
def get_optimizer(model_params, total_steps, optimizer_config): optimizer_config = copy.deepcopy(optimizer_config) optimizer_name = optimizer_config.pop('name') optimizer = eval(f'get_{optimizer_name}')(model_params, total_steps=total_steps, **optimizer_config) return optimizer
def get_grouped_parameters(model_params): named_params = [] for m in model_params: named_params += list(m.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] grouped_parameters = [{'params': [p for (n, p) in named_params if (not any(((nd in n) for nd in no_decay)))], ...
def get_BertAdam_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = BertAdam(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps) return optimizer
def get_AdamW_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = Lamb(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps, adam=True, correct_bias=True, **kwargs) return opt...
def get_Lamb_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = Lamb(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps, adam=False, correct_bias=False, **kwargs) return op...
def get_Adam(model_params, lr=0.0002, **kwargs): params = [] for m in model_params: params += list(m.parameters()) return Adam(params, lr=lr, betas=(0.9, 0.999))
def get_AdamW(model_params, lr=0.0002, **kwargs): params = [] for m in model_params: params += list(m.parameters()) optimizer = AdamW(params, lr=lr) return optimizer
def get_TorchOptim(model_params, torch_optim_name, **kwargs): params = [] for m in model_params: params += list(m.parameters()) Opt_class = getattr(torch.optim, torch_optim_name) kwargs.pop('total_steps') optim = Opt_class(params, **kwargs) return optim
class AdamW(Optimizer): "\n Implements Adam algorithm with weight decay fix as introduced in\n `Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`__.\n Parameters:\n params (:obj:`Iterable[torch.nn.parameter.Parameter]`):\n Iterable of parameters to optimize or di...
class _LRSchedule(ABC): ' Parent of all LRSchedules here. ' warn_t_total = False def __init__(self, warmup=0.002, t_total=(- 1), **kw): '\n :param warmup: what fraction of t_total steps will be used for linear warmup\n :param t_total: how many training steps (updates) are planned\n...
class ConstantLR(_LRSchedule): def get_lr_(self, progress): return 1.0
class WarmupCosineSchedule(_LRSchedule): '\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Decreases learning rate from 1. to 0. over remaining `1 - warmup` steps following a cosine curve.\n If `cycles` (default=0.5) is different from default, learning rate foll...
class WarmupCosineWithHardRestartsSchedule(WarmupCosineSchedule): '\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n If `cycles` (default=1.) is different from default, learning rate follows `cycles` times a cosine decaying\n learning rate (with hard restarts).\n...
class WarmupCosineWithWarmupRestartsSchedule(WarmupCosineWithHardRestartsSchedule): '\n All training progress is divided in `cycles` (default=1.) parts of equal length.\n Every part follows a schedule with the first `warmup` fraction of the training steps linearly increasing from 0. to 1.,\n followed by ...
class WarmupConstantSchedule(_LRSchedule): '\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Keeps learning rate equal to 1. after warmup.\n ' def get_lr_(self, progress): if (progress < self.warmup): return (progress / self.warmup) ...
class WarmupLinearSchedule(_LRSchedule): '\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Linearly decreases learning rate from 1. to 0. over remaining `1 - warmup` steps.\n ' warn_t_total = True def get_lr_(self, progress): if (progress < self...
class BertAdam(Optimizer): "Implements BERT version of Adam algorithm with weight decay fix.\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1...
class Lamb(Optimizer): "Implements Lamb algorithm.\n It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): ...
def main(): if (not os.path.isdir(KALDI_ROOT)): print('CHANGE THIS TO YOUR OWN KALDI ROOT: ', KALDI_ROOT) exit() if (not os.path.isdir(LIBRI_PATH)): print('Invalid path for the kaldi librispeech dataset: ', LIBRI_PATH) print('Please run the kaldi scripts first! More information...
def main(): if (not os.path.isdir(KALDI_ROOT)): print('CHANGE THIS TO YOUR OWN KALDI ROOT: ', KALDI_ROOT) exit() if (not os.path.isdir(TIMIT_PATH)): print('Invalid path for the kaldi TIMIT dataset: ', TIMIT_PATH) print('Please run the kaldi scripts first! More information are d...
def main(): if (not os.path.isdir(KALDI_PATH)): print('CHANGE THIS TO YOUR OWN KALDI PATH: ', KALDI_PATH) print('Please run the kaldi scripts first to generate kaldi data directory.') exit() if (not os.path.isdir(OUTPUT_DIR)): os.mkdir(OUTPUT_DIR) for s in SETS: pri...
def get_preprocess_args(): parser = argparse.ArgumentParser(description='preprocess arguments for any dataset.') parser.add_argument('-i', '--input_data', default='../LibriSpeech/', type=str, help='Path to your LibriSpeech directory', required=False) parser.add_argument('-o', '--output_path', default='./d...
def extract_length(input_file): torchaudio.set_audio_backend('sox_io') return torchaudio.info(input_file).num_frames
def generate_length(args, tr_set, audio_extension): for (i, s) in enumerate(tr_set): if os.path.isdir(os.path.join(args.input_data, s.lower())): s = s.lower() elif os.path.isdir(os.path.join(args.input_data, s.upper())): s = s.upper() else: assert NotImp...
def main(): args = get_preprocess_args() if ('librilight' in args.input_data.lower()): SETS = (['small', 'medium', 'large'] + ['small-splitted', 'medium-splitted', 'large-splitted']) elif ('librispeech' in args.input_data.lower()): SETS = ['train-clean-100', 'train-clean-360', 'train-other...
def locate_txt(flac): filename = os.path.basename(flac) tags = filename.split('.')[0].split('-') txt_path = os.path.join(os.path.dirname(flac), f'{tags[0]}-{tags[1]}.trans.txt') return txt_path
def get_preprocess_args(): parser = argparse.ArgumentParser(description='preprocess arguments for LibriSpeech dataset.') parser.add_argument('--data_path', default='./data/libri_alignment', type=str, help='Path to raw LibriSpeech alignment') parser.add_argument('--output_path', default='./data/libri_phone...
def phone_preprocess(data_path, output_path, sets, unaligned): print('Data sets :') for (idx, s) in enumerate(sets): print('\t', idx, ':', s) todo_sets = input('Please enter the index for preprocessing sets (seperate w/ space): ') sets = [sets[int(s)] for s in todo_sets.split(' ')] idx = 0...
def time_to_frame(start_time, end_time, phone): phones = [] start_time = int((start_time * sample_rate)) end_time = int((end_time * sample_rate)) (_, hop_length, win_length) = _stft_parameters(sample_rate=sample_rate) h_window = (win_length * 0.5) start_time = ((start_time - h_window) if (star...
def main(): args = get_preprocess_args() if (not os.path.exists(args.output_path)): os.makedirs(args.output_path) try: file = open(os.path.join(args.data_path, 'train-clean-360/unaligned.txt')).readlines() unaligned = [str(line).split('\t')[0].split(' ')[0] for line in file] ...
def boolean_string(s): if (s not in ['False', 'True']): raise ValueError('Not a valid boolean string') return (s == 'True')
def get_preprocess_args(): parser = argparse.ArgumentParser(description='preprocess arguments for any dataset.') parser.add_argument('--output_path', default='./data/', type=str, help='Path to store output', required=False) parser.add_argument('--audio_extention', default='.flac', type=str, help='audio fi...
def acoustic_preprocess(args, tr_set, dim, audio_extention): for (i, s) in enumerate(tr_set): print('') print('Preprocessing data in: ', s, end='') todo = list(Path(os.path.join(args.data_root, s)).rglob(('*' + audio_extention))) print(len(todo), 'audio files found.') if (a...
def main(): args = get_preprocess_args() mel_dim = (num_mels * ((1 + int(args.delta)) + int(args.delta_delta))) mfcc_dim = (num_mfcc * ((1 + int(args.delta)) + int(args.delta_delta))) dim = (num_freq if (args.feature_type == 'linear') else (mfcc_dim if (args.feature_type == 'mfcc') else mel_dim)) ...