Spaces:
Runtime error
Runtime error
try onnx
Browse files- README.md +1 -1
- app_onnx.py +577 -0
- requirements.txt +1 -0
README.md
CHANGED
@@ -5,7 +5,7 @@ colorFrom: red
|
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.43.0
|
8 |
-
app_file:
|
9 |
pinned: true
|
10 |
license: apache-2.0
|
11 |
---
|
|
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.43.0
|
8 |
+
app_file: app_onnx.py
|
9 |
pinned: true
|
10 |
license: apache-2.0
|
11 |
---
|
app_onnx.py
ADDED
@@ -0,0 +1,577 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import random
|
3 |
+
import argparse
|
4 |
+
import glob
|
5 |
+
import json
|
6 |
+
import os
|
7 |
+
import time
|
8 |
+
from concurrent.futures import ThreadPoolExecutor
|
9 |
+
|
10 |
+
import gradio as gr
|
11 |
+
import numpy as np
|
12 |
+
import onnxruntime as rt
|
13 |
+
import tqdm
|
14 |
+
from huggingface_hub import hf_hub_download
|
15 |
+
|
16 |
+
import MIDI
|
17 |
+
from midi_synthesizer import MidiSynthesizer
|
18 |
+
from midi_tokenizer import MIDITokenizer
|
19 |
+
|
20 |
+
MAX_SEED = np.iinfo(np.int32).max
|
21 |
+
in_space = os.getenv("SYSTEM") == "spaces"
|
22 |
+
|
23 |
+
|
24 |
+
def softmax(x, axis):
|
25 |
+
x_max = np.amax(x, axis=axis, keepdims=True)
|
26 |
+
exp_x_shifted = np.exp(x - x_max)
|
27 |
+
return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
|
28 |
+
|
29 |
+
|
30 |
+
def sample_top_p_k(probs, p, k, generator=None):
|
31 |
+
if generator is None:
|
32 |
+
generator = np.random
|
33 |
+
probs_idx = np.argsort(-probs, axis=-1)
|
34 |
+
probs_sort = np.take_along_axis(probs, probs_idx, -1)
|
35 |
+
probs_sum = np.cumsum(probs_sort, axis=-1)
|
36 |
+
mask = probs_sum - probs_sort > p
|
37 |
+
probs_sort[mask] = 0.0
|
38 |
+
mask = np.zeros(probs_sort.shape[-1])
|
39 |
+
mask[:k] = 1
|
40 |
+
probs_sort = probs_sort * mask
|
41 |
+
probs_sort /= np.sum(probs_sort, axis=-1, keepdims=True)
|
42 |
+
shape = probs_sort.shape
|
43 |
+
probs_sort_flat = probs_sort.reshape(-1, shape[-1])
|
44 |
+
probs_idx_flat = probs_idx.reshape(-1, shape[-1])
|
45 |
+
next_token = np.stack([generator.choice(idxs, p=pvals) for pvals, idxs in zip(probs_sort_flat, probs_idx_flat)])
|
46 |
+
next_token = next_token.reshape(*shape[:-1])
|
47 |
+
return next_token
|
48 |
+
|
49 |
+
|
50 |
+
def generate(model, prompt=None, batch_size=1, max_len=512, temp=1.0, top_p=0.98, top_k=20,
|
51 |
+
disable_patch_change=False, disable_control_change=False, disable_channels=None, generator=None):
|
52 |
+
tokenizer = model[2]
|
53 |
+
if disable_channels is not None:
|
54 |
+
disable_channels = [tokenizer.parameter_ids["channel"][c] for c in disable_channels]
|
55 |
+
else:
|
56 |
+
disable_channels = []
|
57 |
+
if generator is None:
|
58 |
+
generator = np.random
|
59 |
+
max_token_seq = tokenizer.max_token_seq
|
60 |
+
if prompt is None:
|
61 |
+
input_tensor = np.full((1, max_token_seq), tokenizer.pad_id, dtype=np.int64)
|
62 |
+
input_tensor[0, 0] = tokenizer.bos_id # bos
|
63 |
+
input_tensor = input_tensor[None, :, :]
|
64 |
+
input_tensor = np.repeat(input_tensor, repeats=batch_size, axis=0)
|
65 |
+
else:
|
66 |
+
if len(prompt.shape) == 2:
|
67 |
+
prompt = prompt[None, :]
|
68 |
+
prompt = np.repeat(prompt, repeats=batch_size, axis=0)
|
69 |
+
elif prompt.shape[0] == 1:
|
70 |
+
prompt = np.repeat(prompt, repeats=batch_size, axis=0)
|
71 |
+
elif len(prompt.shape) != 3 or prompt.shape[0] != batch_size:
|
72 |
+
raise ValueError(f"invalid shape for prompt, {prompt.shape}")
|
73 |
+
prompt = prompt[..., :max_token_seq]
|
74 |
+
if prompt.shape[-1] < max_token_seq:
|
75 |
+
prompt = np.pad(prompt, ((0, 0), (0, 0), (0, max_token_seq - prompt.shape[-1])),
|
76 |
+
mode="constant", constant_values=tokenizer.pad_id)
|
77 |
+
input_tensor = prompt
|
78 |
+
cur_len = input_tensor.shape[1]
|
79 |
+
bar = tqdm.tqdm(desc="generating", total=max_len - cur_len)
|
80 |
+
with bar:
|
81 |
+
while cur_len < max_len:
|
82 |
+
end = [False] * batch_size
|
83 |
+
hidden = model[0].run(None, {'x': input_tensor})[0][:, -1]
|
84 |
+
next_token_seq = np.empty((batch_size, 0), dtype=np.int64)
|
85 |
+
event_names = [""] * batch_size
|
86 |
+
for i in range(max_token_seq):
|
87 |
+
mask = np.zeros((batch_size, tokenizer.vocab_size), dtype=np.int64)
|
88 |
+
for b in range(batch_size):
|
89 |
+
if end[b]:
|
90 |
+
mask[b, tokenizer.pad_id] = 1
|
91 |
+
continue
|
92 |
+
if i == 0:
|
93 |
+
mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
|
94 |
+
if disable_patch_change:
|
95 |
+
mask_ids.remove(tokenizer.event_ids["patch_change"])
|
96 |
+
if disable_control_change:
|
97 |
+
mask_ids.remove(tokenizer.event_ids["control_change"])
|
98 |
+
mask[b, mask_ids] = 1
|
99 |
+
else:
|
100 |
+
param_names = tokenizer.events[event_names[b]]
|
101 |
+
if i > len(param_names):
|
102 |
+
mask[b, tokenizer.pad_id] = 1
|
103 |
+
continue
|
104 |
+
param_name = param_names[i - 1]
|
105 |
+
mask_ids = tokenizer.parameter_ids[param_name]
|
106 |
+
if param_name == "channel":
|
107 |
+
mask_ids = [i for i in mask_ids if i not in disable_channels]
|
108 |
+
mask[b, mask_ids] = 1
|
109 |
+
mask = mask[:, None, :]
|
110 |
+
logits = model[1].run(None, {'x': next_token_seq, "hidden": hidden})[0][:, -1:]
|
111 |
+
scores = softmax(logits / temp, -1) * mask
|
112 |
+
samples = sample_top_p_k(scores, top_p, top_k, generator)
|
113 |
+
if i == 0:
|
114 |
+
next_token_seq = samples
|
115 |
+
for b in range(batch_size):
|
116 |
+
if end[b]:
|
117 |
+
continue
|
118 |
+
eid = samples[b].item()
|
119 |
+
if eid == tokenizer.eos_id:
|
120 |
+
end[b] = True
|
121 |
+
else:
|
122 |
+
event_names[b] = tokenizer.id_events[eid]
|
123 |
+
else:
|
124 |
+
next_token_seq = np.concatenate([next_token_seq, samples], axis=1)
|
125 |
+
if all([len(tokenizer.events[event_names[b]]) == i for b in range(batch_size) if not end[b]]):
|
126 |
+
break
|
127 |
+
if next_token_seq.shape[1] < max_token_seq:
|
128 |
+
next_token_seq = np.pad(next_token_seq,
|
129 |
+
((0, 0), (0, max_token_seq - next_token_seq.shape[-1])),
|
130 |
+
mode="constant", constant_values=tokenizer.pad_id)
|
131 |
+
next_token_seq = next_token_seq[:, None, :]
|
132 |
+
input_tensor = np.concatenate([input_tensor, next_token_seq], axis=1)
|
133 |
+
cur_len += 1
|
134 |
+
bar.update(1)
|
135 |
+
yield next_token_seq[:, 0]
|
136 |
+
if all(end):
|
137 |
+
break
|
138 |
+
|
139 |
+
|
140 |
+
def create_msg(name, data):
|
141 |
+
return {"name": name, "data": data}
|
142 |
+
|
143 |
+
|
144 |
+
def send_msgs(msgs):
|
145 |
+
return json.dumps(msgs)
|
146 |
+
|
147 |
+
|
148 |
+
def calc_time(x):
|
149 |
+
return 5.849e-5*x**2 + 0.04781*x + 0.1168
|
150 |
+
|
151 |
+
def get_duration(model_name, tab, mid_seq, continuation_state, continuation_select, instruments, drum_kit, bpm,
|
152 |
+
time_sig, key_sig, mid, midi_events, reduce_cc_st, remap_track_channel, add_default_instr,
|
153 |
+
remove_empty_channels, seed, seed_rand, gen_events, temp, top_p, top_k, allow_cc):
|
154 |
+
if tab == 0:
|
155 |
+
start_events = 1
|
156 |
+
elif tab == 1 and mid is not None:
|
157 |
+
start_events = midi_events
|
158 |
+
elif tab == 2 and mid_seq is not None:
|
159 |
+
start_events = len(mid_seq[0])
|
160 |
+
else:
|
161 |
+
start_events = 1
|
162 |
+
t = calc_time(start_events + gen_events) - calc_time(start_events) + 5
|
163 |
+
if "large" in model_name:
|
164 |
+
t *= 2
|
165 |
+
return t
|
166 |
+
|
167 |
+
|
168 |
+
@spaces.GPU(duration=get_duration)
|
169 |
+
def run(model_name, tab, mid_seq, continuation_state, continuation_select, instruments, drum_kit, bpm, time_sig,
|
170 |
+
key_sig, mid, midi_events, reduce_cc_st, remap_track_channel, add_default_instr, remove_empty_channels,
|
171 |
+
seed, seed_rand, gen_events, temp, top_p, top_k, allow_cc):
|
172 |
+
model = models[model_name]
|
173 |
+
model[0].set_providers(['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
174 |
+
model[1].set_providers(['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
175 |
+
tokenizer = model[2]
|
176 |
+
bpm = int(bpm)
|
177 |
+
if time_sig == "auto":
|
178 |
+
time_sig = None
|
179 |
+
time_sig_nn = 4
|
180 |
+
time_sig_dd = 2
|
181 |
+
else:
|
182 |
+
time_sig_nn, time_sig_dd = time_sig.split('/')
|
183 |
+
time_sig_nn = int(time_sig_nn)
|
184 |
+
time_sig_dd = {2: 1, 4: 2, 8: 3}[int(time_sig_dd)]
|
185 |
+
if key_sig == 0:
|
186 |
+
key_sig = None
|
187 |
+
key_sig_sf = 0
|
188 |
+
key_sig_mi = 0
|
189 |
+
else:
|
190 |
+
key_sig = (key_sig - 1)
|
191 |
+
key_sig_sf = key_sig // 2 - 7
|
192 |
+
key_sig_mi = key_sig % 2
|
193 |
+
gen_events = int(gen_events)
|
194 |
+
max_len = gen_events
|
195 |
+
if seed_rand:
|
196 |
+
seed = random.randint(0, MAX_SEED)
|
197 |
+
generator = np.random.RandomState(seed)
|
198 |
+
disable_patch_change = False
|
199 |
+
disable_channels = None
|
200 |
+
if tab == 0:
|
201 |
+
i = 0
|
202 |
+
mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
|
203 |
+
if tokenizer.version == "v2":
|
204 |
+
if time_sig is not None:
|
205 |
+
mid.append(tokenizer.event2tokens(["time_signature", 0, 0, 0, time_sig_nn - 1, time_sig_dd - 1]))
|
206 |
+
if key_sig is not None:
|
207 |
+
mid.append(tokenizer.event2tokens(["key_signature", 0, 0, 0, key_sig_sf + 7, key_sig_mi]))
|
208 |
+
if bpm != 0:
|
209 |
+
mid.append(tokenizer.event2tokens(["set_tempo", 0, 0, 0, bpm]))
|
210 |
+
patches = {}
|
211 |
+
if instruments is None:
|
212 |
+
instruments = []
|
213 |
+
for instr in instruments:
|
214 |
+
patches[i] = patch2number[instr]
|
215 |
+
i = (i + 1) if i != 8 else 10
|
216 |
+
if drum_kit != "None":
|
217 |
+
patches[9] = drum_kits2number[drum_kit]
|
218 |
+
for i, (c, p) in enumerate(patches.items()):
|
219 |
+
mid.append(tokenizer.event2tokens(["patch_change", 0, 0, i + 1, c, p]))
|
220 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
221 |
+
mid_seq = mid.tolist()
|
222 |
+
if len(instruments) > 0:
|
223 |
+
disable_patch_change = True
|
224 |
+
disable_channels = [i for i in range(16) if i not in patches]
|
225 |
+
elif tab == 1 and mid is not None:
|
226 |
+
eps = 4 if reduce_cc_st else 0
|
227 |
+
mid = tokenizer.tokenize(MIDI.midi2score(mid), cc_eps=eps, tempo_eps=eps,
|
228 |
+
remap_track_channel=remap_track_channel,
|
229 |
+
add_default_instr=add_default_instr,
|
230 |
+
remove_empty_channels=remove_empty_channels)
|
231 |
+
mid = mid[:int(midi_events)]
|
232 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
233 |
+
mid_seq = mid.tolist()
|
234 |
+
elif tab == 2 and mid_seq is not None:
|
235 |
+
mid = np.asarray(mid_seq, dtype=np.int64)
|
236 |
+
if continuation_select > 0:
|
237 |
+
continuation_state.append(mid_seq)
|
238 |
+
mid = np.repeat(mid[continuation_select - 1:continuation_select], repeats=OUTPUT_BATCH_SIZE, axis=0)
|
239 |
+
mid_seq = mid.tolist()
|
240 |
+
else:
|
241 |
+
continuation_state.append(mid.shape[1])
|
242 |
+
else:
|
243 |
+
continuation_state = [0]
|
244 |
+
mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
|
245 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
246 |
+
mid_seq = mid.tolist()
|
247 |
+
|
248 |
+
if mid is not None:
|
249 |
+
max_len += mid.shape[1]
|
250 |
+
|
251 |
+
init_msgs = [create_msg("progress", [0, gen_events])]
|
252 |
+
if not (tab == 2 and continuation_select == 0):
|
253 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
254 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
255 |
+
init_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
256 |
+
create_msg("visualizer_append", [i, events])]
|
257 |
+
yield mid_seq, continuation_state, seed, send_msgs(init_msgs)
|
258 |
+
midi_generator = generate(model, mid, batch_size=OUTPUT_BATCH_SIZE, max_len=max_len, temp=temp,
|
259 |
+
top_p=top_p, top_k=top_k, disable_patch_change=disable_patch_change,
|
260 |
+
disable_control_change=not allow_cc, disable_channels=disable_channels,
|
261 |
+
generator=generator)
|
262 |
+
events = [list() for i in range(OUTPUT_BATCH_SIZE)]
|
263 |
+
t = time.time()
|
264 |
+
for i, token_seqs in enumerate(midi_generator):
|
265 |
+
token_seqs = token_seqs.tolist()
|
266 |
+
for j in range(OUTPUT_BATCH_SIZE):
|
267 |
+
token_seq = token_seqs[j]
|
268 |
+
mid_seq[j].append(token_seq)
|
269 |
+
events[j].append(tokenizer.tokens2event(token_seq))
|
270 |
+
if time.time() - t > 0.2:
|
271 |
+
msgs = [create_msg("progress", [i + 1, gen_events])]
|
272 |
+
for j in range(OUTPUT_BATCH_SIZE):
|
273 |
+
msgs += [create_msg("visualizer_append", [j, events[j]])]
|
274 |
+
events[j] = list()
|
275 |
+
yield mid_seq, continuation_state, seed, send_msgs(msgs)
|
276 |
+
t = time.time()
|
277 |
+
yield mid_seq, continuation_state, seed, send_msgs([])
|
278 |
+
|
279 |
+
|
280 |
+
def finish_run(model_name, mid_seq):
|
281 |
+
if mid_seq is None:
|
282 |
+
outputs = [None] * OUTPUT_BATCH_SIZE
|
283 |
+
return *outputs, []
|
284 |
+
tokenizer = models[model_name][2]
|
285 |
+
outputs = []
|
286 |
+
end_msgs = [create_msg("progress", [0, 0])]
|
287 |
+
if not os.path.exists("outputs"):
|
288 |
+
os.mkdir("outputs")
|
289 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
290 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
291 |
+
mid = tokenizer.detokenize(mid_seq[i])
|
292 |
+
with open(f"outputs/output{i + 1}.mid", 'wb') as f:
|
293 |
+
f.write(MIDI.score2midi(mid))
|
294 |
+
outputs.append(f"outputs/output{i + 1}.mid")
|
295 |
+
end_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
296 |
+
create_msg("visualizer_append", [i, events]),
|
297 |
+
create_msg("visualizer_end", i)]
|
298 |
+
return *outputs, send_msgs(end_msgs)
|
299 |
+
|
300 |
+
|
301 |
+
def synthesis_task(mid):
|
302 |
+
return synthesizer.synthesis(MIDI.score2opus(mid))
|
303 |
+
|
304 |
+
def render_audio(model_name, mid_seq, should_render_audio):
|
305 |
+
if (not should_render_audio) or mid_seq is None:
|
306 |
+
outputs = [None] * OUTPUT_BATCH_SIZE
|
307 |
+
return tuple(outputs)
|
308 |
+
tokenizer = models[model_name][2]
|
309 |
+
outputs = []
|
310 |
+
if not os.path.exists("outputs"):
|
311 |
+
os.mkdir("outputs")
|
312 |
+
audio_futures = []
|
313 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
314 |
+
mid = tokenizer.detokenize(mid_seq[i])
|
315 |
+
audio_future = thread_pool.submit(synthesis_task, mid)
|
316 |
+
audio_futures.append(audio_future)
|
317 |
+
for future in audio_futures:
|
318 |
+
outputs.append((44100, future.result()))
|
319 |
+
if OUTPUT_BATCH_SIZE == 1:
|
320 |
+
return outputs[0]
|
321 |
+
return tuple(outputs)
|
322 |
+
|
323 |
+
|
324 |
+
def undo_continuation(model_name, mid_seq, continuation_state):
|
325 |
+
if mid_seq is None or len(continuation_state) < 2:
|
326 |
+
return mid_seq, continuation_state, send_msgs([])
|
327 |
+
tokenizer = models[model_name][2]
|
328 |
+
if isinstance(continuation_state[-1], list):
|
329 |
+
mid_seq = continuation_state[-1]
|
330 |
+
else:
|
331 |
+
mid_seq = [ms[:continuation_state[-1]] for ms in mid_seq]
|
332 |
+
continuation_state = continuation_state[:-1]
|
333 |
+
end_msgs = [create_msg("progress", [0, 0])]
|
334 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
335 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
336 |
+
end_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
337 |
+
create_msg("visualizer_append", [i, events]),
|
338 |
+
create_msg("visualizer_end", i)]
|
339 |
+
return mid_seq, continuation_state, send_msgs(end_msgs)
|
340 |
+
|
341 |
+
|
342 |
+
def load_javascript(dir="javascript"):
|
343 |
+
scripts_list = glob.glob(f"{dir}/*.js")
|
344 |
+
javascript = ""
|
345 |
+
for path in scripts_list:
|
346 |
+
with open(path, "r", encoding="utf8") as jsfile:
|
347 |
+
js_content = jsfile.read()
|
348 |
+
js_content = js_content.replace("const MIDI_OUTPUT_BATCH_SIZE=4;",
|
349 |
+
f"const MIDI_OUTPUT_BATCH_SIZE={OUTPUT_BATCH_SIZE};")
|
350 |
+
javascript += f"\n<!-- {path} --><script>{js_content}</script>"
|
351 |
+
template_response_ori = gr.routes.templates.TemplateResponse
|
352 |
+
|
353 |
+
def template_response(*args, **kwargs):
|
354 |
+
res = template_response_ori(*args, **kwargs)
|
355 |
+
res.body = res.body.replace(
|
356 |
+
b'</head>', f'{javascript}</head>'.encode("utf8"))
|
357 |
+
res.init_headers()
|
358 |
+
return res
|
359 |
+
|
360 |
+
gr.routes.templates.TemplateResponse = template_response
|
361 |
+
|
362 |
+
|
363 |
+
def hf_hub_download_retry(repo_id, filename):
|
364 |
+
print(f"downloading {repo_id} {filename}")
|
365 |
+
retry = 0
|
366 |
+
err = None
|
367 |
+
while retry < 30:
|
368 |
+
try:
|
369 |
+
return hf_hub_download(repo_id=repo_id, filename=filename)
|
370 |
+
except Exception as e:
|
371 |
+
err = e
|
372 |
+
retry += 1
|
373 |
+
if err:
|
374 |
+
raise err
|
375 |
+
|
376 |
+
|
377 |
+
def get_tokenizer(config_name):
|
378 |
+
tv, size = config_name.split("-")
|
379 |
+
tv = tv[1:]
|
380 |
+
if tv[-1] == "o":
|
381 |
+
o = True
|
382 |
+
tv = tv[:-1]
|
383 |
+
else:
|
384 |
+
o = False
|
385 |
+
if tv not in ["v1", "v2"]:
|
386 |
+
raise ValueError(f"Unknown tokenizer version {tv}")
|
387 |
+
tokenizer = MIDITokenizer(tv)
|
388 |
+
tokenizer.set_optimise_midi(o)
|
389 |
+
return tokenizer
|
390 |
+
|
391 |
+
|
392 |
+
number2drum_kits = {-1: "None", 0: "Standard", 8: "Room", 16: "Power", 24: "Electric", 25: "TR-808", 32: "Jazz",
|
393 |
+
40: "Blush", 48: "Orchestra"}
|
394 |
+
patch2number = {v: k for k, v in MIDI.Number2patch.items()}
|
395 |
+
drum_kits2number = {v: k for k, v in number2drum_kits.items()}
|
396 |
+
key_signatures = ['C♭', 'A♭m', 'G♭', 'E♭m', 'D♭', 'B♭m', 'A♭', 'Fm', 'E♭', 'Cm', 'B♭', 'Gm', 'F', 'Dm',
|
397 |
+
'C', 'Am', 'G', 'Em', 'D', 'Bm', 'A', 'F♯m', 'E', 'C♯m', 'B', 'G♯m', 'F♯', 'D♯m', 'C♯', 'A♯m']
|
398 |
+
|
399 |
+
if __name__ == "__main__":
|
400 |
+
parser = argparse.ArgumentParser()
|
401 |
+
parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
|
402 |
+
parser.add_argument("--port", type=int, default=7860, help="gradio server port")
|
403 |
+
parser.add_argument("--device", type=str, default="cuda", help="device to run model")
|
404 |
+
parser.add_argument("--batch", type=int, default=8, help="batch size")
|
405 |
+
parser.add_argument("--max-gen", type=int, default=1024, help="max")
|
406 |
+
opt = parser.parse_args()
|
407 |
+
OUTPUT_BATCH_SIZE = opt.batch
|
408 |
+
soundfont_path = hf_hub_download_retry(repo_id="skytnt/midi-model", filename="soundfont.sf2")
|
409 |
+
thread_pool = ThreadPoolExecutor(max_workers=OUTPUT_BATCH_SIZE)
|
410 |
+
synthesizer = MidiSynthesizer(soundfont_path)
|
411 |
+
models_info = {
|
412 |
+
"generic pretrain model (tv2o-medium) by skytnt": [
|
413 |
+
"skytnt/midi-model-tv2o-medium", "", "tv2o-medium", {
|
414 |
+
"jpop": "skytnt/midi-model-tv2om-jpop-lora",
|
415 |
+
"touhou": "skytnt/midi-model-tv2om-touhou-lora"
|
416 |
+
}
|
417 |
+
],
|
418 |
+
"generic pretrain model (tv2o-large) by asigalov61": [
|
419 |
+
"asigalov61/Music-Llama", "", "tv2o-large", {}
|
420 |
+
],
|
421 |
+
"generic pretrain model (tv2o-medium) by asigalov61": [
|
422 |
+
"asigalov61/Music-Llama-Medium", "", "tv2o-medium", {}
|
423 |
+
],
|
424 |
+
"generic pretrain model (tv1-medium) by skytnt": [
|
425 |
+
"skytnt/midi-model", "", "tv1-medium", {}
|
426 |
+
]
|
427 |
+
}
|
428 |
+
models = {}
|
429 |
+
providers = ['CPUExecutionProvider']
|
430 |
+
|
431 |
+
for name, (repo_id, path, config, loras) in models_info.items():
|
432 |
+
model_base_path = hf_hub_download_retry(repo_id=repo_id, filename=f"{path}onnx/model_base.onnx")
|
433 |
+
model_token_path = hf_hub_download_retry(repo_id=repo_id, filename=f"{path}onnx/model_token.onnx")
|
434 |
+
model_base = rt.InferenceSession(model_base_path, providers=providers)
|
435 |
+
model_token = rt.InferenceSession(model_token_path, providers=providers)
|
436 |
+
tokenizer = get_tokenizer(config)
|
437 |
+
models[name] = [model_base, model_token, tokenizer]
|
438 |
+
for lora_name, lora_repo in loras.items():
|
439 |
+
model_base_path = hf_hub_download_retry(repo_id=lora_repo, filename=f"onnx/model_base.onnx")
|
440 |
+
model_token_path = hf_hub_download_retry(repo_id=lora_repo, filename=f"onnx/model_token.onnx")
|
441 |
+
model_base = rt.InferenceSession(model_base_path, providers=providers)
|
442 |
+
model_token = rt.InferenceSession(model_token_path, providers=providers)
|
443 |
+
tokenizer = get_tokenizer(config)
|
444 |
+
models[f"{name} with {lora_name} lora"] = [model_base, model_token, tokenizer]
|
445 |
+
|
446 |
+
load_javascript()
|
447 |
+
app = gr.Blocks()
|
448 |
+
with app:
|
449 |
+
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Midi Composer</h1>")
|
450 |
+
gr.Markdown("![Visitors](https://api.visitorbadge.io/api/visitors?path=skytnt.midi-composer&style=flat)\n\n"
|
451 |
+
"Midi event transformer for symbolic music generation\n\n"
|
452 |
+
"Demo for [SkyTNT/midi-model](https://github.com/SkyTNT/midi-model)\n\n"
|
453 |
+
"[Open In Colab]"
|
454 |
+
"(https://colab.research.google.com/github/SkyTNT/midi-model/blob/main/demo.ipynb)"
|
455 |
+
" or [download windows app](https://github.com/SkyTNT/midi-model/releases)"
|
456 |
+
" for unlimited generation\n\n"
|
457 |
+
"**Update v1.3**: MIDITokenizerV2 and new MidiVisualizer"
|
458 |
+
)
|
459 |
+
js_msg = gr.Textbox(elem_id="msg_receiver", visible=False)
|
460 |
+
js_msg.change(None, [js_msg], [], js="""
|
461 |
+
(msg_json) =>{
|
462 |
+
let msgs = JSON.parse(msg_json);
|
463 |
+
executeCallbacks(msgReceiveCallbacks, msgs);
|
464 |
+
return [];
|
465 |
+
}
|
466 |
+
""")
|
467 |
+
input_model = gr.Dropdown(label="select model", choices=list(models.keys()),
|
468 |
+
type="value", value=list(models.keys())[0])
|
469 |
+
tab_select = gr.State(value=0)
|
470 |
+
with gr.Tabs():
|
471 |
+
with gr.TabItem("custom prompt") as tab1:
|
472 |
+
input_instruments = gr.Dropdown(label="🪗instruments (auto if empty)", choices=list(patch2number.keys()),
|
473 |
+
multiselect=True, max_choices=15, type="value")
|
474 |
+
input_drum_kit = gr.Dropdown(label="🥁drum kit", choices=list(drum_kits2number.keys()), type="value",
|
475 |
+
value="None")
|
476 |
+
input_bpm = gr.Slider(label="BPM (beats per minute, auto if 0)", minimum=0, maximum=255,
|
477 |
+
step=1,
|
478 |
+
value=0)
|
479 |
+
input_time_sig = gr.Radio(label="time signature (only for tv2 models)",
|
480 |
+
value="auto",
|
481 |
+
choices=["auto", "4/4", "2/4", "3/4", "6/4", "7/4",
|
482 |
+
"2/2", "3/2", "4/2", "3/8", "5/8", "6/8", "7/8", "9/8", "12/8"]
|
483 |
+
)
|
484 |
+
input_key_sig = gr.Radio(label="key signature (only for tv2 models)",
|
485 |
+
value="auto",
|
486 |
+
choices=["auto"] + key_signatures,
|
487 |
+
type="index"
|
488 |
+
)
|
489 |
+
example1 = gr.Examples([
|
490 |
+
[[], "None"],
|
491 |
+
[["Acoustic Grand"], "None"],
|
492 |
+
[['Acoustic Grand', 'SynthStrings 2', 'SynthStrings 1', 'Pizzicato Strings',
|
493 |
+
'Pad 2 (warm)', 'Tremolo Strings', 'String Ensemble 1'], "Orchestra"],
|
494 |
+
[['Trumpet', 'Oboe', 'Trombone', 'String Ensemble 1', 'Clarinet',
|
495 |
+
'French Horn', 'Pad 4 (choir)', 'Bassoon', 'Flute'], "None"],
|
496 |
+
[['Flute', 'French Horn', 'Clarinet', 'String Ensemble 2', 'English Horn', 'Bassoon',
|
497 |
+
'Oboe', 'Pizzicato Strings'], "Orchestra"],
|
498 |
+
[['Electric Piano 2', 'Lead 5 (charang)', 'Electric Bass(pick)', 'Lead 2 (sawtooth)',
|
499 |
+
'Pad 1 (new age)', 'Orchestra Hit', 'Cello', 'Electric Guitar(clean)'], "Standard"],
|
500 |
+
[["Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar", "Distortion Guitar",
|
501 |
+
"Electric Bass(finger)"], "Standard"]
|
502 |
+
], [input_instruments, input_drum_kit])
|
503 |
+
with gr.TabItem("midi prompt") as tab2:
|
504 |
+
input_midi = gr.File(label="input midi", file_types=[".midi", ".mid"], type="binary")
|
505 |
+
input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
|
506 |
+
step=1,
|
507 |
+
value=128)
|
508 |
+
input_reduce_cc_st = gr.Checkbox(label="reduce control_change and set_tempo events", value=True)
|
509 |
+
input_remap_track_channel = gr.Checkbox(
|
510 |
+
label="remap tracks and channels so each track has only one channel and in order", value=True)
|
511 |
+
input_add_default_instr = gr.Checkbox(
|
512 |
+
label="add a default instrument to channels that don't have an instrument", value=True)
|
513 |
+
input_remove_empty_channels = gr.Checkbox(label="remove channels without notes", value=False)
|
514 |
+
example2 = gr.Examples([[file, 128] for file in glob.glob("example/*.mid")],
|
515 |
+
[input_midi, input_midi_events])
|
516 |
+
with gr.TabItem("last output prompt") as tab3:
|
517 |
+
gr.Markdown("Continue generating on the last output.")
|
518 |
+
input_continuation_select = gr.Radio(label="select output to continue generating", value="all",
|
519 |
+
choices=["all"] + [f"output{i + 1}" for i in
|
520 |
+
range(OUTPUT_BATCH_SIZE)],
|
521 |
+
type="index"
|
522 |
+
)
|
523 |
+
undo_btn = gr.Button("undo the last continuation")
|
524 |
+
|
525 |
+
tab1.select(lambda: 0, None, tab_select, queue=False)
|
526 |
+
tab2.select(lambda: 1, None, tab_select, queue=False)
|
527 |
+
tab3.select(lambda: 2, None, tab_select, queue=False)
|
528 |
+
input_seed = gr.Slider(label="seed", minimum=0, maximum=2 ** 31 - 1,
|
529 |
+
step=1, value=0)
|
530 |
+
input_seed_rand = gr.Checkbox(label="random seed", value=True)
|
531 |
+
input_gen_events = gr.Slider(label="generate max n midi events", minimum=1, maximum=opt.max_gen,
|
532 |
+
step=1, value=opt.max_gen // 2)
|
533 |
+
with gr.Accordion("options", open=False):
|
534 |
+
input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
|
535 |
+
input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.95)
|
536 |
+
input_top_k = gr.Slider(label="top k", minimum=1, maximum=128, step=1, value=20)
|
537 |
+
input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
|
538 |
+
input_render_audio = gr.Checkbox(label="render audio after generation", value=True)
|
539 |
+
example3 = gr.Examples([[1, 0.94, 128], [1, 0.98, 20], [1, 0.98, 12]],
|
540 |
+
[input_temp, input_top_p, input_top_k])
|
541 |
+
run_btn = gr.Button("generate", variant="primary")
|
542 |
+
# stop_btn = gr.Button("stop and output")
|
543 |
+
output_midi_seq = gr.State()
|
544 |
+
output_continuation_state = gr.State([0])
|
545 |
+
midi_outputs = []
|
546 |
+
audio_outputs = []
|
547 |
+
with gr.Tabs(elem_id="output_tabs"):
|
548 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
549 |
+
with gr.TabItem(f"output {i + 1}") as tab1:
|
550 |
+
output_midi_visualizer = gr.HTML(elem_id=f"midi_visualizer_container_{i}")
|
551 |
+
output_audio = gr.Audio(label="output audio", format="mp3", elem_id=f"midi_audio_{i}")
|
552 |
+
output_midi = gr.File(label="output midi", file_types=[".mid"])
|
553 |
+
midi_outputs.append(output_midi)
|
554 |
+
audio_outputs.append(output_audio)
|
555 |
+
run_event = run_btn.click(run, [input_model, tab_select, output_midi_seq, output_continuation_state,
|
556 |
+
input_continuation_select, input_instruments, input_drum_kit, input_bpm,
|
557 |
+
input_time_sig, input_key_sig, input_midi, input_midi_events,
|
558 |
+
input_reduce_cc_st, input_remap_track_channel,
|
559 |
+
input_add_default_instr, input_remove_empty_channels,
|
560 |
+
input_seed, input_seed_rand, input_gen_events, input_temp, input_top_p,
|
561 |
+
input_top_k, input_allow_cc],
|
562 |
+
[output_midi_seq, output_continuation_state, input_seed, js_msg],
|
563 |
+
concurrency_limit=10, queue=True)
|
564 |
+
finish_run_event = run_event.then(fn=finish_run,
|
565 |
+
inputs=[input_model, output_midi_seq],
|
566 |
+
outputs=midi_outputs + [js_msg],
|
567 |
+
queue=False)
|
568 |
+
finish_run_event.then(fn=render_audio,
|
569 |
+
inputs=[input_model, output_midi_seq, input_render_audio],
|
570 |
+
outputs=audio_outputs,
|
571 |
+
queue=False)
|
572 |
+
# stop_btn.click(None, [], [], cancels=run_event,
|
573 |
+
# queue=False)
|
574 |
+
undo_btn.click(undo_continuation, [input_model, output_midi_seq, output_continuation_state],
|
575 |
+
[output_midi_seq, output_continuation_state, js_msg], queue=False)
|
576 |
+
app.queue().launch(server_port=opt.port, share=opt.share, inbrowser=True)
|
577 |
+
thread_pool.shutdown()
|
requirements.txt
CHANGED
@@ -2,6 +2,7 @@
|
|
2 |
Pillow
|
3 |
numpy
|
4 |
torch
|
|
|
5 |
peft>=0.13.0
|
6 |
transformers>=4.36
|
7 |
gradio==4.43.0
|
|
|
2 |
Pillow
|
3 |
numpy
|
4 |
torch
|
5 |
+
onnxruntime-gpu
|
6 |
peft>=0.13.0
|
7 |
transformers>=4.36
|
8 |
gradio==4.43.0
|