code stringlengths 17 6.64M |
|---|
def test_superb_pr():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestPR(SuperbPR):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_ic():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestIC(SuperbIC):
def default_config(self) -> dict:
config = super().default_config()
config['pr... |
def test_superb_sid():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestSID(SuperbSID):
def default_config(self) -> dict:
config = super().default_config()
config[... |
def test_superb_sd():
with tempfile.TemporaryDirectory() as tempdir:
secs = [10, 2, 1, 8, 5]
with pseudo_audio(secs) as (wav_paths, num_samples):
class TestSD(SuperbSD):
def default_config(self) -> dict:
config = super().default_config()
... |
def test_superb_asv():
with tempfile.TemporaryDirectory() as tempdir:
secs = [10, 2, 1, 8, 5]
with pseudo_audio(secs) as (wav_paths, num_samples):
class TestASV(SuperbASV):
def default_config(self) -> dict:
config = super().default_config()
... |
@pytest.mark.parametrize('vocab_type', ['subword', 'character'])
def test_superb_sf(vocab_type):
if (vocab_type == 'subword'):
vocab_args = {'vocab_size': 22}
else:
vocab_args = {}
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num... |
def test_audio_info():
with pseudo_audio([3.0, 4.1, 1.1]) as (paths, num_samples):
infos = get_audio_info(paths, [Path(path).stem for path in paths])
assert (infos[0]['num_frames'] == (3 * 16000))
|
@pytest.mark.parametrize('duplicate', [10000, 100000])
def test_balanced_weighted_sampler(duplicate: int):
labels = ['a', 'a', 'b', 'a']
batch_size = 5
prev_diff_ratio = 1.0
sampler = BalancedWeightedSampler(labels, batch_size=batch_size, duplicate=duplicate, seed=0)
indices = list(sampler)
as... |
@pytest.mark.extra_dependency
def test_beam_decoder():
decoder = BeamDecoder()
emissions = torch.randn((4, 100, 31))
emissions = torch.log_softmax(emissions, dim=2)
hyps = decoder.decode(emissions)
|
def _download_with_timeout(timeout: float, num_process: int):
processes = []
for _ in range(num_process):
process = Process(target=_urls_to_filepaths, args=(URL,), kwargs=dict(refresh=True))
process.start()
processes.append(process)
exitcodes = []
for process in processes:
... |
def test_download():
filepath = Path(_urls_to_filepaths(URL, download=False))
if filepath.is_file():
os.remove(filepath)
logger.info('This should timeout')
_download_with_timeout(0.1, 2)
assert (not filepath.is_file()), 'The download should failed due to the too short timeout second: 0.1 s... |
@pytest.mark.corpus
@pytest.mark.parametrize('fold_id', [0, 1, 2, 3, 4])
def test_er_dataset(fold_id):
v3_er_folder = (((Path(__file__).parent.parent / 's3prl') / 'downstream') / 'emotion')
IEMOCAP = dotenv_values()['IEMOCAP']
with (v3_er_folder / 'config.yaml').open() as file:
config = yaml.load(... |
@pytest.mark.corpus
def test_fluent_commands():
config = dotenv_values()
dataset_root = config['FluentSpeechCommands']
dataset = FluentSpeechCommands(dataset_root)
dataset.data_split_ids
dataset.data_split
dataset.all_data
|
def test_chunking():
chunks = list(chunking(0.0, 8.5, 2.0, 1.0, False))
assert (len(chunks) == 7)
chunks = list(chunking(1.1, 8.5, 2.0, 1.0, True))
assert (len(chunks) == 8)
|
def test_frame_tensor_label():
labels = [(0, 3.0, 4.1), (1, 1.2, 3.2)]
label = chunk_labels_to_frame_tensor_label(1.5, 4.0, labels, 3, 160)
assert (label[((- 1), 0)] == 1)
assert (label[(0, 1)] == 1)
|
def test_g2p():
g2p = G2P()
char_sent = 'HELLO WORLD'
phn_sent = g2p.encode(char_sent)
logging.info(phn_sent)
|
@pytest.mark.corpus
def test_librispeech_dataset():
config = dotenv_values()
dataset_root = config['LibriSpeech']
dataset = LibriSpeech(dataset_root, train_split=['train-clean-100', 'train-clean-360'], valid_split=['dev-clean', 'dev-other'], test_split=['test-clean', 'test-other'])
data = dataset.all_... |
@pytest.mark.corpus
def test_librilight():
config = dotenv_values()
train_corpus = LibriLight(config['LibriLight'])
eval_corpus = LibriSpeech(config['LibriSpeech'], 4, [])
train_data = train_corpus.all_data
(_, valid_data, test_data) = eval_corpus.data_split
assert (len(train_data) == 48)
|
def test_FrameLevel(helpers):
module = FrameLevel(3, 4, [5, 6])
x = torch.randn(32, 10, 3)
x_len = (torch.ones(32) * 3).long()
(h, hl) = module(x, x_len)
|
def test_load_audio():
with pseudo_audio([3.0, 4.0, 5.2]) as (paths, num_frames):
dataset = LoadAudio(paths, [None, 1.0, 3.1], [None, 3.2, None], max_secs=4.2)
for item in dataset:
assert isinstance(item['wav'], torch.Tensor)
|
def isclose(x: float, y: float) -> float:
return (abs((x - y)) < 1e-09)
|
def test_metric():
hyps = ['a ac abb d']
refs = ['a ab abc d']
assert isclose(cer(hyps, refs), 0.2)
assert isclose(wer(hyps, refs), 0.5)
assert isclose(per(hyps, refs), 0.5)
|
@pytest.mark.parametrize('pooling_type', ['MeanPooling', 'TemporalStatisticsPooling', 'AttentiveStatisticsPooling', 'SelfAttentivePooling'])
def test_utterance_level_with_pooling(pooling_type: str):
model = UtteranceLevel(256, 64, [128], 'ReLU', None, pooling_type, None)
output = model(torch.randn(32, 100, 25... |
@pytest.mark.corpus
def test_quesst14_for_qbe():
def quesst14_for_qbe(dataset_root: str):
corpus = Quesst14(dataset_root)
def path_to_dict(path: str):
return dict(wav_path=path)
return dict(all_data={Path(path).stem: path_to_dict(path) for path in ((corpus.valid_queries + cor... |
def test_rnn(helpers):
modules = [RNNEncoder(input_size=8, output_size=6, module='LSTM', hidden_size=[10, 10, 10], dropout=[0.1, 0.1, 0.1], layer_norm=[True, True, True], proj=[True, True, True], sample_rate=[1, 2, 1], sample_style='drop', bidirectional=True), RNNEncoder(input_size=8, output_size=6, module='LSTM'... |
def _merge_batch_indices(batch_indices):
all_indices = []
for indices in batch_indices:
all_indices += indices
return all_indices
|
@pytest.mark.parametrize('world_size', [1, 2, 3, 4, 5, 6, 7, 8])
def test_distributed_sampler(world_size):
sampler = [[1, 2, 3], [4, 5, 6, 7], [8], [9, 10]]
ddp_indices = []
for rank in range(world_size):
ddp_sampler = DistributedBatchSamplerWrapper(sampler, world_size, rank)
ddp_indices +... |
@pytest.mark.parametrize('batch_size', [1, 2, 3, len(data)])
def test_FixedBatchSizeBatchSampler(batch_size):
dataset = data
iter1 = list(iter(FixedBatchSizeBatchSampler(dataset, batch_size, shuffle=False)))
iter2 = list(iter(FixedBatchSizeBatchSampler(dataset, batch_size, shuffle=True)))
indices1 = s... |
@pytest.mark.corpus
def test_snips():
config = dotenv_values()
dataset_root = config['SNIPS']
dataset = SNIPS(dataset_root, ['Ivy', 'Joanna', 'Joey', 'Justin', 'Kendra', 'Kimberly', 'Matthew', 'Salli'], ['Aditi', 'Amy', 'Geraint', 'Nicole'], ['Brian', 'Emma', 'Raveena', 'Russell'])
(train_data, valid_... |
def test_sorted_slice_sampler():
batch_size = 16
max_length = (16000 * 5)
lengths = [random.randint((16000 * 3), (16000 * 8)) for index in range(1000)]
sampler = SortedSliceSampler(lengths, batch_size=batch_size, max_length=max_length)
for epoch in range(5):
sampler.set_epoch(epoch)
... |
def test_sorted_bucketing_sampler():
batch_size = 16
max_length = (16000 * 5)
lengths = [random.randint((16000 * 3), (16000 * 8)) for index in range(1000)]
sampler = SortedBucketingSampler(lengths, batch_size=batch_size, max_length=max_length, shuffle=False)
for epoch in range(5):
sampler.... |
def test_sox_effect():
effects = [['channels', '1'], ['rate', '16000'], ['gain', '-3.0']]
with tempfile.NamedTemporaryFile() as file:
tensor = torch.randn(1, (16000 * 10))
filename = f'{file.name}.wav'
torchaudio.save(filename, tensor, SAMPLE_RATE)
(wav1, sr1) = torchaudio.sox_... |
def test_specaug_model():
model = FrameLevelLinear(input_size=13, output_size=25, hidden_size=32)
model = ModelWithSpecaug(model)
assert (model.specaug.apply_time_mask == True)
assert (model.specaug.apply_freq_mask == True)
|
def _class_counter(data_dict):
counter = Counter()
for (data_id, data) in data_dict.items():
counter.update([data['class_name']])
return counter
|
@pytest.mark.corpus
def test_speech_commands():
env = dotenv_values()
corpus = SpeechCommandsV1(env['GSC1'], env['GSC1_TEST'])
all_data = corpus.all_data
classes = set([value['class_name'] for (key, value) in all_data.items()])
assert (len(classes) == 12), f'{classes}'
(train, valid, test) = c... |
def test_tokenizer():
char_tokenizer = CharacterTokenizer()
phone_tokenizer = default_phoneme_tokenizer()
char_text = 'HELLO WORLD'
char_text_enc = char_tokenizer.encode(char_text)
char_text_dec = char_tokenizer.decode(char_text_enc)
assert isinstance(char_text_enc, list)
assert (char_text... |
def test_version():
s3prl.__version__
|
def is_same_vocab(vocabs_1, vocabs_2):
if (len(vocabs_1) != len(vocabs_2)):
return False
for (v1, v2) in zip(vocabs_1, vocabs_2):
if (v1 != v2):
return False
return True
|
@pytest.mark.corpus
def test_vocabulary():
config = dotenv_values()
corpus = LibriSpeech(config['LibriSpeech'])
text_list = corpus.data_dict['train-clean-100']['text_list']
with tempfile.TemporaryDirectory() as directory:
logging.info(directory)
text_file = os.path.join(directory, 'tex... |
@pytest.mark.corpus
@pytest.mark.parametrize('use_cache', [False, True])
def test_voxceleb1sid(use_cache):
config = dotenv_values()
voxceleb1 = Path(config['VoxCeleb1'])
if voxceleb1.is_dir():
(train_data, valid_data, test_data) = VoxCeleb1SID(voxceleb1).data_split
else:
raise ValueErr... |
def extract_single_name(name: str, ckpt: str, legacy: bool, output_dir: str, device: str, refresh: bool=False):
output_dir: Path = Path(output_dir)
output_dir.mkdir(exist_ok=True, parents=True)
output_path = str((output_dir / f'{name}.pt').resolve())
if (Path(output_path).is_file() and (not refresh)):... |
def load_valid_paths():
with open('./valid_paths.txt', 'r') as fp:
paths = [line.strip() for line in fp if (line.strip() != '')]
return paths
|
def get_third_party():
txt_files = list(Path('./requirements').rglob('*.txt'))
package_list = []
for file in txt_files:
with open(file, 'r') as fp:
for line in fp:
line = line.strip()
if (line == ''):
continue
package_... |
def run_command(command: str):
try:
check_output(command.split(' '))
except CalledProcessError as e:
print(e.output.decode('utf-8'))
raise
|
def main():
parser = argparse.ArgumentParser()
parser.add_argument('files', type=str, nargs='*', default=[], help='If no file is given, use the files under ./valid_paths.txt')
parser.add_argument('--check', action='store_true', help='Only checks the files')
args = parser.parse_args()
if (len(args.... |
def linkcode_resolve(domain, info):
def find_source():
obj = sys.modules[info['module']]
for part in info['fullname'].split('.'):
obj = getattr(obj, part)
if isinstance(obj, property):
return None
file_parts = Path(inspect.getsourcefile(obj)).parts
... |
class LowResourceLinearSuperbASR(SuperbASR):
def prepare_data(self, prepare_data: dict, target_dir: str, cache_dir: str, get_path_only=False):
(train_path, valid_path, test_paths) = super().prepare_data(prepare_data, target_dir, cache_dir, get_path_only)
df = pd.read_csv(train_path)
df = ... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('problem', help='The problem module. E.g. `s3prl.problem.ssl.tera.Tera`')
parser.add_argument('dataset_root', help='The dataset root for pretrain.')
parser.add_argument('save_to', help='The directory to save checkpoint')
pars... |
def main():
logging.basicConfig(level=logging.INFO)
(problem, config) = parse_args()
save_to = Path(config.save_to)
save_to.mkdir(exist_ok=True, parents=True)
body = problem.Body(**config.Body)
head = problem.Head(**config.Head)
loss = problem.Loss(**config.Loss)
stats = Container()
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('upstream', help='The upstream name. E.g. wav2vec2')
parser.add_argument('problem', help='The problem module. E.g. s3prl.problem.SuperbSID')
parser.add_argument('dataset_root', help='The dataset root of your problem.')
parser... |
def main():
logging.basicConfig(level=logging.INFO)
(problem, config) = parse_args()
save_to = Path(config.save_to)
save_to.mkdir(exist_ok=True, parents=True)
upstream = S3PRLUpstream(config.upstream, config.feature_selection)
stats = Container(upstream_rate=upstream.downsample_rate)
logge... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('load_from', help='The directory containing all the checkpoints')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
load_from = Path(args.load_from)
task: Task = Object.load_checkpoint((load_from / 'task.ckpt')).to(device)
task.eval()
test_dataset: Dataset = Object.load_checkpoint((load_from / 'test_dataset.ckpt'))
test_dataloader = test_dataset.to_dataloader(batch_size=1, nu... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('librispeech', help='The root directory of LibriSpeech')
parser.add_argument('save_to', help='The directory to save checkpoint')
parser.add_argument('--total_steps', type=int, default=200000)
parser.add_argument('--log_step',... |
def main():
logging.basicConfig()
logger.setLevel(logging.INFO)
args = parse_args()
librispeech = Path(args.librispeech)
assert librispeech.is_dir()
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('librispeech', help='The root directory of LibriSpeech')
parser.add_argument('save_to', help='The directory to save checkpoint')
parser.add_argument('--total_steps', type=int, default=200000)
parser.add_argument('--log_step',... |
def main():
logging.basicConfig(level=logging.INFO)
args = parse_args()
librispeech = Path(args.librispeech)
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.Preprocessor(librispeech)
logger.info('Prepa... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('load_from', help='The directory containing all the checkpoints')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
load_from = Path(args.load_from)
task: Task = Object.load_checkpoint((load_from / 'task.ckpt')).to(device)
task.eval()
test_dataset: Dataset = Object.load_checkpoint((load_from / 'test_dataset.ckpt'))
test_dataloader = test_dataset.to_dataloader(batch_size=1, nu... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('voxceleb1', help='The root directory of VoxCeleb1')
parser.add_argument('save_to', help='The directory to save checkpoint')
parser.add_argument('--total_steps', type=int, default=200000)
parser.add_argument('--log_step', typ... |
def main():
logging.basicConfig()
logger.setLevel(logging.INFO)
args = parse_args()
voxceleb1 = Path(args.voxceleb1)
assert voxceleb1.is_dir()
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.Prepro... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('voxceleb1', help='The root directory of VoxCeleb1')
parser.add_argument('save_to', help='The directory to save checkpoint')
parser.add_argument('--total_steps', type=int, default=200000)
parser.add_argument('--log_step', typ... |
def main():
logging.basicConfig(level=logging.INFO)
args = parse_args()
voxceleb1 = Path(args.voxceleb1)
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.Preprocessor(voxceleb1)
logger.info('Preparing t... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--load_from', type=str, default='result/sv', help='The directory containing all the checkpoints')
args = parser.parse_args()
return args
|
def main():
args = parse_args()
load_from = Path(args.load_from)
task: Task = Object.load_checkpoint((load_from / 'task.ckpt')).to(device)
task.eval()
test_dataset: Dataset = Object.load_checkpoint((load_from / 'test_dataset.ckpt'))
test_dataloader = DataLoader(test_dataset, batch_size=1, num_... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--voxceleb1', type=str, default='/work/jason410/PublicData/Voxceleb1', help='The root directory of VoxCeleb1')
parser.add_argument('--save_to', type=str, default='result/sv', help='The directory to save checkpoint')
parser.add_a... |
def main():
logging.basicConfig()
logger.setLevel(logging.INFO)
args = parse_args()
voxceleb1 = Path(args.voxceleb1)
assert voxceleb1.is_dir()
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.Prepro... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--voxceleb1', type=str, default='/work/jason410/PublicData/Voxceleb1', help='The root directory of VoxCeleb1')
parser.add_argument('--save_to', type=str, default='lightning_result/sv', help='The directory to save checkpoint')
pa... |
def main():
logging.basicConfig()
logger.setLevel(logging.INFO)
args = parse_args()
voxceleb1 = Path(args.voxceleb1)
assert voxceleb1.is_dir()
save_to = Path(args.save_to)
save_to.mkdir(exist_ok=True, parents=True)
logger.info('Preparing preprocessor')
preprocessor = problem.Prepro... |
def default_collate_fn(samples, padding_value: int=0):
'\n Each item in **DynamicItemDataset** is a dict\n This function pad (or transform into numpy list) a batch of dict\n\n Args:\n samples (List[dict]): Suppose each Container is in\n\n .. code-block:: yaml\n\n wav: a s... |
class Corpus():
@property
@abc.abstractmethod
def all_data(self) -> dict:
raise NotImplementedError
@property
@abc.abstractmethod
def data_split_ids(self):
raise NotImplementedError
@property
def data_split(self):
(train_ids, valid_ids, test_ids) = self.data_... |
class FluentSpeechCommands(Corpus):
'\n Parse the Fluent Speech Command dataset\n\n Args:\n dataset_root: (str) The dataset root of Fluent Speech Command\n '
def __init__(self, dataset_root: str, n_jobs: int=4) -> None:
self.dataset_root = Path(dataset_root)
self.train = self.... |
class IEMOCAP(Corpus):
'\n Parse the IEMOCAP dataset\n\n Args:\n dataset_root: (str) The dataset root of IEMOCAP\n '
def __init__(self, dataset_root: str, n_jobs: int=4) -> None:
self.dataset_root = Path(dataset_root)
self.sessions = [self._preprocess_single_session(self.datas... |
def read_text(file: Path) -> str:
src_file = ('-'.join(str(file).split('-')[:(- 1)]) + '.trans.txt')
idx = file.stem.replace('.flac', '')
with open(src_file, 'r') as fp:
for line in fp:
if (idx == line.split(' ')[0]):
return line[:(- 1)].split(' ', 1)[1]
logging.war... |
def check_no_repeat(splits: List[str]) -> bool:
count = defaultdict(int)
for split in splits:
count[split] += 1
repeated = ''
for (key, val) in count.items():
if (val > 1):
repeated += f' {key} ({val} times)'
if (len(repeated) != 0):
logging.warning(f'Found repe... |
def _parse_spk_to_gender(speaker_file: Path) -> dict:
speaker_file = Path(speaker_file)
with speaker_file.open() as file:
lines = [line.strip() for line in file.readlines()]
for line_id in range(len(lines)):
line = lines[line_id]
if (('SEX' in line) and ('SUBSET' in line) and ('MIN... |
class LibriLight(Corpus):
def __init__(self, dataset_root: str, n_jobs: int=4, train_split: str='10m-fold0') -> None:
self.dataset_root = Path(dataset_root).resolve()
self.train_split = train_split
if (train_split == '10h'):
roots = [(self.dataset_root / '1h'), (self.dataset_r... |
def read_text(file: Path) -> str:
src_file = ('-'.join(str(file).split('-')[:(- 1)]) + '.trans.txt')
idx = file.stem.replace('.flac', '')
with open(src_file, 'r') as fp:
for line in fp:
if (idx == line.split(' ')[0]):
return line[:(- 1)].split(' ', 1)[1]
logger.warn... |
def check_no_repeat(splits: List[str]) -> bool:
count = defaultdict(int)
for split in splits:
count[split] += 1
repeated = ''
for (key, val) in count.items():
if (val > 1):
repeated += f' {key} ({val} times)'
if (len(repeated) != 0):
logger.warning(f'Found repea... |
def _parse_spk_to_gender(speaker_file: Path) -> dict:
speaker_file = Path(speaker_file)
with speaker_file.open() as file:
lines = [line.strip() for line in file.readlines()]
for line_id in range(len(lines)):
line = lines[line_id]
if (('SEX' in line) and ('SUBSET' in line) and ('MIN... |
class LibriSpeech(Corpus):
'LibriSpeech Corpus\n Link: https://www.openslr.org/12\n\n Args:\n dataset_root (str): Path to LibriSpeech corpus directory.\n n_jobs (int, optional): Number of jobs. Defaults to 4.\n train_split (List[str], optional): Training splits. Defaults to ["train-clea... |
class Quesst14():
def __init__(self, dataset_root: str):
dataset_root = Path(dataset_root)
self.doc_paths = self._english_audio_paths(dataset_root, 'language_key_utterances.lst')
self.dev_query_paths = self._english_audio_paths(dataset_root, f'language_key_dev.lst')
self.eval_quer... |
class SNIPS(Corpus):
def __init__(self, dataset_root: str, train_speakers: List[str], valid_speakers: List[str], test_speakers: List[str]) -> None:
self.dataset_root = Path(dataset_root)
self.train_speakers = train_speakers
self.valid_speakers = valid_speakers
self.test_speakers =... |
class SpeechCommandsV1(Corpus):
"\n Args:\n dataset_root (str): should contain a 'dev' sub-folder for the training/validation set\n and a 'test' sub-folder for the testing set\n "
def __init__(self, gsc1: str, gsc1_test: str, n_jobs: int=4) -> None:
train_dataset_root = Path(g... |
class VoxCeleb1SID(Corpus):
def __init__(self, dataset_root: str, n_jobs: int=4, cache_root: str=CACHE_ROOT) -> None:
self.dataset_root = Path(dataset_root).resolve()
uid2split = self._get_standard_usage(self.dataset_root, cache_root)
self._split2uids = defaultdict(list)
for (uid,... |
class VoxCeleb1SV(Corpus):
def __init__(self, dataset_root: str, download_dir: str, force_download: bool=True) -> None:
self.dataset_root = Path(dataset_root).resolve()
(train_path, valid_path, test_path, speakerid2label) = self.format_path(self.dataset_root, download_dir, force_download)
... |
class Dataset(data.Dataset):
def __len__(self) -> int:
raise NotImplementedError
def __getitem__(self, index: int):
raise NotImplementedError
def getinfo(self, index: int):
raise NotImplementedError
|
class EncodeCategory(Dataset):
def __init__(self, labels: List[str], encoder: CategoryEncoder) -> None:
super().__init__()
self.labels = labels
self.encoder = encoder
def __len__(self):
return len(self.labels)
def __getitem__(self, index: int):
label = self.label... |
class EncodeCategories(Dataset):
def __init__(self, labels: List[List[str]], encoders: CategoryEncoders) -> None:
super().__init__()
self.labels = labels
self.encoders = encoders
def __len__(self):
return len(self.labels)
def __getitem__(self, index: int):
labels... |
class EncodeMultiLabel(Dataset):
def __init__(self, labels: List[List[str]], encoder: CategoryEncoder) -> None:
super().__init__()
self.labels = labels
self.encoder = encoder
def __len__(self):
return len(self.labels)
@staticmethod
def label_to_binary_vector(label_id... |
class EncodeText(Dataset):
def __init__(self, text: List[str], tokenizer: Tokenizer, iob: List[str]=None) -> None:
super().__init__()
self.text = text
self.iob = iob
if (iob is not None):
assert (len(text) == len(iob))
self.tokenizer = tokenizer
def __len_... |
def get_info(dataset, names: List[str], cache_dir: str=None, n_jobs: int=6):
logger.info(f"Getting info from dataset {dataset.__class__.__qualname__}: {' '.join(names)}")
if isinstance(cache_dir, (str, Path)):
logger.info(f'Using cached info in {cache_dir}')
cache_dir: Path = Path(cache_dir)
... |
class CategoryEncoder():
def __init__(self, category: List[str]) -> None:
self.category = list(sorted(set(category)))
def __len__(self) -> int:
return len(self.category)
def encode(self, label: str) -> int:
return self.category.index(label)
def decode(self, index: int) -> s... |
class CategoryEncoders():
def __init__(self, categories: List[List[str]]) -> None:
self.categories = [CategoryEncoder(c) for c in categories]
def __len__(self) -> int:
return sum([len(c) for c in self.categories])
def __iter__(self):
for category in self.categories:
... |
def parse_lexicon(line: str) -> Tuple[(str, List[str])]:
line.replace('\t', ' ')
(word, *phonemes) = line.split()
return (word, phonemes)
|
def read_lexicon_files(file_list: List[str]) -> Dict[(str, List[str])]:
w2p_dict = defaultdict(list)
for file in file_list:
with open(file, 'r') as fp:
lines = [line.strip() for line in fp]
for line in lines:
(word, phonemes) = parse_lexicon(line)
... |
class G2P():
'Grapheme-to-phoneme\n\n Args:\n file_list (List[str], optional): List of lexicon files. Defaults to None.\n allow_unk (bool): If false, raise Error when a word can not be recognized by this basic G2P\n '
def __init__(self, file_list: List[str]=None, allow_unk: bool=False):
... |
class Tokenizer():
def __init__(self):
super().__init__()
@abc.abstractmethod
def encode(self, text: str, iob: str=None) -> List[int]:
raise NotImplementedError
@abc.abstractmethod
def decode(self, idxs: List[int], ignore_repeat: bool=False) -> str:
raise NotImplementedE... |
class CharacterTokenizer(Tokenizer):
'Character tokenizer.'
def __init__(self, vocab_list: List[str]=None):
super().__init__()
if (vocab_list is None):
vocab_list = CHARACTER_VOCAB
for tok in ['<pad>', '<eos>', '<unk>']:
assert (tok not in vocab_list)
s... |
class CharacterSlotTokenizer(Tokenizer):
'Character tokenizer with slots.'
def __init__(self, vocab_list: List[str], slots: List[str]):
super().__init__()
for tok in ['<pad>', '<eos>', '<unk>']:
assert (tok not in vocab_list)
self._vocab_list = (['<pad>', '<eos>', '<unk>']... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.