changeset 8:6cafb481a1e5

Python3 readiness (thanks to 2to3) Currently tested only on 2.7 though.
author Dan Stowell <danstowell@users.sourceforge.net>
date Thu, 29 Nov 2012 11:17:45 +0000
parents 8a27868916fe
children 7adab9621caa
files MFCC.py README.md smacpy.py
diffstat 3 files changed, 29 insertions(+), 29 deletions(-) [+]
line wrap: on
line diff
--- a/MFCC.py	Thu Nov 29 11:06:56 2012 +0000
+++ b/MFCC.py	Thu Nov 29 11:17:45 2012 +0000
@@ -40,16 +40,16 @@
 		if self.updated: return self.valid
 		self.updated = True
 		self.valid = False
-		print 'Updating parameters and recalculating filters: '
-		print 'Nyquist: ',self.NqHz
+		print('Updating parameters and recalculating filters: ')
+		print('Nyquist: ',self.NqHz)
 		
 		if self.maxHz > self.NqHz : 
 			raise Exception('Maximum frequency must be smaller than the Nyquist frequency')
 		
 		self.maxMel = 1000*log(1+self.maxHz/700.0)/log(1+1000.0/700.0)
 		self.minMel = 1000*log(1+self.minHz/700.0)/log(1+1000.0/700.0)
-		print 'minHz:%s\nmaxHz:%s\nminMel:%s\nmaxMel:%s\n' \
-		%(self.minHz,self.maxHz,self.minMel,self.maxMel)
+		print('minHz:%s\nmaxHz:%s\nminMel:%s\nmaxMel:%s\n' \
+		%(self.minHz,self.maxHz,self.minMel,self.maxMel))
 		self.filterMatrix = self.getFilterMatrix(self.inputSize,self.numBands)
 		self.DCTMatrix = self.getDCTMatrix(self.numBands)
 		self.filterIter = self.filterMatrix.__iter__()
