예제 #1
0
def main(dir_in, dir_out):
    if not os.path.exists(dir_out):
        os.mkdir(dir_out)

    for file in os.listdir(dir_in):
        if file == ".DS_Store":
            continue

        file_path = dir_in + "/" + file

        df = pd.read_csv(file_path)

        df.insert(2, "Channel", 0)
        df.insert(0, "Track", 1)

        df.to_csv(file_path, index=False)

        with open(file_path, "r") as f:
            lines = f.readlines()

        end_time = lines[-1].split(",")[1]

        lines[0] = "1,0,Start_track\n"
        lines.append("1," + end_time + ",End_track")

        with open(file_path, "w") as f:
            f.writelines(lines)

        midi_object = py_midicsv.csv_to_midi(file_path)

        midi_file = dir_out + "/" + file.replace("csv", "mid")

        with open(midi_file, "wb") as output_file:
            midi_writer = py_midicsv.FileWriter(output_file)
            midi_writer.write(midi_object)
예제 #2
0
def reverse_transformation(array,frequency,beats_per_sec):
    csv_file = open("gen.csv",'w')
    csv.register_dialect('registered', delimiter=',', quoting=csv.QUOTE_NONE, lineterminator = '\n')
    writer = csv.writer(csv_file,dialect='registered')
    freq = int(beats_per_sec/frequency)
    writer.writerow([0, 0, 'Header', 1, 3, beats_per_sec])
    writer.writerow([1, 0, 'Start_track'])
    for x in range(len(array)):
        if x == 0:
            for y in range(len(array[x])):
                if array[x][y]:
                    writer.writerow([1, x*freq, 'Note_on_c', 0, y , 65])
            continue
        for y in range(len(array[x])):
            if array[x][y] ^ array[x-1][y]:
                if array[x][y] == True:
                    writer.writerow([1, x*freq, 'Note_on_c', 0,y , 65])
                if array[x][y] == False:
                    writer.writerow([1,x*freq,'Note_off_c',0,y ,0])
    writer.writerow([1,(len(array)+1)*freq,'End_track'])
    writer.writerow([0,0,'End_of_file'])
    csv_file.close()
    csv_file = open("gen.csv",'r')
    midi_object = py_midicsv.csv_to_midi(csv_file)
    filename = "gen.mid"
    output_file = open(filename,'wb')
    midi_writer = py_midicsv.FileWriter(output_file)
    midi_writer.write(midi_object)
예제 #3
0
    def write_midi(self, path: str, events: list[str]) -> None:
        midi_obj = pm.csv_to_midi(events)
        with open(path + '.midi', 'wb') as f:
            midi_writer = pm.FileWriter(f)
            midi_writer.write(midi_obj)

        with open(path + '.csv', 'w') as f:
            f.writelines(e + '\n' for e in events)
예제 #4
0
def csv_to_mid(_csv_files):
    for file in _csv_files:

        text_to_csv(file)

        with open(
                f"sorting/midi output/midi_{file.replace('.txt', '').replace('csv_', '')}.mid",
                "wb") as output_file:
            pm.FileWriter(output_file).write(
                pm.csv_to_midi(f"sorting/translating/{file}"))
예제 #5
0
def txttomidi(txt):
    pathTo = os.getcwd()
    outFile = txt[0:-4] + ".mid"
    actualVal = outFile.split("\\")[-1]
    midi_object = py_midicsv.csv_to_midi(txt)
    with open(outFile, "wb") as output_file:
        midi_writer = py_midicsv.FileWriter(output_file)
        midi_writer.write(midi_object)
    start = pathTo + "\\randoTxt\\" + actualVal
    end = pathTo + "\\randoMidi"
    shutil.move(start, end)
예제 #6
0
def convert_to_midi_file(data, file, keep_newcsv):
    new_data = [', '.join(i) for i in data]
    csv_string = '\n'.join(new_data)

    with open(file + ".newcsv", "w") as output_csv:
        output_csv.write(csv_string)
    midi_object = py_midicsv.csv_to_midi(file + ".newcsv")
    if not keep_newcsv:
        os.remove(file + ".newcsv")

    with open(file + ".mid", "wb") as output_file:
        midi_writer = py_midicsv.FileWriter(output_file)
        midi_writer.write(midi_object)
