gfbati commited on
Commit
b03e08e
1 Parent(s): b873834

https://github.com/muhdhuz/audio2spec

Browse files
audio2spec-master/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## wav2png
2
+
3
+ Run this script to convert wav files to spectrograms, which are saved as png files.
4
+ Is able to run on a folder structure with class labels:
5
+
6
+ root/dog/0001.wav
7
+ root/dog/0002.wav
8
+
9
+ root/cat/0001.wav
10
+ root/cat/0002.wav etc.
11
+ Or otherwise on single files.
12
+
13
+ Example use:
14
+
15
+ **For class folder structure**
16
+ ```bash
17
+ python ./wav2png.py folder --rootdir [rootdir]
18
+ ```
19
+ **For single files**
20
+ ```bash
21
+ python ./wav2png.py single --filename [filename.wav]
22
+ ```
23
+ Scaling is done on the STFT output to be compatible with 8-bit png format. The script searches the dataset for the maximum and minimum values, rounds up and down to the nearest integer respectively then scales to [0,255].
24
+
25
+ ## png2wav
26
+
27
+ Run to convert individual png spectrograms back to wav. Script assumes (and inverts) similar scaling as in wav2png. Griffin-Lim algortihm is initialized with [SPSI](http://ieeexplore.ieee.org/abstract/document/7251907/). SPSI code originally from [here](https://github.com/lonce/SPSI_Python).
28
+
29
+ Example use:
30
+
31
+ **For single png spectrogram**
32
+ ```bash
33
+ python ./png2wav.py [filename.png]
34
+ ```
35
+
36
+ ## cqtconv
37
+
38
+ This script is to transform a linear frequency scaled spectrogram image (like the ones generated by wav2png) to a pseudo constant-Q (CQT) scaled spectrogram. Algorithm is adapted from [Matlab code written by Dan Ellis](http://www.ee.columbia.edu/ln/rosa/matlab/sgram/).
39
+
40
+ Example use:
41
+
42
+ **For linear to cqt**
43
+ ```bash
44
+ python ./cqtconv.py --rootdir [rootdir] --outdir [outdir] --conversion spec2cqt
45
+ ```
46
+ **For cqt to linear**
47
+ ```bash
48
+ python ./cqtconv.py --rootdir [rootdir] --outdir [outdir] --conversion cqt2spec
49
+ ```
audio2spec-master/cqtconv.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import numpy as np
3
+ # https://github.com/librosa/librosa
4
+ import librosa
5
+ import librosa.display
6
+ import argparse
7
+ import os
8
+ from PIL import Image
9
+ from PIL import PngImagePlugin
10
+ import json
11
+ import scipy
12
+
13
+
14
+ FLAGS = None
15
+ # ------------------------------------------------------
16
+ # get any args provided on the command line
17
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
18
+ parser.add_argument('--conversion', type=str, choices=['spec2cqt','cqt2spec'], help='direction of conversion', default='spec2cqt')
19
+ parser.add_argument('--filename', type=str, help='For single mode, enter filename', default=None)
20
+ parser.add_argument('--rootdir', type=str, help='Roots folder where class folders containing audio files are kept', default='./')
21
+ parser.add_argument('--outdir', type=str, help='Output directory', default='./output')
22
+ #parser.add_argument('--sr', type=int, help='Samplerate', default=None)
23
+ parser.add_argument('--fftsize', type=int, help='Size of fft window in samples', default=1024)
24
+ #parser.add_argument('--hopsize', type=int, help='Size of frame hop through sample file', default=256)
25
+
26
+ FLAGS, unparsed = parser.parse_known_args()
27
+ print('\n FLAGS parsed : {0}'.format(FLAGS))
28
+
29
+ #filetypes = ['.wav','.mp3'] not yet implimented. manually change fileExtList in listDirectory
30
+
31
+ def get_subdirs(a_dir):
32
+ """ Returns a list of sub directory names in a_dir """
33
+ return [name for name in os.listdir(a_dir)
34
+ if (os.path.isdir(os.path.join(a_dir, name)) and not (name.startswith('.')))]
35
+
36
+
37
+ def listDirectory(directory, fileExtList):
38
+ """Returns a list of file info objects in directory that extension in the list fileExtList - include the . in your extension string"""
39
+ fnameList = [os.path.normcase(f)
40
+ for f in os.listdir(directory)
41
+ if (not(f.startswith('.')))]
42
+ fileList = [os.path.join(directory, f)
43
+ for f in fnameList
44
+ if os.path.splitext(f)[1] in fileExtList]
45
+ return fileList , fnameList
46
+
47
+
48
+ def logSpect2PNG(outimg, fname, lwinfo=None) :
49
+
50
+ info = PngImagePlugin.PngInfo()
51
+ lwinfo = lwinfo or {}
52
+ lwinfo['fileMin'] = str(np.amin(outimg))
53
+ lwinfo['fileMax'] = str(np.amax(outimg))
54
+ info.add_text('meta',json.dumps(lwinfo)) #info required to reverse scaling
55
+
56
+ shift = int(lwinfo['scaleMax']) - int(lwinfo['scaleMin'])
57
+ SC2 = 255*(outimg-int(lwinfo['scaleMin']))/shift
58
+ savimg = Image.fromarray(np.flipud(SC2))
59
+
60
+ pngimg = savimg.convert('L')
61
+ pngimg.save(fname,pnginfo=info)
62
+
63
+
64
+ def PNG2LogSpect(fname,scalemin,scalemax):
65
+
66
+ """
67
+ Read png spectrograms, expand to original scale and return numpy array.
68
+ If not stored in one of png metadata, the values needed to undo previous scaling are required to be specified.
69
+ """
70
+ img = Image.open(fname)
71
+ #info = PngImagePlugin.PngInfo()
72
+
73
+ try:
74
+ img.text = img.text
75
+ lwinfo = json.loads(img.text['meta'])
76
+ except:
77
+ print('PNG2LogSpect: no img.text, using user specified values!')
78
+ lwinfo = {}
79
+ lwinfo['scaleMin'] = scalemin #require to pass in
80
+ lwinfo['scaleMax'] = scalemax
81
+ #info.add_text('meta',json.dumps(lwinfo))
82
+
83
+ minx, maxx = float(lwinfo['scaleMin']), float(lwinfo['scaleMax'])
84
+ #minx, maxx = float(lwinfo['oldmin']), float(lwinfo['oldmax'])
85
+
86
+ img = img.convert('L')
87
+ outimg = np.asarray(img, dtype=np.float32)
88
+ outimg = (outimg - 0)/(255-0)*(maxx-minx) + minx
89
+
90
+ return np.flipud(outimg), lwinfo
91
+
92
+
93
+ def logfmap(I, L, H) :
94
+ """
95
+ % [M,N] = logfmap(I,L,H)
96
+ I - number of rows in the original spectrogram
97
+ L - low bin to preserve
98
+ H - high bin to preserve
99
+
100
+ % Return a maxtrix for premultiplying spectrograms to map
101
+ % the rows into a log frequency space.
102
+ % Output map covers bins L to H of input
103
+ % L must be larger than 1, since the lowest bin of the FFT
104
+ % (corresponding to 0 Hz) cannot be represented on a
105
+ % log frequency axis. Including bins close to 1 makes
106
+ % the number of output rows exponentially larger.
107
+ % N returns the recovery matrix such that N*M is approximately I
108
+ % (for dimensions L to H).
109
+ %
110
+ % Ported from MATLAB code written by Dan Ellis:
111
+ % 2004-05-21 dpwe@ee.columbia.edu
112
+ """
113
+ ratio = (H-1)/H;
114
+ opr = np.int(np.round(np.log(L/H)/np.log(ratio))) #number of frequency bins in log rep + 1
115
+ print('opr is ' + str(opr))
116
+ ibin = L*np.exp(list(range(0,opr)*-np.log(ratio))) #fractional bin numbers (len(ibin) = opr-1)
117
+
118
+ M = np.zeros((opr,I))
119
+ eps=np.finfo(float).eps
120
+
121
+ for i in range(0, opr) :
122
+ # Where do we sample this output bin?
123
+ # Idea is to make them 1:1 at top, and progressively denser below
124
+ # i.e. i = max -> bin = topbin, i = max-1 -> bin = topbin-1,
125
+ # but general form is bin = A exp (i/B)
126
+
127
+ tt = np.multiply(np.pi, (list(range(0,I))-ibin[i]))
128
+ M[i,:] = np.divide((np.sin(tt)+eps) , (tt+eps));
129
+
130
+ # Normalize rows, but only if they are boosted by the operation
131
+ G = np.ones((I));
132
+ print ('H is ' + str(H))
133
+ G[0:H] = np.divide(list(range(0,H)), H)
134
+
135
+ N = np.transpose(np.multiply(M,np.matlib.repmat(G,opr,1)))
136
+
137
+ return M,N
138
+
139
+ def spect2CQT(topdir, outdir, fftSize, lowRow=1):
140
+ """
141
+ Creates psuedo constant-Q spectrograms from linear frequency spectrograms.
142
+ Creates class folders in outdir with the same structure found in topdir.
143
+
144
+ Parameters
145
+ topdir - the dir containing class folders containing png (log magnitude) spectrogram files.
146
+ outdir - the top level directory to write psuedo constantQ files to (written in to class subfolders)
147
+ lowRow is the lowest row in the FFT that you want to include in the psuedo constant Q spectrogram
148
+ """
149
+
150
+ # First lets get the logf map we want
151
+ LIN_FREQ_BINS = int(fftSize/2+1) #number of bins in original linear frequency mag spectrogram
152
+ LOW_ROW = lowRow
153
+ LOG_FREQ_BINS = int(fftSize/2+1) #resample the lgfmapped psuedo consantQ matrix to have this many frequency bins
154
+ M,N = logfmap(LIN_FREQ_BINS,LOW_ROW,LOG_FREQ_BINS)
155
+
156
+
157
+ subdirs = get_subdirs(topdir)
158
+ count = 0
159
+ for subdir in subdirs:
160
+
161
+ fullpaths, _ = listDirectory(topdir + '/' + subdir, '.png')
162
+
163
+ for idx in range(len(fullpaths)) :
164
+ fname = os.path.basename(fullpaths[idx])
165
+ D, pnginfo = PNG2LogSpect(fullpaths[idx],None,None)
166
+
167
+ # Here's the beef
168
+ MD = np.dot(M,D)
169
+ MD = scipy.signal.resample(MD, LIN_FREQ_BINS) #downsample to something reasonable
170
+
171
+ #save
172
+ #info={}
173
+ pnginfo["linFreqBins"] = LIN_FREQ_BINS
174
+ pnginfo["lowRow"] = LOW_ROW
175
+ pnginfo["logFreqBins"] = LOG_FREQ_BINS
176
+
177
+ try:
178
+ os.stat(outdir + '/' + subdir) # test for existence
179
+ except:
180
+ os.makedirs(outdir + '/' + subdir) # create if necessary
181
+
182
+ print(str(count) + ': ' + subdir + '/' + os.path.splitext(fname)[0])
183
+ logSpect2PNG(MD, outdir+'/'+subdir+'/'+os.path.splitext(fname)[0]+'.png',lwinfo=pnginfo)
184
+
185
+ count +=1
186
+ print("COMPLETE")
187
+
188
+ def CQT2spec(topdir,outdir):
189
+
190
+ subdirs = get_subdirs(topdir)
191
+ count = 0
192
+ for subdir in subdirs:
193
+
194
+ fullpaths, _ = listDirectory(topdir + '/' + subdir, '.png')
195
+
196
+ for idx in range(len(fullpaths)) :
197
+ fname = os.path.basename(fullpaths[idx])
198
+ D, pnginfo = PNG2LogSpect(fullpaths[idx],None,None)
199
+ M,N = logfmap(pnginfo["linFreqBins"],pnginfo["lowRow"],pnginfo["logFreqBins"])
200
+ resampledD = scipy.signal.resample(D, M.shape[0]) #upsample
201
+
202
+ # Here's the beef
203
+ ND = np.dot(N,resampledD)
204
+
205
+ try:
206
+ os.stat(outdir + '/' + subdir) # test for existence
207
+ except:
208
+ os.makedirs(outdir + '/' + subdir) # create if necessary
209
+
210
+ print(str(count) + ': ' + subdir + '/' + os.path.splitext(fname)[0])
211
+ logSpect2PNG(ND, outdir+'/'+subdir+'/'+os.path.splitext(fname)[0]+'.png',lwinfo=pnginfo)
212
+
213
+ count +=1
214
+ print("COMPLETE")
215
+
216
+ if FLAGS.conversion == 'spec2cqt':
217
+ spect2CQT(FLAGS.rootdir,FLAGS.outdir,FLAGS.fftsize,lowRow=10)
218
+ elif FLAGS.conversion == 'cqt2spec':
219
+ CQT2spec(FLAGS.rootdir,FLAGS.outdir)
audio2spec-master/png2wav.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import numpy as np
3
+ # https://github.com/librosa/librosa
4
+ import librosa
5
+ import librosa.display
6
+ import argparse
7
+ import os
8
+ from PIL import Image
9
+ from PIL import PngImagePlugin
10
+ import json
11
+
12
+ from spsi import spsi
13
+
14
+ FLAGS = None
15
+ # ------------------------------------------------------
16
+ # get any args provided on the command line
17
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
18
+ parser.add_argument('filename', type=str, help='Name of log mag spectrogram. Include extension')
19
+ parser.add_argument('--outdir', type=str, help='Output directory', default='./output')
20
+ parser.add_argument('--scalemax', type=int, help='Value to use as the max when scaling from png [0,255] to original [min,max]', default=None)
21
+ parser.add_argument('--scalemin', type=int, help='Value to use as the min when scaling from png [0,255] to original [min,max]', default=None)
22
+ parser.add_argument('--sr', type=int, help='Samplerate', default=22050)
23
+ parser.add_argument('--hopsize', type=int, help='Size of frame hop through sample file', default=256)
24
+ parser.add_argument('--glsteps', type=int, help='Number of Griffin&Lim iterations following SPSI', default=50 )
25
+ parser.add_argument('--wavfile', type=str, help='Optional name for output audio file. Unspecified means use the png filename', default=None)
26
+
27
+ FLAGS, unparsed = parser.parse_known_args()
28
+ print('\n FLAGS parsed : {0}'.format(FLAGS))
29
+
30
+
31
+ def inv_log(img):
32
+ img = np.exp(img) - 1.
33
+ return img
34
+
35
+
36
+ def PNG2LogSpect(fname,scalemin,scalemax):
37
+
38
+ """
39
+ Read png spectrograms, expand to original scale and return numpy array.
40
+ If not stored in one of png metadata, the values needed to undo previous scaling are required to be specified.
41
+ """
42
+ img = Image.open(fname)
43
+ #info = PngImagePlugin.PngInfo()
44
+
45
+ try:
46
+ img.text = img.text
47
+ lwinfo = json.loads(img.text['meta'])
48
+ except:
49
+ print('PNG2LogSpect: no img.text, using user specified values!')
50
+ lwinfo = {}
51
+ lwinfo['scaleMin'] = scalemin #require to pass in
52
+ lwinfo['scaleMax'] = scalemax
53
+ #info.add_text('meta',json.dumps(lwinfo))
54
+
55
+ minx, maxx = float(lwinfo['scaleMin']), float(lwinfo['scaleMax'])
56
+ #minx, maxx = float(lwinfo['oldmin']), float(lwinfo['oldmax'])
57
+
58
+ img = img.convert('L')
59
+ outimg = np.asarray(img, dtype=np.float32)
60
+ outimg = (outimg - 0)/(255-0)*(maxx-minx) + minx
61
+
62
+ return np.flipud(outimg), lwinfo
63
+
64
+
65
+ D,_ = PNG2LogSpect(FLAGS.filename,FLAGS.scalemin,FLAGS.scalemax)
66
+ Dsize, _ = D.shape
67
+ fftsize = 2*(Dsize-1) #infer fftsize from no. of fft bins i.e. height of image
68
+
69
+ magD = inv_log(D)
70
+ y_out = spsi(magD, fftsize=fftsize, hop_length=FLAGS.hopsize)
71
+ #print(magD.shape)
72
+ #print(y_out.shape)
73
+
74
+ if FLAGS.glsteps != 0 : #use spsi result for initial phase
75
+ x = librosa.stft(y_out, fftsize, FLAGS.hopsize, center=False)
76
+ p = np.angle(x)
77
+ #print(x.shape)
78
+ for i in range(FLAGS.glsteps):
79
+ S = magD * np.exp(1j*p)
80
+ y_out = librosa.istft(S, FLAGS.hopsize, center=True) # Griffin Lim, assumes hann window, librosa only does one iteration?
81
+ p = np.angle(librosa.stft(y_out, fftsize, FLAGS.hopsize, center=True))
82
+
83
+ scalefactor = np.amax(np.abs(y_out))
84
+ #print(np.amin(np.abs(y_out)))
85
+ #print(y_out[50:70])
86
+ print('scaling peak sample, ' + str(scalefactor) + ' to 1')
87
+ #y_out/=scalefactor
88
+
89
+ if FLAGS.wavfile == None:
90
+ librosa.output.write_wav(os.path.splitext(FLAGS.filename)[0]+'.wav', y_out, FLAGS.sr)
91
+ else:
92
+ librosa.output.write_wav(FLAGS.wavfile, y_out, FLAGS.sr)
93
+
94
+
95
+
audio2spec-master/spsi.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import scipy
3
+
4
+
5
+ def spsi(msgram, fftsize, hop_length) :
6
+ """
7
+ Takes a 2D spectrogram ([freqs,frames]), the fft length (= window length) and the hope size (both in units of samples).
8
+ Returns an audio signal.
9
+ """
10
+
11
+ numBins, numFrames = msgram.shape
12
+ y_out=np.zeros(numFrames*hop_length+fftsize-hop_length)
13
+ #np.zeros(numFrames*hop_length+fftsize-hop_length)
14
+
15
+ m_phase=np.zeros(numBins);
16
+ m_win=scipy.signal.hanning(fftsize, sym=True) # assumption here that hann was used to create the frames of the spectrogram
17
+
18
+ #processes one frame of audio at a time
19
+ for i in range(numFrames) :
20
+ m_mag=msgram[:, i]
21
+ for j in range(1,numBins-1) :
22
+ if(m_mag[j]>m_mag[j-1] and m_mag[j]>m_mag[j+1]) : #if j is a peak
23
+ alpha=m_mag[j-1];
24
+ beta=m_mag[j];
25
+ gamma=m_mag[j+1];
26
+ denom=alpha-2*beta+gamma;
27
+
28
+ if(denom!=0) :
29
+ p=0.5*(alpha-gamma)/denom;
30
+ else :
31
+ p=0;
32
+
33
+ phaseRate=2*np.pi*(j+p)/fftsize; #adjusted phase rate
34
+ m_phase[j]= m_phase[j] + hop_length*phaseRate; #phase accumulator for this peak bin
35
+ peakPhase=m_phase[j];
36
+
37
+ # If actual peak is to the right of the bin freq
38
+ if (p>0) :
39
+ # First bin to right has pi shift
40
+ bin=j+1;
41
+ m_phase[bin]=peakPhase+np.pi;
42
+
43
+ # Bins to left have shift of pi
44
+ bin=j-1;
45
+ while((bin>1) and (m_mag[bin]<m_mag[bin+1])) : # until you reach the trough
46
+ m_phase[bin]=peakPhase+np.pi;
47
+ bin=bin-1;
48
+
49
+ #Bins to the right (beyond the first) have 0 shift
50
+ bin=j+2;
51
+ while((bin<(numBins)) and (m_mag[bin]<m_mag[bin-1])) :
52
+ m_phase[bin]=peakPhase;
53
+ bin=bin+1;
54
+
55
+ #if actual peak is to the left of the bin frequency
56
+ if(p<0) :
57
+ # First bin to left has pi shift
58
+ bin=j-1;
59
+ m_phase[bin]=peakPhase+np.pi;
60
+
61
+ # and bins to the right of me - here I am stuck in the middle with you
62
+ bin=j+1;
63
+ while((bin<(numBins)) and (m_mag[bin]<m_mag[bin-1])) :
64
+ m_phase[bin]=peakPhase+np.pi;
65
+ bin=bin+1;
66
+
67
+ # and further to the left have zero shift
68
+ bin=j-2;
69
+ while((bin>1) and (m_mag[bin]<m_mag[bin+1])) : # until trough
70
+ m_phase[bin]=peakPhase;
71
+ bin=bin-1;
72
+
73
+ #end ops for peaks
74
+ #end loop over fft bins with
75
+
76
+ magphase=m_mag*np.exp(1j*m_phase) #reconstruct with new phase (elementwise mult)
77
+ magphase[0]=0; magphase[numBins-1] = 0 #remove dc and nyquist
78
+ m_recon=np.concatenate([magphase,np.flip(np.conjugate(magphase[1:numBins-1]), 0)])
79
+
80
+ #overlap and add
81
+ m_recon=np.real(np.fft.ifft(m_recon))*m_win
82
+ y_out[i*hop_length:i*hop_length+fftsize]+=m_recon
83
+
84
+ return y_out
85
+
86
+
87
+ def magspect2audio(msgram, fftsize, hop_length) :
88
+ return spsi(msgram, fftsize, hop_length)
89
+
90
+ def logspect2audio(lsgram, fftsize, hop_length) :
91
+ return spsi(np.power(10, lsgram/20), fftsize, hop_length)
92
+
93
+
94
+
95
+
96
+
97
+
audio2spec-master/wav2png.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import numpy as np
3
+ # https://github.com/librosa/librosa
4
+ import librosa
5
+ import librosa.display
6
+ import argparse
7
+ import os
8
+ from PIL import Image
9
+ from PIL import PngImagePlugin
10
+ import json
11
+ import math
12
+
13
+
14
+ FLAGS = None
15
+ # ------------------------------------------------------
16
+ # get any args provided on the command line
17
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
18
+ parser.add_argument('mode', type=str, help='Choices: folder | single. folder mode for wav files in directory structure, single mode for single files', default='folder')
19
+ parser.add_argument('--filename', type=str, help='For single mode, enter filename', default=None)
20
+ parser.add_argument('--rootdir', type=str, help='Roots folder where class folders containing audio files are kept', default='./')
21
+ parser.add_argument('--outdir', type=str, help='Output directory', default='./output')
22
+ parser.add_argument('--sr', type=int, help='Samplerate', default=None)
23
+ parser.add_argument('--fftsize', type=int, help='Size of fft window in samples', default=1024)
24
+ parser.add_argument('--hopsize', type=int, help='Size of frame hop through sample file', default=256)
25
+ parser.add_argument('--dur', type=int, help='Make files this duration in sec. If unspecified keep original duration', default=None)
26
+
27
+ FLAGS, unparsed = parser.parse_known_args()
28
+ print('\n FLAGS parsed : {0}'.format(FLAGS))
29
+
30
+ #filetypes = ['.wav','.mp3'] not yet implimented. manually change fileExtList in listDirectory
31
+
32
+ def get_subdirs(a_dir):
33
+ """ Returns a list of sub directory names in a_dir """
34
+ return [name for name in os.listdir(a_dir)
35
+ if (os.path.isdir(os.path.join(a_dir, name)) and not (name.startswith('.')))]
36
+
37
+
38
+ def listDirectory(directory, fileExtList):
39
+ """Returns a list of file info objects in directory that extension in the list fileExtList - include the . in your extension string"""
40
+ fnameList = [os.path.normcase(f)
41
+ for f in os.listdir(directory)
42
+ if (not(f.startswith('.')))]
43
+ fileList = [os.path.join(directory, f)
44
+ for f in fnameList
45
+ if os.path.splitext(f)[1] in fileExtList]
46
+ return fileList , fnameList
47
+
48
+
49
+ def wav2stft(fname, srate, fftSize, fftHop, dur) :
50
+ try:
51
+ audiodata, samplerate = librosa.load(fname, sr=srate, mono=True, duration=dur)
52
+ #print(np.amax(np.abs(audiodata)))
53
+ #print(np.amin(np.abs(audiodata)))
54
+ #print(audiodata[50:70])
55
+ except:
56
+ print('can not read ' + fname)
57
+ return
58
+
59
+ if srate == None:
60
+ print('Using native samplerate of ' + str(samplerate))
61
+ S = np.abs(librosa.stft(audiodata, n_fft=fftSize, hop_length=fftHop, win_length=fftSize, center=True))
62
+ #print(audiodata.shape)
63
+ #print(S.shape)
64
+ return S
65
+
66
+
67
+ def log_scale(x):
68
+ output = np.log1p(x)
69
+ return output
70
+
71
+
72
+ def findMinMax(img):
73
+ return np.amin(img),np.amax(img)
74
+
75
+
76
+ def logSpect2PNG(outimg, fname, lwinfo=None) :
77
+
78
+ info = PngImagePlugin.PngInfo()
79
+ lwinfo = lwinfo or {}
80
+ lwinfo['fileMin'] = str(np.amin(outimg))
81
+ lwinfo['fileMax'] = str(np.amax(outimg))
82
+ info.add_text('meta',json.dumps(lwinfo)) #info required to reverse scaling
83
+
84
+ shift = int(lwinfo['scaleMax']) - int(lwinfo['scaleMin'])
85
+ SC2 = 255*(outimg-int(lwinfo['scaleMin']))/shift
86
+ savimg = Image.fromarray(np.flipud(SC2))
87
+
88
+ pngimg = savimg.convert('L')
89
+ pngimg.save(fname,pnginfo=info)
90
+
91
+
92
+ def checkScaling(topdir, outdir, srate, fftSize, fftHop, dur):
93
+ """
94
+ Returns the max and min values of the log magnitude after STFT in the whole dataset.
95
+ This is to provide a known and standardized mapping from [min,max] -> [0,255] when saving as a png image.
96
+
97
+ Parameters
98
+ topdir - the dir containing class folders containing wav files.
99
+ outdir - the top level directory to write wave files to (written in to class subfolders)
100
+ dur - (in seconds) all files will be truncated or zeropadded to have this duration given the srate
101
+ srate - input files will be resampled to srate as they are read in before being saved as wav files
102
+ """
103
+ print("Now determining maximum log magnitude value in dataset for scaling to png...")
104
+ subdirs = get_subdirs(topdir)
105
+ max_mag = 0
106
+ min_mag = 0
107
+ for subdir in subdirs:
108
+
109
+ fullpaths, _ = listDirectory(topdir + '/' + subdir, '.wav')
110
+
111
+ for idx in range(len(fullpaths)) :
112
+ fname = os.path.basename(fullpaths[idx])
113
+
114
+ D = wav2stft(fullpaths[idx], srate, fftSize, fftHop, dur)
115
+ D = log_scale(D)
116
+ minM,maxM = findMinMax(D)
117
+ if minM > min_mag:
118
+ min_mag = minM
119
+ if maxM > max_mag:
120
+ max_mag = maxM
121
+
122
+ print("Dataset: min magnitude=",min_mag,"max magnitude=",max_mag)
123
+ minScale = int(math.floor(min_mag))
124
+ maxScale = int(math.ceil(max_mag))
125
+ #print("New scale: min magnitude=",minScale,"max magnitude=",maxScale)
126
+ print("Using [{0},{1}] -> [0,255] for png conversion".format(minScale,maxScale))
127
+ pnginfo = {}
128
+ pnginfo['datasetMin'] = str(min_mag)
129
+ pnginfo['datasetMax'] = str(max_mag)
130
+ pnginfo['scaleMin'] = str(minScale)
131
+ pnginfo['scaleMax'] = str(maxScale)
132
+ return pnginfo
133
+
134
+
135
+ def wav2Spect(topdir, outdir, srate, fftSize, fftHop, dur, pnginfo) :
136
+ """
137
+ Creates spectrograms for subfolder-labeled wavfiles.
138
+ Creates class folders for the spectrogram files in outdir with the same structure found in topdir.
139
+
140
+ Parameters
141
+ topdir - the dir containing class folders containing wav files.
142
+ outdir - the top level directory to write wave files to (written in to class subfolders)
143
+ dur - (in seconds) all files will be truncated or zeropadded to have this duration given the srate
144
+ srate - input files will be resampled to srate as they are read in before being saved as wav files
145
+ """
146
+
147
+ subdirs = get_subdirs(topdir)
148
+ count = 0
149
+ for subdir in subdirs:
150
+
151
+ fullpaths, _ = listDirectory(topdir + '/' + subdir, '.wav')
152
+
153
+ for idx in range(len(fullpaths)) :
154
+ fname = os.path.basename(fullpaths[idx])
155
+ D = wav2stft(fullpaths[idx], srate, fftSize, fftHop, dur)
156
+ D = log_scale(D)
157
+
158
+ try:
159
+ os.stat(outdir + '/' + subdir) # test for existence
160
+ except:
161
+ os.makedirs(outdir + '/' + subdir) # create if necessary
162
+
163
+ print(str(count) + ': ' + subdir + '/' + os.path.splitext(fname)[0])
164
+
165
+ logSpect2PNG(D, outdir+'/'+subdir+'/'+os.path.splitext(fname)[0]+'.png', lwinfo=pnginfo)
166
+
167
+ count +=1
168
+ print("COMPLETE")
169
+
170
+
171
+ def wav2Spect_single(filename, srate, fftSize, fftHop, dur) :
172
+ """
173
+ Creates spectrograms from single wavfiles.
174
+ """
175
+ D = wav2stft(filename, srate, fftSize, fftHop, dur)
176
+ D = log_scale(D)
177
+ minM,maxM = findMinMax(D)
178
+
179
+ print("Dataset: min magnitude=",minM,"max magnitude=",maxM)
180
+ minScale = int(math.floor(minM))
181
+ maxScale = int(math.ceil(maxM))
182
+ print("Using [{0},{1}] -> [0,255] for png conversion".format(minScale,maxScale))
183
+ pnginfo = {}
184
+ pnginfo['datasetMin'] = str(minM)
185
+ pnginfo['datasetMax'] = str(maxM)
186
+ pnginfo['scaleMin'] = str(minScale)
187
+ pnginfo['scaleMax'] = str(maxScale)
188
+
189
+ print(str(0) + ': ' + os.path.splitext(filename)[0])
190
+ logSpect2PNG(D, os.path.splitext(filename)[0] +'.png',pnginfo)
191
+
192
+ print("COMPLETE")
193
+
194
+
195
+ if FLAGS.mode == 'folder':
196
+ pnginfo = checkScaling(FLAGS.rootdir,FLAGS.outdir,FLAGS.sr,FLAGS.fftsize,FLAGS.hopsize,FLAGS.dur)
197
+ wav2Spect(FLAGS.rootdir,FLAGS.outdir,FLAGS.sr,FLAGS.fftsize,FLAGS.hopsize,FLAGS.dur,pnginfo)
198
+ elif FLAGS.mode == 'single':
199
+ wav2Spect_single(FLAGS.filename,FLAGS.sr,FLAGS.fftsize,FLAGS.hopsize,FLAGS.dur)
200
+ else:
201
+ raise ValueError("Not an acceptable mode! Choices: folder | single. folder mode for wav files in directory structure, single mode for single files")
202
+