asigalov61 commited on
Commit
3888ab7
1 Parent(s): 9bff65c

Create app.py

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