File size: 5,395 Bytes
32b2aaa d2b7e94 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa 1df74c6 32b2aaa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
import logging
import os
import random
import warnings
from functools import partial
from typing import Union
import numpy as np
import torch
try:
import augment
except ImportError:
raise ImportError(
"augment is not installed, please install it first using:"
"\npip install git+https://github.com/facebookresearch/WavAugment@54afcdb00ccc852c2f030f239f8532c9562b550e"
)
from .base import Effect
_logger = logging.getLogger(__name__)
_DEBUG = bool(os.environ.get("DEBUG", False))
class AttachableEffect(Effect):
def attach(self, chain: augment.EffectChain) -> augment.EffectChain:
raise NotImplementedError
def apply(self, wav: np.ndarray, sr: int):
chain = augment.EffectChain()
chain = self.attach(chain)
tensor = torch.from_numpy(wav)[None].float() # (1, T)
tensor = chain.apply(
tensor, src_info={"rate": sr}, target_info={"channels": 1, "rate": sr}
)
wav = tensor.numpy()[0] # (T,)
return wav
class SoxEffect(AttachableEffect):
def __init__(self, effect_name: str, *args, **kwargs):
self.effect_name = effect_name
self.args = args
self.kwargs = kwargs
def attach(self, chain: augment.EffectChain) -> augment.EffectChain:
_logger.debug(
f"Attaching {self.effect_name} with {self.args} and {self.kwargs}"
)
if not hasattr(chain, self.effect_name):
raise ValueError(f"EffectChain has no attribute {self.effect_name}")
return getattr(chain, self.effect_name)(*self.args, **self.kwargs)
class Maybe(AttachableEffect):
"""
Attach an effect with a probability.
"""
def __init__(self, prob: float, effect: AttachableEffect):
self.prob = prob
self.effect = effect
if _DEBUG:
warnings.warn("DEBUG mode is on. Maybe -> Must.")
self.prob = 1
def attach(self, chain: augment.EffectChain) -> augment.EffectChain:
if random.random() > self.prob:
return chain
return self.effect.attach(chain)
class Chain(AttachableEffect):
"""
Attach a chain of effects.
"""
def __init__(self, *effects: AttachableEffect):
self.effects = effects
def attach(self, chain: augment.EffectChain) -> augment.EffectChain:
for effect in self.effects:
chain = effect.attach(chain)
return chain
class Choice(AttachableEffect):
"""
Attach one of the effects randomly.
"""
def __init__(self, *effects: AttachableEffect):
self.effects = effects
def attach(self, chain: augment.EffectChain) -> augment.EffectChain:
return random.choice(self.effects).attach(chain)
class Generator:
def __call__(self) -> str:
raise NotImplementedError
class Uniform(Generator):
def __init__(self, low, high):
self.low = low
self.high = high
def __call__(self) -> str:
return str(random.uniform(self.low, self.high))
class Randint(Generator):
def __init__(self, low, high):
self.low = low
self.high = high
def __call__(self) -> str:
return str(random.randint(self.low, self.high))
class Concat(Generator):
def __init__(self, *parts: Union[Generator, str]):
self.parts = parts
def __call__(self):
return "".join(
[part if isinstance(part, str) else part() for part in self.parts]
)
class RandomLowpassDistorter(SoxEffect):
def __init__(self, low=2000, high=16000):
super().__init__(
"sinc", "-n", Randint(50, 200), Concat("-", Uniform(low, high))
)
class RandomBandpassDistorter(SoxEffect):
def __init__(self, low=100, high=1000, min_width=2000, max_width=4000):
super().__init__(
"sinc",
"-n",
Randint(50, 200),
partial(self._fn, low, high, min_width, max_width),
)
@staticmethod
def _fn(low, high, min_width, max_width):
start = random.randint(low, high)
stop = start + random.randint(min_width, max_width)
return f"{start}-{stop}"
class RandomEqualizer(SoxEffect):
def __init__(
self,
low=100,
high=4000,
q_low=1,
q_high=5,
db_low: int = -30,
db_high: int = 30,
):
super().__init__(
"equalizer",
Uniform(low, high),
lambda: f"{random.randint(q_low, q_high)}q",
lambda: random.randint(db_low, db_high),
)
class RandomOverdrive(SoxEffect):
def __init__(self, gain_low=5, gain_high=40, colour_low=20, colour_high=80):
super().__init__(
"overdrive", Uniform(gain_low, gain_high), Uniform(colour_low, colour_high)
)
class RandomReverb(Chain):
def __init__(self, deterministic=False):
super().__init__(
SoxEffect(
"reverb",
Uniform(50, 50) if deterministic else Uniform(0, 100),
Uniform(50, 50) if deterministic else Uniform(0, 100),
Uniform(50, 50) if deterministic else Uniform(0, 100),
),
SoxEffect("channels", 1),
)
class Flanger(SoxEffect):
def __init__(self):
super().__init__("flanger")
class Phaser(SoxEffect):
def __init__(self):
super().__init__("phaser")
|