def outputMelody(notes, out):

    with open(notes, 'r') as f:
        read = csv.reader(f, delimiter=',')
        noteList = []
        for row in read:
            if row == []:
                continue
            noteList.append(row[0])

    with open(out + ".csv", 'w') as results:
        writer = csv.writer(results, delimiter='\n')

        midi = []
        midi.append('0, 0, Header, 0, 1, 960')
        midi.append('1, 0, Start_track')
        time = 0

        for i in range(len(noteList)):
            if (noteList[i] in "0" or noteList[i] in "1"):
                time += 480

            elif (noteList[i] not in "1" and noteList[i] not in "0"):
                midi.append("1, " + str(time) + ", Note_on_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 127")
                time += 480
            j = i + 1

            if (j < (len(noteList) - 1)
                    and (noteList[j] in "1" or noteList[j] in "0")):
                while (noteList[j] in "1" and j < (len(noteList) - 1)):
                    time += 480
                    j += 1
                midi.append("1, " + str(time) + ", Note_off_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 0")

                i = j
            elif (noteList[i] not in "1" and noteList[i] not in "0"):
                midi.append("1, " + str(time) + ", Note_off_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 0")

        midi.append('1, ' + str(time) + ', End_track')
        midi.append('0, 0, End_of_file')
        writer.writerow(midi)

        midi_obj = pm.csv_to_midi(midi)

        with open(out + ".mid", "wb") as out_file:
            midi_writer = pm.FileWriter(out_file)
            midi_writer.write(midi_obj)
예제 #8
0
def CsvToMidi(final_dataframe, file):
    import py_midicsv as pm

    midi_object = pm.csv_to_midi(final_dataframe)

    save_file_name = os.path.join("HarmonizedMelodies/",
                                  ("harmonized_" + file[18:]))

    with open(save_file_name, "wb") as output_file:
        midi_writer = pm.FileWriter(output_file)
        midi_writer.write(midi_object)

    del midi_object, final_dataframe

    return save_file_name
예제 #9
0
def outputMelody(notes, out):

    with open(notes, 'r') as f:
        read = csv.reader(f, delimiter=',')
        noteList = []
        for row in f:
            noteList.append(row.strip("[']\n"))

    with open(out + ".csv", 'w') as results:
        writer = csv.writer(results, delimiter='\n')

        midi = []
        midi.append('0, 0, Header, 0, 1, 960')
        midi.append('1, 0, Start_track')
        time = 0

        for i in range(len(noteList)):
            if (noteList[i] == "0" or noteList[i] == "1"):
                time += 240
                break
            if (noteList[i] != "1"):
                midi.append("1, " + str(time) + ", Note_on_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 127")
                time += 240
                string = ""
            j = i + 1
            if (j < (len(noteList) - 1)):
                while (noteList[j] == "1" and j < (len(noteList) - 1)):
                    time += 240
                    j += 1
                midi.append("1, " + str(time) + ", Note_off_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 0")
                time += 240
                i = j
            elif (noteList[i] != "1"):
                midi.append("1, " + str(time) + ", Note_off_c, 0, " +
                            str(int(noteList[i]) + 46) + ", 0")
                time += 240

        midi.append('1, ' + str(time) + ', End_track')
        midi.append('0, 0, End_of_file')
        writer.writerow(midi)

        midi_obj = pm.csv_to_midi(midi)

        with open(out + ".mid", "wb") as out_file:
            midi_writer = pm.FileWriter(out_file)
            midi_writer.write(midi_obj)
예제 #10
0
def write_to_midi(csv_list, new_filename):
    """
    Write csv_list to disc, convert csv file to midi file.
    :param csv_list:
    :param new_filename:
    :return:
    """

    with open(new_filename[:-4] + '.csv', 'w') as writeFile:
        for line in csv_list:
            writeFile.write(line)
    # use provided function to load midi pattern from csv file
    # in order to use built-in function to write midi file itself to disc
    pattern = midi.csv_to_midi(new_filename[:-4] + '.csv')
    with open(new_filename, 'wb') as midiFile:
        writer = midi.FileWriter(midiFile)
        writer.write(pattern)
    return
