def presetToCsv(preset):

    mid = mido.read_syx_file(preset["midiFile"])
    mido.write_syx_file('patch.txt', mid, plaintext=True)
    mid = mido.MidiFile(preset["midiFile"])
    #print(mid)

    try:
        skip = preset["skip"]
    except KeyError:
        skip = 0

    for i, track in enumerate(mid.tracks):
        counter = 0
        for m, msg in enumerate(track):

            #if skip != 0 and not m % 2:
            #    continue
            #print("--------------------------------", m)
            try:
                print("--------------------------------", m, msg.data[3],
                      msg.data[4], msg.data[5], msg.data[6], msg.data[7],
                      msg.data[8], msg.data[9], msg.data[10], msg.data[11],
                      msg.data[12])
                allChars = []
                patchNameChars = []
                for idx, chrOrd in enumerate(msg.data):
                    allChars.append(chr(chrOrd))

                    if idx < preset["idx"]["titleBegin"] or idx > preset[
                            "idx"]["titleEnd"]:
                        continue
                    patchNameChars.append(chr(chrOrd))

                try:
                    categoryString = preset["categories"][msg.data[
                        preset["idx"]["cat"]]]
                except IndexError:
                    categoryString = ""

                patchName = ''.join(patchNameChars).strip()

                msb = str(msg.data[preset["idx"]["msb"]])
                pc = str(msg.data[preset["idx"]["pc"]])

                if dumpAllChars:
                    print(''.join(allChars).strip())
                else:
                    print('"' +
                          '","'.join([msb, pc, patchName, categoryString]) +
                          '"')

                counter += 1
                if limitOutputTo == None:
                    continue
                if counter > limitOutputTo:
                    sys.exit()
            except AttributeError:
                continue
Example #2
0
 def dump_raw(self, **kwargs):
     if 'filename' in kwargs:
         # if filename is given, dump to syx file:
         # update: create sysex-message so we don't have to manually add the
         # first and last byte
         message = []
         for m in self.msg_bytes[:]:
             h, l = self.nib(m)
             message.append(h)
             message.append(l)
         msg = mido.Message('sysex', data=message)
         mido.write_syx_file(kwargs['filename'], (msg, ))
     else:
         print(*self.msg_bytes)
Example #3
0
    def make_b00_file(self):

        new_add_syx_0 = [0xF0, 0x43, 0x10, 0x4C, 0x00, 0x00, 0x7E, 0x00, 0xF7]

        new_add_syx_1 = [0xF0, 0x43, 0x70, 0x70, 0x73, 0xF7]

        send_request = [0xF0, 0x43, 0x70, 0x78, 0x20, 0xF7]

        send_bank = [
            0xF0, 0x43, 0x70, 0x78, 0x44, 0x7e, 0x00, 0x00, 0x00, 0xF7
        ]

        save_forbidden = [
            0xF0, 0x43, 0x70, 0x78, 0x44, 0x7e, 0x00, 0x02, 0x01, 0xF7
        ]

        cancel_forbidden = [
            0xF0, 0x43, 0x70, 0x78, 0x44, 0x7e, 0x00, 0x02, 0x00, 0xF7
        ]

        midi_new_add_syx0 = mido.parse(new_add_syx_0)
        midi_new_add_syx1 = mido.parse(new_add_syx_1)
        midi_cancel_forbidden = mido.parse(cancel_forbidden)
        midi_save_forbidden = mido.parse(save_forbidden)

        midi_send_request = mido.parse(send_request)

        midi_send_boo = self.dump_b00()

        midi_send_bank = mido.parse(send_bank)
        file_path = self.save_path

        messages = [
            midi_new_add_syx0,
            midi_new_add_syx1,
            midi_cancel_forbidden,
            midi_save_forbidden,
            midi_send_request,
            midi_send_boo,
            midi_send_bank,
        ]
        file_upload = UploadFile()
        file_upload.mkdir_temp(self.dir_name)
        mido.write_syx_file(file_path, messages)
        fname, fpath = file_upload.oss_upload(self.name_path, file_path)
        file_upload.remove_temp(self.dir_name)
        self.sql_path = fpath
        return self.sql_path
Example #4
0
def process(frames):
    global offset, i
    global msg
    global syx_iter
    global controller_map, patch_no, vals, latent
    port.clear_buffer()
    needs_update = False

    for offset, data in inport.incoming_midi_events():
        msg = mido.parse(bytes(data))

        if msg.type == 'note_on':
            port.write_midi_event(
                0,
                mido.Message('control_change', control=123).bytes())
        if msg.type != 'control_change':
            continue

        if msg.control not in controller_map:
            if len(controller_map) == 8:
                continue
            print(f"latent {len(controller_map)} set to encoder {msg.control}")
            controller_map[msg.control] = len(controller_map)
        l_i = list(controller_map).index(msg.control)
        print(f'Latent: {latent}')
        latent[:, controller_map[msg.control]] = msg.value
        needs_update = True

        # print("{0}: 0x{1}".format(client.last_frame_time + offset,
        #                           binascii.hexlify(data).decode()))
    # print(time.time()-offset)
    inport.clear_buffer()
    if (needs_update):
        offset = time.time()

        z = vals.gather(0, latent)
        msg = model.generate(z, t=0.001).sample()

        msg = DX7Single.to_syx(msg.numpy().tolist())

        port.write_midi_event(1, msg.bytes())
        mido.write_syx_file('example_single_voice.mid', [msg])
Example #5
0
	def write_syx(self, filename):
		assert (self._verify(self._data) == self.VERIFY_COMPLETE)
		mido.write_syx_file(filename, self._data, plaintext=False)
