def createSpectrogram(filename,newFilename): #Create temporary mono track if needed if isMono(rawDataPath+filename): command = "cp '{}' 'tmp\\{}.mp3'".format(rawDataPath+filename,newFilename) else: command = '"C:\Program Files (x86)\sox-14-4-2\sox" "{}" "tmp\\{}.mp3" remix 1,2'.format(rawDataPath+filename,newFilename) print (command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=currentPath) output, errors = p.communicate() if errors: print (errors) #Create spectrogram filename.replace(".mp3","") command = '"C:\Program Files (x86)\sox-14-4-2\sox" "tmp\\{}.mp3" -n spectrogram -Y 200 -X {} -m -r -o "{}.png"'.format(newFilename,pixelPerSecond,spectrogramsPath+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=currentPath) print(command) output, errors = p.communicate() if errors: print (errors) try: #Remove tmp mono track os.remove("tmp\\{}.mp3".format(newFilename)) except Exception as e: print (str(e))
def createSpectrogram(filename,newFilename): #Create temporary mono track if needed if isMono(rawDataPath+filename): print('mono') command = "cp '{}' '/tmp/{}.mp3'".format(rawDataPath+filename,newFilename) print(command) else: command = "sox '{}' '/tmp/{}.mp3' remix 1,2".format(rawDataPath+filename,newFilename) print(command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Create spectrogram filename.replace(".mp3","") command = "sox '/tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format(newFilename,pixelPerSecond,spectrogramsPath+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Remove tmp mono track try: os.remove("/tmp/{}.mp3".format(newFilename)) except FileNotFoundError as err: print(err)
def AudioToSlices(audiofilename): newFilename = audiofilename.replace(".mp3", "")+"_dan" if isMono("single/" + audiofilename): command = "cp 'single/{}' 'single/{}.mp3'".format(audiofilename,newFilename) else: command = "sox 'single/{}' 'single/{}.mp3' remix 1,2".format(audiofilename,newFilename)#转成单声道 shell_runner(command) command = "sox 'single/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o 'single/{}.png'".format(newFilename,pixelPerSecond,newFilename) shell_runner(command) png2slices(newFilename)
def AudioToSlices(Path, audiofilename): #print ("Creating spectrograms...") #print ("Creating spectrogram for file {}".format(audiofilename)) # fileGenre = getGenre(Path + audiofilename) # # fileGenre = str(fileGenre) # fileGenre = str(fileGenre, encoding='utf-8') # # print(fileGenre) # genresID[fileGenre] = genresID[fileGenre] + 1 if fileGenre in genresID else 1 # fileID = genresID[fileGenre] newFilename = audiofilename.replace(".mp3", "") + "_dan" if isMono(Path + audiofilename): command = "cp '{}' 'Music_single/{}.mp3'".format( Path + audiofilename, newFilename) else: command = "sox '{}' 'Music_single/{}.mp3' remix 1,2".format( Path + audiofilename, newFilename) #转成单声道 #print(command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #filename.replace(".mp3","") command = "sox 'Music_single/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o 'Music_single/{}.png'".format( newFilename, pixelPerSecond, newFilename) #print(command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Remove tmp mono track #os.remove("./{}.mp3".format(newFilename))#删除单声道文件 #os.remove(rawPrePath+audiofilename)#删除源文件 #print ("Spectrograms created!") #print ("Creating slices...") #print(newFilename) png2slices(Path, newFilename)
def mp2png(filename,newFilename): #Create temporary mono track if needed print('wewe') if isMono(filename): command = "cp '{}' './tmp/{}.mp3'".format(filename,newFilename) else: command = "sox '{}' './tmp/{}.mp3' remix 1,2".format(filename,newFilename) os.system(command) print('fefe') #Create spectrogram filename.replace(".mp3","") command = "sox './tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format(newFilename,pixelPerSecond,newFilename) os.system(command)
def createSpectrogram(filename, newFilename, genre): #Create temporary mono track if needed file_path = rawDataPath + '/' + genre + '/' + filename if isMono(file_path): command = "cp '{}' 'tmp/{}.mp3'".format(file_path, newFilename) else: command = "sox '{}' 'tmp/{}.mp3' remix 1,2".format( file_path, newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) print(command) output, errors = p.communicate() if errors: print(errors) #Create spectrogram filename.replace(".mp3", "") command = "sox 'tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -ocr -o '{}.png'".format( newFilename, pixelPerSecond, spectrogramsPath + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) # print(command) output, errors = p.communicate() if errors: print(errors) #Remove tmp mono track try: os.remove("tmp/{}.mp3".format(newFilename)) except Exception as e: print(e)
def createSpectrogram(filename, newFilename): #Create temporary mono track if needed if isMono(rawDataPath + filename): #Copy the file as is command = 'cp "{}" "{}"'.format(rawDataPath + filename, tempDataPath + newFilename) else: #Creates a mono(single channel) output file which is a mix-down of input channels 1 and 2 command = 'sox "{}" "{}" remix 1,2'.format(rawDataPath + filename, tempDataPath + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) filename.replace(".mp3", "") #Create monochrome(-m) raw spectrogram(-r) with resolution of (pixelPerSecond by 200) pixels in size (-X, -Y) # Raw spectrogram : suppress the display of axes and legends command = "sox '{}' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format( tempDataPath + newFilename, pixelPerSecond, spectrogramsPath + newFilename.replace(".mp3", "")) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Remove tmp mono track os.remove(tempDataPath + newFilename)
def createSpectrogram(filename,newFilename): #Create temporary mono track if needed if isMono(rawDataPath+filename): command = "cp '{}' '/tmp/{}.mp3'".format(rawDataPath+filename,newFilename) else: command = "sox '{}' '/tmp/{}.mp3' remix 1,2".format(rawDataPath+filename,newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print errors #Create spectrogram filename.replace(".mp3","") command = "sox '/tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format(newFilename,pixelPerSecond,spectrogramsPath+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print errors #Remove tmp mono track os.remove("/tmp/{}.mp3".format(newFilename))
def createInputSpectrogram(filename, newFilename): #Create temporary mono track if needed print "In createInputSpectrogram" if isMono(inputDataPath + filename): command = "cp '{}' '/tmp/{}.mp3'".format(inputDataPath + filename, newFilename) else: command = "sox '{}' '/tmp/{}.mp3' remix 1,2".format( inputDataPath + filename, newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print errors #Create spectrogram filename.replace(".mp3", "") command = "sox '/tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format( newFilename, pixelPerSecond, spectrogramsInputPath + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print errors #Remove tmp mono track os.remove("/tmp/{}.mp3".format(newFilename))
def createLinearSpectrogramSox(filename, newFilename): '''Create spectrogram from mp3 files''' # Create temporary mono track if needed if isMono(rawDataPath + filename): command = "cp '{}' '/tmp/{}.mp3'".format(rawDataPath + filename, newFilename) else: command = 'sox "{}" "/tmp/{}.mp3" remix 1,2'.format( rawDataPath + filename, newFilename) process = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=current_path) # pylint: disable=unused-variable output, errors = process.communicate() if errors: print(errors) # Create spectrogram filename.replace(".mp3", "") # trim 20 will cut 20 seconds off front of song command = 'sox "/tmp/{}.mp3" -n trim 20 spectrogram -w Hamming -Y 200 -X {} -m -r -o "{}.png"'.format(newFilename, \ pixelPerSecond, spectrogramsPath + newFilename) # -r removes axes process = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, cwd=current_path) # pylint: disable=unused-variable output, errors = process.communicate() if errors: print(errors) # Remove tmp mono track os.remove("/tmp/{}.mp3".format(newFilename))
def createSpectrogram(filename,newFilename): #Create temporary mono track if needed print("This is the new filename",newFilename) if isMono(rawDataPath+filename): command = "cp '{}' './tmp/{}.mp3'".format(rawDataPath+filename,newFilename) else: command = "sox '{}' './tmp/{}.mp3' remix 1,2".format(rawDataPath+filename,newFilename) print("This is the first command",command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) print("Open successfully") output, errors = p.communicate() if errors: print(errors) #Create spectrogram filename.replace(".mp3","") command = "sox './tmp/{}.mp3' -n spectrogram -Y 200 -X {} -m -r -o '{}.png'".format(newFilename,pixelPerSecond,spectrogramsPath+newFilename) print("This is command",command) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() print("shit") if errors: print(errors)
def createSpectrogram(filename, newFilename): #Create temporary mono track if needed if isMono(rawDataPath + filename): command = 'cp "{}" "{}.mp3"'.format(rawDataPath + filename, tempPath + newFilename) else: command = 'sox "{}" "{}.mp3" remix 1,2'.format(rawDataPath + filename, tempPath + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=False, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Create spectrogram filename.replace(".mp3", "") command = 'sox "{}.mp3" -n spectrogram -Y 200 -X {} -m -r -o "{}.png"'.format( tempPath + newFilename, pixelPerSecond, spectrogramsPath + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=False, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Remove tmp mono track if os.path.exists("Data/temp/{}.mp3".format(newFilename)): os.remove("Data/temp/{}.mp3".format(newFilename))
def classify(): #List genres genres = os.listdir(slicesPath) genres = [filename for filename in genres if os.path.isdir(slicesPath+filename)] nbClasses = len(genres) #Create model model = createModel(nbClasses, sliceSize) #s = song() #lib = library() #create spectrogram path if it doesn't exist if not os.path.exists(os.path.dirname(predictSpect)): try: os.makedirs(os.path.dirname(predictSpect)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise #create slice path if it doesn't exist if not os.path.exists(os.path.dirname(predSlicePath)): try: os.makedirs(os.path.dirname(predSlicePath)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise counter = 0 #print ("Creating Spectrogams") #parse through all files in library and create spectrograms for filename in os.listdir(predictionPath): if filename.endswith(".mp3"): newFilename = 'new_' + filename newFilename = newFilename.replace(".mp3", "") if (Path(predictSpect+newFilename)).exists(): break if(isMono(predictionPath+filename)): command = "cp '{}' '/tmp/{}.wav' remix 1,2".format(predictionPath+filename, newFilename) else: command = "sox '{}' '/tmp/{}.wav' remix 1,2".format(predictionPath+filename,newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print (errors) #create spectrogram from given file filename.replace(".mp3","") #print "Creating spectrogram for file {}".format(filename) command = "sox '/tmp/{}.wav' -n spectrogram -Y 200 -X 50 -m -r -o '{}.png'".format(newFilename,predictSpect+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print (errors) #Remove tmp mono track #os.remove("/tmp/{}.wav".format(newFilename)) counter += 1 subdata = [] data = [] #print ("Spectrogams Created! ") #slice spectrograms #print ("Slicing Spectrogams") for newFilename in os.listdir(predictSpect): if newFilename.endswith(".png"): #slice img = Image.open(predictSpect+newFilename) width, height = img.size nbSamples = int(width/sliceSize) width - sliceSize #For each sample for i in range(nbSamples): #print "Creating slice: ", (i+1), "/", nbSamples, "for", newFilename #Extract and save 128x128 sample startPixel = i*sliceSize imgTmp = img.crop((startPixel, 1, startPixel + sliceSize, sliceSize + 1)) imgTmp.save(predSlicePath+"{}_{}.png".format(newFilename[:-4],i)) img_array = getImageData(predSlicePath+newFilename[:-4]+"_"+str(i)+".png", sliceSize) #append each loaded image to a sub-data array, and break to new subdata element when name changes subdata.append(img_array) #os.remove() #append sub-data array to super array data.append(subdata) subdata = [] #print ("Slices Created! ") model.load('python/musicDNN.tflearn') #print ("Model loaded! ") #print data #parse through super array predicting each one #and assign name to song object then append song object to songList in library #print ("Predicting") for vec in data: predictionSoftmax = model.predict(vec)[0] predictedIndex = max(enumerate(predictionSoftmax), key=lambda x:x[1])[0] s.vector = predictionSoftmax s.name = filename in os.listdir(predictionPath) s.genre = genres[predictedIndex] lib.songList.append(s.vector) lib.labels.append(s.genre) for x in lib.songList: print x
#Define currentPath = os.path.dirname(os.path.realpath(__file__)) file = "test.mp3" newFilename = "testmono" desiredSize = 128 #Create path if not existing slicePath = preTemp + "predictSlice\\" if not os.path.exists(os.path.dirname(slicePath)): try: os.makedirs(os.path.dirname(slicePath)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise if isMono(file): command = 'cp "{}" "{}.mp3"'.format(file, preTemp + newFilename) else: command = 'sox "{}" "{}.mp3" remix 1,2'.format(file, preTemp + newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=False, cwd=currentPath) output, errors = p.communicate() if errors: print(errors) #Create spectrogram
def Send_File_to_Server(): try: if(os.path.isfile('received')): return desiredSize = 128 port = 12345 time.sleep(1) #Create path if not existing slicePath = preTemp+"predictSlice\\"; if not os.path.exists(os.path.dirname(slicePath)): try: os.makedirs(os.path.dirname(slicePath)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise if isMono(file): command = 'cp "{}" "{}.mp3"'.format(file,preTemp+newFilename) else: command = 'sox "{}" "{}.mp3" remix 1,2'.format(file,preTemp+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=False, cwd=currentPath) output, errors = p.communicate() if errors: print (errors) #Create spectrogram command = 'sox "{}.mp3" -n spectrogram -Y 200 -X {} -m -r -o "{}.png"'.format(preTemp+newFilename,pixelPerSecond,preTemp+newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=False, cwd=currentPath) output, errors = p.communicate() if errors: print (errors) #Remove tmp mono track if os.path.exists("{}.mp3".format(preTemp+newFilename)): os.remove("{}.mp3".format(preTemp+newFilename)) # Load the full spectrogram img = Image.open(preTemp+newFilename+".png") #Compute approximate number of 128x128 samples width, height = img.size nbSamples = int(width/desiredSize) width - desiredSize #For each sample for i in range(nbSamples): #Extract and save 128x128 sample startPixel = i*desiredSize imgTmp = img.crop((startPixel, 1, startPixel + desiredSize, desiredSize + 1)) imgTmp.save(slicePath+"{}/{}_{}.png".format("",newFilename[:-4],i)) print ("Slices Created... ") # Create Array nbClasses = 13 filenames = os.listdir(slicePath) print (filenames) data = [] trainNb = 0 for filename in filenames: imgData = getImageData(slicePath+"/"+filename, sliceSize) data.append((imgData)) trainNb = trainNb + 1 print ("FEED_DATA #############################################################") feedData = np.array(data[:trainNb]).reshape([-1, sliceSize, sliceSize, 1]) print(feedData) datatosend = feedData.tolist() print ("data_arr created ..........") print ("sending data ....") s=socket.socket() # hostname = socket.gethostbyname('baap') s.connect(("127.0.0.1", port)) data = s.send(pickle.dumps(datatosend)) s.shutdown(socket.SHUT_WR) print("slices ready to rock!!!") print("data send") f = open('file2send','wb') # Open in binary l = s.recv(1024) timeout = time.time() + 10 # 5 minutes from now while (l): print ("Receiving...") f.write(l) l = s.recv(1024) f.close() os.rename('file2send', 'received') s.close() print("Receivied") except Exception as e: print (e) raise return
model.load('musicDNN.tflearn') print(" Weights loaded! ✅") testAccuracy = model.evaluate(test_X, test_y)[0] print("[+] Test accuracy: {}".format(testAccuracy)) if "predict" in args.mode: #get name of input file to predict userinput = raw_input('Input a file to predict genre: ') #userinput = 'Classical_4' userinput += '.mp3' newFilename = 'new_' + userinput newFilename = newFilename.replace(".mp3", "") if (isMono(userinput)): command = "cp '{}' '/tmp/{}.wav'".format(userinput, newFilename) else: command = "sox '{}' '/tmp/{}.wav' remix 1,2".format( userinput, newFilename) p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, cwd=currentPath) output, errors = p.communicate() if errors: print(errors)