예제 #11
0
    def save_music(self, encoded: str, filename: str) -> None:
        words = encoded.split(' ')

        csv_rows = []

        csv_rows.append(['0', '0', 'Header', '0', '1', '384'])
        csv_rows.append(['1', '0', 'Start_track'])
        csv_rows.append(['1', '0', 'Tempo', '500000'])

        m_track, m_channel, m_time, m_velocity = '1', '0', 0, 127

        for word in words:
            vel_change = re.match(r'v([0-9]*)', word)
            if vel_change:
                m_velocity = int(vel_change.group(1)) * self.VELOCITIES

            wait = re.match(r'wait([0-9]*)', word)
            if wait:
                m_time += int(wait.group(1)) * self.TIME_CONSTANT

            note = re.match(r'(?P<end>end)?p(?P<note>[0-9]*)', word)
            if note:
                m_type = 'Note_off_c' if note.group('end') else 'Note_on_c'
                m_note = note.group('note')
                csv_rows.append([
                    m_track,
                    str(m_time), m_type, m_channel, m_note,
                    str(m_velocity)
                ])

        csv_rows.append(['1', str(m_time + 5000), 'End_track'])
        csv_rows.append(['0', '0', 'End_of_file'])

        csv_rows = [str.join(', ', row) for row in csv_rows]
        midi_object = pm.csv_to_midi(csv_rows)

        pathlib.Path(self.output_dir).mkdir(parents=True, exist_ok=True)

        filepath = os.path.join(self.output_dir, prefix_timestamp(filename))
        with open(filepath, 'wb') as file:
            midi_writer = pm.FileWriter(file)
            midi_writer.write(midi_object)
예제 #12
0
def store_csv_to_midi(title: str, csv_data: str) -> str:
    """
    Parses and stores CSV data to a MIDI file.
    :param title: Title of the song (file).
    :param csv_data: CSV string data of the song.
    """
    logging.info(f'Writing MIDI file at {RESULTS_PATH}{title}')

    file_path = f'{RESULTS_PATH}/{title}.csv'
    with open(file_path, mode='w') as f:
        f.write(csv_data)

    with open(file_path, mode='r') as f:
        midi_data = csv_to_midi(f)
        with open(f'{RESULTS_PATH}/{title}.mid', mode='wb') as g:
            writer = FileWriter(g)
            writer.write(midi_data)

    # os.remove(file_path)

    return f'{RESULTS_PATH}/{title}.mid'
예제 #13
0
def reduce_to_single_track(filename, new_filename, track_nr):
    """
    Reduce a file to a single track and save it to a new file.
    can be used to make file monophonic if the track nr of the track
    that should be kept is known (has to be determined with other functions)
    takes filename of polyphonic midi and name of file to which monophonic should be written
    :param filename:
    :param new_filename:
    :param track_nr:
    :return:
    """

    s = load_to_csv(filename)
    track_dict = split_tracks(s)
    new_csv = []

    # must keep first and last line of track '0'
    header_line = track_dict['0'][0]

    # change the number of tracks that is written there to 1
    header_line = replace_int_in_line(header_line, 4, 1)
    new_csv.append(header_line)

    # copy lines of chosen track to new csv
    for elem in track_dict[track_nr]:
        new_csv.append(elem)
    new_csv.append(track_dict['0'][-1])

    # write new csv to disc
    with open(new_filename[:-4] + '.csv', 'w') as writeFile:
        for line in new_csv:
            writeFile.write(line)

    # use provided function to load midi pattern from csv file
    # in order to use built-in function to write midi file itself to disc
    pattern = midi.csv_to_midi(new_filename[:-4] + '.csv')
    with open(new_filename, 'wb') as midiFile:
        writer = midi.FileWriter(midiFile)
        writer.write(pattern)
    return
예제 #14
0
        if keystate != key['state']:
            key['state'] = keystate
            if keystate == 'on':
                midimessages.append([
                    2,
                    int(relativetime * bps * ccpqn), 'Note_on_c',
                    key['channel'], key['pitch'], velocity
                ])
            elif keystate == 'off':
                midimessages.append([
                    2,
                    int(relativetime * bps * ccpqn), 'Note_off_c',
                    key['channel'], key['pitch'], velocity
                ])
            print(f"{relativetime:.2f} {key['pitch']} {key['state']}")

    framenum += 1

midimessages.append([2, int(relativetime * bps * ccpqn), 'End_track'])
midimessages.append([0, 0, 'End_of_file'])

csvfile = open('output.mid', 'w')
csvwriter = csv.writer(csvfile)
csvwriter.writerows(midimessages)
csvfile.close()
mid = pm.csv_to_midi('output.mid')
with open("output.mid", "wb") as output_file:
    midi_writer = pm.FileWriter(output_file)
    midi_writer.write(mid)
    output_file.close()
