|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Create a data preprocess pipeline that can be run with libtorchaudio |
| 4 | +""" |
| 5 | +import os |
| 6 | +import argparse |
| 7 | + |
| 8 | +import torch |
| 9 | +import torchaudio |
| 10 | + |
| 11 | + |
| 12 | +class Pipeline(torch.nn.Module): |
| 13 | + """Example audio process pipeline. |
| 14 | +
|
| 15 | + This example load waveform from a file then apply effects and save it to a file. |
| 16 | + """ |
| 17 | + def __init__(self): |
| 18 | + super().__init__() |
| 19 | + rir, sample_rate = _load_rir() |
| 20 | + self.register_buffer('rir', rir) |
| 21 | + self.rir_sample_rate: int = sample_rate |
| 22 | + |
| 23 | + def forward(self, input_path: str, output_path: str): |
| 24 | + torchaudio.sox_effects.init_sox_effects() |
| 25 | + |
| 26 | + # 1. load audio |
| 27 | + waveform, sample_rate = torchaudio.load(input_path) |
| 28 | + |
| 29 | + # 2. Add background noise |
| 30 | + alpha = 0.01 |
| 31 | + waveform = alpha * torch.randn_like(waveform) + (1 - alpha) * waveform |
| 32 | + |
| 33 | + # 3. Reample the RIR filter to much the audio sample rate |
| 34 | + rir, _ = torchaudio.sox_effects.apply_effects_tensor( |
| 35 | + self.rir, self.rir_sample_rate, effects=[["rate", str(sample_rate)]]) |
| 36 | + rir = rir / torch.norm(rir, p=2) |
| 37 | + rir = torch.flip(rir, [1]) |
| 38 | + |
| 39 | + # 4. Apply RIR filter |
| 40 | + waveform = torch.nn.functional.pad(waveform, (rir.shape[1] - 1, 0)) |
| 41 | + waveform = torch.nn.functional.conv1d(waveform[None, ...], rir[None, ...])[0] |
| 42 | + |
| 43 | + # Save |
| 44 | + torchaudio.save(output_path, waveform, sample_rate) |
| 45 | + |
| 46 | + |
| 47 | +def _create_jit_pipeline(output_path): |
| 48 | + module = torch.jit.script(Pipeline()) |
| 49 | + print("*" * 40) |
| 50 | + print("* Pipeline code") |
| 51 | + print("*" * 40) |
| 52 | + print() |
| 53 | + print(module.code) |
| 54 | + print("*" * 40) |
| 55 | + module.save(output_path) |
| 56 | + |
| 57 | + |
| 58 | +def _get_path(*paths): |
| 59 | + return os.path.join(os.path.dirname(__file__), *paths) |
| 60 | + |
| 61 | + |
| 62 | +def _load_rir(): |
| 63 | + path = _get_path("data", "rir.wav") |
| 64 | + return torchaudio.load(path) |
| 65 | + |
| 66 | + |
| 67 | +def _parse_args(): |
| 68 | + parser = argparse.ArgumentParser(description=__doc__) |
| 69 | + parser.add_argument( |
| 70 | + "--output-path", |
| 71 | + default=_get_path("data", "pipeline.zip"), |
| 72 | + help="Output JIT file." |
| 73 | + ) |
| 74 | + return parser.parse_args() |
| 75 | + |
| 76 | + |
| 77 | +def _main(): |
| 78 | + args = _parse_args() |
| 79 | + _create_jit_pipeline(args.output_path) |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == '__main__': |
| 83 | + _main() |
0 commit comments