Spaces:
Running
Running
File size: 7,776 Bytes
503b2cf fe0a0f7 503b2cf 7ea4f7d 503b2cf 7ea4f7d 503b2cf 7ea4f7d 1436450 55bec7f 503b2cf 7ea4f7d f8c391a 7ea4f7d 533246c 7ea4f7d 4ca7e3a 7ea4f7d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
import re
import os
import time
import torch
import shutil
import argparse
import warnings
import gradio as gr
from transformers import GPT2Config
from model import Patchilizer, TunesFormer
from convert import abc2xml, xml2, xml2img
from utils import (
PATCH_NUM_LAYERS,
PATCH_LENGTH,
CHAR_NUM_LAYERS,
PATCH_SIZE,
SHARE_WEIGHTS,
WEIGHTS_PATH,
TEMP_DIR,
TEYVAT,
DEVICE,
)
def get_args(parser: argparse.ArgumentParser):
parser.add_argument(
"-num_tunes",
type=int,
default=1,
help="the number of independently computed returned tunes",
)
parser.add_argument(
"-max_patch",
type=int,
default=128,
help="integer to define the maximum length in tokens of each tune",
)
parser.add_argument(
"-top_p",
type=float,
default=0.8,
help="float to define the tokens that are within the sample operation of text generation",
)
parser.add_argument(
"-top_k",
type=int,
default=8,
help="integer to define the tokens that are within the sample operation of text generation",
)
parser.add_argument(
"-temperature",
type=float,
default=1.2,
help="the temperature of the sampling operation",
)
parser.add_argument("-seed", type=int, default=None, help="seed for randomstate")
parser.add_argument(
"-show_control_code",
type=bool,
default=False,
help="whether to show control code",
)
return parser.parse_args()
def generate_music(args, region: str):
patchilizer = Patchilizer()
patch_config = GPT2Config(
num_hidden_layers=PATCH_NUM_LAYERS,
max_length=PATCH_LENGTH,
max_position_embeddings=PATCH_LENGTH,
vocab_size=1,
)
char_config = GPT2Config(
num_hidden_layers=CHAR_NUM_LAYERS,
max_length=PATCH_SIZE,
max_position_embeddings=PATCH_SIZE,
vocab_size=128,
)
model = TunesFormer(patch_config, char_config, share_weights=SHARE_WEIGHTS)
checkpoint = torch.load(WEIGHTS_PATH, map_location=torch.device("cpu"))
model.load_state_dict(checkpoint["model"])
model = model.to(DEVICE)
model.eval()
prompt = f"A:{region}\n"
tunes = ""
num_tunes = args.num_tunes
max_patch = args.max_patch
top_p = args.top_p
top_k = args.top_k
temperature = args.temperature
seed = args.seed
show_control_code = args.show_control_code
print(" Hyper parms ".center(60, "#"), "\n")
arg_dict: dict = vars(args)
for key in arg_dict.keys():
print(f"{key}: {str(arg_dict[key])}")
print("\n", " Output tunes ".center(60, "#"))
start_time = time.time()
for i in range(num_tunes):
title_artist = f"T:{region} Style Fragment\nC:Generated by AI\n"
tune = f"X:{str(i + 1)}\n{title_artist + prompt}"
lines = re.split(r"(\n)", tune)
tune = ""
skip = False
for line in lines:
if show_control_code or line[:2] not in ["S:", "B:", "E:"]:
if not skip:
print(line, end="")
tune += line
skip = False
else:
skip = True
input_patches = torch.tensor(
[patchilizer.encode(prompt, add_special_patches=True)[:-1]], device=DEVICE
)
if tune == "":
tokens = None
else:
prefix = patchilizer.decode(input_patches[0])
remaining_tokens = prompt[len(prefix) :]
tokens = torch.tensor(
[patchilizer.bos_token_id] + [ord(c) for c in remaining_tokens],
device=DEVICE,
)
while input_patches.shape[1] < max_patch:
predicted_patch, seed = model.generate(
input_patches,
tokens,
top_p=top_p,
top_k=top_k,
temperature=temperature,
seed=seed,
)
tokens = None
if predicted_patch[0] != patchilizer.eos_token_id:
next_bar = patchilizer.decode([predicted_patch])
if show_control_code or next_bar[:2] not in ["S:", "B:", "E:"]:
print(next_bar, end="")
tune += next_bar
if next_bar == "":
break
next_bar = remaining_tokens + next_bar
remaining_tokens = ""
predicted_patch = torch.tensor(
patchilizer.bar2patch(next_bar), device=DEVICE
).unsqueeze(0)
input_patches = torch.cat(
[input_patches, predicted_patch.unsqueeze(0)], dim=1
)
else:
break
tunes += f"{tune}\n\n"
print("\n")
print("Generation time: {:.2f} seconds".format(time.time() - start_time))
timestamp = time.strftime("%a_%d_%b_%Y_%H_%M_%S", time.localtime())
try:
xml = abc2xml(tunes, f"{TEMP_DIR}/[{region}]{timestamp}.musicxml")
midi = xml2(xml, "mid")
audio = xml2(xml, "wav")
pdf, jpg = xml2img(xml)
mxl = xml2(xml, "mxl")
return audio, midi, pdf, xml, mxl, tunes, jpg
except Exception as e:
print(f"Invalid abc generated: {e}, retrying...")
return generate_music(args, region)
def infer(p, k, t, region: str):
if os.path.exists(TEMP_DIR):
shutil.rmtree(TEMP_DIR)
os.makedirs(TEMP_DIR, exist_ok=True)
parser = argparse.ArgumentParser()
args = get_args(parser)
args.top_p = p
args.top_k = k
args.temperature = t
if region == "Natlan":
region = "Teyvat"
return generate_music(args, region)
if __name__ == "__main__":
warnings.filterwarnings("ignore")
gr.Interface(
fn=infer,
inputs=[
gr.Slider(0.01, 1.0, 0.8, step=0.01, label="Top-P sample"),
gr.Slider(0, 80, 8, step=1, label="Top-K sample (0=closed)"),
gr.Slider(0.01, 2.0, 1.2, step=0.01, label="Temperature"),
gr.Dropdown(
choices=TEYVAT,
value="Mondstadt",
label="Region",
),
],
outputs=[
gr.Audio(label="Audio", type="filepath"),
gr.File(label="Download MIDI"),
gr.File(label="Download PDF"),
gr.File(label="Download MusicXML"),
gr.File(label="Download MXL"),
gr.Textbox(label="ABC notation", show_copy_button=True),
gr.Image(label="Staff", type="filepath", show_share_button=False),
],
flagging_mode="never",
title="Genshin Music Generation",
description="""
Welcome to this space based on the Tunesformer open source project, which is totally free! The current model is still in debugging, the plan is in the Genshin Impact after the main line is killed, all countries and regions after all the characters are open, the second creation of the concert will be complete and the sample is balanced, at that time to re-fine-tune the model and add the reality of the style of screening to assist in the game of each country's output to strengthen the learning in order to enhance the output differentiation and quality. Note: Data engineering on the Star Rail is in operation, and will hopefully be baselined in the future as well with the mainline kill.<br>
Data source: <a href="https://musescore.org">MuseScore</a> Tags source: <a href="https://genshin-impact.fandom.com/wiki/Genshin_Impact_Wiki">Genshin Impact Wiki | Fandom</a> Model base: <a href="https://github.com/sander-wood/tunesformer">Tunesformer</a>
""",
).launch()
|