예제 #15
0
def csv_midi(csv_file):
    midi_object = py_midicsv.csv_to_midi(csv_file)
    with open("Steganography.mid", "wb") as output_file:
        midi_writer = py_midicsv.FileWriter(output_file)
        midi_writer.write(midi_object)
예제 #16
0
import py_midicsv

# Load the MIDI file and parse it into CSV format
csv_string = py_midicsv.midi_to_csv("rgg.mid")
print(csv_string)

# Parse the CSV output of the previous command back into a MIDI file
midi_object = py_midicsv.csv_to_midi(csv_string)

# Save the parsed MIDI file to disk
#with open("example_converted.mid", "wb") as output_file:
#    midi_writer = py_midicsv.FileWriter(output_file)
#    midi_writer.write(midi_object)
input_midifile = input_midifile.sort_values(['Track', 'Time'])

# adds the end of file thing to the end of the output database
for index, note in input_end_of_file.iterrows():
    input_midifile = input_midifile.append(note)

input_midifile.to_csv('test.csv', index=0, header=0, encoding='utf-8')

harmonized = []
nonfloatharm = []

with open('test.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
    for row in reader:
        harmonized.append(''.join(row))

for x in harmonized:
    x = x.replace(".0", "")
    for i in range(0, 5):
        x = x.replace(",,", ",")
        x = x.replace('\"\"\"', '\"')
    x = x.strip(",")
    nonfloatharm.append(x)

midi_object = py_midicsv.csv_to_midi(nonfloatharm)

with open("harmonized.mid", "wb") as output_file:
    midi_writer = py_midicsv.FileWriter(output_file)
    midi_writer.write(midi_object)
예제 #18
0
def __csv_to_midi(file_in, file_out):
    with open(file_in, "r") as f:
        midi_object = py_midicsv.csv_to_midi(f.readlines())
    with open(file_out, "wb") as f:
        midi_writer = py_midicsv.FileWriter(f)
        midi_writer.write(midi_object)
예제 #19
0
    print(loudness1, loudness2)

# The output matrix is transformed into a csv file.
with open('result.csv', 'w') as f:
    f.write('0, 0, Header, 1, 2, 264\n')
    f.write('1, 0, Start_track\n')
    f.write('1, 0, Key_signature, 0, "major"\n')
    f.write('1, 0, Tempo, 501133\n')
    f.write('1, 0, Time_signature, 4, 2, 24, 8\n')
    f.write('1, 0, End_track\n')
    f.write('2, 0, Start_track\n')
    f.write('2, 0, Title_t, "drums"\n')
    f.write('2, 0, MIDI_port, 0\n')
    for i in range(0, len(result)):
        y = result[i]
        midi_clock = i * 264

        loudness1 = int(y[0] * 127)
        loudness2 = int(y[1] * 127)
        f.write('2, {}, Note_on_c, 9, 38, {}\n'.format(midi_clock, loudness1))
        f.write('2, {}, Note_on_c, 9, 42, {}\n'.format(midi_clock, loudness2))
    f.write('2, 0, End_track\n')
    f.write('0, 0, End_of_file\n')

midi = py_midicsv.csv_to_midi('result.csv')

# the csv file containing the information of the output is transformed into a midi file.
with open("result.mid", "wb") as output_file:
    midi_writer = py_midicsv.FileWriter(output_file)
    midi_writer.write(midi)
예제 #20
0
import py_midicsv as pm
import sys

# Parse the CSV output of the previous command back into a MIDI file
midi_object = pm.csv_to_midi(sys.argv[1] + ".csv")

# Save the parsed MIDI file to disk
with open(sys.argv[1] + "_raw.mid", "wb") as output_file:
    midi_writer = pm.FileWriter(output_file)
    midi_writer.write(midi_object)
예제 #21
0
def txt2midi(path):
    track_num = 1
    current_time = current_bpm = 0
    current_velocity = 6
    BPM = 120

    # Open input text file and split it into a list of strings
    with open(path, 'r') as txt:
        str_list = txt.read().split(' ')

    # Open up the output csv file and write in MIDI events in CSV format
    with open(f'output.csv', 'w') as csv:
        csv.write(f'0, 0, Header, 0, {track_num}, {DEFAULT_PPQ}\n')
        csv.write('1, 0, Start_track\n')
        csv.write(f'1, 0, Title_t, Everything\n')
        csv.write('1, 0, Copyright_t, "public domain"\n')
        csv.write('1, 0, Time_signature, 4, 4, 24, 8\n')
        # Use 120 BPM
        csv.write(f'1, 0, Tempo, {round(60_000_000/BPM)}\n')

        for str_event in str_list:
            # Velocity Event
            if '.v' in str_event:
                current_velocity = unsimplify_velocity(
                    int(str_event[:str_event.find('.')]), VELOCITY_SPLITS)
            # Sustain On Event
            elif str_event == 'sus.on':
                csv.write(
                    f'{track_num}, {current_time}, Control_c, 0, 64, 127\n')
            # Sustain Off Event
            elif str_event == 'sus.off':
                csv.write(
                    f'{track_num}, {current_time}, Control_c, 0, 64, 0\n')

            # Time Shift Event
            elif '.shift' in str_event:
                current_time += ms2ticks(int(str_event[:str_event.find('.')]),
                                         BPM)
            else:
                # Note On
                if '.on' in str_event:
                    note = str_event[:str_event.find('.')]
                    csv.write(
                        f'{track_num}, {current_time}, Note_on_c, 0, {note}, {current_velocity}\n'
                    )
                # Note Off
                elif '.off' in str_event:
                    note = str_event[:str_event.find('.')]
                    csv.write(
                        f'{track_num}, {current_time}, Note_off_c, 0, {note}, 0\n'
                    )
                else:
                    pass

        csv.write(f'{track_num}, {current_time}, End_track\n')
        csv.write(f'0, 0, End_of_file')

    output = pm.csv_to_midi(f"output.csv")
    # Save the parsed MIDI file
    with open(f"output.mid", "wb") as output_file:
        midi_writer = pm.FileWriter(output_file)
        midi_writer.write(output)
예제 #22
0
def export_midi(midi_array, song_meta_data, tempo, path):
    def find_runs(x, row_index):
        # finds continuous segments of note presses and returns the value, start, length, and velocity for each note

        n = x.shape[0]
        loc_run_start = np.empty(n, dtype=bool)
        loc_run_start[0] = True

        np.not_equal(x[:-1], x[1:], out=loc_run_start[1:])
        run_starts = np.nonzero(loc_run_start)[0]

        # run_velocity -> take the value of first element in the run
        run_velocities = x[loc_run_start]

        # find run lengths, unused
        run_lengths = np.diff(np.append(run_starts, n))

        # need to make a np array with note value (passed in as row_index) that is the same length as
        # the number of notes found for that row
        note_values = np.full(len(run_starts), row_index)

        # return array where each row has [note value, start of run, velocity of note]
        # note value is what note was played, determined by row_index passed in
        return np.dstack((note_values, run_starts, run_velocities))[0]


    # gathering note presses for each row (note) in midi array in order
    note_presses_and_releases = np.vstack([find_runs(row, idx) for idx, row in enumerate(midi_array)])


    # remove actions where the start tick and velocity are both 0
    # these are runs of 0's found at the beginning of the track for each note
    # if counted, it would include these as a note release for each note at the beginning of track, so they are excluded
    mask = (note_presses_and_releases[:, 1] == 0) & (note_presses_and_releases[:, 2] == 0)
    note_presses_and_releases = note_presses_and_releases[~mask]

    # IF YOU WANT TO COMBINE SUS PEDAL AND NOTE PRESSES:
    # sus_pedal_actions = np.vstack(find_runs(midi_sus_array[0], 128))
    # mask = (sus_pedal_actions[:, 1] == 0) & (sus_pedal_actions[:, 2] == 0)
    # sus_pedal_actions = sus_pedal_actions[~mask]
    # all_midi_actions = np.vstack([note_presses_and_releases, sus_pedal_actions])
    # sorted_all_midi_actions = all_midi_actions[all_midi_actions[:, 1].argsort()]

    #JUST NOTE PRESSES AND RELEASES:
    sorted_note_presses_and_releases = note_presses_and_releases[note_presses_and_releases[:, 1].argsort()]

    def write_midi_line(track, tick, control, channel, control_num, velocity):
        midi_string = ', '.join([str(track), str(tick), str(control), str(channel), str(control_num), str(velocity)])
        midi_string += '\n'
        return midi_string


    # recombining midi actions with metadata and end of file strings
    midi_out = []
    for line in song_meta_data:
        if 'Tempo' in line:
            # 4088860
            new_line = f'1, 0, Tempo, {tempo}'
            midi_out.append(new_line)
        else:
            midi_out.append(line)
    for line in sorted_note_presses_and_releases:
        if line[0] == 128:
            #                              track     tick   control  channel  control_num  velocity
            midi_out.append(write_midi_line(2, int(line[1]), 'Control_c', 0, 64, int(line[2])))
        else:
            #                              track     tick   control  channel  control_num  velocity
            midi_out.append(write_midi_line(2, int(line[1]), 'Note_on_c', 0, int(line[0]), int(line[2])))
    for line in track_end:
        midi_out.append(line)


    midi_object = pm.csv_to_midi(midi_out)
    with open(path, 'wb') as output_file:
        midi_writer = pm.FileWriter(output_file)
        midi_writer.write(midi_object)
    def convert_file(self, file):

        # TODO: Modify Discrete Sound
        off_note = 0
        success_num = 0
        new_csv_string = []

        total_track = 0
        track_num = 1  # Set the Track number

        program_num = 0
        delta_time = 0
        channel = 0
        pitch = 60
        velocity = 90

        # FOR CHECKING

        if os.path.isfile(file):

            file_name = file.split("/")[-1]
            epsilon_folder = file.split("/")[-2]
            self.epsilon_folder = epsilon_folder

            if "orig" in file_name:
                self.atype = "orig"
            elif "noise" in file_name:
                self.atype = "noise"
            else:  # origin input2midi
                self.atype = "att"

            if self.atype in file_name:

                # only_file_name = file_name.replace(self.atype + "_", "").replace(
                #     ".npy", ""
                only_file_name = file_name.replace(".npy", "")

            else:

                only_file_name = file_name.replace(".npy", "")

            this_genre = ""  # genre of this midi

            # Genre UNUSED FOR NOW
            # for genre in self.config.genres:
            #     if genre in self.config.to_convert_path:
            #         this_genre = genre
            #         break
            # if 'to_convert_path' contains genre name -> this_genre = genre name
            # else this_genre = ''
            # print(this_genre)

            # FOR SIMULATION
            # if file != 'scn15_11_format0.mid.npy': continue
            # only_file_name = 'scn15_11_format0.mid'

            # print(only_file_name)

            new_csv_string = []
            load_data = np.load(file)
            load_data = np.squeeze(load_data)

            if this_genre == "":  # 'to_convert_path' not contain genre name

                origin_file = self.origin_midi_dir + self.get_origin_file_name(
                    self.composer, self.orig_midi_name)

            else:  # 'to_convert_path' contains genre name
                origin_file = (self.origin_midi_dir + this_genre + "/" +
                               self.get_origin_file_name(
                                   self.composer, self.orig_midi_name))

            # print("Original file:", origin_file)

            try:
                origin_file_csv = py_midicsv.midi_to_csv(origin_file)
            except:
                print("MIDI_TO_CSV ERROR !!")

            else:
                # print("current file:", file)
                # for string in origin_file_csv:
                #    if 'Program_c' in string: print(string)

                total_track = 2
                current_used_instrument = [-1, -1]
                # find total track num
                for instrument_num, lst in enumerate(
                        load_data):  # instrument_num : 0-127
                    if np.sum(lst) != (off_note) * 400 * 128:
                        total_track += 1
                        current_used_instrument.append(instrument_num)

                # slower by 4.8
                header = origin_file_csv[0].split(", ")
                # print('Before header:', header)
                header[-1] = str(int(int(header[-1][:-1]) * 1.3)) + "\n"
                header[-2] = str(int(total_track))
                # print('After header:', header)
                new_csv_string.append(
                    ", ".join(header)
                )  # header_string(total_track) + change last to 168 (too fast)
                new_csv_string.append(
                    origin_file_csv[1])  # self.start_track_string(track_num)

                for string in origin_file_csv:
                    if "SMPTE_offset" in string:
                        # print(string)
                        continue
                    elif "Time_signature" in string or "Tempo" in string:
                        new_csv_string.append(string)

                    elif "Program_c" in string:
                        break

                new_csv_string.append(
                    self.end_track_string(track_num, delta_time))
                # print('Before Real Data Part:')
                # for string in new_csv_string: print(string)

                # ## Real Data Part # deleted after add 128 instrument dim
                # current_used_instrument = [-1, -1]
                # for instrument_num in instrument_dict.keys():
                #     current_used_instrument.append(instrument_num)
                # print(lst.shape)

                # print(total_track)

                # Set the track_string_list to identify different instrument time line
                track_string_list = [[] for i in range(0, total_track)]
                track_string_list[0].append(
                    -1)  # To Generate Error -> Header File
                track_string_list[1].append(
                    -1)  # To Generate Error -> Meta File

                note_on_list = [[] for i in range(0, total_track)]
                note_on_list[0].append(-1)
                note_on_list[1].append(-1)

                control_change_list = [[] for i in range(0, total_track)]
                control_change_list[0].append(-1)
                control_change_list[1].append(-1)

                note_off_list = [[] for i in range(0, total_track)]
                note_off_list[0].append(-1)
                note_off_list[1].append(-1)

                # print(load_data.shape[0], " ", load_data.shape[1], " ", load_data.shape[2])
                for channel_instrument in range(0, load_data.shape[0]):
                    for row in range(0, load_data.shape[1]):
                        for col in range(0, load_data.shape[2]):

                            if load_data[channel_instrument][row][
                                    col] == off_note:
                                continue
                            else:
                                # Set the different condition for attacked Midi Files
                                # print('music21 instrument:', load_data[row][col]) # 0-59
                                # print('py_midicsv instrument:', program_num_map[load_data[row][col]])

                                if (len(track_string_list[
                                        current_used_instrument.index(
                                            channel_instrument)]) != 0):
                                    program_num = channel_instrument  # program_num = instrment num
                                    pitch = col
                                    channel = 0
                                    delta_time = 50 * row
                                    end_delta_time = 50 * (row + 1)
                                    velocity = int(
                                        load_data[channel_instrument][row]
                                        [col])

                                    # Check if the note is continuous or not

                                    # Append Note_on when before event don't exist

                                    if row != 0 and (
                                            load_data[channel_instrument][
                                                row - 1][col] == 0):
                                        note_on_list[track_num].append([
                                            track_num,
                                            delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                                    elif row != 0 and (
                                            load_data[channel_instrument][
                                                row - 1][col] != 0):

                                        control_change_list[track_num].append([
                                            track_num,
                                            delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                                    # Append Note_off when after event don't exist

                                    if row != (load_data.shape[1] - 1) and (
                                            load_data[channel_instrument][
                                                row + 1][col] == 0):
                                        note_off_list[track_num].append([
                                            track_num,
                                            end_delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                                else:
                                    # Set the track_string_list new track header - program_c event
                                    track_num = current_used_instrument.index(
                                        channel_instrument)
                                    if channel_instrument == 128:
                                        program_num = 1
                                    else:
                                        program_num = channel_instrument
                                    channel = 0
                                    pitch = col
                                    delta_time = 50 * row
                                    end_delta_time = 50 * (row + 1)
                                    velocity = int(
                                        load_data[channel_instrument][row]
                                        [col])
                                    track_string_list[track_num].append(
                                        self.start_track_string(track_num))
                                    track_string_list[track_num].append(
                                        self.title_track_string(track_num))
                                    track_string_list[track_num].append(
                                        self.program_c_string(
                                            track_num, channel, program_num))

                                    if row != 0 and (
                                            load_data[channel_instrument][
                                                row - 1][col] == 0):
                                        note_on_list[track_num].append([
                                            track_num,
                                            delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                                    elif row != 0 and (
                                            load_data[channel_instrument][
                                                row - 1][col] != 0):

                                        control_change_list[track_num].append([
                                            track_num,
                                            delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                                    if row != (load_data.shape[1] - 1) and (
                                            load_data[channel_instrument][
                                                row + 1][col] == 0):
                                        note_off_list[track_num].append([
                                            track_num,
                                            end_delta_time,
                                            channel,
                                            pitch,
                                            velocity,
                                        ])

                        for num in range(2,
                                         len(note_on_list)):  # num = track num
                            for notes in range(0, len(note_on_list[num])):
                                track_string_list[num].append(
                                    self.note_on_event_string(
                                        note_on_list[num][notes][0],
                                        note_on_list[num][notes][1],
                                        note_on_list[num][notes][2],
                                        note_on_list[num][notes][3],
                                        note_on_list[num][notes][4],
                                    ))

                        for num in range(
                                2,
                                len(control_change_list)):  # num = track num
                            for notes in range(0,
                                               len(control_change_list[num])):
                                track_string_list[num].append(
                                    self.control_change_event_string(
                                        control_change_list[num][notes][0],
                                        control_change_list[num][notes][1],
                                        control_change_list[num][notes][2],
                                        control_change_list[num][notes][3],
                                        control_change_list[num][notes][4],
                                    ))

                        for num in range(2, len(note_off_list)):
                            for notes in range(0, len(note_off_list[num])):
                                track_string_list[num].append(
                                    self.note_off_event_string(
                                        note_off_list[num][notes][0],
                                        note_off_list[num][notes][1],
                                        note_off_list[num][notes][2],
                                        note_off_list[num][notes][3],
                                        note_off_list[num][notes][4],
                                    ))

                        note_on_list = [[] for i in range(0, total_track)]
                        control_change_list = [[]
                                               for i in range(0, total_track)]
                        note_off_list = [[] for i in range(0, total_track)]

                end_delta_time = 400 * 50
                for i in range(2, len(track_string_list)):
                    for j in track_string_list[i]:
                        new_csv_string.append(j)
                    new_csv_string.append(
                        self.end_track_string(i, end_delta_time))
                new_csv_string.append(
                    "0, 0, End_of_file\n")  # end of file string
                # print('NEW STRING')

                # data = pd.DataFrame(new_csv_string)
                # data.to_csv(csv_output_dir,index = False)

                midi_object = py_midicsv.csv_to_midi(new_csv_string)

                self.make_directory(self.output_file_dir +
                                    str(epsilon_folder) + "/origin")
                self.make_directory(self.output_file_dir +
                                    str(epsilon_folder) + "/attack")

                new_output_file_dir = self.output_file_dir + str(
                    epsilon_folder)
                if self.atype == "orig":

                    new_output_file_dir = (new_output_file_dir + "/origin/" +
                                           self.orig_midi_name + "_" +
                                           self.atype + "_" + only_file_name +
                                           ".mid")

                elif self.atype == "att":

                    new_output_file_dir = (new_output_file_dir + "/attack/" +
                                           self.orig_midi_name + "_" +
                                           self.atype + "_" + only_file_name +
                                           ".mid")

                with open(
                        new_output_file_dir,
                        "wb",
                ) as output_file:
                    midi_writer = py_midicsv.FileWriter(output_file)
                    midi_writer.write(midi_object)
                    # print("Good Midi File")

                    self.success_num += 1

                # For Cheking Error Data, Represent to csv files
                if self.csv_printable:
                    self.checking_csv(only_file_name)
    def save(self, filename):
        midi_file = py_midicsv.csv_to_midi(self.csv_string)

        with open(filename + ".mid", "wb") as output_file:
            midi_writer = py_midicsv.FileWriter(output_file)
            midi_writer.write(midi_file)
예제 #25
0
def notes_to_midi(midi_filename: str, on_notes: np.ndarray,
                  new_mini_name: str):
    csv_string = py_midicsv.midi_to_csv(midi_filename)
    N = len(csv_string)

    # make original ON_note and OFF_list list
    on_original = []
    off_original = []

    for i in range(N):
        row = csv_string[i]
        row = row.replace('\n', '')
        row = row.split(', ')

        if row[2] == 'Note_on_c':
            on_original += [row[4]]

        if row[2] == 'Note_off_c':
            off_original += [row[4]]

    # compute index map
    index_map = []
    for i in range(len(off_original)):
        first_one = True
        for j in range(len(on_original)):
            if off_original[i] == on_original[j] and first_one:
                first_one = False

                key_pressed = on_original[j]
                on_original[j] = -1

                index_map += [j]

    # conpute new off nodes
    off_notes = []
    for i in index_map:
        off_notes += [on_notes[i]]

    # replace notes
    data = []
    on_counts = 0
    off_counts = 0

    for i in range(len(csv_string)):
        row = csv_string[i]
        row = row.replace('\n', '')
        row = row.split(', ')

        if row[2] == 'Note_on_c':
            row[4] = str(on_notes[on_counts])
            csv_string[i] = ', '.join(row) + '\n'
            on_counts += 1

        if row[2] == 'Note_off_c':
            row[4] = str(off_notes[off_counts])
            csv_string[i] = ', '.join(row) + '\n'
            off_counts += 1

    midi_object = py_midicsv.csv_to_midi(csv_string)

    with open(new_mini_name + '.mid', "wb") as output_file:
        midi_writer = py_midicsv.FileWriter(output_file)
        midi_writer.write(midi_object)