Hmjz100 commited on
Commit
c974b7f
·
verified ·
1 Parent(s): 6ea0ebc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -222
app.py CHANGED
@@ -1,35 +1,70 @@
1
- import os
2
- os.system("pip install gradio")
3
-
4
  import gradio as gr
 
 
 
5
  from pathlib import Path
6
- os.system("pip install gsutil")
7
- os.system("​​​pip install glob2​​​")
8
- import glob2
9
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
11
  os.system("git clone --branch=main https://github.com/google-research/t5x")
 
12
  os.system("mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp")
 
13
  os.system("sed -i 's:jax\[tpu\]:jax:' setup.py")
 
14
  os.system("python3 -m pip install -e .")
 
15
  os.system("python3 -m pip install --upgrade pip")
16
-
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # 安装 mt3
 
19
  os.system("git clone --branch=main https://github.com/magenta/mt3")
 
20
  os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp")
 
 
 
21
  os.system("python3 -m pip install -e .")
 
22
  os.system("pip install tensorflow_cpu")
 
23
  # 复制检查点
 
24
  os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
25
 
26
  # 复制 soundfont 文件(原始文件来自 https://sites.google.com/site/soundfonts4u)
 
27
  os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
28
 
29
  #@title 导入和定义
 
30
  import functools
31
  import os
32
-
33
  import numpy as np
34
  import tensorflow.compat.v2 as tf
35
 
@@ -42,6 +77,7 @@ import note_seq
42
  import seqio
43
  import t5
44
  import t5x
 
45
 
46
  from mt3 import metrics_utils
47
  from mt3 import models
@@ -57,228 +93,241 @@ nest_asyncio.apply()
57
  SAMPLE_RATE = 16000
58
  SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
59
 
60
- def callbak_audio(audio, sample_rate):
61
- return note_seq.audio_io.wav_data_to_samples_librosa(
62
- audio, sample_rate=sample_rate)
63
 
 
 
64
  class InferenceModel(object):
