Esempio n. 1
0
def generateNewSequence(input_sequence, temperature, write_to_file):

    input_sequence = mm.quantize_note_sequence(input_sequence, 8)
    bundle = sequence_generator_bundle.read_bundle_file(
        '/Library/Application Support/Quin Scacheri/Magenta Beats/drum_kit_rnn.mag'
    )
    generator_map = drums_rnn_sequence_generator.get_generator_map()
    drum_rnn = generator_map['drum_kit'](checkpoint=None, bundle=bundle)
    drum_rnn.initialize()

    qpm = input_sequence.tempos[0].qpm
    last_end_time = (max(
        n.end_time
        for n in input_sequence.notes) if input_sequence.notes else 0)
    #    total_seconds = num_steps * input_sequence.quantization_info.steps_per_quarter;

    generator_options = generator_pb2.GeneratorOptions()
    generator_options.args['temperature'].float_value = temperature
    generate_section = generator_options.generate_sections.add(
        start_time=last_end_time, end_time=8.0)

    new_sequence = drum_rnn.generate(input_sequence, generator_options)
    new_sequence = mm.trim_note_sequence(new_sequence, 2.0, 4.0)
    new_sequence = mm.quantize_note_sequence(new_sequence, 4)
    #
    #    new_sequence.quantization_info.steps_per_quarter = 8

    if (True):
        mm.sequence_proto_to_midi_file(input_sequence, 'primer.mid')
        mm.sequence_proto_to_midi_file(new_sequence, 'new_sequence.mid')

    return new_sequence
Esempio n. 2
0
def generateNewSequence(input_sequence, num_steps, temperature, write_to_file = False):

    input_sequence = mm.quantize_note_sequence(input_sequence, 8)
    bundle = sequence_generator_bundle.read_bundle_file('drum_kit_rnn.mag')
    generator_map = drums_rnn_sequence_generator.get_generator_map()
    drum_rnn = generator_map['drum_kit'](checkpoint=None, bundle=bundle)
    drum_rnn.initialize()

    qpm = input_sequence.tempos[0].qpm
    last_end_time = (max(n.end_time for n in input_sequence.notes)
                      if input_sequence.notes else 0)
    total_seconds = num_steps * input_sequence.quantization_info.steps_per_quarter;

    generator_options = generator_pb2.GeneratorOptions()
    generator_options.args['temperature'].float_value = temperature
    generate_section = generator_options.generate_sections.add(start_time=last_end_time, end_time=total_seconds)

    new_sequence = drum_rnn.generate(input_sequence, generator_options)
    new_sequence.quantization_info.steps_per_quarter = 8
    mm.quantize_note_sequence(new_sequence, 8)

    if (write_to_file == True):
        mm.sequence_proto_to_midi_file(input_sequence, 'oldSequence.mid')
        mm.sequence_proto_to_midi_file(new_sequence, 'newSequence.mid')

    return new_sequence
Esempio n. 3
0
def extendTwinkle():
    twinkle_twinkle = createTwinkle()
    print("Initializing Melody RNN...")
    bundle = sequence_generator_bundle.read_bundle_file('./basic_rnn.mag')
    generator_map = melody_rnn_sequence_generator.get_generator_map()
    melody_rnn = generator_map['basic_rnn'](checkpoint=None, bundle=bundle)
    melody_rnn.initialize()

    input_sequence = twinkle_twinkle # change this to teapot if you want
    num_steps = 128 # change this for shorter or longer sequences
    temperature = 1.0 # the higher the temperature the more random the sequence.

    # Set the start time to begin on the next step after the last note ends.
    last_end_time = (max(n.end_time for n in input_sequence.notes)
                      if input_sequence.notes else 0)
    qpm = input_sequence.tempos[0].qpm
    seconds_per_step = 60.0 / qpm / melody_rnn.steps_per_quarter
    total_seconds = num_steps * seconds_per_step

    generator_options = generator_pb2.GeneratorOptions()
    generator_options.args['temperature'].float_value = temperature
    generate_section = generator_options.generate_sections.add(start_time=last_end_time + seconds_per_step, end_time=total_seconds)

    # Ask the model to continue the sequence.
    sequence = melody_rnn.generate(input_sequence, generator_options)

    mm.sequence_proto_to_midi_file(sequence, 'twinkleExtended.mid')
    def __init__(self,
                 generator_name,
                 num_bars_to_generate,
                 hparams,
                 checkpoint=None,
                 bundle_file=None):
        self._num_bars_to_generate = num_bars_to_generate

        if not checkpoint and not bundle_file:
            raise GeneratorException(
                'No generator checkpoint or bundle location supplied.')
        if (checkpoint or generator_name or hparams) and bundle_file:
            raise GeneratorException(
                'Cannot specify both bundle file and checkpoint, generator_name, '
                'or hparams.')

        bundle = None
        if bundle_file:
            bundle = sequence_generator_bundle.read_bundle_file(bundle_file)
            generator_name = bundle.generator_details.id

        if generator_name not in _GENERATOR_FACTORY_MAP:
            raise GeneratorException('Invalid generator name given: %s',
                                     generator_name)

        generator = _GENERATOR_FACTORY_MAP[generator_name].create_generator(
            checkpoint=checkpoint, bundle=bundle, hparams=hparams)
        generator.initialize()

        self._generator = generator
