-
Notifications
You must be signed in to change notification settings - Fork 16
/
openai_musenet_colab_notebook.py
491 lines (361 loc) · 29.7 KB
/
openai_musenet_colab_notebook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# -*- coding: utf-8 -*-
"""OpenAI_MuseNet_Colab_Notebook.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/asigalov61/OpenAI-MuseNet-Colab-Notebook/blob/main/OpenAI_MuseNet_Colab_Notebook.ipynb
# MuseNet Companion (ver 1.0)
# OpenAI MuseNet API Colab Notebook
***
### Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools
### Source code is courtesy of https://github.com/MrCheeze/musenet-midi and https://github.com/daanklijn/musenet-midi-py
***
### Project Los Angeles
### Tegridy Code 2022
***
# Setup Environment
"""
#@title Install dependecies
!git clone https://github.com/asigalov61/tegridy-tools
!pip install requests # for MuseNet API requests
!pip install numpy
!pip install matplotlib # for plotting only
!apt install fluidsynth # Pip does not work for some reason. Only apt works
!pip install midi2audio # for plotting only
#@title Import modules
print('Loading needed modules. Please wait...')
import os
import secrets
import requests # for MuseNet API
import copy
import json
import numpy
print('Loading TMIDIX module...')
os.chdir('/content/tegridy-tools/tegridy-tools')
import TMIDIX # for MIDI processing
# for plotting/listening only
import matplotlib.pyplot as plt
from midi2audio import FluidSynth
import matplotlib.pyplot as plt
from IPython.display import display, Audio
os.chdir('/content/')
print('Done!')
"""# Generate"""
#@title Load Custom MIDI
full_path_to_custom_MIDI = "/content/tegridy-tools/tegridy-tools/seed2.mid" #@param {type:"string"}
display_this_number_of_tokens = 512 #@param {type:"slider", min:16, max:4096, step:16}
print('Loading custom MIDI...')
data0 = TMIDIX.midi2opus(open(full_path_to_custom_MIDI, 'rb').read())
print('Parsing data...')
INSTRUMENTS = ["piano", "piano", "piano", "piano", "piano", "piano", "piano", "piano", "piano",
"piano", "piano", "piano", "piano", "piano",
"violin", "violin", "cello", "cello", "bass", "bass", "guitar", "guitar",
"flute", "flute", "clarinet", "clarinet", "trumpet", "trumpet", "harp", "harp",
'drum', 'drum']
TRACKS_OUT_INDEX = {"piano": 0, "violin": 3, "cello": 4, "bass": 2, "guitar": 1, "flute": 8,
"clarinet": 7, "trumpet": 6, "harp": 5, "drum": 9}
VOLUMES = [0, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 80, 0, 80, 0, 80, 0, 80, 0, 80,
0, 80, 0, 80, 0, 80, 0, 100, 0]
DELAY_MULTIPLIER = 10
FNAME = '/content/MuseNet-Companion-Composition'
events_matrix = []
itrack = 1
while itrack < len(data0):
for event in data0[itrack]:
if event[0] == 'note_on' or event[0] == 'note_off' or event[0] == 'patch_change':
events_matrix.append(event)
itrack += 1
patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
patch_map = [[0, 1, 2, 3, 4, 5, 6, 7], # Piano
[40, 41], # Violin
[42, 43], # Cello
[32, 33, 34, 35, 36, 37, 38, 39], # Bass
[24, 25, 26, 27, 28, 29, 30], # Guitar
[73, 74, 75], # Flute
[71, 72], # Clarinet
[56, 57, 58, 59, 60], # Trumpet
[46], # Harp
[-1] # Drums
]
events_matrix2 = []
for event in events_matrix:
if event[0] == 'patch_change':
patches[event[2]] = event[3]
if event[0] == 'note_on' or event[0] == 'note_off':
event.extend([patches[event[2]]])
once = False
for p in patch_map:
if event[5] in p and event[2] != 9: # Except the drums
event[2] = patch_map.index(p)
once = True
if not once and event[2] != 9: # Except the drums
event[2] = 0 # All other instruments/patches channel
event[4] = max(80, event[4])
if event[2] < 10: # We won't write chans 11-16 for now...
events_matrix2.append(event)
encoded = []
for event in events_matrix2:
time = event[1] / 10
if event[1] != 0:
encoded.append(min(127, int(time)) + (128 * 31))
if event[0] == 'note_on':
if event[2] == 0:
encoded.append(event[3] + (int(event[4] / 9) * 128))
if event[2] > 0 and event[2] < 9:
encoded.append(event[3] + ((12 + (2*event[2])) * 128))
if event[2] == 9:
encoded.append(event[3] + (30 * 128))
if event[0] == 'note_off':
if event[2] == 0:
encoded.append(event[3] + (0 * 128))
if event[2] > 0 and event[2] < 9:
encoded.append(event[3] + ((13 + (2*event[2])) * 128))
if event[2] == 9:
encoded.append(0 + (31 * 128))
print('Rendering the encoding and plotting custom MIDI...')
song = []
delta_times = 0
for token in encoded[:display_this_number_of_tokens]:
if 0 <= token < 3840:
note = token % 128
idx = token // 128
velocity = VOLUMES[idx]
instrument = INSTRUMENTS[idx]
channel = TRACKS_OUT_INDEX[instrument]
delay = delta_times
if velocity > 0:
song.append(['note_on', delay * DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
else:
song.append(['note_off', delay * DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
elif 3840 <= token <= 3968:
note = token % 128
idx = token // 128
velocity = VOLUMES[idx]
instrument = INSTRUMENTS[idx]
channel = TRACKS_OUT_INDEX[instrument]
delay = delta_times
if velocity > 0:
song.append(['note_on', delay* DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
else:
song.append(['note_off', (delay+1) * DELAY_MULTIPLIER, channel, note, 0])
delta_times = 0
elif 3968 < token < 4096:
delta_times = token % 128
elif token == 4096:
pass
else:
pass
print('Converting to MIDI. Please stand-by...')
output_signature = 'MuseNet Companion'
track_name = 'Project Los Angeles'
number_of_ticks_per_quarter = data0[0]
list_of_MIDI_patches = [0, 24, 32, 40, 42, 46, 56, 71, 73, 0, 0, 0, 0, 0, 0, 0]
output_file_name = FNAME
text_encoding='ISO-8859-1'
output_header = [number_of_ticks_per_quarter,
[['track_name', 0, bytes(output_signature, text_encoding)]]]
patch_list = [['patch_change', 0, 0, list_of_MIDI_patches[0]],
['patch_change', 0, 1, list_of_MIDI_patches[1]],
['patch_change', 0, 2, list_of_MIDI_patches[2]],
['patch_change', 0, 3, list_of_MIDI_patches[3]],
['patch_change', 0, 4, list_of_MIDI_patches[4]],
['patch_change', 0, 5, list_of_MIDI_patches[5]],
['patch_change', 0, 6, list_of_MIDI_patches[6]],
['patch_change', 0, 7, list_of_MIDI_patches[7]],
['patch_change', 0, 8, list_of_MIDI_patches[8]],
['patch_change', 0, 9, list_of_MIDI_patches[9]],
['patch_change', 0, 10, list_of_MIDI_patches[10]],
['patch_change', 0, 11, list_of_MIDI_patches[11]],
['patch_change', 0, 12, list_of_MIDI_patches[12]],
['patch_change', 0, 13, list_of_MIDI_patches[13]],
['patch_change', 0, 14, list_of_MIDI_patches[14]],
['patch_change', 0, 15, list_of_MIDI_patches[15]],
['track_name', 0, bytes(track_name, text_encoding)]]
output = output_header + [patch_list + song]
midi_data = TMIDIX.opus2midi(output, text_encoding)
with open(output_file_name + '.mid', 'wb') as midi_file:
midi_file.write(midi_data)
midi_file.close()
print('Displaying resulting composition...')
x = []
y =[]
c = []
colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver']
song_f = TMIDIX.opus2score(output)
for s in song_f[2]:
if s[0] == 'note':
x.append(s[1] / (data0[0]*2))
y.append(s[4])
c.append(colors[s[3]])
FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(output_file_name + '.mid'), str(output_file_name + '.wav'))
display(Audio(str(output_file_name + '.wav'), rate=16000))
plt.figure(figsize=(14,5))
ax=plt.axes(title=output_file_name)
ax.set_facecolor('black')
plt.scatter(x,y, c=c)
plt.xlabel("Time")
plt.ylabel("Pitch")
plt.show()
print('Done! Enjoy! :)')
"""# Querry MuseNet API and plot/play the results"""
#@title Querry API and play/plot results
#@markdown Custom MIDI or self-continuation
use_loaded_custom_MIDI = True #@param {type:"boolean"}
trim_custom_MIDI_tokens = 512 #@param {type:"slider", min:64, max:4096, step:64}
#@markdown Select a genre from dropdown menu
genre = 'chopin' #@param ["random", "chopin", "mozart", "rachmaninoff", "ladygaga", "country", "disney", "jazz", "bach", "beethoven", "journey", "thebeatles", "video", "broadway", "franksinatra", "bluegrass", "tchaikovsky", "liszt", "everything", "ragtime", "andrehazes", "cocciante", "thecranberries", "ligabue", "metallica", "traffic", "philcollins", "nineinchnails", "thepretenders", "sugarray", "grandfunkrailroad", "ron", "ellington", "fleetwoodmac", "thebeachboys", "kool & the gang", "foreigner", "tlc", "scottjames", "benfoldsfive", "smashmouth", "oasis", "allsaints", "donnasummer", "weezer", "bjork", "mariahcarey", "berte", "cheaptrick", "caroleking", "thecars", "gganderson", "robertpalmer", "zucchero", "alicecooper", "vanhalen", "brucehornsby", "coolio", "jimmybuffett", "lobo", "badcompany", "eminem", "creedenceclearwaterrevival", "deeppurple", "shearinggeorge", "robbiewilliams", "dalla", "ub40", "lindaronstadt", "sinatra", "inxs", "jonimitchell", "michaeljackson", "last", "devo", "shaniatwain", "korn", "brooksgarth", "sweet", "thewho", "roxette", "bowiedavid", "beegees", "renefroger", "mina", "estefangloria", "mccartney", "theventures", "carboni", "simplyred", "santana", "jewel", "meatloaf", "giorgia", "nofx", "rickymartin", "thecure", "thetemptations", "tozzi", "beck", "eiffel65", "jenniferlopez", "reelbigfish", "patsycline", "richardcliff", "styx", "acdc", "brucespringsteen", "michaelgeorge", "blondie", "pinkfloyd", "oldfieldmike", "redhotchilipeppers", "therollingstones", "morandi", "heart", "robertaflack", "pantera", "alabama", "jethrotull", "hanson", "mosch", "ludwigvanbeethoven", "dvorak", "chrisrea", "guns n' roses", "duranduran", "ericclapton", "bettemidler", "bwitched", "gordonlightfoot", "thegrassroots", "chicago", "whitezombie", "michaelbolton", "paulsimon", "marillion", "thepointersisters", "theanimals", "cher", "haydn", "aerosmith", "supertramp", "littleriverband", "america", "tonyorlando", "tompetty", "thecorrs", "aliceinchains", "kiss", "prince", "toto", "vanmorrison", "wagner", "cashjohnny", "annielennox", "enya", "thedoobiebrothers", "thetragicallyhip", "rush", "laurapausini", "stevemillerband", "simonandgarfunkel", "fiorellamannoia", "olivianewton-john", "carlysimon", "elvispresley", "vangelis", "bobdylan", "bbking", "vengaboys", "paoli", "thehollies", "alainsouchon", "pooh", "raf", "fiorello", "lionelrichie", "jimihendrix", "theeverlybrothers", "limpbizkit", "donhenley", "georgeharrison", "threedognight", "johnmellencamp", "carpenters", "raycharles", "basie", "billyocean", "scorpions", "royorbison", "whitneyhouston", "ironmaiden", "jovanotti", "alanjackson", "barrymanilow", "hueylewis", "kennyloggins", "chopinfrederic", "talkingheads", "themonkees", "rem", "jeanmicheljarre", "michelezarrillo", "eurythmics", "thedoors", "guesswho", "miller", "thefourseasons", "matiabazar", "tompettyandtheheartbreakers", "chickcorea", "scottjoplin", "amedeominghi", "bryanadams", "paulaabdul", "rossivasco", "billyjoel", "daniele", "claudedebussy", "gilbert & sullivan", "chakakhan", "nirvana", "garbage", "andreabocelli", "johnnyrivers", "emerson, lake & palmer", "theallmanbrothersband", "zappa", "boston", "mango", "barbrastreisand", "willsmith", "ozzyosbourne", "janetjackson", "antonellovenditti", "u2", "humperdinckengelbert", "jamiroquai", "zero", "chuckberry", "spicegirls", "ledzeppelin", "masini", "thekinks", "eagles", "billyidol", "alanismorissette", "joecocker", "jimcroce", "bobmarley", "blacksabbath", "stonetemplepilots", "silverchair", "paulmccartney", "blur", "nek", "greenday", "thepolice", "depechemode", "rageagainstthemachine", "madonna", "rogerskenny", "brooks & dunn", "883", "thedrifters", "amygrant", "herman", "toriamos", "eltonjohn", "britneyspears", "lennykravitz", "celentano", "ringostarr", "neildiamond", "aqua", "oscarpeterson", "joejackson", "moby", "collinsphil", "leosayer", "takethat", "electriclightorchestra", "pearljam", "marcanthony", "borodin", "petshopboys", "stevienicks", "hollybuddy", "turnertina", "annaoxa", "zztop", "sting", "themoodyblues", "ruggeri", "creed", "claudebolling", "renzoarbore", "erasure", "elviscostello", "airsupply", "tinaturner", "leali", "petergabriel", "nodoubt", "bread", "huey lewis & the news", "brandy", "level42", "radiohead", "georgebenson", "wonderstevie", "thesmashingpumpkins", "cyndilauper", "rodstewart", "bush", "ramazzotti", "bobseger", "theshadows", "gershwin", "cream", "biagioantonacci", "steviewonder", "nomadi", "direstraits", "davidbowie", "amostori", "thealanparsonsproject", "johnlennon", "crosbystillsnashandyoung", "battiato", "kansas", "clementi", "richielionel", "yes", "brassensgeorges", "steelydan", "jacksonmichael", "buddyholly", "earthwindandfire", "natkingcole", "therascals", "bonjovi", "alanparsons", "backstreetboys", "glencampbell", "howardcarpendale", "thesupremes", "villagepeople", "blink-182", "jacksonbrowne", "sade", "lynyrdskynyrd", "foofighters", "2unlimited", "battisti", "hall & oates", "stansfieldlisa", "genesis", "boyzone", "theoffspring", "tomjones", "davematthewsband", "johnelton", "neilyoung", "dionnewarwick", "aceofbase", "marilynmanson", "taylorjames", "rkelly", "grandi", "sublime", "edvardgrieg", "tool", "bachjohannsebastian", "patbenatar", "celinedion", "queen", "soundgarden", "abba", "drdre", "defleppard", "dominofats", "realmccoy", "natalieimbruglia", "hole", "spinners", "arethafranklin", "reospeedwagon", "indian", "movie", "scottish", "irish", "african", "taylorswift", "shakira", "blues", "latin", "katyperry", "world", "kpop", "africandrum", "michaelbuble", "rihanna", "gospel", "beyonce", "chinese", "arabic", "adele", "kellyclarkson", "theeagles", "handel", "rachmaninov", "schumann", "christmas", "dance", "punk", "natl_anthem", "brahms", "rap", "ravel", "burgmueller", "other", "schubert", "granados", "albeniz", "mendelssohn", "debussy", "grieg", "moszkowski", "godowsky", "folk", "mussorgsky", "kids", "balakirev", "hymns", "verdi", "hummel", "deleted", "delibes", "saint-saens", "puccini", "satie", "offenbach", "widor", "songs", "stravinsky", "vivaldi", "gurlitt", "alkan", "weber", "strauss", "traditional", "rossini", "mahler", "soler", "sousa", "telemann", "busoni", "scarlatti", "stamitz", "classical", "jstrauss2", "gabrieli", "nielsen", "purcell", "donizetti", "kuhlau", "gounod", "gibbons", "weiss", "faure", "holst", "spohr", "monteverdi", "reger", "bizet", "elgar", "czerny", "sullivan", "shostakovich", "franck", "rubinstein", "albrechtsberger", "paganini", "diabelli", "gottschalk", "wieniawski", "lully", "morley", "sibelius", "scriabin", "heller", "thalberg", "dowland", "carulli", "pachelbel", "sor", "marcello", "ketterer", "rimsky-korsakov", "ascher", "bruckner", "janequin", "anonymous", "kreutzer", "sanz", "joplin", "susato", "giuliani", "lassus", "palestrina", "smetana", "berlioz", "couperin", "gomolka", "daquin", "herz", "campion", "walthew", "pergolesi", "reicha", "polak", "holborne", "hassler", "corelli", "cato", "azzaiolo", "anerio", "gastoldi", "goudimel", "dussek", "prez", "cimarosa", "byrd", "praetorius", "rameau", "khachaturian", "machaut", "gade", "perosi", "gorzanis", "smith", "haberbier", "carr", "marais", "glazunov", "guerrero", "cabanilles", "losy", "roman", "hasse", "sammartini", "blow", "zipoli", "duvernoy", "aguado", "cherubini", "victoria", "field", "andersen", "poulenc", "d'aragona", "lemire", "krakowa", "maier", "rimini", "encina", "banchieri", "best", "galilei", "warhorse", "gypsy", "soundtrack", "encore", "roblaidlow", "nationalanthems", "benjyshelton", "ongcmu", "crosbystillsnashyoung", "smashingpumpkins", "aaaaaaaaaaa", "alanismorrisette", "animenz", "onedirection", "nintendo", "disneythemes", "gunsnroses", "rollingstones", "juliancasablancas", "abdelmoinealfa", "berckmansdeoliveira", "moviethemes", "beachboys", "davemathews", "videogamethemes", "moabberckmansdeoliveira", "unknown", "cameronleesimpson", "johannsebastianbach", "thecarpenters", "elo", "nightwish", "blink182", "emersonlakeandpalmer", "tvthemes"]
#@markdown Select instruments
piano = True #@param {type:"boolean"}
strings = True #@param {type:"boolean"}
winds = True #@param {type:"boolean"}
drums = True #@param {type:"boolean"}
harp = True #@param {type:"boolean"}
guitar = True #@param {type:"boolean"}
bass = True #@param {type:"boolean"}
#@markdown Generation settings
number_of_tokens_to_generate = 512 #@param {type:"slider", min:64, max:1024, step:8}
temperature = 1 #@param {type:"slider", min:0.1, max:2, step:0.1}
truncation = 0 #@param {type:"integer"}
INSTRUMENTS = ["piano", "piano", "piano", "piano", "piano", "piano", "piano", "piano", "piano",
"piano", "piano", "piano", "piano", "piano",
"violin", "violin", "cello", "cello", "bass", "bass", "guitar", "guitar",
"flute", "flute", "clarinet", "clarinet", "trumpet", "trumpet", "harp", "harp",
'drum', 'drum']
TRACKS_OUT_INDEX = {"piano": 0, "violin": 3, "cello": 4, "bass": 2, "guitar": 1, "flute": 8,
"clarinet": 7, "trumpet": 6, "harp": 5, "drum": 9}
VOLUMES = [0, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 80, 0, 80, 0, 80, 0, 80, 0, 80,
0, 80, 0, 80, 0, 80, 0, 100, 0]
if use_loaded_custom_MIDI:
DELAY_MULTIPLIER = 10
else:
DELAY_MULTIPLIER = 20
if use_loaded_custom_MIDI and len(encoded) > 16:
c_encoding = ' '.join([str(y) for y in encoded[:trim_custom_MIDI_tokens]])
else:
c_encoding = '4096'
genreList = ["chopin","mozart","rachmaninoff","ladygaga","country","disney","jazz","bach","beethoven","journey","thebeatles","video","broadway","franksinatra","bluegrass","tchaikovsky","liszt","everything","ragtime","andrehazes","cocciante","thecranberries","ligabue","metallica","traffic","philcollins","nineinchnails","thepretenders","sugarray","grandfunkrailroad","ron","ellington","fleetwoodmac","thebeachboys","kool & the gang","foreigner","tlc","scottjames","benfoldsfive","smashmouth","oasis","allsaints","donnasummer","weezer","bjork","mariahcarey","berte","cheaptrick","caroleking","thecars","gganderson","robertpalmer","zucchero","alicecooper","vanhalen","brucehornsby","coolio","jimmybuffett","lobo","badcompany","eminem","creedenceclearwaterrevival","deeppurple","shearinggeorge","robbiewilliams","dalla","ub40","lindaronstadt","sinatra","inxs","jonimitchell","michaeljackson","last","devo","shaniatwain","korn","brooksgarth","sweet","thewho","roxette","bowiedavid","beegees","renefroger","mina","estefangloria","mccartney","theventures","carboni","simplyred","santana","jewel","meatloaf","giorgia","nofx","rickymartin","thecure","thetemptations","tozzi","beck","eiffel65","jenniferlopez","reelbigfish","patsycline","richardcliff","styx","acdc","brucespringsteen","michaelgeorge","blondie","pinkfloyd","oldfieldmike","redhotchilipeppers","therollingstones","morandi","heart","robertaflack","pantera","alabama","jethrotull","hanson","mosch","ludwigvanbeethoven","dvorak","chrisrea","guns n' roses","duranduran","ericclapton","bettemidler","bwitched","gordonlightfoot","thegrassroots","chicago","whitezombie","michaelbolton","paulsimon","marillion","thepointersisters","theanimals","cher","haydn","aerosmith","supertramp","littleriverband","america","tonyorlando","tompetty","thecorrs","aliceinchains","kiss","prince","toto","vanmorrison","wagner","cashjohnny","annielennox","enya","thedoobiebrothers","thetragicallyhip","rush","laurapausini","stevemillerband","simonandgarfunkel","fiorellamannoia","olivianewton-john","carlysimon","elvispresley","vangelis","bobdylan","bbking","vengaboys","paoli","thehollies","alainsouchon","pooh","raf","fiorello","lionelrichie","jimihendrix","theeverlybrothers","limpbizkit","donhenley","georgeharrison","threedognight","johnmellencamp","carpenters","raycharles","basie","billyocean","scorpions","royorbison","whitneyhouston","ironmaiden","jovanotti","alanjackson","barrymanilow","hueylewis","kennyloggins","chopinfrederic","talkingheads","themonkees","rem","jeanmicheljarre","michelezarrillo","eurythmics","thedoors","guesswho","miller","thefourseasons","matiabazar","tompettyandtheheartbreakers","chickcorea","scottjoplin","amedeominghi","bryanadams","paulaabdul","rossivasco","billyjoel","daniele","claudedebussy","gilbert & sullivan","chakakhan","nirvana","garbage","andreabocelli","johnnyrivers","emerson, lake & palmer","theallmanbrothersband","zappa","boston","mango","barbrastreisand","willsmith","ozzyosbourne","janetjackson","antonellovenditti","u2","humperdinckengelbert","jamiroquai","zero","chuckberry","spicegirls","ledzeppelin","masini","thekinks","eagles","billyidol","alanismorissette","joecocker","jimcroce","bobmarley","blacksabbath","stonetemplepilots","silverchair","paulmccartney","blur","nek","greenday","thepolice","depechemode","rageagainstthemachine","madonna","rogerskenny","brooks & dunn","883","thedrifters","amygrant","herman","toriamos","eltonjohn","britneyspears","lennykravitz","celentano","ringostarr","neildiamond","aqua","oscarpeterson","joejackson","moby","collinsphil","leosayer","takethat","electriclightorchestra","pearljam","marcanthony","borodin","petshopboys","stevienicks","hollybuddy","turnertina","annaoxa","zztop","sting","themoodyblues","ruggeri","creed","claudebolling","renzoarbore","erasure","elviscostello","airsupply","tinaturner","leali","petergabriel","nodoubt","bread","huey lewis & the news","brandy","level42","radiohead","georgebenson","wonderstevie","thesmashingpumpkins","cyndilauper","rodstewart","bush","ramazzotti","bobseger","theshadows","gershwin","cream","biagioantonacci","steviewonder","nomadi","direstraits","davidbowie","amostori","thealanparsonsproject","johnlennon","crosbystillsnashandyoung","battiato","kansas","clementi","richielionel","yes","brassensgeorges","steelydan","jacksonmichael","buddyholly","earthwindandfire","natkingcole","therascals","bonjovi","alanparsons","backstreetboys","glencampbell","howardcarpendale","thesupremes","villagepeople","blink-182","jacksonbrowne","sade","lynyrdskynyrd","foofighters","2unlimited","battisti","hall & oates","stansfieldlisa","genesis","boyzone","theoffspring","tomjones","davematthewsband","johnelton","neilyoung","dionnewarwick","aceofbase","marilynmanson","taylorjames","rkelly","grandi","sublime","edvardgrieg","tool","bachjohannsebastian","patbenatar","celinedion","queen","soundgarden","abba","drdre","defleppard","dominofats","realmccoy","natalieimbruglia","hole","spinners","arethafranklin","reospeedwagon","indian","movie","scottish","irish","african","taylorswift","shakira","blues","latin","katyperry","world","kpop","africandrum","michaelbuble","rihanna","gospel","beyonce","chinese","arabic","adele","kellyclarkson","theeagles","handel","rachmaninov","schumann","christmas","dance","punk","natl_anthem","brahms","rap","ravel","burgmueller","other","schubert","granados","albeniz","mendelssohn","debussy","grieg","moszkowski","godowsky","folk","mussorgsky","kids","balakirev","hymns","verdi","hummel","deleted","delibes","saint-saens","puccini","satie","offenbach","widor","songs","stravinsky","vivaldi","gurlitt","alkan","weber","strauss","traditional","rossini","mahler","soler","sousa","telemann","busoni","scarlatti","stamitz","classical","jstrauss2","gabrieli","nielsen","purcell","donizetti","kuhlau","gounod","gibbons","weiss","faure","holst","spohr","monteverdi","reger","bizet","elgar","czerny","sullivan","shostakovich","franck","rubinstein","albrechtsberger","paganini","diabelli","gottschalk","wieniawski","lully","morley","sibelius","scriabin","heller","thalberg","dowland","carulli","pachelbel","sor","marcello","ketterer","rimsky-korsakov","ascher","bruckner","janequin","anonymous","kreutzer","sanz","joplin","susato","giuliani","lassus","palestrina","smetana","berlioz","couperin","gomolka","daquin","herz","campion","walthew","pergolesi","reicha","polak","holborne","hassler","corelli","cato","azzaiolo","anerio","gastoldi","goudimel","dussek","prez","cimarosa","byrd","praetorius","rameau","khachaturian","machaut","gade","perosi","gorzanis","smith","haberbier","carr","marais","glazunov","guerrero","cabanilles","losy","roman","hasse","sammartini","blow","zipoli","duvernoy","aguado","cherubini","victoria","field","andersen","poulenc","d'aragona","lemire","krakowa","maier","rimini","encina","banchieri","best","galilei","warhorse","gypsy","soundtrack","encore","roblaidlow","nationalanthems","benjyshelton","ongcmu","crosbystillsnashyoung","smashingpumpkins","aaaaaaaaaaa","alanismorrisette","animenz","onedirection","nintendo","disneythemes","gunsnroses","rollingstones","juliancasablancas","abdelmoinealfa","berckmansdeoliveira","moviethemes","beachboys","davemathews","videogamethemes","moabberckmansdeoliveira","unknown","cameronleesimpson","johannsebastianbach","thecarpenters","elo","nightwish","blink182","emersonlakeandpalmer","tvthemes"]
if genre == 'random':
genre = genreList[secrets.randbelow(len(genreList))]
print('Starting up...')
headers = {"Content-Type": "application/json"}
data = json.dumps({
"genre": "chopin",
"instrument":{
"piano": piano,
"strings": strings,
"winds": winds,
"drums": drums,
"harp": harp,
"guitar": guitar,
"bass": bass
},
"encoding": c_encoding,
"temperature": temperature,
"truncation": truncation,
"generationLength": number_of_tokens_to_generate,
"audioFormat": "audio/ogg"})
print('Requesting data from the MuseNet API. Please wait...')
response = requests.post('https://musenet.openai.com/sample', headers=headers, data=data)
print('Decoding...')
res = response.json()
print('Done!')
print('Parsing data...')
for i in range(4):
FNAME = '/content/MuseNet-Companion-Composition-' + str(i)
encoding = [int(y) for y in res['completions'][i]['encoding'].split()]
song = []
delta_times = 0
for token in encoding:
if 0 <= token < 3840:
note = token % 128
idx = token // 128
velocity = VOLUMES[idx]
instrument = INSTRUMENTS[idx]
channel = TRACKS_OUT_INDEX[instrument]
delay = delta_times
if velocity > 0:
song.append(['note_on', delay * DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
else:
song.append(['note_off', delay * DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
elif 3840 <= token <= 3968:
note = token % 128
idx = token // 128
velocity = VOLUMES[idx]
instrument = INSTRUMENTS[idx]
channel = TRACKS_OUT_INDEX[instrument]
delay = delta_times
if velocity > 0:
song.append(['note_on', delay* DELAY_MULTIPLIER, channel, note, velocity])
delta_times = 0
else:
song.append(['note_off', (delay+1) * DELAY_MULTIPLIER, channel, note, 0])
delta_times = 0
elif 3968 < token < 4096:
delta_times = token % 128
elif token == 4096:
pass
else:
pass
print('Converting to MIDI. Please stand-by...')
output_signature = 'MuseNet Companion'
track_name = 'Project Los Angeles'
if use_loaded_custom_MIDI:
number_of_ticks_per_quarter = data0[0]
else:
number_of_ticks_per_quarter = 1000
list_of_MIDI_patches = [0, 24, 32, 40, 42, 46, 56, 71, 73, 0, 0, 0, 0, 0, 0, 0]
output_file_name = FNAME
text_encoding='ISO-8859-1'
output_header = [number_of_ticks_per_quarter,
[['track_name', 0, bytes(output_signature, text_encoding)]]]
patch_list = [['patch_change', 0, 0, list_of_MIDI_patches[0]],
['patch_change', 0, 1, list_of_MIDI_patches[1]],
['patch_change', 0, 2, list_of_MIDI_patches[2]],
['patch_change', 0, 3, list_of_MIDI_patches[3]],
['patch_change', 0, 4, list_of_MIDI_patches[4]],
['patch_change', 0, 5, list_of_MIDI_patches[5]],
['patch_change', 0, 6, list_of_MIDI_patches[6]],
['patch_change', 0, 7, list_of_MIDI_patches[7]],
['patch_change', 0, 8, list_of_MIDI_patches[8]],
['patch_change', 0, 9, list_of_MIDI_patches[9]],
['patch_change', 0, 10, list_of_MIDI_patches[10]],
['patch_change', 0, 11, list_of_MIDI_patches[11]],
['patch_change', 0, 12, list_of_MIDI_patches[12]],
['patch_change', 0, 13, list_of_MIDI_patches[13]],
['patch_change', 0, 14, list_of_MIDI_patches[14]],
['patch_change', 0, 15, list_of_MIDI_patches[15]],
['track_name', 0, bytes(track_name, text_encoding)]]
output = output_header + [patch_list + song]
midi_data = TMIDIX.opus2midi(output, text_encoding)
with open(output_file_name + '.mid', 'wb') as midi_file:
midi_file.write(midi_data)
midi_file.close()
print('Displaying resulting composition...')
x = []
y =[]
c = []
colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver']
song_f = TMIDIX.opus2score(output)
for s in song_f[2]:
if s[0] == 'note':
if use_loaded_custom_MIDI:
x.append(s[1] / data0[0] / 2)
else:
x.append(s[1] / 2000)
y.append(s[4])
c.append(colors[s[3]])
FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(output_file_name + '.mid'), str(output_file_name + '.wav'))
display(Audio(str(output_file_name + '.wav'), rate=16000))
plt.figure(figsize=(14,5))
ax=plt.axes(title=output_file_name)
ax.set_facecolor('black')
plt.scatter(x,y, c=c)
plt.xlabel("Time")
plt.ylabel("Pitch")
plt.show()
print('Done! Enjoy! :)')
"""# Congrats! You did it! :)"""