Next commited on
Commit
fba1e3a
1 Parent(s): 0d229bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +298 -298
app.py CHANGED
@@ -1,298 +1,298 @@
1
- import argparse
2
- import glob
3
- import os.path
4
- import uuid
5
-
6
- import gradio as gr
7
- import numpy as np
8
- import onnxruntime as rt
9
- import tqdm
10
- import json
11
- from huggingface_hub import hf_hub_download
12
-
13
- import MIDI
14
- from midi_synthesizer import synthesis
15
- from midi_tokenizer import MIDITokenizer
16
-
17
- in_space = os.getenv("SYSTEM") == "spaces"
18
-
19
-
20
- def softmax(x, axis):
21
- x_max = np.amax(x, axis=axis, keepdims=True)
22
- exp_x_shifted = np.exp(x - x_max)
23
- return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
24
-
25
-
26
- def sample_top_p_k(probs, p, k):
27
- probs_idx = np.argsort(-probs, axis=-1)
28
- probs_sort = np.take_along_axis(probs, probs_idx, -1)
29
- probs_sum = np.cumsum(probs_sort, axis=-1)
30
- mask = probs_sum - probs_sort > p
31
- probs_sort[mask] = 0.0
32
- mask = np.zeros(probs_sort.shape[-1])
33
- mask[:k] = 1
34
- probs_sort = probs_sort * mask
35
- probs_sort /= np.sum(probs_sort, axis=-1, keepdims=True)
36
- shape = probs_sort.shape
37
- probs_sort_flat = probs_sort.reshape(-1, shape[-1])
38
- probs_idx_flat = probs_idx.reshape(-1, shape[-1])
39
- next_token = np.stack([np.random.choice(idxs, p=pvals) for pvals, idxs in zip(probs_sort_flat, probs_idx_flat)])
40
- next_token = next_token.reshape(*shape[:-1])
41
- return next_token
42
-
43
-
44
- def generate(model, prompt=None, max_len=512, temp=1.0, top_p=0.98, top_k=20,
45
- disable_patch_change=False, disable_control_change=False, disable_channels=None):
46
- if disable_channels is not None:
47
- disable_channels = [tokenizer.parameter_ids["channel"][c] for c in disable_channels]
48
- else:
49
- disable_channels = []
50
- max_token_seq = tokenizer.max_token_seq
51
- if prompt is None:
52
- input_tensor = np.full((1, max_token_seq), tokenizer.pad_id, dtype=np.int64)
53
- input_tensor[0, 0] = tokenizer.bos_id # bos
54
- else:
55
- prompt = prompt[:, :max_token_seq]
56
- if prompt.shape[-1] < max_token_seq:
57
- prompt = np.pad(prompt, ((0, 0), (0, max_token_seq - prompt.shape[-1])),
58
- mode="constant", constant_values=tokenizer.pad_id)
59
- input_tensor = prompt
60
- input_tensor = input_tensor[None, :, :]
61
- cur_len = input_tensor.shape[1]
62
- bar = tqdm.tqdm(desc="generating", total=max_len - cur_len, disable=in_space)
63
- with bar:
64
- while cur_len < max_len:
65
- end = False
66
- hidden = model[0].run(None, {'x': input_tensor})[0][:, -1]
67
- next_token_seq = np.empty((1, 0), dtype=np.int64)
68
- event_name = ""
69
- for i in range(max_token_seq):
70
- mask = np.zeros(tokenizer.vocab_size, dtype=np.int64)
71
- if i == 0:
72
- mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
73
- if disable_patch_change:
74
- mask_ids.remove(tokenizer.event_ids["patch_change"])
75
- if disable_control_change:
76
- mask_ids.remove(tokenizer.event_ids["control_change"])
77
- mask[mask_ids] = 1
78
- else:
79
- param_name = tokenizer.events[event_name][i - 1]
80
- mask_ids = tokenizer.parameter_ids[param_name]
81
- if param_name == "channel":
82
- mask_ids = [i for i in mask_ids if i not in disable_channels]
83
- mask[mask_ids] = 1
84
- logits = model[1].run(None, {'x': next_token_seq, "hidden": hidden})[0][:, -1:]
85
- scores = softmax(logits / temp, -1) * mask
86
- sample = sample_top_p_k(scores, top_p, top_k)
87
- if i == 0:
88
- next_token_seq = sample
89
- eid = sample.item()
90
- if eid == tokenizer.eos_id:
91
- end = True
92
- break
93
- event_name = tokenizer.id_events[eid]
94
- else:
95
- next_token_seq = np.concatenate([next_token_seq, sample], axis=1)
96
- if len(tokenizer.events[event_name]) == i:
97
- break
98
- if next_token_seq.shape[1] < max_token_seq:
99
- next_token_seq = np.pad(next_token_seq, ((0, 0), (0, max_token_seq - next_token_seq.shape[-1])),
100
- mode="constant", constant_values=tokenizer.pad_id)
101
- next_token_seq = next_token_seq[None, :, :]
102
- input_tensor = np.concatenate([input_tensor, next_token_seq], axis=1)
103
- cur_len += 1
104
- bar.update(1)
105
- yield next_token_seq.reshape(-1)
106
- if end:
107
- break
108
-
109
-
110
- def create_msg(name, data):
111
- return {"name": name, "data": data, "uuid": uuid.uuid4().hex}
112
-
113
-
114
- def send_msgs(msgs, msgs_history):
115
- msgs_history.append(msgs)
116
- if len(msgs_history) > 50:
117
- msgs_history.pop(0)
118
- return json.dumps(msgs_history)
119
-
120
-
121
- def run(model_name, tab, instruments, drum_kit, mid, midi_events, gen_events, temp, top_p, top_k, allow_cc):
122
- msgs_history = []
123
- mid_seq = []
124
- gen_events = int(gen_events)
125
- max_len = gen_events
126
-
127
- disable_patch_change = False
128
- disable_channels = None
129
- if tab == 0:
130
- i = 0
131
- mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
132
- patches = {}
133
- if instruments is None:
134
- instruments = []
135
- for instr in instruments:
136
- patches[i] = patch2number[instr]
137
- i = (i + 1) if i != 8 else 10
138
- if drum_kit != "None":
139
- patches[9] = drum_kits2number[drum_kit]
140
- for i, (c, p) in enumerate(patches.items()):
141
- mid.append(tokenizer.event2tokens(["patch_change", 0, 0, i, c, p]))
142
- mid_seq = mid
143
- mid = np.asarray(mid, dtype=np.int64)
144
- if len(instruments) > 0:
145
- disable_patch_change = True
146
- disable_channels = [i for i in range(16) if i not in patches]
147
- elif mid is not None:
148
- mid = tokenizer.tokenize(MIDI.midi2score(mid))
149
- mid = np.asarray(mid, dtype=np.int64)
150
- mid = mid[:int(midi_events)]
151
- max_len += len(mid)
152
- for token_seq in mid:
153
- mid_seq.append(token_seq.tolist())
154
- init_msgs = [create_msg("visualizer_clear", None)]
155
- for tokens in mid_seq:
156
- init_msgs.append(create_msg("visualizer_append", tokenizer.tokens2event(tokens)))
157
- yield mid_seq, None, None, send_msgs(init_msgs, msgs_history), msgs_history
158
- model = models[model_name]
159
- generator = generate(model, mid, max_len=max_len, temp=temp, top_p=top_p, top_k=top_k,
160
- disable_patch_change=disable_patch_change, disable_control_change=not allow_cc,
161
- disable_channels=disable_channels)
162
- for i, token_seq in enumerate(generator):
163
- token_seq = token_seq.tolist()
164
- mid_seq.append(token_seq)
165
- event = tokenizer.tokens2event(token_seq)
166
- yield mid_seq, None, None, send_msgs([create_msg("visualizer_append", event), create_msg("progress", [i + 1, gen_events])], msgs_history), msgs_history
167
- mid = tokenizer.detokenize(mid_seq)
168
- with open(f"output.mid", 'wb') as f:
169
- f.write(MIDI.score2midi(mid))
170
- audio = synthesis(MIDI.score2opus(mid), soundfont_path)
171
- yield mid_seq, "output.mid", (44100, audio), send_msgs([create_msg("visualizer_end", None)], msgs_history), msgs_history
172
-
173
-
174
- def cancel_run(mid_seq, msgs_history):
175
- if mid_seq is None:
176
- return None, None, []
177
- mid = tokenizer.detokenize(mid_seq)
178
- with open(f"output.mid", 'wb') as f:
179
- f.write(MIDI.score2midi(mid))
180
- audio = synthesis(MIDI.score2opus(mid), soundfont_path)
181
- return "output.mid", (44100, audio), send_msgs([create_msg("visualizer_end", None)], msgs_history)
182
-
183
-
184
- def load_javascript(dir="javascript"):
185
- scripts_list = glob.glob(f"{dir}/*.js")
186
- javascript = ""
187
- for path in scripts_list:
188
- with open(path, "r", encoding="utf8") as jsfile:
189
- javascript += f"\n<!-- {path} --><script>{jsfile.read()}</script>"
190
- template_response_ori = gr.routes.templates.TemplateResponse
191
-
192
- def template_response(*args, **kwargs):
193
- res = template_response_ori(*args, **kwargs)
194
- res.body = res.body.replace(
195
- b'</head>', f'{javascript}</head>'.encode("utf8"))
196
- res.init_headers()
197
- return res
198
-
199
- gr.routes.templates.TemplateResponse = template_response
200
-
201
-
202
- number2drum_kits = {-1: "None", 0: "Standard", 8: "Room", 16: "Power", 24: "Electric", 25: "TR-808", 32: "Jazz",
203
- 40: "Blush", 48: "Orchestra"}
204
- patch2number = {v: k for k, v in MIDI.Number2patch.items()}
205
- drum_kits2number = {v: k for k, v in number2drum_kits.items()}
206
-
207
- if __name__ == "__main__":
208
- parser = argparse.ArgumentParser()
209
- parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
210
- parser.add_argument("--port", type=int, default=7860, help="gradio server port")
211
- parser.add_argument("--max-gen", type=int, default=1024, help="max")
212
- opt = parser.parse_args()
213
- soundfont_path = hf_hub_download(repo_id="skytnt/midi-model", filename="soundfont.sf2")
214
- models_info = {"generic pretrain model": ["skytnt/midi-model", ""],
215
- "j-pop finetune model": ["skytnt/midi-model-ft", "jpop/"],
216
- "touhou finetune model": ["skytnt/midi-model-ft", "touhou/"],
217
- }
218
- models = {}
219
- tokenizer = MIDITokenizer()
220
- providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
221
- for name, (repo_id, path) in models_info.items():
222
- model_base_path = hf_hub_download(repo_id=repo_id, filename=f"{path}onnx/model_base.onnx")
223
- model_token_path = hf_hub_download(repo_id=repo_id, filename=f"{path}onnx/model_token.onnx")
224
- model_base = rt.InferenceSession(model_base_path, providers=providers)
225
- model_token = rt.InferenceSession(model_token_path, providers=providers)
226
- models[name] = [model_base, model_token]
227
-
228
- load_javascript()
229
- app = gr.Blocks()
230
- with app:
231
- gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Midi Composer</h1>")
232
- gr.Markdown("![Visitors](https://api.visitorbadge.io/api/visitors?path=skytnt.midi-composer&style=flat)\n\n"
233
- "Midi event transformer for music generation\n\n"
234
- "Demo for [SkyTNT/midi-model](https://github.com/SkyTNT/midi-model)\n\n"
235
- "[Open In Colab]"
236
- "(https://colab.research.google.com/github/SkyTNT/midi-model/blob/main/demo.ipynb)"
237
- " for faster running and longer generation"
238
- )
239
- js_msg_history_state = gr.State(value=[])
240
- js_msg = gr.Textbox(elem_id="msg_receiver", visible=False)
241
- js_msg.change(None, [js_msg], [], js="""
242
- (msg_json) =>{
243
- let msgs = JSON.parse(msg_json);
244
- executeCallbacks(msgReceiveCallbacks, msgs);
245
- return [];
246
- }
247
- """)
248
- input_model = gr.Dropdown(label="select model", choices=list(models.keys()),
249
- type="value", value=list(models.keys())[0])
250
- tab_select = gr.State(value=0)
251
- with gr.Tabs():
252
- with gr.TabItem("instrument prompt") as tab1:
253
- input_instruments = gr.Dropdown(label="instruments (auto if empty)", choices=list(patch2number.keys()),
254
- multiselect=True, max_choices=15, type="value")
255
- input_drum_kit = gr.Dropdown(label="drum kit", choices=list(drum_kits2number.keys()), type="value",
256
- value="None")
257
- example1 = gr.Examples([
258
- [[], "None"],
259
- [["Acoustic Grand"], "None"],
260
- [["Acoustic Grand", "Violin", "Viola", "Cello", "Contrabass"], "Orchestra"],
261
- [["Flute", "Cello", "Bassoon", "Tuba"], "None"],
262
- [["Violin", "Viola", "Cello", "Contrabass", "Trumpet", "French Horn", "Brass Section",
263
- "Flute", "Piccolo", "Tuba", "Trombone", "Timpani"], "Orchestra"],
264
- [["Acoustic Guitar(nylon)", "Acoustic Guitar(steel)", "Electric Guitar(jazz)",
265
- "Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar", "Distortion Guitar",
266
- "Electric Bass(finger)"], "Standard"]
267
- ], [input_instruments, input_drum_kit])
268
- with gr.TabItem("midi prompt") as tab2:
269
- input_midi = gr.File(label="input midi", file_types=[".midi", ".mid"], type="binary")
270
- input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
271
- step=1,
272
- value=128)
273
- example2 = gr.Examples([[file, 128] for file in glob.glob("example/*.mid")],
274
- [input_midi, input_midi_events])
275
-
276
- tab1.select(lambda: 0, None, tab_select, queue=False)
277
- tab2.select(lambda: 1, None, tab_select, queue=False)
278
- input_gen_events = gr.Slider(label="generate n midi events", minimum=1, maximum=opt.max_gen,
279
- step=1, value=opt.max_gen // 2)
280
- with gr.Accordion("options", open=False):
281
- input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
282
- input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.98)
283
- input_top_k = gr.Slider(label="top k", minimum=1, maximum=20, step=1, value=12)
284
- input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
285
- example3 = gr.Examples([[1, 0.98, 12], [1.2, 0.95, 8]], [input_temp, input_top_p, input_top_k])
286
- run_btn = gr.Button("generate", variant="primary")
287
- stop_btn = gr.Button("stop and output")
288
- output_midi_seq = gr.State()
289
- output_midi_visualizer = gr.HTML(elem_id="midi_visualizer_container")
290
- output_audio = gr.Audio(label="output audio", format="mp3", elem_id="midi_audio")
291
- output_midi = gr.File(label="output midi", file_types=[".mid"])
292
- run_event = run_btn.click(run, [input_model, tab_select, input_instruments, input_drum_kit, input_midi,
293
- input_midi_events, input_gen_events, input_temp, input_top_p, input_top_k,
294
- input_allow_cc],
295
- [output_midi_seq, output_midi, output_audio, js_msg, js_msg_history_state],
296
- concurrency_limit=3)
297
- stop_btn.click(cancel_run, [output_midi_seq, js_msg_history_state], [output_midi, output_audio, js_msg], cancels=run_event, queue=False)
298
- app.launch(server_port=opt.port, share=opt.share, inbrowser=True)
 
