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