code
stringlengths
17
6.64M
def run_cli(): ' ' _ = LightningCLI(save_config_callback=SaveConfigCallbackWanb)
def main(): ' ' load_dotenv() run_cli()
def dataset(): 'CLI entrypoint for the dataset preparation script.' load_dotenv() parser = ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) (parser.add_argument('config', type=str, help='Path to a config file with arguments.'),) parser.add_argument('--prepr...
def verify_dataset(datamodule: LightningDataModule): '\n Verify that all files in the dataset are present.\n ' for split in ['fit', 'validate', 'test']: datamodule.setup(split) if (split == 'fit'): dataset = datamodule.train_dataloader().dataset elif (split == 'valida...
def inference(): '\n Given an input audio, compute reconstruction.\n\n Optionally, can pass in different audio files for sinusoidal, noise, and transient\n embeddings.\n ' load_dotenv() parser = ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parse...
class AudioDataset(Dataset): "\n Dataset of audio files.\n\n Args:\n data_dir: Path to the directory containing the dataset.\n meta_file: Name of the json metadata file.\n sample_rate: Expected sample rate of the audio files.\n num_samples: Expected number of samples in the audio...
class AudioWithParametersDataset(AudioDataset): '\n Dataset of audio pairs with an additional parameter tensor\n\n Args:\n data_dir: Path to the directory containing the dataset.\n meta_file: Name of the json metadata file.\n sample_rate: Expected sample rate of the audio files.\n ...
class AudioDataModule(pl.LightningDataModule): '\n LightningDataModule for the audio dataset. This class is responsible for downloading\n and extracting a preprocessed dataset, or downloading and preprocessing the\n raw audio files if the preprocessed dataset is not available.\n\n Args:\n batch...
class ModalDataModule(AudioDataModule): '\n DataModule for the modal audio dataset. In addition to the origin audio waveform,\n this also contains a synthesized waveform containing only the modal components,\n extracted from the original waveform using sinusoidal modeling.\n\n Dataset items are return...
class FirstOrderDifferenceLoss(torch.nn.Module): '\n A loss function that calculates the first-order difference\n of the input and target tensors and then calculates the L1\n loss between the two. This essentially applies a high-pass\n filter to the signal before calculating the loss, which may\n p...
class WeightedLoss(torch.nn.Module): '\n A loss function that combines and sums weightings of multiple loss functions.\n\n Args:\n losses: A list of loss functions.\n weights: A list of weights for each loss function. Defaults to None, which\n results in equal weighting of all loss ...
class LogSpectralDistance(Metric): '\n Log Spectral Distance (LSD) metric.\n\n Implementation based on https://arxiv.org/abs/1909.06628\n ' full_state_update = False def __init__(self, n_fft=8092, hop_size=64, eps: float=1e-08, **kwargs: Any) -> None: super().__init__(**kwargs) s...
class MFCCError(Metric): '\n MFCC Error\n ' full_state_update = False def __init__(self, sample_rate: int=48000, n_mfcc: int=40, n_fft: int=2048, hop_length: int=128, **kwargs: Any) -> None: super().__init__(**kwargs) self.add_state('mfcc', default=torch.tensor(0.0), dist_reduce_fx=...
class SpectralFluxOnsetError(Metric): '\n Error between spectral flux onset signals\n ' full_state_update = False def __init__(self, n_fft=1024, hop_size=64, **kwargs: Any) -> None: super().__init__(**kwargs) self.add_state('error', default=torch.tensor(0.0), dist_reduce_fx='sum') ...
class Pad(nn.Module): 'Pad a tensor with zeros according to causal or non-causal 1D padding scheme.\n\n Args:\n kernel_size (int): Size of the convolution kernel.\n dilation (int): Dilation factor.\n causal (bool, optional): Whether to use causal padding. Defaults to True.\n ' def ...
class FiLM(nn.Module): 'Feature-wise Linear Modulation layer. Takes an embedding -- usually shared\n between layers -- and applies a linear transformation to get the affine parameters\n of the FiLM transformation.\n\n Args:\n film_embedding_size (int): Size of the FiLM embedding.\n input_ch...
class TFiLM(nn.Module): 'Temporal Feature-wise Linear Modulation layer. Derives affine parameters from a\n decimated version of the input signal, and applies them to the input. Allows the\n model to learn longer-range temporal dependencies.\n ' def __init__(self, channels: int, block_size: int): ...
class GatedActivation(nn.Module): 'Gated activation function for 1D convolutional networks. Expects input of shape\n (batch_size, channels * 2, time).\n ' def forward(self, x: torch.Tensor) -> torch.Tensor: (x1, x2) = x.chunk(2, dim=(- 2)) assert (x1.shape[(- 2)] == x2.shape[(- 2)]), 'I...
class AttentionPooling(nn.Module): def __init__(self, in_features: int, keep_seq_dim: bool=False): super().__init__() self.norm = nn.LayerNorm(in_features) self.query = nn.Parameter(torch.zeros(1, 1, in_features)) self.attn = nn.MultiheadAttention(in_features, 1, bias=False) ...
class _SoundStreamResidualUnit(nn.Module): def __init__(self, width: int, dilation: int, kernel_size: int=7, causal: bool=False, film_conditioning: bool=False, film_embedding_size: int=128, film_batch_norm: bool=False): super().__init__() self.net = nn.Sequential(Pad(kernel_size, dilation, causal...
class _SoundStreamEncoderBlock(nn.Module): def __init__(self, width: int, stride: int, kernel_size: int=7, causal: bool=False, film_conditioning: bool=False, film_embedding_size: int=128, film_batch_norm: bool=False): super().__init__() self.net = nn.ModuleList([_SoundStreamResidualUnit((width //...
class SoundStreamEncoder(nn.Module): 'Convolutional waveform encoder from SoundStream model, without vector\n quantization.\n\n Args:\n input_channels (int): Number of input channels.\n hidden_channels (int): Number of hidden channels.\n output_channels (int): Number of output channels....
class SoundStreamAttentionEncoder(nn.Module): 'SoundStream encoder with attention pooling' def __init__(self, input_channels: int, hidden_channels: int, output_channels: int, **kwargs): super().__init__() self.encoder = SoundStreamEncoder(input_channels, hidden_channels, output_channels, **kw...
def _get_activation(activation: str): if (activation == 'gated'): return GatedActivation() return getattr(nn, activation)()
class _DilatedResidualBlock(nn.Module): 'Temporal convolutional network internal block\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n kernel_size (int): Size of the convolution kernel.\n dilation (int): Dilation factor.\n ...
class TCN(nn.Module): 'Temporal convolutional network\n\n Args:\n in_channels (int): Number of input channels.\n hidden_channels (int): Number of hidden channels.\n out_channels (int): Number of output channels.\n dilation_base (int, optional): Base of the dilation factor. Defaults ...
class ModalSynth(torch.nn.Module): '\n Modal synthesis with given frequencies, amplitudes, and optional phase\n Users linear interpolation to generate the frequency envelope.\n ' def forward(self, params: torch.Tensor, num_samples: int): '\n params: [nb,num_params,num_modes,num_frames...
def modal_synth(freqs: torch.Tensor, amps: torch.Tensor, num_samples: int, phase: Optional[torch.Tensor]=None) -> torch.Tensor: '\n Synthesizes a modal signal from a set of frequencies, phases, and amplitudes.\n\n Args:\n freqs: A 3D tensor of frequencies in angular frequency of shape\n (b...
class TransientTCN(torch.nn.Module): def __init__(self, in_channels: int=1, hidden_channels: int=32, out_channels: int=1, dilation_base: int=2, dilation_blocks: Optional[int]=None, num_layers: int=8, kernel_size: int=13, film_conditioning: bool=False, film_embedding_size: Optional[int]=None, film_batch_norm: boo...
class DrumBlender(pl.LightningModule): '\n LightningModule for kick synthesis from a modal frequency input\n\n # TODO: Alot of these are currently optional to help with testing and devlopment,\n # but they should be required in the future\n\n Args:\n modal_synth (nn.Module): Synthesis model tak...
def download_full_dataset(url: str, bucket: str, metafile: str, output_dir: Union[(str, Path)]) -> None: '\n Download the kick dataset from Cloudflare.\n\n Args:\n url: The URL of the Cloudflare endpoint.\n bucket: The name of the bucket to download from.\n metafile: The name of the met...
def get_file_list_r2(metadata: Dict, bucket: str, s3) -> List: '\n List all objects in subfolders of the R2 bucket.\n\n Args:\n metadata (Dict): The dataset metadata. Contains a list of items and\n their subfolders, which contain the files to download.\n bucket (str): The name of th...
def get_subfolder_filelist_r2(bucket: str, subfolder: str, s3) -> List: '\n List all objects in a subfolder of the R2 bucket. Makes sure to\n handle continuation tokens.\n\n Args:\n bucket (str): The name of the bucket.\n subfolder (str): The subfolder to list files from.\n s3 (boto3...
def download_filelist_r2(file_list: List, output_dir: Path, bucket: str, s3): '\n Download a list of files from the R2 bucket.\n\n Args:\n file_list (List): A list of files to download.\n bucket (str): The name of the bucket.\n s3 (boto3.client): The boto3 client for the R2 bucket.\n ...
def download_file_r2(filename: str, url: str, bucket: str, output: Optional[str]=None): '\n Download a file from an R2 bucket.\n\n Args:\n filename: The name of the file to download.\n url: The URL of the Cloudflare endpoint.\n bucket: The name of the bucket.\n output (optional):...
def upload_file_r2(filename: str, url: str, bucket: str): '\n Upload a file to the R2 bucket.\n\n Args:\n filename (str): The name of the file to upload.\n url (str): The URL of the Cloudflare endpoint.\n bucket (str): The name of the bucket.\n ' s3 = boto3.client('s3', endpoint_...
class R2ProgressPercentage(): '\n A class to track the progress of a file upload to the R2 bucket.\n https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html # noqa: E501\n\n Args:\n filename: The name of the file being transferred.\n upload: Whether the file is...
def get_files_from_folders(basedir: str, folders: Union[(Dict, List[str])], pattern: str) -> List: '\n List all files in a list of folders.\n\n Args:\n folders (List[str]): A list of folders to search for files.\n pattern (str): The pattern to search for. E.g. "*.wav"\n ' file_list = []...
def create_tarfile(output_file: str, source_dir: str): '\n Create a tarfile from a directory.\n\n Args:\n output_file: The name of the tarfile to create.\n source_dir: The directory to create the tarfile from.\n ' with tarfile.open(output_file, 'w:gz') as tar: for item in tqdm(l...
def str2int(s: str) -> int: '\n Convert string to int using hex hashing.\n https://stackoverflow.com/a/16008760/82733\n ' return (int(hashlib.sha1(s.encode('utf-8')).hexdigest(), 16) % ((2 ** 32) - 1))
def load_model(config: str, ckpt: str, include_data: bool=False): '\n Load model from checkpoint\n ' config_parser = ArgumentParser() config_parser.add_subclass_arguments(DrumBlender, 'model', fail_untyped=False) config_parser.add_argument('--trainer', type=dict, default={}) config_parser.ad...
def load_datamodule(config: str): '\n Load a datamodule from a config file\n ' datamodule_parser = ArgumentParser() datamodule_parser.add_subclass_arguments(AudioDataModule, 'datamodule') if (config is not None): with open(config, 'r') as f: config = yaml.safe_load(f) ...
def load_config_yaml(config: str): '\n Load a config file\n ' with open(config, 'r') as f: config = yaml.safe_load(f) return config
def main(arguments): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('indir', help='Input dir -- root log dir for metric csvs', type=str) parser.add_argument('type', help="Table type: ['all', 'instrument']", type=str) pars...
def pytest_sessionstart(session): wandb.init(mode='disabled')
def import_class(class_path: str): (module_path, class_name) = class_path.rsplit('.', 1) module = __import__(module_path, fromlist=[class_name]) return getattr(module, class_name)
def pytest_generate_tests(metafunc): for (test_type, glob_params) in TEST_TYPES.items(): if (test_type in metafunc.fixturenames): files = glob.glob(**glob_params) metafunc.parametrize(test_type, files)
@pytest.fixture def parser(): parser = LightningArgumentParser() return parser
def read_cfg(cfg: os.PathLike, wrap: Optional[str]='cfg'): with open(cfg, 'r') as f: cfg_string = f.read() if (wrap is not None): cfg_string = f'''{wrap}: {cfg_string}''' cfg_string = cfg_string.replace('\n', '\n ') return cfg_string
def test_can_instantiate_from_data_config(data_cfg, parser): cfg_string = read_cfg(data_cfg) parser.add_lightning_class_args(LightningDataModule, 'cfg', subclass_mode=True, required=True) args = parser.parse_string(cfg_string) assert ('class_path' in args.cfg), 'No class_path key in config root level'...
def test_can_instantiate_from_loss_config(loss_cfg, parser): cfg_string = read_cfg(loss_cfg) parser.add_argument('cfg', type=Union[(Callable, torch.nn.Module)]) args = parser.parse_string(cfg_string) assert ('class_path' in args.cfg), 'No class_path key in config root level' class_path = args.cfg[...
def test_can_instantiate_from_model_config(model_cfg, parser): cfg_string = read_cfg(model_cfg) parser.add_argument('cfg', type=torch.nn.Module) args = parser.parse_string(cfg_string) assert ('class_path' in args.cfg), 'No class_path key in config root level' class_path = args.cfg['class_path'] ...
def test_can_instantiate_from_experiment_config(experiment_cfg, monkeypatch): with monkeypatch.context() as m: import sys m.setattr(sys, 'argv', ['fake_file.py', '-c', str(experiment_cfg), '--trainer.accelerator', 'cpu', '--trainer.devices', '1']) cli = LightningCLI(run=False) assert i...
def test_kick_dataset_init_no_data(fs): with pytest.raises(FileNotFoundError): AudioDataset('nonexistent_dir', 'nonexistent_file.json', TEST_SAMPLE_RATE, TEST_NUM_SAMPLES)
def processed_metadata(filename: str): expected_filename = Path(TEST_DATA_DIR).joinpath(TEST_META_FILE) if (filename.name != expected_filename): raise FileNotFoundError metadata = {} for i in range(100): metadata[i] = {'filename': f'kick_{i}.wav', 'sample_pack_key': 'pack_a', 'type': '...
def audio_dataset(fs, mocker, **kwargs): fs.create_dir(TEST_DATA_DIR) fs.create_file(Path(TEST_DATA_DIR).joinpath(TEST_META_FILE)) mocker.patch('json.load', side_effect=processed_metadata) return AudioDataset(TEST_DATA_DIR, TEST_META_FILE, TEST_SAMPLE_RATE, TEST_NUM_SAMPLES, **kwargs)
def test_audio_dataset_init_no_split(fs, mocker): dataset = audio_dataset(fs, mocker) assert (len(dataset.file_list) == 100)
def test_audio_dataset_init_train(fs, mocker): dataset = audio_dataset(fs, mocker, split='train') assert (len(dataset.file_list) == 80)
def test_audio_dataset_init_test(fs, mocker): dataset = audio_dataset(fs, mocker, split='test') assert (len(dataset.file_list) == 10)
def test_audio_dataset_init_val(fs, mocker): dataset = audio_dataset(fs, mocker, split='val') assert (len(dataset.file_list) == 10)
def test_audio_dataset_init_invalid_split(fs, mocker): with pytest.raises(ValueError): audio_dataset(fs, mocker, split='invalid')
def test_audio_dataset_init_reproducible(fs, mocker): dataset_a = audio_dataset(fs, mocker) dataset_b = AudioDataset(TEST_DATA_DIR, TEST_META_FILE, TEST_SAMPLE_RATE, TEST_NUM_SAMPLES) assert (dataset_a.file_list == dataset_b.file_list)
def test_audio_dataset_len(fs, mocker): dataset = audio_dataset(fs, mocker) (len(dataset) == 100)
def test_audio_dataset_getitem(fs, mocker): dataset = audio_dataset(fs, mocker) test_audio = torch.rand(1, TEST_NUM_SAMPLES) mocker = mocker.patch(f'{TESTED_MODULE}.torchaudio.load', return_value=(test_audio, TEST_SAMPLE_RATE)) (audio,) = dataset[0] assert (audio.shape == (1, TEST_NUM_SAMPLES)) ...
@pytest.fixture def sample_pack_split_metadata(): metadata = {} for i in range(100): pack = 'a' if (i >= 80): pack = 'b' if (i >= 90): pack = 'c' metadata[i] = {'filename': i, 'sample_pack_key': pack, 'type': 'electro'} return metadata
def test_audio_dataset_sample_pack_split(fs, mocker, sample_pack_split_metadata): dataset = audio_dataset(fs, mocker, split_strategy='sample_pack') dataset.metadata = sample_pack_split_metadata dataset._sample_pack_split(split='train', test_size=0.1, val_size=0.1) assert (len(dataset.file_list) == 80)...
def test_audio_dataset_sample_pack_split_reproducible(fs, mocker, sample_pack_split_metadata): dataset = audio_dataset(fs, mocker, split_strategy='sample_pack') dataset.metadata = sample_pack_split_metadata dataset._sample_pack_split(split='test', test_size=0.1, val_size=0.1) file_list_a = list(datase...
@pytest.fixture def fakefs(fs, mocker): '\n Fake FS for testing with a mocked tqdm, which behaves\n poorly with fakefs\n ' mocker.patch(f'{TESTED_MODULE}.tqdm', side_effect=(lambda x: x)) return fs
def test_audio_datamodule_init(): AudioDataModule()
def test_audio_datamodule_prepare_download_archive(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = AudioDataModule() data.prepare_data() assert (mocked_download.call_args_list == [m...
def test_audio_datamodule_prepare_datadir_exists(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = AudioDataModule() fs.create_dir(data.data_dir) data.prepare_data() assert (mocke...
def test_audio_datamodule_prepare_archive_exists(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = AudioDataModule() fs.create_file(data.archive) data.prepare_data() assert (mocke...
def test_audio_datamodule_prepare_unprocessed_raise(fs, mocker): data = AudioDataModule() fs.create_dir(data.data_dir) with pytest.raises(RuntimeError): data.prepare_data(use_preprocessed=False)
def test_audio_datamodule_prepare_unprocessed_downloaded(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_full_dataset') mocked_preprocess = mocker.patch(f'{TESTED_MODULE}.AudioDataModule.preprocess_dataset') data = AudioDataModule() fs.create_dir(data.data_dir_unproce...
def test_audio_datamodule_prepare_unprocessed_with_downloaded(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_full_dataset') mocked_preprocess = mocker.patch(f'{TESTED_MODULE}.AudioDataModule.preprocess_dataset') data = AudioDataModule() data.prepare_data(use_preproce...
def unprocessed_metadata(filename: str): data = AudioDataModule() expected_filename = Path(data.data_dir_unprocessed).joinpath(data.meta_file) if (filename.name != expected_filename): raise FileNotFoundError metadata = {'sample_group_1': {'type': 'cool-sounds', 'folders': ['folder1', 'folder2'...
def create_fake_dataset(metadata: dict, num_files: int, fakefs): data = AudioDataModule() for group in metadata.values(): for folder in group['folders']: for i in range(num_files): fakefs.create_file(Path(data.data_dir_unprocessed).joinpath(folder).joinpath(f'file_{i}.wav')...
def expected_hashed_ouput(filename: str, audio_dir: str): file = Path(filename) output_hash = data_utils.str2int(str(Path(*file.parts[1:]))) output_file = Path(audio_dir).joinpath(f'{output_hash}.wav') return output_file
def test_audio_dataset_preprocess(fakefs, mocker): '\n A bit of a complex test to make sure that all functions and files are\n called as expected from the preprocess_dataset class method.\n ' data = AudioDataModule() meta_file = Path(data.data_dir_unprocessed).joinpath(data.meta_file) fakefs....
def test_audio_dataset_archive(mocker): data = AudioDataModule() mocked_archive = mocker.patch(f'{TESTED_MODULE}.data_utils.create_tarfile') data.archive_dataset('test.tar.gz') mocked_archive.assert_called_once_with('test.tar.gz', data.data_dir)
def processed_metadata(filename: str): data = AudioDataModule() expected_filename = Path(data.data_dir).joinpath(data.meta_file) if (filename.name != expected_filename): raise FileNotFoundError metadata = {} for i in range(100): metadata[i] = {'filename': f'kick_{i}.wav', 'sample_p...
@pytest.fixture def kick_datamodule(fs, mocker): data = AudioDataModule() fs.create_dir(data.data_dir) fs.create_file(Path(data.data_dir).joinpath(data.meta_file)) mocker.patch('drumblender.data.audio.json.load', side_effect=processed_metadata) return AudioDataModule()
def test_audio_datamodule_setup_train(kick_datamodule): kick_datamodule.setup('fit') assert (len(kick_datamodule.train_dataset) == 80) assert (len(kick_datamodule.val_dataset) == 10) with pytest.raises(AttributeError): kick_datamodule.test_dataset
def test_audio_datamodule_setup_val(kick_datamodule): kick_datamodule.setup('validate') assert (len(kick_datamodule.val_dataset) == 10) with pytest.raises(AttributeError): kick_datamodule.train_dataset with pytest.raises(AttributeError): kick_datamodule.test_dataset
def test_audio_datamodule_setup_test(kick_datamodule): kick_datamodule.setup('test') assert (len(kick_datamodule.test_dataset) == 10) with pytest.raises(AttributeError): kick_datamodule.train_dataset with pytest.raises(AttributeError): kick_datamodule.val_dataset
def test_audio_datamodule_train_data(kick_datamodule, mocker): kick_datamodule.setup('fit') train_loader = kick_datamodule.train_dataloader() assert isinstance(train_loader, DataLoader) mocker = mocker.patch(f'{TESTED_MODULE}.torchaudio.load', return_value=(torch.rand(1, kick_datamodule.num_samples), ...
def test_modal_datamodule_init(): data = ModalDataModule() assert isinstance(data, ModalDataModule) assert isinstance(data, AudioDataModule)
def test_modal_datamodule_prepare_download_archive(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = ModalDataModule() data.prepare_data() assert (mocked_download.call_args_list == [m...
def test_modal_datamodule_prepare_datadir_exists(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = ModalDataModule() fs.create_dir(data.data_dir) data.prepare_data() assert (mocke...
def test_modal_datamodule_prepare_archive_exists(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2') mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive') data = ModalDataModule() fs.create_file(data.archive) data.prepare_data() assert (mocke...
def test_modal_datamodule_prepare_unprocessed_raise(fs, mocker): data = ModalDataModule() fs.create_dir(data.data_dir) with pytest.raises(RuntimeError): data.prepare_data(use_preprocessed=False)
def test_modal_datamodule_prepare_unprocessed_downloaded(fs, mocker): mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_full_dataset') mocked_preprocess = mocker.patch(f'{TESTED_MODULE}.ModalDataModule.preprocess_dataset') data = ModalDataModule() fs.create_dir(data.data_dir_unproce...
def mock_modal_audio_load(filename, sample_rate, num_samples): filename_parts = Path(filename).parts assert (filename_parts[0] == 'dataset') assert filename_parts[(- 1)].endswith('.wav') return (torch.rand(1, num_samples), sample_rate)
def mock_cqt_call(x, num_samples, num_frames, num_bins): assert (x.shape == (1, num_samples)) freqs = torch.rand(1, num_frames, num_bins) amps = torch.rand(1, num_frames, num_bins) phases = torch.rand(1, num_frames, num_bins) return (freqs, amps, phases)
def processed_modal_metadata(filename: str): data = ModalDataModule() expected_filename = Path(data.data_dir).joinpath(data.meta_file) if (filename.name != expected_filename): raise FileNotFoundError metadata = {} for i in range(100): metadata[i] = {'filename': f'kick_{i}.wav', 'fi...
def mock_json_dump_update(metadata, outfile, expected_outfile): assert (outfile.name == expected_outfile)
def run_preprocess_test(data, fakefs, mocker): '\n Make sure that the modal preprocessing is calling all the right\n methods with the expected inputs and ouputs. This involves mocking\n several methods.\n ' fakefs.create_dir(data.data_dir) fakefs.create_file(Path(data.data_dir).joinpath(data.m...
def test_modal_dataset_preprocess_no_save_audio(fakefs, mocker): '\n Make sure that the modal preprocessing is calling all the right\n methods with the expected inputs and ouputs. This involves mocking\n several methods.\n ' data = ModalDataModule(sample_rate=16000, num_samples=16000, n_bins=64, h...
def test_modal_dataset_preprocess_save_audio(fakefs, mocker): '\n Make sure that the modal preprocessing is calling all the right\n methods with the expected inputs and ouputs. This involves mocking\n several methods.\n ' data = ModalDataModule(sample_rate=16000, num_samples=16000, n_bins=64, hop_...
def kick_modal_datamodule(fs, mocker, **kwargs): data = ModalDataModule(**kwargs) fs.create_dir(data.data_dir) fs.create_file(Path(data.data_dir).joinpath(data.meta_file)) mocker.patch('drumblender.data.audio.json.load', side_effect=processed_modal_metadata) return ModalDataModule(**kwargs)