1
+ import argparse
2
+ import glob
3
+ import os.path
4
+ import uuid
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ import onnxruntime as rt
9
+ import tqdm
10
+ import json
11
+ from huggingface_hub import hf_hub_download
12
+
13
+ import MIDI
14
+ from midi_synthesizer import synthesis
15
+ from midi_tokenizer import MIDITokenizer
16
+
17
+ in_space = os.getenv("SYSTEM") == "spaces"
18
+
19
+
20
+ def softmax(x, axis):
21
+ x_max = np.amax(x, axis=axis, keepdims=True)
22
+ exp_x_shifted = np.exp(x - x_max)
23
+ return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
24
+
25
+
26
+ def sample_top_p_k(probs, p, k):
27
+ probs_idx = np.argsort(-probs, axis=-1)
28
+ probs_sort = np.take_along_axis(probs, probs_idx, -1)
29
+ probs_sum = np.cumsum(probs_sort, axis=-1)
30
+ mask = probs_sum - probs_sort > p
31
+ probs_sort[mask] = 0.0
32
+ mask = np.zeros(probs_sort.shape[-1])
33
+ mask[:k] = 1
34
+ probs_sort = probs_sort * mask
35
+ probs_sort /= np.sum(probs_sort, axis=-1, keepdims=True)
36
+ shape = probs_sort.shape
37
+ probs_sort_flat = probs_sort.reshape(-1, shape[-1])
38
+ probs_idx_flat = probs_idx.reshape(-1, shape[-1])
39
+ next_token = np.stack([np.random.choice(idxs, p=pvals) for pvals, idxs in zip(probs_sort_flat, probs_idx_flat)])
40
+ next_token = next_token.reshape(*shape[:-1])
41
+ return next_token
42
+
43
+
44
+ def generate(model, prompt=None, max_len=512, temp=1.0, top_p=0.98, top_k=20,
45
+ disable_patch_change=False, disable_control_change=False, disable_channels=None):
46
+ if disable_channels is not None:
47
+ disable_channels = [tokenizer.parameter_ids["channel"][c] for c in disable_channels]
48
+ else:
49
+ disable_channels = []
50
+ max_token_seq = tokenizer.max_token_seq
51
+ if prompt is None:
52
+ input_tensor = np.full((1, max_token_seq), tokenizer.pad_id, dtype=np.int64)
53
+ input_tensor[0, 0] = tokenizer.bos_id # bos
54
+ else:
55
+ prompt = prompt[:, :max_token_seq]
56
+ if prompt.shape[-1] < max_token_seq:
57
+ prompt = np.pad(prompt, ((0, 0), (0, max_token_seq - prompt.shape[-1])),
58
+ mode="constant", constant_values=tokenizer.pad_id)
59
+ input_tensor = prompt
60
+ input_tensor = input_tensor[None, :, :]
61
+ cur_len = input_tensor.shape[1]
62
+ bar = tqdm.tqdm(desc="generating", total=max_len - cur_len, disable=in_space)
63
+ with bar:
64
+ while cur_len < max_len:
65
+ end = False
66
+ hidden = model[0].run(None, {'x': input_tensor})[0][:, -1]
67
+ next_token_seq = np.empty((1, 0), dtype=np.int64)
68
+ event_name = ""
69
+ for i in range(max_token_seq):
70
+ mask = np.zeros(tokenizer.vocab_size, dtype=np.int64)
71
+ if i == 0:
72
+ mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
73
+ if disable_patch_change:
74
+ mask_ids.remove(tokenizer.event_ids["patch_change"])
75
+ if disable_control_change:
76
+ mask_ids.remove(tokenizer.event_ids["control_change"])
77
+ mask[mask_ids] = 1
78
+ else:
79
+ param_name = tokenizer.events[event_name][i - 1]
80
+ mask_ids = tokenizer.parameter_ids[param_name]
81
+ if param_name == "channel":
82
+ mask_ids = [i for i in mask_ids if i not in disable_channels]
83
+ mask[mask_ids] = 1
84
+ logits = model[1].run(None, {'x': next_token_seq, "hidden": hidden})[0][:, -1:]
85
+ scores = softmax(logits / temp, -1) * mask
86
+ sample = sample_top_p_k(scores, top_p, top_k)
87
+ if i == 0:
88
+ next_token_seq = sample
89
+ eid = sample.item()
90
+ if eid == tokenizer.eos_id:
91
+ end = True
92
+ break
93
+ event_name = tokenizer.id_events[eid]
94
+ else:
95
+ next_token_seq = np.concatenate([next_token_seq, sample], axis=1)
96
+ if len(tokenizer.events[event_name]) == i:
97
+ break
98
+ if next_token_seq.shape[1] < max_token_seq:
99
+ next_token_seq = np.pad(next_token_seq, ((0, 0), (0, max_token_seq - next_token_seq.shape[-1])),
100
+ mode="constant", constant_values=tokenizer.pad_id)
101
+ next_token_seq = next_token_seq[None, :, :]
102
+ input_tensor = np.concatenate([input_tensor, next_token_seq], axis=1)
103
+ cur_len += 1
104
+ bar.update(1)
105
+ yield next_token_seq.reshape(-1)
106
+ if end:
107
+ break
108
+
109
+
110
+ def create_msg(name, data):
111
+ return {"name": name, "data": data, "uuid": uuid.uuid4().hex}
112
+
113
+
114
+ def send_msgs(msgs, msgs_history):
115
+ msgs_history.append(msgs)
116
+ if len(msgs_history) > 50:
117
+ msgs_history.pop(0)
118
+ return json.dumps(msgs_history)
119
+
120
+
121
+ def run(model_name, tab, instruments, drum_kit, mid, midi_events, gen_events, temp, top_p, top_k, allow_cc):
122
+ msgs_history = []
123
+ mid_seq = []
124
+ gen_events = int(gen_events)
125
+ max_len = gen_events
126
+
127
+ disable_patch_change = False
128
+ disable_channels = None
129
+ if tab == 0:
130
+ i = 0
131
+ mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
132
+ patches = {}
133
+ if instruments is None:
134
+ instruments = []
135
+ for instr in instruments:
136
+ patches[i] = patch2number[instr]
137
+ i = (i + 1) if i != 8 else 10
138
+ if drum_kit != "None":
139
+ patches[9] = drum_kits2number[drum_kit]
140
+ for i, (c, p) in enumerate(patches.items()):
141
+ mid.append(tokenizer.event2tokens(["patch_change", 0, 0, i, c, p]))
142
+ mid_seq = mid
143
+ mid = np.asarray(mid, dtype=np.int64)
144
+ if len(instruments) > 0:
145
+ disable_patch_change = True
146
+ disable_channels = [i for i in range(16) if i not in patches]
147
+ elif mid is not None:
148
+ mid = tokenizer.tokenize(MIDI.midi2score(mid))
149
+ mid = np.asarray(mid, dtype=np.int64)
150
+ mid = mid[:int(midi_events)]
151
+ max_len += len(mid)
152
+ for token_seq in mid:
153
+ mid_seq.append(token_seq.tolist())
154
+ init_msgs = [create_msg("visualizer_clear", None)]
155
+ for tokens in mid_seq:
156
+ init_msgs.append(create_msg("visualizer_append", tokenizer.tokens2event(tokens)))
157
+ yield mid_seq, None, None, send_msgs(init_msgs, msgs_history), msgs_history
158
+ model = models[model_name]
159
+ generator = generate(model, mid, max_len=max_len, temp=temp, top_p=top_p, top_k=top_k,
160
+ disable_patch_change=disable_patch_change, disable_control_change=not allow_cc,
161
+ disable_channels=disable_channels)
162
+ for i, token_seq in enumerate(generator):
163
+ token_seq = token_seq.tolist()
164
+ mid_seq.append(token_seq)
165
+ event = tokenizer.tokens2event(token_seq)
166
+ yield mid_seq, None, None, send_msgs([create_msg("visualizer_append", event), create_msg("progress", [i + 1, gen_events])], msgs_history), msgs_history
167
+ mid = tokenizer.detokenize(mid_seq)
168
+ with open(f"output.mid", 'wb') as f:
169
+ f.write(MIDI.score2midi(mid))
170
+ audio = synthesis(MIDI.score2opus(mid), soundfont_path)
171
+ yield mid_seq, "output.mid", (44100, audio), send_msgs([create_msg("visualizer_end", None)], msgs_history), msgs_history
172
+
173
+
174
+ def cancel_run(mid_seq, msgs_history):
175
+ if mid_seq is None:
176
+ return None, None, []
177
+ mid = tokenizer.detokenize(mid_seq)
178
+ with open(f"output.mid", 'wb') as f:
179
+ f.write(MIDI.score2midi(mid))
180
+ audio = synthesis(MIDI.score2opus(mid), soundfont_path)
181
+ return "output.mid", (44100, audio), send_msgs([create_msg("visualizer_end", None)], msgs_history)
182
+
183
+
184
+ def load_javascript(dir="javascript"):
185
+ scripts_list = glob.glob(f"{dir}/*.js")
186
+ javascript = ""
187
+ for path in scripts_list:
188
+ with open(path, "r", encoding="utf8") as jsfile:
189
+ javascript += f"\n<!-- {path} --><script>{jsfile.read()}</script>"
190
+ template_response_ori = gr.routes.templates.TemplateResponse
191
+
192
+ def template_response(*args, **kwargs):
193
+ res = template_response_ori(*args, **kwargs)
194
+ res.body = res.body.replace(
195
+ b'</head>', f'{javascript}</head>'.encode("utf8"))
196
+ res.init_headers()
197
+ return res
198
+
199
+ gr.routes.templates.TemplateResponse = template_response
200
+
201
+
202
+ number2drum_kits = {-1: "None", 0: "Standard", 8: "Room", 16: "Power", 24: "Electric", 25: "TR-808", 32: "Jazz",
203
+ 40: "Blush", 48: "Orchestra"}
204
+ patch2number = {v: k for k, v in MIDI.Number2patch.items()}
205
+ drum_kits2number = {v: k for k, v in number2drum_kits.items()}
206
+
207
+ if __name__ == "__main__":
208
+ parser = argparse.ArgumentParser()
209
+ parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
210
+ parser.add_argument("--port", type=int, default=7860, help="gradio server port")
211
+ parser.add_argument("--max-gen", type=int, default=1024, help="max")
212
+ opt = parser.parse_args()
213
+ soundfont_path = "ProtoSquare_.sf2"
214
+ models_info = {"generic pretrain model": ["skytnt/midi-model", ""],
215
+ "j-pop finetune model": ["skytnt/midi-model-ft", "jpop/"],
216
+ "touhou finetune model": ["skytnt/midi-model-ft", "touhou/"],
217
+ }
218
+ models = {}
219
+ tokenizer = MIDITokenizer()
220
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
221
+ for name, (repo_id, path) in models_info.items():
222
+ model_base_path = hf_hub_download(repo_id=repo_id, filename=f"{path}onnx/model_base.onnx")
223
+ model_token_path = hf_hub_download(repo_id=repo_id, filename=f"{path}onnx/model_token.onnx")
224
+ model_base = rt.InferenceSession(model_base_path, providers=providers)
225
+ model_token = rt.InferenceSession(model_token_path, providers=providers)
226
+ models[name] = [model_base, model_token]
227
+
228
+ load_javascript()
229
+ app = gr.Blocks()
230
+ with app:
231
+ gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Midi Composer</h1>")
232
+ gr.Markdown("![Visitors](https://api.visitorbadge.io/api/visitors?path=skytnt.midi-composer&style=flat)\n\n"
233
+ "Midi event transformer for music generation\n\n"
234
+ "Demo for [SkyTNT/midi-model](https://github.com/SkyTNT/midi-model)\n\n"
235
+ "[Open In Colab]"
236
+ "(https://colab.research.google.com/github/SkyTNT/midi-model/blob/main/demo.ipynb)"
237
+ " for faster running and longer generation"
238
+ )
239
+ js_msg_history_state = gr.State(value=[])
240
+ js_msg = gr.Textbox(elem_id="msg_receiver", visible=False)
241
+ js_msg.change(None, [js_msg], [], js="""
242
+ (msg_json) =>{
243
+ let msgs = JSON.parse(msg_json);
244
+ executeCallbacks(msgReceiveCallbacks, msgs);
245
+ return [];
246
+ }
247
+ """)
248
+ input_model = gr.Dropdown(label="select model", choices=list(models.keys()),
249
+ type="value", value=list(models.keys())[0])
250
+ tab_select = gr.State(value=0)
251
+ with gr.Tabs():
252
+ with gr.TabItem("instrument prompt") as tab1:
253
+ input_instruments = gr.Dropdown(label="instruments (auto if empty)", choices=list(patch2number.keys()),
254
+ multiselect=True, max_choices=15, type="value")
255
+ input_drum_kit = gr.Dropdown(label="drum kit", choices=list(drum_kits2number.keys()), type="value",
256
+ value="None")
257
+ example1 = gr.Examples([
258
+ [[], "None"],
259
+ [["Acoustic Grand"], "None"],
260
+ [["Acoustic Grand", "Violin", "Viola", "Cello", "Contrabass"], "Orchestra"],
261
+ [["Flute", "Cello", "Bassoon", "Tuba"], "None"],
262
+ [["Violin", "Viola", "Cello", "Contrabass", "Trumpet", "French Horn", "Brass Section",
263
+ "Flute", "Piccolo", "Tuba", "Trombone", "Timpani"], "Orchestra"],
264
+ [["Acoustic Guitar(nylon)", "Acoustic Guitar(steel)", "Electric Guitar(jazz)",
265
+ "Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar", "Distortion Guitar",
266
+ "Electric Bass(finger)"], "Standard"]
267
+ ], [input_instruments, input_drum_kit])
268
+ with gr.TabItem("midi prompt") as tab2:
269
+ input_midi = gr.File(label="input midi", file_types=[".midi", ".mid"], type="binary")
270
+ input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
271
+ step=1,
272
+ value=128)
273
+ example2 = gr.Examples([[file, 128] for file in glob.glob("example/*.mid")],
274
+ [input_midi, input_midi_events])
275
+
276
+ tab1.select(lambda: 0, None, tab_select, queue=False)
277
+ tab2.select(lambda: 1, None, tab_select, queue=False)
278
+ input_gen_events = gr.Slider(label="generate n midi events", minimum=1, maximum=opt.max_gen,
279
+ step=1, value=opt.max_gen // 2)
280
+ with gr.Accordion("options", open=False):
281
+ input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
282
+ input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.98)
283
+ input_top_k = gr.Slider(label="top k", minimum=1, maximum=20, step=1, value=12)
284
+ input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
285
+ example3 = gr.Examples([[1, 0.98, 12], [1.2, 0.95, 8]], [input_temp, input_top_p, input_top_k])
286
+ run_btn = gr.Button("generate", variant="primary")
287
+ stop_btn = gr.Button("stop and output")
288
+ output_midi_seq = gr.State()
289
+ output_midi_visualizer = gr.HTML(elem_id="midi_visualizer_container")
290
+ output_audio = gr.Audio(label="output audio", format="mp3", elem_id="midi_audio")
291
+ output_midi = gr.File(label="output midi", file_types=[".mid"])
292
+ run_event = run_btn.click(run, [input_model, tab_select, input_instruments, input_drum_kit, input_midi,
293
+ input_midi_events, input_gen_events, input_temp, input_top_p, input_top_k,
294
+ input_allow_cc],
295
+ [output_midi_seq, output_midi, output_audio, js_msg, js_msg_history_state],
296
+ concurrency_limit=3)
297
+ stop_btn.click(cancel_run, [output_midi_seq, js_msg_history_state], [output_midi, output_audio, js_msg], cancels=run_event, queue=False)
298
+ app.launch(server_port=opt.port, share=opt.share, inbrowser=True)