Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- .gitattributes +1 -0
- app.py +30 -35
- canon.flac +3 -0
.gitattributes
CHANGED
|
@@ -29,3 +29,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 29 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 30 |
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
| 31 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 29 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 30 |
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
| 31 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
canon.flac filter=lfs diff=lfs merge=lfs -text
|
app.py
CHANGED
|
@@ -13,22 +13,18 @@ os.system("python3 -m pip install -e .")
|
|
| 13 |
os.system("python3 -m pip install --upgrade pip")
|
| 14 |
|
| 15 |
|
| 16 |
-
|
| 17 |
-
# install mt3
|
| 18 |
os.system("git clone --branch=main https://github.com/magenta/mt3")
|
| 19 |
os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp")
|
| 20 |
os.system("python3 -m pip install -e .")
|
| 21 |
os.system("pip install tensorflow_cpu")
|
| 22 |
-
#
|
| 23 |
os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
|
| 24 |
|
| 25 |
-
#
|
| 26 |
os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
|
| 27 |
|
| 28 |
-
#@title
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
|
| 33 |
|
| 34 |
import functools
|
|
@@ -45,7 +41,6 @@ import librosa
|
|
| 45 |
import note_seq
|
| 46 |
|
| 47 |
|
| 48 |
-
|
| 49 |
import seqio
|
| 50 |
import t5
|
| 51 |
import t5x
|
|
@@ -72,11 +67,11 @@ def upload_audio(audio, sample_rate):
|
|
| 72 |
|
| 73 |
|
| 74 |
class InferenceModel(object):
|
| 75 |
-
"""
|
| 76 |
|
| 77 |
def __init__(self, checkpoint_path, model_type='mt3'):
|
| 78 |
|
| 79 |
-
#
|
| 80 |
if model_type == 'ismir2021':
|
| 81 |
num_velocity_bins = 127
|
| 82 |
self.encoding_spec = note_sequences.NoteEncodingSpec
|
|
@@ -99,7 +94,7 @@ class InferenceModel(object):
|
|
| 99 |
self.partitioner = t5x.partitioning.PjitPartitioner(
|
| 100 |
model_parallel_submesh=None, num_partitions=1)
|
| 101 |
|
| 102 |
-
#
|
| 103 |
self.spectrogram_config = spectrograms.SpectrogramConfig()
|
| 104 |
self.codec = vocabularies.build_codec(
|
| 105 |
vocab_config=vocabularies.VocabularyConfig(
|
|
@@ -110,11 +105,11 @@ class InferenceModel(object):
|
|
| 110 |
'targets': seqio.Feature(vocabulary=self.vocabulary),
|
| 111 |
}
|
| 112 |
|
| 113 |
-
#
|
| 114 |
self._parse_gin(gin_files)
|
| 115 |
self.model = self._load_model()
|
| 116 |
|
| 117 |
-
#
|
| 118 |
self.restore_from_checkpoint(checkpoint_path)
|
| 119 |
|
| 120 |
@property
|
|
@@ -125,7 +120,7 @@ class InferenceModel(object):
|
|
| 125 |
}
|
| 126 |
|
| 127 |
def _parse_gin(self, gin_files):
|
| 128 |
-
"""
|
| 129 |
gin_bindings = [
|
| 130 |
'from __gin__ import dynamic_registration',
|
| 131 |
'from mt3 import vocabularies',
|
|
@@ -137,7 +132,7 @@ class InferenceModel(object):
|
|
| 137 |
gin_files, gin_bindings, finalize_config=False)
|
| 138 |
|
| 139 |
def _load_model(self):
|
| 140 |
-
"""
|
| 141 |
model_config = gin.get_configurable(network.T5Config)()
|
| 142 |
module = network.Transformer(config=model_config)
|
| 143 |
return models.ContinuousInputsEncoderDecoderModel(
|
|
@@ -149,7 +144,7 @@ class InferenceModel(object):
|
|
| 149 |
|
| 150 |
|
| 151 |
def restore_from_checkpoint(self, checkpoint_path):
|
| 152 |
-
"""
|
| 153 |
train_state_initializer = t5x.utils.TrainStateInitializer(
|
| 154 |
optimizer_def=self.model.optimizer_def,
|
| 155 |
init_fn=self.model.get_initial_variables,
|
|
@@ -166,7 +161,7 @@ class InferenceModel(object):
|
|
| 166 |
|
| 167 |
@functools.lru_cache()
|
| 168 |
def _get_predict_fn(self, train_state_axes):
|
| 169 |
-
"""
|
| 170 |
def partial_predict_fn(params, batch, decode_rng):
|
| 171 |
return self.model.predict_batch_with_aux(
|
| 172 |
params, batch, decoder_params={'decode_rng': None})
|
|
@@ -179,18 +174,18 @@ class InferenceModel(object):
|
|
| 179 |
)
|
| 180 |
|
| 181 |
def predict_tokens(self, batch, seed=0):
|
| 182 |
-
"""
|
| 183 |
prediction, _ = self._predict_fn(
|
| 184 |
-
|
| 185 |
return self.vocabulary.decode_tf(prediction).numpy()
|
| 186 |
|
| 187 |
def __call__(self, audio):
|
| 188 |
-
"""
|
| 189 |
|
| 190 |
-
|
| 191 |
-
audio
|
| 192 |
-
|
| 193 |
-
|
| 194 |
"""
|
| 195 |
ds = self.audio_to_dataset(audio)
|
| 196 |
ds = self.preprocess(ds)
|
|
@@ -211,7 +206,7 @@ class InferenceModel(object):
|
|
| 211 |
return result['est_ns']
|
| 212 |
|
| 213 |
def audio_to_dataset(self, audio):
|
| 214 |
-
"""
|
| 215 |
frames, frame_times = self._audio_to_frames(audio)
|
| 216 |
return tf.data.Dataset.from_tensors({
|
| 217 |
'inputs': frames,
|
|
@@ -219,7 +214,7 @@ class InferenceModel(object):
|
|
| 219 |
})
|
| 220 |
|
| 221 |
def _audio_to_frames(self, audio):
|
| 222 |
-
"""
|
| 223 |
frame_size = self.spectrogram_config.hop_width
|
| 224 |
padding = [0, frame_size - len(audio) % frame_size]
|
| 225 |
audio = np.pad(audio, padding, mode='constant')
|
|
@@ -236,7 +231,7 @@ class InferenceModel(object):
|
|
| 236 |
output_features=self.output_features,
|
| 237 |
feature_key='inputs',
|
| 238 |
additional_feature_keys=['input_times']),
|
| 239 |
-
#
|
| 240 |
preprocessors.add_dummy_targets,
|
| 241 |
functools.partial(
|
| 242 |
preprocessors.compute_spectrograms,
|
|
@@ -249,12 +244,12 @@ class InferenceModel(object):
|
|
| 249 |
def postprocess(self, tokens, example):
|
| 250 |
tokens = self._trim_eos(tokens)
|
| 251 |
start_time = example['input_times'][0]
|
| 252 |
-
#
|
| 253 |
start_time -= start_time % (1 / self.codec.steps_per_second)
|
| 254 |
return {
|
| 255 |
'est_tokens': tokens,
|
| 256 |
'start_time': start_time,
|
| 257 |
-
#
|
| 258 |
'raw_inputs': []
|
| 259 |
}
|
| 260 |
|
|
@@ -285,16 +280,16 @@ def inference(audio):
|
|
| 285 |
return './transcribed.mid'
|
| 286 |
|
| 287 |
title = "MT3"
|
| 288 |
-
description = "
|
| 289 |
|
| 290 |
-
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2111.03017' target='_blank'>MT3:
|
| 291 |
|
| 292 |
-
examples=[['download.wav']]
|
| 293 |
|
| 294 |
gr.Interface(
|
| 295 |
inference,
|
| 296 |
-
gr.inputs.Audio(type="filepath", label="
|
| 297 |
-
[gr.outputs.File(label="
|
| 298 |
title=title,
|
| 299 |
description=description,
|
| 300 |
article=article,
|
|
|
|
| 13 |
os.system("python3 -m pip install --upgrade pip")
|
| 14 |
|
| 15 |
|
| 16 |
+
# 安装 mt3
|
|
|
|
| 17 |
os.system("git clone --branch=main https://github.com/magenta/mt3")
|
| 18 |
os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp")
|
| 19 |
os.system("python3 -m pip install -e .")
|
| 20 |
os.system("pip install tensorflow_cpu")
|
| 21 |
+
# 复制检查点
|
| 22 |
os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
|
| 23 |
|
| 24 |
+
# 复制 soundfont 文件(原始文件来自 https://sites.google.com/site/soundfonts4u)
|
| 25 |
os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
|
| 26 |
|
| 27 |
+
#@title 导入和定义
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
import functools
|
|
|
|
| 41 |
import note_seq
|
| 42 |
|
| 43 |
|
|
|
|
| 44 |
import seqio
|
| 45 |
import t5
|
| 46 |
import t5x
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
class InferenceModel(object):
|
| 70 |
+
"""音乐转录的 T5X 模型包装器。"""
|
| 71 |
|
| 72 |
def __init__(self, checkpoint_path, model_type='mt3'):
|
| 73 |
|
| 74 |
+
# 模型常量。
|
| 75 |
if model_type == 'ismir2021':
|
| 76 |
num_velocity_bins = 127
|
| 77 |
self.encoding_spec = note_sequences.NoteEncodingSpec
|
|
|
|
| 94 |
self.partitioner = t5x.partitioning.PjitPartitioner(
|
| 95 |
model_parallel_submesh=None, num_partitions=1)
|
| 96 |
|
| 97 |
+
# 构建编解码器和词汇表。
|
| 98 |
self.spectrogram_config = spectrograms.SpectrogramConfig()
|
| 99 |
self.codec = vocabularies.build_codec(
|
| 100 |
vocab_config=vocabularies.VocabularyConfig(
|
|
|
|
| 105 |
'targets': seqio.Feature(vocabulary=self.vocabulary),
|
| 106 |
}
|
| 107 |
|
| 108 |
+
# 创建 T5X 模型。
|
| 109 |
self._parse_gin(gin_files)
|
| 110 |
self.model = self._load_model()
|
| 111 |
|
| 112 |
+
# 从检查点中恢复。
|
| 113 |
self.restore_from_checkpoint(checkpoint_path)
|
| 114 |
|
| 115 |
@property
|
|
|
|
| 120 |
}
|
| 121 |
|
| 122 |
def _parse_gin(self, gin_files):
|
| 123 |
+
"""解析用于训练模型的 gin 文件。"""
|
| 124 |
gin_bindings = [
|
| 125 |
'from __gin__ import dynamic_registration',
|
| 126 |
'from mt3 import vocabularies',
|
|
|
|
| 132 |
gin_files, gin_bindings, finalize_config=False)
|
| 133 |
|
| 134 |
def _load_model(self):
|
| 135 |
+
"""在解析训练 gin 配置后加载 T5X `Model`。"""
|
| 136 |
model_config = gin.get_configurable(network.T5Config)()
|
| 137 |
module = network.Transformer(config=model_config)
|
| 138 |
return models.ContinuousInputsEncoderDecoderModel(
|
|
|
|
| 144 |
|
| 145 |
|
| 146 |
def restore_from_checkpoint(self, checkpoint_path):
|
| 147 |
+
"""从检查点中恢复训练状态,重置 self._predict_fn()。"""
|
| 148 |
train_state_initializer = t5x.utils.TrainStateInitializer(
|
| 149 |
optimizer_def=self.model.optimizer_def,
|
| 150 |
init_fn=self.model.get_initial_variables,
|
|
|
|
| 161 |
|
| 162 |
@functools.lru_cache()
|
| 163 |
def _get_predict_fn(self, train_state_axes):
|
| 164 |
+
"""生成一个分区的预测函数用于解码。"""
|
| 165 |
def partial_predict_fn(params, batch, decode_rng):
|
| 166 |
return self.model.predict_batch_with_aux(
|
| 167 |
params, batch, decoder_params={'decode_rng': None})
|
|
|
|
| 174 |
)
|
| 175 |
|
| 176 |
def predict_tokens(self, batch, seed=0):
|
| 177 |
+
"""从预处理的数据集批次中预测 tokens。"""
|
| 178 |
prediction, _ = self._predict_fn(
|
| 179 |
+
self._train_state.params, batch, jax.random.PRNGKey(seed))
|
| 180 |
return self.vocabulary.decode_tf(prediction).numpy()
|
| 181 |
|
| 182 |
def __call__(self, audio):
|
| 183 |
+
"""从音频样本推断出音符序列。
|
| 184 |
|
| 185 |
+
参数:
|
| 186 |
+
audio:16kHz 的单个音频样本的 1 维 numpy 数组。
|
| 187 |
+
返回:
|
| 188 |
+
转录音频的音符序列。
|
| 189 |
"""
|
| 190 |
ds = self.audio_to_dataset(audio)
|
| 191 |
ds = self.preprocess(ds)
|
|
|
|
| 206 |
return result['est_ns']
|
| 207 |
|
| 208 |
def audio_to_dataset(self, audio):
|
| 209 |
+
"""从输入音频创建一个包含频谱图的 TF Dataset。"""
|
| 210 |
frames, frame_times = self._audio_to_frames(audio)
|
| 211 |
return tf.data.Dataset.from_tensors({
|
| 212 |
'inputs': frames,
|
|
|
|
| 214 |
})
|
| 215 |
|
| 216 |
def _audio_to_frames(self, audio):
|
| 217 |
+
"""从音频计算频谱图帧。"""
|
| 218 |
frame_size = self.spectrogram_config.hop_width
|
| 219 |
padding = [0, frame_size - len(audio) % frame_size]
|
| 220 |
audio = np.pad(audio, padding, mode='constant')
|
|
|
|
| 231 |
output_features=self.output_features,
|
| 232 |
feature_key='inputs',
|
| 233 |
additional_feature_keys=['input_times']),
|
| 234 |
+
# 在训练期间进行缓存。
|
| 235 |
preprocessors.add_dummy_targets,
|
| 236 |
functools.partial(
|
| 237 |
preprocessors.compute_spectrograms,
|
|
|
|
| 244 |
def postprocess(self, tokens, example):
|
| 245 |
tokens = self._trim_eos(tokens)
|
| 246 |
start_time = example['input_times'][0]
|
| 247 |
+
# 向下取整到最接近的符号化时间步。
|
| 248 |
start_time -= start_time % (1 / self.codec.steps_per_second)
|
| 249 |
return {
|
| 250 |
'est_tokens': tokens,
|
| 251 |
'start_time': start_time,
|
| 252 |
+
# 内部 MT3 代码期望原始输入,这里不使用。
|
| 253 |
'raw_inputs': []
|
| 254 |
}
|
| 255 |
|
|
|
|
| 280 |
return './transcribed.mid'
|
| 281 |
|
| 282 |
title = "MT3"
|
| 283 |
+
description = "MT3:多任务多音轨音乐转录的 Gradio 演示。要使用它,只需上传音频文件,或点击示例以加载它们。更多信息请参阅下面的链接。"
|
| 284 |
|
| 285 |
+
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2111.03017' target='_blank'>MT3: 多任务多音轨音乐转录</a> | <a href='https://github.com/magenta/mt3' target='_blank'>Github 仓库</a></p>"
|
| 286 |
|
| 287 |
+
examples=[['canon.flac'], ['download.wav']]
|
| 288 |
|
| 289 |
gr.Interface(
|
| 290 |
inference,
|
| 291 |
+
gr.inputs.Audio(type="filepath", label="输入"),
|
| 292 |
+
[gr.outputs.File(label="输出")],
|
| 293 |
title=title,
|
| 294 |
description=description,
|
| 295 |
article=article,
|
canon.flac
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d13c270188979b6840a736cbd85f5e1bdb12b1bdab3e35af8a4ae7eb2c1c80ac
|
| 3 |
+
size 6229211
|