Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,72 +1,48 @@
|
|
| 1 |
import argparse
|
| 2 |
import glob
|
| 3 |
-
import os.path
|
| 4 |
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
-
import
|
|
|
|
|
|
|
| 8 |
import tqdm
|
| 9 |
-
import json
|
| 10 |
-
from huggingface_hub import hf_hub_download
|
| 11 |
|
| 12 |
import MIDI
|
| 13 |
-
from
|
| 14 |
from midi_tokenizer import MIDITokenizer
|
| 15 |
-
|
|
|
|
| 16 |
in_space = os.getenv("SYSTEM") == "spaces"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 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 =
|
| 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
|
| 60 |
cur_len = input_tensor.shape[1]
|
| 61 |
-
bar = tqdm.tqdm(desc="generating", total=max_len - cur_len
|
| 62 |
-
with bar:
|
| 63 |
while cur_len < max_len:
|
| 64 |
end = False
|
| 65 |
-
hidden = model
|
| 66 |
-
next_token_seq =
|
| 67 |
event_name = ""
|
| 68 |
for i in range(max_token_seq):
|
| 69 |
-
mask =
|
| 70 |
if i == 0:
|
| 71 |
mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
|
| 72 |
if disable_patch_change:
|
|
@@ -80,9 +56,9 @@ def generate(model, prompt=None, max_len=512, temp=1.0, top_p=0.98, top_k=20,
|
|
| 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
|
| 84 |
-
scores = softmax(logits / temp,
|
| 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,29 +67,58 @@ def generate(model, prompt=None, max_len=512, temp=1.0, top_p=0.98, top_k=20,
|
|
| 91 |
break
|
| 92 |
event_name = tokenizer.id_events[eid]
|
| 93 |
else:
|
| 94 |
-
next_token_seq =
|
| 95 |
if len(tokenizer.events[event_name]) == i:
|
| 96 |
break
|
| 97 |
if next_token_seq.shape[1] < max_token_seq:
|
| 98 |
-
next_token_seq =
|
| 99 |
-
|
| 100 |
-
next_token_seq = next_token_seq
|
| 101 |
-
input_tensor =
|
| 102 |
cur_len += 1
|
| 103 |
bar.update(1)
|
| 104 |
-
yield next_token_seq.reshape(-1)
|
| 105 |
if end:
|
| 106 |
break
|
| 107 |
|
| 108 |
|
| 109 |
-
def
|
| 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 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
disable_patch_change = False
|
| 119 |
disable_channels = None
|
|
@@ -130,7 +135,7 @@ def run(model_name, tab, instruments, drum_kit, mid, midi_events, gen_events, te
|
|
| 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,67 +144,41 @@ def run(model_name, tab, instruments, drum_kit, mid, midi_events, gen_events, te
|
|
| 139 |
mid = mid[:int(midi_events)]
|
| 140 |
max_len += len(mid)
|
| 141 |
for token_seq in mid:
|
| 142 |
-
mid_seq.append(token_seq
|
| 143 |
-
|
| 144 |
-
|
| 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
|
| 152 |
-
token_seq = token_seq.tolist()
|
| 153 |
mid_seq.append(token_seq)
|
| 154 |
-
|
| 155 |
-
yield mid_seq,
|
| 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)
|
| 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)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 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,37 +188,16 @@ drum_kits2number = {v: k for k, v in number2drum_kits.items()}
|
|
| 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("--
|
| 215 |
-
opt = parser.parse_args()
|
| 216 |
soundfont_path = hf_hub_download(repo_id="skytnt/midi-model", filename="soundfont.sf2")
|
| 217 |
-
|
| 218 |
-
"j-pop finetune model": ["skytnt/midi-model-ft", "jpop/"],
|
| 219 |
-
"touhou finetune model": ["skytnt/midi-model-ft", "touhou/"]}
|
| 220 |
-
models = {}
|
| 221 |
tokenizer = MIDITokenizer()
|
| 222 |
-
|
| 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.
|
| 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 |
-
with gr.Accordion(label="Model option", open=True):
|
| 243 |
load_model_path_btn = gr.Button("Get Models")
|
| 244 |
model_path_input = gr.Dropdown(label="model")
|
| 245 |
load_model_path_btn.click(get_model_path, [], model_path_input)
|
|
@@ -271,28 +229,26 @@ if __name__ == "__main__":
|
|
| 271 |
input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
|
| 272 |
step=1,
|
| 273 |
value=128)
|
| 274 |
-
example2 = gr.Examples([[file, 128] for file in glob.glob("example/*.mid")],
|
| 275 |
-
[input_midi, input_midi_events])
|
| 276 |
|
| 277 |
tab1.select(lambda: 0, None, tab_select, queue=False)
|
| 278 |
tab2.select(lambda: 1, None, tab_select, queue=False)
|
| 279 |
-
input_gen_events = gr.Slider(label="generate n midi events", minimum=1, maximum=
|
| 280 |
-
step=1, value=opt.max_gen // 2)
|
| 281 |
with gr.Accordion("options", open=False):
|
| 282 |
input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
|
| 283 |
input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.98)
|
| 284 |
input_top_k = gr.Slider(label="top k", minimum=1, maximum=20, step=1, value=12)
|
| 285 |
input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
|
|
|
|
| 286 |
example3 = gr.Examples([[1, 0.98, 12], [1.2, 0.95, 8]], [input_temp, input_top_p, input_top_k])
|
| 287 |
run_btn = gr.Button("generate", variant="primary")
|
| 288 |
stop_btn = gr.Button("stop and output")
|
| 289 |
output_midi_seq = gr.Variable()
|
| 290 |
-
|
| 291 |
-
output_audio = gr.Audio(label="output audio", format="mp3", elem_id="midi_audio")
|
| 292 |
output_midi = gr.File(label="output midi", file_types=[".mid"])
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
| 1 |
import argparse
|
| 2 |
import glob
|
|
|
|
| 3 |
|
| 4 |
+
import PIL
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
import tqdm
|
|
|
|
|
|
|
| 11 |
|
| 12 |
import MIDI
|
| 13 |
+
from midi_model import MIDIModel
|
| 14 |
from midi_tokenizer import MIDITokenizer
|
| 15 |
+
from midi_synthesizer import synthesis
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
in_space = os.getenv("SYSTEM") == "spaces"
|
| 18 |
+
@torch.inference_mode()
|
| 19 |
+
def generate(prompt=None, max_len=512, temp=1.0, top_p=0.98, top_k=20,
|
| 20 |
+
disable_patch_change=False, disable_control_change=False, disable_channels=None, amp=True):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
if disable_channels is not None:
|
| 22 |
disable_channels = [tokenizer.parameter_ids["channel"][c] for c in disable_channels]
|
| 23 |
else:
|
| 24 |
disable_channels = []
|
| 25 |
max_token_seq = tokenizer.max_token_seq
|
| 26 |
if prompt is None:
|
| 27 |
+
input_tensor = torch.full((1, max_token_seq), tokenizer.pad_id, dtype=torch.long, device=model.device)
|
| 28 |
input_tensor[0, 0] = tokenizer.bos_id # bos
|
| 29 |
else:
|
| 30 |
prompt = prompt[:, :max_token_seq]
|
| 31 |
if prompt.shape[-1] < max_token_seq:
|
| 32 |
prompt = np.pad(prompt, ((0, 0), (0, max_token_seq - prompt.shape[-1])),
|
| 33 |
mode="constant", constant_values=tokenizer.pad_id)
|
| 34 |
+
input_tensor = torch.from_numpy(prompt).to(dtype=torch.long, device=model.device)
|
| 35 |
+
input_tensor = input_tensor.unsqueeze(0)
|
| 36 |
cur_len = input_tensor.shape[1]
|
| 37 |
+
bar = tqdm.tqdm(desc="generating", total=max_len - cur_len)
|
| 38 |
+
with bar, torch.cuda.amp.autocast(enabled=amp):
|
| 39 |
while cur_len < max_len:
|
| 40 |
end = False
|
| 41 |
+
hidden = model.forward(input_tensor)[0, -1].unsqueeze(0)
|
| 42 |
+
next_token_seq = None
|
| 43 |
event_name = ""
|
| 44 |
for i in range(max_token_seq):
|
| 45 |
+
mask = torch.zeros(tokenizer.vocab_size, dtype=torch.int64, device=model.device)
|
| 46 |
if i == 0:
|
| 47 |
mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
|
| 48 |
if disable_patch_change:
|
|
|
|
| 56 |
if param_name == "channel":
|
| 57 |
mask_ids = [i for i in mask_ids if i not in disable_channels]
|
| 58 |
mask[mask_ids] = 1
|
| 59 |
+
logits = model.forward_token(hidden, next_token_seq)[:, -1:]
|
| 60 |
+
scores = torch.softmax(logits / temp, dim=-1) * mask
|
| 61 |
+
sample = model.sample_top_p_k(scores, top_p, top_k)
|
| 62 |
if i == 0:
|
| 63 |
next_token_seq = sample
|
| 64 |
eid = sample.item()
|
|
|
|
| 67 |
break
|
| 68 |
event_name = tokenizer.id_events[eid]
|
| 69 |
else:
|
| 70 |
+
next_token_seq = torch.cat([next_token_seq, sample], dim=1)
|
| 71 |
if len(tokenizer.events[event_name]) == i:
|
| 72 |
break
|
| 73 |
if next_token_seq.shape[1] < max_token_seq:
|
| 74 |
+
next_token_seq = F.pad(next_token_seq, (0, max_token_seq - next_token_seq.shape[1]),
|
| 75 |
+
"constant", value=tokenizer.pad_id)
|
| 76 |
+
next_token_seq = next_token_seq.unsqueeze(1)
|
| 77 |
+
input_tensor = torch.cat([input_tensor, next_token_seq], dim=1)
|
| 78 |
cur_len += 1
|
| 79 |
bar.update(1)
|
| 80 |
+
yield next_token_seq.reshape(-1).cpu().numpy()
|
| 81 |
if end:
|
| 82 |
break
|
| 83 |
|
| 84 |
|
| 85 |
+
def run(tab, instruments, drum_kit, mid, midi_events, gen_events, temp, top_p, top_k, allow_cc, amp):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
mid_seq = []
|
| 87 |
+
max_len = int(gen_events)
|
| 88 |
+
img_len = 1024
|
| 89 |
+
img = np.full((128 * 2, img_len, 3), 255, dtype=np.uint8)
|
| 90 |
+
state = {"t1": 0, "t": 0, "cur_pos": 0}
|
| 91 |
+
rand = np.random.RandomState(0)
|
| 92 |
+
colors = {(i, j): rand.randint(0, 200, 3) for i in range(128) for j in range(16)}
|
| 93 |
+
|
| 94 |
+
def draw_event(tokens):
|
| 95 |
+
if tokens[0] in tokenizer.id_events:
|
| 96 |
+
name = tokenizer.id_events[tokens[0]]
|
| 97 |
+
if len(tokens) <= len(tokenizer.events[name]):
|
| 98 |
+
return
|
| 99 |
+
params = tokens[1:]
|
| 100 |
+
params = [params[i] - tokenizer.parameter_ids[p][0] for i, p in enumerate(tokenizer.events[name])]
|
| 101 |
+
if not all([0 <= params[i] < tokenizer.event_parameters[p] for i, p in enumerate(tokenizer.events[name])]):
|
| 102 |
+
return
|
| 103 |
+
event = [name] + params
|
| 104 |
+
state["t1"] += event[1]
|
| 105 |
+
t = state["t1"] * 16 + event[2]
|
| 106 |
+
state["t"] = t
|
| 107 |
+
if name == "note":
|
| 108 |
+
tr, d, c, p = event[3:7]
|
| 109 |
+
shift = t + d - (state["cur_pos"] + img_len)
|
| 110 |
+
if shift > 0:
|
| 111 |
+
img[:, :-shift] = img[:, shift:]
|
| 112 |
+
img[:, -shift:] = 255
|
| 113 |
+
state["cur_pos"] += shift
|
| 114 |
+
t = t - state["cur_pos"]
|
| 115 |
+
img[p * 2:(p + 1) * 2, t: t + d] = colors[(tr, c)]
|
| 116 |
+
|
| 117 |
+
def get_img():
|
| 118 |
+
t = state["t"] - state["cur_pos"]
|
| 119 |
+
img_new = img.copy()
|
| 120 |
+
img_new[:, t: t + 2] = 0
|
| 121 |
+
return PIL.Image.fromarray(np.flip(img_new, 0))
|
| 122 |
|
| 123 |
disable_patch_change = False
|
| 124 |
disable_channels = None
|
|
|
|
| 135 |
mid.append(tokenizer.event2tokens(["patch_change", 0, 0, i, c, p]))
|
| 136 |
mid_seq = mid
|
| 137 |
mid = np.asarray(mid, dtype=np.int64)
|
| 138 |
+
if len(instruments) > 0 or drum_kit != "None":
|
| 139 |
disable_patch_change = True
|
| 140 |
disable_channels = [i for i in range(16) if i not in patches]
|
| 141 |
elif mid is not None:
|
|
|
|
| 144 |
mid = mid[:int(midi_events)]
|
| 145 |
max_len += len(mid)
|
| 146 |
for token_seq in mid:
|
| 147 |
+
mid_seq.append(token_seq)
|
| 148 |
+
draw_event(token_seq)
|
| 149 |
+
generator = generate(mid, max_len=max_len, temp=temp, top_p=top_p, top_k=top_k,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
disable_patch_change=disable_patch_change, disable_control_change=not allow_cc,
|
| 151 |
+
disable_channels=disable_channels, amp=amp)
|
| 152 |
+
for token_seq in generator:
|
|
|
|
| 153 |
mid_seq.append(token_seq)
|
| 154 |
+
draw_event(token_seq)
|
| 155 |
+
yield mid_seq, get_img(), None, None
|
| 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, get_img(), "output.mid", (44100, audio)
|
| 161 |
|
| 162 |
|
| 163 |
def cancel_run(mid_seq):
|
|
|
|
|
|
|
| 164 |
mid = tokenizer.detokenize(mid_seq)
|
| 165 |
with open(f"output.mid", 'wb') as f:
|
| 166 |
f.write(MIDI.score2midi(mid))
|
| 167 |
audio = synthesis(MIDI.score2opus(mid), soundfont_path)
|
| 168 |
+
return "output.mid", (44100, audio)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
def load_model(path):
|
| 172 |
+
ckpt = torch.load(path, map_location="cpu")
|
| 173 |
+
state_dict = ckpt.get("state_dict", ckpt)
|
| 174 |
+
model.load_state_dict(state_dict, strict=False)
|
| 175 |
+
model.eval()
|
| 176 |
+
return "success"
|
| 177 |
|
| 178 |
|
| 179 |
+
def get_model_path():
|
| 180 |
+
model_paths = sorted(glob.glob("**/*.ckpt", recursive=True))
|
| 181 |
+
return model_path_input.update(choices=model_paths)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
|
| 184 |
number2drum_kits = {-1: "None", 0: "Standard", 8: "Room", 16: "Power", 24: "Electric", 25: "TR-808", 32: "Jazz",
|
|
|
|
| 188 |
|
| 189 |
if __name__ == "__main__":
|
| 190 |
parser = argparse.ArgumentParser()
|
|
|
|
| 191 |
parser.add_argument("--port", type=int, default=7860, help="gradio server port")
|
| 192 |
+
parser.add_argument("--device", type=str, default="cuda", help="device to run model")
|
|
|
|
| 193 |
soundfont_path = hf_hub_download(repo_id="skytnt/midi-model", filename="soundfont.sf2")
|
| 194 |
+
opt = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
| 195 |
tokenizer = MIDITokenizer()
|
| 196 |
+
model = MIDIModel(tokenizer).to(device=opt.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
|
|
|
| 198 |
app = gr.Blocks()
|
| 199 |
with app:
|
| 200 |
+
with gr.Accordion(label="Model option", open=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
load_model_path_btn = gr.Button("Get Models")
|
| 202 |
model_path_input = gr.Dropdown(label="model")
|
| 203 |
load_model_path_btn.click(get_model_path, [], model_path_input)
|
|
|
|
| 229 |
input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
|
| 230 |
step=1,
|
| 231 |
value=128)
|
|
|
|
|
|
|
| 232 |
|
| 233 |
tab1.select(lambda: 0, None, tab_select, queue=False)
|
| 234 |
tab2.select(lambda: 1, None, tab_select, queue=False)
|
| 235 |
+
input_gen_events = gr.Slider(label="generate n midi events", minimum=1, maximum=4096, step=1, value=512)
|
|
|
|
| 236 |
with gr.Accordion("options", open=False):
|
| 237 |
input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
|
| 238 |
input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.98)
|
| 239 |
input_top_k = gr.Slider(label="top k", minimum=1, maximum=20, step=1, value=12)
|
| 240 |
input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
|
| 241 |
+
input_amp = gr.Checkbox(label="enable amp", value=True)
|
| 242 |
example3 = gr.Examples([[1, 0.98, 12], [1.2, 0.95, 8]], [input_temp, input_top_p, input_top_k])
|
| 243 |
run_btn = gr.Button("generate", variant="primary")
|
| 244 |
stop_btn = gr.Button("stop and output")
|
| 245 |
output_midi_seq = gr.Variable()
|
| 246 |
+
output_midi_img = gr.Image(label="output image")
|
|
|
|
| 247 |
output_midi = gr.File(label="output midi", file_types=[".mid"])
|
| 248 |
+
output_audio = gr.Audio(label="output audio", format="mp3")
|
| 249 |
+
run_event = run_btn.click(run, [tab_select, input_instruments, input_drum_kit, input_midi, input_midi_events,
|
| 250 |
+
input_gen_events, input_temp, input_top_p, input_top_k,
|
| 251 |
+
input_allow_cc, input_amp],
|
| 252 |
+
[output_midi_seq, output_midi_img, output_midi, output_audio])
|
| 253 |
+
stop_btn.click(cancel_run, output_midi_seq, [output_midi, output_audio], cancels=run_event, queue=False)
|
| 254 |
+
app.queue(1).launch(server_port=opt.port)
|