github-actions[bot] commited on
Commit
370f492
·
1 Parent(s): 7c7a006

Sync from GitHub 2026-04-01T15:57:25Z

Browse files
Files changed (16) hide show
  1. .gitignore +0 -3
  2. LICENCE +0 -21
  3. README.md +10 -16
  4. app.py +7 -0
  5. constants.py +0 -128
  6. decoder.py +0 -346
  7. familizer.py +0 -136
  8. generate.py +0 -436
  9. generation_utils.py +0 -191
  10. licence.md +0 -21
  11. load.py +0 -63
  12. packages.txt +1 -1
  13. playback.py +0 -36
  14. playground.py +0 -207
  15. requirements.txt +1 -17
  16. utils.py +0 -300
.gitignore DELETED
@@ -1,3 +0,0 @@
1
- __pycache__/
2
- .vscode/
3
- test/
 
 
 
 
LICENCE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Halid Bayram, Louis Demetz, Jean Simonnet
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,23 +1,17 @@
1
  ---
2
  title: The Jam Machine
3
- emoji: 🎶
4
- colorFrom: indigo
5
- colorTo: black
6
  sdk: gradio
7
- sdk_version: 3.13.1
8
- python_version: 3.10.6
9
- app_file: playground.py
10
  pinned: true
 
11
  ---
12
 
13
- ## The-Jam-Machine
14
- The-Jam-Machine is a Generative AI trained on text transcription of MIDI music, meant to enhance creativity while making computer music. It uses a GPT2 model architexture and has been trained on about 5000 midi songs.
15
- ## The app
16
- The app hosted on HuggingFace is just a simple demo of what the AI can do. \
17
- It is be limited to 3 instruments and 8 bars of music. \
18
 
19
- ## [Project Presentation](https://pitch.com/public/417162a8-88b0-4472-a651-c66bb89428be)
20
- ## Contributors:
21
- Jean Simonnet: [Github](https://github.com/misnaej) / [Linkedin](https://www.linkedin.com/in/jeansimonnet/) \
22
- Louis Demetz: [Github](https://github.com/louis-demetz) / [Linkedin](https://www.linkedin.com/in/ldemetz/) \
23
- Halid Bayram: [Github](https://github.com/m41w4r3exe) / [Linkedin](https://www.linkedin.com/in/halid-bayram-6b9ba861/)
 
1
  ---
2
  title: The Jam Machine
3
+ emoji: 🎹
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
+ python_version: "3.11"
8
+ app_file: app.py
 
9
  pinned: true
10
+ license: mit
11
  ---
12
 
13
+ # The Jam Machine
 
 
 
 
14
 
15
+ Generative AI music composition using a GPT-2 model trained on ~5,000 MIDI songs.
16
+
17
+ See the [GitHub repo](https://github.com/misnaej/the-jam-machine) for details.
 
 
app.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """HuggingFace Space entry point for The Jam Machine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from jammy.app.playground import demo
6
+
7
+ demo.launch(server_name="0.0.0.0", server_port=7860) # noqa: S104
constants.py DELETED
@@ -1,128 +0,0 @@
1
- # fmt: off
2
- # Instrument mapping and mapping functions
3
- INSTRUMENT_CLASSES = [
4
- {"name": "Piano", "program_range": range(0, 8), "family_number": 0},
5
- {"name": "Chromatic Percussion", "program_range": range(8, 16), "family_number": 1},
6
- {"name": "Organ", "program_range": range(16, 24), "family_number": 2},
7
- {"name": "Guitar", "program_range": range(24, 32), "family_number": 3},
8
- {"name": "Bass", "program_range": range(32, 40), "family_number": 4},
9
- {"name": "Strings", "program_range": range(40, 48), "family_number": 5},
10
- {"name": "Ensemble", "program_range": range(48, 56), "family_number": 6},
11
- {"name": "Brass", "program_range": range(56, 64), "family_number": 7},
12
- {"name": "Reed", "program_range": range(64, 72), "family_number": 8},
13
- {"name": "Pipe", "program_range": range(72, 80), "family_number": 9},
14
- {"name": "Synth Lead", "program_range": range(80, 88), "family_number": 10},
15
- {"name": "Synth Pad", "program_range": range(88, 96), "family_number": 11},
16
- {"name": "Synth Effects", "program_range": range(96, 104), "family_number": 12},
17
- {"name": "Ethnic", "program_range": range(104, 112), "family_number": 13},
18
- {"name": "Percussive", "program_range": range(112, 120), "family_number": 14},
19
- {"name": "Sound Effects", "program_range": range(120, 128), "family_number": 15,},
20
- ]
21
- # fmt: on
22
-
23
- # Instrument mapping for decodiing our midi sequence into midi instruments of our choice
24
- INSTRUMENT_TRANSFER_CLASSES = [
25
- {
26
- "name": "Piano",
27
- "program_range": [4],
28
- "family_number": 0,
29
- "transfer_to": "Electric Piano 1",
30
- },
31
- {
32
- "name": "Chromatic Percussion",
33
- "program_range": [11],
34
- "family_number": 1,
35
- "transfer_to": "Vibraphone",
36
- },
37
- {
38
- "name": "Organ",
39
- "program_range": [17],
40
- "family_number": 2,
41
- "transfer_to": "Percussive Organ",
42
- },
43
- {
44
- "name": "Guitar",
45
- "program_range": [80],
46
- "family_number": 3,
47
- "transfer_to": "Synth Lead Square",
48
- },
49
- {
50
- "name": "Bass",
51
- "program_range": [38],
52
- "family_number": 4,
53
- "transfer_to": "Synth Bass 1",
54
- },
55
- {
56
- "name": "Strings",
57
- "program_range": [50],
58
- "family_number": 5,
59
- "transfer_to": "Synth Strings 1",
60
- },
61
- {
62
- "name": "Ensemble",
63
- "program_range": [51],
64
- "family_number": 6,
65
- "transfer_to": "Synth Strings 2",
66
- },
67
- {
68
- "name": "Brass",
69
- "program_range": [63],
70
- "family_number": 7,
71
- "transfer_to": "Synth Brass 1",
72
- },
73
- {
74
- "name": "Reed",
75
- "program_range": [64],
76
- "family_number": 8,
77
- "transfer_to": "Synth Brass 2",
78
- },
79
- {
80
- "name": "Pipe",
81
- "program_range": [82],
82
- "family_number": 9,
83
- "transfer_to": "Synth Lead Calliope",
84
- },
85
- {
86
- "name": "Synth Lead",
87
- "program_range": [81], # Synth Lead Sawtooth
88
- "family_number": 10,
89
- "transfer_to": "Synth Lead Sawtooth",
90
- },
91
- {
92
- "name": "Synth Pad",
93
- "program_range": range(88, 96),
94
- "family_number": 11,
95
- "transfer_to": "Synth Pad",
96
- },
97
- {
98
- "name": "Synth Effects",
99
- "program_range": range(96, 104),
100
- "family_number": 12,
101
- "transfer_to": "Synth Effects",
102
- },
103
- {
104
- "name": "Ethnic",
105
- "program_range": range(104, 112),
106
- "family_number": 13,
107
- "transfer_to": "Ethnic",
108
- },
109
- {
110
- "name": "Percussive",
111
- "program_range": range(112, 120),
112
- "family_number": 14,
113
- "transfer_to": "Percussive",
114
- },
115
- {
116
- "name": "Sound Effects",
117
- "program_range": range(120, 128),
118
- "family_number": 15,
119
- "transfer_to": "Sound Effects",
120
- },
121
- ]
122
-
123
-
124
- "Encoding and decoding constants"
125
-
126
- DRUMS_BEAT_QUANTIZATION = 4 # 8th notes per beat
127
- NONE_DRUMS_BEAT_QUANTIZATION = 4 # 4th notes per beat
128
- BEATS_PER_BAR = 4 # 4/4 time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
decoder.py DELETED
@@ -1,346 +0,0 @@
1
- from utils import *
2
- from familizer import Familizer
3
- from miditok import Event
4
-
5
-
6
- class TextDecoder:
7
- """Decodes text into:
8
- 1- List of events
9
- 2- Then converts these events to midi file via MidiTok and miditoolkit
10
-
11
- :param tokenizer: from MidiTok
12
-
13
- Usage with write_to_midi method:
14
- args: text(String) example -> PIECE_START TRACK_START INST=25 DENSITY=2 BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50...BAR_END TRACK_END
15
- returns: midi file from miditoolkit
16
- """
17
-
18
- def __init__(self, tokenizer, familized=True):
19
- self.tokenizer = tokenizer
20
- self.familized = familized
21
-
22
- def decode(self, text):
23
- r"""converts from text to instrument events
24
- Args:
25
- text (String): example -> PIECE_START TRACK_START INST=25 DENSITY=2 BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50...BAR_END TRACK_END
26
-
27
- Returns:
28
- Dict{inst_id: List[Events]}: List of events of Notes with velocities, aggregated Timeshifts, for each instrument
29
- """
30
- piece_events = self.text_to_events(text)
31
- piece_events = self.get_track_ids(piece_events)
32
- self.check_for_duplicated_events(piece_events)
33
- inst_events = self.piece_to_inst_events(piece_events)
34
- inst_events = self.get_bar_ids(inst_events)
35
- events = self.add_missing_timeshifts_in_a_bar(inst_events)
36
- events = self.remove_unwanted_tokens(events)
37
- events = self.aggregate_timeshifts(events)
38
- events = self.add_velocity(events)
39
- return events
40
-
41
- def tokenize(self, events):
42
- r"""converts from events to MidiTok tokens
43
- Args:
44
- events (Dict{inst_id: List[Events]}): List of events for each instrument
45
-
46
- Returns:
47
- List[List[Events]]: List of tokens for each instrument
48
- """
49
- tokens = []
50
- for inst in events:
51
- tokens.append(self.tokenizer.events_to_tokens(inst["events"]))
52
- return tokens
53
-
54
- def get_midi(self, text, filename=None):
55
- r"""converts from text to midi
56
- Args:
57
- text (String): example -> PIECE_START TRACK_START INST=25 DENSITY=2 BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50...BAR_END TRACK_END
58
-
59
- Returns:
60
- miditoolkit midi: Returns and writes to midi
61
- """
62
- events = self.decode(text)
63
- tokens = self.tokenize(events)
64
- instruments = self.get_instruments_tuple(events)
65
- midi = self.tokenizer.tokens_to_midi(tokens, instruments)
66
-
67
- if filename is not None:
68
- midi.dump(f"{filename}")
69
- print(f"midi file written: {filename}")
70
-
71
- return midi
72
-
73
- @staticmethod
74
- def text_to_events(text, verbose=False):
75
- events = []
76
- instrument = "drums"
77
- track_index = -1
78
- # bar_value = 0
79
- cumul_time_delta = 0
80
- max_cumul_time_delta = 0
81
-
82
- for word in text.split(" "):
83
- _event = word.split("=")
84
- value = _event[1] if len(_event) > 1 else None
85
- beyond_quantization = False # needs to be reset for each event
86
-
87
- if _event[0] == "INST":
88
- track_index += 1
89
- bar_value = 0
90
- # get the instrument for passing in get_event when time_delta for proper quantization
91
- instrument = get_event(_event[0], value).value
92
-
93
- # how much delta can be added before over quantization
94
- max_cumul_time_delta = (
95
- DRUMS_BEAT_QUANTIZATION * 4
96
- if instrument.lower() == "drums"
97
- else NONE_DRUMS_BEAT_QUANTIZATION * 4
98
- )
99
-
100
- if _event[0] == "BAR_START":
101
- bar_value += 1
102
- value = bar_value
103
- # reseting cumul_time_delta
104
- cumul_time_delta = 0
105
-
106
- # ----- hack to prevent over quantization -> NOT IDEAL - the model should not output these events
107
- if _event[0] == "TIME_DELTA":
108
- cumul_time_delta += int(_event[1])
109
- if cumul_time_delta > max_cumul_time_delta:
110
- beyond_quantization = True
111
- cumul_time_delta -= int(_event[1])
112
-
113
- if _event[0] == "NOTE_ON" and cumul_time_delta >= max_cumul_time_delta:
114
- beyond_quantization = True
115
-
116
- if beyond_quantization:
117
- print(
118
- f"instrument {instrument} - bar {bar_value} - skipping {_event[0]} because of over quantization"
119
- ) if verbose else None
120
- # ---------------------------------------------------------------------------------------------``
121
-
122
- # getting event
123
- event = get_event(_event[0], value, instrument)
124
- if event and not beyond_quantization:
125
- if event.type == "Bar-End":
126
- print(
127
- f"instrument {instrument} - bar {bar_value} - Cumulated TIME_DELTA = {cumul_time_delta}"
128
- ) if verbose else None
129
- cumul_time_delta = 0
130
-
131
- # appending event
132
- events.append(event)
133
-
134
- return events
135
-
136
- @staticmethod
137
- def get_track_ids(events):
138
- """Adding tracking the track id for each track start and end event"""
139
- track_id = 0
140
- for i, event in enumerate(events):
141
- if event.type == "Track-Start":
142
- events[i].value = track_id
143
- if event.type == "Track-End":
144
- events[i].value = track_id
145
- track_id += 1
146
- return events
147
-
148
- @staticmethod
149
- def piece_to_inst_events(piece_events):
150
- """Converts piece events of 8 bars to instrument events for entire song
151
-
152
- Args:
153
- piece_events (List[Events]): List of events of Notes, Timeshifts, Bars, Tracks
154
-
155
- Returns:
156
- Dict{inst_id: List[Events]}: List of events for each instrument
157
-
158
- """
159
- inst_events = []
160
- current_track = -1 # so does not start before Track-Start is encountered
161
- for event in piece_events:
162
- # creates a new entry in the dictionnary when "Track-Start" event is encountered
163
- if event.type == "Track-Start":
164
- current_track = event.value
165
- if len(inst_events) == event.value:
166
- inst_events.append({})
167
- inst_events[current_track]["channel"] = current_track
168
- inst_events[current_track]["events"] = []
169
- # append event to the track
170
- if current_track != -1:
171
- inst_events[current_track]["events"].append(event)
172
-
173
- if event.type == "Instrument":
174
- inst_events[current_track]["Instrument"] = event.value
175
- # TODO: needs cleaning Track-start and track end
176
- return inst_events
177
-
178
- @staticmethod
179
- def get_bar_ids(inst_events):
180
- """tracking bar index for each instrument and saving them in the miditok Events"""
181
- for inst_index, inst_event in enumerate(inst_events):
182
- bar_idx = 0
183
- for event_index, event in enumerate(inst_event["events"]):
184
- if event.type == "Bar-Start" or event.type == "Bar-End":
185
- inst_events[inst_index]["events"][event_index].value = bar_idx
186
- if event.type == "Bar-End":
187
- bar_idx += 1
188
- return inst_events
189
-
190
- @staticmethod
191
- def add_missing_timeshifts_in_a_bar(inst_events, beat_per_bar=4, verbose=False):
192
- """Add missing time shifts in bar to make sure that each bar has 4 beats
193
- takes care of the problem of a missing time shift if notes do not last until the end of the bar
194
- takes care of the problem of empty bars that are only defined by "BAR_START BAR END
195
- """
196
- new_inst_events = []
197
- for index, inst_event in enumerate(inst_events):
198
- new_inst_events.append({})
199
- new_inst_events[index]["Instrument"] = inst_event["Instrument"]
200
- new_inst_events[index]["channel"] = index
201
- new_inst_events[index]["events"] = []
202
-
203
- for event in inst_event["events"]:
204
- if event.type == "Bar-Start":
205
- beat_count = 0
206
-
207
- if event.type == "Time-Shift":
208
- beat_count += int_dec_base_to_beat(event.value)
209
-
210
- if event.type == "Bar-End" and beat_count < beat_per_bar:
211
- time_shift_to_add = beat_to_int_dec_base(beat_per_bar - beat_count)
212
- new_inst_events[index]["events"].append(
213
- Event("Time-Shift", time_shift_to_add)
214
- )
215
- beat_count += int_dec_base_to_beat(time_shift_to_add)
216
-
217
- if event.type == "Bar-End" and verbose == True:
218
- print(
219
- f"Instrument {index} - {inst_event['Instrument']} - Bar {event.value} - beat_count = {beat_count}"
220
- )
221
- if event.type == "Bar-End" and beat_count > beat_per_bar:
222
- print(
223
- f"Instrument {index} - {inst_event['Instrument']} - Bar {event.value} - Beat count exceeded "
224
- )
225
- new_inst_events[index]["events"].append(event)
226
-
227
- return new_inst_events
228
-
229
- # TODO
230
- @staticmethod
231
- def check_bar_count_in_section(inst_events, bars_in_sections=8):
232
- new_inst_events = []
233
- for index, inst_event in enumerate(inst_events):
234
- pass
235
- return new_inst_events
236
-
237
- @staticmethod
238
- def remove_unwanted_tokens(events):
239
- for inst_index, inst_event in enumerate(events):
240
- new_inst_event = []
241
- for event in inst_event["events"]:
242
- if not (
243
- event.type == "Bar-Start"
244
- or event.type == "Bar-End"
245
- or event.type == "Track-Start"
246
- or event.type == "Track-End"
247
- or event.type == "Piece-Start"
248
- or event.type == "Instrument"
249
- ):
250
- new_inst_event.append(event)
251
- # replace the events list with the new one
252
- events[inst_index]["events"] = new_inst_event
253
- return events
254
-
255
- @staticmethod
256
- def check_for_duplicated_events(event_list):
257
- for i, event in enumerate(event_list):
258
- if (
259
- i < len(event_list) - 1
260
- and event.type == event_list[i + 1].type
261
- and event.value == event_list[i + 1].value
262
- ):
263
- print(f"Duplicate event found at index {i} : {event}")
264
-
265
- @staticmethod
266
- def add_timeshifts(beat_values1, beat_values2):
267
- """Adds two beat values
268
-
269
- Args:
270
- beat_values1 (String): like 0.3.8
271
- beat_values2 (String): like 1.7.8
272
-
273
- Returns:
274
- beat_str (String): added beats like 2.2.8 for example values
275
- """
276
- value1 = int_dec_base_to_beat(beat_values1)
277
- value2 = int_dec_base_to_beat(beat_values2)
278
- return beat_to_int_dec_base(value1 + value2)
279
-
280
- def aggregate_timeshifts(self, events):
281
- """Aggregates consecutive time shift events bigger than a bar
282
- -> like Timeshift 4.0.8
283
-
284
- Args:
285
- events (_type_): _description_
286
-
287
- Returns:
288
- _type_: _description_
289
- """
290
- for inst_index, inst_event in enumerate(events):
291
- new_inst_event = []
292
- for event in inst_event["events"]:
293
- if (
294
- event.type == "Time-Shift"
295
- and len(new_inst_event) > 0
296
- and new_inst_event[-1].type == "Time-Shift"
297
- ):
298
- new_inst_event[-1].value = self.add_timeshifts(
299
- new_inst_event[-1].value, event.value
300
- )
301
- else:
302
- new_inst_event.append(event)
303
-
304
- events[inst_index]["events"] = new_inst_event
305
- return events
306
-
307
- @staticmethod
308
- def add_velocity(events):
309
- """Adds default velocity 99 to note events since they are removed from text, needed to generate midi"""
310
- for inst_index, inst_event in enumerate(events):
311
- new_inst_event = []
312
- for inst_event in inst_event["events"]:
313
- new_inst_event.append(inst_event)
314
- if inst_event.type == "Note-On":
315
- new_inst_event.append(Event("Velocity", 99))
316
- events[inst_index]["events"] = new_inst_event
317
- return events
318
-
319
- def get_instruments_tuple(self, events):
320
- """Returns instruments tuple for midi generation"""
321
- instruments = []
322
- for track in events:
323
- is_drum = 0
324
- if track["Instrument"].lower() == "drums":
325
- track["Instrument"] = 0
326
- is_drum = 1
327
- if self.familized and not is_drum:
328
- track["Instrument"] = Familizer(arbitrary=True).get_program_number(
329
- int(track["Instrument"])
330
- )
331
- instruments.append((int(track["Instrument"]), is_drum))
332
- return tuple(instruments)
333
-
334
-
335
- if __name__ == "__main__":
336
- # filename = "midi/generated/JammyMachina/elec-gmusic-familized-model-13-12__17-35-53/20230221_235439"
337
- filename = "source/tests/20230305_150554" # investigating the duplicates issues
338
- encoded_json = readFromFile(
339
- f"{filename}.json",
340
- True,
341
- )
342
- encoded_text = encoded_json["generated_midi"]
343
- # encoded_text = "PIECE_START TRACK_START INST=25 DENSITY=2 BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=67 NOTE_ON=64 TIME_DELTA=1 NOTE_OFF=67 NOTE_OFF=64 BAR_END BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 BAR_END BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=67 NOTE_ON=64 TIME_DELTA=1 NOTE_OFF=67 NOTE_OFF=64 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 BAR_END BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=67 NOTE_ON=64 TIME_DELTA=1 NOTE_OFF=67 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 BAR_END BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=69 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=69 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=57 TIME_DELTA=1 NOTE_OFF=57 NOTE_ON=56 TIME_DELTA=1 NOTE_OFF=56 NOTE_ON=64 NOTE_ON=60 NOTE_ON=55 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=55 BAR_END BAR_START NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=66 NOTE_ON=62 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=66 NOTE_OFF=62 NOTE_OFF=50 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=67 NOTE_ON=64 TIME_DELTA=1 NOTE_OFF=67 NOTE_OFF=64 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=50 NOTE_ON=64 NOTE_ON=60 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=64 NOTE_OFF=60 NOTE_OFF=50 NOTE_ON=59 NOTE_ON=55 NOTE_ON=50 TIME_DELTA=1 NOTE_OFF=59 NOTE_OFF=50 NOTE_OFF=55 NOTE_OFF=50 BAR_END BAR_START BAR_END TRACK_END"
344
-
345
- miditok = get_miditok()
346
- TextDecoder(miditok).get_midi(encoded_text, filename=filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
familizer.py DELETED
@@ -1,136 +0,0 @@
1
- import random
2
- from joblib import Parallel, delayed
3
- from pathlib import Path
4
- from constants import INSTRUMENT_CLASSES, INSTRUMENT_TRANSFER_CLASSES
5
- from utils import get_files, timeit, FileCompressor
6
-
7
-
8
- class Familizer:
9
- def __init__(self, n_jobs=-1, arbitrary=False):
10
- self.n_jobs = n_jobs
11
- self.reverse_family(arbitrary)
12
-
13
- def get_family_number(self, program_number):
14
- """
15
- Given a MIDI instrument number, return its associated instrument family number.
16
- """
17
- for instrument_class in INSTRUMENT_CLASSES:
18
- if program_number in instrument_class["program_range"]:
19
- return instrument_class["family_number"]
20
-
21
- def reverse_family(self, arbitrary):
22
- """
23
- Create a dictionary of family numbers to randomly assigned program numbers.
24
- This is used to reverse the family number tokens back to program number tokens.
25
- """
26
-
27
- if arbitrary is True:
28
- int_class = INSTRUMENT_TRANSFER_CLASSES
29
- else:
30
- int_class = INSTRUMENT_CLASSES
31
-
32
- self.reference_programs = {}
33
- for family in int_class:
34
- self.reference_programs[family["family_number"]] = random.choice(
35
- family["program_range"]
36
- )
37
-
38
- def get_program_number(self, family_number):
39
- """
40
- Given given a family number return a random program number in the respective program_range.
41
- This is the reverse operation of get_family_number.
42
- """
43
- assert family_number in self.reference_programs
44
- return self.reference_programs[family_number]
45
-
46
- # Replace instruments in text files
47
- def replace_instrument_token(self, token):
48
- """
49
- Given a MIDI program number in a word token, replace it with the family or program
50
- number token depending on the operation.
51
- e.g. INST=86 -> INST=10
52
- """
53
- inst_number = int(token.split("=")[1])
54
- if self.operation == "family":
55
- return "INST=" + str(self.get_family_number(inst_number))
56
- elif self.operation == "program":
57
- return "INST=" + str(self.get_program_number(inst_number))
58
-
59
- def replace_instrument_in_text(self, text):
60
- """Given a text piece, replace all instrument tokens with family number tokens."""
61
- return " ".join(
62
- [
63
- self.replace_instrument_token(token)
64
- if token.startswith("INST=") and not token == "INST=DRUMS"
65
- else token
66
- for token in text.split(" ")
67
- ]
68
- )
69
-
70
- def replace_instruments_in_file(self, file):
71
- """Given a text file, replace all instrument tokens with family number tokens."""
72
- text = file.read_text()
73
- file.write_text(self.replace_instrument_in_text(text))
74
-
75
- @timeit
76
- def replace_instruments(self):
77
- """
78
- Given a directory of text files:
79
- Replace all instrument tokens with family number tokens.
80
- """
81
- files = get_files(self.output_directory, extension="txt")
82
- Parallel(n_jobs=self.n_jobs)(
83
- delayed(self.replace_instruments_in_file)(file) for file in files
84
- )
85
-
86
- def replace_tokens(self, input_directory, output_directory, operation):
87
- """
88
- Given a directory and an operation, perform the operation on all text files in the directory.
89
- operation can be either 'family' or 'program'.
90
- """
91
- self.input_directory = input_directory
92
- self.output_directory = output_directory
93
- self.operation = operation
94
-
95
- # Uncompress files, replace tokens, compress files
96
- fc = FileCompressor(self.input_directory, self.output_directory, self.n_jobs)
97
- fc.unzip()
98
- self.replace_instruments()
99
- fc.zip()
100
- print(self.operation + " complete.")
101
-
102
- def to_family(self, input_directory, output_directory):
103
- """
104
- Given a directory containing zip files, replace all instrument tokens with
105
- family number tokens. The output is a directory of zip files.
106
- """
107
- self.replace_tokens(input_directory, output_directory, "family")
108
-
109
- def to_program(self, input_directory, output_directory):
110
- """
111
- Given a directory containing zip files, replace all instrument tokens with
112
- program number tokens. The output is a directory of zip files.
113
- """
114
- self.replace_tokens(input_directory, output_directory, "program")
115
-
116
-
117
- if __name__ == "__main__":
118
- # Choose number of jobs for parallel processing
119
- n_jobs = -1
120
-
121
- # Instantiate Familizer
122
- familizer = Familizer(n_jobs)
123
-
124
- # Choose directory to process for program
125
- input_directory = Path("midi/dataset/first_selection/validate").resolve() # fmt: skip
126
- output_directory = input_directory / "family"
127
-
128
- # familize files
129
- familizer.to_family(input_directory, output_directory)
130
-
131
- # Choose directory to process for family
132
- # input_directory = Path("../data/music_picks/encoded_samples/validate/family").resolve() # fmt: skip
133
- # output_directory = input_directory.parent / "program"
134
-
135
- # # programize files
136
- # familizer.to_program(input_directory, output_directory)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
generate.py DELETED
@@ -1,436 +0,0 @@
1
- from generation_utils import *
2
- import random
3
-
4
-
5
- class GenerateMidiText:
6
- """Generating music with Class
7
-
8
- LOGIC:
9
-
10
- FOR GENERATING FROM SCRATCH:
11
- - self.generate_one_new_track()
12
- it calls
13
- - self.generate_until_track_end()
14
-
15
- FOR GENERATING NEW BARS:
16
- - self.generate_one_more_bar()
17
- it calls
18
- - self.process_prompt_for_next_bar()
19
- - self.generate_until_track_end()"""
20
-
21
- def __init__(self, model, tokenizer, piece_by_track=[]):
22
- self.model = model
23
- self.tokenizer = tokenizer
24
- # default initialization
25
- self.initialize_default_parameters()
26
- self.initialize_dictionaries(piece_by_track)
27
-
28
- """Setters"""
29
-
30
- def initialize_default_parameters(self):
31
- self.set_device()
32
- self.set_attention_length()
33
- self.generate_until = "TRACK_END"
34
- self.set_force_sequence_lenth()
35
- self.set_nb_bars_generated()
36
- self.set_improvisation_level(0)
37
-
38
- def initialize_dictionaries(self, piece_by_track):
39
- self.piece_by_track = piece_by_track
40
-
41
- def set_device(self, device="cpu"):
42
- self.device = ("cpu",)
43
-
44
- def set_attention_length(self):
45
- self.max_length = self.model.config.n_positions
46
- print(
47
- f"Attention length set to {self.max_length} -> 'model.config.n_positions'"
48
- )
49
-
50
- def set_force_sequence_lenth(self, force_sequence_length=True):
51
- self.force_sequence_length = force_sequence_length
52
-
53
- def set_improvisation_level(self, improvisation_value):
54
- self.no_repeat_ngram_size = improvisation_value
55
- print("--------------------")
56
- print(f"no_repeat_ngram_size set to {improvisation_value}")
57
- print("--------------------")
58
-
59
- def reset_temperatures(self, track_id, temperature):
60
- self.piece_by_track[track_id]["temperature"] = temperature
61
-
62
- def set_nb_bars_generated(self, n_bars=8): # default is a 8 bar model
63
- self.model_n_bar = n_bars
64
-
65
- """ Generation Tools - Dictionnaries """
66
-
67
- def initiate_track_dict(self, instr, density, temperature):
68
- label = len(self.piece_by_track)
69
- self.piece_by_track.append(
70
- {
71
- "label": f"track_{label}",
72
- "instrument": instr,
73
- "density": density,
74
- "temperature": temperature,
75
- "bars": [],
76
- }
77
- )
78
-
79
- def update_track_dict__add_bars(self, bars, track_id):
80
- """Add bars to the track dictionnary"""
81
- for bar in self.striping_track_ends(bars).split("BAR_START "):
82
- if bar == "": # happens is there is one bar only
83
- continue
84
- else:
85
- if "TRACK_START" in bar:
86
- self.piece_by_track[track_id]["bars"].append(bar)
87
- else:
88
- self.piece_by_track[track_id]["bars"].append("BAR_START " + bar)
89
-
90
- def get_all_instr_bars(self, track_id):
91
- return self.piece_by_track[track_id]["bars"]
92
-
93
- def striping_track_ends(self, text):
94
- if "TRACK_END" in text:
95
- # first get rid of extra space if any
96
- # then gets rid of "TRACK_END"
97
- text = text.rstrip(" ").rstrip("TRACK_END")
98
- return text
99
-
100
- def get_last_generated_track(self, piece):
101
- """Get the last track from a piece written as a single long string"""
102
- track = self.get_tracks_from_a_piece(piece)[-1]
103
- return track
104
-
105
- def get_tracks_from_a_piece(self, piece):
106
- """Get all the tracks from a piece written as a single long string"""
107
- all_tracks = [
108
- "TRACK_START " + the_track + "TRACK_END "
109
- for the_track in self.striping_track_ends(piece.split("TRACK_START ")[1::])
110
- ]
111
- return all_tracks
112
-
113
- def get_piece_from_track_list(self, track_list):
114
- piece = "PIECE_START "
115
- for track in track_list:
116
- piece += track
117
- return piece
118
-
119
- def get_whole_track_from_bar_dict(self, track_id):
120
- text = ""
121
- for bar in self.piece_by_track[track_id]["bars"]:
122
- text += bar
123
- text += "TRACK_END "
124
- return text
125
-
126
- @staticmethod
127
- def get_newly_generated_text(input_prompt, full_piece):
128
- return full_piece[len(input_prompt) :]
129
-
130
- def get_whole_piece_from_bar_dict(self):
131
- text = "PIECE_START "
132
- for track_id, _ in enumerate(self.piece_by_track):
133
- text += self.get_whole_track_from_bar_dict(track_id)
134
- return text
135
-
136
- def delete_one_track(self, track):
137
- self.piece_by_track.pop(track)
138
-
139
- """Basic generation tools"""
140
-
141
- def tokenize_input_prompt(self, input_prompt, verbose=True):
142
- """Tokenizing prompt
143
-
144
- Args:
145
- - input_prompt (str): prompt to tokenize
146
-
147
- Returns:
148
- - input_prompt_ids (torch.tensor): tokenized prompt
149
- """
150
- if verbose:
151
- print("Tokenizing input_prompt...")
152
-
153
- return self.tokenizer.encode(input_prompt, return_tensors="pt")
154
-
155
- def generate_sequence_of_token_ids(
156
- self,
157
- input_prompt_ids,
158
- temperature,
159
- verbose=True,
160
- ):
161
- """
162
- generate a sequence of token ids based on input_prompt_ids
163
- The sequence length depends on the trained model (self.model_n_bar)
164
- """
165
- generated_ids = self.model.generate(
166
- input_prompt_ids,
167
- max_length=self.max_length,
168
- do_sample=True,
169
- temperature=temperature,
170
- no_repeat_ngram_size=self.no_repeat_ngram_size, # default = 0
171
- eos_token_id=self.tokenizer.encode(self.generate_until)[0], # good
172
- )
173
-
174
- if verbose:
175
- print("Generating a token_id sequence...")
176
-
177
- return generated_ids
178
-
179
- def convert_ids_to_text(self, generated_ids, verbose=True):
180
- """converts the token_ids to text"""
181
- generated_text = self.tokenizer.decode(generated_ids[0])
182
- if verbose:
183
- print("Converting token sequence to MidiText...")
184
- return generated_text
185
-
186
- def generate_until_track_end(
187
- self,
188
- input_prompt="PIECE_START ",
189
- instrument=None,
190
- density=None,
191
- temperature=None,
192
- verbose=True,
193
- expected_length=None,
194
- ):
195
- """generate until the TRACK_END token is reached
196
- full_piece = input_prompt + generated"""
197
- if expected_length is None:
198
- expected_length = self.model_n_bar
199
-
200
- if instrument is not None:
201
- input_prompt = f"{input_prompt}TRACK_START INST={str(instrument)} "
202
- if density is not None:
203
- input_prompt = f"{input_prompt}DENSITY={str(density)} "
204
-
205
- if instrument is None and density is not None:
206
- print("Density cannot be defined without an input_prompt instrument #TOFIX")
207
-
208
- if temperature is None:
209
- ValueError("Temperature must be defined")
210
-
211
- if verbose:
212
- print("--------------------")
213
- print(
214
- f"Generating {instrument} - Density {density} - temperature {temperature}"
215
- )
216
- bar_count_checks = False
217
- failed = 0
218
- while not bar_count_checks: # regenerate until right length
219
- input_prompt_ids = self.tokenize_input_prompt(input_prompt, verbose=verbose)
220
- generated_tokens = self.generate_sequence_of_token_ids(
221
- input_prompt_ids, temperature, verbose=verbose
222
- )
223
- full_piece = self.convert_ids_to_text(generated_tokens, verbose=verbose)
224
- generated = self.get_newly_generated_text(input_prompt, full_piece)
225
- # bar_count_checks
226
- bar_count_checks, bar_count = bar_count_check(generated, expected_length)
227
-
228
- if not self.force_sequence_length:
229
- # set bar_count_checks to true to exist the while loop
230
- bar_count_checks = True
231
-
232
- if not bar_count_checks and self.force_sequence_length:
233
- # if the generated sequence is not the expected length
234
- if failed > -1: # deactivated for speed
235
- full_piece, bar_count_checks = forcing_bar_count(
236
- input_prompt,
237
- generated,
238
- bar_count,
239
- expected_length,
240
- )
241
- else:
242
- print('"--- Wrong length - Regenerating ---')
243
-
244
- if not bar_count_checks:
245
- failed += 1
246
-
247
- if failed > 2:
248
- bar_count_checks = True # exit the while loop if failed too much
249
-
250
- return full_piece
251
-
252
- def generate_one_new_track(
253
- self,
254
- instrument,
255
- density,
256
- temperature,
257
- input_prompt="PIECE_START ",
258
- ):
259
- self.initiate_track_dict(instrument, density, temperature)
260
- full_piece = self.generate_until_track_end(
261
- input_prompt=input_prompt,
262
- instrument=instrument,
263
- density=density,
264
- temperature=temperature,
265
- )
266
-
267
- track = self.get_last_generated_track(full_piece)
268
- self.update_track_dict__add_bars(track, -1)
269
- full_piece = self.get_whole_piece_from_bar_dict()
270
- return full_piece
271
-
272
- """ Piece generation - Basics """
273
-
274
- def generate_piece(self, instrument_list, density_list, temperature_list):
275
- """generate a sequence with mutiple tracks
276
-
277
- Args:
278
- - inst_list sets the list of instruments and the the order of generation
279
- - density and
280
- - temperature are paired with inst_list
281
-
282
- Each track/intrument is generated based on a prompt which contains the previously generated track/instrument
283
-
284
- Returns:
285
- 'generated_piece' which keeps track of the entire piece
286
- """
287
-
288
- generated_piece = "PIECE_START "
289
- for instrument, density, temperature in zip(
290
- instrument_list, density_list, temperature_list
291
- ):
292
- generated_piece = self.generate_one_new_track(
293
- instrument,
294
- density,
295
- temperature,
296
- input_prompt=generated_piece,
297
- )
298
-
299
- # generated_piece = self.get_whole_piece_from_bar_dict()
300
- self.check_the_piece_for_errors()
301
- return generated_piece
302
-
303
- """ Piece generation - Extra Bars """
304
-
305
- def process_prompt_for_next_bar(self, track_idx, verbose=True):
306
- """Processing the prompt for the model to generate one more bar only.
307
- The prompt containts:
308
- if not the first bar: the previous, already processed, bars of the track
309
- the bar initialization (ex: "TRACK_START INST=DRUMS DENSITY=2 ")
310
- the last (self.model_n_bar)-1 bars of the track
311
- Args:
312
- track_idx (int): the index of the track to be processed
313
-
314
- Returns:
315
- the processed prompt for generating the next bar
316
- """
317
- track = self.piece_by_track[track_idx]
318
- # for bars which are not the bar to prolong
319
- pre_promt = "PIECE_START "
320
- for i, othertrack in enumerate(self.piece_by_track):
321
- if i != track_idx:
322
- len_diff = len(othertrack["bars"]) - len(track["bars"])
323
- if len_diff > 0:
324
- if verbose:
325
- print(
326
- f"Adding bars - {len(track['bars'][-self.model_n_bar :])} selected from SIDE track: {i} for prompt"
327
- )
328
- # if other bars are longer, it mean that this one should catch up
329
- pre_promt += othertrack["bars"][0]
330
- for bar in track["bars"][-self.model_n_bar :]:
331
- pre_promt += bar
332
- pre_promt += "TRACK_END "
333
- elif (
334
- False
335
- ): # len_diff <= 0: # THIS DOES NOT WORK - It just adds empty bars
336
- # adding an empty bars at the end of the other tracks if they have not been processed yet
337
- pre_promt += othertracks["bars"][0]
338
- for bar in track["bars"][-(self.model_n_bar - 1) :]:
339
- pre_promt += bar
340
- for _ in range(abs(len_diff) + 1):
341
- pre_promt += "BAR_START BAR_END "
342
- pre_promt += "TRACK_END "
343
-
344
- # for the bar to prolong
345
- # initialization e.g TRACK_START INST=DRUMS DENSITY=2
346
- processed_prompt = track["bars"][0]
347
- if verbose:
348
- print(
349
- f"Adding bars - {len(track['bars'][-(self.model_n_bar - 1) :])} selected from MAIN track: {track_idx} for prompt"
350
- )
351
- for bar in track["bars"][-(self.model_n_bar - 1) :]:
352
- # adding the "last" bars of the track
353
- processed_prompt += bar
354
-
355
- processed_prompt += "BAR_START "
356
-
357
- # making the preprompt short enought to avoid bug due to length of the prompt (model limitation)
358
- pre_promt = self.force_prompt_length(pre_promt, 1500)
359
-
360
- print(
361
- f"--- prompt length = {len((pre_promt + processed_prompt).split(' '))} ---"
362
- )
363
-
364
- return pre_promt + processed_prompt
365
-
366
- def force_prompt_length(self, prompt, expected_length):
367
- """remove one instrument/track from the prompt it too long
368
- Args:
369
- prompt (str): the prompt to be processed
370
- expected_length (int): the expected length of the prompt
371
- Returns:
372
- the truncated prompt"""
373
- if len(prompt.split(" ")) < expected_length:
374
- truncated_prompt = prompt
375
- else:
376
- tracks = self.get_tracks_from_a_piece(prompt)
377
- selected_tracks = random.sample(tracks, len(tracks) - 1)
378
- truncated_prompt = self.get_piece_from_track_list(selected_tracks)
379
- print(f"Prompt too long - deleting one track")
380
-
381
- return truncated_prompt
382
-
383
- def generate_one_more_bar(self, track_index):
384
- """Generate one more bar from the input_prompt"""
385
- processed_prompt = self.process_prompt_for_next_bar(track_index)
386
-
387
- prompt_plus_bar = self.generate_until_track_end(
388
- input_prompt=processed_prompt,
389
- temperature=self.piece_by_track[track_index]["temperature"],
390
- expected_length=1,
391
- verbose=False,
392
- )
393
- added_bar = self.get_newly_generated_bar(prompt_plus_bar)
394
- self.update_track_dict__add_bars(added_bar, track_index)
395
-
396
- def get_newly_generated_bar(self, prompt_plus_bar):
397
- return "BAR_START " + self.striping_track_ends(
398
- prompt_plus_bar.split("BAR_START ")[-1]
399
- )
400
-
401
- def generate_n_more_bars(self, n_bars, only_this_track=None, verbose=True):
402
- """Generate n more bars from the input_prompt"""
403
- if only_this_track is None:
404
- only_this_track
405
-
406
- print(f"================== ")
407
- print(f"Adding {n_bars} more bars to the piece ")
408
- for bar_id in range(n_bars):
409
- print(f"----- added bar #{bar_id+1} --")
410
- for i, track in enumerate(self.piece_by_track):
411
- if only_this_track is None or i == only_this_track:
412
- print(f"--------- {track['label']}")
413
- self.generate_one_more_bar(i)
414
- self.check_the_piece_for_errors()
415
-
416
- def check_the_piece_for_errors(self, piece: str = None):
417
- if piece is None:
418
- piece = self.get_whole_piece_from_bar_dict()
419
- errors = []
420
- errors.append(
421
- [
422
- (token, id)
423
- for id, token in enumerate(piece.split(" "))
424
- if token not in self.tokenizer.vocab or token == "UNK"
425
- ]
426
- )
427
- if len(errors) > 0:
428
- # print(piece)
429
- for er in errors:
430
- er
431
- print(f"Token not found in the piece at {er[0][1]}: {er[0][0]}")
432
- print(piece.split(" ")[er[0][1] - 5 : er[0][1] + 5])
433
-
434
-
435
- if __name__ == "__main__":
436
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
generation_utils.py DELETED
@@ -1,191 +0,0 @@
1
- import os
2
- import numpy as np
3
- import matplotlib.pyplot as plt
4
- import matplotlib
5
- from utils import writeToFile, get_datetime
6
-
7
- from constants import INSTRUMENT_CLASSES
8
- from playback import get_music, show_piano_roll
9
-
10
- # matplotlib settings
11
- matplotlib.use("Agg") # for server
12
- matplotlib.rcParams["xtick.major.size"] = 0
13
- matplotlib.rcParams["ytick.major.size"] = 0
14
- matplotlib.rcParams["axes.facecolor"] = "none"
15
- matplotlib.rcParams["axes.edgecolor"] = "grey"
16
-
17
-
18
- class WriteTextMidiToFile: # utils saving miditext from teh class GenerateMidiText to file
19
- def __init__(self, generate_midi, output_path):
20
- self.generated_midi = generate_midi.generated_piece
21
- self.output_path = output_path
22
- self.hyperparameter_and_bars = generate_midi.piece_by_track
23
-
24
- def hashing_seq(self):
25
- self.current_time = get_datetime()
26
- self.output_path_filename = f"{self.output_path}/{self.current_time}.json"
27
-
28
- def wrapping_seq_hyperparameters_in_dict(self):
29
- # assert type(self.generated_midi) is str, "error: generate_midi must be a string"
30
- # assert (
31
- # type(self.hyperparameter_dict) is dict
32
- # ), "error: feature_dict must be a dictionnary"
33
- return {
34
- "generated_midi": self.generated_midi,
35
- "hyperparameters_and_bars": self.hyperparameter_and_bars,
36
- }
37
-
38
- def text_midi_to_file(self):
39
- self.hashing_seq()
40
- output_dict = self.wrapping_seq_hyperparameters_in_dict()
41
- print(f"Token generate_midi written: {self.output_path_filename}")
42
- writeToFile(self.output_path_filename, output_dict)
43
- return self.output_path_filename
44
-
45
-
46
- def define_generation_dir(generation_dir):
47
- if not os.path.exists(generation_dir):
48
- os.makedirs(generation_dir)
49
- return generation_dir
50
-
51
-
52
- def bar_count_check(sequence, n_bars):
53
- """check if the sequence contains the right number of bars"""
54
- sequence = sequence.split(" ")
55
- # find occurences of "BAR_END" in a "sequence"
56
- # I don't check for "BAR_START" because it is not always included in "sequence"
57
- # e.g. BAR_START is included the prompt when generating one more bar
58
- bar_count = 0
59
- for seq in sequence:
60
- if seq == "BAR_END":
61
- bar_count += 1
62
- bar_count_matches = bar_count == n_bars
63
- if not bar_count_matches:
64
- print(f"Bar count is {bar_count} - but should be {n_bars}")
65
- return bar_count_matches, bar_count
66
-
67
-
68
- def print_inst_classes(INSTRUMENT_CLASSES):
69
- """Print the instrument classes"""
70
- for classe in INSTRUMENT_CLASSES:
71
- print(f"{classe}")
72
-
73
-
74
- def check_if_prompt_inst_in_tokenizer_vocab(tokenizer, inst_prompt_list):
75
- """Check if the prompt instrument are in the tokenizer vocab"""
76
- for inst in inst_prompt_list:
77
- if f"INST={inst}" not in tokenizer.vocab:
78
- instruments_in_dataset = np.sort(
79
- [tok.split("=")[-1] for tok in tokenizer.vocab if "INST" in tok]
80
- )
81
- print_inst_classes(INSTRUMENT_CLASSES)
82
- raise ValueError(
83
- f"""The instrument {inst} is not in the tokenizer vocabulary.
84
- Available Instruments: {instruments_in_dataset}"""
85
- )
86
-
87
-
88
- # TODO
89
- def check_if_prompt_density_in_tokenizer_vocab(tokenizer, density_prompt_list):
90
- pass
91
-
92
-
93
- def forcing_bar_count(input_prompt, generated, bar_count, expected_length):
94
- """Forcing the generated sequence to have the expected length
95
- expected_length and bar_count refers to the length of newly_generated_only (without input prompt)
96
- """
97
-
98
- if bar_count - expected_length > 0: # Cut the sequence if too long
99
- full_piece = ""
100
- splited = generated.split("BAR_END ")
101
- for count, spl in enumerate(splited):
102
- if count < expected_length:
103
- full_piece += spl + "BAR_END "
104
-
105
- full_piece += "TRACK_END "
106
- full_piece = input_prompt + full_piece
107
- print(f"Generated sequence trunkated at {expected_length} bars")
108
- bar_count_checks = True
109
-
110
- elif bar_count - expected_length < 0: # Do nothing it the sequence if too short
111
- full_piece = input_prompt + generated
112
- bar_count_checks = False
113
- print(f"--- Generated sequence is too short - Force Regeration ---")
114
-
115
- return full_piece, bar_count_checks
116
-
117
-
118
- def get_max_time(inst_midi):
119
- max_time = 0
120
- for inst in inst_midi.instruments:
121
- max_time = max(max_time, inst.get_end_time())
122
- return max_time
123
-
124
-
125
- def plot_piano_roll(inst_midi):
126
- piano_roll_fig = plt.figure(figsize=(25, 3 * len(inst_midi.instruments)))
127
- piano_roll_fig.tight_layout()
128
- piano_roll_fig.patch.set_alpha(0)
129
- inst_count = 0
130
- beats_per_bar = 4
131
- sec_per_beat = 0.5
132
- next_beat = max(inst_midi.get_beats()) + np.diff(inst_midi.get_beats())[0]
133
- bars_time = np.append(inst_midi.get_beats(), (next_beat))[::beats_per_bar].astype(
134
- int
135
- )
136
- for inst in inst_midi.instruments:
137
- # hardcoded for now
138
- if inst.name == "Drums":
139
- color = "purple"
140
- elif inst.name == "Synth Bass 1":
141
- color = "orange"
142
- else:
143
- color = "green"
144
-
145
- inst_count += 1
146
- plt.subplot(len(inst_midi.instruments), 1, inst_count)
147
-
148
- for bar in bars_time:
149
- plt.axvline(bar, color="grey", linewidth=0.5)
150
- octaves = np.arange(0, 128, 12)
151
- for octave in octaves:
152
- plt.axhline(octave, color="grey", linewidth=0.5)
153
- plt.yticks(octaves, visible=False)
154
-
155
- p_midi_note_list = inst.notes
156
- note_time = []
157
- note_pitch = []
158
- for note in p_midi_note_list:
159
- note_time.append([note.start, note.end])
160
- note_pitch.append([note.pitch, note.pitch])
161
- note_pitch = np.array(note_pitch)
162
- note_time = np.array(note_time)
163
-
164
- plt.plot(
165
- note_time.T,
166
- note_pitch.T,
167
- color=color,
168
- linewidth=4,
169
- solid_capstyle="butt",
170
- )
171
- plt.ylim(0, 128)
172
- xticks = np.array(bars_time)[:-1]
173
- plt.tight_layout()
174
- plt.xlim(min(bars_time), max(bars_time))
175
- plt.ylim(max([note_pitch.min() - 5, 0]), note_pitch.max() + 5)
176
- plt.xticks(
177
- xticks + 0.5 * beats_per_bar * sec_per_beat,
178
- labels=xticks.argsort() + 1,
179
- visible=False,
180
- )
181
- plt.text(
182
- 0.2,
183
- note_pitch.max() + 4,
184
- inst.name,
185
- fontsize=20,
186
- color=color,
187
- horizontalalignment="left",
188
- verticalalignment="top",
189
- )
190
-
191
- return piano_roll_fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
licence.md DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Halid Bayram, Louis Demetz, Jean Simonnet
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
load.py DELETED
@@ -1,63 +0,0 @@
1
- from transformers import GPT2LMHeadModel
2
- from transformers import PreTrainedTokenizerFast
3
- import os
4
- import torch
5
-
6
-
7
- class LoadModel:
8
- """
9
- Example usage:
10
-
11
- # if loading model and tokenizer from Huggingface
12
- model_repo = "misnaej/the-jam-machine"
13
- model, tokenizer = LoadModel(
14
- model_repo, from_huggingface=True
15
- ).load_model_and_tokenizer()
16
-
17
- # if loading model and tokenizer from a local folder
18
- model_path = "models/model_2048_wholedataset"
19
- model, tokenizer = LoadModel(
20
- model_path, from_huggingface=False
21
- ).load_model_and_tokenizer()
22
-
23
- """
24
-
25
- def __init__(self, path, from_huggingface=True, device="cpu", revision=None):
26
- # path is either a relative path on a local/remote machine or a model repo on HuggingFace
27
- if not from_huggingface:
28
- if not os.path.exists(path):
29
- print(path)
30
- raise Exception("Model path does not exist")
31
- self.from_huggingface = from_huggingface
32
- self.path = path
33
- self.device = device
34
- self.revision = revision
35
- if torch.cuda.is_available():
36
- self.device = "cuda"
37
-
38
- def load_model_and_tokenizer(self):
39
- model = self.load_model()
40
- tokenizer = self.load_tokenizer()
41
-
42
- return model, tokenizer
43
-
44
- def load_model(self):
45
- if self.revision is None:
46
- model = GPT2LMHeadModel.from_pretrained(self.path) # .to(self.device)
47
- else:
48
- model = GPT2LMHeadModel.from_pretrained(
49
- self.path, revision=self.revision
50
- ) # .to(self.device)
51
-
52
- return model
53
-
54
- def load_tokenizer(self):
55
- if self.from_huggingface:
56
- pass
57
- else:
58
- if not os.path.exists(f"{self.path}/tokenizer.json"):
59
- raise Exception(
60
- f"There is no 'tokenizer.json'file in the defined {self.path}"
61
- )
62
- tokenizer = PreTrainedTokenizerFast.from_pretrained(self.path)
63
- return tokenizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages.txt CHANGED
@@ -1 +1 @@
1
- fluidsynth
 
1
+ fluidsynth
playback.py DELETED
@@ -1,36 +0,0 @@
1
- import matplotlib.pyplot as plt
2
- import librosa.display
3
- from pretty_midi import PrettyMIDI
4
-
5
-
6
- # Note: these functions are meant to be played within an interactive Python shell
7
- # Please refer to the synth.ipynb for an example of how to use them
8
-
9
-
10
- def get_music(midi_file):
11
- """
12
- Load a midi file and return the PrettyMIDI object and the audio signal
13
- """
14
- print(f"Getting MIDI music from: {midi_file}")
15
- music = PrettyMIDI(midi_file=midi_file)
16
- waveform = music.fluidsynth()
17
- return music, waveform
18
-
19
-
20
- def show_piano_roll(music_notes, fs=100):
21
- """
22
- Show the piano roll of a music piece, with all instruments squashed onto a single 128xN matrix
23
- :param music_notes: PrettyMIDI object
24
- :param fs: sampling frequency
25
- """
26
- # get the piano roll
27
- piano_roll = music_notes.get_piano_roll(fs)
28
- print("Piano roll shape: {}".format(piano_roll.shape))
29
-
30
- # plot the piano roll
31
- plt.figure(figsize=(12, 4))
32
- librosa.display.specshow(piano_roll, sr=100, x_axis="time", y_axis="cqt_note")
33
- plt.colorbar()
34
- plt.title("Piano roll")
35
- plt.tight_layout()
36
- plt.show()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
playground.py DELETED
@@ -1,207 +0,0 @@
1
- import gradio as gr
2
- from load import LoadModel
3
- from generate import GenerateMidiText
4
- from constants import INSTRUMENT_TRANSFER_CLASSES
5
- from decoder import TextDecoder
6
- from utils import get_miditok
7
- from playback import get_music
8
- from matplotlib import pylab
9
- import sys
10
- import os
11
- import matplotlib
12
- from generation_utils import plot_piano_roll
13
-
14
- matplotlib.use("Agg")
15
-
16
- sys.modules["pylab"] = pylab
17
-
18
- model_repo = "JammyMachina/elec-gmusic-familized-model-13-12__17-35-53"
19
- n_bar_generated = 8
20
-
21
- model, tokenizer = LoadModel(
22
- model_repo,
23
- from_huggingface=True,
24
- ).load_model_and_tokenizer()
25
-
26
- miditok = get_miditok()
27
- decoder = TextDecoder(miditok)
28
-
29
-
30
- def define_prompt(state, genesis):
31
- if len(state) == 0:
32
- input_prompt = "PIECE_START "
33
- else:
34
- input_prompt = genesis.get_whole_piece_from_bar_dict()
35
- return input_prompt
36
-
37
-
38
- def generator(
39
- label,
40
- regenerate,
41
- temp,
42
- density,
43
- instrument,
44
- state,
45
- piece_by_track,
46
- add_bars=False,
47
- add_bar_count=1,
48
- ):
49
- genesis = GenerateMidiText(model, tokenizer, piece_by_track)
50
- track = {
51
- "label": label,
52
- "instrument": instrument,
53
- "temperature": temp,
54
- "density": density,
55
- }
56
- inst = next(
57
- (
58
- inst
59
- for inst in INSTRUMENT_TRANSFER_CLASSES
60
- if inst["transfer_to"] == instrument
61
- ),
62
- {"family_number": "DRUMS"},
63
- )["family_number"]
64
-
65
- inst_index = -1 # default to last generated
66
- if piece_by_track != []:
67
- for index, instrum in enumerate(state):
68
- if instrum["label"] == track["label"]:
69
- inst_index = index # changing if exists
70
-
71
- # Generate
72
- if not add_bars:
73
- # Regenerate
74
- if regenerate:
75
- state.pop(inst_index)
76
- genesis.delete_one_track(inst_index)
77
-
78
- generated_text = (
79
- genesis.get_whole_piece_from_bar_dict()
80
- ) # maybe not useful here
81
- inst_index = -1 # reset to last generated
82
-
83
- # NEW TRACK
84
- input_prompt = define_prompt(state, genesis)
85
- generated_text = genesis.generate_one_new_track(
86
- inst, density, temp, input_prompt=input_prompt
87
- )
88
-
89
- regenerate = True # set generate to true
90
- else:
91
- # NEW BARS
92
- genesis.generate_n_more_bars(add_bar_count) # for all instruments
93
- generated_text = genesis.get_whole_piece_from_bar_dict()
94
-
95
- # save the mix midi and get the mix audio
96
- decoder.get_midi(generated_text, "mixed.mid")
97
- mixed_inst_midi, mixed_audio = get_music("mixed.mid")
98
- # get the instrument text MIDI
99
- inst_text = genesis.get_whole_track_from_bar_dict(inst_index)
100
- # save the instrument midi and get the instrument audio
101
- decoder.get_midi(inst_text, f"{instrument}.mid")
102
- _, inst_audio = get_music(f"{instrument}.mid")
103
- # generate the piano roll
104
- piano_roll = plot_piano_roll(mixed_inst_midi)
105
- track["text"] = inst_text
106
- state.append(track)
107
- output_file = "./mixed.mid"
108
- return (
109
- inst_text,
110
- (44100, inst_audio),
111
- piano_roll,
112
- state,
113
- (44100, mixed_audio),
114
- regenerate,
115
- genesis.piece_by_track,
116
- output_file,
117
- )
118
-
119
-
120
- def generated_text_from_state(state):
121
- generated_text_from_state = "PIECE_START "
122
- for track in state:
123
- generated_text_from_state += track["text"]
124
- return generated_text_from_state
125
-
126
-
127
- def instrument_col(default_inst, col_id):
128
- inst_label = gr.State(col_id)
129
- with gr.Column(scale=1, min_width=100):
130
- track_md = gr.Markdown(f"""## TRACK {col_id+1}""")
131
- inst = gr.Dropdown(
132
- sorted([inst["transfer_to"] for inst in INSTRUMENT_TRANSFER_CLASSES])
133
- + ["Drums"],
134
- value=default_inst,
135
- label="Instrument",
136
- )
137
- temp = gr.Dropdown(
138
- [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
139
- value=0.7,
140
- label="Creativity",
141
- )
142
- density = gr.Dropdown([1, 2, 3], value=3, label="Note Density")
143
- regenerate = gr.State(
144
- value=False
145
- ) # initial state should be to generate (not regenerate)
146
- gen_btn = gr.Button("Generate")
147
- inst_audio = gr.Audio(label="TRACK Audio", show_label=True)
148
- output_txt = gr.Textbox(
149
- label="output", lines=10, max_lines=10, show_label=False, visible=False
150
- )
151
-
152
- gen_btn.click(
153
- fn=generator,
154
- inputs=[inst_label, regenerate, temp, density, inst, state, piece_by_track],
155
- outputs=[
156
- output_txt,
157
- inst_audio,
158
- piano_roll,
159
- state,
160
- mixed_audio,
161
- regenerate,
162
- piece_by_track,
163
- output_file,
164
- ],
165
- )
166
-
167
-
168
- with gr.Blocks() as demo:
169
- piece_by_track = gr.State([])
170
- state = gr.State([])
171
- title = gr.Markdown(
172
- """ # Demo-App of The-Jam-Machine
173
- ## A Generative AI trained on text transcription of MIDI music """
174
- )
175
-
176
- description = gr.Markdown(
177
- """
178
- For each **TRACK**, choose your **instrument** along with **creativity** (temperature) and **note density**.
179
- Then, hit the **Generate** Button, and after a few seconds a track should have been generated.
180
- Check the **piano roll** and listen to the TRACK! If you don't like it, hit the generate button to regenerate it.
181
- You can then generate more tracks and listen to the **mixed audio**! \n
182
- Does it sound nice? Maybe a little robotic and laking some depth... Well, you can download the MIDI file and import it in your favorite DAW to edit the instruments and add some effects!
183
- Note: Do not try to generate several tracks simultaneously as it will crash the app; wait for one track to be generated before generating another one.
184
- """
185
- )
186
-
187
- aud_md = gr.Markdown(f""" ## Mixed Audio, Piano Roll and MIDI Download """)
188
- with gr.Row(variant="default"):
189
- mixed_audio = gr.Audio(label="Mixed Audio", show_label=False)
190
- output_file = gr.File(
191
- label="Download",
192
- show_label=False,
193
- )
194
- with gr.Row(variant="compact"):
195
- piano_roll = gr.Plot(label="Piano Roll", show_label=False)
196
-
197
- with gr.Row(variant="default"):
198
- instrument_col("Drums", 0)
199
- instrument_col("Synth Bass 1", 1)
200
- instrument_col("Synth Lead Square", 2)
201
-
202
- demo.launch(debug=True, server_name="0.0.0.0", share=False)
203
- """
204
- TODO: add improvise button
205
- TODO: cleanup input output of generator
206
- TODO: add a way to add bars
207
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,17 +1 @@
1
- gradio
2
- matplotlib
3
- numpy
4
- joblib
5
- pathlib
6
- transformers
7
- miditok == 1.3.2
8
- librosa
9
- pretty_midi
10
- pydub
11
- scipy
12
- datetime
13
- torch
14
- torchvision
15
- pyFluidSynth
16
- accelerate
17
- httpx==0.24.1
 
1
+ the-jam-machine @ git+https://github.com/misnaej/the-jam-machine.git@main
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils.py DELETED
@@ -1,300 +0,0 @@
1
- from datetime import datetime
2
- from miditok import Event, MIDILike
3
- import os
4
- import json
5
- from time import perf_counter
6
- from constants import DRUMS_BEAT_QUANTIZATION, NONE_DRUMS_BEAT_QUANTIZATION
7
- from joblib import Parallel, delayed
8
- from zipfile import ZipFile, ZIP_DEFLATED
9
- from scipy.io.wavfile import write
10
- import numpy as np
11
- from pydub import AudioSegment
12
- import shutil
13
-
14
- """ Diverse utils"""
15
-
16
-
17
- def index_has_substring(list, substring):
18
- for i, s in enumerate(list):
19
- if substring in s:
20
- return i
21
- return -1
22
-
23
-
24
- # TODO: Make this singleton
25
- def get_miditok():
26
- pitch_range = range(0, 127) # was (21, 109)
27
- beat_res = {(0, 400): 8}
28
- return MIDILike(pitch_range, beat_res)
29
-
30
-
31
- def timeit(func):
32
- def wrapper(*args, **kwargs):
33
- start = perf_counter()
34
- result = func(*args, **kwargs)
35
- end = perf_counter()
36
- print(f"{func.__name__} took {end - start:.2f} seconds to run.")
37
- return result
38
-
39
- return wrapper
40
-
41
-
42
- def chain(input, funcs, *params):
43
- """Chain functions together, passing the output of one function as the input of the next."""
44
- res = input
45
- for func in funcs:
46
- try:
47
- res = func(res, *params)
48
- except TypeError:
49
- res = func(res)
50
- return res
51
-
52
-
53
- def split_dots(value):
54
- """Splits a string separated by dots "a.b.c" into a list of integers [a, b, c]"""
55
- return list(map(int, value.split(".")))
56
-
57
-
58
- def compute_list_average(l):
59
- return sum(l) / len(l)
60
-
61
-
62
- def get_datetime():
63
- return datetime.now().strftime("%Y%m%d_%H%M%S")
64
-
65
-
66
- """ Encoding functions """
67
-
68
-
69
- def int_dec_base_to_beat(beat_str):
70
- """
71
- Converts "integer.decimal.base" (str, from miditok) into beats
72
- e.g. "0.4.8" = 0 + 4/8 = 0.5
73
- Args:
74
- - beat_str: "integer.decimal.base"
75
- Returns:
76
- - beats: float
77
- """
78
- integer, decimal, base = split_dots(beat_str)
79
- return integer + decimal / base
80
-
81
-
82
- def int_dec_base_to_delta(beat_str, instrument="drums"):
83
- """converts the time shift to time_delta according to Tristan's encoding scheme
84
- Drums TIME_DELTA are quantized according to DRUMS_BEAT_QUANTIZATION
85
- Other Instrument TIME_DELTA are quantized according to NONE_DRUMS_BEAT_QUANTIZATION
86
- """
87
-
88
- beat_res = (
89
- DRUMS_BEAT_QUANTIZATION
90
- if instrument.lower() == "drums"
91
- else NONE_DRUMS_BEAT_QUANTIZATION
92
- )
93
- time_delta = int_dec_base_to_beat(beat_str) * beat_res
94
- return time_delta.__int__()
95
-
96
-
97
- def get_text(event, instrument="drums"):
98
- """Converts an event into a string for the midi-text format"""
99
- match event.type:
100
- case "Piece-Start":
101
- return "PIECE_START "
102
- case "Track-Start":
103
- return "TRACK_START "
104
- case "Track-End":
105
- return "TRACK_END "
106
- case "Instrument":
107
- if str(event.value).lower() == "drums":
108
- return f"INST=DRUMS "
109
- else:
110
- return f"INST={event.value} "
111
- case "Density":
112
- return f"DENSITY={event.value} "
113
- case "Bar-Start":
114
- return "BAR_START "
115
- case "Bar-End":
116
- return "BAR_END "
117
- case "Time-Shift":
118
- return f"TIME_DELTA={int_dec_base_to_delta(event.value, instrument)} "
119
- case "Note-On":
120
- return f"NOTE_ON={event.value} "
121
- case "Note-Off":
122
- return f"NOTE_OFF={event.value} "
123
- case _:
124
- return ""
125
-
126
-
127
- """ Decoding functions """
128
-
129
-
130
- def time_delta_to_beat(time_delta, instrument="drums"):
131
- """
132
- Converts TIME_DELTA (from midi-text) to beats according to Tristan's encoding scheme
133
- Args:
134
- - time_delta: int (TIME_DELTA)
135
- - instrument: str ("Drums" or other instrument): used to determine the quantization resolution defined on constants.py
136
- Returns:
137
- - beats: float
138
- """
139
- beat_res = (
140
- DRUMS_BEAT_QUANTIZATION
141
- if instrument.lower() == "drums"
142
- else NONE_DRUMS_BEAT_QUANTIZATION
143
- )
144
- beats = float(time_delta) / beat_res
145
- return beats
146
-
147
-
148
- def beat_to_int_dec_base(beat, beat_res=8):
149
- """
150
- Converts beats into "integer.decimal.base" (str) for miditok
151
- Args:
152
- - beat_str: "integer.decimal.base"
153
- Returns:
154
- - beats: float (e.g. "0.4.8" = 0 + 4/8 = 0.5)
155
- """
156
- int_dec_base = [
157
- int((beat * beat_res) // beat_res),
158
- int((beat * beat_res) % beat_res),
159
- beat_res,
160
- ]
161
- return ".".join(map(str, int_dec_base))
162
-
163
-
164
- def time_delta_to_int_dec_base(time_delta, instrument="drums"):
165
- return chain(
166
- time_delta,
167
- [
168
- time_delta_to_beat,
169
- beat_to_int_dec_base,
170
- ],
171
- instrument,
172
- )
173
-
174
-
175
- def get_event(text, value=None, instrument="drums"):
176
- """Converts a midi-text like event into a miditok like event"""
177
- match text:
178
- case "PIECE_START":
179
- return Event("Piece-Start", value)
180
- case "TRACK_START":
181
- return Event("Track-Start", value)
182
- case "TRACK_END":
183
- return Event("Track-End", value)
184
- case "INST":
185
- if value == "DRUMS":
186
- value = "Drums"
187
- return Event("Instrument", value)
188
- case "BAR_START":
189
- return Event("Bar-Start", value)
190
- case "BAR_END":
191
- return Event("Bar-End", value)
192
- case "TIME_SHIFT":
193
- return Event("Time-Shift", value)
194
- case "TIME_DELTA":
195
- return Event("Time-Shift", time_delta_to_int_dec_base(value, instrument))
196
- # return Event("Time-Shift", to_beat_str(int(value) / 4))
197
- case "NOTE_ON":
198
- return Event("Note-On", value)
199
- case "NOTE_OFF":
200
- return Event("Note-Off", value)
201
- case _:
202
- return None
203
-
204
-
205
- """ File utils"""
206
-
207
-
208
- def writeToFile(path, content):
209
- if type(content) is dict:
210
- with open(f"{path}", "w") as json_file:
211
- json.dump(content, json_file)
212
- else:
213
- if type(content) is not str:
214
- content = str(content)
215
- os.makedirs(os.path.dirname(path), exist_ok=True)
216
- with open(path, "w") as f:
217
- f.write(content)
218
-
219
-
220
- def readFromFile(path, isJSON=False):
221
- with open(path, "r") as f:
222
- if isJSON:
223
- return json.load(f)
224
- else:
225
- return f.read()
226
-
227
-
228
- def get_files(directory, extension, recursive=False):
229
- """
230
- Given a directory, get a list of the file paths of all files matching the
231
- specified file extension.
232
- directory: the directory to search as a Path object
233
- extension: the file extension to match as a string
234
- recursive: whether to search recursively in the directory or not
235
- """
236
- if recursive:
237
- return list(directory.rglob(f"*.{extension}"))
238
- else:
239
- return list(directory.glob(f"*.{extension}"))
240
-
241
-
242
- def load_jsonl(filepath):
243
- """Load a jsonl file"""
244
- with open(filepath, "r") as f:
245
- data = [json.loads(line) for line in f]
246
- return data
247
-
248
-
249
- def write_mp3(waveform, output_path, bitrate="92k"):
250
- """
251
- Write a waveform to an mp3 file.
252
- output_path: Path object for the output mp3 file
253
- waveform: numpy array of the waveform
254
- bitrate: bitrate of the mp3 file (64k, 92k, 128k, 256k, 312k)
255
- """
256
- # write the wav file
257
- wav_path = output_path.with_suffix(".wav")
258
- write(wav_path, 44100, waveform.astype(np.float32))
259
- # compress the wav file as mp3
260
- AudioSegment.from_wav(wav_path).export(output_path, format="mp3", bitrate=bitrate)
261
- # remove the wav file
262
- wav_path.unlink()
263
-
264
-
265
- def copy_file(input_file, output_dir):
266
- """Copy an input file to the output_dir"""
267
- output_file = output_dir / input_file.name
268
- shutil.copy(input_file, output_file)
269
-
270
-
271
- class FileCompressor:
272
- def __init__(self, input_directory, output_directory, n_jobs=-1):
273
- self.input_directory = input_directory
274
- self.output_directory = output_directory
275
- self.n_jobs = n_jobs
276
-
277
- # File compression and decompression
278
- def unzip_file(self, file):
279
- """uncompress single zip file"""
280
- with ZipFile(file, "r") as zip_ref:
281
- zip_ref.extractall(self.output_directory)
282
-
283
- def zip_file(self, file):
284
- """compress a single text file to a new zip file and delete the original"""
285
- output_file = self.output_directory / (file.stem + ".zip")
286
- with ZipFile(output_file, "w") as zip_ref:
287
- zip_ref.write(file, arcname=file.name, compress_type=ZIP_DEFLATED)
288
- file.unlink()
289
-
290
- @timeit
291
- def unzip(self):
292
- """uncompress all zip files in folder"""
293
- files = get_files(self.input_directory, extension="zip")
294
- Parallel(n_jobs=self.n_jobs)(delayed(self.unzip_file)(file) for file in files)
295
-
296
- @timeit
297
- def zip(self):
298
- """compress all text files in folder to new zip files and remove the text files"""
299
- files = get_files(self.output_directory, extension="txt")
300
- Parallel(n_jobs=self.n_jobs)(delayed(self.zip_file)(file) for file in files)