@@ -61,7 +61,7 @@
 		This function calculates two extra bands at the edges for
 		finding the starting and end point of the first and last 
 		actual filters.'''
-		centresMel = numpy.array(xrange(numBands+2)) * (self.maxMel-self.minMel)/(numBands+1) + self.minMel
+		centresMel = numpy.array(range(numBands+2)) * (self.maxMel-self.minMel)/(numBands+1) + self.minMel
 		centresBin = numpy.floor(0.5 + 700.0*inputSize*(exp(centresMel*log(1+1000.0/700.0)/1000.0)-1)/self.NqHz)
 		return numpy.array(centresBin,int)
 		
@@ -69,7 +69,7 @@
 		'''Compose the Mel scaling matrix.'''
 		filterMatrix = numpy.zeros((numBands,inputSize))
 		self.filterCentres = self.getFilterCentres(inputSize,numBands)
-		for i in xrange(numBands) :
+		for i in range(numBands) :
 			start,centre,end = self.filterCentres[i:i+3]
 			self.setFilter(filterMatrix[i],start,centre,end)
 		return filterMatrix.transpose()
@@ -78,8 +78,8 @@
 		'''Calculate a single Mel filter.'''
 		k1 = numpy.float32(filterCentre-filterStart)
 		k2 = numpy.float32(filterEnd-filterCentre)
-		up = (numpy.array(xrange(filterStart,filterCentre))-filterStart)/k1
-		dn = (filterEnd-numpy.array(xrange(filterCentre,filterEnd)))/k2
+		up = (numpy.array(range(filterStart,filterCentre))-filterStart)/k1
+		dn = (filterEnd-numpy.array(range(filterCentre,filterEnd)))/k2
 		filt[filterStart:filterCentre] = up
 		filt[filterCentre:filterEnd] = dn
 
@@ -90,7 +90,7 @@
 	def getDCTMatrix(self,size):
 		'''Calculate the square DCT transform matrix. Results are 
 		equivalent to Matlab dctmtx(n) with 64 bit precision.'''
-		DCTmx = numpy.array(xrange(size),numpy.float64).repeat(size).reshape(size,size)
+		DCTmx = numpy.array(range(size),numpy.float64).repeat(size).reshape(size,size)
 		DCTmxT = numpy.pi * (DCTmx.transpose()+0.5) / size
 		DCTmxT = (1.0/sqrt( size / 2.0)) * cos(DCTmx * DCTmxT)
 		DCTmxT[0] = DCTmxT[0] * (sqrt(2.0)/2.0)
--- a/README.md	Thu Nov 29 11:06:56 2012 +0000
+++ b/README.md	Thu Nov 29 11:17:45 2012 +0000
@@ -22,7 +22,7 @@
     * scikits.audiolab
     * sklearn.mixture
 
-It has been tested on python 2.7 (on ubuntu 11.10 and 12.04).
+It has been tested on python 2.7 (on ubuntu 11.10 and 12.04). Not yet tested on python3 but it should be fine...
 
 
 Usage example 1: commandline
--- a/smacpy.py	Thu Nov 29 11:06:56 2012 +0000
+++ b/smacpy.py	Thu Nov 29 11:17:45 2012 +0000
@@ -58,7 +58,7 @@
 		allfeatures = {wavpath:self.file_to_features(os.path.join(wavfolder, wavpath)) for wavpath in trainingdata}
 
 		# Determine the normalisation stats, and remember them
-		allconcat = np.vstack(allfeatures.values())
+		allconcat = np.vstack(list(allfeatures.values()))
 		self.means = np.mean(allconcat, 0)
 		self.invstds = np.std(allconcat, 0)
 		for i,val in enumerate(self.invstds):
@@ -69,7 +69,7 @@
 
 		# For each label, compile a normalised concatenated list of features
 		aggfeatures = {}
-		for wavpath, features in allfeatures.iteritems():
+		for wavpath, features in allfeatures.items():
 			label = trainingdata[wavpath]
 			normed = self.__normalise(features)
 			if label not in aggfeatures:
@@ -79,13 +79,13 @@
 
 		# For each label's aggregated features, train a GMM and remember it
 		self.gmms = {}
-		for label, aggf in aggfeatures.iteritems():
+		for label, aggf in aggfeatures.items():
 			if verbose:
-				print "    Training a GMM for label %s, using data of shape %s" % (label, str(np.shape(aggf)))
+				print("    Training a GMM for label %s, using data of shape %s" % (label, str(np.shape(aggf))))
 			self.gmms[label] = GMM(n_components=10, cvtype='full')
 			self.gmms[label].fit(aggf)
 		if verbose:
-			print "  Trained %i classes from %i input files" % (len(self.gmms), len(trainingdata))
+			print("  Trained %i classes from %i input files" % (len(self.gmms), len(trainingdata)))
 
 	def __normalise(self, data):
 		"Normalises data using the mean and stdev of the training data - so that everything is on a common scale."
@@ -97,7 +97,7 @@
 		# For each label GMM, find the overall log-likelihood and choose the strongest
 		bestlabel = ''
 		bestll = -9e99
-		for label, gmm in self.gmms.iteritems():
+		for label, gmm in self.gmms.items():
 			ll = gmm.eval(features)[0]
 			ll = np.sum(ll)
 			if ll > bestll:
@@ -107,7 +107,7 @@
 
 	def file_to_features(self, wavpath):
 		"Reads through a mono WAV file, converting each frame to the required features. Returns a 2D array."
-		if verbose: print "Reading %s" % wavpath
+		if verbose: print("Reading %s" % wavpath)
 		if not os.path.isfile(wavpath): raise ValueError("path %s not found" % path)
 		sf = Sndfile(wavpath, "r")
 		if sf.channels != 1:            raise ValueError("sound file has multiple channels (%i) - mono audio required." % sf.channels)
@@ -118,7 +118,7 @@
 			try:
 				chunk = sf.read_frames(framelen, dtype=np.float32)
 				if len(chunk) != framelen:
-					print "Not read sufficient samples - returning"
+					print("Not read sufficient samples - returning")
 					break
 				framespectrum = np.fft.fft(window * chunk)
 				magspec = abs(framespectrum[:framelen/2])
@@ -163,23 +163,23 @@
 		if len(wavsfound[onepath])==0:
 			raise RuntimeError("Found no files using this pattern: %s" % pattern)
 		if verbose:
-			print "Class-labels and filenames to be used from %s:" % onepath
-			for wavpath,label in sorted(wavsfound[onepath].iteritems()):
-				print " %s: \t %s" % (label, wavpath)
+			print("Class-labels and filenames to be used from %s:" % onepath)
+			for wavpath,label in sorted(wavsfound[onepath].items()):
+				print(" %s: \t %s" % (label, wavpath))
 
-	print "##################################################"
-	print "TRAINING"
+	print("##################################################")
+	print("TRAINING")
 	model = Smacpy(args['trainpath'], wavsfound['trainpath'])
 
-	print "##################################################"
-	print "TESTING"
+	print("##################################################")
+	print("TESTING")
 	if args['trainpath'] == args['testpath']:
-		print " (nb testing on the same files as used for training - for true evaluation please train and test on independent data):"
+		print(" (nb testing on the same files as used for training - for true evaluation please train and test on independent data):")
 	ncorrect = 0
-	for wavpath,label in wavsfound['testpath'].iteritems():
+	for wavpath,label in wavsfound['testpath'].items():
 		result = model.classify(os.path.join(args['testpath'], wavpath))
-		print " inferred: %s" % result
+		print(" inferred: %s" % result)
 		if result == label:
 			ncorrect += 1
-	print "Got %i correct out of %i (trained on %i classes)" % (ncorrect, len(wavsfound['testpath']), len(model.gmms))
+	print("Got %i correct out of %i (trained on %i classes)" % (ncorrect, len(wavsfound['testpath']), len(model.gmms)))