def testHandelImport(self): # can get a single file just by file name unused_fp = corpus.getWork('hwv56/movement1-01') # fpCollection = corpus.getComposer('handel') self.assertEqual(len(fpCollection) >= 1, True) fpCollection = corpus.getComposer('handel', ['md']) self.assertEqual(len(fpCollection) >= 1, True)
def testHandelImport(self): # can get a single file just by file name unused_fp = corpus.getWork('hwv56/movement1-01')# fpCollection = corpus.getComposer('handel') self.assertEqual(len(fpCollection) >= 1, True) fpCollection = corpus.getComposer('handel', ['md']) self.assertEqual(len(fpCollection) >= 1, True)
def testEssenImport(self): # can get a single file just by file name filePath = corpus.getWork('altdeu10') self.assertTrue(filePath.endswith('essenFolksong/altdeu10.abc') or filePath.endswith(r'essenFolksong\altdeu10.abc')) filePathCollection = corpus.getComposer('essenFolksong') self.assertEqual(len(filePathCollection), 31) filePathCollection = corpus.getComposer('essenFolksong', ['abc']) self.assertEqual(len(filePathCollection), 31)
def testDesPrezImport(self): # can get a single file just by file name filePath = str(corpus.getWork('fortunaDunGranTempo')) filePath = re.sub(r'\\', '/', filePath) self.assertEqual(filePath.endswith('josquin/fortunaDunGranTempo.abc'), True) filePathCollection = corpus.getComposer('josquin') self.assertEqual(len(filePathCollection) >= 8, True) filePathCollection = corpus.getComposer('josquin', ['abc']) self.assertEqual(len(filePathCollection) >= 8, True)
def testDesPrezImport(self): # can get a single file just by file name filePath = corpus.getWork("fortunaDunGranTempo") filePath = re.sub(r"\\", "/", filePath) self.assertEqual(filePath.endswith("josquin/fortunaDunGranTempo.abc"), True) filePathCollection = corpus.getComposer("josquin") self.assertEqual(len(filePathCollection) >= 8, True) filePathCollection = corpus.getComposer("josquin", ["abc"]) self.assertEqual(len(filePathCollection) >= 8, True)
def testDesPrezImport(self): # can get a single file just by file name filePath = str(corpus.getWork('fortunaDunGranTempo')) filePath = re.sub(r'\\', '/', filePath) self.assertTrue(filePath.endswith('josquin/fortunaDunGranTempo.abc')) filePathCollection = corpus.getComposer('josquin') self.assertGreaterEqual(len(filePathCollection), 8) filePathCollection = corpus.getComposer('josquin', ['abc']) self.assertGreaterEqual(len(filePathCollection), 8)
def testEssenImport(self): # can get a single file just by file name filePath = corpus.getWork('altdeu10') self.assertEqual(filePath.name, 'altdeu10.abc') self.assertEqual(filePath.parent.name, 'essenFolksong') filePathCollection = corpus.getComposer('essenFolksong') self.assertEqual(len(filePathCollection), 31) filePathCollection = corpus.getComposer('essenFolksong', ['abc']) self.assertEqual(len(filePathCollection), 31)
def testEssenImport(self): # can get a single file just by file name filePath = corpus.getWork("altdeu10") self.assertTrue( filePath.endswith("essenFolksong/altdeu10.abc") or filePath.endswith(r"essenFolksong\altdeu10.abc") ) filePathCollection = corpus.getComposer("essenFolksong") self.assertEqual(len(filePathCollection), 31) filePathCollection = corpus.getComposer("essenFolksong", ["abc"]) self.assertEqual(len(filePathCollection), 31)
def show_composer_works(composername): works = [] workPaths = corpus.getComposer(composername) for work in workPaths : filenameArr = os.path.split(work) works.append({'filename': filenameArr[-1], 'path': work}) return render_template('composer.html', works=works, composername=composername)
def chorales_from_corpus(): """ Return a list of Bach chorales """ chorales = corpus.getComposer('bach', 'xml') chorale_list = [] for chorale in chorales: chorale_list.append(converter.parse(chorale)) return chorale_list
def showComposers(): composers = [] composerDirs = os.listdir('/Users/TGriffey/anaconda/envs/music21-remix/lib/python2.7/site-packages/music21/corpus') for composerDir in composerDirs : works = corpus.getComposer(composerDir) if len(works) > 0 : composers.append(composerDir) return render_template('home.html', composers=composers)
def show_composer_works(composername): works = [] workPaths = corpus.getComposer(composername) for work in workPaths: filenameArr = os.path.split(work) works.append({'filename': filenameArr[-1], 'path': work}) return render_template('composer.html', works=works, composername=composername)
def main(): parser = get_cmd_line_parser(description=__doc__) parser.parse_args() work_path = numpy.random.choice(corpus.getComposer('bach')) work = corpus.parse(work_path) for note in work.flat.notes: print('{} [{}]: {} {}'.format(note.offset, note.duration.quarterLength, note.pitch, note.frequency)) return 0
def __init__(self, composer: Optional[str] = None): if composer is None: self.composer = "ALL" self.filenames = [ path for path in corpus.corpora.CoreCorpus().getPaths() if str(path).endswith(self._extensions) ] else: self.composer = composer self.filenames = corpus.getComposer(composer, self._extensions)
def showComposers(): composers = [] composerDirs = os.listdir( '/Users/TGriffey/anaconda/envs/music21-remix/lib/python2.7/site-packages/music21/corpus' ) for composerDir in composerDirs: works = corpus.getComposer(composerDir) if len(works) > 0: composers.append(composerDir) return render_template('home.html', composers=composers)
def testBachKeys(self): from music21 import key keyObjs = [] for filePath in corpus.getComposer('bach')[23:28]: # get 5 in the middle s = corpus.parse(filePath) # get keys from first part keyStream = s.parts[0].flat.getElementsByClass(key.KeySignature) keyObj = keyStream[0] keyObjs.append(keyObj) # environLocal.printDebug([keyObj]) self.assertEqual(len(keyObjs), 5)
def testBachKeys(self): from music21 import key keyObjs = [] for filePath in corpus.getComposer( 'bach')[23:28]: # get 5 in the middle s = corpus.parse(filePath) # get keys from first part keyObj = s.parts[0][key.KeySignature].first() keyObjs.append(keyObj) # environLocal.printDebug([keyObj]) self.assertEqual(len(keyObjs), 5)
def check_fetch_jsb(): """ Move files into tfbldr dir, in case python path is nfs """ all_bach_paths = corpus.getComposer("bach") partial_path = get_tfbldr_dataset_dir("jsb") for path in all_bach_paths: if "riemenschneider" in path: continue filename = os.path.split(path)[-1] local_path = os.path.join(partial_path, filename) if not os.path.exists(local_path): shutil.copy2(path, local_path) return partial_path
def check_fetch_bach_chorales_music21(): """ Move files into dagbldr dir, in case python is on nfs. """ from music21 import corpus all_bach_paths = corpus.getComposer("bach") partial_path = get_dataset_dir("bach_chorales_music21") for path in all_bach_paths: if "riemenschneider" in path: continue filename = os.path.split(path)[-1] local_path = os.path.join(partial_path, filename) if not os.path.exists(local_path): shutil.copy2(path, local_path) return partial_path
def check_fetch_bach_chorales_music21(): """ Move files into pthbldr dir, in case python is on nfs. """ from music21 import corpus all_bach_paths = corpus.getComposer("bach") partial_path = get_dataset_dir("bach_chorales_music21") for path in all_bach_paths: if "riemenschneider" in path: continue filename = os.path.split(path)[-1] local_path = os.path.join(partial_path, filename) if not os.path.exists(local_path): shutil.copy2(path, local_path) return partial_path
def GetWorksByComposer(composerName): """Create graphs of trajectories from corpus.""" listofWorks = corpus.getComposer(composerName) if len(listofWorks) > 150: listofWorks = list(islice(listofWorks, 150)) dictOfGraphs = dict() if len(listofWorks) > 0: for piece in listofWorks: try: print("Building Trajectory for ", piece) graph = GraphOfNewPiece(piece, 'corpus') dictOfGraphs = mergeDicts(dictOfGraphs, graph) except BaseException: print("--> Cannot build Trajectory for ", piece) return dictOfGraphs
def read_all_corpus(): # Corpus used here is Bach corp = getComposer('bach') # Filter any piece which can cause errors for our program excluded = [ 'bwv227.11.mxl', 'bwv248.23-2.mxl', 'bwv248.42-4.mxl', 'bwv377.mxl', 'bwv8.6.mxl', 'bwv846.mxl', 'bwv161.6.mxl', 'bwv248.64-6.mxl', 'bwv248.64-s.mxl', 'bwv36.4-2.mxl', 'bwv432.mxl' ] corp = [path for path in corp if not any(ex in path for ex in excluded)] # Read the corpus chords.read_chords_corpus(corp, debug=True) notes.read_notes_corpus(corp, debug=True) rhythm.read_rhythms_corpus(corp, debug=True)
def add_composer(composer, filetype, path, explicit_repeats): """ Music21 corpus pieces by composer. Use `firms_cli.py composers` to see a list of composers. """ start = time.time() sqlIRSystem = connect(path) paths = corpus.getComposer(composer, filetype) if len(paths) == 0: print("Error: no pieces found matching composer %s" % composer) else: print("Found %s pieces" % (len(paths))) for idx,path in enumerate(paths): print("\tProcessing piece %s: %s" % (idx, path)) stream = corpus.parse(path) for piece in stream.recurse(classFilter=m21stream.Score, skipSelf=False): sqlIRSystem.add_piece(piece, path, explicit_repeats) print("Ellapsed time: %s sec" % (time.time() - start))
def make_dataset(self, trainingSplit): #Make another function to create datasets from midi files in a given folder print("Making Dataset!") bundle = corpus.getComposer(self.composer, fileExtensions='mxl') #get all bach pieces print(len(bundle)) shuffle(bundle) #Shuffle to make dataset less likely to create a bias #bundle = bundle[:9] #Limit dataset size for testing tr_bundle = bundle[:int(len(bundle) * trainingSplit)] ts_bundle = bundle[int(len(bundle) * trainingSplit) + 1:] for idx, corpus_file_name in enumerate(tr_bundle): piece = MusicalPiece() piece.load_song(str(corpus_file_name)) transpositions = [ 0, 4, -4, 12, -12 ] #oriignal, up and down a major third, and up and down an octave for trans_idx in range(len(transpositions)): trans = transpositions[trans_idx] piece.make_pitches_one_hot(keep_chords=True, transposition=trans) self.train = self.train + piece.one_hot_vector_sequence for idx, corpus_file_name in enumerate(ts_bundle): piece = MusicalPiece() piece.load_song(str(corpus_file_name)) transpositions = [0, 4, -4, 12, -12] #oriignal, up and down a major third, and up and down an octave for trans_idx in range(len(transpositions)): trans = transpositions[trans_idx] piece.make_pitches_one_hot(keep_chords=True, transposition=trans) self.test = self.test + piece.one_hot_vector_sequence print("Dataset complete!")
from music21 import corpus # Corpus used here is Bach corp = corpus.getComposer('bach') # Filter any piece which can cause errors for our program excluded = [ 'bwv227.11.mxl', 'bwv248.23-2.mxl', 'bwv248.42-4.mxl', 'bwv377.mxl', 'bwv8.6.mxl', 'bwv846.mxl', 'bwv161.6.mxl', 'bwv248.64-6.mxl', 'bwv248.64-s.mxl', 'bwv36.4-2.mxl', 'bwv432.mxl' ] corp = [path for path in corp if not any(ex in path for ex in excluded)] no_correct = 0 print(' Actual | Pred ') print('-----------------') for path in corp: song = corpus.parse(path) key_gold = [key for key in song.flat.getElementsByClass('Key')][0] key_pred = song.analyze('key') no_correct += int(key_gold == key_pred) if key_gold != key_pred: print('{} | {}'.format(key_gold, key_pred)) print('Key Signature Detection accuracy: {}'.format( float(no_correct) / len(corp)))
me.data = '' mt.events.append(me) all_mt.append(mt) mf = MidiFile() mf.ticksPerQuarterNote = int(tempo_multiplier * qpm_mult) for mt in all_mt: mf.tracks.append(mt) mf.open(outfile, 'wb') mf.write() mf.close() start = time.time() all_bach_paths = corpus.getComposer('bach') print("Total number of Bach pieces to process from music21: %i" % len(all_bach_paths)) skipped = 0 processed = 0 n_major = 0 n_minor = 0 all_major = [] all_minor = [] for it, p_bach in enumerate(all_bach_paths): if "riemenschneider" in str(p_bach): # skip certain files we don't care about skipped += 1 continue p = corpus.parse(p_bach) if len(p.parts) != 4:
#%% from music21 import note,stream,corpus,chord,environment,converter,midi,duration,chord import matplotlib as pyplot pyplot.rcParams['figure.figsize'] = (20.0, 10.0) pyplot.rcParams["figure.dpi"] = 200 #%% bachCount = corpus.getComposer('bach') len(bachCount) #%% bwv846 = corpus.parse('bach/bwv846') bwv846.measures(1, 2).show() #%% bwv846.show('midi') #%% bwv846.parts[0].plot() bwv846.parts[1].plot() bwv846.plot() #%% bwv846.plot('histogram', 'pitch') #%% bwv846.plot('histogram', 'pitchClass') #%% bwv846.plot('3dbars', 'pitchClass')