Esempio n. 5
0
def main(_):
  bundle_file = FLAGS.bundle_path
  checkpoint_file = FLAGS.checkpoint_path
  metagraph_filename = checkpoint_file + '.meta'

  bundle = sequence_generator_bundle.read_bundle_file(bundle_file)

  with tf.gfile.Open(checkpoint_file, 'wb') as f:
    f.write(bundle.checkpoint_file[0])

  with tf.gfile.Open(metagraph_filename, 'wb') as f:
    f.write(bundle.metagraph_file)
def main(_):
    bundle_file = FLAGS.bundle_path
    checkpoint_file = FLAGS.checkpoint_path
    metagraph_filename = checkpoint_file + '.meta'

    bundle = sequence_generator_bundle.read_bundle_file(bundle_file)

    with tf.gfile.Open(checkpoint_file, 'wb') as f:
        f.write(bundle.checkpoint_file[0])

    with tf.gfile.Open(metagraph_filename, 'wb') as f:
        f.write(bundle.metagraph_file)
def get_bundle():
    """Returns a generator_pb2.GeneratorBundle object based read from bundle_file.

  Returns:
    Either a generator_pb2.GeneratorBundle or None if the bundle_file flag is
    not set or the save_generator_bundle flag is set.
  """
    if should_save_generator_bundle():
        return None
    bundle_file = get_bundle_file()
    if bundle_file is None:
        return None
    return sequence_generator_bundle.read_bundle_file(bundle_file)
Esempio n. 8
0
def extendDrums():
    dt = createDrumTrack()
    print("Initializing Drums RNN...")
    bundle = sequence_generator_bundle.read_bundle_file('drum_kit_rnn.mag')
    generator_map = drums_rnn_sequence_generator.get_generator_map()
    drum_rnn = generator_map['drum_kit'](checkpoint=None, bundle=bundle)
    drum_rnn.initialize()

    input_sequence = drums # change this to teapot if you want
    num_steps = 128 # change this for shorter or longer sequences
    temperature = 1.0 # the higher the temperature the more random the sequence.

    # Set the start time to begin on the next step after the last note ends.
    # new_start_time =
    generator_options = generator_pb2.GeneratorOptions()
    # generator_options.args['primer_sequence'].string_value = "drums.mid"
    generate_section = generator_options.generate_sections.add(start_time=last_end_time + seconds_per_step, end_time=total_seconds)

    # Ask the model to continue the sequence.
    drum_rnn.generateDrumTrack(128, )
Esempio n. 9
0
def load_generator_from_bundle_file(bundle_file):
    """loads a bundle file as a SequenceGenerator() object."""
    try:
        bundle = read_bundle_file(bundle_file)
    except GeneratorBundleParseException:
        logging.warning("Failed to parse '{}'".format(bundle_file))
        return None

    generator_id = bundle.generator_details.id  # pylint: disable-msg=no-member
    if generator_id not in GENERATOR_MAP:
        logging.warning(
            "Unrecognized SequenceGenerator ID '{}' in '{}'".format(
                generator_id, bundle_file))
        return None

    generator = GENERATOR_MAP[generator_id](checkpoint=None, bundle=bundle)
    generator.initialize()
    logging.info("Loaded '{}' generator bundle from file '{}'".format(
        bundle.generator_details.id,
        bundle_file))  # pylint: disable-msg=no-member
    return generator
def app(unused_argv):
    # Initialize MidiHub.
    hub = midi_hub.MidiHub(["magenta_in 1"], ["VirtualMIDISynth #1 0"],
                           midi_hub.TextureType.POLYPHONIC)

    # TODO ex
    # Bundle TODO describe
    notebook_utils.download_bundle("drum_kit_rnn.mag", "bundles")
    bundle = sequence_generator_bundle.read_bundle_file(
        os.path.join("bundles", "drum_kit_rnn.mag"))

    # Generator TODO describe
    generator_map = drums_rnn_sequence_generator.get_generator_map()
    generator = generator_map["drum_kit"](checkpoint=None, bundle=bundle)
    generator.initialize()

    output_file = os.path.join("output", "out.html")

    interaction = LooperMidi(hub, generator, output_file)
    interaction.start()
    interaction.join()

    return 0
