XZZ123888 commited on
Commit
7bd4091
·
1 Parent(s): ddd3ea2

Upload 3 files

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