Example #6
0
    # for i in tqdm(range(max_to_sample)):

    logits = model.generate(X, X_a)
    samples = logits.sample()

    has_unsampled = ~X_a.all(-1)

    batch_idxs, sample_idx = (~X_a).nonzero().t()

    X[batch_idxs, sample_idx] = samples[batch_idxs, sample_idx]
    X_a[batch_idxs, sample_idx] = 1

    syx = dx7_bulk_pack(X.numpy().tolist())
    mido.write_syx_file(
        f'/home/nintorac/.local/share/DigitalSuburban/Dexed/Cartridges/neuralDX7/np_{n}.syx',
        [syx])

# # %%
# from neuralDX7.constants import voice_struct, VOICE_KEYS, checksum
# def dx7_bulk_pack(voices):

#     HEADER = int('0x43', 0), int('0x00', 0), int('0x09', 0), int('0x20', 0), int('0x00', 0)
#     assert len(voices)==32
#     voices_bytes = bytes()
#     for voice in voices:
#         voice_bytes = voice_struct.pack(dict(zip(VOICE_KEYS, voice)))
#         voices_bytes += voice_bytes

#     patch_checksum = [checksum(voices_bytes)]
Example #7
0
#%%
plt.figure(figsize=(20, 30))
plt.scatter(*zip(*X_embedded), linewidths=0.1)

# %%
### ---------K-means---------------

from sklearn.cluster import KMeans
from neuralDX7.utils import dx7_bulk_pack
import mido
n_clusters = 8
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(features)
labels = kmeans.labels_
tasting = []

out_template = '/home/nintorac/.local/share/DigitalSuburban/Dexed/cartridges/neuralDX7/group_{}.syx'

for i in range(n_clusters):
    in_cluster, = (labels == i).nonzero()
    if len(in_cluster) < 32:
        continue

    choices = np.random.choice(in_cluster, 32)
    voices = X[choices]

    patch_message = dx7_bulk_pack(voices)

    mido.write_syx_file(out_template.format(i), [patch_message])

# %%
 &&&&&  %&&&&&   &&&&&&&&&&&   &&&&&   &&&&&/  &&&&&&&&&&&&
"""

TIMESTAMP = datetime.now().strftime('%Y%m%d-%H%M')
A4_DATA_SIZE = 725

print (LOGO)
print(" --[ KORG A4 MIDI Dump ] --\n")


midi_in_port = mido.open_input('Studio 1810c')
print("[READY] Waiting for MIDI data from A4]")
midi_msg = midi_in_port.receive()
sysex_data = midi_msg.data

if len(sysex_data) == A4_DATA_SIZE:
    print("[SUCCESS] Data Read Successful")

    patch_data = [mido.Message('sysex', data=sysex_data)]
    file_name_text = f"korg-a4-patches-{TIMESTAMP}.txt"
    file_name_raw = f"korg-a4-patches-{TIMESTAMP}.sysex"

    try:
        mido.write_syx_file(file_name_text, patch_data, plaintext=True)
        mido.write_syx_file(file_name_raw, patch_data, plaintext=False)
        print (f"[SUCCESS] Data written to {file_name_text}, {file_name_raw}")
    except:
        print (f"[FAILED] Something went wrong writing files.")

else:
    print(f"[Failed] Wrong MIDI Data size: {len(sysex_data)}")
Example #9
0
 def write_syx(self, filename):
     assert (self._verify(self._data) == self.VERIFY_COMPLETE)
     mido.write_syx_file(filename, self._data, plaintext=False)
Example #10
0
else:
    file_prefix = ''

port = mido.open_input(midi_devs[int(sys.argv[1])])

for bank in range(1, 9):
    for number in range(1, 9):
        while True:
            msg = port.receive()
            if msg.type == 'sysex':
                if (msg.data[0] == 65 and msg.data[1] == 53
                        and msg.data[2] == 0 and msg.data[3] == 35
                        and msg.data[4] == 32):
                    file_name = file_prefix + str(bank) + str(number) + ' '
                    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -"
                    for i in range(42, 52):
                        file_name += alpha[msg.data[i]]
                    file_name = file_name.rstrip()
                    file_name += '.syx'
                    print(file_name)
                    mido.write_syx_file(file_name, (msg, ))
                    break
    while True:
        msg = port.receive()
        if msg.type == 'sysex':
            if (msg.data[0] == 65 and msg.data[1] == 53 and msg.data[2] == 0
                    and msg.data[3] == 35 and msg.data[4] == 32):
                break

port.close()
Example #11
0
    # voices
    for params in params_list:

        for osc in range(N_OSC):
            data += encode_osc(params, osc)

        data += encode_global(params)

    this_checksum = checksum(data)

    return [*head, *data, this_checksum]


#%%

data = np.load(ARTIFACTS_ROOT.joinpath('dev-dx7.npy'))
data = np.load(ARTIFACTS_ROOT.joinpath('dev-dx7.npy'))[[1] * 32]

params_list = list(
    map(lambda params: dict(zip(PARAMETER_ORDER, list(params))), data))

syx = encode_syx(params_list)

message = mido.Message('sysex', data=syx)
mido.write_syx_file(ARTIFACTS_ROOT.joinpath('patch.syx'), [message])

# %%

# %%
Example #12
0
 def backup_all(self, directory, prefix='patch_'):
     for i, (bank, prog) in enumerate(product(['A','B','C','D'], range(1,9))):
         program_name = '%s%i' % (bank, prog)
         print(program_name, end=' ')
         write_syx_file(os.path.join(directory, '%s%s.syx'%(prefix, program_name)),
                        self.download_patch(i))
Example #13
0
 def write_data_to_file(self, filename, data):
     messages = [Message('sysex', data=data)]
     mido.write_syx_file(filename, messages)