Ejemplo n.º 1
0
def getMidiFromWave(folder, file, dataBase="DataBase/MIDIs/mozart/"):
	
	window_size = 172

	model2 = torch.load(folder + "model2.data")
	model2.eval()

	dico = pickle.load(open(folder + "dico.data", "rb"))

	w = waveForm.waveForm(file).getCQT()

	CQTs = []
	for i in range(len(w[0])//172 -1):
		CQTs.append(w[ : , i*window_size : (i+1)*window_size])
		CQTs[i] = np.array(CQTs[i]).astype(float)
		CQTs[i] = CQTs[i].reshape(1, 1, CQTs[i].shape[0], CQTs[i].shape[1])
		CQTs[i] = torch.FloatTensor(CQTs[i])

	wraps = []
	for i in tqdm(range(len(CQTs[:10]))):
		wraps.append(nearestNeighbor(dico, model2.forward(CQTs[i]).data))

	pianoroll = None

	for elem in wraps:
		end = int(elem[elem.rfind("_")+1:])
		name = elem[:elem.rfind("_")]
		start = int(name[name.rfind("_")+1:])
		name = name[:name.rfind("_")]	

		s = score.score(dataBase + name + ".mid")
		s = s.extractPart(start, end)

		if pianoroll is None:
			pianoroll = s.pianoroll
		else:
			pianoroll = np.concatenate((pianoroll, s.pianoroll), axis=0)

	out = score.score("", fromArray=(pianoroll, "out"))

	print(out.getPianoRoll())
	print(out.getPianoRoll().shape)

	out_name = file[:file.rfind(".")] + ".mid"
	out.writeToMidi("out.mid")

	print("File saved in", out_name)
Ejemplo n.º 2
0
	def addToDictionary(self, file, computeSound=True, pathTemp="/fast/guilhem/"):
		'''Adds all pianoroll snippets extracted from a given file.
		
		Parameters
		----------
		file : str
			Name of the file from which we extract the snippets.
		computeSound : bool, optional
			If True, creates a .wav file to inject in the latent space.
		pathTemp : str, optional
			The folder in which we save the temporary WaveForm files.
		'''

		windowSize = 4
		STEP = 2
		snippets = []

		self.model1.eval()

		s = score.score(file, outPath=pathTemp)
		if computeSound is True:
			file = file[file.rfind("/")+1:]
			file = file[:file.rfind(".")]
			s.toWaveForm().save(pathTemp +  file + ".wav")

		windowSize *= s.quantization
		N = s.length * s.quantization

		#for i in range((N-windowSize)//STEP):
		for i in range(10):
			tmpPart1 = s.extractPart(i*STEP, i*STEP+windowSize)
			N1 = np.array(tmpPart1.getPianoRoll()).astype(float)
			N1 = N1.reshape(1, 1, N1.shape[0], N1.shape[1])
			X1 = torch.FloatTensor(N1)  
			if self.GPU:
				X1 = X1.cuda()

			embedded = self.model1.forward(X1)[0]

			self.dico[embedded] = tmpPart1.name
Ejemplo n.º 3
0
    def constructDatabase(self, path, name=None):
        """Construct the database of tuples from an existing midi database.

        Parameters
        ----------
        path : str
            The path to the folder to load (must contain midi files).
        name : str, optional
            The name to give to the database object.
        """

        if os.path.isdir(path):
            self.path = path
            if name:
                self.name = name
            else:
                self.name = str(path)
            print()
            print("________ We are working on '" + path + "'")
            print()
        else:
            print(
                "The path you gave is not a directory, please provide a correct directory."
            )
            raise RuntimeError("Invalid database directory")

        if not os.path.isdir(".TEMP"):
            os.makedirs(".TEMP")

        print("_____ Filling the database ...")
        print()

        # Number of skiped files
        skipedFiles = 0
        # Total number of files
        N = 0
        scores = []
        for filename in glob(self.path + '/**', recursive=True):

            if filename[filename.rfind("."):] in [".mid", ".midi"]:
                if os.path.isfile(filename):
                    print(" -", filename)
                    try:
                        scores.append(
                            score.score(filename, outPath=self.outPath))

                    except RuntimeError:
                        skipedFiles += 1
                    N += 1

        print()
        print("We passed a total of ", N, "files.")
        print(skipedFiles, "of them have been skiped.")
        print()

        print("_____ Augmenting database ...")
        print()

        #scores = self.augmentData(scores)

        print("_____ Computing the sound ...")
        print()

        shapes1 = []
        shapes2 = []

        for s in tqdm(scores):
            waveforms = []
            spectrum_temp = []

            N = s.length * s.quantization
            windowSize = WINDOW_SIZE * s.quantization
            retParts = []
            r = []

            for f in range(len(FONTS)):
                spectrum_temp.append(s.toWaveForm(font=FONTS[f]).getCQT())
                r.append(spectrum_temp[f].shape[1] / s.getPianoRoll().shape[1])

            tmpPart1 = []
            tmpPart2 = []
            for i in range((N - windowSize) // STEP):
                tmpPart1 = s.extractPart(i * STEP, i * STEP + windowSize)
                tmpPart2 = []
                tmpNames = []
                for f in range(len(FONTS)):

                    tmpPart2.append(
                        spectrum_temp[f][:,
                                         round(i * STEP *
                                               r[f]):round(i * STEP * r[f]) +
                                         round(windowSize * r[f])])
                    tmpNames.append(tmpPart1.name + "-" + FONTS[f])

                self.data.append((tmpPart1.getPianoRoll(), tmpPart2, tmpNames))

                if DEBUG:
                    if str(tmpPart1.getPianoRoll().shape) not in shapes1:
                        shapes1.append(str(tmpPart1.getPianoRoll().shape))
                    if str(tmpPart2[0].shape) not in shapes2:
                        shapes2.append(str(tmpPart2[0].shape))

        random.shuffle(self.data)

        if DEBUG:
            print("Shape 1")
            print(shapes1)
            print()
            print("Shape 2")
            print(shapes2)
import sys
import time
import pylab
sys.path.append('..')

from Modules import score
from Modules import waveForm
'''
	You can instanciate from a score object and extract parts from it.
	Then you can create associated waveForm objects.
'''

s = score.score('dataBaseTest/MIDIs/xmas/bk_xmas3.mid')
s1 = s.extractAllParts(5, step=1000)
print(s1)

w = []
for midipart in s1:
    midipart.writeToMidi('../' + midipart.name + ".mid")
    w.append(midipart.toWaveForm())
print(w)

STFTarrays = []
CQT = []

t1 = time.time()
for wavepart in w:
    STFTarrays.append(wavepart.getSTFTlog())
t2 = time.time()
t3 = time.time()
for wavepart in w: