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
|
|
|
|
|
| 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 torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
import tqdm
|
| 15 |
+
from huggingface_hub import hf_hub_download
|
| 16 |
+
from transformers import DynamicCache
|
| 17 |
+
|
| 18 |
+
import MIDI
|
| 19 |
+
from midi_model import MIDIModel, MIDIModelConfig
|
| 20 |
+
from midi_synthesizer import MidiSynthesizer
|
| 21 |
+
|
| 22 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 23 |
+
in_space = os.getenv("SYSTEM") == "spaces"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@torch.inference_mode()
|
| 27 |
+
def generate(model: MIDIModel, prompt=None, batch_size=1, max_len=512, temp=1.0, top_p=0.98, top_k=20,
|
| 28 |
+
disable_patch_change=False, disable_control_change=False, disable_channels=None, generator=None):
|
| 29 |
+
tokenizer = model.tokenizer
|
| 30 |
+
if disable_channels is not None:
|
| 31 |
+
disable_channels = [tokenizer.parameter_ids["channel"][c] for c in disable_channels]
|
| 32 |
+
else:
|
| 33 |
+
disable_channels = []
|
| 34 |
+
max_token_seq = tokenizer.max_token_seq
|
| 35 |
+
if prompt is None:
|
| 36 |
+
input_tensor = torch.full((1, max_token_seq), tokenizer.pad_id, dtype=torch.long, device=model.device)
|
| 37 |
+
input_tensor[0, 0] = tokenizer.bos_id # bos
|
| 38 |
+
input_tensor = input_tensor.unsqueeze(0)
|
| 39 |
+
input_tensor = torch.cat([input_tensor] * batch_size, dim=0)
|
| 40 |
+
else:
|
| 41 |
+
if len(prompt.shape) == 2:
|
| 42 |
+
prompt = prompt[None, :]
|
| 43 |
+
prompt = np.repeat(prompt, repeats=batch_size, axis=0)
|
| 44 |
+
elif prompt.shape[0] == 1:
|
| 45 |
+
prompt = np.repeat(prompt, repeats=batch_size, axis=0)
|
| 46 |
+
elif len(prompt.shape) != 3 or prompt.shape[0] != batch_size:
|
| 47 |
+
raise ValueError(f"invalid shape for prompt, {prompt.shape}")
|
| 48 |
+
prompt = prompt[..., :max_token_seq]
|
| 49 |
+
if prompt.shape[-1] < max_token_seq:
|
| 50 |
+
prompt = np.pad(prompt, ((0, 0), (0, 0), (0, max_token_seq - prompt.shape[-1])),
|
| 51 |
+
mode="constant", constant_values=tokenizer.pad_id)
|
| 52 |
+
input_tensor = torch.from_numpy(prompt).to(dtype=torch.long, device=model.device)
|
| 53 |
+
cur_len = input_tensor.shape[1]
|
| 54 |
+
bar = tqdm.tqdm(desc="generating", total=max_len - cur_len, disable=in_space)
|
| 55 |
+
cache1 = DynamicCache()
|
| 56 |
+
past_len = 0
|
| 57 |
+
with bar:
|
| 58 |
+
while cur_len < max_len:
|
| 59 |
+
end = [False] * batch_size
|
| 60 |
+
hidden = model.forward(input_tensor[:, past_len:], cache=cache1)[:, -1]
|
| 61 |
+
next_token_seq = None
|
| 62 |
+
event_names = [""] * batch_size
|
| 63 |
+
cache2 = DynamicCache()
|
| 64 |
+
for i in range(max_token_seq):
|
| 65 |
+
mask = torch.zeros((batch_size, tokenizer.vocab_size), dtype=torch.int64, device=model.device)
|
| 66 |
+
for b in range(batch_size):
|
| 67 |
+
if end[b]:
|
| 68 |
+
mask[b, tokenizer.pad_id] = 1
|
| 69 |
+
continue
|
| 70 |
+
if i == 0:
|
| 71 |
+
mask_ids = list(tokenizer.event_ids.values()) + [tokenizer.eos_id]
|
| 72 |
+
if disable_patch_change:
|
| 73 |
+
mask_ids.remove(tokenizer.event_ids["patch_change"])
|
| 74 |
+
if disable_control_change:
|
| 75 |
+
mask_ids.remove(tokenizer.event_ids["control_change"])
|
| 76 |
+
mask[b, mask_ids] = 1
|
| 77 |
+
else:
|
| 78 |
+
param_names = tokenizer.events[event_names[b]]
|
| 79 |
+
if i > len(param_names):
|
| 80 |
+
mask[b, tokenizer.pad_id] = 1
|
| 81 |
+
continue
|
| 82 |
+
param_name = param_names[i - 1]
|
| 83 |
+
mask_ids = tokenizer.parameter_ids[param_name]
|
| 84 |
+
if param_name == "channel":
|
| 85 |
+
mask_ids = [i for i in mask_ids if i not in disable_channels]
|
| 86 |
+
mask[b, mask_ids] = 1
|
| 87 |
+
mask = mask.unsqueeze(1)
|
| 88 |
+
x = next_token_seq
|
| 89 |
+
if i != 0:
|
| 90 |
+
hidden = None
|
| 91 |
+
x = x[:, -1:]
|
| 92 |
+
logits = model.forward_token(hidden, x, cache=cache2)[:, -1:]
|
| 93 |
+
scores = torch.softmax(logits / temp, dim=-1) * mask
|
| 94 |
+
samples = model.sample_top_p_k(scores, top_p, top_k, generator=generator)
|
| 95 |
+
if i == 0:
|
| 96 |
+
next_token_seq = samples
|
| 97 |
+
for b in range(batch_size):
|
| 98 |
+
if end[b]:
|
| 99 |
+
continue
|
| 100 |
+
eid = samples[b].item()
|
| 101 |
+
if eid == tokenizer.eos_id:
|
| 102 |
+
end[b] = True
|
| 103 |
+
else:
|
| 104 |
+
event_names[b] = tokenizer.id_events[eid]
|
| 105 |
+
else:
|
| 106 |
+
next_token_seq = torch.cat([next_token_seq, samples], dim=1)
|
| 107 |
+
if all([len(tokenizer.events[event_names[b]]) == i for b in range(batch_size) if not end[b]]):
|
| 108 |
+
break
|
| 109 |
+
if next_token_seq.shape[1] < max_token_seq:
|
| 110 |
+
next_token_seq = F.pad(next_token_seq, (0, max_token_seq - next_token_seq.shape[1]),
|
| 111 |
+
"constant", value=tokenizer.pad_id)
|
| 112 |
+
next_token_seq = next_token_seq.unsqueeze(1)
|
| 113 |
+
input_tensor = torch.cat([input_tensor, next_token_seq], dim=1)
|
| 114 |
+
past_len = cur_len
|
| 115 |
+
cur_len += 1
|
| 116 |
+
bar.update(1)
|
| 117 |
+
yield next_token_seq[:, 0].cpu().numpy()
|
| 118 |
+
if all(end):
|
| 119 |
+
break
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def create_msg(name, data):
|
| 123 |
+
return {"name": name, "data": data}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def send_msgs(msgs):
|
| 127 |
+
return json.dumps(msgs)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_duration(model_name, tab, mid_seq, continuation_state, continuation_select, instruments, drum_kit, bpm,
|
| 131 |
+
time_sig, key_sig, mid, midi_events, reduce_cc_st, remap_track_channel, add_default_instr,
|
| 132 |
+
remove_empty_channels, seed, seed_rand, gen_events, temp, top_p, top_k, allow_cc):
|
| 133 |
+
t = gen_events // 23
|
| 134 |
+
if "large" in model_name:
|
| 135 |
+
t = gen_events // 14
|
| 136 |
+
return t + 5
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@spaces.GPU(duration=get_duration)
|
| 140 |
+
def run(model_name, tab, mid_seq, continuation_state, continuation_select, instruments, drum_kit, bpm, time_sig,
|
| 141 |
+
key_sig, mid, midi_events, reduce_cc_st, remap_track_channel, add_default_instr, remove_empty_channels,
|
| 142 |
+
seed, seed_rand, gen_events, temp, top_p, top_k, allow_cc):
|
| 143 |
+
model = models[model_name]
|
| 144 |
+
model.to(device=opt.device)
|
| 145 |
+
tokenizer = model.tokenizer
|
| 146 |
+
bpm = int(bpm)
|
| 147 |
+
if time_sig == "auto":
|
| 148 |
+
time_sig = None
|
| 149 |
+
time_sig_nn = 4
|
| 150 |
+
time_sig_dd = 2
|
| 151 |
+
else:
|
| 152 |
+
time_sig_nn, time_sig_dd = time_sig.split('/')
|
| 153 |
+
time_sig_nn = int(time_sig_nn)
|
| 154 |
+
time_sig_dd = {2: 1, 4: 2, 8: 3}[int(time_sig_dd)]
|
| 155 |
+
if key_sig == 0:
|
| 156 |
+
key_sig = None
|
| 157 |
+
key_sig_sf = 0
|
| 158 |
+
key_sig_mi = 0
|
| 159 |
+
else:
|
| 160 |
+
key_sig = (key_sig - 1)
|
| 161 |
+
key_sig_sf = key_sig // 2 - 7
|
| 162 |
+
key_sig_mi = key_sig % 2
|
| 163 |
+
gen_events = int(gen_events)
|
| 164 |
+
max_len = gen_events
|
| 165 |
+
if seed_rand:
|
| 166 |
+
seed = random.randint(0, MAX_SEED)
|
| 167 |
+
generator = torch.Generator(opt.device).manual_seed(seed)
|
| 168 |
+
disable_patch_change = False
|
| 169 |
+
disable_channels = None
|
| 170 |
+
if tab == 0:
|
| 171 |
+
i = 0
|
| 172 |
+
mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
|
| 173 |
+
if tokenizer.version == "v2":
|
| 174 |
+
if time_sig is not None:
|
| 175 |
+
mid.append(tokenizer.event2tokens(["time_signature", 0, 0, 0, time_sig_nn - 1, time_sig_dd - 1]))
|
| 176 |
+
if key_sig is not None:
|
| 177 |
+
mid.append(tokenizer.event2tokens(["key_signature", 0, 0, 0, key_sig_sf + 7, key_sig_mi]))
|
| 178 |
+
if bpm != 0:
|
| 179 |
+
mid.append(tokenizer.event2tokens(["set_tempo", 0, 0, 0, bpm]))
|
| 180 |
+
patches = {}
|
| 181 |
+
if instruments is None:
|
| 182 |
+
instruments = []
|
| 183 |
+
for instr in instruments:
|
| 184 |
+
patches[i] = patch2number[instr]
|
| 185 |
+
i = (i + 1) if i != 8 else 10
|
| 186 |
+
if drum_kit != "None":
|
| 187 |
+
patches[9] = drum_kits2number[drum_kit]
|
| 188 |
+
for i, (c, p) in enumerate(patches.items()):
|
| 189 |
+
mid.append(tokenizer.event2tokens(["patch_change", 0, 0, i + 1, c, p]))
|
| 190 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
| 191 |
+
mid_seq = mid.tolist()
|
| 192 |
+
if len(instruments) > 0:
|
| 193 |
+
disable_patch_change = True
|
| 194 |
+
disable_channels = [i for i in range(16) if i not in patches]
|
| 195 |
+
elif tab == 1 and mid is not None:
|
| 196 |
+
eps = 4 if reduce_cc_st else 0
|
| 197 |
+
mid = tokenizer.tokenize(MIDI.midi2score(mid), cc_eps=eps, tempo_eps=eps,
|
| 198 |
+
remap_track_channel=remap_track_channel,
|
| 199 |
+
add_default_instr=add_default_instr,
|
| 200 |
+
remove_empty_channels=remove_empty_channels)
|
| 201 |
+
mid = mid[:int(midi_events)]
|
| 202 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
| 203 |
+
mid_seq = mid.tolist()
|
| 204 |
+
elif tab == 2 and mid_seq is not None:
|
| 205 |
+
mid = np.asarray(mid_seq, dtype=np.int64)
|
| 206 |
+
if continuation_select > 0:
|
| 207 |
+
continuation_state.append(mid_seq)
|
| 208 |
+
mid = np.repeat(mid[continuation_select - 1:continuation_select], repeats=OUTPUT_BATCH_SIZE, axis=0)
|
| 209 |
+
mid_seq = mid.tolist()
|
| 210 |
+
else:
|
| 211 |
+
continuation_state.append(mid.shape[1])
|
| 212 |
+
else:
|
| 213 |
+
continuation_state = [0]
|
| 214 |
+
mid = [[tokenizer.bos_id] + [tokenizer.pad_id] * (tokenizer.max_token_seq - 1)]
|
| 215 |
+
mid = np.asarray([mid] * OUTPUT_BATCH_SIZE, dtype=np.int64)
|
| 216 |
+
mid_seq = mid.tolist()
|
| 217 |
+
|
| 218 |
+
if mid is not None:
|
| 219 |
+
max_len += mid.shape[1]
|
| 220 |
+
|
| 221 |
+
init_msgs = [create_msg("progress", [0, gen_events])]
|
| 222 |
+
if not (tab == 2 and continuation_select == 0):
|
| 223 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
| 224 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
| 225 |
+
init_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
| 226 |
+
create_msg("visualizer_append", [i, events])]
|
| 227 |
+
yield mid_seq, continuation_state, seed, send_msgs(init_msgs)
|
| 228 |
+
midi_generator = generate(model, mid, batch_size=OUTPUT_BATCH_SIZE, max_len=max_len, temp=temp,
|
| 229 |
+
top_p=top_p, top_k=top_k, disable_patch_change=disable_patch_change,
|
| 230 |
+
disable_control_change=not allow_cc, disable_channels=disable_channels,
|
| 231 |
+
generator=generator)
|
| 232 |
+
events = [list() for i in range(OUTPUT_BATCH_SIZE)]
|
| 233 |
+
t = time.time() + 1
|
| 234 |
+
for i, token_seqs in enumerate(midi_generator):
|
| 235 |
+
token_seqs = token_seqs.tolist()
|
| 236 |
+
for j in range(OUTPUT_BATCH_SIZE):
|
| 237 |
+
token_seq = token_seqs[j]
|
| 238 |
+
mid_seq[j].append(token_seq)
|
| 239 |
+
events[j].append(tokenizer.tokens2event(token_seq))
|
| 240 |
+
if time.time() - t > 0.5:
|
| 241 |
+
msgs = [create_msg("progress", [i + 1, gen_events])]
|
| 242 |
+
for j in range(OUTPUT_BATCH_SIZE):
|
| 243 |
+
msgs += [create_msg("visualizer_append", [j, events[j]])]
|
| 244 |
+
events[j] = list()
|
| 245 |
+
yield mid_seq, continuation_state, seed, send_msgs(msgs)
|
| 246 |
+
t = time.time()
|
| 247 |
+
yield mid_seq, continuation_state, seed, send_msgs([])
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def finish_run(model_name, mid_seq):
|
| 251 |
+
if mid_seq is None:
|
| 252 |
+
outputs = [None] * OUTPUT_BATCH_SIZE
|
| 253 |
+
return *outputs, []
|
| 254 |
+
tokenizer = models[model_name].tokenizer
|
| 255 |
+
outputs = []
|
| 256 |
+
end_msgs = [create_msg("progress", [0, 0])]
|
| 257 |
+
if not os.path.exists("outputs"):
|
| 258 |
+
os.mkdir("outputs")
|
| 259 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
| 260 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
| 261 |
+
mid = tokenizer.detokenize(mid_seq[i])
|
| 262 |
+
with open(f"outputs/output{i + 1}.mid", 'wb') as f:
|
| 263 |
+
f.write(MIDI.score2midi(mid))
|
| 264 |
+
outputs.append(f"outputs/output{i + 1}.mid")
|
| 265 |
+
end_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
| 266 |
+
create_msg("visualizer_append", [i, events]),
|
| 267 |
+
create_msg("visualizer_end", i)]
|
| 268 |
+
return *outputs, send_msgs(end_msgs)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def synthesis_task(mid):
|
| 272 |
+
return synthesizer.synthesis(MIDI.score2opus(mid))
|
| 273 |
+
|
| 274 |
+
def render_audio(model_name, mid_seq, should_render_audio):
|
| 275 |
+
if (not should_render_audio) or mid_seq is None:
|
| 276 |
+
outputs = [None] * OUTPUT_BATCH_SIZE
|
| 277 |
+
return tuple(outputs)
|
| 278 |
+
tokenizer = models[model_name].tokenizer
|
| 279 |
+
outputs = []
|
| 280 |
+
if not os.path.exists("outputs"):
|
| 281 |
+
os.mkdir("outputs")
|
| 282 |
+
audio_futures = []
|
| 283 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
| 284 |
+
mid = tokenizer.detokenize(mid_seq[i])
|
| 285 |
+
audio_future = thread_pool.submit(synthesis_task, mid)
|
| 286 |
+
audio_futures.append(audio_future)
|
| 287 |
+
for future in audio_futures:
|
| 288 |
+
outputs.append((44100, future.result()))
|
| 289 |
+
if OUTPUT_BATCH_SIZE == 1:
|
| 290 |
+
return outputs[0]
|
| 291 |
+
return tuple(outputs)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def undo_continuation(model_name, mid_seq, continuation_state):
|
| 295 |
+
if mid_seq is None or len(continuation_state) < 2:
|
| 296 |
+
return mid_seq, continuation_state, send_msgs([])
|
| 297 |
+
tokenizer = models[model_name].tokenizer
|
| 298 |
+
if isinstance(continuation_state[-1], list):
|
| 299 |
+
mid_seq = continuation_state[-1]
|
| 300 |
+
else:
|
| 301 |
+
mid_seq = [ms[:continuation_state[-1]] for ms in mid_seq]
|
| 302 |
+
continuation_state = continuation_state[:-1]
|
| 303 |
+
end_msgs = [create_msg("progress", [0, 0])]
|
| 304 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
| 305 |
+
events = [tokenizer.tokens2event(tokens) for tokens in mid_seq[i]]
|
| 306 |
+
end_msgs += [create_msg("visualizer_clear", [i, tokenizer.version]),
|
| 307 |
+
create_msg("visualizer_append", [i, events]),
|
| 308 |
+
create_msg("visualizer_end", i)]
|
| 309 |
+
return mid_seq, continuation_state, send_msgs(end_msgs)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def load_javascript(dir="javascript"):
|
| 313 |
+
scripts_list = glob.glob(f"{dir}/*.js")
|
| 314 |
+
javascript = ""
|
| 315 |
+
for path in scripts_list:
|
| 316 |
+
with open(path, "r", encoding="utf8") as jsfile:
|
| 317 |
+
js_content = jsfile.read()
|
| 318 |
+
js_content = js_content.replace("const MIDI_OUTPUT_BATCH_SIZE=4;",
|
| 319 |
+
f"const MIDI_OUTPUT_BATCH_SIZE={OUTPUT_BATCH_SIZE};")
|
| 320 |
+
javascript += f"\n<!-- {path} --><script>{js_content}</script>"
|
| 321 |
+
template_response_ori = gr.routes.templates.TemplateResponse
|
| 322 |
+
|
| 323 |
+
def template_response(*args, **kwargs):
|
| 324 |
+
res = template_response_ori(*args, **kwargs)
|
| 325 |
+
res.body = res.body.replace(
|
| 326 |
+
b'</head>', f'{javascript}</head>'.encode("utf8"))
|
| 327 |
+
res.init_headers()
|
| 328 |
+
return res
|
| 329 |
+
|
| 330 |
+
gr.routes.templates.TemplateResponse = template_response
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def hf_hub_download_retry(repo_id, filename):
|
| 334 |
+
print(f"downloading {repo_id} {filename}")
|
| 335 |
+
retry = 0
|
| 336 |
+
err = None
|
| 337 |
+
while retry < 30:
|
| 338 |
+
try:
|
| 339 |
+
return hf_hub_download(repo_id=repo_id, filename=filename)
|
| 340 |
+
except Exception as e:
|
| 341 |
+
err = e
|
| 342 |
+
retry += 1
|
| 343 |
+
if err:
|
| 344 |
+
raise err
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
number2drum_kits = {-1: "None", 0: "Standard", 8: "Room", 16: "Power", 24: "Electric", 25: "TR-808", 32: "Jazz",
|
| 348 |
+
40: "Blush", 48: "Orchestra"}
|
| 349 |
+
patch2number = {v: k for k, v in MIDI.Number2patch.items()}
|
| 350 |
+
drum_kits2number = {v: k for k, v in number2drum_kits.items()}
|
| 351 |
+
key_signatures = ['C♭', 'A♭m', 'G♭', 'E♭m', 'D♭', 'B♭m', 'A♭', 'Fm', 'E♭', 'Cm', 'B♭', 'Gm', 'F', 'Dm',
|
| 352 |
+
'C', 'Am', 'G', 'Em', 'D', 'Bm', 'A', 'F♯m', 'E', 'C♯m', 'B', 'G♯m', 'F♯', 'D♯m', 'C♯', 'A♯m']
|
| 353 |
+
|
| 354 |
+
if __name__ == "__main__":
|
| 355 |
+
parser = argparse.ArgumentParser()
|
| 356 |
+
parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
|
| 357 |
+
parser.add_argument("--port", type=int, default=7860, help="gradio server port")
|
| 358 |
+
parser.add_argument("--device", type=str, default="cuda", help="device to run model")
|
| 359 |
+
parser.add_argument("--batch", type=int, default=8, help="batch size")
|
| 360 |
+
parser.add_argument("--max-gen", type=int, default=1024, help="max")
|
| 361 |
+
opt = parser.parse_args()
|
| 362 |
+
OUTPUT_BATCH_SIZE = opt.batch
|
| 363 |
+
soundfont_path = hf_hub_download_retry(repo_id="skytnt/midi-model", filename="soundfont.sf2")
|
| 364 |
+
thread_pool = ThreadPoolExecutor(max_workers=OUTPUT_BATCH_SIZE)
|
| 365 |
+
synthesizer = MidiSynthesizer(soundfont_path)
|
| 366 |
+
models_info = {
|
| 367 |
+
"generic pretrain model (tv2o-medium) by skytnt": [
|
| 368 |
+
"skytnt/midi-model-tv2o-medium", {
|
| 369 |
+
"jpop": "skytnt/midi-model-tv2om-jpop-lora",
|
| 370 |
+
"touhou": "skytnt/midi-model-tv2om-touhou-lora"
|
| 371 |
+
}
|
| 372 |
+
],
|
| 373 |
+
"generic pretrain model (tv2o-large) by asigalov61": [
|
| 374 |
+
"asigalov61/Music-Llama", {}
|
| 375 |
+
],
|
| 376 |
+
"generic pretrain model (tv2o-medium) by asigalov61": [
|
| 377 |
+
"asigalov61/Music-Llama-Medium", {}
|
| 378 |
+
],
|
| 379 |
+
"generic pretrain model (tv1-medium) by skytnt": [
|
| 380 |
+
"skytnt/midi-model", {}
|
| 381 |
+
],
|
| 382 |
+
"custom model test": [
|
| 383 |
+
"skytnt/midi-model", {}
|
| 384 |
+
]
|
| 385 |
+
}
|
| 386 |
+
models = {}
|
| 387 |
+
if opt.device == "cuda":
|
| 388 |
+
torch.backends.cudnn.deterministic = True
|
| 389 |
+
torch.backends.cudnn.benchmark = False
|
| 390 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 391 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 392 |
+
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
| 393 |
+
torch.backends.cuda.enable_flash_sdp(True)
|
| 394 |
+
for name, (repo_id, loras) in models_info.items():
|
| 395 |
+
model = MIDIModel.from_pretrained(repo_id)
|
| 396 |
+
model.to(device="cpu", dtype=torch.float32)
|
| 397 |
+
models[name] = model
|
| 398 |
+
for lora_name, lora_repo in loras.items():
|
| 399 |
+
model = MIDIModel.from_pretrained(repo_id)
|
| 400 |
+
print(f"loading lora {lora_repo} for {name}")
|
| 401 |
+
model = model.load_merge_lora(lora_repo)
|
| 402 |
+
model.to(device="cpu", dtype=torch.float32)
|
| 403 |
+
models[f"{name} with {lora_name} lora"] = model
|
| 404 |
+
|
| 405 |
+
load_javascript()
|
| 406 |
+
app = gr.Blocks(theme=gr.themes.Soft())
|
| 407 |
+
with app:
|
| 408 |
+
gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Midi Composer</h1>")
|
| 409 |
+
gr.Markdown(
|
| 410 |
+
"A modified version of the Midi-Generator for the IAT-360 Course by Ethan Lum\n\n"
|
| 411 |
+
"Demo for [SkyTNT/midi-model](https://github.com/SkyTNT/midi-model)\n\n"
|
| 412 |
+
"[Open In Colab]"
|
| 413 |
+
"(https://colab.research.google.com/github/SkyTNT/midi-model/blob/main/demo.ipynb)"
|
| 414 |
+
" or [download windows app](https://github.com/SkyTNT/midi-model/releases)"
|
| 415 |
+
" for unlimited generation\n\n"
|
| 416 |
+
)
|
| 417 |
+
js_msg = gr.Textbox(elem_id="msg_receiver", visible=False)
|
| 418 |
+
js_msg.change(None, [js_msg], [], js="""
|
| 419 |
+
(msg_json) =>{
|
| 420 |
+
let msgs = JSON.parse(msg_json);
|
| 421 |
+
executeCallbacks(msgReceiveCallbacks, msgs);
|
| 422 |
+
return [];
|
| 423 |
+
}
|
| 424 |
+
""")
|
| 425 |
+
input_model = gr.Dropdown(label="select model", choices=list(models.keys()),
|
| 426 |
+
type="value", value=list(models.keys())[0])
|
| 427 |
+
tab_select = gr.State(value=0)
|
| 428 |
+
with gr.Tabs():
|
| 429 |
+
|
| 430 |
+
with gr.TabItem("midi prompt") as tab1:
|
| 431 |
+
input_midi = gr.File(label="input midi", file_types=[".midi", ".mid"], type="binary")
|
| 432 |
+
input_midi_events = gr.Slider(label="use first n midi events as prompt", minimum=1, maximum=512,
|
| 433 |
+
step=1,
|
| 434 |
+
value=128)
|
| 435 |
+
input_reduce_cc_st = gr.Checkbox(label="reduce control_change and set_tempo events", value=True)
|
| 436 |
+
input_remap_track_channel = gr.Checkbox(
|
| 437 |
+
label="remap tracks and channels so each track has only one channel and in order", value=True)
|
| 438 |
+
input_add_default_instr = gr.Checkbox(
|
| 439 |
+
label="add a default instrument to channels that don't have an instrument", value=True)
|
| 440 |
+
input_remove_empty_channels = gr.Checkbox(label="remove channels without notes", value=False)
|
| 441 |
+
example2 = gr.Examples([[file, 128] for file in glob.glob("example/*.mid")],
|
| 442 |
+
[input_midi, input_midi_events])
|
| 443 |
+
with gr.TabItem("last output prompt") as tab3:
|
| 444 |
+
gr.Markdown("Continue generating on the last output.")
|
| 445 |
+
input_continuation_select = gr.Radio(label="select output to continue generating", value="all",
|
| 446 |
+
choices=["all"] + [f"output{i + 1}" for i in
|
| 447 |
+
range(OUTPUT_BATCH_SIZE)],
|
| 448 |
+
type="index"
|
| 449 |
+
)
|
| 450 |
+
undo_btn = gr.Button("undo the last continuation")
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
tab1.select(lambda: 1, None, tab_select, queue=False)
|
| 454 |
+
tab3.select(lambda: 2, None, tab_select, queue=False)
|
| 455 |
+
input_seed = gr.Slider(label="seed", minimum=0, maximum=2 ** 31 - 1,
|
| 456 |
+
step=1, value=0)
|
| 457 |
+
input_seed_rand = gr.Checkbox(label="random seed", value=True)
|
| 458 |
+
input_gen_events = gr.Slider(label="generate max n midi events", minimum=1, maximum=opt.max_gen,
|
| 459 |
+
step=1, value=opt.max_gen // 2)
|
| 460 |
+
with gr.Accordion("options", open=False):
|
| 461 |
+
input_temp = gr.Slider(label="temperature", minimum=0.1, maximum=1.2, step=0.01, value=1)
|
| 462 |
+
input_top_p = gr.Slider(label="top p", minimum=0.1, maximum=1, step=0.01, value=0.95)
|
| 463 |
+
input_top_k = gr.Slider(label="top k", minimum=1, maximum=128, step=1, value=20)
|
| 464 |
+
input_allow_cc = gr.Checkbox(label="allow midi cc event", value=True)
|
| 465 |
+
input_render_audio = gr.Checkbox(label="render audio after generation", value=True)
|
| 466 |
+
example3 = gr.Examples([[1, 0.94, 128], [1, 0.98, 20], [1, 0.98, 12]],
|
| 467 |
+
[input_temp, input_top_p, input_top_k])
|
| 468 |
+
run_btn = gr.Button("generate", variant="primary")
|
| 469 |
+
# stop_btn = gr.Button("stop and output")
|
| 470 |
+
output_midi_seq = gr.State()
|
| 471 |
+
output_continuation_state = gr.State([0])
|
| 472 |
+
midi_outputs = []
|
| 473 |
+
audio_outputs = []
|
| 474 |
+
with gr.Tabs(elem_id="output_tabs"):
|
| 475 |
+
for i in range(OUTPUT_BATCH_SIZE):
|
| 476 |
+
with gr.TabItem(f"output {i + 1}") as tab1:
|
| 477 |
+
output_midi_visualizer = gr.HTML(elem_id=f"midi_visualizer_container_{i}")
|
| 478 |
+
output_audio = gr.Audio(label="output audio", format="mp3", elem_id=f"midi_audio_{i}")
|
| 479 |
+
output_midi = gr.File(label="output midi", file_types=[".mid"])
|
| 480 |
+
midi_outputs.append(output_midi)
|
| 481 |
+
audio_outputs.append(output_audio)
|
| 482 |
+
run_event = run_btn.click(run, [input_model, tab_select, output_midi_seq, output_continuation_state,
|
| 483 |
+
input_continuation_select, input_instruments, input_drum_kit, input_bpm,
|
| 484 |
+
input_time_sig, input_key_sig, input_midi, input_midi_events,
|
| 485 |
+
input_reduce_cc_st, input_remap_track_channel,
|
| 486 |
+
input_add_default_instr, input_remove_empty_channels,
|
| 487 |
+
input_seed, input_seed_rand, input_gen_events, input_temp, input_top_p,
|
| 488 |
+
input_top_k, input_allow_cc],
|
| 489 |
+
[output_midi_seq, output_continuation_state, input_seed, js_msg], queue=True)
|
| 490 |
+
finish_run_event = run_event.then(fn=finish_run,
|
| 491 |
+
inputs=[input_model, output_midi_seq],
|
| 492 |
+
outputs=midi_outputs + [js_msg],
|
| 493 |
+
queue=False)
|
| 494 |
+
finish_run_event.then(fn=render_audio,
|
| 495 |
+
inputs=[input_model, output_midi_seq, input_render_audio],
|
| 496 |
+
outputs=audio_outputs,
|
| 497 |
+
queue=False)
|
| 498 |
+
# stop_btn.click(None, [], [], cancels=run_event,
|
| 499 |
+
# queue=False)
|
| 500 |
+
undo_btn.click(undo_continuation, [input_model, output_midi_seq, output_continuation_state],
|
| 501 |
+
[output_midi_seq, output_continuation_state, js_msg], queue=False)
|
| 502 |
+
app.queue().launch(server_port=opt.port, share=opt.share, inbrowser=True, ssr_mode=False)
|
| 503 |
+
thread_pool.shutdown()
|