65
- """音乐转录的 T5X 模型包装器。"""
66
-
67
- def __init__(self, checkpoint_path, model_type='mt3'):
68
-
69
- # 模型常量。
70
- if model_type == 'ismir2021':
71
- num_velocity_bins = 127
72
- self.encoding_spec = note_sequences.NoteEncodingSpec
73
- self.inputs_length = 512
74
- elif model_type == 'mt3':
75
- num_velocity_bins = 1
76
- self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
77
- self.inputs_length = 256
78
- else:
79
- raise ValueError('unknown model_type: %s' % model_type)
80
-
81
- gin_files = ['/home/user/app/mt3/gin/model.gin',
82
- '/home/user/app/mt3/gin/mt3.gin']
83
-
84
- self.batch_size = 8
85
- self.outputs_length = 1024
86
- self.sequence_length = {'inputs': self.inputs_length,
87
- 'targets': self.outputs_length}
88
-
89
- self.partitioner = t5x.partitioning.PjitPartitioner(
90
- model_parallel_submesh=(1, 1, 1, 1))
91
-
92
- # 构建编解码器和词汇表。
93
- self.spectrogram_config = spectrograms.SpectrogramConfig()
94
- self.codec = vocabularies.build_codec(
95
- vocab_config=vocabularies.VocabularyConfig(
96
- num_velocity_bins=num_velocity_bins))
97
- self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
98
- self.output_features = {
99
- 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
100
- 'targets': seqio.Feature(vocabulary=self.vocabulary),
101
- }
102
-
103
- # 创建 T5X 模型。
104
- self._parse_gin(gin_files)
105
- self.model = self._load_model()
106
-
107
- # 从检查点中恢复。
108
- self.restore_from_checkpoint(checkpoint_path)
109
-
110
- @property
111
- def input_shapes(self):
112
- return {
113
- 'encoder_input_tokens': (self.batch_size, self.inputs_length),
114
- 'decoder_input_tokens': (self.batch_size, self.outputs_length)
115
- }
116
-
117
- def _parse_gin(self, gin_files):
118
- """解析用于训练模型的 gin 文件。"""
119
- gin_bindings = [
120
- 'from __gin__ import dynamic_registration',
121
- 'from mt3 import vocabularies',
122
123
- 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
124
- ]
125
- with gin.unlock_config():
126
- gin.parse_config_files_and_bindings(
127
- gin_files, gin_bindings, finalize_config=False)
128
-
129
- def _load_model(self):
130
- """在解析训练 gin 配置后加载 T5X `Model`。"""
131
- model_config = gin.get_configurable(network.T5Config)()
132
- module = network.Transformer(config=model_config)
133
- return models.ContinuousInputsEncoderDecoderModel(
134
- module=module,
135
- input_vocabulary=self.output_features['inputs'].vocabulary,
136
- output_vocabulary=self.output_features['targets'].vocabulary,
137
- optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
138
- input_depth=spectrograms.input_depth(self.spectrogram_config))
139
-
140
-
141
- def restore_from_checkpoint(self, checkpoint_path):
142
- """从检查点中恢复训练状态,重置 self._predict_fn()。"""
143
- train_state_initializer = t5x.utils.TrainStateInitializer(
144
- optimizer_def=self.model.optimizer_def,
145
- init_fn=self.model.get_initial_variables,
146
- input_shapes=self.input_shapes,
147
- partitioner=self.partitioner)
148
-
149
- restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
150
- path=checkpoint_path, mode='specific', dtype='float32')
151
-
152
- train_state_axes = train_state_initializer.train_state_axes
153
- self._predict_fn = self._get_predict_fn(train_state_axes)
154
- self._train_state = train_state_initializer.from_checkpoint_or_scratch(
155
- [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
156
-
157
- @functools.lru_cache()
158
- def _get_predict_fn(self, train_state_axes):
159
- """生成一个分区的预测函数用于解码。"""
160
- def partial_predict_fn(params, batch, decode_rng):
161
- return self.model.predict_batch_with_aux(
162
- params, batch, decoder_params={'decode_rng': None})
163
- return self.partitioner.partition(
164
- partial_predict_fn,
165
- in_axis_resources=(
166
- train_state_axes.params,
167
- t5x.partitioning.PartitionSpec('data',), None),
168
- out_axis_resources=t5x.partitioning.PartitionSpec('data',)
169
- )
170
-
171
- def predict_tokens(self, batch, seed=0):
172
- """从预处理的数据集批次中预测 tokens。"""
173
- prediction, _ = self._predict_fn(
174
- self._train_state.params, batch, jax.random.PRNGKey(seed))
175
- return self.vocabulary.decode_tf(prediction).numpy()
176
-
177
- def __call__(self, audio):
178
- """从音频样本推断出音符序列。
179
-
180
- 参数:
181
- audio:16kHz 的单个音频样本的 1 维 numpy 数组。
182
- 返回:
183
- 转录音频的音符序列。
184
- """
185
- ds = self.audio_to_dataset(audio)
186
- ds = self.preprocess(ds)
187
-
188
- model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
189
- ds, task_feature_lengths=self.sequence_length)
190
- model_ds = model_ds.batch(self.batch_size)
191
-
192
- inferences = (tokens for batch in model_ds.as_numpy_iterator()
193
- for tokens in self.predict_tokens(batch))
194
-
195
- predictions = []
196
- for example, tokens in zip(ds.as_numpy_iterator(), inferences):
197
- predictions.append(self.postprocess(tokens, example))
198
-
199
- result = metrics_utils.event_predictions_to_ns(
200
- predictions, codec=self.codec, encoding_spec=self.encoding_spec)
201
- return result['est_ns']
202
-
203
- def audio_to_dataset(self, audio):
204
- """从输入音频创建一个包含频谱图的 TF Dataset。"""
205
- frames, frame_times = self._audio_to_frames(audio)
206
- return tf.data.Dataset.from_tensors({
207
- 'inputs': frames,
208
- 'input_times': frame_times,
209
- })
210
-
211
- def _audio_to_frames(self, audio):
212
- """从音频计算频谱图帧。"""
213
- frame_size = self.spectrogram_config.hop_width
214
- padding = [0, frame_size - len(audio) % frame_size]
215
- audio = np.pad(audio, padding, mode='constant')
216
- frames = spectrograms.split_audio(audio, self.spectrogram_config)
217
- num_frames = len(audio) // frame_size
218
- times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
219
- return frames, times
220
-
221
- def preprocess(self, ds):
222
- pp_chain = [
223
- functools.partial(
224
- t5.data.preprocessors.split_tokens_to_inputs_length,
225
- sequence_length=self.sequence_length,
226
- output_features=self.output_features,
227
- feature_key='inputs',
228
- additional_feature_keys=['input_times']),
229
- # 在训练期间进行缓存。
230
- preprocessors.add_dummy_targets,
231
- functools.partial(
232
- preprocessors.compute_spectrograms,
233
- spectrogram_config=self.spectrogram_config)
234
- ]
235
- for pp in pp_chain:
236
- ds = pp(ds)
237
- return ds
238
-
239
- def postprocess(self, tokens, example):
240
- tokens = self._trim_eos(tokens)
241
- start_time = example['input_times'][0]
242
- # 向下取整到最接近的符号化时间步。
243
- start_time -= start_time % (1 / self.codec.steps_per_second)
244
- return {
245
- 'est_tokens': tokens,
246
- 'start_time': start_time,
247
- # 内部 MT3 代码期望原始输入,这里不使用。
248
- 'raw_inputs': []
249
- }
250
-
251
- @staticmethod
252
- def _trim_eos(tokens):
253
- tokens = np.array(tokens, np.int32)
254
- if vocabularies.DECODED_EOS_ID in tokens:
255
- tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
256
- return tokens
257
-
258
- print(glob2.glob("."))
 
 
 
 
 
 
 
 
 
 
259
  inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
260
 
261
  def inference(url):
262
- os.system(f"yt-dlp -x {url} -o 'audio.%(ext)s'")
263
- audio = glob2.glob('audio.*')[0]
264
- with open(audio, 'rb') as fd:
265
- contents = fd.read()
266
- audio = callbak_audio(contents,sample_rate=16000)
267
- est_ns = inference_model(audio)
268
- note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
269
- return './transcribed.mid'
270
-
 
271
  title = "YouTube-To-MT3"
272
  description = "将YouTube音频上传到 MT3:多任务多音轨音乐转录的 Gradio 演示。感谢 <a href=\"https://huggingface.co/spaces/akhaliq/MT3\">akhaliq</a> 的原始 <i>Spaces</i> 实现。"
273
 
274
  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>"
275
 
276
  gr.Interface(
277
- inference,
278
- gr.inputs.Textbox(label="URL"),
279
- gr.outputs.File(label="输出"),
280
- title=title,
281
- description=description,
282
- article=article,
283
- enable_queue=True
284
- ).launch()
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import datetime
4
+ import pytz
5
  from pathlib import Path
 
 
 
6
 
7
+ def current_time():
8
+ current = datetime.datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y年-%m月-%d日 %H时:%M分:%S秒")
9
+ return current
10
+
11
+ print(f"[{current_time()}] 开始部署空间...")
12
 
13
+ """
14
+ print(f"[{current_time()}] 日志:安装 - 必要包")
15
+ os.system("pip install -r ./requirements.txt")
16
+ """
17
+ print(f"[{current_time()}] 日志:安装 - glob2")
18
+ os.system("pip install glob2")
19
+ print(f"[{current_time()}] 日志:安装 - gsutil")
20
+ os.system("pip install gsutil")
21
+ print(f"[{current_time()}] 日志:Git - 克隆 Github 的 T5X 训练框架到当前目录")
22
  os.system("git clone --branch=main https://github.com/google-research/t5x")
23
+ print(f"[{current_time()}] 日志:文件 - 移动 t5x 到当前目录并重命名为 t5x_tmp 并删除")
24
  os.system("mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp")
25
+ print(f"[{current_time()}] 日志:编辑 - 替换 setup.py 内的文本“jax[tpu]”为“jax”")
26
  os.system("sed -i 's:jax\[tpu\]:jax:' setup.py")
27
+ print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包")
28
  os.system("python3 -m pip install -e .")
29
+ print(f"[{current_time()}] 日志:Python - 更新 Python 包管理器 pip")
30
  os.system("python3 -m pip install --upgrade pip")
31
+ print(f"[{current_time()}] 日志:安装 - langchain")
32
+ os.system("pip install langchain")
33
+ print(f"[{current_time()}] 日志:安装 - sentence-transformers")
34
+ os.system("pip install sentence-transformers")
35
+
36
+ # 安装 airio
37
+ print(f"[{current_time()}] 日志:Git - 克隆 Github 的 airio 到当前目录")
38
+ os.system("git clone --branch=main https://github.com/google/airio")
39
+ print(f"[{current_time()}] 日志:文件 - 移动 airio 到当前目录并重命名为 airio_tmp 并删除")
40
+ os.system("mv airio airio_tmp; mv airio_tmp/* .; rm -r airio_tmp")
41
+ print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包")
42
+ os.system("python3 -m pip install -e .")
43
 
44
  # 安装 mt3
45
+ print(f"[{current_time()}] 日志:Git - 克隆 Github 的 MT3 模型到当前目录")
46
  os.system("git clone --branch=main https://github.com/magenta/mt3")
47
+ print(f"[{current_time()}] 日志:文件 - 移动 mt3 到当前目录并重命名为 mt3_tmp 并删除")
48
  os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp")
49
+ print(f"[{current_time()}] 日志:Python - 使用 pip 从 storage.googleapis.com 安装 jax[cuda11_local] nest-asyncio pyfluidsynth")
50
+ os.system("python3 -m pip install jax[cuda11_local] nest-asyncio pyfluidsynth==1.3.0 -e . -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html")
51
+ print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包")
52
  os.system("python3 -m pip install -e .")
53
+ print(f"[{current_time()}] 日志:安装 - TensorFlow CPU")
54
  os.system("pip install tensorflow_cpu")
55
+
56
  # 复制检查点
57
+ print(f"[{current_time()}] 日志:gsutil - 复制 MT3 检查点到当前目录")
58
  os.system("gsutil -q -m cp -r gs://mt3/checkpoints .")
59
 
60
  # 复制 soundfont 文件(原始文件来自 https://sites.google.com/site/soundfonts4u)
61
+ print(f"[{current_time()}] 日志:gsutil - 复制 SoundFont 文件到当前目录")
62
  os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .")
63
 
64
  #@title 导入和定义
65
+ print(f"[{current_time()}] 日志:导入 - 必要工具")
66
  import functools
67
  import os
 
68
  import numpy as np
69
  import tensorflow.compat.v2 as tf
70
 
 
77
  import seqio
78
  import t5
79
  import t5x
80
+ import glob2
81
 
82
  from mt3 import metrics_utils
83
  from mt3 import models
 
93
  SAMPLE_RATE = 16000
94
  SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2'
95
 
96
+ def upload_audio(audio, sample_rate):
97
+ return note_seq.audio_io.wav_data_to_samples_librosa(
98
+ audio, sample_rate=sample_rate)
99
 
100
+
101
+ print(f"[{current_time()}] 日志:开始包装模型...")
102
  class InferenceModel(object):
103
+ """音乐转录的 T5X 模型包装器。"""
104
+
105
+ def __init__(self, checkpoint_path, model_type='mt3'):
106
+
107
+ # 模型常量。
108
+ if model_type == 'ismir2021':
109
+ num_velocity_bins = 127
110
+ self.encoding_spec = note_sequences.NoteEncodingSpec
111
+ self.inputs_length = 512
112
+ elif model_type == 'mt3':
113
+ num_velocity_bins = 1
114
+ self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec
115
+ self.inputs_length = 256
116
+ else:
117
+ raise ValueError('unknown model_type: %s' % model_type)
118
+
119
+ gin_files = ['/home/user/app/mt3/gin/model.gin',
120
+ '/home/user/app/mt3/gin/mt3.gin']
121
+
122
+ self.batch_size = 8
123
+ self.outputs_length = 1024
124
+ self.sequence_length = {'inputs': self.inputs_length,
125
+ 'targets': self.outputs_length}
126
+
127
+ self.partitioner = t5x.partitioning.PjitPartitioner(
128
+ model_parallel_submesh=None, num_partitions=1)
129
+
130
+ # 构建编解码器和词汇表。
131
+ print(f"[{current_time()}] 日志:构建编解码器")
132
+ self.spectrogram_config = spectrograms.SpectrogramConfig()
133
+ self.codec = vocabularies.build_codec(
134
+ vocab_config=vocabularies.VocabularyConfig(
135
+ num_velocity_bins=num_velocity_bins)
136
+ )
137
+ self.vocabulary = vocabularies.vocabulary_from_codec(self.codec)
138
+ self.output_features = {
139
+ 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2),
140
+ 'targets': seqio.Feature(vocabulary=self.vocabulary),
141
+ }
142
+
143
+ # 创建 T5X 模型。
144
+ print(f"[{current_time()}] 日志:创建 T5X 模型")
145
+ self._parse_gin(gin_files)
146
+ self.model = self._load_model()
147
+
148
+ # 从检查点中恢复。
149
+ print(f"[{current_time()}] 日志:恢复模型检查点")
150
+ self.restore_from_checkpoint(checkpoint_path)
151
+
152
+ @property
153
+ def input_shapes(self):
154
+ return {
155
+ 'encoder_input_tokens': (self.batch_size, self.inputs_length),
156
+ 'decoder_input_tokens': (self.batch_size, self.outputs_length)
157
+ }
158
+
159
+ def _parse_gin(self, gin_files):
160
+ """解析用于训练模型的 gin 文件。"""
161
+ print(f"[{current_time()}] 日志:解析 gin 文件")
162
+ gin_bindings = [
163
+ 'from __gin__ import dynamic_registration',
164
+ 'from mt3 import vocabularies',
165
166
+ 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS'
167
+ ]
168
+ with gin.unlock_config():
169
+ gin.parse_config_files_and_bindings(
170
+ gin_files, gin_bindings, finalize_config=False)
171
+
172
+ def _load_model(self):
173
+ """在解析训练 gin 配置后加载 T5X `Model`。"""
174
+ print(f"[{current_time()}] 日志:加载 T5X 模型")
175
+ model_config = gin.get_configurable(network.T5Config)()
176
+ module = network.Transformer(config=model_config)
177
+ return models.ContinuousInputsEncoderDecoderModel(
178
+ module=module,
179
+ input_vocabulary=self.output_features['inputs'].vocabulary,
180
+ output_vocabulary=self.output_features['targets'].vocabulary,
181
+ optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0),
182
+ input_depth=spectrograms.input_depth(self.spectrogram_config))
183
+
184
+
185
+ def restore_from_checkpoint(self, checkpoint_path):
186
+ """从检查点中恢复训练状态,重置 self._predict_fn()。"""
187
+ print(f"[{current_time()}] 日志:从检查点恢复训练状态")
188
+ train_state_initializer = t5x.utils.TrainStateInitializer(
189
+ optimizer_def=self.model.optimizer_def,
190
+ init_fn=self.model.get_initial_variables,
191
+ input_shapes=self.input_shapes,
192
+ partitioner=self.partitioner)
193
+
194
+ restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig(
195
+ path=checkpoint_path, mode='specific', dtype='float32')
196
+
197
+ train_state_axes = train_state_initializer.train_state_axes
198
+ self._predict_fn = self._get_predict_fn(train_state_axes)
199
+ self._train_state = train_state_initializer.from_checkpoint_or_scratch(
200
+ [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0))
201
+
202
+ @functools.lru_cache()
203
+ def _get_predict_fn(self, train_state_axes):
204
+ """生成一个分区的预测函数用于解码。"""
205
+ print(f"[{current_time()}] 日志:生成用于解码的预测函数")
206
+ def partial_predict_fn(params, batch, decode_rng):
207
+ return self.model.predict_batch_with_aux(
208
+ params, batch, decoder_params={'decode_rng': None})
209
+ return self.partitioner.partition(
210
+ partial_predict_fn,
211
+ in_axis_resources=(
212
+ train_state_axes.params,
213
+ t5x.partitioning.PartitionSpec('data',), None),
214
+ out_axis_resources=t5x.partitioning.PartitionSpec('data',)
215
+ )
216
+
217
+ def predict_tokens(self, batch, seed=0):
218
+ """从预处理的数据集批次中预测 tokens。"""
219
+ print(f"[{current_time()}] 运行:从预处理数据集中预测音符序列")
220
+ prediction, _ = self._predict_fn(self._train_state.params, batch, jax.random.PRNGKey(seed))
221
+ return self.vocabulary.decode_tf(prediction).numpy()
222
+
223
+ def __call__(self, audio):
224
+ """从音频样本推断出音符序列。
225
+ 参数:
226
+ audio:16kHz 的单个音频样本的 1 维 numpy 数组。
227
+ 返回:
228
+ 转录音频的音符序列。
229
+ """
230
+ print(f"[{current_time()}] 运行:从音频样本中推断音符序列")
231
+ ds = self.audio_to_dataset(audio)
232
+ ds = self.preprocess(ds)
233
+
234
+ model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)(
235
+ ds, task_feature_lengths=self.sequence_length)
236
+ model_ds = model_ds.batch(self.batch_size)
237
+
238
+ inferences = (tokens for batch in model_ds.as_numpy_iterator()
239
+ for tokens in self.predict_tokens(batch))
240
+
241
+ predictions = []
242
+ for example, tokens in zip(ds.as_numpy_iterator(), inferences):
243
+ predictions.append(self.postprocess(tokens, example))
244
+
245
+ result = metrics_utils.event_predictions_to_ns(
246
+ predictions, codec=self.codec, encoding_spec=self.encoding_spec)
247
+ return result['est_ns']
248
+
249
+ def audio_to_dataset(self, audio):
250
+ """从输入音频创建一个包含频谱图的 TF Dataset。"""
251
+ print(f"[{current_time()}] 运行:从音频创建包含频谱图的 TF Dataset")
252
+ frames, frame_times = self._audio_to_frames(audio)
253
+ return tf.data.Dataset.from_tensors({
254
+ 'inputs': frames,
255
+ 'input_times': frame_times,
256
+ })
257
+
258
+ def _audio_to_frames(self, audio):
259
+ """从音频计算频谱图帧。"""
260
+ print(f"[{current_time()}] 运行:从音频计算频谱图帧")
261
+ frame_size = self.spectrogram_config.hop_width
262
+ padding = [0, frame_size - len(audio) % frame_size]
263
+ audio = np.pad(audio, padding, mode='constant')
264
+ frames = spectrograms.split_audio(audio, self.spectrogram_config)
265
+ num_frames = len(audio) // frame_size
266
+ times = np.arange(num_frames) / self.spectrogram_config.frames_per_second
267
+ return frames, times
268
+
269
+ def preprocess(self, ds):
270
+ pp_chain = [
271
+ functools.partial(
272
+ t5.data.preprocessors.split_tokens_to_inputs_length,
273
+ sequence_length=self.sequence_length,
274
+ output_features=self.output_features,
275
+ feature_key='inputs',
276
+ additional_feature_keys=['input_times']),
277
+ # 在训练期间进行缓存。
278
+ preprocessors.add_dummy_targets,
279
+ functools.partial(
280
+ preprocessors.compute_spectrograms,
281
+ spectrogram_config=self.spectrogram_config)
282
+ ]
283
+ for pp in pp_chain:
284
+ ds = pp(ds)
285
+ return ds
286
+
287
+ def postprocess(self, tokens, example):
288
+ tokens = self._trim_eos(tokens)
289
+ start_time = example['input_times'][0]
290
+ # 向下取整到最接近的符号化时间步。
291
+ start_time -= start_time % (1 / self.codec.steps_per_second)
292
+ return {
293
+ 'est_tokens': tokens,
294
+ 'start_time': start_time,
295
+ # 内部 MT3 代码期望原始输入,这里不使用。
296
+ 'raw_inputs': []
297
+ }
298
+
299
+ @staticmethod
300
+ def _trim_eos(tokens):
301
+ tokens = np.array(tokens, np.int32)
302
+ if vocabularies.DECODED_EOS_ID in tokens:
303
+ tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)]
304
+ return tokens
305
+
306
+
307
  inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3')
308
 
309
  def inference(url):
310
+ print(f"[{current_time()}] 运行:输入地址: {url}")
311
+ os.system(f"yt-dlp -x {url} -o 'audio.%(ext)s'")
312
+ audio = glob2.glob('audio.*')[0]
313
+ with open(audio, 'rb') as fd:
314
+ contents = fd.read()
315
+ audio = callbak_audio(contents,sample_rate=16000)
316
+ est_ns = inference_model(audio)
317
+ note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid')
318
+ return './transcribed.mid'
319
+
320
  title = "YouTube-To-MT3"
321
  description = "将YouTube音频上传到 MT3:多任务多音轨音乐转录的 Gradio 演示。感谢 <a href=\"https://huggingface.co/spaces/akhaliq/MT3\">akhaliq</a> 的原始 <i>Spaces</i> 实现。"
322
 
323
  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>"
324
 
325
  gr.Interface(
326
+ inference,
327
+ gr.inputs.Textbox(label="URL"),
328
+ gr.outputs.File(label="输出"),
329
+ title=title,
330
+ description=description,
331
+ article=article,
332
+ enable_queue=True
333
+ ).launch()