def generate(unused_argv):
    # Bundle TODO describe
    notebook_utils.download_bundle("drum_kit_rnn.mag", "bundles")
    bundle = sequence_generator_bundle.read_bundle_file(
        os.path.join("bundles", "drum_kit_rnn.mag"))

    # Generator TODO describe
    generator_map = drums_rnn_sequence_generator.get_generator_map()
    generator = generator_map["drum_kit"](checkpoint=None, bundle=bundle)
    generator.initialize()

    # TODO describe
    magenta.music.DrumTrack([frozenset([36])])
    primer_drums = magenta.music.DrumTrack([
        frozenset(pitches)
        for pitches in [(36, ), (), (), (), (46, ), (), (), ()]
    ])
    primer_sequence = primer_drums.to_sequence(qpm=120)

    # TODO describe
    qpm = 120

    # TODO describe
    # steps_per_quarter = 4
    seconds_per_step = 60.0 / qpm / generator.steps_per_quarter

    # TODO describe
    num_steps = 32

    # TODO describe
    total_seconds = num_steps * seconds_per_step

    # TODO describe
    # TODO same as min / max in 02
    primer_end_time = primer_sequence.total_time

    # TODO describe
    start_time = primer_end_time + seconds_per_step
    end_time = total_seconds

    # TODO describe
    generator_options = generator_pb2.GeneratorOptions()
    generator_options.generate_sections.add(start_time=1, end_time=end_time)

    # TODO describe
    generator_options.args['temperature'].float_value = 0.1
    generator_options.args['beam_size'].int_value = 1
    generator_options.args['branch_factor'].int_value = 1
    generator_options.args['steps_per_iteration'].int_value = 1

    # TODO describe
    sequence = generator.generate(primer_sequence, generator_options)

    # TODO print
    last_end_time = max(n.end_time for n in sequence.notes)
    first_start_time = min(n.start_time for n in sequence.notes)
    primer_length = last_end_time - first_start_time
    print("seconds_per_step: " + str(seconds_per_step))
    print("num_steps: " + str(num_steps))
    print("total_seconds: " + str(total_seconds))
    print("primer_end_time: " + str(primer_end_time))
    print("start_time: " + str(start_time))
    print("end_time: " + str(end_time))
    print("last_end_time: " + str(last_end_time))
    print("first_start_time: " + str(first_start_time))
    print("primer_length: " + str(primer_length))

    # TODO describe
    midi_file = os.path.join("output", "out.mid")
    midi_io.note_sequence_to_midi_file(sequence, midi_file)
    print(midi_file)

    # TODO describe
    plot_file = os.path.join("output", "out.html")
    print(plot_file)
    pm = midi_io.note_sequence_to_pretty_midi(sequence)
    output_file(plot_file)
    plot = plot_midi(pm)
    show(plot)

    return 0
Esempio n. 12
0
# See the License for the specific language governing permissions and
# limitations under the License.
# 

import magenta.models.basic_rnn.basic_rnn_generator as basic_rnn_generator
from magenta.music import sequence_generator_bundle
from magenta.protobuf import generator_pb2
from magenta.music import midi_io
from magenta.models.shared.melody_rnn_generate import _steps_to_seconds
import os
import tempfile


basic_generator = basic_rnn_generator.create_generator(
    None,
    sequence_generator_bundle.read_bundle_file(os.path.abspath('./magenta/basic_rnn.mag')),
    4)

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)
Esempio n. 13
0
BUNDLE_DIR = "bundles"
OUTPUT_DIR = "output"
if not os.path.exists(OUTPUT_DIR):
    os.makedirs(OUTPUT_DIR)
MIDI_FILE = OUTPUT_DIR + "/" + MODEL_NAME + "_" + DATETIME + ".mid"
PLOT_FILE = OUTPUT_DIR + "/" + MODEL_NAME + "_" + DATETIME + ".html"

# The higher the value, the more random is the generated sequence
# 1.0 is the default value ; 1.25 is more random ; 0.75 is less random
TEMPERATURE = 1.0

# The primer sequence TODO describe

# Bundle TODO describe
notebook_utils.download_bundle(BUNDLE_NAME, BUNDLE_DIR)
bundle = sequence_generator_bundle.read_bundle_file(
    os.path.join(BUNDLE_DIR, BUNDLE_NAME))

# Generator TODO describe
generator_map = melody_rnn_sequence_generator.get_generator_map()
generator = generator_map[MODEL_NAME](checkpoint=None, bundle=bundle)
generator.initialize()

# Generator options TODO describe
generator_options = generator_pb2.GeneratorOptions()
generator_options.args["temperature"].float_value = TEMPERATURE

# TODO is this unused?
generate_section = generator_options.generate_sections.add(start_time=0,
                                                           end_time=30)

# Generate the sequence TODO describe