def testSimpleSequenceToPrettyMidi_DropEventsAfterLastNote(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto( source_midi) # Add a final tempo long after the last note. multi_tempo_sequence_proto.tempos.add(time=600.0, qpm=120) # Translate without dropping. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto) # Translate dropping anything after the last note. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=0) # The added tempo should have been dropped. del multi_tempo_sequence_proto.tempos[-1] self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto) # Add a final tempo 15 seconds after the last note. last_note_time = max( [n.end_time for n in multi_tempo_sequence_proto.notes]) multi_tempo_sequence_proto.tempos.add(time=last_note_time + 15, qpm=120) # Translate dropping anything 30 seconds after the last note, which should # preserve the added tempo. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=30) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def CheckReadWriteMidi(self, filename): """Test writing to a MIDI file and comparing it to the original Sequence.""" # TODO(deck): The input MIDI file is opened in pretty-midi and # re-written to a temp file, sanitizing the MIDI data (reordering # note ons, etc). Issue 85 in the pretty-midi GitHub # (http://github.com/craffel/pretty-midi/issues/85) requests that # this sanitization be available outside of the context of a file # write. If that is implemented, this rewrite code should be # modified or deleted. # When writing to the temp file, use the file object itself instead of # file.name to avoid the permission error on Windows. with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as rewrite_file: original_midi = pretty_midi.PrettyMIDI(filename) original_midi.write(rewrite_file) # Use file object # Back the file position to top to reload the rewrite_file rewrite_file.seek(0) source_midi = pretty_midi.PrettyMIDI( rewrite_file) # Use file object sequence_proto = midi_io.midi_to_sequence_proto(source_midi) # Translate the NoteSequence to MIDI and write to a file. with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as temp_file: midi_io.sequence_proto_to_midi_file(sequence_proto, temp_file.name) # Read it back in and compare to source. created_midi = pretty_midi.PrettyMIDI(temp_file) # Use file object self.CheckPrettyMidiAndSequence(created_midi, sequence_proto)
def CheckReadWriteMidi(self, filename): """Test writing to a MIDI file and comparing it to the original Sequence.""" # TODO(deck): The input MIDI file is opened in pretty-midi and # re-written to a temp file, sanitizing the MIDI data (reordering # note ons, etc). Issue 85 in the pretty-midi GitHub # (http://github.com/craffel/pretty-midi/issues/85) requests that # this sanitization be available outside of the context of a file # write. If that is implemented, this rewrite code should be # modified or deleted. # When writing to the temp file, use the file object itself instead of # file.name to avoid the permission error on Windows. with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as rewrite_file: original_midi = pretty_midi.PrettyMIDI(filename) original_midi.write(rewrite_file) # Use file object # Back the file position to top to reload the rewrite_file rewrite_file.seek(0) source_midi = pretty_midi.PrettyMIDI(rewrite_file) # Use file object sequence_proto = midi_io.midi_to_sequence_proto(source_midi) # Translate the NoteSequence to MIDI and write to a file. with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as temp_file: midi_io.sequence_proto_to_midi_file(sequence_proto, temp_file.name) # Read it back in and compare to source. created_midi = pretty_midi.PrettyMIDI(temp_file) # Use file object self.CheckPrettyMidiAndSequence(created_midi, sequence_proto)
def testSimpleSequenceToPrettyMidi_DropEventsAfterLastNote(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) # Add a final tempo long after the last note. multi_tempo_sequence_proto.tempos.add(time=600.0, qpm=120) # Translate without dropping. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto) # Translate dropping anything after the last note. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=0) # The added tempo should have been dropped. del multi_tempo_sequence_proto.tempos[-1] self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto) # Add a final tempo 15 seconds after the last note. last_note_time = max([n.end_time for n in multi_tempo_sequence_proto.notes]) multi_tempo_sequence_proto.tempos.add(time=last_note_time + 15, qpm=120) # Translate dropping anything 30 seconds after the last note, which should # preserve the added tempo. translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=30) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def generate_midi(midi_data, total_seconds=10): primer_sequence = midi_io.midi_to_sequence_proto(midi_data) generate_request = generator_pb2.GenerateSequenceRequest() if len(primer_sequence.notes) > 4: estimated_tempo = midi_data.estimate_tempo() if estimated_tempo > 240: qpm = estimated_tempo / 2 else: qpm = estimated_tempo else: qpm = 120 primer_sequence.tempos[0].qpm = qpm generate_request.input_sequence.CopyFrom(primer_sequence) generate_section = (generate_request.generator_options.generate_sections.add()) # Set the start time to begin on the next step after the last note ends. notes_by_end_time = sorted(primer_sequence.notes, key=lambda n: n.end_time) last_end_time = notes_by_end_time[-1].end_time if notes_by_end_time else 0 generate_section.start_time_seconds = last_end_time + _steps_to_seconds( 1, qpm) generate_section.end_time_seconds = total_seconds # generate_response = generator_map[generator_name].generate(generate_request) generate_response = basic_generator.generate(generate_request) output = tempfile.NamedTemporaryFile() midi_io.sequence_proto_to_midi_file( generate_response.generated_sequence, output.name) output.seek(0) return output
def convert_midi(root_dir, sub_dir, full_file_path): """Converts a midi file to a sequence proto. Args: root_dir: A string specifying the root directory for the files being converted. sub_dir: The directory being converted currently. full_file_path: the full path to the file to convert. Returns: Either a NoteSequence proto or None if the file could not be converted. """ try: sequence = midi_io.midi_to_sequence_proto( tf.gfile.FastGFile(full_file_path, 'rb').read()) except midi_io.MIDIConversionError as e: tf.logging.warning( 'Could not parse MIDI file %s. It will be skipped. Error was: %s', full_file_path, e) return None sequence.collection_name = os.path.basename(root_dir) sequence.filename = os.path.join(sub_dir, os.path.basename(full_file_path)) sequence.id = note_sequence_io.generate_note_sequence_id( sequence.filename, sequence.collection_name, 'midi') return sequence
def convert_midi(root_dir, sub_dir, full_file_path): """Converts a midi file to a sequence proto. Args: root_dir: A string specifying the root directory for the files being converted. sub_dir: The directory being converted currently. full_file_path: the full path to the file to convert. Returns: Either a NoteSequence proto or None if the file could not be converted. """ try: sequence = midi_io.midi_to_sequence_proto( tf.gfile.FastGFile(full_file_path, 'rb').read()) except midi_io.MIDIConversionError as e: tf.logging.warning( 'Could not parse MIDI file %s. It will be skipped. Error was: %s', full_file_path, e) return None sequence.collection_name = os.path.basename(root_dir) sequence.filename = os.path.join(sub_dir, os.path.basename(full_file_path)) sequence.id = note_sequence_io.generate_note_sequence_id( sequence.filename, sequence.collection_name, 'midi') tf.logging.info('Converted MIDI file %s.', full_file_path) return sequence
def testSimpleSequenceToPrettyMidi_MultipleTempos(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def testSimpleSequenceToPrettyMidi_MultipleTempos(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def convert_directory(root_dir, sub_dir, sequence_writer, recursive=False): """Converts MIDIs to NoteSequences and writes to `sequence_writer`. MIDI files found in the specified directory specified by the combination of `root_dir` and `sub_dir` and converted to NoteSequence protos with the basename of `root_dir` as the collection_name, and the relative path to the MIDI file from `root_dir` as the filename. If `recursive` is true, recursively converts any subdirectories of the specified directory. Args: root_dir: A string specifying a root directory. sub_dir: A string specifying a path to a directory under `root_dir` in which to convert MIDI contents. sequence_writer: A NoteSequenceRecordWriter to write the resulting NoteSequence protos to. recursive: A boolean specifying whether or not recursively convert MIDIs contained in subdirectories of the specified directory. Returns: The number of NoteSequence protos written as an integer. """ dir_to_convert = os.path.join(root_dir, sub_dir) tf.logging.info("Converting MIDI files in '%s'.", dir_to_convert) files_in_dir = tf.gfile.ListDirectory(os.path.join(dir_to_convert)) recurse_sub_dirs = [] sequences_written = 0 sequences_skipped = 0 for file_in_dir in files_in_dir: full_file_path = os.path.join(dir_to_convert, file_in_dir) if tf.gfile.IsDirectory(full_file_path): if recursive: recurse_sub_dirs.append(os.path.join(sub_dir, file_in_dir)) continue try: sequence = midi_io.midi_to_sequence_proto( tf.gfile.FastGFile(full_file_path).read()) except midi_io.MIDIConversionError as e: tf.logging.warning( 'Could not parse MIDI file %s. It will be skipped. Error was: %s', full_file_path, e) sequences_skipped += 1 continue sequence.collection_name = os.path.basename(root_dir) sequence.filename = os.path.join(sub_dir, file_in_dir) sequence.id = note_sequence_io.generate_note_sequence_id( sequence.filename, sequence.collection_name, 'midi') sequence_writer.write(sequence) sequences_written += 1 tf.logging.info("Converted %d MIDI files in '%s'.", sequences_written, dir_to_convert) tf.logging.info('Could not parse %d MIDI files.', sequences_skipped) for recurse_sub_dir in recurse_sub_dirs: sequences_written += convert_directory(root_dir, recurse_sub_dir, sequence_writer, recursive) return sequences_written
def generate_test_set(): """Generate the test TFRecord.""" test_file_pairs = [] for directory in test_dirs: path = os.path.join(FLAGS.input_dir, directory) path = os.path.join(path, '*.wav') wav_files = glob.glob(path) # find matching mid files for wav_file in wav_files: base_name_root, _ = os.path.splitext(wav_file) mid_file = base_name_root + '.mid' test_file_pairs.append((wav_file, mid_file)) test_output_name = os.path.join(FLAGS.output_dir, 'maps_config2_test.tfrecord') with tf.python_io.TFRecordWriter(test_output_name) as writer: for pair in test_file_pairs: print(pair) # load the wav data and resample it. samples = audio_io.load_audio(pair[0], FLAGS.sample_rate) wav_data = audio_io.samples_to_wav_data(samples, FLAGS.sample_rate) # load the midi data and convert to a notesequence midi_data = tf.gfile.Open(pair[1]).read() ns = midi_io.midi_to_sequence_proto(midi_data) velocities = [note.velocity for note in ns.notes] velocity_max = np.max(velocities) velocity_min = np.min(velocities) new_velocity_tuple = music_pb2.VelocityRange( min=velocity_min, max=velocity_max) example = tf.train.Example(features=tf.train.Features(feature={ 'id': tf.train.Feature(bytes_list=tf.train.BytesList( value=[pair[0]] )), 'sequence': tf.train.Feature(bytes_list=tf.train.BytesList( value=[ns.SerializeToString()] )), 'audio': tf.train.Feature(bytes_list=tf.train.BytesList( value=[wav_data] )), 'velocity_range': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_velocity_tuple.SerializeToString()] )), })) writer.write(example.SerializeToString()) return [filename_to_id(wav) for wav, _ in test_file_pairs]
def generate_test_set(): """Generate the test TFRecord.""" test_file_pairs = [] for directory in test_dirs: path = os.path.join(FLAGS.input_dir, directory) path = os.path.join(path, '*.wav') wav_files = glob.glob(path) # find matching mid files for wav_file in wav_files: base_name_root, _ = os.path.splitext(wav_file) mid_file = base_name_root + '.mid' test_file_pairs.append((wav_file, mid_file)) test_output_name = os.path.join(FLAGS.output_dir, 'maps_config2_test.tfrecord') with tf.python_io.TFRecordWriter(test_output_name) as writer: for pair in test_file_pairs: print(pair) # load the wav data and resample it. samples = audio_io.load_audio(pair[0], FLAGS.sample_rate) wav_data = audio_io.samples_to_wav_data(samples, FLAGS.sample_rate) # load the midi data and convert to a notesequence midi_data = tf.gfile.Open(pair[1]).read() ns = midi_io.midi_to_sequence_proto(midi_data) velocities = [note.velocity for note in ns.notes] velocity_max = np.max(velocities) velocity_min = np.min(velocities) new_velocity_tuple = music_pb2.VelocityRange( min=velocity_min, max=velocity_max) example = tf.train.Example(features=tf.train.Features(feature={ 'id': tf.train.Feature(bytes_list=tf.train.BytesList( value=[pair[0]] )), 'sequence': tf.train.Feature(bytes_list=tf.train.BytesList( value=[ns.SerializeToString()] )), 'audio': tf.train.Feature(bytes_list=tf.train.BytesList( value=[wav_data] )), 'velocity_range': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_velocity_tuple.SerializeToString()] )), })) writer.write(example.SerializeToString()) return [filename_to_id(wav) for wav, _ in test_file_pairs]
def generate_train_set(): """Generate the train TFRecord.""" train_file_pairs = [] for directory in train_dirs: path = os.path.join(FLAGS.input_dir, directory) path = os.path.join(path, '*.wav') wav_files = glob.glob(path) # find matching mid files for wav_file in wav_files: base_name_root, _ = os.path.splitext(wav_file) mid_file = base_name_root + '.mid' train_file_pairs.append((wav_file, mid_file)) train_output_name = os.path.join(FLAGS.output_dir, 'maps_config2_train.tfrecord') with tf.python_io.TFRecordWriter(train_output_name) as writer: for pair in train_file_pairs: print(pair) # load the wav data wav_data = tf.gfile.Open(pair[0]).read() samples = audio_io.wav_data_to_samples(wav_data, FLAGS.sample_rate) # load the midi data and convert to a notesequence midi_data = tf.gfile.Open(pair[1]).read() ns = midi_io.midi_to_sequence_proto(midi_data) splits = find_split_points(ns, samples, FLAGS.sample_rate, FLAGS.min_length, FLAGS.max_length) for start, end in zip(splits[:-1], splits[1:]): if end - start < FLAGS.min_length: continue new_ns = sequences_lib.extract_subsequence(ns, start, end) new_wav_data = audio_io.crop_wav_data(wav_data, FLAGS.sample_rate, start, end - start) example = tf.train.Example(features=tf.train.Features(feature={ 'id': tf.train.Feature(bytes_list=tf.train.BytesList( value=[pair[0]] )), 'sequence': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_ns.SerializeToString()] )), 'audio': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_wav_data] )) })) writer.write(example.SerializeToString())
def generate_train_set(): """Generate the train TFRecord.""" train_file_pairs = [] for directory in train_dirs: path = os.path.join(FLAGS.input_dir, directory) path = os.path.join(path, '*.wav') wav_files = glob.glob(path) # find matching mid files for wav_file in wav_files: base_name_root, _ = os.path.splitext(wav_file) mid_file = base_name_root + '.mid' train_file_pairs.append((wav_file, mid_file)) train_output_name = os.path.join(FLAGS.output_dir, 'maps_config2_train.tfrecord') with tf.python_io.TFRecordWriter(train_output_name) as writer: for pair in train_file_pairs: print(pair) # load the wav data wav_data = tf.gfile.Open(pair[0]).read() samples = audio_io.wav_data_to_samples(wav_data, FLAGS.sample_rate) # load the midi data and convert to a notesequence midi_data = tf.gfile.Open(pair[1]).read() ns = midi_io.midi_to_sequence_proto(midi_data) splits = find_split_points(ns, samples, FLAGS.sample_rate, FLAGS.min_length, FLAGS.max_length) for start, end in zip(splits[:-1], splits[1:]): if end - start < FLAGS.min_length: continue new_ns = sequences_lib.extract_subsequence(ns, start, end) new_wav_data = audio_io.crop_wav_data(wav_data, FLAGS.sample_rate, start, end - start) example = tf.train.Example(features=tf.train.Features( feature={ 'id': tf.train.Feature(bytes_list=tf.train.BytesList( value=[pair[0]])), 'sequence': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_ns.SerializeToString()])), 'audio': tf.train.Feature(bytes_list=tf.train.BytesList( value=[new_wav_data])) })) writer.write(example.SerializeToString())
def testSimpleSequenceToPrettyMidi_DefaultTicksAndTempo(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) stripped_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) del stripped_sequence_proto.tempos[:] stripped_sequence_proto.ClearField('ticks_per_quarter') expected_sequence_proto = music_pb2.NoteSequence() expected_sequence_proto.CopyFrom(stripped_sequence_proto) expected_sequence_proto.tempos.add( qpm=constants.DEFAULT_QUARTERS_PER_MINUTE) expected_sequence_proto.ticks_per_quarter = constants.STANDARD_PPQ translated_midi = midi_io.sequence_proto_to_pretty_midi( stripped_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, expected_sequence_proto)
def testSimpleSequenceToPrettyMidi_DefaultTicksAndTempo(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) stripped_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) del stripped_sequence_proto.tempos[:] stripped_sequence_proto.ClearField('ticks_per_quarter') expected_sequence_proto = music_pb2.NoteSequence() expected_sequence_proto.CopyFrom(stripped_sequence_proto) expected_sequence_proto.tempos.add( qpm=constants.DEFAULT_QUARTERS_PER_MINUTE) expected_sequence_proto.ticks_per_quarter = constants.STANDARD_PPQ translated_midi = midi_io.sequence_proto_to_pretty_midi( stripped_sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, expected_sequence_proto)
def testSimpleSequenceToPrettyMidi_FirstTempoNotAtZero(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) del multi_tempo_sequence_proto.tempos[:] multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) # Translating to MIDI adds an implicit DEFAULT_QUARTERS_PER_MINUTE tempo # at time 0, so recreate the list with that in place. del multi_tempo_sequence_proto.tempos[:] multi_tempo_sequence_proto.tempos.add( time=0.0, qpm=constants.DEFAULT_QUARTERS_PER_MINUTE) multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def testSimpleSequenceToPrettyMidi_FirstTempoNotAtZero(self): source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename) multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi) del multi_tempo_sequence_proto.tempos[:] multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) translated_midi = midi_io.sequence_proto_to_pretty_midi( multi_tempo_sequence_proto) # Translating to MIDI adds an implicit DEFAULT_QUARTERS_PER_MINUTE tempo # at time 0, so recreate the list with that in place. del multi_tempo_sequence_proto.tempos[:] multi_tempo_sequence_proto.tempos.add( time=0.0, qpm=constants.DEFAULT_QUARTERS_PER_MINUTE) multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60) multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120) self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)
def convert_midi(root_dir, sub_dir, full_file_path, output_file): data_converter = CONFIG_MAP[FLAGS.config].data_converter augmenter = CONFIG_MAP[FLAGS.config].note_sequence_augmenter ret = [] try: sequence = midi_io.midi_to_sequence_proto( tf.gfile.GFile(full_file_path, 'rb').read()) except midi_io.MIDIConversionError as e: tf.logging.warning( 'Could not parse MIDI file %s. It will be skipped. Error was: %s', full_file_path, e) return [] sequence.collection_name = os.path.basename(root_dir) sequence.filename = os.path.join(sub_dir, os.path.basename(full_file_path)) sequence.id = note_sequence_io.generate_note_sequence_id( sequence.filename, sequence.collection_name, 'midi') # tf.logging.info('Converted MIDI file %s.', full_file_path) for s in (augmenter.get_all(sequence) if augmenter is not None else [sequence]): data = data_converter.to_tensors(s) for inp, c, l in zip(data.inputs, data.controls, data.lengths): s = list(inp.shape) inp = inp.reshape(-1).tolist() c = c.reshape(-1).tolist() if len(c) == 0: c = [0] if isinstance(l, int): l = [l] ret.append({'notes': inp, 'chords': c, 'shape': s, 'lengths': l}) if len(ret) > 0: np.save( "{}_npy/{}".format(output_file, os.path.basename(full_file_path)), ret) return ret
work_dir = os.getcwd() input_dir = os.path.join(work_dir, 'data') output_dir = os.path.join(work_dir, 'output') anthems_file = os.path.join(output_dir, 'anthems.tfrecord') # files_in_dir = tf.gfile.ListDirectory(input_dir) files_in_dir = tf.io.gfile.listdir(input_dir) with note_sequence_io.NoteSequenceRecordWriter(anthems_file) as writer: for file_in_dir in files_in_dir: full_file_path = os.path.join(input_dir, file_in_dir) print(full_file_path) try: sequence = midi_io.midi_to_sequence_proto( tf.io.gfile.GFile(full_file_path, 'rb').read()) except midi_io.MIDIConversionError as e: tf.logging.warning('Could not parse midi file %s. Error was: %s', full_file_path, e) sequence.collection_name = os.path.basename(work_dir) sequence.filename = os.path.join(output_dir, os.path.basename(full_file_path)) sequence.id = note_sequence_io.generate_note_sequence_id( sequence.filename, sequence.collection_name, 'midi') if sequence: writer.write(sequence) filenames = [anthems_file] dataset = tf.data.TFRecordDataset(filenames)
def convert_midi(root_dir, sub_dir, full_file_path): sequence = midi_io.midi_to_sequence_proto(tf.gfile.FastGFile(full_file_path, 'rb').read())
def CheckMidiToSequence(self, filename): """Test the translation from PrettyMIDI to Sequence proto.""" source_midi = pretty_midi.PrettyMIDI(filename) sequence_proto = midi_io.midi_to_sequence_proto(source_midi) self.CheckPrettyMidiAndSequence(source_midi, sequence_proto)
def CheckSequenceToPrettyMidi(self, filename): """Test the translation from Sequence proto to PrettyMIDI.""" source_midi = pretty_midi.PrettyMIDI(filename) sequence_proto = midi_io.midi_to_sequence_proto(source_midi) translated_midi = midi_io.sequence_proto_to_pretty_midi(sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, sequence_proto)
def CheckSequenceToPrettyMidi(self, filename): """Test the translation from Sequence proto to PrettyMIDI.""" source_midi = pretty_midi.PrettyMIDI(filename) sequence_proto = midi_io.midi_to_sequence_proto(source_midi) translated_midi = midi_io.sequence_proto_to_pretty_midi(sequence_proto) self.CheckPrettyMidiAndSequence(translated_midi, sequence_proto)
def CheckMidiToSequence(self, filename): """Test the translation from PrettyMIDI to Sequence proto.""" source_midi = pretty_midi.PrettyMIDI(filename) sequence_proto = midi_io.midi_to_sequence_proto(source_midi) self.CheckPrettyMidiAndSequence(source_midi, sequence_proto)