Spaces:
Running
on
Zero
Running
on
Zero
File size: 52,619 Bytes
71de706 |
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 |
import copy
from contextlib import contextmanager
from inspect import signature
from typing import List
import numpy as np
import torch
from flatten_dict import flatten
from flatten_dict import unflatten
from numpy.random import RandomState
from .. import ml
from ..core import AudioSignal
from ..core import util
from .datasets import AudioLoader
tt = torch.tensor
"""Shorthand for converting things to torch.tensor."""
class BaseTransform:
"""This is the base class for all transforms that are implemented
in this library. Transforms have two main operations: ``transform``
and ``instantiate``.
``instantiate`` sets the parameters randomly
from distribution tuples for each parameter. For example, for the
``BackgroundNoise`` transform, the signal-to-noise ratio (``snr``)
is chosen randomly by instantiate. By default, it chosen uniformly
between 10.0 and 30.0 (the tuple is set to ``("uniform", 10.0, 30.0)``).
``transform`` applies the transform using the instantiated parameters.
A simple example is as follows:
>>> seed = 0
>>> signal = ...
>>> transform = transforms.NoiseFloor(db = ("uniform", -50.0, -30.0))
>>> kwargs = transform.instantiate()
>>> output = transform(signal.clone(), **kwargs)
By breaking apart the instantiation of parameters from the actual audio
processing of the transform, we can make things more reproducible, while
also applying the transform on batches of data efficiently on GPU,
rather than on individual audio samples.
.. note::
We call ``signal.clone()`` for the input to the ``transform`` function
because signals are modified in-place! If you don't clone the signal,
you will lose the original data.
Parameters
----------
keys : list, optional
Keys that the transform looks for when
calling ``self.transform``, by default []. In general this is
set automatically, and you won't need to manipulate this argument.
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
Examples
--------
>>> seed = 0
>>>
>>> audio_path = "tests/audio/spk/f10_script4_produced.wav"
>>> signal = AudioSignal(audio_path, offset=10, duration=2)
>>> transform = tfm.Compose(
>>> [
>>> tfm.RoomImpulseResponse(sources=["tests/audio/irs.csv"]),
>>> tfm.BackgroundNoise(sources=["tests/audio/noises.csv"]),
>>> ],
>>> )
>>>
>>> kwargs = transform.instantiate(seed, signal)
>>> output = transform(signal, **kwargs)
"""
def __init__(self, keys: list = [], name: str = None, prob: float = 1.0):
# Get keys from the _transform signature.
tfm_keys = list(signature(self._transform).parameters.keys())
# Filter out signal and kwargs keys.
ignore_keys = ["signal", "kwargs"]
tfm_keys = [k for k in tfm_keys if k not in ignore_keys]
# Combine keys specified by the child class, the keys found in
# _transform signature, and the mask key.
self.keys = keys + tfm_keys + ["mask"]
self.prob = prob
if name is None:
name = self.__class__.__name__
self.name = name
def _prepare(self, batch: dict):
sub_batch = batch[self.name]
for k in self.keys:
assert k in sub_batch.keys(), f"{k} not in batch"
return sub_batch
def _transform(self, signal):
return signal
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
return {}
@staticmethod
def apply_mask(batch: dict, mask: torch.Tensor):
"""Applies a mask to the batch.
Parameters
----------
batch : dict
Batch whose values will be masked in the ``transform`` pass.
mask : torch.Tensor
Mask to apply to batch.
Returns
-------
dict
A dictionary that contains values only where ``mask = True``.
"""
masked_batch = {k: v[mask] for k, v in flatten(batch).items()}
return unflatten(masked_batch)
def transform(self, signal: AudioSignal, **kwargs):
"""Apply the transform to the audio signal,
with given keyword arguments.
Parameters
----------
signal : AudioSignal
Signal that will be modified by the transforms in-place.
kwargs: dict
Keyword arguments to the specific transforms ``self._transform``
function.
Returns
-------
AudioSignal
Transformed AudioSignal.
Examples
--------
>>> for seed in range(10):
>>> kwargs = transform.instantiate(seed, signal)
>>> output = transform(signal.clone(), **kwargs)
"""
tfm_kwargs = self._prepare(kwargs)
mask = tfm_kwargs["mask"]
if torch.any(mask):
tfm_kwargs = self.apply_mask(tfm_kwargs, mask)
tfm_kwargs = {k: v for k, v in tfm_kwargs.items() if k != "mask"}
signal[mask] = self._transform(signal[mask], **tfm_kwargs)
return signal
def __call__(self, *args, **kwargs):
return self.transform(*args, **kwargs)
def instantiate(
self,
state: RandomState = None,
signal: AudioSignal = None,
):
"""Instantiates parameters for the transform.
Parameters
----------
state : RandomState, optional
_description_, by default None
signal : AudioSignal, optional
_description_, by default None
Returns
-------
dict
Dictionary containing instantiated arguments for every keyword
argument to ``self._transform``.
Examples
--------
>>> for seed in range(10):
>>> kwargs = transform.instantiate(seed, signal)
>>> output = transform(signal.clone(), **kwargs)
"""
state = util.random_state(state)
# Not all instantiates need the signal. Check if signal
# is needed before passing it in, so that the end-user
# doesn't need to have variables they're not using flowing
# into their function.
needs_signal = "signal" in set(signature(self._instantiate).parameters.keys())
kwargs = {}
if needs_signal:
kwargs = {"signal": signal}
# Instantiate the parameters for the transform.
params = self._instantiate(state, **kwargs)
for k in list(params.keys()):
v = params[k]
if isinstance(v, (AudioSignal, torch.Tensor, dict)):
params[k] = v
else:
params[k] = tt(v)
mask = state.rand() <= self.prob
params[f"mask"] = tt(mask)
# Put the params into a nested dictionary that will be
# used later when calling the transform. This is to avoid
# collisions in the dictionary.
params = {self.name: params}
return params
def batch_instantiate(
self,
states: list = None,
signal: AudioSignal = None,
):
"""Instantiates arguments for every item in a batch,
given a list of states. Each state in the list
corresponds to one item in the batch.
Parameters
----------
states : list, optional
List of states, by default None
signal : AudioSignal, optional
AudioSignal to pass to the ``self.instantiate`` section
if it is needed for this transform, by default None
Returns
-------
dict
Collated dictionary of arguments.
Examples
--------
>>> batch_size = 4
>>> signal = AudioSignal(audio_path, offset=10, duration=2)
>>> signal_batch = AudioSignal.batch([signal.clone() for _ in range(batch_size)])
>>>
>>> states = [seed + idx for idx in list(range(batch_size))]
>>> kwargs = transform.batch_instantiate(states, signal_batch)
>>> batch_output = transform(signal_batch, **kwargs)
"""
kwargs = []
for state in states:
kwargs.append(self.instantiate(state, signal))
kwargs = util.collate(kwargs)
return kwargs
class Identity(BaseTransform):
"""This transform just returns the original signal."""
pass
class SpectralTransform(BaseTransform):
"""Spectral transforms require STFT data to exist, since manipulations
of the STFT require the spectrogram. This just calls ``stft`` before
the transform is called, and calls ``istft`` after the transform is
called so that the audio data is written to after the spectral
manipulation.
"""
def transform(self, signal, **kwargs):
signal.stft()
super().transform(signal, **kwargs)
signal.istft()
return signal
class Compose(BaseTransform):
"""Compose applies transforms in sequence, one after the other. The
transforms are passed in as positional arguments or as a list like so:
>>> transform = tfm.Compose(
>>> [
>>> tfm.RoomImpulseResponse(sources=["tests/audio/irs.csv"]),
>>> tfm.BackgroundNoise(sources=["tests/audio/noises.csv"]),
>>> ],
>>> )
This will convolve the signal with a room impulse response, and then
add background noise to the signal. Instantiate instantiates
all the parameters for every transform in the transform list so the
interface for using the Compose transform is the same as everything
else:
>>> kwargs = transform.instantiate()
>>> output = transform(signal.clone(), **kwargs)
Under the hood, the transform maps each transform to a unique name
under the hood of the form ``{position}.{name}``, where ``position``
is the index of the transform in the list. ``Compose`` can nest
within other ``Compose`` transforms, like so:
>>> preprocess = transforms.Compose(
>>> tfm.GlobalVolumeNorm(),
>>> tfm.CrossTalk(),
>>> name="preprocess",
>>> )
>>> augment = transforms.Compose(
>>> tfm.RoomImpulseResponse(),
>>> tfm.BackgroundNoise(),
>>> name="augment",
>>> )
>>> postprocess = transforms.Compose(
>>> tfm.VolumeChange(),
>>> tfm.RescaleAudio(),
>>> tfm.ShiftPhase(),
>>> name="postprocess",
>>> )
>>> transform = transforms.Compose(preprocess, augment, postprocess),
This defines 3 composed transforms, and then composes them in sequence
with one another.
Parameters
----------
*transforms : list
List of transforms to apply
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(self, *transforms: list, name: str = None, prob: float = 1.0):
if isinstance(transforms[0], list):
transforms = transforms[0]
for i, tfm in enumerate(transforms):
tfm.name = f"{i}.{tfm.name}"
keys = [tfm.name for tfm in transforms]
super().__init__(keys=keys, name=name, prob=prob)
self.transforms = transforms
self.transforms_to_apply = keys
@contextmanager
def filter(self, *names: list):
"""This can be used to skip transforms entirely when applying
the sequence of transforms to a signal. For example, take
the following transforms with the names ``preprocess, augment, postprocess``.
>>> preprocess = transforms.Compose(
>>> tfm.GlobalVolumeNorm(),
>>> tfm.CrossTalk(),
>>> name="preprocess",
>>> )
>>> augment = transforms.Compose(
>>> tfm.RoomImpulseResponse(),
>>> tfm.BackgroundNoise(),
>>> name="augment",
>>> )
>>> postprocess = transforms.Compose(
>>> tfm.VolumeChange(),
>>> tfm.RescaleAudio(),
>>> tfm.ShiftPhase(),
>>> name="postprocess",
>>> )
>>> transform = transforms.Compose(preprocess, augment, postprocess)
If we wanted to apply all 3 to a signal, we do:
>>> kwargs = transform.instantiate()
>>> output = transform(signal.clone(), **kwargs)
But if we only wanted to apply the ``preprocess`` and ``postprocess``
transforms to the signal, we do:
>>> with transform_fn.filter("preprocess", "postprocess"):
>>> output = transform(signal.clone(), **kwargs)
Parameters
----------
*names : list
List of transforms, identified by name, to apply to signal.
"""
old_transforms = self.transforms_to_apply
self.transforms_to_apply = names
yield
self.transforms_to_apply = old_transforms
def _transform(self, signal, **kwargs):
for transform in self.transforms:
if any([x in transform.name for x in self.transforms_to_apply]):
signal = transform(signal, **kwargs)
return signal
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
parameters = {}
for transform in self.transforms:
parameters.update(transform.instantiate(state, signal=signal))
return parameters
def __getitem__(self, idx):
return self.transforms[idx]
def __len__(self):
return len(self.transforms)
def __iter__(self):
for transform in self.transforms:
yield transform
class Choose(Compose):
"""Choose logic is the same as :py:func:`audiotools.data.transforms.Compose`,
but instead of applying all the transforms in sequence, it applies just a single transform,
which is chosen for each item in the batch.
Parameters
----------
*transforms : list
List of transforms to apply
weights : list
Probability of choosing any specific transform.
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
Examples
--------
>>> transforms.Choose(tfm.LowPass(), tfm.HighPass())
"""
def __init__(
self,
*transforms: list,
weights: list = None,
name: str = None,
prob: float = 1.0,
):
super().__init__(*transforms, name=name, prob=prob)
if weights is None:
_len = len(self.transforms)
weights = [1 / _len for _ in range(_len)]
self.weights = np.array(weights)
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
kwargs = super()._instantiate(state, signal)
tfm_idx = list(range(len(self.transforms)))
tfm_idx = state.choice(tfm_idx, p=self.weights)
one_hot = []
for i, t in enumerate(self.transforms):
mask = kwargs[t.name]["mask"]
if mask.item():
kwargs[t.name]["mask"] = tt(i == tfm_idx)
one_hot.append(kwargs[t.name]["mask"])
kwargs["one_hot"] = one_hot
return kwargs
class Repeat(Compose):
"""Repeatedly applies a given transform ``n_repeat`` times."
Parameters
----------
transform : BaseTransform
Transform to repeat.
n_repeat : int, optional
Number of times to repeat transform, by default 1
"""
def __init__(
self,
transform,
n_repeat: int = 1,
name: str = None,
prob: float = 1.0,
):
transforms = [copy.copy(transform) for _ in range(n_repeat)]
super().__init__(transforms, name=name, prob=prob)
self.n_repeat = n_repeat
class RepeatUpTo(Choose):
"""Repeatedly applies a given transform up to ``max_repeat`` times."
Parameters
----------
transform : BaseTransform
Transform to repeat.
max_repeat : int, optional
Max number of times to repeat transform, by default 1
weights : list
Probability of choosing any specific number up to ``max_repeat``.
"""
def __init__(
self,
transform,
max_repeat: int = 5,
weights: list = None,
name: str = None,
prob: float = 1.0,
):
transforms = []
for n in range(1, max_repeat):
transforms.append(Repeat(transform, n_repeat=n))
super().__init__(transforms, name=name, prob=prob, weights=weights)
self.max_repeat = max_repeat
class ClippingDistortion(BaseTransform):
"""Adds clipping distortion to signal. Corresponds
to :py:func:`audiotools.core.effects.EffectMixin.clip_distortion`.
Parameters
----------
perc : tuple, optional
Clipping percentile. Values are between 0.0 to 1.0.
Typical values are 0.1 or below, by default ("uniform", 0.0, 0.1)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
perc: tuple = ("uniform", 0.0, 0.1),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.perc = perc
def _instantiate(self, state: RandomState):
return {"perc": util.sample_from_dist(self.perc, state)}
def _transform(self, signal, perc):
return signal.clip_distortion(perc)
class Equalizer(BaseTransform):
"""Applies an equalization curve to the audio signal. Corresponds
to :py:func:`audiotools.core.effects.EffectMixin.equalizer`.
Parameters
----------
eq_amount : tuple, optional
The maximum dB cut to apply to the audio in any band,
by default ("const", 1.0 dB)
n_bands : int, optional
Number of bands in EQ, by default 6
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
eq_amount: tuple = ("const", 1.0),
n_bands: int = 6,
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.eq_amount = eq_amount
self.n_bands = n_bands
def _instantiate(self, state: RandomState):
eq_amount = util.sample_from_dist(self.eq_amount, state)
eq = -eq_amount * state.rand(self.n_bands)
return {"eq": eq}
def _transform(self, signal, eq):
return signal.equalizer(eq)
class Quantization(BaseTransform):
"""Applies quantization to the input waveform. Corresponds
to :py:func:`audiotools.core.effects.EffectMixin.quantization`.
Parameters
----------
channels : tuple, optional
Number of evenly spaced quantization channels to quantize
to, by default ("choice", [8, 32, 128, 256, 1024])
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
channels: tuple = ("choice", [8, 32, 128, 256, 1024]),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.channels = channels
def _instantiate(self, state: RandomState):
return {"channels": util.sample_from_dist(self.channels, state)}
def _transform(self, signal, channels):
return signal.quantization(channels)
class MuLawQuantization(BaseTransform):
"""Applies mu-law quantization to the input waveform. Corresponds
to :py:func:`audiotools.core.effects.EffectMixin.mulaw_quantization`.
Parameters
----------
channels : tuple, optional
Number of mu-law spaced quantization channels to quantize
to, by default ("choice", [8, 32, 128, 256, 1024])
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
channels: tuple = ("choice", [8, 32, 128, 256, 1024]),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.channels = channels
def _instantiate(self, state: RandomState):
return {"channels": util.sample_from_dist(self.channels, state)}
def _transform(self, signal, channels):
return signal.mulaw_quantization(channels)
class NoiseFloor(BaseTransform):
"""Adds a noise floor of Gaussian noise to the signal at a specified
dB.
Parameters
----------
db : tuple, optional
Level of noise to add to signal, by default ("const", -50.0)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
db: tuple = ("const", -50.0),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.db = db
def _instantiate(self, state: RandomState, signal: AudioSignal):
db = util.sample_from_dist(self.db, state)
audio_data = state.randn(signal.num_channels, signal.signal_length)
nz_signal = AudioSignal(audio_data, signal.sample_rate)
nz_signal.normalize(db)
return {"nz_signal": nz_signal}
def _transform(self, signal, nz_signal):
# Clone bg_signal so that transform can be repeatedly applied
# to different signals with the same effect.
return signal + nz_signal
class BackgroundNoise(BaseTransform):
"""Adds background noise from audio specified by a set of CSV files.
A valid CSV file looks like, and is typically generated by
:py:func:`audiotools.data.preprocess.create_csv`:
.. csv-table::
:header: path
room_tone/m6_script2_clean.wav
room_tone/m6_script2_cleanraw.wav
room_tone/m6_script2_ipad_balcony1.wav
room_tone/m6_script2_ipad_bedroom1.wav
room_tone/m6_script2_ipad_confroom1.wav
room_tone/m6_script2_ipad_confroom2.wav
room_tone/m6_script2_ipad_livingroom1.wav
room_tone/m6_script2_ipad_office1.wav
.. note::
All paths are relative to an environment variable called ``PATH_TO_DATA``,
so that CSV files are portable across machines where data may be
located in different places.
This transform calls :py:func:`audiotools.core.effects.EffectMixin.mix`
and :py:func:`audiotools.core.effects.EffectMixin.equalizer` under the
hood.
Parameters
----------
snr : tuple, optional
Signal-to-noise ratio, by default ("uniform", 10.0, 30.0)
sources : List[str], optional
Sources containing folders, or CSVs with paths to audio files,
by default None
weights : List[float], optional
Weights to sample audio files from each source, by default None
eq_amount : tuple, optional
Amount of equalization to apply, by default ("const", 1.0)
n_bands : int, optional
Number of bands in equalizer, by default 3
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
loudness_cutoff : float, optional
Loudness cutoff when loading from audio files, by default None
"""
def __init__(
self,
snr: tuple = ("uniform", 10.0, 30.0),
sources: List[str] = None,
weights: List[float] = None,
eq_amount: tuple = ("const", 1.0),
n_bands: int = 3,
name: str = None,
prob: float = 1.0,
loudness_cutoff: float = None,
):
super().__init__(name=name, prob=prob)
self.snr = snr
self.eq_amount = eq_amount
self.n_bands = n_bands
self.loader = AudioLoader(sources, weights)
self.loudness_cutoff = loudness_cutoff
def _instantiate(self, state: RandomState, signal: AudioSignal):
eq_amount = util.sample_from_dist(self.eq_amount, state)
eq = -eq_amount * state.rand(self.n_bands)
snr = util.sample_from_dist(self.snr, state)
bg_signal = self.loader(
state,
signal.sample_rate,
duration=signal.signal_duration,
loudness_cutoff=self.loudness_cutoff,
num_channels=signal.num_channels,
)["signal"]
return {"eq": eq, "bg_signal": bg_signal, "snr": snr}
def _transform(self, signal, bg_signal, snr, eq):
# Clone bg_signal so that transform can be repeatedly applied
# to different signals with the same effect.
return signal.mix(bg_signal.clone(), snr, eq)
class CrossTalk(BaseTransform):
"""Adds crosstalk between speakers, whose audio is drawn from a CSV file
that was produced via :py:func:`audiotools.data.preprocess.create_csv`.
This transform calls :py:func:`audiotools.core.effects.EffectMixin.mix`
under the hood.
Parameters
----------
snr : tuple, optional
How loud cross-talk speaker is relative to original signal in dB,
by default ("uniform", 0.0, 10.0)
sources : List[str], optional
Sources containing folders, or CSVs with paths to audio files,
by default None
weights : List[float], optional
Weights to sample audio files from each source, by default None
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
loudness_cutoff : float, optional
Loudness cutoff when loading from audio files, by default -40
"""
def __init__(
self,
snr: tuple = ("uniform", 0.0, 10.0),
sources: List[str] = None,
weights: List[float] = None,
name: str = None,
prob: float = 1.0,
loudness_cutoff: float = -40,
):
super().__init__(name=name, prob=prob)
self.snr = snr
self.loader = AudioLoader(sources, weights)
self.loudness_cutoff = loudness_cutoff
def _instantiate(self, state: RandomState, signal: AudioSignal):
snr = util.sample_from_dist(self.snr, state)
crosstalk_signal = self.loader(
state,
signal.sample_rate,
duration=signal.signal_duration,
loudness_cutoff=self.loudness_cutoff,
num_channels=signal.num_channels,
)["signal"]
return {"crosstalk_signal": crosstalk_signal, "snr": snr}
def _transform(self, signal, crosstalk_signal, snr):
# Clone bg_signal so that transform can be repeatedly applied
# to different signals with the same effect.
loudness = signal.loudness()
mix = signal.mix(crosstalk_signal.clone(), snr)
mix.normalize(loudness)
return mix
class RoomImpulseResponse(BaseTransform):
"""Convolves signal with a room impulse response, at a specified
direct-to-reverberant ratio, with equalization applied. Room impulse
response data is drawn from a CSV file that was produced via
:py:func:`audiotools.data.preprocess.create_csv`.
This transform calls :py:func:`audiotools.core.effects.EffectMixin.apply_ir`
under the hood.
Parameters
----------
drr : tuple, optional
_description_, by default ("uniform", 0.0, 30.0)
sources : List[str], optional
Sources containing folders, or CSVs with paths to audio files,
by default None
weights : List[float], optional
Weights to sample audio files from each source, by default None
eq_amount : tuple, optional
Amount of equalization to apply, by default ("const", 1.0)
n_bands : int, optional
Number of bands in equalizer, by default 6
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
use_original_phase : bool, optional
Whether or not to use the original phase, by default False
offset : float, optional
Offset from each impulse response file to use, by default 0.0
duration : float, optional
Duration of each impulse response, by default 1.0
"""
def __init__(
self,
drr: tuple = ("uniform", 0.0, 30.0),
sources: List[str] = None,
weights: List[float] = None,
eq_amount: tuple = ("const", 1.0),
n_bands: int = 6,
name: str = None,
prob: float = 1.0,
use_original_phase: bool = False,
offset: float = 0.0,
duration: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.drr = drr
self.eq_amount = eq_amount
self.n_bands = n_bands
self.use_original_phase = use_original_phase
self.loader = AudioLoader(sources, weights)
self.offset = offset
self.duration = duration
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
eq_amount = util.sample_from_dist(self.eq_amount, state)
eq = -eq_amount * state.rand(self.n_bands)
drr = util.sample_from_dist(self.drr, state)
ir_signal = self.loader(
state,
signal.sample_rate,
offset=self.offset,
duration=self.duration,
loudness_cutoff=None,
num_channels=signal.num_channels,
)["signal"]
ir_signal.zero_pad_to(signal.sample_rate)
return {"eq": eq, "ir_signal": ir_signal, "drr": drr}
def _transform(self, signal, ir_signal, drr, eq):
# Clone ir_signal so that transform can be repeatedly applied
# to different signals with the same effect.
return signal.apply_ir(
ir_signal.clone(), drr, eq, use_original_phase=self.use_original_phase
)
class VolumeChange(BaseTransform):
"""Changes the volume of the input signal.
Uses :py:func:`audiotools.core.effects.EffectMixin.volume_change`.
Parameters
----------
db : tuple, optional
Change in volume in decibels, by default ("uniform", -12.0, 0.0)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
db: tuple = ("uniform", -12.0, 0.0),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.db = db
def _instantiate(self, state: RandomState):
return {"db": util.sample_from_dist(self.db, state)}
def _transform(self, signal, db):
return signal.volume_change(db)
class VolumeNorm(BaseTransform):
"""Normalizes the volume of the excerpt to a specified decibel.
Uses :py:func:`audiotools.core.effects.EffectMixin.normalize`.
Parameters
----------
db : tuple, optional
dB to normalize signal to, by default ("const", -24)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
db: tuple = ("const", -24),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.db = db
def _instantiate(self, state: RandomState):
return {"db": util.sample_from_dist(self.db, state)}
def _transform(self, signal, db):
return signal.normalize(db)
class GlobalVolumeNorm(BaseTransform):
"""Similar to :py:func:`audiotools.data.transforms.VolumeNorm`, this
transform also normalizes the volume of a signal, but it uses
the volume of the entire audio file the loaded excerpt comes from,
rather than the volume of just the excerpt. The volume of the
entire audio file is expected in ``signal.metadata["loudness"]``.
If loading audio from a CSV generated by :py:func:`audiotools.data.preprocess.create_csv`
with ``loudness = True``, like the following:
.. csv-table::
:header: path,loudness
daps/produced/f1_script1_produced.wav,-16.299999237060547
daps/produced/f1_script2_produced.wav,-16.600000381469727
daps/produced/f1_script3_produced.wav,-17.299999237060547
daps/produced/f1_script4_produced.wav,-16.100000381469727
daps/produced/f1_script5_produced.wav,-16.700000762939453
daps/produced/f3_script1_produced.wav,-16.5
The ``AudioLoader`` will automatically load the loudness column into
the metadata of the signal.
Uses :py:func:`audiotools.core.effects.EffectMixin.volume_change`.
Parameters
----------
db : tuple, optional
dB to normalize signal to, by default ("const", -24)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
db: tuple = ("const", -24),
name: str = None,
prob: float = 1.0,
):
super().__init__(name=name, prob=prob)
self.db = db
def _instantiate(self, state: RandomState, signal: AudioSignal):
if "loudness" not in signal.metadata:
db_change = 0.0
elif float(signal.metadata["loudness"]) == float("-inf"):
db_change = 0.0
else:
db = util.sample_from_dist(self.db, state)
db_change = db - float(signal.metadata["loudness"])
return {"db": db_change}
def _transform(self, signal, db):
return signal.volume_change(db)
class Silence(BaseTransform):
"""Zeros out the signal with some probability.
Parameters
----------
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 0.1
"""
def __init__(self, name: str = None, prob: float = 0.1):
super().__init__(name=name, prob=prob)
def _transform(self, signal):
_loudness = signal._loudness
signal = AudioSignal(
torch.zeros_like(signal.audio_data),
sample_rate=signal.sample_rate,
stft_params=signal.stft_params,
)
# So that the amound of noise added is as if it wasn't silenced.
# TODO: improve this hack
signal._loudness = _loudness
return signal
class LowPass(BaseTransform):
"""Applies a LowPass filter.
Uses :py:func:`audiotools.core.dsp.DSPMixin.low_pass`.
Parameters
----------
cutoff : tuple, optional
Cutoff frequency distribution,
by default ``("choice", [4000, 8000, 16000])``
zeros : int, optional
Number of zero-crossings in filter, argument to
``julius.LowPassFilters``, by default 51
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
cutoff: tuple = ("choice", [4000, 8000, 16000]),
zeros: int = 51,
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.cutoff = cutoff
self.zeros = zeros
def _instantiate(self, state: RandomState):
return {"cutoff": util.sample_from_dist(self.cutoff, state)}
def _transform(self, signal, cutoff):
return signal.low_pass(cutoff, zeros=self.zeros)
class HighPass(BaseTransform):
"""Applies a HighPass filter.
Uses :py:func:`audiotools.core.dsp.DSPMixin.high_pass`.
Parameters
----------
cutoff : tuple, optional
Cutoff frequency distribution,
by default ``("choice", [50, 100, 250, 500, 1000])``
zeros : int, optional
Number of zero-crossings in filter, argument to
``julius.LowPassFilters``, by default 51
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
cutoff: tuple = ("choice", [50, 100, 250, 500, 1000]),
zeros: int = 51,
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.cutoff = cutoff
self.zeros = zeros
def _instantiate(self, state: RandomState):
return {"cutoff": util.sample_from_dist(self.cutoff, state)}
def _transform(self, signal, cutoff):
return signal.high_pass(cutoff, zeros=self.zeros)
class RescaleAudio(BaseTransform):
"""Rescales the audio so it is in between ``-val`` and ``val``
only if the original audio exceeds those bounds. Useful if
transforms have caused the audio to clip.
Uses :py:func:`audiotools.core.effects.EffectMixin.ensure_max_of_audio`.
Parameters
----------
val : float, optional
Max absolute value of signal, by default 1.0
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(self, val: float = 1.0, name: str = None, prob: float = 1):
super().__init__(name=name, prob=prob)
self.val = val
def _transform(self, signal):
return signal.ensure_max_of_audio(self.val)
class ShiftPhase(SpectralTransform):
"""Shifts the phase of the audio.
Uses :py:func:`audiotools.core.dsp.DSPMixin.shift)phase`.
Parameters
----------
shift : tuple, optional
How much to shift phase by, by default ("uniform", -np.pi, np.pi)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
shift: tuple = ("uniform", -np.pi, np.pi),
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.shift = shift
def _instantiate(self, state: RandomState):
return {"shift": util.sample_from_dist(self.shift, state)}
def _transform(self, signal, shift):
return signal.shift_phase(shift)
class InvertPhase(ShiftPhase):
"""Inverts the phase of the audio.
Uses :py:func:`audiotools.core.dsp.DSPMixin.shift_phase`.
Parameters
----------
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(self, name: str = None, prob: float = 1):
super().__init__(shift=("const", np.pi), name=name, prob=prob)
class CorruptPhase(SpectralTransform):
"""Corrupts the phase of the audio.
Uses :py:func:`audiotools.core.dsp.DSPMixin.corrupt_phase`.
Parameters
----------
scale : tuple, optional
How much to corrupt phase by, by default ("uniform", 0, np.pi)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self, scale: tuple = ("uniform", 0, np.pi), name: str = None, prob: float = 1
):
super().__init__(name=name, prob=prob)
self.scale = scale
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
scale = util.sample_from_dist(self.scale, state)
corruption = state.normal(scale=scale, size=signal.phase.shape[1:])
return {"corruption": corruption.astype("float32")}
def _transform(self, signal, corruption):
return signal.shift_phase(shift=corruption)
class FrequencyMask(SpectralTransform):
"""Masks a band of frequencies at a center frequency
from the audio.
Uses :py:func:`audiotools.core.dsp.DSPMixin.mask_frequencies`.
Parameters
----------
f_center : tuple, optional
Center frequency between 0.0 and 1.0 (Nyquist), by default ("uniform", 0.0, 1.0)
f_width : tuple, optional
Width of zero'd out band, by default ("const", 0.1)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
f_center: tuple = ("uniform", 0.0, 1.0),
f_width: tuple = ("const", 0.1),
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.f_center = f_center
self.f_width = f_width
def _instantiate(self, state: RandomState, signal: AudioSignal):
f_center = util.sample_from_dist(self.f_center, state)
f_width = util.sample_from_dist(self.f_width, state)
fmin = max(f_center - (f_width / 2), 0.0)
fmax = min(f_center + (f_width / 2), 1.0)
fmin_hz = (signal.sample_rate / 2) * fmin
fmax_hz = (signal.sample_rate / 2) * fmax
return {"fmin_hz": fmin_hz, "fmax_hz": fmax_hz}
def _transform(self, signal, fmin_hz: float, fmax_hz: float):
return signal.mask_frequencies(fmin_hz=fmin_hz, fmax_hz=fmax_hz)
class TimeMask(SpectralTransform):
"""Masks out contiguous time-steps from signal.
Uses :py:func:`audiotools.core.dsp.DSPMixin.mask_timesteps`.
Parameters
----------
t_center : tuple, optional
Center time in terms of 0.0 and 1.0 (duration of signal),
by default ("uniform", 0.0, 1.0)
t_width : tuple, optional
Width of dropped out portion, by default ("const", 0.025)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
t_center: tuple = ("uniform", 0.0, 1.0),
t_width: tuple = ("const", 0.025),
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.t_center = t_center
self.t_width = t_width
def _instantiate(self, state: RandomState, signal: AudioSignal):
t_center = util.sample_from_dist(self.t_center, state)
t_width = util.sample_from_dist(self.t_width, state)
tmin = max(t_center - (t_width / 2), 0.0)
tmax = min(t_center + (t_width / 2), 1.0)
tmin_s = signal.signal_duration * tmin
tmax_s = signal.signal_duration * tmax
return {"tmin_s": tmin_s, "tmax_s": tmax_s}
def _transform(self, signal, tmin_s: float, tmax_s: float):
return signal.mask_timesteps(tmin_s=tmin_s, tmax_s=tmax_s)
class MaskLowMagnitudes(SpectralTransform):
"""Masks low magnitude regions out of signal.
Uses :py:func:`audiotools.core.dsp.DSPMixin.mask_low_magnitudes`.
Parameters
----------
db_cutoff : tuple, optional
Decibel value for which things below it will be masked away,
by default ("uniform", -10, 10)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
db_cutoff: tuple = ("uniform", -10, 10),
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.db_cutoff = db_cutoff
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
return {"db_cutoff": util.sample_from_dist(self.db_cutoff, state)}
def _transform(self, signal, db_cutoff: float):
return signal.mask_low_magnitudes(db_cutoff)
class Smoothing(BaseTransform):
"""Convolves the signal with a smoothing window.
Uses :py:func:`audiotools.core.effects.EffectMixin.convolve`.
Parameters
----------
window_type : tuple, optional
Type of window to use, by default ("const", "average")
window_length : tuple, optional
Length of smoothing window, by
default ("choice", [8, 16, 32, 64, 128, 256, 512])
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
window_type: tuple = ("const", "average"),
window_length: tuple = ("choice", [8, 16, 32, 64, 128, 256, 512]),
name: str = None,
prob: float = 1,
):
super().__init__(name=name, prob=prob)
self.window_type = window_type
self.window_length = window_length
def _instantiate(self, state: RandomState, signal: AudioSignal = None):
window_type = util.sample_from_dist(self.window_type, state)
window_length = util.sample_from_dist(self.window_length, state)
window = signal.get_window(
window_type=window_type, window_length=window_length, device="cpu"
)
return {"window": AudioSignal(window, signal.sample_rate)}
def _transform(self, signal, window):
sscale = signal.audio_data.abs().max(dim=-1, keepdim=True).values
sscale[sscale == 0.0] = 1.0
out = signal.convolve(window)
oscale = out.audio_data.abs().max(dim=-1, keepdim=True).values
oscale[oscale == 0.0] = 1.0
out = out * (sscale / oscale)
return out
class TimeNoise(TimeMask):
"""Similar to :py:func:`audiotools.data.transforms.TimeMask`, but
replaces with noise instead of zeros.
Parameters
----------
t_center : tuple, optional
Center time in terms of 0.0 and 1.0 (duration of signal),
by default ("uniform", 0.0, 1.0)
t_width : tuple, optional
Width of dropped out portion, by default ("const", 0.025)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
t_center: tuple = ("uniform", 0.0, 1.0),
t_width: tuple = ("const", 0.025),
name: str = None,
prob: float = 1,
):
super().__init__(t_center=t_center, t_width=t_width, name=name, prob=prob)
def _transform(self, signal, tmin_s: float, tmax_s: float):
signal = signal.mask_timesteps(tmin_s=tmin_s, tmax_s=tmax_s, val=0.0)
mag, phase = signal.magnitude, signal.phase
mag_r, phase_r = torch.randn_like(mag), torch.randn_like(phase)
mask = (mag == 0.0) * (phase == 0.0)
mag[mask] = mag_r[mask]
phase[mask] = phase_r[mask]
signal.magnitude = mag
signal.phase = phase
return signal
class FrequencyNoise(FrequencyMask):
"""Similar to :py:func:`audiotools.data.transforms.FrequencyMask`, but
replaces with noise instead of zeros.
Parameters
----------
f_center : tuple, optional
Center frequency between 0.0 and 1.0 (Nyquist), by default ("uniform", 0.0, 1.0)
f_width : tuple, optional
Width of zero'd out band, by default ("const", 0.1)
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
f_center: tuple = ("uniform", 0.0, 1.0),
f_width: tuple = ("const", 0.1),
name: str = None,
prob: float = 1,
):
super().__init__(f_center=f_center, f_width=f_width, name=name, prob=prob)
def _transform(self, signal, fmin_hz: float, fmax_hz: float):
signal = signal.mask_frequencies(fmin_hz=fmin_hz, fmax_hz=fmax_hz)
mag, phase = signal.magnitude, signal.phase
mag_r, phase_r = torch.randn_like(mag), torch.randn_like(phase)
mask = (mag == 0.0) * (phase == 0.0)
mag[mask] = mag_r[mask]
phase[mask] = phase_r[mask]
signal.magnitude = mag
signal.phase = phase
return signal
class SpectralDenoising(Equalizer):
"""Applies denoising algorithm detailed in
:py:func:`audiotools.ml.layers.spectral_gate.SpectralGate`,
using a randomly generated noise signal for denoising.
Parameters
----------
eq_amount : tuple, optional
Amount of eq to apply to noise signal, by default ("const", 1.0)
denoise_amount : tuple, optional
Amount to denoise by, by default ("uniform", 0.8, 1.0)
nz_volume : float, optional
Volume of noise to denoise with, by default -40
n_bands : int, optional
Number of bands in equalizer, by default 6
n_freq : int, optional
Number of frequency bins to smooth by, by default 3
n_time : int, optional
Number of time bins to smooth by, by default 5
name : str, optional
Name of this transform, used to identify it in the dictionary
produced by ``self.instantiate``, by default None
prob : float, optional
Probability of applying this transform, by default 1.0
"""
def __init__(
self,
eq_amount: tuple = ("const", 1.0),
denoise_amount: tuple = ("uniform", 0.8, 1.0),
nz_volume: float = -40,
n_bands: int = 6,
n_freq: int = 3,
n_time: int = 5,
name: str = None,
prob: float = 1,
):
super().__init__(eq_amount=eq_amount, n_bands=n_bands, name=name, prob=prob)
self.nz_volume = nz_volume
self.denoise_amount = denoise_amount
self.spectral_gate = ml.layers.SpectralGate(n_freq, n_time)
def _transform(self, signal, nz, eq, denoise_amount):
nz = nz.normalize(self.nz_volume).equalizer(eq)
self.spectral_gate = self.spectral_gate.to(signal.device)
signal = self.spectral_gate(signal, nz, denoise_amount)
return signal
def _instantiate(self, state: RandomState):
kwargs = super()._instantiate(state)
kwargs["denoise_amount"] = util.sample_from_dist(self.denoise_amount, state)
kwargs["nz"] = AudioSignal(state.randn(22050), 44100)
return kwargs
|