-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelpers.py
More file actions
182 lines (163 loc) · 5.18 KB
/
helpers.py
File metadata and controls
182 lines (163 loc) · 5.18 KB
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
import random
import librosa as lib
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pippi import dsp, fx
import scipy
import param_generation as pg
from common_vars import SR
sr=SR
import string
def specShow(sig):
plt.figure(figsize=(8, 5))
# multiframe spectrogram
#make mono
try:
sig=sig.frames
except:
pass
sig=np.nan_to_num(list(sig))
try:
sig=lib.to_mono(np.transpose(sig))
except:
return
X = lib.stft(sig)
# Xdb = lib.amplitude_to_db(abs(X))
plt.figure(figsize=(14, 5))
plt.subplot(1, 2, 1)
lib.display.specshow(X**0.5, sr=sr, x_axis='time', y_axis='hz')
# single frame spectrogram
X = scipy.fft(sig)
X_mag = librosa.core.amplitude_to_db(np.absolute(X))
f = np.linspace(0, sr, len(X_mag)) # frequency variable
plt.subplot(1, 2, 2)
res=int(len(sig)/2)
plt.plot(f[:res], X_mag[:res])
plt.xlabel('Frequency (Hz)')
def waveShow(sig):
try:
sig=sig.frames
except:
pass
sig=lib.to_mono(np.transpose(sig))
lib.display.waveplot(sig)
from scipy.signal import butter, lfilter, freqz
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(sig, cutoff, fs, order=5):
try:
sig=sig.frames
except:
pass
sig=lib.to_mono(np.transpose(sig))
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, sig)
return np.reshape(y,(-1,1))
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(sig, lowcut, highcut, fs, order=5):
try:
sig=sig.frames
except:
pass
sig = np.transpose(sig).flatten()
sig=lib.to_mono(np.transpose(sig))
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, sig)
return np.reshape(y,(-1,1))
def paramToDF(params):
pdfs=[]
for j,p in enumerate(params):
dict=p.__dict__.copy()
pdfs.append(pd.DataFrame.from_dict([dict]).add_suffix("_%d"%j))
df=pd.concat(pdfs,axis=1)
return df
def paramToSound(params):
out = dsp.buffer(length=1,channels=1)
for p in params:
s=pg.Synth(p)
out.dub(s.buff,p.getStart())
return fx.norm(out,1)
out=fx.norm(out,1)
return out,params
# def stackMaker(n,l=1,c=1):
# #makes a sample of length l with num channels c
# out = dsp.buffer(length=l,channels=c)
# params=[]
# for i in range(n):
# p=pg.RandomParams()
# s=pg.Synth(p)
# out.dub(s.buff,p.getStart())
# params.append(p)
# out=fx.norm(out,1)
# return out,params
def StackMaker(n,l=1,c=1):
#makes a sample of length l with num channels c
out = dsp.buffer(length=l,channels=c)
params = []
for i in range(n):
p = pg.RandomParams()
s = pg.Synth(p)
out.dub(s.buff,p.getStart())
params.append(p)
out = fx.norm(out,1)
return out,params
def rToParams(r,n=0):
r=r.astype(int)
pset=pg.RandomParams()
pset.oscType=int(round(r["oscType_%d"%(n,)]))
pset.isNoise=int(round(r["isNoise_%d"%(n,)]))
pset.A=r["A_%d"%(n,)]
pset.D=r["D_%d"%(n,)]
pset.S=r["S_%d"%(n,)]
pset.R=r["R_%d"%(n,)]
#pitches
pset.pitch_0=int(r["pitch_0_%d"%(n,)])
pset.pitch_1=int(r["pitch_1_%d"%(n,)])
pset.pitch_2=int(r["pitch_2_%d"%(n,)])
pset.pitch_3=int(r["pitch_3_%d"%(n,)])
#######
pset.amplitude=r["amplitude_%d"%(n,)]
pset.bpCutLow,pset.bpCutHigh=r["bpCutLow_%d"%(n,)],r["bpCutHigh_%d"%(n,)]
pset.bpOrder=int(round(r["bpOrder_%d"%(n,)]))
pset.start=r["start_%d"%(n,)]
pset.length=r["length_%d"%(n,)]
return pset
#convert pippi outputs to mono audio
def memToAud(out):
return np.squeeze(np.asarray(out.frames))
# converting audio to images
def cutAudio(x,num_samples=sr):
xt,i=lib.effects.trim(x, top_db=50)
nTrimmed=len(x)-len(xt)
xt=xt[0:num_samples]
xt=lib.util.normalize(xt)
new_x =np.pad(xt,(0,num_samples-xt.shape[0]),'constant')
return new_x,nTrimmed
def audToImage(x,num_bins=100):
D=librosa.stft(x,n_fft=num_bins**2,win_length=num_bins**2,hop_length=int(num_bins*4)+1)
S = librosa.feature.melspectrogram(S=D, sr=sr, n_mels=num_bins)
S_dB = librosa.power_to_db(np.abs(S))
return S_dB
#random string generation
def string_generator(size=4, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def get_mel_spec(sound):
fig, ax = plt.subplots()
S = librosa.feature.melspectrogram(y=sound, sr=sr, n_mels=128,
fmax=20000)
S_dB = librosa.power_to_db(S, ref=np.max)
img = librosa.display.specshow(S_dB, x_axis='time',
y_axis='mel', sr=sr,
fmax=20000, ax=ax,cmap = "Greys")
return img